compiler-sfc.global.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692
  1. var VueCompilerSFC = (function (exports, path, url, postcss, require$$0) {
  2. 'use strict';
  3. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
  4. var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  5. var postcss__default = /*#__PURE__*/_interopDefaultLegacy(postcss);
  6. var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
  7. /**
  8. * Make a map and return a function for checking if a key
  9. * is in that map.
  10. * IMPORTANT: all calls of this function must be prefixed with
  11. * \/\*#\_\_PURE\_\_\*\/
  12. * So that rollup can tree-shake them if necessary.
  13. */
  14. function makeMap(str, expectsLowerCase) {
  15. const map = Object.create(null);
  16. const list = str.split(',');
  17. for (let i = 0; i < list.length; i++) {
  18. map[list[i]] = true;
  19. }
  20. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  21. }
  22. /**
  23. * dev only flag -> name mapping
  24. */
  25. const PatchFlagNames = {
  26. [1 /* TEXT */]: `TEXT`,
  27. [2 /* CLASS */]: `CLASS`,
  28. [4 /* STYLE */]: `STYLE`,
  29. [8 /* PROPS */]: `PROPS`,
  30. [16 /* FULL_PROPS */]: `FULL_PROPS`,
  31. [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  32. [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  33. [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  34. [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  35. [512 /* NEED_PATCH */]: `NEED_PATCH`,
  36. [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  37. [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  38. [-1 /* HOISTED */]: `HOISTED`,
  39. [-2 /* BAIL */]: `BAIL`
  40. };
  41. /**
  42. * Dev only
  43. */
  44. const slotFlagsText = {
  45. [1 /* STABLE */]: 'STABLE',
  46. [2 /* DYNAMIC */]: 'DYNAMIC',
  47. [3 /* FORWARDED */]: 'FORWARDED'
  48. };
  49. const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  50. 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  51. 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
  52. const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
  53. const range = 2;
  54. function generateCodeFrame(source, start = 0, end = source.length) {
  55. const lines = source.split(/\r?\n/);
  56. let count = 0;
  57. const res = [];
  58. for (let i = 0; i < lines.length; i++) {
  59. count += lines[i].length + 1;
  60. if (count >= start) {
  61. for (let j = i - range; j <= i + range || end > count; j++) {
  62. if (j < 0 || j >= lines.length)
  63. continue;
  64. const line = j + 1;
  65. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  66. const lineLength = lines[j].length;
  67. if (j === i) {
  68. // push underline
  69. const pad = start - (count - lineLength) + 1;
  70. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  71. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  72. }
  73. else if (j > i) {
  74. if (end > count) {
  75. const length = Math.max(Math.min(end - count, lineLength), 1);
  76. res.push(` | ` + '^'.repeat(length));
  77. }
  78. count += lineLength + 1;
  79. }
  80. }
  81. break;
  82. }
  83. }
  84. return res.join('\n');
  85. }
  86. /**
  87. * On the client we only need to offer special cases for boolean attributes that
  88. * have different names from their corresponding dom properties:
  89. * - itemscope -> N/A
  90. * - allowfullscreen -> allowFullscreen
  91. * - formnovalidate -> formNoValidate
  92. * - ismap -> isMap
  93. * - nomodule -> noModule
  94. * - novalidate -> noValidate
  95. * - readonly -> readOnly
  96. */
  97. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  98. /**
  99. * The full list is needed during SSR to produce the correct initial markup.
  100. */
  101. const isBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs +
  102. `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,` +
  103. `loop,open,required,reversed,scoped,seamless,` +
  104. `checked,muted,multiple,selected`);
  105. const unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/;
  106. const attrValidationCache = {};
  107. function isSSRSafeAttrName(name) {
  108. if (attrValidationCache.hasOwnProperty(name)) {
  109. return attrValidationCache[name];
  110. }
  111. const isUnsafe = unsafeAttrCharRE.test(name);
  112. if (isUnsafe) {
  113. console.error(`unsafe attribute name: ${name}`);
  114. }
  115. return (attrValidationCache[name] = !isUnsafe);
  116. }
  117. const propsToAttrMap = {
  118. acceptCharset: 'accept-charset',
  119. className: 'class',
  120. htmlFor: 'for',
  121. httpEquiv: 'http-equiv'
  122. };
  123. /**
  124. * CSS properties that accept plain numbers
  125. */
  126. const isNoUnitNumericStyleProp = /*#__PURE__*/ makeMap(`animation-iteration-count,border-image-outset,border-image-slice,` +
  127. `border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,` +
  128. `columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,` +
  129. `grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,` +
  130. `grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,` +
  131. `line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,` +
  132. // SVG
  133. `fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,` +
  134. `stroke-miterlimit,stroke-opacity,stroke-width`);
  135. /**
  136. * Known attributes, this is used for stringification of runtime static nodes
  137. * so that we don't stringify bindings that cannot be set from HTML.
  138. * Don't also forget to allow `data-*` and `aria-*`!
  139. * Generated from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
  140. */
  141. const isKnownAttr = /*#__PURE__*/ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,` +
  142. `autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,` +
  143. `border,buffered,capture,challenge,charset,checked,cite,class,code,` +
  144. `codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,` +
  145. `coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,` +
  146. `disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,` +
  147. `formaction,formenctype,formmethod,formnovalidate,formtarget,headers,` +
  148. `height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,` +
  149. `ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,` +
  150. `manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,` +
  151. `open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,` +
  152. `referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,` +
  153. `selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,` +
  154. `start,step,style,summary,tabindex,target,title,translate,type,usemap,` +
  155. `value,width,wrap`);
  156. function normalizeStyle(value) {
  157. if (isArray(value)) {
  158. const res = {};
  159. for (let i = 0; i < value.length; i++) {
  160. const item = value[i];
  161. const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
  162. if (normalized) {
  163. for (const key in normalized) {
  164. res[key] = normalized[key];
  165. }
  166. }
  167. }
  168. return res;
  169. }
  170. else if (isObject(value)) {
  171. return value;
  172. }
  173. }
  174. const listDelimiterRE = /;(?![^(]*\))/g;
  175. const propertyDelimiterRE = /:(.+)/;
  176. function parseStringStyle(cssText) {
  177. const ret = {};
  178. cssText.split(listDelimiterRE).forEach(item => {
  179. if (item) {
  180. const tmp = item.split(propertyDelimiterRE);
  181. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  182. }
  183. });
  184. return ret;
  185. }
  186. function stringifyStyle(styles) {
  187. let ret = '';
  188. if (!styles) {
  189. return ret;
  190. }
  191. for (const key in styles) {
  192. const value = styles[key];
  193. const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
  194. if (isString(value) ||
  195. (typeof value === 'number' && isNoUnitNumericStyleProp(normalizedKey))) {
  196. // only render valid values
  197. ret += `${normalizedKey}:${value};`;
  198. }
  199. }
  200. return ret;
  201. }
  202. function normalizeClass(value) {
  203. let res = '';
  204. if (isString(value)) {
  205. res = value;
  206. }
  207. else if (isArray(value)) {
  208. for (let i = 0; i < value.length; i++) {
  209. const normalized = normalizeClass(value[i]);
  210. if (normalized) {
  211. res += normalized + ' ';
  212. }
  213. }
  214. }
  215. else if (isObject(value)) {
  216. for (const name in value) {
  217. if (value[name]) {
  218. res += name + ' ';
  219. }
  220. }
  221. }
  222. return res.trim();
  223. }
  224. // These tag configs are shared between compiler-dom and runtime-dom, so they
  225. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  226. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  227. 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
  228. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  229. 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
  230. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  231. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  232. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  233. 'option,output,progress,select,textarea,details,dialog,menu,' +
  234. 'summary,template,blockquote,iframe,tfoot';
  235. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  236. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  237. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  238. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  239. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  240. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  241. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  242. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  243. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  244. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  245. 'text,textPath,title,tspan,unknown,use,view';
  246. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  247. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  248. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  249. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  250. const escapeRE = /["'&<>]/;
  251. function escapeHtml(string) {
  252. const str = '' + string;
  253. const match = escapeRE.exec(str);
  254. if (!match) {
  255. return str;
  256. }
  257. let html = '';
  258. let escaped;
  259. let index;
  260. let lastIndex = 0;
  261. for (index = match.index; index < str.length; index++) {
  262. switch (str.charCodeAt(index)) {
  263. case 34: // "
  264. escaped = '&quot;';
  265. break;
  266. case 38: // &
  267. escaped = '&amp;';
  268. break;
  269. case 39: // '
  270. escaped = '&#39;';
  271. break;
  272. case 60: // <
  273. escaped = '&lt;';
  274. break;
  275. case 62: // >
  276. escaped = '&gt;';
  277. break;
  278. default:
  279. continue;
  280. }
  281. if (lastIndex !== index) {
  282. html += str.substring(lastIndex, index);
  283. }
  284. lastIndex = index + 1;
  285. html += escaped;
  286. }
  287. return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
  288. }
  289. /**
  290. * For converting {{ interpolation }} values to displayed strings.
  291. * @private
  292. */
  293. const toDisplayString = (val) => {
  294. return val == null
  295. ? ''
  296. : isObject(val)
  297. ? JSON.stringify(val, replacer, 2)
  298. : String(val);
  299. };
  300. const replacer = (_key, val) => {
  301. if (isMap(val)) {
  302. return {
  303. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  304. entries[`${key} =>`] = val;
  305. return entries;
  306. }, {})
  307. };
  308. }
  309. else if (isSet(val)) {
  310. return {
  311. [`Set(${val.size})`]: [...val.values()]
  312. };
  313. }
  314. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  315. return String(val);
  316. }
  317. return val;
  318. };
  319. /**
  320. * List of @babel/parser plugins that are used for template expression
  321. * transforms and SFC script transforms. By default we enable proposals slated
  322. * for ES2020. This will need to be updated as the spec moves forward.
  323. * Full list at https://babeljs.io/docs/en/next/babel-parser#plugins
  324. */
  325. const babelParserDefaultPlugins = [
  326. 'bigInt',
  327. 'optionalChaining',
  328. 'nullishCoalescingOperator'
  329. ];
  330. const EMPTY_OBJ = Object.freeze({})
  331. ;
  332. Object.freeze([]) ;
  333. const NOOP = () => { };
  334. /**
  335. * Always return false.
  336. */
  337. const NO = () => false;
  338. const onRE = /^on[^a-z]/;
  339. const isOn = (key) => onRE.test(key);
  340. const extend = Object.assign;
  341. const hasOwnProperty = Object.prototype.hasOwnProperty;
  342. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  343. const isArray = Array.isArray;
  344. const isMap = (val) => toTypeString(val) === '[object Map]';
  345. const isSet = (val) => toTypeString(val) === '[object Set]';
  346. const isFunction = (val) => typeof val === 'function';
  347. const isString = (val) => typeof val === 'string';
  348. const isSymbol = (val) => typeof val === 'symbol';
  349. const isObject = (val) => val !== null && typeof val === 'object';
  350. const objectToString = Object.prototype.toString;
  351. const toTypeString = (value) => objectToString.call(value);
  352. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  353. const isReservedProp = /*#__PURE__*/ makeMap(
  354. // the leading comma is intentional so empty string "" is also included
  355. ',key,ref,' +
  356. 'onVnodeBeforeMount,onVnodeMounted,' +
  357. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  358. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  359. const cacheStringFunction = (fn) => {
  360. const cache = Object.create(null);
  361. return ((str) => {
  362. const hit = cache[str];
  363. return hit || (cache[str] = fn(str));
  364. });
  365. };
  366. const camelizeRE = /-(\w)/g;
  367. /**
  368. * @private
  369. */
  370. const camelize = cacheStringFunction((str) => {
  371. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  372. });
  373. const hyphenateRE = /\B([A-Z])/g;
  374. /**
  375. * @private
  376. */
  377. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  378. /**
  379. * @private
  380. */
  381. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  382. /**
  383. * @private
  384. */
  385. const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
  386. function defaultOnError(error) {
  387. throw error;
  388. }
  389. function createCompilerError(code, loc, messages, additionalMessage) {
  390. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  391. ;
  392. const error = new SyntaxError(String(msg));
  393. error.code = code;
  394. error.loc = loc;
  395. return error;
  396. }
  397. const errorMessages = {
  398. // parse errors
  399. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  400. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  401. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  402. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  403. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  404. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  405. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  406. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  407. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  408. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  409. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  410. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  411. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  412. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  413. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  414. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  415. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  416. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  417. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  418. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  419. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  420. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  421. // Vue-specific parse errors
  422. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  423. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  424. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  425. [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  426. 'Note that dynamic directive argument cannot contain spaces.',
  427. // transform errors
  428. [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  429. [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  430. [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
  431. [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  432. [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  433. [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  434. [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  435. [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  436. [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  437. [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  438. `When there are multiple named slots, all slots should use <template> ` +
  439. `syntax to avoid scope ambiguity.`,
  440. [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  441. [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  442. `default slot. These children will be ignored.`,
  443. [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  444. [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  445. [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  446. [42 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  447. [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  448. [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  449. // generic errors
  450. [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  451. [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  452. [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  453. [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
  454. };
  455. const FRAGMENT = Symbol(`Fragment` );
  456. const TELEPORT = Symbol(`Teleport` );
  457. const SUSPENSE = Symbol(`Suspense` );
  458. const KEEP_ALIVE = Symbol(`KeepAlive` );
  459. const BASE_TRANSITION = Symbol(`BaseTransition` );
  460. const OPEN_BLOCK = Symbol(`openBlock` );
  461. const CREATE_BLOCK = Symbol(`createBlock` );
  462. const CREATE_VNODE = Symbol(`createVNode` );
  463. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  464. const CREATE_TEXT = Symbol(`createTextVNode` );
  465. const CREATE_STATIC = Symbol(`createStaticVNode` );
  466. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  467. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  468. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  469. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  470. const RENDER_LIST = Symbol(`renderList` );
  471. const RENDER_SLOT = Symbol(`renderSlot` );
  472. const CREATE_SLOTS = Symbol(`createSlots` );
  473. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  474. const MERGE_PROPS = Symbol(`mergeProps` );
  475. const TO_HANDLERS = Symbol(`toHandlers` );
  476. const CAMELIZE = Symbol(`camelize` );
  477. const CAPITALIZE = Symbol(`capitalize` );
  478. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  479. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  480. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  481. const POP_SCOPE_ID = Symbol(`popScopeId` );
  482. const WITH_SCOPE_ID = Symbol(`withScopeId` );
  483. const WITH_CTX = Symbol(`withCtx` );
  484. const UNREF = Symbol(`unref` );
  485. const IS_REF = Symbol(`isRef` );
  486. // Name mapping for runtime helpers that need to be imported from 'vue' in
  487. // generated code. Make sure these are correctly exported in the runtime!
  488. // Using `any` here because TS doesn't allow symbols as index type.
  489. const helperNameMap = {
  490. [FRAGMENT]: `Fragment`,
  491. [TELEPORT]: `Teleport`,
  492. [SUSPENSE]: `Suspense`,
  493. [KEEP_ALIVE]: `KeepAlive`,
  494. [BASE_TRANSITION]: `BaseTransition`,
  495. [OPEN_BLOCK]: `openBlock`,
  496. [CREATE_BLOCK]: `createBlock`,
  497. [CREATE_VNODE]: `createVNode`,
  498. [CREATE_COMMENT]: `createCommentVNode`,
  499. [CREATE_TEXT]: `createTextVNode`,
  500. [CREATE_STATIC]: `createStaticVNode`,
  501. [RESOLVE_COMPONENT]: `resolveComponent`,
  502. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  503. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  504. [WITH_DIRECTIVES]: `withDirectives`,
  505. [RENDER_LIST]: `renderList`,
  506. [RENDER_SLOT]: `renderSlot`,
  507. [CREATE_SLOTS]: `createSlots`,
  508. [TO_DISPLAY_STRING]: `toDisplayString`,
  509. [MERGE_PROPS]: `mergeProps`,
  510. [TO_HANDLERS]: `toHandlers`,
  511. [CAMELIZE]: `camelize`,
  512. [CAPITALIZE]: `capitalize`,
  513. [TO_HANDLER_KEY]: `toHandlerKey`,
  514. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  515. [PUSH_SCOPE_ID]: `pushScopeId`,
  516. [POP_SCOPE_ID]: `popScopeId`,
  517. [WITH_SCOPE_ID]: `withScopeId`,
  518. [WITH_CTX]: `withCtx`,
  519. [UNREF]: `unref`,
  520. [IS_REF]: `isRef`
  521. };
  522. function registerRuntimeHelpers(helpers) {
  523. Object.getOwnPropertySymbols(helpers).forEach(s => {
  524. helperNameMap[s] = helpers[s];
  525. });
  526. }
  527. // AST Utilities ---------------------------------------------------------------
  528. // Some expressions, e.g. sequence and conditional expressions, are never
  529. // associated with template nodes, so their source locations are just a stub.
  530. // Container types like CompoundExpression also don't need a real location.
  531. const locStub = {
  532. source: '',
  533. start: { line: 1, column: 1, offset: 0 },
  534. end: { line: 1, column: 1, offset: 0 }
  535. };
  536. function createRoot(children, loc = locStub) {
  537. return {
  538. type: 0 /* ROOT */,
  539. children,
  540. helpers: [],
  541. components: [],
  542. directives: [],
  543. hoists: [],
  544. imports: [],
  545. cached: 0,
  546. temps: 0,
  547. codegenNode: undefined,
  548. loc
  549. };
  550. }
  551. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
  552. if (context) {
  553. if (isBlock) {
  554. context.helper(OPEN_BLOCK);
  555. context.helper(CREATE_BLOCK);
  556. }
  557. else {
  558. context.helper(CREATE_VNODE);
  559. }
  560. if (directives) {
  561. context.helper(WITH_DIRECTIVES);
  562. }
  563. }
  564. return {
  565. type: 13 /* VNODE_CALL */,
  566. tag,
  567. props,
  568. children,
  569. patchFlag,
  570. dynamicProps,
  571. directives,
  572. isBlock,
  573. disableTracking,
  574. loc
  575. };
  576. }
  577. function createArrayExpression(elements, loc = locStub) {
  578. return {
  579. type: 17 /* JS_ARRAY_EXPRESSION */,
  580. loc,
  581. elements
  582. };
  583. }
  584. function createObjectExpression(properties, loc = locStub) {
  585. return {
  586. type: 15 /* JS_OBJECT_EXPRESSION */,
  587. loc,
  588. properties
  589. };
  590. }
  591. function createObjectProperty(key, value) {
  592. return {
  593. type: 16 /* JS_PROPERTY */,
  594. loc: locStub,
  595. key: isString(key) ? createSimpleExpression(key, true) : key,
  596. value
  597. };
  598. }
  599. function createSimpleExpression(content, isStatic, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
  600. return {
  601. type: 4 /* SIMPLE_EXPRESSION */,
  602. loc,
  603. content,
  604. isStatic,
  605. constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
  606. };
  607. }
  608. function createInterpolation(content, loc) {
  609. return {
  610. type: 5 /* INTERPOLATION */,
  611. loc,
  612. content: isString(content)
  613. ? createSimpleExpression(content, false, loc)
  614. : content
  615. };
  616. }
  617. function createCompoundExpression(children, loc = locStub) {
  618. return {
  619. type: 8 /* COMPOUND_EXPRESSION */,
  620. loc,
  621. children
  622. };
  623. }
  624. function createCallExpression(callee, args = [], loc = locStub) {
  625. return {
  626. type: 14 /* JS_CALL_EXPRESSION */,
  627. loc,
  628. callee,
  629. arguments: args
  630. };
  631. }
  632. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  633. return {
  634. type: 18 /* JS_FUNCTION_EXPRESSION */,
  635. params,
  636. returns,
  637. newline,
  638. isSlot,
  639. loc
  640. };
  641. }
  642. function createConditionalExpression(test, consequent, alternate, newline = true) {
  643. return {
  644. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  645. test,
  646. consequent,
  647. alternate,
  648. newline,
  649. loc: locStub
  650. };
  651. }
  652. function createCacheExpression(index, value, isVNode = false) {
  653. return {
  654. type: 20 /* JS_CACHE_EXPRESSION */,
  655. index,
  656. value,
  657. isVNode,
  658. loc: locStub
  659. };
  660. }
  661. function createBlockStatement(body) {
  662. return {
  663. type: 21 /* JS_BLOCK_STATEMENT */,
  664. body,
  665. loc: locStub
  666. };
  667. }
  668. function createTemplateLiteral(elements) {
  669. return {
  670. type: 22 /* JS_TEMPLATE_LITERAL */,
  671. elements,
  672. loc: locStub
  673. };
  674. }
  675. function createIfStatement(test, consequent, alternate) {
  676. return {
  677. type: 23 /* JS_IF_STATEMENT */,
  678. test,
  679. consequent,
  680. alternate,
  681. loc: locStub
  682. };
  683. }
  684. function createAssignmentExpression(left, right) {
  685. return {
  686. type: 24 /* JS_ASSIGNMENT_EXPRESSION */,
  687. left,
  688. right,
  689. loc: locStub
  690. };
  691. }
  692. function createSequenceExpression(expressions) {
  693. return {
  694. type: 25 /* JS_SEQUENCE_EXPRESSION */,
  695. expressions,
  696. loc: locStub
  697. };
  698. }
  699. function createReturnStatement(returns) {
  700. return {
  701. type: 26 /* JS_RETURN_STATEMENT */,
  702. returns,
  703. loc: locStub
  704. };
  705. }
  706. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  707. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  708. function isCoreComponent(tag) {
  709. if (isBuiltInType(tag, 'Teleport')) {
  710. return TELEPORT;
  711. }
  712. else if (isBuiltInType(tag, 'Suspense')) {
  713. return SUSPENSE;
  714. }
  715. else if (isBuiltInType(tag, 'KeepAlive')) {
  716. return KEEP_ALIVE;
  717. }
  718. else if (isBuiltInType(tag, 'BaseTransition')) {
  719. return BASE_TRANSITION;
  720. }
  721. }
  722. const nonIdentifierRE = /^\d|[^\$\w]/;
  723. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  724. const memberExpRE = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]]+\])*$/;
  725. const isMemberExpression = (path) => {
  726. if (!path)
  727. return false;
  728. return memberExpRE.test(path.trim());
  729. };
  730. function getInnerRange(loc, offset, length) {
  731. const source = loc.source.substr(offset, length);
  732. const newLoc = {
  733. source,
  734. start: advancePositionWithClone(loc.start, loc.source, offset),
  735. end: loc.end
  736. };
  737. if (length != null) {
  738. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  739. }
  740. return newLoc;
  741. }
  742. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  743. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  744. }
  745. // advance by mutation without cloning (for performance reasons), since this
  746. // gets called a lot in the parser
  747. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  748. let linesCount = 0;
  749. let lastNewLinePos = -1;
  750. for (let i = 0; i < numberOfCharacters; i++) {
  751. if (source.charCodeAt(i) === 10 /* newline char code */) {
  752. linesCount++;
  753. lastNewLinePos = i;
  754. }
  755. }
  756. pos.offset += numberOfCharacters;
  757. pos.line += linesCount;
  758. pos.column =
  759. lastNewLinePos === -1
  760. ? pos.column + numberOfCharacters
  761. : numberOfCharacters - lastNewLinePos;
  762. return pos;
  763. }
  764. function assert(condition, msg) {
  765. /* istanbul ignore if */
  766. if (!condition) {
  767. throw new Error(msg || `unexpected compiler condition`);
  768. }
  769. }
  770. function findDir(node, name, allowEmpty = false) {
  771. for (let i = 0; i < node.props.length; i++) {
  772. const p = node.props[i];
  773. if (p.type === 7 /* DIRECTIVE */ &&
  774. (allowEmpty || p.exp) &&
  775. (isString(name) ? p.name === name : name.test(p.name))) {
  776. return p;
  777. }
  778. }
  779. }
  780. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  781. for (let i = 0; i < node.props.length; i++) {
  782. const p = node.props[i];
  783. if (p.type === 6 /* ATTRIBUTE */) {
  784. if (dynamicOnly)
  785. continue;
  786. if (p.name === name && (p.value || allowEmpty)) {
  787. return p;
  788. }
  789. }
  790. else if (p.name === 'bind' &&
  791. (p.exp || allowEmpty) &&
  792. isBindKey(p.arg, name)) {
  793. return p;
  794. }
  795. }
  796. }
  797. function isBindKey(arg, name) {
  798. return !!(arg && isStaticExp(arg) && arg.content === name);
  799. }
  800. function hasDynamicKeyVBind(node) {
  801. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  802. p.name === 'bind' &&
  803. (!p.arg || // v-bind="obj"
  804. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  805. !p.arg.isStatic) // v-bind:[foo]
  806. );
  807. }
  808. function isText(node) {
  809. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  810. }
  811. function isVSlot(p) {
  812. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  813. }
  814. function isTemplateNode(node) {
  815. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  816. }
  817. function isSlotOutlet(node) {
  818. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  819. }
  820. function injectProp(node, prop, context) {
  821. let propsWithInjection;
  822. const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  823. if (props == null || isString(props)) {
  824. propsWithInjection = createObjectExpression([prop]);
  825. }
  826. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  827. // merged props... add ours
  828. // only inject key to object literal if it's the first argument so that
  829. // if doesn't override user provided keys
  830. const first = props.arguments[0];
  831. if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  832. first.properties.unshift(prop);
  833. }
  834. else {
  835. if (props.callee === TO_HANDLERS) {
  836. // #2366
  837. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  838. createObjectExpression([prop]),
  839. props
  840. ]);
  841. }
  842. else {
  843. props.arguments.unshift(createObjectExpression([prop]));
  844. }
  845. }
  846. !propsWithInjection && (propsWithInjection = props);
  847. }
  848. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  849. let alreadyExists = false;
  850. // check existing key to avoid overriding user provided keys
  851. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  852. const propKeyName = prop.key.content;
  853. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  854. p.key.content === propKeyName);
  855. }
  856. if (!alreadyExists) {
  857. props.properties.unshift(prop);
  858. }
  859. propsWithInjection = props;
  860. }
  861. else {
  862. // single v-bind with expression, return a merged replacement
  863. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  864. createObjectExpression([prop]),
  865. props
  866. ]);
  867. }
  868. if (node.type === 13 /* VNODE_CALL */) {
  869. node.props = propsWithInjection;
  870. }
  871. else {
  872. node.arguments[2] = propsWithInjection;
  873. }
  874. }
  875. function toValidAssetId(name, type) {
  876. return `_${type}_${name.replace(/[^\w]/g, '_')}`;
  877. }
  878. // Check if a node contains expressions that reference current context scope ids
  879. function hasScopeRef(node, ids) {
  880. if (!node || Object.keys(ids).length === 0) {
  881. return false;
  882. }
  883. switch (node.type) {
  884. case 1 /* ELEMENT */:
  885. for (let i = 0; i < node.props.length; i++) {
  886. const p = node.props[i];
  887. if (p.type === 7 /* DIRECTIVE */ &&
  888. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  889. return true;
  890. }
  891. }
  892. return node.children.some(c => hasScopeRef(c, ids));
  893. case 11 /* FOR */:
  894. if (hasScopeRef(node.source, ids)) {
  895. return true;
  896. }
  897. return node.children.some(c => hasScopeRef(c, ids));
  898. case 9 /* IF */:
  899. return node.branches.some(b => hasScopeRef(b, ids));
  900. case 10 /* IF_BRANCH */:
  901. if (hasScopeRef(node.condition, ids)) {
  902. return true;
  903. }
  904. return node.children.some(c => hasScopeRef(c, ids));
  905. case 4 /* SIMPLE_EXPRESSION */:
  906. return (!node.isStatic &&
  907. isSimpleIdentifier(node.content) &&
  908. !!ids[node.content]);
  909. case 8 /* COMPOUND_EXPRESSION */:
  910. return node.children.some(c => isObject(c) && hasScopeRef(c, ids));
  911. case 5 /* INTERPOLATION */:
  912. case 12 /* TEXT_CALL */:
  913. return hasScopeRef(node.content, ids);
  914. case 2 /* TEXT */:
  915. case 3 /* COMMENT */:
  916. return false;
  917. default:
  918. return false;
  919. }
  920. }
  921. // The default decoder only provides escapes for characters reserved as part of
  922. // the template syntax, and is only used if the custom renderer did not provide
  923. // a platform-specific decoder.
  924. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  925. const decodeMap = {
  926. gt: '>',
  927. lt: '<',
  928. amp: '&',
  929. apos: "'",
  930. quot: '"'
  931. };
  932. const defaultParserOptions = {
  933. delimiters: [`{{`, `}}`],
  934. getNamespace: () => 0 /* HTML */,
  935. getTextMode: () => 0 /* DATA */,
  936. isVoidTag: NO,
  937. isPreTag: NO,
  938. isCustomElement: NO,
  939. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  940. onError: defaultOnError,
  941. comments: false
  942. };
  943. function baseParse(content, options = {}) {
  944. const context = createParserContext(content, options);
  945. const start = getCursor(context);
  946. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  947. }
  948. function createParserContext(content, rawOptions) {
  949. const options = extend({}, defaultParserOptions);
  950. for (const key in rawOptions) {
  951. // @ts-ignore
  952. options[key] = rawOptions[key] || defaultParserOptions[key];
  953. }
  954. return {
  955. options,
  956. column: 1,
  957. line: 1,
  958. offset: 0,
  959. originalSource: content,
  960. source: content,
  961. inPre: false,
  962. inVPre: false
  963. };
  964. }
  965. function parseChildren(context, mode, ancestors) {
  966. const parent = last(ancestors);
  967. const ns = parent ? parent.ns : 0 /* HTML */;
  968. const nodes = [];
  969. while (!isEnd(context, mode, ancestors)) {
  970. const s = context.source;
  971. let node = undefined;
  972. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  973. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  974. // '{{'
  975. node = parseInterpolation(context, mode);
  976. }
  977. else if (mode === 0 /* DATA */ && s[0] === '<') {
  978. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  979. if (s.length === 1) {
  980. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  981. }
  982. else if (s[1] === '!') {
  983. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  984. if (startsWith(s, '<!--')) {
  985. node = parseComment(context);
  986. }
  987. else if (startsWith(s, '<!DOCTYPE')) {
  988. // Ignore DOCTYPE by a limitation.
  989. node = parseBogusComment(context);
  990. }
  991. else if (startsWith(s, '<![CDATA[')) {
  992. if (ns !== 0 /* HTML */) {
  993. node = parseCDATA(context, ancestors);
  994. }
  995. else {
  996. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  997. node = parseBogusComment(context);
  998. }
  999. }
  1000. else {
  1001. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  1002. node = parseBogusComment(context);
  1003. }
  1004. }
  1005. else if (s[1] === '/') {
  1006. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  1007. if (s.length === 2) {
  1008. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  1009. }
  1010. else if (s[2] === '>') {
  1011. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  1012. advanceBy(context, 3);
  1013. continue;
  1014. }
  1015. else if (/[a-z]/i.test(s[2])) {
  1016. emitError(context, 23 /* X_INVALID_END_TAG */);
  1017. parseTag(context, 1 /* End */, parent);
  1018. continue;
  1019. }
  1020. else {
  1021. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  1022. node = parseBogusComment(context);
  1023. }
  1024. }
  1025. else if (/[a-z]/i.test(s[1])) {
  1026. node = parseElement(context, ancestors);
  1027. }
  1028. else if (s[1] === '?') {
  1029. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  1030. node = parseBogusComment(context);
  1031. }
  1032. else {
  1033. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  1034. }
  1035. }
  1036. }
  1037. if (!node) {
  1038. node = parseText(context, mode);
  1039. }
  1040. if (isArray(node)) {
  1041. for (let i = 0; i < node.length; i++) {
  1042. pushNode(nodes, node[i]);
  1043. }
  1044. }
  1045. else {
  1046. pushNode(nodes, node);
  1047. }
  1048. }
  1049. // Whitespace management for more efficient output
  1050. // (same as v2 whitespace: 'condense')
  1051. let removedWhitespace = false;
  1052. if (mode !== 2 /* RAWTEXT */) {
  1053. for (let i = 0; i < nodes.length; i++) {
  1054. const node = nodes[i];
  1055. if (!context.inPre && node.type === 2 /* TEXT */) {
  1056. if (!/[^\t\r\n\f ]/.test(node.content)) {
  1057. const prev = nodes[i - 1];
  1058. const next = nodes[i + 1];
  1059. // If:
  1060. // - the whitespace is the first or last node, or:
  1061. // - the whitespace is adjacent to a comment, or:
  1062. // - the whitespace is between two elements AND contains newline
  1063. // Then the whitespace is ignored.
  1064. if (!prev ||
  1065. !next ||
  1066. prev.type === 3 /* COMMENT */ ||
  1067. next.type === 3 /* COMMENT */ ||
  1068. (prev.type === 1 /* ELEMENT */ &&
  1069. next.type === 1 /* ELEMENT */ &&
  1070. /[\r\n]/.test(node.content))) {
  1071. removedWhitespace = true;
  1072. nodes[i] = null;
  1073. }
  1074. else {
  1075. // Otherwise, condensed consecutive whitespace inside the text
  1076. // down to a single space
  1077. node.content = ' ';
  1078. }
  1079. }
  1080. else {
  1081. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  1082. }
  1083. }
  1084. }
  1085. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  1086. // remove leading newline per html spec
  1087. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  1088. const first = nodes[0];
  1089. if (first && first.type === 2 /* TEXT */) {
  1090. first.content = first.content.replace(/^\r?\n/, '');
  1091. }
  1092. }
  1093. }
  1094. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  1095. }
  1096. function pushNode(nodes, node) {
  1097. if (node.type === 2 /* TEXT */) {
  1098. const prev = last(nodes);
  1099. // Merge if both this and the previous node are text and those are
  1100. // consecutive. This happens for cases like "a < b".
  1101. if (prev &&
  1102. prev.type === 2 /* TEXT */ &&
  1103. prev.loc.end.offset === node.loc.start.offset) {
  1104. prev.content += node.content;
  1105. prev.loc.end = node.loc.end;
  1106. prev.loc.source += node.loc.source;
  1107. return;
  1108. }
  1109. }
  1110. nodes.push(node);
  1111. }
  1112. function parseCDATA(context, ancestors) {
  1113. advanceBy(context, 9);
  1114. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  1115. if (context.source.length === 0) {
  1116. emitError(context, 6 /* EOF_IN_CDATA */);
  1117. }
  1118. else {
  1119. advanceBy(context, 3);
  1120. }
  1121. return nodes;
  1122. }
  1123. function parseComment(context) {
  1124. const start = getCursor(context);
  1125. let content;
  1126. // Regular comment.
  1127. const match = /--(\!)?>/.exec(context.source);
  1128. if (!match) {
  1129. content = context.source.slice(4);
  1130. advanceBy(context, context.source.length);
  1131. emitError(context, 7 /* EOF_IN_COMMENT */);
  1132. }
  1133. else {
  1134. if (match.index <= 3) {
  1135. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  1136. }
  1137. if (match[1]) {
  1138. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  1139. }
  1140. content = context.source.slice(4, match.index);
  1141. // Advancing with reporting nested comments.
  1142. const s = context.source.slice(0, match.index);
  1143. let prevIndex = 1, nestedIndex = 0;
  1144. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  1145. advanceBy(context, nestedIndex - prevIndex + 1);
  1146. if (nestedIndex + 4 < s.length) {
  1147. emitError(context, 16 /* NESTED_COMMENT */);
  1148. }
  1149. prevIndex = nestedIndex + 1;
  1150. }
  1151. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  1152. }
  1153. return {
  1154. type: 3 /* COMMENT */,
  1155. content,
  1156. loc: getSelection(context, start)
  1157. };
  1158. }
  1159. function parseBogusComment(context) {
  1160. const start = getCursor(context);
  1161. const contentStart = context.source[1] === '?' ? 1 : 2;
  1162. let content;
  1163. const closeIndex = context.source.indexOf('>');
  1164. if (closeIndex === -1) {
  1165. content = context.source.slice(contentStart);
  1166. advanceBy(context, context.source.length);
  1167. }
  1168. else {
  1169. content = context.source.slice(contentStart, closeIndex);
  1170. advanceBy(context, closeIndex + 1);
  1171. }
  1172. return {
  1173. type: 3 /* COMMENT */,
  1174. content,
  1175. loc: getSelection(context, start)
  1176. };
  1177. }
  1178. function parseElement(context, ancestors) {
  1179. // Start tag.
  1180. const wasInPre = context.inPre;
  1181. const wasInVPre = context.inVPre;
  1182. const parent = last(ancestors);
  1183. const element = parseTag(context, 0 /* Start */, parent);
  1184. const isPreBoundary = context.inPre && !wasInPre;
  1185. const isVPreBoundary = context.inVPre && !wasInVPre;
  1186. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  1187. return element;
  1188. }
  1189. // Children.
  1190. ancestors.push(element);
  1191. const mode = context.options.getTextMode(element, parent);
  1192. const children = parseChildren(context, mode, ancestors);
  1193. ancestors.pop();
  1194. element.children = children;
  1195. // End tag.
  1196. if (startsWithEndTagOpen(context.source, element.tag)) {
  1197. parseTag(context, 1 /* End */, parent);
  1198. }
  1199. else {
  1200. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  1201. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  1202. const first = children[0];
  1203. if (first && startsWith(first.loc.source, '<!--')) {
  1204. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  1205. }
  1206. }
  1207. }
  1208. element.loc = getSelection(context, element.loc.start);
  1209. if (isPreBoundary) {
  1210. context.inPre = false;
  1211. }
  1212. if (isVPreBoundary) {
  1213. context.inVPre = false;
  1214. }
  1215. return element;
  1216. }
  1217. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  1218. /**
  1219. * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
  1220. */
  1221. function parseTag(context, type, parent) {
  1222. // Tag open.
  1223. const start = getCursor(context);
  1224. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  1225. const tag = match[1];
  1226. const ns = context.options.getNamespace(tag, parent);
  1227. advanceBy(context, match[0].length);
  1228. advanceSpaces(context);
  1229. // save current state in case we need to re-parse attributes with v-pre
  1230. const cursor = getCursor(context);
  1231. const currentSource = context.source;
  1232. // Attributes.
  1233. let props = parseAttributes(context, type);
  1234. // check <pre> tag
  1235. if (context.options.isPreTag(tag)) {
  1236. context.inPre = true;
  1237. }
  1238. // check v-pre
  1239. if (!context.inVPre &&
  1240. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  1241. context.inVPre = true;
  1242. // reset context
  1243. extend(context, cursor);
  1244. context.source = currentSource;
  1245. // re-parse attrs and filter out v-pre itself
  1246. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  1247. }
  1248. // Tag close.
  1249. let isSelfClosing = false;
  1250. if (context.source.length === 0) {
  1251. emitError(context, 9 /* EOF_IN_TAG */);
  1252. }
  1253. else {
  1254. isSelfClosing = startsWith(context.source, '/>');
  1255. if (type === 1 /* End */ && isSelfClosing) {
  1256. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  1257. }
  1258. advanceBy(context, isSelfClosing ? 2 : 1);
  1259. }
  1260. let tagType = 0 /* ELEMENT */;
  1261. const options = context.options;
  1262. if (!context.inVPre && !options.isCustomElement(tag)) {
  1263. const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
  1264. if (options.isNativeTag && !hasVIs) {
  1265. if (!options.isNativeTag(tag))
  1266. tagType = 1 /* COMPONENT */;
  1267. }
  1268. else if (hasVIs ||
  1269. isCoreComponent(tag) ||
  1270. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  1271. /^[A-Z]/.test(tag) ||
  1272. tag === 'component') {
  1273. tagType = 1 /* COMPONENT */;
  1274. }
  1275. if (tag === 'slot') {
  1276. tagType = 2 /* SLOT */;
  1277. }
  1278. else if (tag === 'template' &&
  1279. props.some(p => {
  1280. return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
  1281. })) {
  1282. tagType = 3 /* TEMPLATE */;
  1283. }
  1284. }
  1285. return {
  1286. type: 1 /* ELEMENT */,
  1287. ns,
  1288. tag,
  1289. tagType,
  1290. props,
  1291. isSelfClosing,
  1292. children: [],
  1293. loc: getSelection(context, start),
  1294. codegenNode: undefined // to be created during transform phase
  1295. };
  1296. }
  1297. function parseAttributes(context, type) {
  1298. const props = [];
  1299. const attributeNames = new Set();
  1300. while (context.source.length > 0 &&
  1301. !startsWith(context.source, '>') &&
  1302. !startsWith(context.source, '/>')) {
  1303. if (startsWith(context.source, '/')) {
  1304. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  1305. advanceBy(context, 1);
  1306. advanceSpaces(context);
  1307. continue;
  1308. }
  1309. if (type === 1 /* End */) {
  1310. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  1311. }
  1312. const attr = parseAttribute(context, attributeNames);
  1313. if (type === 0 /* Start */) {
  1314. props.push(attr);
  1315. }
  1316. if (/^[^\t\r\n\f />]/.test(context.source)) {
  1317. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  1318. }
  1319. advanceSpaces(context);
  1320. }
  1321. return props;
  1322. }
  1323. function parseAttribute(context, nameSet) {
  1324. // Name.
  1325. const start = getCursor(context);
  1326. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  1327. const name = match[0];
  1328. if (nameSet.has(name)) {
  1329. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  1330. }
  1331. nameSet.add(name);
  1332. if (name[0] === '=') {
  1333. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  1334. }
  1335. {
  1336. const pattern = /["'<]/g;
  1337. let m;
  1338. while ((m = pattern.exec(name))) {
  1339. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  1340. }
  1341. }
  1342. advanceBy(context, name.length);
  1343. // Value
  1344. let value = undefined;
  1345. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  1346. advanceSpaces(context);
  1347. advanceBy(context, 1);
  1348. advanceSpaces(context);
  1349. value = parseAttributeValue(context);
  1350. if (!value) {
  1351. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  1352. }
  1353. }
  1354. const loc = getSelection(context, start);
  1355. if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
  1356. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  1357. const dirName = match[1] ||
  1358. (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
  1359. let arg;
  1360. if (match[2]) {
  1361. const isSlot = dirName === 'slot';
  1362. const startOffset = name.indexOf(match[2]);
  1363. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  1364. let content = match[2];
  1365. let isStatic = true;
  1366. if (content.startsWith('[')) {
  1367. isStatic = false;
  1368. if (!content.endsWith(']')) {
  1369. emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  1370. }
  1371. content = content.substr(1, content.length - 2);
  1372. }
  1373. else if (isSlot) {
  1374. // #1241 special case for v-slot: vuetify relies extensively on slot
  1375. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  1376. // supports such usage so we are keeping it consistent with 2.x.
  1377. content += match[3] || '';
  1378. }
  1379. arg = {
  1380. type: 4 /* SIMPLE_EXPRESSION */,
  1381. content,
  1382. isStatic,
  1383. constType: isStatic
  1384. ? 3 /* CAN_STRINGIFY */
  1385. : 0 /* NOT_CONSTANT */,
  1386. loc
  1387. };
  1388. }
  1389. if (value && value.isQuoted) {
  1390. const valueLoc = value.loc;
  1391. valueLoc.start.offset++;
  1392. valueLoc.start.column++;
  1393. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  1394. valueLoc.source = valueLoc.source.slice(1, -1);
  1395. }
  1396. return {
  1397. type: 7 /* DIRECTIVE */,
  1398. name: dirName,
  1399. exp: value && {
  1400. type: 4 /* SIMPLE_EXPRESSION */,
  1401. content: value.content,
  1402. isStatic: false,
  1403. // Treat as non-constant by default. This can be potentially set to
  1404. // other values by `transformExpression` to make it eligible for hoisting.
  1405. constType: 0 /* NOT_CONSTANT */,
  1406. loc: value.loc
  1407. },
  1408. arg,
  1409. modifiers: match[3] ? match[3].substr(1).split('.') : [],
  1410. loc
  1411. };
  1412. }
  1413. return {
  1414. type: 6 /* ATTRIBUTE */,
  1415. name,
  1416. value: value && {
  1417. type: 2 /* TEXT */,
  1418. content: value.content,
  1419. loc: value.loc
  1420. },
  1421. loc
  1422. };
  1423. }
  1424. function parseAttributeValue(context) {
  1425. const start = getCursor(context);
  1426. let content;
  1427. const quote = context.source[0];
  1428. const isQuoted = quote === `"` || quote === `'`;
  1429. if (isQuoted) {
  1430. // Quoted value.
  1431. advanceBy(context, 1);
  1432. const endIndex = context.source.indexOf(quote);
  1433. if (endIndex === -1) {
  1434. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  1435. }
  1436. else {
  1437. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  1438. advanceBy(context, 1);
  1439. }
  1440. }
  1441. else {
  1442. // Unquoted
  1443. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  1444. if (!match) {
  1445. return undefined;
  1446. }
  1447. const unexpectedChars = /["'<=`]/g;
  1448. let m;
  1449. while ((m = unexpectedChars.exec(match[0]))) {
  1450. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  1451. }
  1452. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  1453. }
  1454. return { content, isQuoted, loc: getSelection(context, start) };
  1455. }
  1456. function parseInterpolation(context, mode) {
  1457. const [open, close] = context.options.delimiters;
  1458. const closeIndex = context.source.indexOf(close, open.length);
  1459. if (closeIndex === -1) {
  1460. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  1461. return undefined;
  1462. }
  1463. const start = getCursor(context);
  1464. advanceBy(context, open.length);
  1465. const innerStart = getCursor(context);
  1466. const innerEnd = getCursor(context);
  1467. const rawContentLength = closeIndex - open.length;
  1468. const rawContent = context.source.slice(0, rawContentLength);
  1469. const preTrimContent = parseTextData(context, rawContentLength, mode);
  1470. const content = preTrimContent.trim();
  1471. const startOffset = preTrimContent.indexOf(content);
  1472. if (startOffset > 0) {
  1473. advancePositionWithMutation(innerStart, rawContent, startOffset);
  1474. }
  1475. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  1476. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  1477. advanceBy(context, close.length);
  1478. return {
  1479. type: 5 /* INTERPOLATION */,
  1480. content: {
  1481. type: 4 /* SIMPLE_EXPRESSION */,
  1482. isStatic: false,
  1483. // Set `isConstant` to false by default and will decide in transformExpression
  1484. constType: 0 /* NOT_CONSTANT */,
  1485. content,
  1486. loc: getSelection(context, innerStart, innerEnd)
  1487. },
  1488. loc: getSelection(context, start)
  1489. };
  1490. }
  1491. function parseText(context, mode) {
  1492. const endTokens = ['<', context.options.delimiters[0]];
  1493. if (mode === 3 /* CDATA */) {
  1494. endTokens.push(']]>');
  1495. }
  1496. let endIndex = context.source.length;
  1497. for (let i = 0; i < endTokens.length; i++) {
  1498. const index = context.source.indexOf(endTokens[i], 1);
  1499. if (index !== -1 && endIndex > index) {
  1500. endIndex = index;
  1501. }
  1502. }
  1503. const start = getCursor(context);
  1504. const content = parseTextData(context, endIndex, mode);
  1505. return {
  1506. type: 2 /* TEXT */,
  1507. content,
  1508. loc: getSelection(context, start)
  1509. };
  1510. }
  1511. /**
  1512. * Get text data with a given length from the current location.
  1513. * This translates HTML entities in the text data.
  1514. */
  1515. function parseTextData(context, length, mode) {
  1516. const rawText = context.source.slice(0, length);
  1517. advanceBy(context, length);
  1518. if (mode === 2 /* RAWTEXT */ ||
  1519. mode === 3 /* CDATA */ ||
  1520. rawText.indexOf('&') === -1) {
  1521. return rawText;
  1522. }
  1523. else {
  1524. // DATA or RCDATA containing "&"". Entity decoding required.
  1525. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  1526. }
  1527. }
  1528. function getCursor(context) {
  1529. const { column, line, offset } = context;
  1530. return { column, line, offset };
  1531. }
  1532. function getSelection(context, start, end) {
  1533. end = end || getCursor(context);
  1534. return {
  1535. start,
  1536. end,
  1537. source: context.originalSource.slice(start.offset, end.offset)
  1538. };
  1539. }
  1540. function last(xs) {
  1541. return xs[xs.length - 1];
  1542. }
  1543. function startsWith(source, searchString) {
  1544. return source.startsWith(searchString);
  1545. }
  1546. function advanceBy(context, numberOfCharacters) {
  1547. const { source } = context;
  1548. advancePositionWithMutation(context, source, numberOfCharacters);
  1549. context.source = source.slice(numberOfCharacters);
  1550. }
  1551. function advanceSpaces(context) {
  1552. const match = /^[\t\r\n\f ]+/.exec(context.source);
  1553. if (match) {
  1554. advanceBy(context, match[0].length);
  1555. }
  1556. }
  1557. function getNewPosition(context, start, numberOfCharacters) {
  1558. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  1559. }
  1560. function emitError(context, code, offset, loc = getCursor(context)) {
  1561. if (offset) {
  1562. loc.offset += offset;
  1563. loc.column += offset;
  1564. }
  1565. context.options.onError(createCompilerError(code, {
  1566. start: loc,
  1567. end: loc,
  1568. source: ''
  1569. }));
  1570. }
  1571. function isEnd(context, mode, ancestors) {
  1572. const s = context.source;
  1573. switch (mode) {
  1574. case 0 /* DATA */:
  1575. if (startsWith(s, '</')) {
  1576. // TODO: probably bad performance
  1577. for (let i = ancestors.length - 1; i >= 0; --i) {
  1578. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  1579. return true;
  1580. }
  1581. }
  1582. }
  1583. break;
  1584. case 1 /* RCDATA */:
  1585. case 2 /* RAWTEXT */: {
  1586. const parent = last(ancestors);
  1587. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  1588. return true;
  1589. }
  1590. break;
  1591. }
  1592. case 3 /* CDATA */:
  1593. if (startsWith(s, ']]>')) {
  1594. return true;
  1595. }
  1596. break;
  1597. }
  1598. return !s;
  1599. }
  1600. function startsWithEndTagOpen(source, tag) {
  1601. return (startsWith(source, '</') &&
  1602. source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
  1603. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  1604. }
  1605. function hoistStatic(root, context) {
  1606. walk(root, context,
  1607. // Root node is unfortunately non-hoistable due to potential parent
  1608. // fallthrough attributes.
  1609. isSingleElementRoot(root, root.children[0]));
  1610. }
  1611. function isSingleElementRoot(root, child) {
  1612. const { children } = root;
  1613. return (children.length === 1 &&
  1614. child.type === 1 /* ELEMENT */ &&
  1615. !isSlotOutlet(child));
  1616. }
  1617. function walk(node, context, doNotHoistNode = false) {
  1618. let hasHoistedNode = false;
  1619. // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
  1620. // static bindings with expressions. These expressions are guaranteed to be
  1621. // constant so they are still eligible for hoisting, but they are only
  1622. // available at runtime and therefore cannot be evaluated ahead of time.
  1623. // This is only a concern for pre-stringification (via transformHoist by
  1624. // @vue/compiler-dom), but doing it here allows us to perform only one full
  1625. // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
  1626. // stringficiation threshold is met.
  1627. let canStringify = true;
  1628. const { children } = node;
  1629. for (let i = 0; i < children.length; i++) {
  1630. const child = children[i];
  1631. // only plain elements & text calls are eligible for hoisting.
  1632. if (child.type === 1 /* ELEMENT */ &&
  1633. child.tagType === 0 /* ELEMENT */) {
  1634. const constantType = doNotHoistNode
  1635. ? 0 /* NOT_CONSTANT */
  1636. : getConstantType(child, context);
  1637. if (constantType > 0 /* NOT_CONSTANT */) {
  1638. if (constantType < 3 /* CAN_STRINGIFY */) {
  1639. canStringify = false;
  1640. }
  1641. if (constantType >= 2 /* CAN_HOIST */) {
  1642. child.codegenNode.patchFlag =
  1643. -1 /* HOISTED */ + (` /* HOISTED */` );
  1644. child.codegenNode = context.hoist(child.codegenNode);
  1645. hasHoistedNode = true;
  1646. continue;
  1647. }
  1648. }
  1649. else {
  1650. // node may contain dynamic children, but its props may be eligible for
  1651. // hoisting.
  1652. const codegenNode = child.codegenNode;
  1653. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1654. const flag = getPatchFlag(codegenNode);
  1655. if ((!flag ||
  1656. flag === 512 /* NEED_PATCH */ ||
  1657. flag === 1 /* TEXT */) &&
  1658. getGeneratedPropsConstantType(child, context) >=
  1659. 2 /* CAN_HOIST */) {
  1660. const props = getNodeProps(child);
  1661. if (props) {
  1662. codegenNode.props = context.hoist(props);
  1663. }
  1664. }
  1665. }
  1666. }
  1667. }
  1668. else if (child.type === 12 /* TEXT_CALL */) {
  1669. const contentType = getConstantType(child.content, context);
  1670. if (contentType > 0) {
  1671. if (contentType < 3 /* CAN_STRINGIFY */) {
  1672. canStringify = false;
  1673. }
  1674. if (contentType >= 2 /* CAN_HOIST */) {
  1675. child.codegenNode = context.hoist(child.codegenNode);
  1676. hasHoistedNode = true;
  1677. }
  1678. }
  1679. }
  1680. // walk further
  1681. if (child.type === 1 /* ELEMENT */) {
  1682. walk(child, context);
  1683. }
  1684. else if (child.type === 11 /* FOR */) {
  1685. // Do not hoist v-for single child because it has to be a block
  1686. walk(child, context, child.children.length === 1);
  1687. }
  1688. else if (child.type === 9 /* IF */) {
  1689. for (let i = 0; i < child.branches.length; i++) {
  1690. // Do not hoist v-if single child because it has to be a block
  1691. walk(child.branches[i], context, child.branches[i].children.length === 1);
  1692. }
  1693. }
  1694. }
  1695. if (canStringify && hasHoistedNode && context.transformHoist) {
  1696. context.transformHoist(children, context, node);
  1697. }
  1698. }
  1699. function getConstantType(node, context) {
  1700. const { constantCache } = context;
  1701. switch (node.type) {
  1702. case 1 /* ELEMENT */:
  1703. if (node.tagType !== 0 /* ELEMENT */) {
  1704. return 0 /* NOT_CONSTANT */;
  1705. }
  1706. const cached = constantCache.get(node);
  1707. if (cached !== undefined) {
  1708. return cached;
  1709. }
  1710. const codegenNode = node.codegenNode;
  1711. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  1712. return 0 /* NOT_CONSTANT */;
  1713. }
  1714. const flag = getPatchFlag(codegenNode);
  1715. if (!flag) {
  1716. let returnType = 3 /* CAN_STRINGIFY */;
  1717. // Element itself has no patch flag. However we still need to check:
  1718. // 1. Even for a node with no patch flag, it is possible for it to contain
  1719. // non-hoistable expressions that refers to scope variables, e.g. compiler
  1720. // injected keys or cached event handlers. Therefore we need to always
  1721. // check the codegenNode's props to be sure.
  1722. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  1723. if (generatedPropsType === 0 /* NOT_CONSTANT */) {
  1724. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1725. return 0 /* NOT_CONSTANT */;
  1726. }
  1727. if (generatedPropsType < returnType) {
  1728. returnType = generatedPropsType;
  1729. }
  1730. // 2. its children.
  1731. for (let i = 0; i < node.children.length; i++) {
  1732. const childType = getConstantType(node.children[i], context);
  1733. if (childType === 0 /* NOT_CONSTANT */) {
  1734. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1735. return 0 /* NOT_CONSTANT */;
  1736. }
  1737. if (childType < returnType) {
  1738. returnType = childType;
  1739. }
  1740. }
  1741. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  1742. // type, check if any of the props can cause the type to be lowered
  1743. // we can skip can_patch because it's guaranteed by the absence of a
  1744. // patchFlag.
  1745. if (returnType > 1 /* CAN_SKIP_PATCH */) {
  1746. for (let i = 0; i < node.props.length; i++) {
  1747. const p = node.props[i];
  1748. if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
  1749. const expType = getConstantType(p.exp, context);
  1750. if (expType === 0 /* NOT_CONSTANT */) {
  1751. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1752. return 0 /* NOT_CONSTANT */;
  1753. }
  1754. if (expType < returnType) {
  1755. returnType = expType;
  1756. }
  1757. }
  1758. }
  1759. }
  1760. // only svg/foreignObject could be block here, however if they are
  1761. // static then they don't need to be blocks since there will be no
  1762. // nested updates.
  1763. if (codegenNode.isBlock) {
  1764. codegenNode.isBlock = false;
  1765. context.helper(CREATE_VNODE);
  1766. }
  1767. constantCache.set(node, returnType);
  1768. return returnType;
  1769. }
  1770. else {
  1771. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1772. return 0 /* NOT_CONSTANT */;
  1773. }
  1774. case 2 /* TEXT */:
  1775. case 3 /* COMMENT */:
  1776. return 3 /* CAN_STRINGIFY */;
  1777. case 9 /* IF */:
  1778. case 11 /* FOR */:
  1779. case 10 /* IF_BRANCH */:
  1780. return 0 /* NOT_CONSTANT */;
  1781. case 5 /* INTERPOLATION */:
  1782. case 12 /* TEXT_CALL */:
  1783. return getConstantType(node.content, context);
  1784. case 4 /* SIMPLE_EXPRESSION */:
  1785. return node.constType;
  1786. case 8 /* COMPOUND_EXPRESSION */:
  1787. let returnType = 3 /* CAN_STRINGIFY */;
  1788. for (let i = 0; i < node.children.length; i++) {
  1789. const child = node.children[i];
  1790. if (isString(child) || isSymbol(child)) {
  1791. continue;
  1792. }
  1793. const childType = getConstantType(child, context);
  1794. if (childType === 0 /* NOT_CONSTANT */) {
  1795. return 0 /* NOT_CONSTANT */;
  1796. }
  1797. else if (childType < returnType) {
  1798. returnType = childType;
  1799. }
  1800. }
  1801. return returnType;
  1802. default:
  1803. return 0 /* NOT_CONSTANT */;
  1804. }
  1805. }
  1806. function getGeneratedPropsConstantType(node, context) {
  1807. let returnType = 3 /* CAN_STRINGIFY */;
  1808. const props = getNodeProps(node);
  1809. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  1810. const { properties } = props;
  1811. for (let i = 0; i < properties.length; i++) {
  1812. const { key, value } = properties[i];
  1813. const keyType = getConstantType(key, context);
  1814. if (keyType === 0 /* NOT_CONSTANT */) {
  1815. return keyType;
  1816. }
  1817. if (keyType < returnType) {
  1818. returnType = keyType;
  1819. }
  1820. if (value.type !== 4 /* SIMPLE_EXPRESSION */) {
  1821. return 0 /* NOT_CONSTANT */;
  1822. }
  1823. const valueType = getConstantType(value, context);
  1824. if (valueType === 0 /* NOT_CONSTANT */) {
  1825. return valueType;
  1826. }
  1827. if (valueType < returnType) {
  1828. returnType = valueType;
  1829. }
  1830. }
  1831. }
  1832. return returnType;
  1833. }
  1834. function getNodeProps(node) {
  1835. const codegenNode = node.codegenNode;
  1836. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1837. return codegenNode.props;
  1838. }
  1839. }
  1840. function getPatchFlag(node) {
  1841. const flag = node.patchFlag;
  1842. return flag ? parseInt(flag, 10) : undefined;
  1843. }
  1844. function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, ssr = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError }) {
  1845. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  1846. const context = {
  1847. // options
  1848. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  1849. prefixIdentifiers,
  1850. hoistStatic,
  1851. cacheHandlers,
  1852. nodeTransforms,
  1853. directiveTransforms,
  1854. transformHoist,
  1855. isBuiltInComponent,
  1856. isCustomElement,
  1857. expressionPlugins,
  1858. scopeId,
  1859. ssr,
  1860. ssrCssVars,
  1861. bindingMetadata,
  1862. inline,
  1863. isTS,
  1864. onError,
  1865. // state
  1866. root,
  1867. helpers: new Set(),
  1868. components: new Set(),
  1869. directives: new Set(),
  1870. hoists: [],
  1871. imports: [],
  1872. constantCache: new Map(),
  1873. temps: 0,
  1874. cached: 0,
  1875. identifiers: Object.create(null),
  1876. scopes: {
  1877. vFor: 0,
  1878. vSlot: 0,
  1879. vPre: 0,
  1880. vOnce: 0
  1881. },
  1882. parent: null,
  1883. currentNode: root,
  1884. childIndex: 0,
  1885. // methods
  1886. helper(name) {
  1887. context.helpers.add(name);
  1888. return name;
  1889. },
  1890. helperString(name) {
  1891. return `_${helperNameMap[context.helper(name)]}`;
  1892. },
  1893. replaceNode(node) {
  1894. /* istanbul ignore if */
  1895. {
  1896. if (!context.currentNode) {
  1897. throw new Error(`Node being replaced is already removed.`);
  1898. }
  1899. if (!context.parent) {
  1900. throw new Error(`Cannot replace root node.`);
  1901. }
  1902. }
  1903. context.parent.children[context.childIndex] = context.currentNode = node;
  1904. },
  1905. removeNode(node) {
  1906. if (!context.parent) {
  1907. throw new Error(`Cannot remove root node.`);
  1908. }
  1909. const list = context.parent.children;
  1910. const removalIndex = node
  1911. ? list.indexOf(node)
  1912. : context.currentNode
  1913. ? context.childIndex
  1914. : -1;
  1915. /* istanbul ignore if */
  1916. if (removalIndex < 0) {
  1917. throw new Error(`node being removed is not a child of current parent`);
  1918. }
  1919. if (!node || node === context.currentNode) {
  1920. // current node removed
  1921. context.currentNode = null;
  1922. context.onNodeRemoved();
  1923. }
  1924. else {
  1925. // sibling node removed
  1926. if (context.childIndex > removalIndex) {
  1927. context.childIndex--;
  1928. context.onNodeRemoved();
  1929. }
  1930. }
  1931. context.parent.children.splice(removalIndex, 1);
  1932. },
  1933. onNodeRemoved: () => { },
  1934. addIdentifiers(exp) {
  1935. // identifier tracking only happens in non-browser builds.
  1936. {
  1937. if (isString(exp)) {
  1938. addId(exp);
  1939. }
  1940. else if (exp.identifiers) {
  1941. exp.identifiers.forEach(addId);
  1942. }
  1943. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  1944. addId(exp.content);
  1945. }
  1946. }
  1947. },
  1948. removeIdentifiers(exp) {
  1949. {
  1950. if (isString(exp)) {
  1951. removeId(exp);
  1952. }
  1953. else if (exp.identifiers) {
  1954. exp.identifiers.forEach(removeId);
  1955. }
  1956. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  1957. removeId(exp.content);
  1958. }
  1959. }
  1960. },
  1961. hoist(exp) {
  1962. context.hoists.push(exp);
  1963. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
  1964. identifier.hoisted = exp;
  1965. return identifier;
  1966. },
  1967. cache(exp, isVNode = false) {
  1968. return createCacheExpression(++context.cached, exp, isVNode);
  1969. }
  1970. };
  1971. function addId(id) {
  1972. const { identifiers } = context;
  1973. if (identifiers[id] === undefined) {
  1974. identifiers[id] = 0;
  1975. }
  1976. identifiers[id]++;
  1977. }
  1978. function removeId(id) {
  1979. context.identifiers[id]--;
  1980. }
  1981. return context;
  1982. }
  1983. function transform(root, options) {
  1984. const context = createTransformContext(root, options);
  1985. traverseNode(root, context);
  1986. if (options.hoistStatic) {
  1987. hoistStatic(root, context);
  1988. }
  1989. if (!options.ssr) {
  1990. createRootCodegen(root, context);
  1991. }
  1992. // finalize meta information
  1993. root.helpers = [...context.helpers];
  1994. root.components = [...context.components];
  1995. root.directives = [...context.directives];
  1996. root.imports = context.imports;
  1997. root.hoists = context.hoists;
  1998. root.temps = context.temps;
  1999. root.cached = context.cached;
  2000. }
  2001. function createRootCodegen(root, context) {
  2002. const { helper } = context;
  2003. const { children } = root;
  2004. if (children.length === 1) {
  2005. const child = children[0];
  2006. // if the single child is an element, turn it into a block.
  2007. if (isSingleElementRoot(root, child) && child.codegenNode) {
  2008. // single element root is never hoisted so codegenNode will never be
  2009. // SimpleExpressionNode
  2010. const codegenNode = child.codegenNode;
  2011. if (codegenNode.type === 13 /* VNODE_CALL */) {
  2012. codegenNode.isBlock = true;
  2013. helper(OPEN_BLOCK);
  2014. helper(CREATE_BLOCK);
  2015. }
  2016. root.codegenNode = codegenNode;
  2017. }
  2018. else {
  2019. // - single <slot/>, IfNode, ForNode: already blocks.
  2020. // - single text node: always patched.
  2021. // root codegen falls through via genNode()
  2022. root.codegenNode = child;
  2023. }
  2024. }
  2025. else if (children.length > 1) {
  2026. // root has multiple nodes - return a fragment block.
  2027. let patchFlag = 64 /* STABLE_FRAGMENT */;
  2028. let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
  2029. // check if the fragment actually contains a single valid child with
  2030. // the rest being comments
  2031. if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
  2032. patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
  2033. patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
  2034. }
  2035. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true);
  2036. }
  2037. else ;
  2038. }
  2039. function traverseChildren(parent, context) {
  2040. let i = 0;
  2041. const nodeRemoved = () => {
  2042. i--;
  2043. };
  2044. for (; i < parent.children.length; i++) {
  2045. const child = parent.children[i];
  2046. if (isString(child))
  2047. continue;
  2048. context.parent = parent;
  2049. context.childIndex = i;
  2050. context.onNodeRemoved = nodeRemoved;
  2051. traverseNode(child, context);
  2052. }
  2053. }
  2054. function traverseNode(node, context) {
  2055. context.currentNode = node;
  2056. // apply transform plugins
  2057. const { nodeTransforms } = context;
  2058. const exitFns = [];
  2059. for (let i = 0; i < nodeTransforms.length; i++) {
  2060. const onExit = nodeTransforms[i](node, context);
  2061. if (onExit) {
  2062. if (isArray(onExit)) {
  2063. exitFns.push(...onExit);
  2064. }
  2065. else {
  2066. exitFns.push(onExit);
  2067. }
  2068. }
  2069. if (!context.currentNode) {
  2070. // node was removed
  2071. return;
  2072. }
  2073. else {
  2074. // node may have been replaced
  2075. node = context.currentNode;
  2076. }
  2077. }
  2078. switch (node.type) {
  2079. case 3 /* COMMENT */:
  2080. if (!context.ssr) {
  2081. // inject import for the Comment symbol, which is needed for creating
  2082. // comment nodes with `createVNode`
  2083. context.helper(CREATE_COMMENT);
  2084. }
  2085. break;
  2086. case 5 /* INTERPOLATION */:
  2087. // no need to traverse, but we need to inject toString helper
  2088. if (!context.ssr) {
  2089. context.helper(TO_DISPLAY_STRING);
  2090. }
  2091. break;
  2092. // for container types, further traverse downwards
  2093. case 9 /* IF */:
  2094. for (let i = 0; i < node.branches.length; i++) {
  2095. traverseNode(node.branches[i], context);
  2096. }
  2097. break;
  2098. case 10 /* IF_BRANCH */:
  2099. case 11 /* FOR */:
  2100. case 1 /* ELEMENT */:
  2101. case 0 /* ROOT */:
  2102. traverseChildren(node, context);
  2103. break;
  2104. }
  2105. // exit transforms
  2106. context.currentNode = node;
  2107. let i = exitFns.length;
  2108. while (i--) {
  2109. exitFns[i]();
  2110. }
  2111. }
  2112. function createStructuralDirectiveTransform(name, fn) {
  2113. const matches = isString(name)
  2114. ? (n) => n === name
  2115. : (n) => name.test(n);
  2116. return (node, context) => {
  2117. if (node.type === 1 /* ELEMENT */) {
  2118. const { props } = node;
  2119. // structural directive transforms are not concerned with slots
  2120. // as they are handled separately in vSlot.ts
  2121. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  2122. return;
  2123. }
  2124. const exitFns = [];
  2125. for (let i = 0; i < props.length; i++) {
  2126. const prop = props[i];
  2127. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  2128. // structural directives are removed to avoid infinite recursion
  2129. // also we remove them *before* applying so that it can further
  2130. // traverse itself in case it moves the node around
  2131. props.splice(i, 1);
  2132. i--;
  2133. const onExit = fn(node, prop, context);
  2134. if (onExit)
  2135. exitFns.push(onExit);
  2136. }
  2137. }
  2138. return exitFns;
  2139. }
  2140. };
  2141. }
  2142. /* -*- Mode: js; js-indent-level: 2; -*- */
  2143. /*
  2144. * Copyright 2011 Mozilla Foundation and contributors
  2145. * Licensed under the New BSD license. See LICENSE or:
  2146. * http://opensource.org/licenses/BSD-3-Clause
  2147. */
  2148. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  2149. /**
  2150. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  2151. */
  2152. var encode = function (number) {
  2153. if (0 <= number && number < intToCharMap.length) {
  2154. return intToCharMap[number];
  2155. }
  2156. throw new TypeError("Must be between 0 and 63: " + number);
  2157. };
  2158. /**
  2159. * Decode a single base 64 character code digit to an integer. Returns -1 on
  2160. * failure.
  2161. */
  2162. var decode = function (charCode) {
  2163. var bigA = 65; // 'A'
  2164. var bigZ = 90; // 'Z'
  2165. var littleA = 97; // 'a'
  2166. var littleZ = 122; // 'z'
  2167. var zero = 48; // '0'
  2168. var nine = 57; // '9'
  2169. var plus = 43; // '+'
  2170. var slash = 47; // '/'
  2171. var littleOffset = 26;
  2172. var numberOffset = 52;
  2173. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  2174. if (bigA <= charCode && charCode <= bigZ) {
  2175. return (charCode - bigA);
  2176. }
  2177. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  2178. if (littleA <= charCode && charCode <= littleZ) {
  2179. return (charCode - littleA + littleOffset);
  2180. }
  2181. // 52 - 61: 0123456789
  2182. if (zero <= charCode && charCode <= nine) {
  2183. return (charCode - zero + numberOffset);
  2184. }
  2185. // 62: +
  2186. if (charCode == plus) {
  2187. return 62;
  2188. }
  2189. // 63: /
  2190. if (charCode == slash) {
  2191. return 63;
  2192. }
  2193. // Invalid base64 digit.
  2194. return -1;
  2195. };
  2196. var base64 = {
  2197. encode: encode,
  2198. decode: decode
  2199. };
  2200. /* -*- Mode: js; js-indent-level: 2; -*- */
  2201. /*
  2202. * Copyright 2011 Mozilla Foundation and contributors
  2203. * Licensed under the New BSD license. See LICENSE or:
  2204. * http://opensource.org/licenses/BSD-3-Clause
  2205. *
  2206. * Based on the Base 64 VLQ implementation in Closure Compiler:
  2207. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  2208. *
  2209. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  2210. * Redistribution and use in source and binary forms, with or without
  2211. * modification, are permitted provided that the following conditions are
  2212. * met:
  2213. *
  2214. * * Redistributions of source code must retain the above copyright
  2215. * notice, this list of conditions and the following disclaimer.
  2216. * * Redistributions in binary form must reproduce the above
  2217. * copyright notice, this list of conditions and the following
  2218. * disclaimer in the documentation and/or other materials provided
  2219. * with the distribution.
  2220. * * Neither the name of Google Inc. nor the names of its
  2221. * contributors may be used to endorse or promote products derived
  2222. * from this software without specific prior written permission.
  2223. *
  2224. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2225. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2226. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2227. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2228. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2229. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2230. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2231. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2232. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2233. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2234. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2235. */
  2236. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  2237. // length quantities we use in the source map spec, the first bit is the sign,
  2238. // the next four bits are the actual value, and the 6th bit is the
  2239. // continuation bit. The continuation bit tells us whether there are more
  2240. // digits in this value following this digit.
  2241. //
  2242. // Continuation
  2243. // | Sign
  2244. // | |
  2245. // V V
  2246. // 101011
  2247. var VLQ_BASE_SHIFT = 5;
  2248. // binary: 100000
  2249. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  2250. // binary: 011111
  2251. var VLQ_BASE_MASK = VLQ_BASE - 1;
  2252. // binary: 100000
  2253. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  2254. /**
  2255. * Converts from a two-complement value to a value where the sign bit is
  2256. * placed in the least significant bit. For example, as decimals:
  2257. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  2258. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  2259. */
  2260. function toVLQSigned(aValue) {
  2261. return aValue < 0
  2262. ? ((-aValue) << 1) + 1
  2263. : (aValue << 1) + 0;
  2264. }
  2265. /**
  2266. * Converts to a two-complement value from a value where the sign bit is
  2267. * placed in the least significant bit. For example, as decimals:
  2268. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  2269. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  2270. */
  2271. function fromVLQSigned(aValue) {
  2272. var isNegative = (aValue & 1) === 1;
  2273. var shifted = aValue >> 1;
  2274. return isNegative
  2275. ? -shifted
  2276. : shifted;
  2277. }
  2278. /**
  2279. * Returns the base 64 VLQ encoded value.
  2280. */
  2281. var encode$1 = function base64VLQ_encode(aValue) {
  2282. var encoded = "";
  2283. var digit;
  2284. var vlq = toVLQSigned(aValue);
  2285. do {
  2286. digit = vlq & VLQ_BASE_MASK;
  2287. vlq >>>= VLQ_BASE_SHIFT;
  2288. if (vlq > 0) {
  2289. // There are still more digits in this value, so we must make sure the
  2290. // continuation bit is marked.
  2291. digit |= VLQ_CONTINUATION_BIT;
  2292. }
  2293. encoded += base64.encode(digit);
  2294. } while (vlq > 0);
  2295. return encoded;
  2296. };
  2297. /**
  2298. * Decodes the next base 64 VLQ value from the given string and returns the
  2299. * value and the rest of the string via the out parameter.
  2300. */
  2301. var decode$1 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  2302. var strLen = aStr.length;
  2303. var result = 0;
  2304. var shift = 0;
  2305. var continuation, digit;
  2306. do {
  2307. if (aIndex >= strLen) {
  2308. throw new Error("Expected more digits in base 64 VLQ value.");
  2309. }
  2310. digit = base64.decode(aStr.charCodeAt(aIndex++));
  2311. if (digit === -1) {
  2312. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  2313. }
  2314. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  2315. digit &= VLQ_BASE_MASK;
  2316. result = result + (digit << shift);
  2317. shift += VLQ_BASE_SHIFT;
  2318. } while (continuation);
  2319. aOutParam.value = fromVLQSigned(result);
  2320. aOutParam.rest = aIndex;
  2321. };
  2322. var base64Vlq = {
  2323. encode: encode$1,
  2324. decode: decode$1
  2325. };
  2326. function getDefaultExportFromCjs (x) {
  2327. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2328. }
  2329. function createCommonjsModule(fn) {
  2330. var module = { exports: {} };
  2331. return fn(module, module.exports), module.exports;
  2332. }
  2333. /* -*- Mode: js; js-indent-level: 2; -*- */
  2334. var util = createCommonjsModule(function (module, exports) {
  2335. /*
  2336. * Copyright 2011 Mozilla Foundation and contributors
  2337. * Licensed under the New BSD license. See LICENSE or:
  2338. * http://opensource.org/licenses/BSD-3-Clause
  2339. */
  2340. /**
  2341. * This is a helper function for getting values from parameter/options
  2342. * objects.
  2343. *
  2344. * @param args The object we are extracting values from
  2345. * @param name The name of the property we are getting.
  2346. * @param defaultValue An optional value to return if the property is missing
  2347. * from the object. If this is not specified and the property is missing, an
  2348. * error will be thrown.
  2349. */
  2350. function getArg(aArgs, aName, aDefaultValue) {
  2351. if (aName in aArgs) {
  2352. return aArgs[aName];
  2353. } else if (arguments.length === 3) {
  2354. return aDefaultValue;
  2355. } else {
  2356. throw new Error('"' + aName + '" is a required argument.');
  2357. }
  2358. }
  2359. exports.getArg = getArg;
  2360. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  2361. var dataUrlRegexp = /^data:.+\,.+$/;
  2362. function urlParse(aUrl) {
  2363. var match = aUrl.match(urlRegexp);
  2364. if (!match) {
  2365. return null;
  2366. }
  2367. return {
  2368. scheme: match[1],
  2369. auth: match[2],
  2370. host: match[3],
  2371. port: match[4],
  2372. path: match[5]
  2373. };
  2374. }
  2375. exports.urlParse = urlParse;
  2376. function urlGenerate(aParsedUrl) {
  2377. var url = '';
  2378. if (aParsedUrl.scheme) {
  2379. url += aParsedUrl.scheme + ':';
  2380. }
  2381. url += '//';
  2382. if (aParsedUrl.auth) {
  2383. url += aParsedUrl.auth + '@';
  2384. }
  2385. if (aParsedUrl.host) {
  2386. url += aParsedUrl.host;
  2387. }
  2388. if (aParsedUrl.port) {
  2389. url += ":" + aParsedUrl.port;
  2390. }
  2391. if (aParsedUrl.path) {
  2392. url += aParsedUrl.path;
  2393. }
  2394. return url;
  2395. }
  2396. exports.urlGenerate = urlGenerate;
  2397. /**
  2398. * Normalizes a path, or the path portion of a URL:
  2399. *
  2400. * - Replaces consecutive slashes with one slash.
  2401. * - Removes unnecessary '.' parts.
  2402. * - Removes unnecessary '<dir>/..' parts.
  2403. *
  2404. * Based on code in the Node.js 'path' core module.
  2405. *
  2406. * @param aPath The path or url to normalize.
  2407. */
  2408. function normalize(aPath) {
  2409. var path = aPath;
  2410. var url = urlParse(aPath);
  2411. if (url) {
  2412. if (!url.path) {
  2413. return aPath;
  2414. }
  2415. path = url.path;
  2416. }
  2417. var isAbsolute = exports.isAbsolute(path);
  2418. var parts = path.split(/\/+/);
  2419. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  2420. part = parts[i];
  2421. if (part === '.') {
  2422. parts.splice(i, 1);
  2423. } else if (part === '..') {
  2424. up++;
  2425. } else if (up > 0) {
  2426. if (part === '') {
  2427. // The first part is blank if the path is absolute. Trying to go
  2428. // above the root is a no-op. Therefore we can remove all '..' parts
  2429. // directly after the root.
  2430. parts.splice(i + 1, up);
  2431. up = 0;
  2432. } else {
  2433. parts.splice(i, 2);
  2434. up--;
  2435. }
  2436. }
  2437. }
  2438. path = parts.join('/');
  2439. if (path === '') {
  2440. path = isAbsolute ? '/' : '.';
  2441. }
  2442. if (url) {
  2443. url.path = path;
  2444. return urlGenerate(url);
  2445. }
  2446. return path;
  2447. }
  2448. exports.normalize = normalize;
  2449. /**
  2450. * Joins two paths/URLs.
  2451. *
  2452. * @param aRoot The root path or URL.
  2453. * @param aPath The path or URL to be joined with the root.
  2454. *
  2455. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  2456. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  2457. * first.
  2458. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  2459. * is updated with the result and aRoot is returned. Otherwise the result
  2460. * is returned.
  2461. * - If aPath is absolute, the result is aPath.
  2462. * - Otherwise the two paths are joined with a slash.
  2463. * - Joining for example 'http://' and 'www.example.com' is also supported.
  2464. */
  2465. function join(aRoot, aPath) {
  2466. if (aRoot === "") {
  2467. aRoot = ".";
  2468. }
  2469. if (aPath === "") {
  2470. aPath = ".";
  2471. }
  2472. var aPathUrl = urlParse(aPath);
  2473. var aRootUrl = urlParse(aRoot);
  2474. if (aRootUrl) {
  2475. aRoot = aRootUrl.path || '/';
  2476. }
  2477. // `join(foo, '//www.example.org')`
  2478. if (aPathUrl && !aPathUrl.scheme) {
  2479. if (aRootUrl) {
  2480. aPathUrl.scheme = aRootUrl.scheme;
  2481. }
  2482. return urlGenerate(aPathUrl);
  2483. }
  2484. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  2485. return aPath;
  2486. }
  2487. // `join('http://', 'www.example.com')`
  2488. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  2489. aRootUrl.host = aPath;
  2490. return urlGenerate(aRootUrl);
  2491. }
  2492. var joined = aPath.charAt(0) === '/'
  2493. ? aPath
  2494. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  2495. if (aRootUrl) {
  2496. aRootUrl.path = joined;
  2497. return urlGenerate(aRootUrl);
  2498. }
  2499. return joined;
  2500. }
  2501. exports.join = join;
  2502. exports.isAbsolute = function (aPath) {
  2503. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  2504. };
  2505. /**
  2506. * Make a path relative to a URL or another path.
  2507. *
  2508. * @param aRoot The root path or URL.
  2509. * @param aPath The path or URL to be made relative to aRoot.
  2510. */
  2511. function relative(aRoot, aPath) {
  2512. if (aRoot === "") {
  2513. aRoot = ".";
  2514. }
  2515. aRoot = aRoot.replace(/\/$/, '');
  2516. // It is possible for the path to be above the root. In this case, simply
  2517. // checking whether the root is a prefix of the path won't work. Instead, we
  2518. // need to remove components from the root one by one, until either we find
  2519. // a prefix that fits, or we run out of components to remove.
  2520. var level = 0;
  2521. while (aPath.indexOf(aRoot + '/') !== 0) {
  2522. var index = aRoot.lastIndexOf("/");
  2523. if (index < 0) {
  2524. return aPath;
  2525. }
  2526. // If the only part of the root that is left is the scheme (i.e. http://,
  2527. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  2528. // have exhausted all components, so the path is not relative to the root.
  2529. aRoot = aRoot.slice(0, index);
  2530. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  2531. return aPath;
  2532. }
  2533. ++level;
  2534. }
  2535. // Make sure we add a "../" for each component we removed from the root.
  2536. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  2537. }
  2538. exports.relative = relative;
  2539. var supportsNullProto = (function () {
  2540. var obj = Object.create(null);
  2541. return !('__proto__' in obj);
  2542. }());
  2543. function identity (s) {
  2544. return s;
  2545. }
  2546. /**
  2547. * Because behavior goes wacky when you set `__proto__` on objects, we
  2548. * have to prefix all the strings in our set with an arbitrary character.
  2549. *
  2550. * See https://github.com/mozilla/source-map/pull/31 and
  2551. * https://github.com/mozilla/source-map/issues/30
  2552. *
  2553. * @param String aStr
  2554. */
  2555. function toSetString(aStr) {
  2556. if (isProtoString(aStr)) {
  2557. return '$' + aStr;
  2558. }
  2559. return aStr;
  2560. }
  2561. exports.toSetString = supportsNullProto ? identity : toSetString;
  2562. function fromSetString(aStr) {
  2563. if (isProtoString(aStr)) {
  2564. return aStr.slice(1);
  2565. }
  2566. return aStr;
  2567. }
  2568. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  2569. function isProtoString(s) {
  2570. if (!s) {
  2571. return false;
  2572. }
  2573. var length = s.length;
  2574. if (length < 9 /* "__proto__".length */) {
  2575. return false;
  2576. }
  2577. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  2578. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  2579. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  2580. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  2581. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  2582. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  2583. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  2584. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  2585. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  2586. return false;
  2587. }
  2588. for (var i = length - 10; i >= 0; i--) {
  2589. if (s.charCodeAt(i) !== 36 /* '$' */) {
  2590. return false;
  2591. }
  2592. }
  2593. return true;
  2594. }
  2595. /**
  2596. * Comparator between two mappings where the original positions are compared.
  2597. *
  2598. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  2599. * mappings with the same original source/line/column, but different generated
  2600. * line and column the same. Useful when searching for a mapping with a
  2601. * stubbed out mapping.
  2602. */
  2603. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  2604. var cmp = strcmp(mappingA.source, mappingB.source);
  2605. if (cmp !== 0) {
  2606. return cmp;
  2607. }
  2608. cmp = mappingA.originalLine - mappingB.originalLine;
  2609. if (cmp !== 0) {
  2610. return cmp;
  2611. }
  2612. cmp = mappingA.originalColumn - mappingB.originalColumn;
  2613. if (cmp !== 0 || onlyCompareOriginal) {
  2614. return cmp;
  2615. }
  2616. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  2617. if (cmp !== 0) {
  2618. return cmp;
  2619. }
  2620. cmp = mappingA.generatedLine - mappingB.generatedLine;
  2621. if (cmp !== 0) {
  2622. return cmp;
  2623. }
  2624. return strcmp(mappingA.name, mappingB.name);
  2625. }
  2626. exports.compareByOriginalPositions = compareByOriginalPositions;
  2627. /**
  2628. * Comparator between two mappings with deflated source and name indices where
  2629. * the generated positions are compared.
  2630. *
  2631. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  2632. * mappings with the same generated line and column, but different
  2633. * source/name/original line and column the same. Useful when searching for a
  2634. * mapping with a stubbed out mapping.
  2635. */
  2636. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  2637. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  2638. if (cmp !== 0) {
  2639. return cmp;
  2640. }
  2641. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  2642. if (cmp !== 0 || onlyCompareGenerated) {
  2643. return cmp;
  2644. }
  2645. cmp = strcmp(mappingA.source, mappingB.source);
  2646. if (cmp !== 0) {
  2647. return cmp;
  2648. }
  2649. cmp = mappingA.originalLine - mappingB.originalLine;
  2650. if (cmp !== 0) {
  2651. return cmp;
  2652. }
  2653. cmp = mappingA.originalColumn - mappingB.originalColumn;
  2654. if (cmp !== 0) {
  2655. return cmp;
  2656. }
  2657. return strcmp(mappingA.name, mappingB.name);
  2658. }
  2659. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  2660. function strcmp(aStr1, aStr2) {
  2661. if (aStr1 === aStr2) {
  2662. return 0;
  2663. }
  2664. if (aStr1 === null) {
  2665. return 1; // aStr2 !== null
  2666. }
  2667. if (aStr2 === null) {
  2668. return -1; // aStr1 !== null
  2669. }
  2670. if (aStr1 > aStr2) {
  2671. return 1;
  2672. }
  2673. return -1;
  2674. }
  2675. /**
  2676. * Comparator between two mappings with inflated source and name strings where
  2677. * the generated positions are compared.
  2678. */
  2679. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  2680. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  2681. if (cmp !== 0) {
  2682. return cmp;
  2683. }
  2684. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  2685. if (cmp !== 0) {
  2686. return cmp;
  2687. }
  2688. cmp = strcmp(mappingA.source, mappingB.source);
  2689. if (cmp !== 0) {
  2690. return cmp;
  2691. }
  2692. cmp = mappingA.originalLine - mappingB.originalLine;
  2693. if (cmp !== 0) {
  2694. return cmp;
  2695. }
  2696. cmp = mappingA.originalColumn - mappingB.originalColumn;
  2697. if (cmp !== 0) {
  2698. return cmp;
  2699. }
  2700. return strcmp(mappingA.name, mappingB.name);
  2701. }
  2702. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  2703. /**
  2704. * Strip any JSON XSSI avoidance prefix from the string (as documented
  2705. * in the source maps specification), and then parse the string as
  2706. * JSON.
  2707. */
  2708. function parseSourceMapInput(str) {
  2709. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  2710. }
  2711. exports.parseSourceMapInput = parseSourceMapInput;
  2712. /**
  2713. * Compute the URL of a source given the the source root, the source's
  2714. * URL, and the source map's URL.
  2715. */
  2716. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  2717. sourceURL = sourceURL || '';
  2718. if (sourceRoot) {
  2719. // This follows what Chrome does.
  2720. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  2721. sourceRoot += '/';
  2722. }
  2723. // The spec says:
  2724. // Line 4: An optional source root, useful for relocating source
  2725. // files on a server or removing repeated values in the
  2726. // “sources” entry. This value is prepended to the individual
  2727. // entries in the “source” field.
  2728. sourceURL = sourceRoot + sourceURL;
  2729. }
  2730. // Historically, SourceMapConsumer did not take the sourceMapURL as
  2731. // a parameter. This mode is still somewhat supported, which is why
  2732. // this code block is conditional. However, it's preferable to pass
  2733. // the source map URL to SourceMapConsumer, so that this function
  2734. // can implement the source URL resolution algorithm as outlined in
  2735. // the spec. This block is basically the equivalent of:
  2736. // new URL(sourceURL, sourceMapURL).toString()
  2737. // ... except it avoids using URL, which wasn't available in the
  2738. // older releases of node still supported by this library.
  2739. //
  2740. // The spec says:
  2741. // If the sources are not absolute URLs after prepending of the
  2742. // “sourceRoot”, the sources are resolved relative to the
  2743. // SourceMap (like resolving script src in a html document).
  2744. if (sourceMapURL) {
  2745. var parsed = urlParse(sourceMapURL);
  2746. if (!parsed) {
  2747. throw new Error("sourceMapURL could not be parsed");
  2748. }
  2749. if (parsed.path) {
  2750. // Strip the last path component, but keep the "/".
  2751. var index = parsed.path.lastIndexOf('/');
  2752. if (index >= 0) {
  2753. parsed.path = parsed.path.substring(0, index + 1);
  2754. }
  2755. }
  2756. sourceURL = join(urlGenerate(parsed), sourceURL);
  2757. }
  2758. return normalize(sourceURL);
  2759. }
  2760. exports.computeSourceURL = computeSourceURL;
  2761. });
  2762. /* -*- Mode: js; js-indent-level: 2; -*- */
  2763. /*
  2764. * Copyright 2011 Mozilla Foundation and contributors
  2765. * Licensed under the New BSD license. See LICENSE or:
  2766. * http://opensource.org/licenses/BSD-3-Clause
  2767. */
  2768. var has = Object.prototype.hasOwnProperty;
  2769. var hasNativeMap = typeof Map !== "undefined";
  2770. /**
  2771. * A data structure which is a combination of an array and a set. Adding a new
  2772. * member is O(1), testing for membership is O(1), and finding the index of an
  2773. * element is O(1). Removing elements from the set is not supported. Only
  2774. * strings are supported for membership.
  2775. */
  2776. function ArraySet() {
  2777. this._array = [];
  2778. this._set = hasNativeMap ? new Map() : Object.create(null);
  2779. }
  2780. /**
  2781. * Static method for creating ArraySet instances from an existing array.
  2782. */
  2783. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  2784. var set = new ArraySet();
  2785. for (var i = 0, len = aArray.length; i < len; i++) {
  2786. set.add(aArray[i], aAllowDuplicates);
  2787. }
  2788. return set;
  2789. };
  2790. /**
  2791. * Return how many unique items are in this ArraySet. If duplicates have been
  2792. * added, than those do not count towards the size.
  2793. *
  2794. * @returns Number
  2795. */
  2796. ArraySet.prototype.size = function ArraySet_size() {
  2797. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  2798. };
  2799. /**
  2800. * Add the given string to this set.
  2801. *
  2802. * @param String aStr
  2803. */
  2804. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  2805. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  2806. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  2807. var idx = this._array.length;
  2808. if (!isDuplicate || aAllowDuplicates) {
  2809. this._array.push(aStr);
  2810. }
  2811. if (!isDuplicate) {
  2812. if (hasNativeMap) {
  2813. this._set.set(aStr, idx);
  2814. } else {
  2815. this._set[sStr] = idx;
  2816. }
  2817. }
  2818. };
  2819. /**
  2820. * Is the given string a member of this set?
  2821. *
  2822. * @param String aStr
  2823. */
  2824. ArraySet.prototype.has = function ArraySet_has(aStr) {
  2825. if (hasNativeMap) {
  2826. return this._set.has(aStr);
  2827. } else {
  2828. var sStr = util.toSetString(aStr);
  2829. return has.call(this._set, sStr);
  2830. }
  2831. };
  2832. /**
  2833. * What is the index of the given string in the array?
  2834. *
  2835. * @param String aStr
  2836. */
  2837. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  2838. if (hasNativeMap) {
  2839. var idx = this._set.get(aStr);
  2840. if (idx >= 0) {
  2841. return idx;
  2842. }
  2843. } else {
  2844. var sStr = util.toSetString(aStr);
  2845. if (has.call(this._set, sStr)) {
  2846. return this._set[sStr];
  2847. }
  2848. }
  2849. throw new Error('"' + aStr + '" is not in the set.');
  2850. };
  2851. /**
  2852. * What is the element at the given index?
  2853. *
  2854. * @param Number aIdx
  2855. */
  2856. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  2857. if (aIdx >= 0 && aIdx < this._array.length) {
  2858. return this._array[aIdx];
  2859. }
  2860. throw new Error('No element indexed by ' + aIdx);
  2861. };
  2862. /**
  2863. * Returns the array representation of this set (which has the proper indices
  2864. * indicated by indexOf). Note that this is a copy of the internal array used
  2865. * for storing the members so that no one can mess with internal state.
  2866. */
  2867. ArraySet.prototype.toArray = function ArraySet_toArray() {
  2868. return this._array.slice();
  2869. };
  2870. var ArraySet_1 = ArraySet;
  2871. var arraySet = {
  2872. ArraySet: ArraySet_1
  2873. };
  2874. /* -*- Mode: js; js-indent-level: 2; -*- */
  2875. /*
  2876. * Copyright 2014 Mozilla Foundation and contributors
  2877. * Licensed under the New BSD license. See LICENSE or:
  2878. * http://opensource.org/licenses/BSD-3-Clause
  2879. */
  2880. /**
  2881. * Determine whether mappingB is after mappingA with respect to generated
  2882. * position.
  2883. */
  2884. function generatedPositionAfter(mappingA, mappingB) {
  2885. // Optimized for most common case
  2886. var lineA = mappingA.generatedLine;
  2887. var lineB = mappingB.generatedLine;
  2888. var columnA = mappingA.generatedColumn;
  2889. var columnB = mappingB.generatedColumn;
  2890. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  2891. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  2892. }
  2893. /**
  2894. * A data structure to provide a sorted view of accumulated mappings in a
  2895. * performance conscious manner. It trades a neglibable overhead in general
  2896. * case for a large speedup in case of mappings being added in order.
  2897. */
  2898. function MappingList() {
  2899. this._array = [];
  2900. this._sorted = true;
  2901. // Serves as infimum
  2902. this._last = {generatedLine: -1, generatedColumn: 0};
  2903. }
  2904. /**
  2905. * Iterate through internal items. This method takes the same arguments that
  2906. * `Array.prototype.forEach` takes.
  2907. *
  2908. * NOTE: The order of the mappings is NOT guaranteed.
  2909. */
  2910. MappingList.prototype.unsortedForEach =
  2911. function MappingList_forEach(aCallback, aThisArg) {
  2912. this._array.forEach(aCallback, aThisArg);
  2913. };
  2914. /**
  2915. * Add the given source mapping.
  2916. *
  2917. * @param Object aMapping
  2918. */
  2919. MappingList.prototype.add = function MappingList_add(aMapping) {
  2920. if (generatedPositionAfter(this._last, aMapping)) {
  2921. this._last = aMapping;
  2922. this._array.push(aMapping);
  2923. } else {
  2924. this._sorted = false;
  2925. this._array.push(aMapping);
  2926. }
  2927. };
  2928. /**
  2929. * Returns the flat, sorted array of mappings. The mappings are sorted by
  2930. * generated position.
  2931. *
  2932. * WARNING: This method returns internal data without copying, for
  2933. * performance. The return value must NOT be mutated, and should be treated as
  2934. * an immutable borrow. If you want to take ownership, you must make your own
  2935. * copy.
  2936. */
  2937. MappingList.prototype.toArray = function MappingList_toArray() {
  2938. if (!this._sorted) {
  2939. this._array.sort(util.compareByGeneratedPositionsInflated);
  2940. this._sorted = true;
  2941. }
  2942. return this._array;
  2943. };
  2944. var MappingList_1 = MappingList;
  2945. var mappingList = {
  2946. MappingList: MappingList_1
  2947. };
  2948. /* -*- Mode: js; js-indent-level: 2; -*- */
  2949. /*
  2950. * Copyright 2011 Mozilla Foundation and contributors
  2951. * Licensed under the New BSD license. See LICENSE or:
  2952. * http://opensource.org/licenses/BSD-3-Clause
  2953. */
  2954. var ArraySet$1 = arraySet.ArraySet;
  2955. var MappingList$1 = mappingList.MappingList;
  2956. /**
  2957. * An instance of the SourceMapGenerator represents a source map which is
  2958. * being built incrementally. You may pass an object with the following
  2959. * properties:
  2960. *
  2961. * - file: The filename of the generated source.
  2962. * - sourceRoot: A root for all relative URLs in this source map.
  2963. */
  2964. function SourceMapGenerator(aArgs) {
  2965. if (!aArgs) {
  2966. aArgs = {};
  2967. }
  2968. this._file = util.getArg(aArgs, 'file', null);
  2969. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  2970. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  2971. this._sources = new ArraySet$1();
  2972. this._names = new ArraySet$1();
  2973. this._mappings = new MappingList$1();
  2974. this._sourcesContents = null;
  2975. }
  2976. SourceMapGenerator.prototype._version = 3;
  2977. /**
  2978. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  2979. *
  2980. * @param aSourceMapConsumer The SourceMap.
  2981. */
  2982. SourceMapGenerator.fromSourceMap =
  2983. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  2984. var sourceRoot = aSourceMapConsumer.sourceRoot;
  2985. var generator = new SourceMapGenerator({
  2986. file: aSourceMapConsumer.file,
  2987. sourceRoot: sourceRoot
  2988. });
  2989. aSourceMapConsumer.eachMapping(function (mapping) {
  2990. var newMapping = {
  2991. generated: {
  2992. line: mapping.generatedLine,
  2993. column: mapping.generatedColumn
  2994. }
  2995. };
  2996. if (mapping.source != null) {
  2997. newMapping.source = mapping.source;
  2998. if (sourceRoot != null) {
  2999. newMapping.source = util.relative(sourceRoot, newMapping.source);
  3000. }
  3001. newMapping.original = {
  3002. line: mapping.originalLine,
  3003. column: mapping.originalColumn
  3004. };
  3005. if (mapping.name != null) {
  3006. newMapping.name = mapping.name;
  3007. }
  3008. }
  3009. generator.addMapping(newMapping);
  3010. });
  3011. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  3012. var sourceRelative = sourceFile;
  3013. if (sourceRoot !== null) {
  3014. sourceRelative = util.relative(sourceRoot, sourceFile);
  3015. }
  3016. if (!generator._sources.has(sourceRelative)) {
  3017. generator._sources.add(sourceRelative);
  3018. }
  3019. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  3020. if (content != null) {
  3021. generator.setSourceContent(sourceFile, content);
  3022. }
  3023. });
  3024. return generator;
  3025. };
  3026. /**
  3027. * Add a single mapping from original source line and column to the generated
  3028. * source's line and column for this source map being created. The mapping
  3029. * object should have the following properties:
  3030. *
  3031. * - generated: An object with the generated line and column positions.
  3032. * - original: An object with the original line and column positions.
  3033. * - source: The original source file (relative to the sourceRoot).
  3034. * - name: An optional original token name for this mapping.
  3035. */
  3036. SourceMapGenerator.prototype.addMapping =
  3037. function SourceMapGenerator_addMapping(aArgs) {
  3038. var generated = util.getArg(aArgs, 'generated');
  3039. var original = util.getArg(aArgs, 'original', null);
  3040. var source = util.getArg(aArgs, 'source', null);
  3041. var name = util.getArg(aArgs, 'name', null);
  3042. if (!this._skipValidation) {
  3043. this._validateMapping(generated, original, source, name);
  3044. }
  3045. if (source != null) {
  3046. source = String(source);
  3047. if (!this._sources.has(source)) {
  3048. this._sources.add(source);
  3049. }
  3050. }
  3051. if (name != null) {
  3052. name = String(name);
  3053. if (!this._names.has(name)) {
  3054. this._names.add(name);
  3055. }
  3056. }
  3057. this._mappings.add({
  3058. generatedLine: generated.line,
  3059. generatedColumn: generated.column,
  3060. originalLine: original != null && original.line,
  3061. originalColumn: original != null && original.column,
  3062. source: source,
  3063. name: name
  3064. });
  3065. };
  3066. /**
  3067. * Set the source content for a source file.
  3068. */
  3069. SourceMapGenerator.prototype.setSourceContent =
  3070. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  3071. var source = aSourceFile;
  3072. if (this._sourceRoot != null) {
  3073. source = util.relative(this._sourceRoot, source);
  3074. }
  3075. if (aSourceContent != null) {
  3076. // Add the source content to the _sourcesContents map.
  3077. // Create a new _sourcesContents map if the property is null.
  3078. if (!this._sourcesContents) {
  3079. this._sourcesContents = Object.create(null);
  3080. }
  3081. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  3082. } else if (this._sourcesContents) {
  3083. // Remove the source file from the _sourcesContents map.
  3084. // If the _sourcesContents map is empty, set the property to null.
  3085. delete this._sourcesContents[util.toSetString(source)];
  3086. if (Object.keys(this._sourcesContents).length === 0) {
  3087. this._sourcesContents = null;
  3088. }
  3089. }
  3090. };
  3091. /**
  3092. * Applies the mappings of a sub-source-map for a specific source file to the
  3093. * source map being generated. Each mapping to the supplied source file is
  3094. * rewritten using the supplied source map. Note: The resolution for the
  3095. * resulting mappings is the minimium of this map and the supplied map.
  3096. *
  3097. * @param aSourceMapConsumer The source map to be applied.
  3098. * @param aSourceFile Optional. The filename of the source file.
  3099. * If omitted, SourceMapConsumer's file property will be used.
  3100. * @param aSourceMapPath Optional. The dirname of the path to the source map
  3101. * to be applied. If relative, it is relative to the SourceMapConsumer.
  3102. * This parameter is needed when the two source maps aren't in the same
  3103. * directory, and the source map to be applied contains relative source
  3104. * paths. If so, those relative source paths need to be rewritten
  3105. * relative to the SourceMapGenerator.
  3106. */
  3107. SourceMapGenerator.prototype.applySourceMap =
  3108. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  3109. var sourceFile = aSourceFile;
  3110. // If aSourceFile is omitted, we will use the file property of the SourceMap
  3111. if (aSourceFile == null) {
  3112. if (aSourceMapConsumer.file == null) {
  3113. throw new Error(
  3114. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  3115. 'or the source map\'s "file" property. Both were omitted.'
  3116. );
  3117. }
  3118. sourceFile = aSourceMapConsumer.file;
  3119. }
  3120. var sourceRoot = this._sourceRoot;
  3121. // Make "sourceFile" relative if an absolute Url is passed.
  3122. if (sourceRoot != null) {
  3123. sourceFile = util.relative(sourceRoot, sourceFile);
  3124. }
  3125. // Applying the SourceMap can add and remove items from the sources and
  3126. // the names array.
  3127. var newSources = new ArraySet$1();
  3128. var newNames = new ArraySet$1();
  3129. // Find mappings for the "sourceFile"
  3130. this._mappings.unsortedForEach(function (mapping) {
  3131. if (mapping.source === sourceFile && mapping.originalLine != null) {
  3132. // Check if it can be mapped by the source map, then update the mapping.
  3133. var original = aSourceMapConsumer.originalPositionFor({
  3134. line: mapping.originalLine,
  3135. column: mapping.originalColumn
  3136. });
  3137. if (original.source != null) {
  3138. // Copy mapping
  3139. mapping.source = original.source;
  3140. if (aSourceMapPath != null) {
  3141. mapping.source = util.join(aSourceMapPath, mapping.source);
  3142. }
  3143. if (sourceRoot != null) {
  3144. mapping.source = util.relative(sourceRoot, mapping.source);
  3145. }
  3146. mapping.originalLine = original.line;
  3147. mapping.originalColumn = original.column;
  3148. if (original.name != null) {
  3149. mapping.name = original.name;
  3150. }
  3151. }
  3152. }
  3153. var source = mapping.source;
  3154. if (source != null && !newSources.has(source)) {
  3155. newSources.add(source);
  3156. }
  3157. var name = mapping.name;
  3158. if (name != null && !newNames.has(name)) {
  3159. newNames.add(name);
  3160. }
  3161. }, this);
  3162. this._sources = newSources;
  3163. this._names = newNames;
  3164. // Copy sourcesContents of applied map.
  3165. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  3166. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  3167. if (content != null) {
  3168. if (aSourceMapPath != null) {
  3169. sourceFile = util.join(aSourceMapPath, sourceFile);
  3170. }
  3171. if (sourceRoot != null) {
  3172. sourceFile = util.relative(sourceRoot, sourceFile);
  3173. }
  3174. this.setSourceContent(sourceFile, content);
  3175. }
  3176. }, this);
  3177. };
  3178. /**
  3179. * A mapping can have one of the three levels of data:
  3180. *
  3181. * 1. Just the generated position.
  3182. * 2. The Generated position, original position, and original source.
  3183. * 3. Generated and original position, original source, as well as a name
  3184. * token.
  3185. *
  3186. * To maintain consistency, we validate that any new mapping being added falls
  3187. * in to one of these categories.
  3188. */
  3189. SourceMapGenerator.prototype._validateMapping =
  3190. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  3191. aName) {
  3192. // When aOriginal is truthy but has empty values for .line and .column,
  3193. // it is most likely a programmer error. In this case we throw a very
  3194. // specific error message to try to guide them the right way.
  3195. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  3196. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  3197. throw new Error(
  3198. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  3199. 'the original mapping entirely and only map the generated position. If so, pass ' +
  3200. 'null for the original mapping instead of an object with empty or null values.'
  3201. );
  3202. }
  3203. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  3204. && aGenerated.line > 0 && aGenerated.column >= 0
  3205. && !aOriginal && !aSource && !aName) {
  3206. // Case 1.
  3207. return;
  3208. }
  3209. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  3210. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  3211. && aGenerated.line > 0 && aGenerated.column >= 0
  3212. && aOriginal.line > 0 && aOriginal.column >= 0
  3213. && aSource) {
  3214. // Cases 2 and 3.
  3215. return;
  3216. }
  3217. else {
  3218. throw new Error('Invalid mapping: ' + JSON.stringify({
  3219. generated: aGenerated,
  3220. source: aSource,
  3221. original: aOriginal,
  3222. name: aName
  3223. }));
  3224. }
  3225. };
  3226. /**
  3227. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  3228. * specified by the source map format.
  3229. */
  3230. SourceMapGenerator.prototype._serializeMappings =
  3231. function SourceMapGenerator_serializeMappings() {
  3232. var previousGeneratedColumn = 0;
  3233. var previousGeneratedLine = 1;
  3234. var previousOriginalColumn = 0;
  3235. var previousOriginalLine = 0;
  3236. var previousName = 0;
  3237. var previousSource = 0;
  3238. var result = '';
  3239. var next;
  3240. var mapping;
  3241. var nameIdx;
  3242. var sourceIdx;
  3243. var mappings = this._mappings.toArray();
  3244. for (var i = 0, len = mappings.length; i < len; i++) {
  3245. mapping = mappings[i];
  3246. next = '';
  3247. if (mapping.generatedLine !== previousGeneratedLine) {
  3248. previousGeneratedColumn = 0;
  3249. while (mapping.generatedLine !== previousGeneratedLine) {
  3250. next += ';';
  3251. previousGeneratedLine++;
  3252. }
  3253. }
  3254. else {
  3255. if (i > 0) {
  3256. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  3257. continue;
  3258. }
  3259. next += ',';
  3260. }
  3261. }
  3262. next += base64Vlq.encode(mapping.generatedColumn
  3263. - previousGeneratedColumn);
  3264. previousGeneratedColumn = mapping.generatedColumn;
  3265. if (mapping.source != null) {
  3266. sourceIdx = this._sources.indexOf(mapping.source);
  3267. next += base64Vlq.encode(sourceIdx - previousSource);
  3268. previousSource = sourceIdx;
  3269. // lines are stored 0-based in SourceMap spec version 3
  3270. next += base64Vlq.encode(mapping.originalLine - 1
  3271. - previousOriginalLine);
  3272. previousOriginalLine = mapping.originalLine - 1;
  3273. next += base64Vlq.encode(mapping.originalColumn
  3274. - previousOriginalColumn);
  3275. previousOriginalColumn = mapping.originalColumn;
  3276. if (mapping.name != null) {
  3277. nameIdx = this._names.indexOf(mapping.name);
  3278. next += base64Vlq.encode(nameIdx - previousName);
  3279. previousName = nameIdx;
  3280. }
  3281. }
  3282. result += next;
  3283. }
  3284. return result;
  3285. };
  3286. SourceMapGenerator.prototype._generateSourcesContent =
  3287. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  3288. return aSources.map(function (source) {
  3289. if (!this._sourcesContents) {
  3290. return null;
  3291. }
  3292. if (aSourceRoot != null) {
  3293. source = util.relative(aSourceRoot, source);
  3294. }
  3295. var key = util.toSetString(source);
  3296. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  3297. ? this._sourcesContents[key]
  3298. : null;
  3299. }, this);
  3300. };
  3301. /**
  3302. * Externalize the source map.
  3303. */
  3304. SourceMapGenerator.prototype.toJSON =
  3305. function SourceMapGenerator_toJSON() {
  3306. var map = {
  3307. version: this._version,
  3308. sources: this._sources.toArray(),
  3309. names: this._names.toArray(),
  3310. mappings: this._serializeMappings()
  3311. };
  3312. if (this._file != null) {
  3313. map.file = this._file;
  3314. }
  3315. if (this._sourceRoot != null) {
  3316. map.sourceRoot = this._sourceRoot;
  3317. }
  3318. if (this._sourcesContents) {
  3319. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  3320. }
  3321. return map;
  3322. };
  3323. /**
  3324. * Render the source map being generated to a string.
  3325. */
  3326. SourceMapGenerator.prototype.toString =
  3327. function SourceMapGenerator_toString() {
  3328. return JSON.stringify(this.toJSON());
  3329. };
  3330. var SourceMapGenerator_1 = SourceMapGenerator;
  3331. var sourceMapGenerator = {
  3332. SourceMapGenerator: SourceMapGenerator_1
  3333. };
  3334. /* -*- Mode: js; js-indent-level: 2; -*- */
  3335. var binarySearch = createCommonjsModule(function (module, exports) {
  3336. /*
  3337. * Copyright 2011 Mozilla Foundation and contributors
  3338. * Licensed under the New BSD license. See LICENSE or:
  3339. * http://opensource.org/licenses/BSD-3-Clause
  3340. */
  3341. exports.GREATEST_LOWER_BOUND = 1;
  3342. exports.LEAST_UPPER_BOUND = 2;
  3343. /**
  3344. * Recursive implementation of binary search.
  3345. *
  3346. * @param aLow Indices here and lower do not contain the needle.
  3347. * @param aHigh Indices here and higher do not contain the needle.
  3348. * @param aNeedle The element being searched for.
  3349. * @param aHaystack The non-empty array being searched.
  3350. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  3351. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  3352. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  3353. * closest element that is smaller than or greater than the one we are
  3354. * searching for, respectively, if the exact element cannot be found.
  3355. */
  3356. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  3357. // This function terminates when one of the following is true:
  3358. //
  3359. // 1. We find the exact element we are looking for.
  3360. //
  3361. // 2. We did not find the exact element, but we can return the index of
  3362. // the next-closest element.
  3363. //
  3364. // 3. We did not find the exact element, and there is no next-closest
  3365. // element than the one we are searching for, so we return -1.
  3366. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  3367. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  3368. if (cmp === 0) {
  3369. // Found the element we are looking for.
  3370. return mid;
  3371. }
  3372. else if (cmp > 0) {
  3373. // Our needle is greater than aHaystack[mid].
  3374. if (aHigh - mid > 1) {
  3375. // The element is in the upper half.
  3376. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  3377. }
  3378. // The exact needle element was not found in this haystack. Determine if
  3379. // we are in termination case (3) or (2) and return the appropriate thing.
  3380. if (aBias == exports.LEAST_UPPER_BOUND) {
  3381. return aHigh < aHaystack.length ? aHigh : -1;
  3382. } else {
  3383. return mid;
  3384. }
  3385. }
  3386. else {
  3387. // Our needle is less than aHaystack[mid].
  3388. if (mid - aLow > 1) {
  3389. // The element is in the lower half.
  3390. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  3391. }
  3392. // we are in termination case (3) or (2) and return the appropriate thing.
  3393. if (aBias == exports.LEAST_UPPER_BOUND) {
  3394. return mid;
  3395. } else {
  3396. return aLow < 0 ? -1 : aLow;
  3397. }
  3398. }
  3399. }
  3400. /**
  3401. * This is an implementation of binary search which will always try and return
  3402. * the index of the closest element if there is no exact hit. This is because
  3403. * mappings between original and generated line/col pairs are single points,
  3404. * and there is an implicit region between each of them, so a miss just means
  3405. * that you aren't on the very start of a region.
  3406. *
  3407. * @param aNeedle The element you are looking for.
  3408. * @param aHaystack The array that is being searched.
  3409. * @param aCompare A function which takes the needle and an element in the
  3410. * array and returns -1, 0, or 1 depending on whether the needle is less
  3411. * than, equal to, or greater than the element, respectively.
  3412. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  3413. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  3414. * closest element that is smaller than or greater than the one we are
  3415. * searching for, respectively, if the exact element cannot be found.
  3416. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  3417. */
  3418. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  3419. if (aHaystack.length === 0) {
  3420. return -1;
  3421. }
  3422. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  3423. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  3424. if (index < 0) {
  3425. return -1;
  3426. }
  3427. // We have found either the exact element, or the next-closest element than
  3428. // the one we are searching for. However, there may be more than one such
  3429. // element. Make sure we always return the smallest of these.
  3430. while (index - 1 >= 0) {
  3431. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  3432. break;
  3433. }
  3434. --index;
  3435. }
  3436. return index;
  3437. };
  3438. });
  3439. /* -*- Mode: js; js-indent-level: 2; -*- */
  3440. /*
  3441. * Copyright 2011 Mozilla Foundation and contributors
  3442. * Licensed under the New BSD license. See LICENSE or:
  3443. * http://opensource.org/licenses/BSD-3-Clause
  3444. */
  3445. // It turns out that some (most?) JavaScript engines don't self-host
  3446. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  3447. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  3448. // custom comparator function, calling back and forth between the VM's C++ and
  3449. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  3450. // worse generated code for the comparator function than would be optimal. In
  3451. // fact, when sorting with a comparator, these costs outweigh the benefits of
  3452. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  3453. // a ~3500ms mean speed-up in `bench/bench.html`.
  3454. /**
  3455. * Swap the elements indexed by `x` and `y` in the array `ary`.
  3456. *
  3457. * @param {Array} ary
  3458. * The array.
  3459. * @param {Number} x
  3460. * The index of the first item.
  3461. * @param {Number} y
  3462. * The index of the second item.
  3463. */
  3464. function swap(ary, x, y) {
  3465. var temp = ary[x];
  3466. ary[x] = ary[y];
  3467. ary[y] = temp;
  3468. }
  3469. /**
  3470. * Returns a random integer within the range `low .. high` inclusive.
  3471. *
  3472. * @param {Number} low
  3473. * The lower bound on the range.
  3474. * @param {Number} high
  3475. * The upper bound on the range.
  3476. */
  3477. function randomIntInRange(low, high) {
  3478. return Math.round(low + (Math.random() * (high - low)));
  3479. }
  3480. /**
  3481. * The Quick Sort algorithm.
  3482. *
  3483. * @param {Array} ary
  3484. * An array to sort.
  3485. * @param {function} comparator
  3486. * Function to use to compare two items.
  3487. * @param {Number} p
  3488. * Start index of the array
  3489. * @param {Number} r
  3490. * End index of the array
  3491. */
  3492. function doQuickSort(ary, comparator, p, r) {
  3493. // If our lower bound is less than our upper bound, we (1) partition the
  3494. // array into two pieces and (2) recurse on each half. If it is not, this is
  3495. // the empty array and our base case.
  3496. if (p < r) {
  3497. // (1) Partitioning.
  3498. //
  3499. // The partitioning chooses a pivot between `p` and `r` and moves all
  3500. // elements that are less than or equal to the pivot to the before it, and
  3501. // all the elements that are greater than it after it. The effect is that
  3502. // once partition is done, the pivot is in the exact place it will be when
  3503. // the array is put in sorted order, and it will not need to be moved
  3504. // again. This runs in O(n) time.
  3505. // Always choose a random pivot so that an input array which is reverse
  3506. // sorted does not cause O(n^2) running time.
  3507. var pivotIndex = randomIntInRange(p, r);
  3508. var i = p - 1;
  3509. swap(ary, pivotIndex, r);
  3510. var pivot = ary[r];
  3511. // Immediately after `j` is incremented in this loop, the following hold
  3512. // true:
  3513. //
  3514. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  3515. //
  3516. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  3517. for (var j = p; j < r; j++) {
  3518. if (comparator(ary[j], pivot) <= 0) {
  3519. i += 1;
  3520. swap(ary, i, j);
  3521. }
  3522. }
  3523. swap(ary, i + 1, j);
  3524. var q = i + 1;
  3525. // (2) Recurse on each half.
  3526. doQuickSort(ary, comparator, p, q - 1);
  3527. doQuickSort(ary, comparator, q + 1, r);
  3528. }
  3529. }
  3530. /**
  3531. * Sort the given array in-place with the given comparator function.
  3532. *
  3533. * @param {Array} ary
  3534. * An array to sort.
  3535. * @param {function} comparator
  3536. * Function to use to compare two items.
  3537. */
  3538. var quickSort_1 = function (ary, comparator) {
  3539. doQuickSort(ary, comparator, 0, ary.length - 1);
  3540. };
  3541. var quickSort = {
  3542. quickSort: quickSort_1
  3543. };
  3544. /* -*- Mode: js; js-indent-level: 2; -*- */
  3545. /*
  3546. * Copyright 2011 Mozilla Foundation and contributors
  3547. * Licensed under the New BSD license. See LICENSE or:
  3548. * http://opensource.org/licenses/BSD-3-Clause
  3549. */
  3550. var ArraySet$2 = arraySet.ArraySet;
  3551. var quickSort$1 = quickSort.quickSort;
  3552. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  3553. var sourceMap = aSourceMap;
  3554. if (typeof aSourceMap === 'string') {
  3555. sourceMap = util.parseSourceMapInput(aSourceMap);
  3556. }
  3557. return sourceMap.sections != null
  3558. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  3559. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  3560. }
  3561. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  3562. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  3563. };
  3564. /**
  3565. * The version of the source mapping spec that we are consuming.
  3566. */
  3567. SourceMapConsumer.prototype._version = 3;
  3568. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  3569. // parsed mapping coordinates from the source map's "mappings" attribute. They
  3570. // are lazily instantiated, accessed via the `_generatedMappings` and
  3571. // `_originalMappings` getters respectively, and we only parse the mappings
  3572. // and create these arrays once queried for a source location. We jump through
  3573. // these hoops because there can be many thousands of mappings, and parsing
  3574. // them is expensive, so we only want to do it if we must.
  3575. //
  3576. // Each object in the arrays is of the form:
  3577. //
  3578. // {
  3579. // generatedLine: The line number in the generated code,
  3580. // generatedColumn: The column number in the generated code,
  3581. // source: The path to the original source file that generated this
  3582. // chunk of code,
  3583. // originalLine: The line number in the original source that
  3584. // corresponds to this chunk of generated code,
  3585. // originalColumn: The column number in the original source that
  3586. // corresponds to this chunk of generated code,
  3587. // name: The name of the original symbol which generated this chunk of
  3588. // code.
  3589. // }
  3590. //
  3591. // All properties except for `generatedLine` and `generatedColumn` can be
  3592. // `null`.
  3593. //
  3594. // `_generatedMappings` is ordered by the generated positions.
  3595. //
  3596. // `_originalMappings` is ordered by the original positions.
  3597. SourceMapConsumer.prototype.__generatedMappings = null;
  3598. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  3599. configurable: true,
  3600. enumerable: true,
  3601. get: function () {
  3602. if (!this.__generatedMappings) {
  3603. this._parseMappings(this._mappings, this.sourceRoot);
  3604. }
  3605. return this.__generatedMappings;
  3606. }
  3607. });
  3608. SourceMapConsumer.prototype.__originalMappings = null;
  3609. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  3610. configurable: true,
  3611. enumerable: true,
  3612. get: function () {
  3613. if (!this.__originalMappings) {
  3614. this._parseMappings(this._mappings, this.sourceRoot);
  3615. }
  3616. return this.__originalMappings;
  3617. }
  3618. });
  3619. SourceMapConsumer.prototype._charIsMappingSeparator =
  3620. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  3621. var c = aStr.charAt(index);
  3622. return c === ";" || c === ",";
  3623. };
  3624. /**
  3625. * Parse the mappings in a string in to a data structure which we can easily
  3626. * query (the ordered arrays in the `this.__generatedMappings` and
  3627. * `this.__originalMappings` properties).
  3628. */
  3629. SourceMapConsumer.prototype._parseMappings =
  3630. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  3631. throw new Error("Subclasses must implement _parseMappings");
  3632. };
  3633. SourceMapConsumer.GENERATED_ORDER = 1;
  3634. SourceMapConsumer.ORIGINAL_ORDER = 2;
  3635. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  3636. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  3637. /**
  3638. * Iterate over each mapping between an original source/line/column and a
  3639. * generated line/column in this source map.
  3640. *
  3641. * @param Function aCallback
  3642. * The function that is called with each mapping.
  3643. * @param Object aContext
  3644. * Optional. If specified, this object will be the value of `this` every
  3645. * time that `aCallback` is called.
  3646. * @param aOrder
  3647. * Either `SourceMapConsumer.GENERATED_ORDER` or
  3648. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  3649. * iterate over the mappings sorted by the generated file's line/column
  3650. * order or the original's source/line/column order, respectively. Defaults to
  3651. * `SourceMapConsumer.GENERATED_ORDER`.
  3652. */
  3653. SourceMapConsumer.prototype.eachMapping =
  3654. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  3655. var context = aContext || null;
  3656. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  3657. var mappings;
  3658. switch (order) {
  3659. case SourceMapConsumer.GENERATED_ORDER:
  3660. mappings = this._generatedMappings;
  3661. break;
  3662. case SourceMapConsumer.ORIGINAL_ORDER:
  3663. mappings = this._originalMappings;
  3664. break;
  3665. default:
  3666. throw new Error("Unknown order of iteration.");
  3667. }
  3668. var sourceRoot = this.sourceRoot;
  3669. mappings.map(function (mapping) {
  3670. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  3671. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  3672. return {
  3673. source: source,
  3674. generatedLine: mapping.generatedLine,
  3675. generatedColumn: mapping.generatedColumn,
  3676. originalLine: mapping.originalLine,
  3677. originalColumn: mapping.originalColumn,
  3678. name: mapping.name === null ? null : this._names.at(mapping.name)
  3679. };
  3680. }, this).forEach(aCallback, context);
  3681. };
  3682. /**
  3683. * Returns all generated line and column information for the original source,
  3684. * line, and column provided. If no column is provided, returns all mappings
  3685. * corresponding to a either the line we are searching for or the next
  3686. * closest line that has any mappings. Otherwise, returns all mappings
  3687. * corresponding to the given line and either the column we are searching for
  3688. * or the next closest column that has any offsets.
  3689. *
  3690. * The only argument is an object with the following properties:
  3691. *
  3692. * - source: The filename of the original source.
  3693. * - line: The line number in the original source. The line number is 1-based.
  3694. * - column: Optional. the column number in the original source.
  3695. * The column number is 0-based.
  3696. *
  3697. * and an array of objects is returned, each with the following properties:
  3698. *
  3699. * - line: The line number in the generated source, or null. The
  3700. * line number is 1-based.
  3701. * - column: The column number in the generated source, or null.
  3702. * The column number is 0-based.
  3703. */
  3704. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  3705. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  3706. var line = util.getArg(aArgs, 'line');
  3707. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  3708. // returns the index of the closest mapping less than the needle. By
  3709. // setting needle.originalColumn to 0, we thus find the last mapping for
  3710. // the given line, provided such a mapping exists.
  3711. var needle = {
  3712. source: util.getArg(aArgs, 'source'),
  3713. originalLine: line,
  3714. originalColumn: util.getArg(aArgs, 'column', 0)
  3715. };
  3716. needle.source = this._findSourceIndex(needle.source);
  3717. if (needle.source < 0) {
  3718. return [];
  3719. }
  3720. var mappings = [];
  3721. var index = this._findMapping(needle,
  3722. this._originalMappings,
  3723. "originalLine",
  3724. "originalColumn",
  3725. util.compareByOriginalPositions,
  3726. binarySearch.LEAST_UPPER_BOUND);
  3727. if (index >= 0) {
  3728. var mapping = this._originalMappings[index];
  3729. if (aArgs.column === undefined) {
  3730. var originalLine = mapping.originalLine;
  3731. // Iterate until either we run out of mappings, or we run into
  3732. // a mapping for a different line than the one we found. Since
  3733. // mappings are sorted, this is guaranteed to find all mappings for
  3734. // the line we found.
  3735. while (mapping && mapping.originalLine === originalLine) {
  3736. mappings.push({
  3737. line: util.getArg(mapping, 'generatedLine', null),
  3738. column: util.getArg(mapping, 'generatedColumn', null),
  3739. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  3740. });
  3741. mapping = this._originalMappings[++index];
  3742. }
  3743. } else {
  3744. var originalColumn = mapping.originalColumn;
  3745. // Iterate until either we run out of mappings, or we run into
  3746. // a mapping for a different line than the one we were searching for.
  3747. // Since mappings are sorted, this is guaranteed to find all mappings for
  3748. // the line we are searching for.
  3749. while (mapping &&
  3750. mapping.originalLine === line &&
  3751. mapping.originalColumn == originalColumn) {
  3752. mappings.push({
  3753. line: util.getArg(mapping, 'generatedLine', null),
  3754. column: util.getArg(mapping, 'generatedColumn', null),
  3755. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  3756. });
  3757. mapping = this._originalMappings[++index];
  3758. }
  3759. }
  3760. }
  3761. return mappings;
  3762. };
  3763. var SourceMapConsumer_1 = SourceMapConsumer;
  3764. /**
  3765. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  3766. * query for information about the original file positions by giving it a file
  3767. * position in the generated source.
  3768. *
  3769. * The first parameter is the raw source map (either as a JSON string, or
  3770. * already parsed to an object). According to the spec, source maps have the
  3771. * following attributes:
  3772. *
  3773. * - version: Which version of the source map spec this map is following.
  3774. * - sources: An array of URLs to the original source files.
  3775. * - names: An array of identifiers which can be referrenced by individual mappings.
  3776. * - sourceRoot: Optional. The URL root from which all sources are relative.
  3777. * - sourcesContent: Optional. An array of contents of the original source files.
  3778. * - mappings: A string of base64 VLQs which contain the actual mappings.
  3779. * - file: Optional. The generated file this source map is associated with.
  3780. *
  3781. * Here is an example source map, taken from the source map spec[0]:
  3782. *
  3783. * {
  3784. * version : 3,
  3785. * file: "out.js",
  3786. * sourceRoot : "",
  3787. * sources: ["foo.js", "bar.js"],
  3788. * names: ["src", "maps", "are", "fun"],
  3789. * mappings: "AA,AB;;ABCDE;"
  3790. * }
  3791. *
  3792. * The second parameter, if given, is a string whose value is the URL
  3793. * at which the source map was found. This URL is used to compute the
  3794. * sources array.
  3795. *
  3796. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  3797. */
  3798. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  3799. var sourceMap = aSourceMap;
  3800. if (typeof aSourceMap === 'string') {
  3801. sourceMap = util.parseSourceMapInput(aSourceMap);
  3802. }
  3803. var version = util.getArg(sourceMap, 'version');
  3804. var sources = util.getArg(sourceMap, 'sources');
  3805. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  3806. // requires the array) to play nice here.
  3807. var names = util.getArg(sourceMap, 'names', []);
  3808. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  3809. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  3810. var mappings = util.getArg(sourceMap, 'mappings');
  3811. var file = util.getArg(sourceMap, 'file', null);
  3812. // Once again, Sass deviates from the spec and supplies the version as a
  3813. // string rather than a number, so we use loose equality checking here.
  3814. if (version != this._version) {
  3815. throw new Error('Unsupported version: ' + version);
  3816. }
  3817. if (sourceRoot) {
  3818. sourceRoot = util.normalize(sourceRoot);
  3819. }
  3820. sources = sources
  3821. .map(String)
  3822. // Some source maps produce relative source paths like "./foo.js" instead of
  3823. // "foo.js". Normalize these first so that future comparisons will succeed.
  3824. // See bugzil.la/1090768.
  3825. .map(util.normalize)
  3826. // Always ensure that absolute sources are internally stored relative to
  3827. // the source root, if the source root is absolute. Not doing this would
  3828. // be particularly problematic when the source root is a prefix of the
  3829. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  3830. .map(function (source) {
  3831. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  3832. ? util.relative(sourceRoot, source)
  3833. : source;
  3834. });
  3835. // Pass `true` below to allow duplicate names and sources. While source maps
  3836. // are intended to be compressed and deduplicated, the TypeScript compiler
  3837. // sometimes generates source maps with duplicates in them. See Github issue
  3838. // #72 and bugzil.la/889492.
  3839. this._names = ArraySet$2.fromArray(names.map(String), true);
  3840. this._sources = ArraySet$2.fromArray(sources, true);
  3841. this._absoluteSources = this._sources.toArray().map(function (s) {
  3842. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  3843. });
  3844. this.sourceRoot = sourceRoot;
  3845. this.sourcesContent = sourcesContent;
  3846. this._mappings = mappings;
  3847. this._sourceMapURL = aSourceMapURL;
  3848. this.file = file;
  3849. }
  3850. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  3851. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  3852. /**
  3853. * Utility function to find the index of a source. Returns -1 if not
  3854. * found.
  3855. */
  3856. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  3857. var relativeSource = aSource;
  3858. if (this.sourceRoot != null) {
  3859. relativeSource = util.relative(this.sourceRoot, relativeSource);
  3860. }
  3861. if (this._sources.has(relativeSource)) {
  3862. return this._sources.indexOf(relativeSource);
  3863. }
  3864. // Maybe aSource is an absolute URL as returned by |sources|. In
  3865. // this case we can't simply undo the transform.
  3866. var i;
  3867. for (i = 0; i < this._absoluteSources.length; ++i) {
  3868. if (this._absoluteSources[i] == aSource) {
  3869. return i;
  3870. }
  3871. }
  3872. return -1;
  3873. };
  3874. /**
  3875. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  3876. *
  3877. * @param SourceMapGenerator aSourceMap
  3878. * The source map that will be consumed.
  3879. * @param String aSourceMapURL
  3880. * The URL at which the source map can be found (optional)
  3881. * @returns BasicSourceMapConsumer
  3882. */
  3883. BasicSourceMapConsumer.fromSourceMap =
  3884. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  3885. var smc = Object.create(BasicSourceMapConsumer.prototype);
  3886. var names = smc._names = ArraySet$2.fromArray(aSourceMap._names.toArray(), true);
  3887. var sources = smc._sources = ArraySet$2.fromArray(aSourceMap._sources.toArray(), true);
  3888. smc.sourceRoot = aSourceMap._sourceRoot;
  3889. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  3890. smc.sourceRoot);
  3891. smc.file = aSourceMap._file;
  3892. smc._sourceMapURL = aSourceMapURL;
  3893. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  3894. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  3895. });
  3896. // Because we are modifying the entries (by converting string sources and
  3897. // names to indices into the sources and names ArraySets), we have to make
  3898. // a copy of the entry or else bad things happen. Shared mutable state
  3899. // strikes again! See github issue #191.
  3900. var generatedMappings = aSourceMap._mappings.toArray().slice();
  3901. var destGeneratedMappings = smc.__generatedMappings = [];
  3902. var destOriginalMappings = smc.__originalMappings = [];
  3903. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  3904. var srcMapping = generatedMappings[i];
  3905. var destMapping = new Mapping;
  3906. destMapping.generatedLine = srcMapping.generatedLine;
  3907. destMapping.generatedColumn = srcMapping.generatedColumn;
  3908. if (srcMapping.source) {
  3909. destMapping.source = sources.indexOf(srcMapping.source);
  3910. destMapping.originalLine = srcMapping.originalLine;
  3911. destMapping.originalColumn = srcMapping.originalColumn;
  3912. if (srcMapping.name) {
  3913. destMapping.name = names.indexOf(srcMapping.name);
  3914. }
  3915. destOriginalMappings.push(destMapping);
  3916. }
  3917. destGeneratedMappings.push(destMapping);
  3918. }
  3919. quickSort$1(smc.__originalMappings, util.compareByOriginalPositions);
  3920. return smc;
  3921. };
  3922. /**
  3923. * The version of the source mapping spec that we are consuming.
  3924. */
  3925. BasicSourceMapConsumer.prototype._version = 3;
  3926. /**
  3927. * The list of original sources.
  3928. */
  3929. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  3930. get: function () {
  3931. return this._absoluteSources.slice();
  3932. }
  3933. });
  3934. /**
  3935. * Provide the JIT with a nice shape / hidden class.
  3936. */
  3937. function Mapping() {
  3938. this.generatedLine = 0;
  3939. this.generatedColumn = 0;
  3940. this.source = null;
  3941. this.originalLine = null;
  3942. this.originalColumn = null;
  3943. this.name = null;
  3944. }
  3945. /**
  3946. * Parse the mappings in a string in to a data structure which we can easily
  3947. * query (the ordered arrays in the `this.__generatedMappings` and
  3948. * `this.__originalMappings` properties).
  3949. */
  3950. BasicSourceMapConsumer.prototype._parseMappings =
  3951. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  3952. var generatedLine = 1;
  3953. var previousGeneratedColumn = 0;
  3954. var previousOriginalLine = 0;
  3955. var previousOriginalColumn = 0;
  3956. var previousSource = 0;
  3957. var previousName = 0;
  3958. var length = aStr.length;
  3959. var index = 0;
  3960. var cachedSegments = {};
  3961. var temp = {};
  3962. var originalMappings = [];
  3963. var generatedMappings = [];
  3964. var mapping, str, segment, end, value;
  3965. while (index < length) {
  3966. if (aStr.charAt(index) === ';') {
  3967. generatedLine++;
  3968. index++;
  3969. previousGeneratedColumn = 0;
  3970. }
  3971. else if (aStr.charAt(index) === ',') {
  3972. index++;
  3973. }
  3974. else {
  3975. mapping = new Mapping();
  3976. mapping.generatedLine = generatedLine;
  3977. // Because each offset is encoded relative to the previous one,
  3978. // many segments often have the same encoding. We can exploit this
  3979. // fact by caching the parsed variable length fields of each segment,
  3980. // allowing us to avoid a second parse if we encounter the same
  3981. // segment again.
  3982. for (end = index; end < length; end++) {
  3983. if (this._charIsMappingSeparator(aStr, end)) {
  3984. break;
  3985. }
  3986. }
  3987. str = aStr.slice(index, end);
  3988. segment = cachedSegments[str];
  3989. if (segment) {
  3990. index += str.length;
  3991. } else {
  3992. segment = [];
  3993. while (index < end) {
  3994. base64Vlq.decode(aStr, index, temp);
  3995. value = temp.value;
  3996. index = temp.rest;
  3997. segment.push(value);
  3998. }
  3999. if (segment.length === 2) {
  4000. throw new Error('Found a source, but no line and column');
  4001. }
  4002. if (segment.length === 3) {
  4003. throw new Error('Found a source and line, but no column');
  4004. }
  4005. cachedSegments[str] = segment;
  4006. }
  4007. // Generated column.
  4008. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  4009. previousGeneratedColumn = mapping.generatedColumn;
  4010. if (segment.length > 1) {
  4011. // Original source.
  4012. mapping.source = previousSource + segment[1];
  4013. previousSource += segment[1];
  4014. // Original line.
  4015. mapping.originalLine = previousOriginalLine + segment[2];
  4016. previousOriginalLine = mapping.originalLine;
  4017. // Lines are stored 0-based
  4018. mapping.originalLine += 1;
  4019. // Original column.
  4020. mapping.originalColumn = previousOriginalColumn + segment[3];
  4021. previousOriginalColumn = mapping.originalColumn;
  4022. if (segment.length > 4) {
  4023. // Original name.
  4024. mapping.name = previousName + segment[4];
  4025. previousName += segment[4];
  4026. }
  4027. }
  4028. generatedMappings.push(mapping);
  4029. if (typeof mapping.originalLine === 'number') {
  4030. originalMappings.push(mapping);
  4031. }
  4032. }
  4033. }
  4034. quickSort$1(generatedMappings, util.compareByGeneratedPositionsDeflated);
  4035. this.__generatedMappings = generatedMappings;
  4036. quickSort$1(originalMappings, util.compareByOriginalPositions);
  4037. this.__originalMappings = originalMappings;
  4038. };
  4039. /**
  4040. * Find the mapping that best matches the hypothetical "needle" mapping that
  4041. * we are searching for in the given "haystack" of mappings.
  4042. */
  4043. BasicSourceMapConsumer.prototype._findMapping =
  4044. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  4045. aColumnName, aComparator, aBias) {
  4046. // To return the position we are searching for, we must first find the
  4047. // mapping for the given position and then return the opposite position it
  4048. // points to. Because the mappings are sorted, we can use binary search to
  4049. // find the best mapping.
  4050. if (aNeedle[aLineName] <= 0) {
  4051. throw new TypeError('Line must be greater than or equal to 1, got '
  4052. + aNeedle[aLineName]);
  4053. }
  4054. if (aNeedle[aColumnName] < 0) {
  4055. throw new TypeError('Column must be greater than or equal to 0, got '
  4056. + aNeedle[aColumnName]);
  4057. }
  4058. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  4059. };
  4060. /**
  4061. * Compute the last column for each generated mapping. The last column is
  4062. * inclusive.
  4063. */
  4064. BasicSourceMapConsumer.prototype.computeColumnSpans =
  4065. function SourceMapConsumer_computeColumnSpans() {
  4066. for (var index = 0; index < this._generatedMappings.length; ++index) {
  4067. var mapping = this._generatedMappings[index];
  4068. // Mappings do not contain a field for the last generated columnt. We
  4069. // can come up with an optimistic estimate, however, by assuming that
  4070. // mappings are contiguous (i.e. given two consecutive mappings, the
  4071. // first mapping ends where the second one starts).
  4072. if (index + 1 < this._generatedMappings.length) {
  4073. var nextMapping = this._generatedMappings[index + 1];
  4074. if (mapping.generatedLine === nextMapping.generatedLine) {
  4075. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  4076. continue;
  4077. }
  4078. }
  4079. // The last mapping for each line spans the entire line.
  4080. mapping.lastGeneratedColumn = Infinity;
  4081. }
  4082. };
  4083. /**
  4084. * Returns the original source, line, and column information for the generated
  4085. * source's line and column positions provided. The only argument is an object
  4086. * with the following properties:
  4087. *
  4088. * - line: The line number in the generated source. The line number
  4089. * is 1-based.
  4090. * - column: The column number in the generated source. The column
  4091. * number is 0-based.
  4092. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  4093. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  4094. * closest element that is smaller than or greater than the one we are
  4095. * searching for, respectively, if the exact element cannot be found.
  4096. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  4097. *
  4098. * and an object is returned with the following properties:
  4099. *
  4100. * - source: The original source file, or null.
  4101. * - line: The line number in the original source, or null. The
  4102. * line number is 1-based.
  4103. * - column: The column number in the original source, or null. The
  4104. * column number is 0-based.
  4105. * - name: The original identifier, or null.
  4106. */
  4107. BasicSourceMapConsumer.prototype.originalPositionFor =
  4108. function SourceMapConsumer_originalPositionFor(aArgs) {
  4109. var needle = {
  4110. generatedLine: util.getArg(aArgs, 'line'),
  4111. generatedColumn: util.getArg(aArgs, 'column')
  4112. };
  4113. var index = this._findMapping(
  4114. needle,
  4115. this._generatedMappings,
  4116. "generatedLine",
  4117. "generatedColumn",
  4118. util.compareByGeneratedPositionsDeflated,
  4119. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  4120. );
  4121. if (index >= 0) {
  4122. var mapping = this._generatedMappings[index];
  4123. if (mapping.generatedLine === needle.generatedLine) {
  4124. var source = util.getArg(mapping, 'source', null);
  4125. if (source !== null) {
  4126. source = this._sources.at(source);
  4127. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  4128. }
  4129. var name = util.getArg(mapping, 'name', null);
  4130. if (name !== null) {
  4131. name = this._names.at(name);
  4132. }
  4133. return {
  4134. source: source,
  4135. line: util.getArg(mapping, 'originalLine', null),
  4136. column: util.getArg(mapping, 'originalColumn', null),
  4137. name: name
  4138. };
  4139. }
  4140. }
  4141. return {
  4142. source: null,
  4143. line: null,
  4144. column: null,
  4145. name: null
  4146. };
  4147. };
  4148. /**
  4149. * Return true if we have the source content for every source in the source
  4150. * map, false otherwise.
  4151. */
  4152. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  4153. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  4154. if (!this.sourcesContent) {
  4155. return false;
  4156. }
  4157. return this.sourcesContent.length >= this._sources.size() &&
  4158. !this.sourcesContent.some(function (sc) { return sc == null; });
  4159. };
  4160. /**
  4161. * Returns the original source content. The only argument is the url of the
  4162. * original source file. Returns null if no original source content is
  4163. * available.
  4164. */
  4165. BasicSourceMapConsumer.prototype.sourceContentFor =
  4166. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  4167. if (!this.sourcesContent) {
  4168. return null;
  4169. }
  4170. var index = this._findSourceIndex(aSource);
  4171. if (index >= 0) {
  4172. return this.sourcesContent[index];
  4173. }
  4174. var relativeSource = aSource;
  4175. if (this.sourceRoot != null) {
  4176. relativeSource = util.relative(this.sourceRoot, relativeSource);
  4177. }
  4178. var url;
  4179. if (this.sourceRoot != null
  4180. && (url = util.urlParse(this.sourceRoot))) {
  4181. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  4182. // many users. We can help them out when they expect file:// URIs to
  4183. // behave like it would if they were running a local HTTP server. See
  4184. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  4185. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  4186. if (url.scheme == "file"
  4187. && this._sources.has(fileUriAbsPath)) {
  4188. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  4189. }
  4190. if ((!url.path || url.path == "/")
  4191. && this._sources.has("/" + relativeSource)) {
  4192. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  4193. }
  4194. }
  4195. // This function is used recursively from
  4196. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  4197. // don't want to throw if we can't find the source - we just want to
  4198. // return null, so we provide a flag to exit gracefully.
  4199. if (nullOnMissing) {
  4200. return null;
  4201. }
  4202. else {
  4203. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  4204. }
  4205. };
  4206. /**
  4207. * Returns the generated line and column information for the original source,
  4208. * line, and column positions provided. The only argument is an object with
  4209. * the following properties:
  4210. *
  4211. * - source: The filename of the original source.
  4212. * - line: The line number in the original source. The line number
  4213. * is 1-based.
  4214. * - column: The column number in the original source. The column
  4215. * number is 0-based.
  4216. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  4217. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  4218. * closest element that is smaller than or greater than the one we are
  4219. * searching for, respectively, if the exact element cannot be found.
  4220. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  4221. *
  4222. * and an object is returned with the following properties:
  4223. *
  4224. * - line: The line number in the generated source, or null. The
  4225. * line number is 1-based.
  4226. * - column: The column number in the generated source, or null.
  4227. * The column number is 0-based.
  4228. */
  4229. BasicSourceMapConsumer.prototype.generatedPositionFor =
  4230. function SourceMapConsumer_generatedPositionFor(aArgs) {
  4231. var source = util.getArg(aArgs, 'source');
  4232. source = this._findSourceIndex(source);
  4233. if (source < 0) {
  4234. return {
  4235. line: null,
  4236. column: null,
  4237. lastColumn: null
  4238. };
  4239. }
  4240. var needle = {
  4241. source: source,
  4242. originalLine: util.getArg(aArgs, 'line'),
  4243. originalColumn: util.getArg(aArgs, 'column')
  4244. };
  4245. var index = this._findMapping(
  4246. needle,
  4247. this._originalMappings,
  4248. "originalLine",
  4249. "originalColumn",
  4250. util.compareByOriginalPositions,
  4251. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  4252. );
  4253. if (index >= 0) {
  4254. var mapping = this._originalMappings[index];
  4255. if (mapping.source === needle.source) {
  4256. return {
  4257. line: util.getArg(mapping, 'generatedLine', null),
  4258. column: util.getArg(mapping, 'generatedColumn', null),
  4259. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  4260. };
  4261. }
  4262. }
  4263. return {
  4264. line: null,
  4265. column: null,
  4266. lastColumn: null
  4267. };
  4268. };
  4269. var BasicSourceMapConsumer_1 = BasicSourceMapConsumer;
  4270. /**
  4271. * An IndexedSourceMapConsumer instance represents a parsed source map which
  4272. * we can query for information. It differs from BasicSourceMapConsumer in
  4273. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  4274. * input.
  4275. *
  4276. * The first parameter is a raw source map (either as a JSON string, or already
  4277. * parsed to an object). According to the spec for indexed source maps, they
  4278. * have the following attributes:
  4279. *
  4280. * - version: Which version of the source map spec this map is following.
  4281. * - file: Optional. The generated file this source map is associated with.
  4282. * - sections: A list of section definitions.
  4283. *
  4284. * Each value under the "sections" field has two fields:
  4285. * - offset: The offset into the original specified at which this section
  4286. * begins to apply, defined as an object with a "line" and "column"
  4287. * field.
  4288. * - map: A source map definition. This source map could also be indexed,
  4289. * but doesn't have to be.
  4290. *
  4291. * Instead of the "map" field, it's also possible to have a "url" field
  4292. * specifying a URL to retrieve a source map from, but that's currently
  4293. * unsupported.
  4294. *
  4295. * Here's an example source map, taken from the source map spec[0], but
  4296. * modified to omit a section which uses the "url" field.
  4297. *
  4298. * {
  4299. * version : 3,
  4300. * file: "app.js",
  4301. * sections: [{
  4302. * offset: {line:100, column:10},
  4303. * map: {
  4304. * version : 3,
  4305. * file: "section.js",
  4306. * sources: ["foo.js", "bar.js"],
  4307. * names: ["src", "maps", "are", "fun"],
  4308. * mappings: "AAAA,E;;ABCDE;"
  4309. * }
  4310. * }],
  4311. * }
  4312. *
  4313. * The second parameter, if given, is a string whose value is the URL
  4314. * at which the source map was found. This URL is used to compute the
  4315. * sources array.
  4316. *
  4317. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  4318. */
  4319. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  4320. var sourceMap = aSourceMap;
  4321. if (typeof aSourceMap === 'string') {
  4322. sourceMap = util.parseSourceMapInput(aSourceMap);
  4323. }
  4324. var version = util.getArg(sourceMap, 'version');
  4325. var sections = util.getArg(sourceMap, 'sections');
  4326. if (version != this._version) {
  4327. throw new Error('Unsupported version: ' + version);
  4328. }
  4329. this._sources = new ArraySet$2();
  4330. this._names = new ArraySet$2();
  4331. var lastOffset = {
  4332. line: -1,
  4333. column: 0
  4334. };
  4335. this._sections = sections.map(function (s) {
  4336. if (s.url) {
  4337. // The url field will require support for asynchronicity.
  4338. // See https://github.com/mozilla/source-map/issues/16
  4339. throw new Error('Support for url field in sections not implemented.');
  4340. }
  4341. var offset = util.getArg(s, 'offset');
  4342. var offsetLine = util.getArg(offset, 'line');
  4343. var offsetColumn = util.getArg(offset, 'column');
  4344. if (offsetLine < lastOffset.line ||
  4345. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  4346. throw new Error('Section offsets must be ordered and non-overlapping.');
  4347. }
  4348. lastOffset = offset;
  4349. return {
  4350. generatedOffset: {
  4351. // The offset fields are 0-based, but we use 1-based indices when
  4352. // encoding/decoding from VLQ.
  4353. generatedLine: offsetLine + 1,
  4354. generatedColumn: offsetColumn + 1
  4355. },
  4356. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  4357. }
  4358. });
  4359. }
  4360. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  4361. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  4362. /**
  4363. * The version of the source mapping spec that we are consuming.
  4364. */
  4365. IndexedSourceMapConsumer.prototype._version = 3;
  4366. /**
  4367. * The list of original sources.
  4368. */
  4369. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  4370. get: function () {
  4371. var sources = [];
  4372. for (var i = 0; i < this._sections.length; i++) {
  4373. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  4374. sources.push(this._sections[i].consumer.sources[j]);
  4375. }
  4376. }
  4377. return sources;
  4378. }
  4379. });
  4380. /**
  4381. * Returns the original source, line, and column information for the generated
  4382. * source's line and column positions provided. The only argument is an object
  4383. * with the following properties:
  4384. *
  4385. * - line: The line number in the generated source. The line number
  4386. * is 1-based.
  4387. * - column: The column number in the generated source. The column
  4388. * number is 0-based.
  4389. *
  4390. * and an object is returned with the following properties:
  4391. *
  4392. * - source: The original source file, or null.
  4393. * - line: The line number in the original source, or null. The
  4394. * line number is 1-based.
  4395. * - column: The column number in the original source, or null. The
  4396. * column number is 0-based.
  4397. * - name: The original identifier, or null.
  4398. */
  4399. IndexedSourceMapConsumer.prototype.originalPositionFor =
  4400. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  4401. var needle = {
  4402. generatedLine: util.getArg(aArgs, 'line'),
  4403. generatedColumn: util.getArg(aArgs, 'column')
  4404. };
  4405. // Find the section containing the generated position we're trying to map
  4406. // to an original position.
  4407. var sectionIndex = binarySearch.search(needle, this._sections,
  4408. function(needle, section) {
  4409. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  4410. if (cmp) {
  4411. return cmp;
  4412. }
  4413. return (needle.generatedColumn -
  4414. section.generatedOffset.generatedColumn);
  4415. });
  4416. var section = this._sections[sectionIndex];
  4417. if (!section) {
  4418. return {
  4419. source: null,
  4420. line: null,
  4421. column: null,
  4422. name: null
  4423. };
  4424. }
  4425. return section.consumer.originalPositionFor({
  4426. line: needle.generatedLine -
  4427. (section.generatedOffset.generatedLine - 1),
  4428. column: needle.generatedColumn -
  4429. (section.generatedOffset.generatedLine === needle.generatedLine
  4430. ? section.generatedOffset.generatedColumn - 1
  4431. : 0),
  4432. bias: aArgs.bias
  4433. });
  4434. };
  4435. /**
  4436. * Return true if we have the source content for every source in the source
  4437. * map, false otherwise.
  4438. */
  4439. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  4440. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  4441. return this._sections.every(function (s) {
  4442. return s.consumer.hasContentsOfAllSources();
  4443. });
  4444. };
  4445. /**
  4446. * Returns the original source content. The only argument is the url of the
  4447. * original source file. Returns null if no original source content is
  4448. * available.
  4449. */
  4450. IndexedSourceMapConsumer.prototype.sourceContentFor =
  4451. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  4452. for (var i = 0; i < this._sections.length; i++) {
  4453. var section = this._sections[i];
  4454. var content = section.consumer.sourceContentFor(aSource, true);
  4455. if (content) {
  4456. return content;
  4457. }
  4458. }
  4459. if (nullOnMissing) {
  4460. return null;
  4461. }
  4462. else {
  4463. throw new Error('"' + aSource + '" is not in the SourceMap.');
  4464. }
  4465. };
  4466. /**
  4467. * Returns the generated line and column information for the original source,
  4468. * line, and column positions provided. The only argument is an object with
  4469. * the following properties:
  4470. *
  4471. * - source: The filename of the original source.
  4472. * - line: The line number in the original source. The line number
  4473. * is 1-based.
  4474. * - column: The column number in the original source. The column
  4475. * number is 0-based.
  4476. *
  4477. * and an object is returned with the following properties:
  4478. *
  4479. * - line: The line number in the generated source, or null. The
  4480. * line number is 1-based.
  4481. * - column: The column number in the generated source, or null.
  4482. * The column number is 0-based.
  4483. */
  4484. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  4485. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  4486. for (var i = 0; i < this._sections.length; i++) {
  4487. var section = this._sections[i];
  4488. // Only consider this section if the requested source is in the list of
  4489. // sources of the consumer.
  4490. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  4491. continue;
  4492. }
  4493. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  4494. if (generatedPosition) {
  4495. var ret = {
  4496. line: generatedPosition.line +
  4497. (section.generatedOffset.generatedLine - 1),
  4498. column: generatedPosition.column +
  4499. (section.generatedOffset.generatedLine === generatedPosition.line
  4500. ? section.generatedOffset.generatedColumn - 1
  4501. : 0)
  4502. };
  4503. return ret;
  4504. }
  4505. }
  4506. return {
  4507. line: null,
  4508. column: null
  4509. };
  4510. };
  4511. /**
  4512. * Parse the mappings in a string in to a data structure which we can easily
  4513. * query (the ordered arrays in the `this.__generatedMappings` and
  4514. * `this.__originalMappings` properties).
  4515. */
  4516. IndexedSourceMapConsumer.prototype._parseMappings =
  4517. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  4518. this.__generatedMappings = [];
  4519. this.__originalMappings = [];
  4520. for (var i = 0; i < this._sections.length; i++) {
  4521. var section = this._sections[i];
  4522. var sectionMappings = section.consumer._generatedMappings;
  4523. for (var j = 0; j < sectionMappings.length; j++) {
  4524. var mapping = sectionMappings[j];
  4525. var source = section.consumer._sources.at(mapping.source);
  4526. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  4527. this._sources.add(source);
  4528. source = this._sources.indexOf(source);
  4529. var name = null;
  4530. if (mapping.name) {
  4531. name = section.consumer._names.at(mapping.name);
  4532. this._names.add(name);
  4533. name = this._names.indexOf(name);
  4534. }
  4535. // The mappings coming from the consumer for the section have
  4536. // generated positions relative to the start of the section, so we
  4537. // need to offset them to be relative to the start of the concatenated
  4538. // generated file.
  4539. var adjustedMapping = {
  4540. source: source,
  4541. generatedLine: mapping.generatedLine +
  4542. (section.generatedOffset.generatedLine - 1),
  4543. generatedColumn: mapping.generatedColumn +
  4544. (section.generatedOffset.generatedLine === mapping.generatedLine
  4545. ? section.generatedOffset.generatedColumn - 1
  4546. : 0),
  4547. originalLine: mapping.originalLine,
  4548. originalColumn: mapping.originalColumn,
  4549. name: name
  4550. };
  4551. this.__generatedMappings.push(adjustedMapping);
  4552. if (typeof adjustedMapping.originalLine === 'number') {
  4553. this.__originalMappings.push(adjustedMapping);
  4554. }
  4555. }
  4556. }
  4557. quickSort$1(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  4558. quickSort$1(this.__originalMappings, util.compareByOriginalPositions);
  4559. };
  4560. var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer;
  4561. var sourceMapConsumer = {
  4562. SourceMapConsumer: SourceMapConsumer_1,
  4563. BasicSourceMapConsumer: BasicSourceMapConsumer_1,
  4564. IndexedSourceMapConsumer: IndexedSourceMapConsumer_1
  4565. };
  4566. /* -*- Mode: js; js-indent-level: 2; -*- */
  4567. /*
  4568. * Copyright 2011 Mozilla Foundation and contributors
  4569. * Licensed under the New BSD license. See LICENSE or:
  4570. * http://opensource.org/licenses/BSD-3-Clause
  4571. */
  4572. var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
  4573. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  4574. // operating systems these days (capturing the result).
  4575. var REGEX_NEWLINE = /(\r?\n)/;
  4576. // Newline character code for charCodeAt() comparisons
  4577. var NEWLINE_CODE = 10;
  4578. // Private symbol for identifying `SourceNode`s when multiple versions of
  4579. // the source-map library are loaded. This MUST NOT CHANGE across
  4580. // versions!
  4581. var isSourceNode = "$$$isSourceNode$$$";
  4582. /**
  4583. * SourceNodes provide a way to abstract over interpolating/concatenating
  4584. * snippets of generated JavaScript source code while maintaining the line and
  4585. * column information associated with the original source code.
  4586. *
  4587. * @param aLine The original line number.
  4588. * @param aColumn The original column number.
  4589. * @param aSource The original source's filename.
  4590. * @param aChunks Optional. An array of strings which are snippets of
  4591. * generated JS, or other SourceNodes.
  4592. * @param aName The original identifier.
  4593. */
  4594. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  4595. this.children = [];
  4596. this.sourceContents = {};
  4597. this.line = aLine == null ? null : aLine;
  4598. this.column = aColumn == null ? null : aColumn;
  4599. this.source = aSource == null ? null : aSource;
  4600. this.name = aName == null ? null : aName;
  4601. this[isSourceNode] = true;
  4602. if (aChunks != null) this.add(aChunks);
  4603. }
  4604. /**
  4605. * Creates a SourceNode from generated code and a SourceMapConsumer.
  4606. *
  4607. * @param aGeneratedCode The generated code
  4608. * @param aSourceMapConsumer The SourceMap for the generated code
  4609. * @param aRelativePath Optional. The path that relative sources in the
  4610. * SourceMapConsumer should be relative to.
  4611. */
  4612. SourceNode.fromStringWithSourceMap =
  4613. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  4614. // The SourceNode we want to fill with the generated code
  4615. // and the SourceMap
  4616. var node = new SourceNode();
  4617. // All even indices of this array are one line of the generated code,
  4618. // while all odd indices are the newlines between two adjacent lines
  4619. // (since `REGEX_NEWLINE` captures its match).
  4620. // Processed fragments are accessed by calling `shiftNextLine`.
  4621. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  4622. var remainingLinesIndex = 0;
  4623. var shiftNextLine = function() {
  4624. var lineContents = getNextLine();
  4625. // The last line of a file might not have a newline.
  4626. var newLine = getNextLine() || "";
  4627. return lineContents + newLine;
  4628. function getNextLine() {
  4629. return remainingLinesIndex < remainingLines.length ?
  4630. remainingLines[remainingLinesIndex++] : undefined;
  4631. }
  4632. };
  4633. // We need to remember the position of "remainingLines"
  4634. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  4635. // The generate SourceNodes we need a code range.
  4636. // To extract it current and last mapping is used.
  4637. // Here we store the last mapping.
  4638. var lastMapping = null;
  4639. aSourceMapConsumer.eachMapping(function (mapping) {
  4640. if (lastMapping !== null) {
  4641. // We add the code from "lastMapping" to "mapping":
  4642. // First check if there is a new line in between.
  4643. if (lastGeneratedLine < mapping.generatedLine) {
  4644. // Associate first line with "lastMapping"
  4645. addMappingWithCode(lastMapping, shiftNextLine());
  4646. lastGeneratedLine++;
  4647. lastGeneratedColumn = 0;
  4648. // The remaining code is added without mapping
  4649. } else {
  4650. // There is no new line in between.
  4651. // Associate the code between "lastGeneratedColumn" and
  4652. // "mapping.generatedColumn" with "lastMapping"
  4653. var nextLine = remainingLines[remainingLinesIndex] || '';
  4654. var code = nextLine.substr(0, mapping.generatedColumn -
  4655. lastGeneratedColumn);
  4656. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  4657. lastGeneratedColumn);
  4658. lastGeneratedColumn = mapping.generatedColumn;
  4659. addMappingWithCode(lastMapping, code);
  4660. // No more remaining code, continue
  4661. lastMapping = mapping;
  4662. return;
  4663. }
  4664. }
  4665. // We add the generated code until the first mapping
  4666. // to the SourceNode without any mapping.
  4667. // Each line is added as separate string.
  4668. while (lastGeneratedLine < mapping.generatedLine) {
  4669. node.add(shiftNextLine());
  4670. lastGeneratedLine++;
  4671. }
  4672. if (lastGeneratedColumn < mapping.generatedColumn) {
  4673. var nextLine = remainingLines[remainingLinesIndex] || '';
  4674. node.add(nextLine.substr(0, mapping.generatedColumn));
  4675. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  4676. lastGeneratedColumn = mapping.generatedColumn;
  4677. }
  4678. lastMapping = mapping;
  4679. }, this);
  4680. // We have processed all mappings.
  4681. if (remainingLinesIndex < remainingLines.length) {
  4682. if (lastMapping) {
  4683. // Associate the remaining code in the current line with "lastMapping"
  4684. addMappingWithCode(lastMapping, shiftNextLine());
  4685. }
  4686. // and add the remaining lines without any mapping
  4687. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  4688. }
  4689. // Copy sourcesContent into SourceNode
  4690. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  4691. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  4692. if (content != null) {
  4693. if (aRelativePath != null) {
  4694. sourceFile = util.join(aRelativePath, sourceFile);
  4695. }
  4696. node.setSourceContent(sourceFile, content);
  4697. }
  4698. });
  4699. return node;
  4700. function addMappingWithCode(mapping, code) {
  4701. if (mapping === null || mapping.source === undefined) {
  4702. node.add(code);
  4703. } else {
  4704. var source = aRelativePath
  4705. ? util.join(aRelativePath, mapping.source)
  4706. : mapping.source;
  4707. node.add(new SourceNode(mapping.originalLine,
  4708. mapping.originalColumn,
  4709. source,
  4710. code,
  4711. mapping.name));
  4712. }
  4713. }
  4714. };
  4715. /**
  4716. * Add a chunk of generated JS to this source node.
  4717. *
  4718. * @param aChunk A string snippet of generated JS code, another instance of
  4719. * SourceNode, or an array where each member is one of those things.
  4720. */
  4721. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  4722. if (Array.isArray(aChunk)) {
  4723. aChunk.forEach(function (chunk) {
  4724. this.add(chunk);
  4725. }, this);
  4726. }
  4727. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  4728. if (aChunk) {
  4729. this.children.push(aChunk);
  4730. }
  4731. }
  4732. else {
  4733. throw new TypeError(
  4734. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  4735. );
  4736. }
  4737. return this;
  4738. };
  4739. /**
  4740. * Add a chunk of generated JS to the beginning of this source node.
  4741. *
  4742. * @param aChunk A string snippet of generated JS code, another instance of
  4743. * SourceNode, or an array where each member is one of those things.
  4744. */
  4745. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  4746. if (Array.isArray(aChunk)) {
  4747. for (var i = aChunk.length-1; i >= 0; i--) {
  4748. this.prepend(aChunk[i]);
  4749. }
  4750. }
  4751. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  4752. this.children.unshift(aChunk);
  4753. }
  4754. else {
  4755. throw new TypeError(
  4756. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  4757. );
  4758. }
  4759. return this;
  4760. };
  4761. /**
  4762. * Walk over the tree of JS snippets in this node and its children. The
  4763. * walking function is called once for each snippet of JS and is passed that
  4764. * snippet and the its original associated source's line/column location.
  4765. *
  4766. * @param aFn The traversal function.
  4767. */
  4768. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  4769. var chunk;
  4770. for (var i = 0, len = this.children.length; i < len; i++) {
  4771. chunk = this.children[i];
  4772. if (chunk[isSourceNode]) {
  4773. chunk.walk(aFn);
  4774. }
  4775. else {
  4776. if (chunk !== '') {
  4777. aFn(chunk, { source: this.source,
  4778. line: this.line,
  4779. column: this.column,
  4780. name: this.name });
  4781. }
  4782. }
  4783. }
  4784. };
  4785. /**
  4786. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  4787. * each of `this.children`.
  4788. *
  4789. * @param aSep The separator.
  4790. */
  4791. SourceNode.prototype.join = function SourceNode_join(aSep) {
  4792. var newChildren;
  4793. var i;
  4794. var len = this.children.length;
  4795. if (len > 0) {
  4796. newChildren = [];
  4797. for (i = 0; i < len-1; i++) {
  4798. newChildren.push(this.children[i]);
  4799. newChildren.push(aSep);
  4800. }
  4801. newChildren.push(this.children[i]);
  4802. this.children = newChildren;
  4803. }
  4804. return this;
  4805. };
  4806. /**
  4807. * Call String.prototype.replace on the very right-most source snippet. Useful
  4808. * for trimming whitespace from the end of a source node, etc.
  4809. *
  4810. * @param aPattern The pattern to replace.
  4811. * @param aReplacement The thing to replace the pattern with.
  4812. */
  4813. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  4814. var lastChild = this.children[this.children.length - 1];
  4815. if (lastChild[isSourceNode]) {
  4816. lastChild.replaceRight(aPattern, aReplacement);
  4817. }
  4818. else if (typeof lastChild === 'string') {
  4819. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  4820. }
  4821. else {
  4822. this.children.push(''.replace(aPattern, aReplacement));
  4823. }
  4824. return this;
  4825. };
  4826. /**
  4827. * Set the source content for a source file. This will be added to the SourceMapGenerator
  4828. * in the sourcesContent field.
  4829. *
  4830. * @param aSourceFile The filename of the source file
  4831. * @param aSourceContent The content of the source file
  4832. */
  4833. SourceNode.prototype.setSourceContent =
  4834. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  4835. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  4836. };
  4837. /**
  4838. * Walk over the tree of SourceNodes. The walking function is called for each
  4839. * source file content and is passed the filename and source content.
  4840. *
  4841. * @param aFn The traversal function.
  4842. */
  4843. SourceNode.prototype.walkSourceContents =
  4844. function SourceNode_walkSourceContents(aFn) {
  4845. for (var i = 0, len = this.children.length; i < len; i++) {
  4846. if (this.children[i][isSourceNode]) {
  4847. this.children[i].walkSourceContents(aFn);
  4848. }
  4849. }
  4850. var sources = Object.keys(this.sourceContents);
  4851. for (var i = 0, len = sources.length; i < len; i++) {
  4852. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  4853. }
  4854. };
  4855. /**
  4856. * Return the string representation of this source node. Walks over the tree
  4857. * and concatenates all the various snippets together to one string.
  4858. */
  4859. SourceNode.prototype.toString = function SourceNode_toString() {
  4860. var str = "";
  4861. this.walk(function (chunk) {
  4862. str += chunk;
  4863. });
  4864. return str;
  4865. };
  4866. /**
  4867. * Returns the string representation of this source node along with a source
  4868. * map.
  4869. */
  4870. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  4871. var generated = {
  4872. code: "",
  4873. line: 1,
  4874. column: 0
  4875. };
  4876. var map = new SourceMapGenerator$1(aArgs);
  4877. var sourceMappingActive = false;
  4878. var lastOriginalSource = null;
  4879. var lastOriginalLine = null;
  4880. var lastOriginalColumn = null;
  4881. var lastOriginalName = null;
  4882. this.walk(function (chunk, original) {
  4883. generated.code += chunk;
  4884. if (original.source !== null
  4885. && original.line !== null
  4886. && original.column !== null) {
  4887. if(lastOriginalSource !== original.source
  4888. || lastOriginalLine !== original.line
  4889. || lastOriginalColumn !== original.column
  4890. || lastOriginalName !== original.name) {
  4891. map.addMapping({
  4892. source: original.source,
  4893. original: {
  4894. line: original.line,
  4895. column: original.column
  4896. },
  4897. generated: {
  4898. line: generated.line,
  4899. column: generated.column
  4900. },
  4901. name: original.name
  4902. });
  4903. }
  4904. lastOriginalSource = original.source;
  4905. lastOriginalLine = original.line;
  4906. lastOriginalColumn = original.column;
  4907. lastOriginalName = original.name;
  4908. sourceMappingActive = true;
  4909. } else if (sourceMappingActive) {
  4910. map.addMapping({
  4911. generated: {
  4912. line: generated.line,
  4913. column: generated.column
  4914. }
  4915. });
  4916. lastOriginalSource = null;
  4917. sourceMappingActive = false;
  4918. }
  4919. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  4920. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  4921. generated.line++;
  4922. generated.column = 0;
  4923. // Mappings end at eol
  4924. if (idx + 1 === length) {
  4925. lastOriginalSource = null;
  4926. sourceMappingActive = false;
  4927. } else if (sourceMappingActive) {
  4928. map.addMapping({
  4929. source: original.source,
  4930. original: {
  4931. line: original.line,
  4932. column: original.column
  4933. },
  4934. generated: {
  4935. line: generated.line,
  4936. column: generated.column
  4937. },
  4938. name: original.name
  4939. });
  4940. }
  4941. } else {
  4942. generated.column++;
  4943. }
  4944. }
  4945. });
  4946. this.walkSourceContents(function (sourceFile, sourceContent) {
  4947. map.setSourceContent(sourceFile, sourceContent);
  4948. });
  4949. return { code: generated.code, map: map };
  4950. };
  4951. var SourceNode_1 = SourceNode;
  4952. var sourceNode = {
  4953. SourceNode: SourceNode_1
  4954. };
  4955. /*
  4956. * Copyright 2009-2011 Mozilla Foundation and contributors
  4957. * Licensed under the New BSD license. See LICENSE.txt or:
  4958. * http://opensource.org/licenses/BSD-3-Clause
  4959. */
  4960. var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator;
  4961. var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer;
  4962. var SourceNode$1 = sourceNode.SourceNode;
  4963. var sourceMap = {
  4964. SourceMapGenerator: SourceMapGenerator$2,
  4965. SourceMapConsumer: SourceMapConsumer$1,
  4966. SourceNode: SourceNode$1
  4967. };
  4968. const PURE_ANNOTATION = `/*#__PURE__*/`;
  4969. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
  4970. const context = {
  4971. mode,
  4972. prefixIdentifiers,
  4973. sourceMap,
  4974. filename,
  4975. scopeId,
  4976. optimizeImports,
  4977. runtimeGlobalName,
  4978. runtimeModuleName,
  4979. ssr,
  4980. source: ast.loc.source,
  4981. code: ``,
  4982. column: 1,
  4983. line: 1,
  4984. offset: 0,
  4985. indentLevel: 0,
  4986. pure: false,
  4987. map: undefined,
  4988. helper(key) {
  4989. return `_${helperNameMap[key]}`;
  4990. },
  4991. push(code, node) {
  4992. context.code += code;
  4993. if (context.map) {
  4994. if (node) {
  4995. let name;
  4996. if (node.type === 4 /* SIMPLE_EXPRESSION */ && !node.isStatic) {
  4997. const content = node.content.replace(/^_ctx\./, '');
  4998. if (content !== node.content && isSimpleIdentifier(content)) {
  4999. name = content;
  5000. }
  5001. }
  5002. addMapping(node.loc.start, name);
  5003. }
  5004. advancePositionWithMutation(context, code);
  5005. if (node && node.loc !== locStub) {
  5006. addMapping(node.loc.end);
  5007. }
  5008. }
  5009. },
  5010. indent() {
  5011. newline(++context.indentLevel);
  5012. },
  5013. deindent(withoutNewLine = false) {
  5014. if (withoutNewLine) {
  5015. --context.indentLevel;
  5016. }
  5017. else {
  5018. newline(--context.indentLevel);
  5019. }
  5020. },
  5021. newline() {
  5022. newline(context.indentLevel);
  5023. }
  5024. };
  5025. function newline(n) {
  5026. context.push('\n' + ` `.repeat(n));
  5027. }
  5028. function addMapping(loc, name) {
  5029. context.map.addMapping({
  5030. name,
  5031. source: context.filename,
  5032. original: {
  5033. line: loc.line,
  5034. column: loc.column - 1 // source-map column is 0 based
  5035. },
  5036. generated: {
  5037. line: context.line,
  5038. column: context.column - 1
  5039. }
  5040. });
  5041. }
  5042. if (sourceMap) {
  5043. // lazy require source-map implementation, only in non-browser builds
  5044. context.map = new SourceMapGenerator$2();
  5045. context.map.setSourceContent(filename, context.source);
  5046. }
  5047. return context;
  5048. }
  5049. function generate(ast, options = {}) {
  5050. const context = createCodegenContext(ast, options);
  5051. if (options.onContextCreated)
  5052. options.onContextCreated(context);
  5053. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  5054. const hasHelpers = ast.helpers.length > 0;
  5055. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  5056. const genScopeId = scopeId != null && mode === 'module';
  5057. const isSetupInlined = !!options.inline;
  5058. // preambles
  5059. // in setup() inline mode, the preamble is generated in a sub context
  5060. // and returned separately.
  5061. const preambleContext = isSetupInlined
  5062. ? createCodegenContext(ast, options)
  5063. : context;
  5064. if (mode === 'module') {
  5065. genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  5066. }
  5067. else {
  5068. genFunctionPreamble(ast, preambleContext);
  5069. }
  5070. // enter render function
  5071. const functionName = ssr ? `ssrRender` : `render`;
  5072. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  5073. if (options.bindingMetadata && !options.inline) {
  5074. // binding optimization args
  5075. args.push('$props', '$setup', '$data', '$options');
  5076. }
  5077. const signature = options.isTS
  5078. ? args.map(arg => `${arg}: any`).join(',')
  5079. : args.join(', ');
  5080. if (genScopeId) {
  5081. if (isSetupInlined) {
  5082. push(`${PURE_ANNOTATION}_withId(`);
  5083. }
  5084. else {
  5085. push(`const ${functionName} = ${PURE_ANNOTATION}_withId(`);
  5086. }
  5087. }
  5088. if (isSetupInlined || genScopeId) {
  5089. push(`(${signature}) => {`);
  5090. }
  5091. else {
  5092. push(`function ${functionName}(${signature}) {`);
  5093. }
  5094. indent();
  5095. if (useWithBlock) {
  5096. push(`with (_ctx) {`);
  5097. indent();
  5098. // function mode const declarations should be inside with block
  5099. // also they should be renamed to avoid collision with user properties
  5100. if (hasHelpers) {
  5101. push(`const { ${ast.helpers
  5102. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  5103. .join(', ')} } = _Vue`);
  5104. push(`\n`);
  5105. newline();
  5106. }
  5107. }
  5108. // generate asset resolution statements
  5109. if (ast.components.length) {
  5110. genAssets(ast.components, 'component', context);
  5111. if (ast.directives.length || ast.temps > 0) {
  5112. newline();
  5113. }
  5114. }
  5115. if (ast.directives.length) {
  5116. genAssets(ast.directives, 'directive', context);
  5117. if (ast.temps > 0) {
  5118. newline();
  5119. }
  5120. }
  5121. if (ast.temps > 0) {
  5122. push(`let `);
  5123. for (let i = 0; i < ast.temps; i++) {
  5124. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  5125. }
  5126. }
  5127. if (ast.components.length || ast.directives.length || ast.temps) {
  5128. push(`\n`);
  5129. newline();
  5130. }
  5131. // generate the VNode tree expression
  5132. if (!ssr) {
  5133. push(`return `);
  5134. }
  5135. if (ast.codegenNode) {
  5136. genNode(ast.codegenNode, context);
  5137. }
  5138. else {
  5139. push(`null`);
  5140. }
  5141. if (useWithBlock) {
  5142. deindent();
  5143. push(`}`);
  5144. }
  5145. deindent();
  5146. push(`}`);
  5147. if (genScopeId) {
  5148. push(`)`);
  5149. }
  5150. return {
  5151. ast,
  5152. code: context.code,
  5153. preamble: isSetupInlined ? preambleContext.code : ``,
  5154. // SourceMapGenerator does have toJSON() method but it's not in the types
  5155. map: context.map ? context.map.toJSON() : undefined
  5156. };
  5157. }
  5158. function genFunctionPreamble(ast, context) {
  5159. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
  5160. const VueBinding = ssr
  5161. ? `require(${JSON.stringify(runtimeModuleName)})`
  5162. : runtimeGlobalName;
  5163. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  5164. // Generate const declaration for helpers
  5165. // In prefix mode, we place the const declaration at top so it's done
  5166. // only once; But if we not prefixing, we place the declaration inside the
  5167. // with block so it doesn't incur the `in` check cost for every helper access.
  5168. if (ast.helpers.length > 0) {
  5169. if (prefixIdentifiers) {
  5170. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n`);
  5171. }
  5172. else {
  5173. // "with" mode.
  5174. // save Vue in a separate variable to avoid collision
  5175. push(`const _Vue = ${VueBinding}\n`);
  5176. // in "with" mode, helpers are declared inside the with block to avoid
  5177. // has check cost, but hoists are lifted out of the function - we need
  5178. // to provide the helper here.
  5179. if (ast.hoists.length) {
  5180. const staticHelpers = [
  5181. CREATE_VNODE,
  5182. CREATE_COMMENT,
  5183. CREATE_TEXT,
  5184. CREATE_STATIC
  5185. ]
  5186. .filter(helper => ast.helpers.includes(helper))
  5187. .map(aliasHelper)
  5188. .join(', ');
  5189. push(`const { ${staticHelpers} } = _Vue\n`);
  5190. }
  5191. }
  5192. }
  5193. // generate variables for ssr helpers
  5194. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  5195. // ssr guarantees prefixIdentifier: true
  5196. push(`const { ${ast.ssrHelpers
  5197. .map(aliasHelper)
  5198. .join(', ')} } = require("@vue/server-renderer")\n`);
  5199. }
  5200. genHoists(ast.hoists, context);
  5201. newline();
  5202. push(`return `);
  5203. }
  5204. function genModulePreamble(ast, context, genScopeId, inline) {
  5205. const { push, helper, newline, scopeId, optimizeImports, runtimeModuleName } = context;
  5206. if (genScopeId) {
  5207. ast.helpers.push(WITH_SCOPE_ID);
  5208. if (ast.hoists.length) {
  5209. ast.helpers.push(PUSH_SCOPE_ID, POP_SCOPE_ID);
  5210. }
  5211. }
  5212. // generate import statements for helpers
  5213. if (ast.helpers.length) {
  5214. if (optimizeImports) {
  5215. // when bundled with webpack with code-split, calling an import binding
  5216. // as a function leads to it being wrapped with `Object(a.b)` or `(0,a.b)`,
  5217. // incurring both payload size increase and potential perf overhead.
  5218. // therefore we assign the imports to variables (which is a constant ~50b
  5219. // cost per-component instead of scaling with template size)
  5220. push(`import { ${ast.helpers
  5221. .map(s => helperNameMap[s])
  5222. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  5223. push(`\n// Binding optimization for webpack code-split\nconst ${ast.helpers
  5224. .map(s => `_${helperNameMap[s]} = ${helperNameMap[s]}`)
  5225. .join(', ')}\n`);
  5226. }
  5227. else {
  5228. push(`import { ${ast.helpers
  5229. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  5230. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  5231. }
  5232. }
  5233. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  5234. push(`import { ${ast.ssrHelpers
  5235. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  5236. .join(', ')} } from "@vue/server-renderer"\n`);
  5237. }
  5238. if (ast.imports.length) {
  5239. genImports(ast.imports, context);
  5240. newline();
  5241. }
  5242. if (genScopeId) {
  5243. push(`const _withId = ${PURE_ANNOTATION}${helper(WITH_SCOPE_ID)}("${scopeId}")`);
  5244. newline();
  5245. }
  5246. genHoists(ast.hoists, context);
  5247. newline();
  5248. if (!inline) {
  5249. push(`export `);
  5250. }
  5251. }
  5252. function genAssets(assets, type, { helper, push, newline }) {
  5253. const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
  5254. for (let i = 0; i < assets.length; i++) {
  5255. const id = assets[i];
  5256. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})`);
  5257. if (i < assets.length - 1) {
  5258. newline();
  5259. }
  5260. }
  5261. }
  5262. function genHoists(hoists, context) {
  5263. if (!hoists.length) {
  5264. return;
  5265. }
  5266. context.pure = true;
  5267. const { push, newline, helper, scopeId, mode } = context;
  5268. const genScopeId = scopeId != null && mode !== 'function';
  5269. newline();
  5270. // push scope Id before initializing hoisted vnodes so that these vnodes
  5271. // get the proper scopeId as well.
  5272. if (genScopeId) {
  5273. push(`${helper(PUSH_SCOPE_ID)}("${scopeId}")`);
  5274. newline();
  5275. }
  5276. hoists.forEach((exp, i) => {
  5277. if (exp) {
  5278. push(`const _hoisted_${i + 1} = `);
  5279. genNode(exp, context);
  5280. newline();
  5281. }
  5282. });
  5283. if (genScopeId) {
  5284. push(`${helper(POP_SCOPE_ID)}()`);
  5285. newline();
  5286. }
  5287. context.pure = false;
  5288. }
  5289. function genImports(importsOptions, context) {
  5290. if (!importsOptions.length) {
  5291. return;
  5292. }
  5293. importsOptions.forEach(imports => {
  5294. context.push(`import `);
  5295. genNode(imports.exp, context);
  5296. context.push(` from '${imports.path}'`);
  5297. context.newline();
  5298. });
  5299. }
  5300. function isText$1(n) {
  5301. return (isString(n) ||
  5302. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  5303. n.type === 2 /* TEXT */ ||
  5304. n.type === 5 /* INTERPOLATION */ ||
  5305. n.type === 8 /* COMPOUND_EXPRESSION */);
  5306. }
  5307. function genNodeListAsArray(nodes, context) {
  5308. const multilines = nodes.length > 3 ||
  5309. (nodes.some(n => isArray(n) || !isText$1(n)));
  5310. context.push(`[`);
  5311. multilines && context.indent();
  5312. genNodeList(nodes, context, multilines);
  5313. multilines && context.deindent();
  5314. context.push(`]`);
  5315. }
  5316. function genNodeList(nodes, context, multilines = false, comma = true) {
  5317. const { push, newline } = context;
  5318. for (let i = 0; i < nodes.length; i++) {
  5319. const node = nodes[i];
  5320. if (isString(node)) {
  5321. push(node);
  5322. }
  5323. else if (isArray(node)) {
  5324. genNodeListAsArray(node, context);
  5325. }
  5326. else {
  5327. genNode(node, context);
  5328. }
  5329. if (i < nodes.length - 1) {
  5330. if (multilines) {
  5331. comma && push(',');
  5332. newline();
  5333. }
  5334. else {
  5335. comma && push(', ');
  5336. }
  5337. }
  5338. }
  5339. }
  5340. function genNode(node, context) {
  5341. if (isString(node)) {
  5342. context.push(node);
  5343. return;
  5344. }
  5345. if (isSymbol(node)) {
  5346. context.push(context.helper(node));
  5347. return;
  5348. }
  5349. switch (node.type) {
  5350. case 1 /* ELEMENT */:
  5351. case 9 /* IF */:
  5352. case 11 /* FOR */:
  5353. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  5354. `Apply appropriate transforms first.`);
  5355. genNode(node.codegenNode, context);
  5356. break;
  5357. case 2 /* TEXT */:
  5358. genText(node, context);
  5359. break;
  5360. case 4 /* SIMPLE_EXPRESSION */:
  5361. genExpression(node, context);
  5362. break;
  5363. case 5 /* INTERPOLATION */:
  5364. genInterpolation(node, context);
  5365. break;
  5366. case 12 /* TEXT_CALL */:
  5367. genNode(node.codegenNode, context);
  5368. break;
  5369. case 8 /* COMPOUND_EXPRESSION */:
  5370. genCompoundExpression(node, context);
  5371. break;
  5372. case 3 /* COMMENT */:
  5373. genComment(node, context);
  5374. break;
  5375. case 13 /* VNODE_CALL */:
  5376. genVNodeCall(node, context);
  5377. break;
  5378. case 14 /* JS_CALL_EXPRESSION */:
  5379. genCallExpression(node, context);
  5380. break;
  5381. case 15 /* JS_OBJECT_EXPRESSION */:
  5382. genObjectExpression(node, context);
  5383. break;
  5384. case 17 /* JS_ARRAY_EXPRESSION */:
  5385. genArrayExpression(node, context);
  5386. break;
  5387. case 18 /* JS_FUNCTION_EXPRESSION */:
  5388. genFunctionExpression(node, context);
  5389. break;
  5390. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  5391. genConditionalExpression(node, context);
  5392. break;
  5393. case 20 /* JS_CACHE_EXPRESSION */:
  5394. genCacheExpression(node, context);
  5395. break;
  5396. // SSR only types
  5397. case 21 /* JS_BLOCK_STATEMENT */:
  5398. genNodeList(node.body, context, true, false);
  5399. break;
  5400. case 22 /* JS_TEMPLATE_LITERAL */:
  5401. genTemplateLiteral(node, context);
  5402. break;
  5403. case 23 /* JS_IF_STATEMENT */:
  5404. genIfStatement(node, context);
  5405. break;
  5406. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  5407. genAssignmentExpression(node, context);
  5408. break;
  5409. case 25 /* JS_SEQUENCE_EXPRESSION */:
  5410. genSequenceExpression(node, context);
  5411. break;
  5412. case 26 /* JS_RETURN_STATEMENT */:
  5413. genReturnStatement(node, context);
  5414. break;
  5415. /* istanbul ignore next */
  5416. case 10 /* IF_BRANCH */:
  5417. // noop
  5418. break;
  5419. default:
  5420. {
  5421. assert(false, `unhandled codegen node type: ${node.type}`);
  5422. // make sure we exhaust all possible types
  5423. const exhaustiveCheck = node;
  5424. return exhaustiveCheck;
  5425. }
  5426. }
  5427. }
  5428. function genText(node, context) {
  5429. context.push(JSON.stringify(node.content), node);
  5430. }
  5431. function genExpression(node, context) {
  5432. const { content, isStatic } = node;
  5433. context.push(isStatic ? JSON.stringify(content) : content, node);
  5434. }
  5435. function genInterpolation(node, context) {
  5436. const { push, helper, pure } = context;
  5437. if (pure)
  5438. push(PURE_ANNOTATION);
  5439. push(`${helper(TO_DISPLAY_STRING)}(`);
  5440. genNode(node.content, context);
  5441. push(`)`);
  5442. }
  5443. function genCompoundExpression(node, context) {
  5444. for (let i = 0; i < node.children.length; i++) {
  5445. const child = node.children[i];
  5446. if (isString(child)) {
  5447. context.push(child);
  5448. }
  5449. else {
  5450. genNode(child, context);
  5451. }
  5452. }
  5453. }
  5454. function genExpressionAsPropertyKey(node, context) {
  5455. const { push } = context;
  5456. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  5457. push(`[`);
  5458. genCompoundExpression(node, context);
  5459. push(`]`);
  5460. }
  5461. else if (node.isStatic) {
  5462. // only quote keys if necessary
  5463. const text = isSimpleIdentifier(node.content)
  5464. ? node.content
  5465. : JSON.stringify(node.content);
  5466. push(text, node);
  5467. }
  5468. else {
  5469. push(`[${node.content}]`, node);
  5470. }
  5471. }
  5472. function genComment(node, context) {
  5473. {
  5474. const { push, helper, pure } = context;
  5475. if (pure) {
  5476. push(PURE_ANNOTATION);
  5477. }
  5478. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  5479. }
  5480. }
  5481. function genVNodeCall(node, context) {
  5482. const { push, helper, pure } = context;
  5483. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
  5484. if (directives) {
  5485. push(helper(WITH_DIRECTIVES) + `(`);
  5486. }
  5487. if (isBlock) {
  5488. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  5489. }
  5490. if (pure) {
  5491. push(PURE_ANNOTATION);
  5492. }
  5493. push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
  5494. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  5495. push(`)`);
  5496. if (isBlock) {
  5497. push(`)`);
  5498. }
  5499. if (directives) {
  5500. push(`, `);
  5501. genNode(directives, context);
  5502. push(`)`);
  5503. }
  5504. }
  5505. function genNullableArgs(args) {
  5506. let i = args.length;
  5507. while (i--) {
  5508. if (args[i] != null)
  5509. break;
  5510. }
  5511. return args.slice(0, i + 1).map(arg => arg || `null`);
  5512. }
  5513. // JavaScript
  5514. function genCallExpression(node, context) {
  5515. const { push, helper, pure } = context;
  5516. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  5517. if (pure) {
  5518. push(PURE_ANNOTATION);
  5519. }
  5520. push(callee + `(`, node);
  5521. genNodeList(node.arguments, context);
  5522. push(`)`);
  5523. }
  5524. function genObjectExpression(node, context) {
  5525. const { push, indent, deindent, newline } = context;
  5526. const { properties } = node;
  5527. if (!properties.length) {
  5528. push(`{}`, node);
  5529. return;
  5530. }
  5531. const multilines = properties.length > 1 ||
  5532. (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  5533. push(multilines ? `{` : `{ `);
  5534. multilines && indent();
  5535. for (let i = 0; i < properties.length; i++) {
  5536. const { key, value } = properties[i];
  5537. // key
  5538. genExpressionAsPropertyKey(key, context);
  5539. push(`: `);
  5540. // value
  5541. genNode(value, context);
  5542. if (i < properties.length - 1) {
  5543. // will only reach this if it's multilines
  5544. push(`,`);
  5545. newline();
  5546. }
  5547. }
  5548. multilines && deindent();
  5549. push(multilines ? `}` : ` }`);
  5550. }
  5551. function genArrayExpression(node, context) {
  5552. genNodeListAsArray(node.elements, context);
  5553. }
  5554. function genFunctionExpression(node, context) {
  5555. const { push, indent, deindent, scopeId, mode } = context;
  5556. const { params, returns, body, newline, isSlot } = node;
  5557. // slot functions also need to push scopeId before rendering its content
  5558. const genScopeId = isSlot && scopeId != null && mode !== 'function';
  5559. if (genScopeId) {
  5560. push(`_withId(`);
  5561. }
  5562. else if (isSlot) {
  5563. push(`_${helperNameMap[WITH_CTX]}(`);
  5564. }
  5565. push(`(`, node);
  5566. if (isArray(params)) {
  5567. genNodeList(params, context);
  5568. }
  5569. else if (params) {
  5570. genNode(params, context);
  5571. }
  5572. push(`) => `);
  5573. if (newline || body) {
  5574. push(`{`);
  5575. indent();
  5576. }
  5577. if (returns) {
  5578. if (newline) {
  5579. push(`return `);
  5580. }
  5581. if (isArray(returns)) {
  5582. genNodeListAsArray(returns, context);
  5583. }
  5584. else {
  5585. genNode(returns, context);
  5586. }
  5587. }
  5588. else if (body) {
  5589. genNode(body, context);
  5590. }
  5591. if (newline || body) {
  5592. deindent();
  5593. push(`}`);
  5594. }
  5595. if (genScopeId || isSlot) {
  5596. push(`)`);
  5597. }
  5598. }
  5599. function genConditionalExpression(node, context) {
  5600. const { test, consequent, alternate, newline: needNewline } = node;
  5601. const { push, indent, deindent, newline } = context;
  5602. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  5603. const needsParens = !isSimpleIdentifier(test.content);
  5604. needsParens && push(`(`);
  5605. genExpression(test, context);
  5606. needsParens && push(`)`);
  5607. }
  5608. else {
  5609. push(`(`);
  5610. genNode(test, context);
  5611. push(`)`);
  5612. }
  5613. needNewline && indent();
  5614. context.indentLevel++;
  5615. needNewline || push(` `);
  5616. push(`? `);
  5617. genNode(consequent, context);
  5618. context.indentLevel--;
  5619. needNewline && newline();
  5620. needNewline || push(` `);
  5621. push(`: `);
  5622. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  5623. if (!isNested) {
  5624. context.indentLevel++;
  5625. }
  5626. genNode(alternate, context);
  5627. if (!isNested) {
  5628. context.indentLevel--;
  5629. }
  5630. needNewline && deindent(true /* without newline */);
  5631. }
  5632. function genCacheExpression(node, context) {
  5633. const { push, helper, indent, deindent, newline } = context;
  5634. push(`_cache[${node.index}] || (`);
  5635. if (node.isVNode) {
  5636. indent();
  5637. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  5638. newline();
  5639. }
  5640. push(`_cache[${node.index}] = `);
  5641. genNode(node.value, context);
  5642. if (node.isVNode) {
  5643. push(`,`);
  5644. newline();
  5645. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  5646. newline();
  5647. push(`_cache[${node.index}]`);
  5648. deindent();
  5649. }
  5650. push(`)`);
  5651. }
  5652. function genTemplateLiteral(node, context) {
  5653. const { push, indent, deindent } = context;
  5654. push('`');
  5655. const l = node.elements.length;
  5656. const multilines = l > 3;
  5657. for (let i = 0; i < l; i++) {
  5658. const e = node.elements[i];
  5659. if (isString(e)) {
  5660. push(e.replace(/(`|\$|\\)/g, '\\$1'));
  5661. }
  5662. else {
  5663. push('${');
  5664. if (multilines)
  5665. indent();
  5666. genNode(e, context);
  5667. if (multilines)
  5668. deindent();
  5669. push('}');
  5670. }
  5671. }
  5672. push('`');
  5673. }
  5674. function genIfStatement(node, context) {
  5675. const { push, indent, deindent } = context;
  5676. const { test, consequent, alternate } = node;
  5677. push(`if (`);
  5678. genNode(test, context);
  5679. push(`) {`);
  5680. indent();
  5681. genNode(consequent, context);
  5682. deindent();
  5683. push(`}`);
  5684. if (alternate) {
  5685. push(` else `);
  5686. if (alternate.type === 23 /* JS_IF_STATEMENT */) {
  5687. genIfStatement(alternate, context);
  5688. }
  5689. else {
  5690. push(`{`);
  5691. indent();
  5692. genNode(alternate, context);
  5693. deindent();
  5694. push(`}`);
  5695. }
  5696. }
  5697. }
  5698. function genAssignmentExpression(node, context) {
  5699. genNode(node.left, context);
  5700. context.push(` = `);
  5701. genNode(node.right, context);
  5702. }
  5703. function genSequenceExpression(node, context) {
  5704. context.push(`(`);
  5705. genNodeList(node.expressions, context);
  5706. context.push(`)`);
  5707. }
  5708. function genReturnStatement({ returns }, context) {
  5709. context.push(`return `);
  5710. if (isArray(returns)) {
  5711. genNodeListAsArray(returns, context);
  5712. }
  5713. else {
  5714. genNode(returns, context);
  5715. }
  5716. }
  5717. const beforeExpr = true;
  5718. const startsExpr = true;
  5719. const isLoop = true;
  5720. const isAssign = true;
  5721. const prefix = true;
  5722. const postfix = true;
  5723. class TokenType {
  5724. constructor(label, conf = {}) {
  5725. this.label = void 0;
  5726. this.keyword = void 0;
  5727. this.beforeExpr = void 0;
  5728. this.startsExpr = void 0;
  5729. this.rightAssociative = void 0;
  5730. this.isLoop = void 0;
  5731. this.isAssign = void 0;
  5732. this.prefix = void 0;
  5733. this.postfix = void 0;
  5734. this.binop = void 0;
  5735. this.updateContext = void 0;
  5736. this.label = label;
  5737. this.keyword = conf.keyword;
  5738. this.beforeExpr = !!conf.beforeExpr;
  5739. this.startsExpr = !!conf.startsExpr;
  5740. this.rightAssociative = !!conf.rightAssociative;
  5741. this.isLoop = !!conf.isLoop;
  5742. this.isAssign = !!conf.isAssign;
  5743. this.prefix = !!conf.prefix;
  5744. this.postfix = !!conf.postfix;
  5745. this.binop = conf.binop != null ? conf.binop : null;
  5746. this.updateContext = null;
  5747. }
  5748. }
  5749. const keywords = new Map();
  5750. function createKeyword(name, options = {}) {
  5751. options.keyword = name;
  5752. const token = new TokenType(name, options);
  5753. keywords.set(name, token);
  5754. return token;
  5755. }
  5756. function createBinop(name, binop) {
  5757. return new TokenType(name, {
  5758. beforeExpr,
  5759. binop
  5760. });
  5761. }
  5762. const types = {
  5763. num: new TokenType("num", {
  5764. startsExpr
  5765. }),
  5766. bigint: new TokenType("bigint", {
  5767. startsExpr
  5768. }),
  5769. decimal: new TokenType("decimal", {
  5770. startsExpr
  5771. }),
  5772. regexp: new TokenType("regexp", {
  5773. startsExpr
  5774. }),
  5775. string: new TokenType("string", {
  5776. startsExpr
  5777. }),
  5778. name: new TokenType("name", {
  5779. startsExpr
  5780. }),
  5781. eof: new TokenType("eof"),
  5782. bracketL: new TokenType("[", {
  5783. beforeExpr,
  5784. startsExpr
  5785. }),
  5786. bracketHashL: new TokenType("#[", {
  5787. beforeExpr,
  5788. startsExpr
  5789. }),
  5790. bracketBarL: new TokenType("[|", {
  5791. beforeExpr,
  5792. startsExpr
  5793. }),
  5794. bracketR: new TokenType("]"),
  5795. bracketBarR: new TokenType("|]"),
  5796. braceL: new TokenType("{", {
  5797. beforeExpr,
  5798. startsExpr
  5799. }),
  5800. braceBarL: new TokenType("{|", {
  5801. beforeExpr,
  5802. startsExpr
  5803. }),
  5804. braceHashL: new TokenType("#{", {
  5805. beforeExpr,
  5806. startsExpr
  5807. }),
  5808. braceR: new TokenType("}"),
  5809. braceBarR: new TokenType("|}"),
  5810. parenL: new TokenType("(", {
  5811. beforeExpr,
  5812. startsExpr
  5813. }),
  5814. parenR: new TokenType(")"),
  5815. comma: new TokenType(",", {
  5816. beforeExpr
  5817. }),
  5818. semi: new TokenType(";", {
  5819. beforeExpr
  5820. }),
  5821. colon: new TokenType(":", {
  5822. beforeExpr
  5823. }),
  5824. doubleColon: new TokenType("::", {
  5825. beforeExpr
  5826. }),
  5827. dot: new TokenType("."),
  5828. question: new TokenType("?", {
  5829. beforeExpr
  5830. }),
  5831. questionDot: new TokenType("?."),
  5832. arrow: new TokenType("=>", {
  5833. beforeExpr
  5834. }),
  5835. template: new TokenType("template"),
  5836. ellipsis: new TokenType("...", {
  5837. beforeExpr
  5838. }),
  5839. backQuote: new TokenType("`", {
  5840. startsExpr
  5841. }),
  5842. dollarBraceL: new TokenType("${", {
  5843. beforeExpr,
  5844. startsExpr
  5845. }),
  5846. at: new TokenType("@"),
  5847. hash: new TokenType("#", {
  5848. startsExpr
  5849. }),
  5850. interpreterDirective: new TokenType("#!..."),
  5851. eq: new TokenType("=", {
  5852. beforeExpr,
  5853. isAssign
  5854. }),
  5855. assign: new TokenType("_=", {
  5856. beforeExpr,
  5857. isAssign
  5858. }),
  5859. incDec: new TokenType("++/--", {
  5860. prefix,
  5861. postfix,
  5862. startsExpr
  5863. }),
  5864. bang: new TokenType("!", {
  5865. beforeExpr,
  5866. prefix,
  5867. startsExpr
  5868. }),
  5869. tilde: new TokenType("~", {
  5870. beforeExpr,
  5871. prefix,
  5872. startsExpr
  5873. }),
  5874. pipeline: createBinop("|>", 0),
  5875. nullishCoalescing: createBinop("??", 1),
  5876. logicalOR: createBinop("||", 1),
  5877. logicalAND: createBinop("&&", 2),
  5878. bitwiseOR: createBinop("|", 3),
  5879. bitwiseXOR: createBinop("^", 4),
  5880. bitwiseAND: createBinop("&", 5),
  5881. equality: createBinop("==/!=/===/!==", 6),
  5882. relational: createBinop("</>/<=/>=", 7),
  5883. bitShift: createBinop("<</>>/>>>", 8),
  5884. plusMin: new TokenType("+/-", {
  5885. beforeExpr,
  5886. binop: 9,
  5887. prefix,
  5888. startsExpr
  5889. }),
  5890. modulo: new TokenType("%", {
  5891. beforeExpr,
  5892. binop: 10,
  5893. startsExpr
  5894. }),
  5895. star: new TokenType("*", {
  5896. binop: 10
  5897. }),
  5898. slash: createBinop("/", 10),
  5899. exponent: new TokenType("**", {
  5900. beforeExpr,
  5901. binop: 11,
  5902. rightAssociative: true
  5903. }),
  5904. _break: createKeyword("break"),
  5905. _case: createKeyword("case", {
  5906. beforeExpr
  5907. }),
  5908. _catch: createKeyword("catch"),
  5909. _continue: createKeyword("continue"),
  5910. _debugger: createKeyword("debugger"),
  5911. _default: createKeyword("default", {
  5912. beforeExpr
  5913. }),
  5914. _do: createKeyword("do", {
  5915. isLoop,
  5916. beforeExpr
  5917. }),
  5918. _else: createKeyword("else", {
  5919. beforeExpr
  5920. }),
  5921. _finally: createKeyword("finally"),
  5922. _for: createKeyword("for", {
  5923. isLoop
  5924. }),
  5925. _function: createKeyword("function", {
  5926. startsExpr
  5927. }),
  5928. _if: createKeyword("if"),
  5929. _return: createKeyword("return", {
  5930. beforeExpr
  5931. }),
  5932. _switch: createKeyword("switch"),
  5933. _throw: createKeyword("throw", {
  5934. beforeExpr,
  5935. prefix,
  5936. startsExpr
  5937. }),
  5938. _try: createKeyword("try"),
  5939. _var: createKeyword("var"),
  5940. _const: createKeyword("const"),
  5941. _while: createKeyword("while", {
  5942. isLoop
  5943. }),
  5944. _with: createKeyword("with"),
  5945. _new: createKeyword("new", {
  5946. beforeExpr,
  5947. startsExpr
  5948. }),
  5949. _this: createKeyword("this", {
  5950. startsExpr
  5951. }),
  5952. _super: createKeyword("super", {
  5953. startsExpr
  5954. }),
  5955. _class: createKeyword("class", {
  5956. startsExpr
  5957. }),
  5958. _extends: createKeyword("extends", {
  5959. beforeExpr
  5960. }),
  5961. _export: createKeyword("export"),
  5962. _import: createKeyword("import", {
  5963. startsExpr
  5964. }),
  5965. _null: createKeyword("null", {
  5966. startsExpr
  5967. }),
  5968. _true: createKeyword("true", {
  5969. startsExpr
  5970. }),
  5971. _false: createKeyword("false", {
  5972. startsExpr
  5973. }),
  5974. _in: createKeyword("in", {
  5975. beforeExpr,
  5976. binop: 7
  5977. }),
  5978. _instanceof: createKeyword("instanceof", {
  5979. beforeExpr,
  5980. binop: 7
  5981. }),
  5982. _typeof: createKeyword("typeof", {
  5983. beforeExpr,
  5984. prefix,
  5985. startsExpr
  5986. }),
  5987. _void: createKeyword("void", {
  5988. beforeExpr,
  5989. prefix,
  5990. startsExpr
  5991. }),
  5992. _delete: createKeyword("delete", {
  5993. beforeExpr,
  5994. prefix,
  5995. startsExpr
  5996. })
  5997. };
  5998. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  5999. const lineBreakG = new RegExp(lineBreak.source, "g");
  6000. function isNewLine(code) {
  6001. switch (code) {
  6002. case 10:
  6003. case 13:
  6004. case 8232:
  6005. case 8233:
  6006. return true;
  6007. default:
  6008. return false;
  6009. }
  6010. }
  6011. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  6012. function isWhitespace(code) {
  6013. switch (code) {
  6014. case 0x0009:
  6015. case 0x000b:
  6016. case 0x000c:
  6017. case 32:
  6018. case 160:
  6019. case 5760:
  6020. case 0x2000:
  6021. case 0x2001:
  6022. case 0x2002:
  6023. case 0x2003:
  6024. case 0x2004:
  6025. case 0x2005:
  6026. case 0x2006:
  6027. case 0x2007:
  6028. case 0x2008:
  6029. case 0x2009:
  6030. case 0x200a:
  6031. case 0x202f:
  6032. case 0x205f:
  6033. case 0x3000:
  6034. case 0xfeff:
  6035. return true;
  6036. default:
  6037. return false;
  6038. }
  6039. }
  6040. class Position {
  6041. constructor(line, col) {
  6042. this.line = void 0;
  6043. this.column = void 0;
  6044. this.line = line;
  6045. this.column = col;
  6046. }
  6047. }
  6048. class SourceLocation {
  6049. constructor(start, end) {
  6050. this.start = void 0;
  6051. this.end = void 0;
  6052. this.filename = void 0;
  6053. this.identifierName = void 0;
  6054. this.start = start;
  6055. this.end = end;
  6056. }
  6057. }
  6058. function getLineInfo(input, offset) {
  6059. let line = 1;
  6060. let lineStart = 0;
  6061. let match;
  6062. lineBreakG.lastIndex = 0;
  6063. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  6064. line++;
  6065. lineStart = lineBreakG.lastIndex;
  6066. }
  6067. return new Position(line, offset - lineStart);
  6068. }
  6069. class BaseParser {
  6070. constructor() {
  6071. this.sawUnambiguousESM = false;
  6072. this.ambiguousScriptDifferentAst = false;
  6073. }
  6074. hasPlugin(name) {
  6075. return this.plugins.has(name);
  6076. }
  6077. getPluginOption(plugin, name) {
  6078. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  6079. }
  6080. }
  6081. function last$1(stack) {
  6082. return stack[stack.length - 1];
  6083. }
  6084. class CommentsParser extends BaseParser {
  6085. addComment(comment) {
  6086. if (this.filename) comment.loc.filename = this.filename;
  6087. this.state.trailingComments.push(comment);
  6088. this.state.leadingComments.push(comment);
  6089. }
  6090. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  6091. if (this.state.leadingComments.length === 0) {
  6092. return;
  6093. }
  6094. let lastElement = null;
  6095. let i = elements.length;
  6096. while (lastElement === null && i > 0) {
  6097. lastElement = elements[--i];
  6098. }
  6099. if (lastElement === null) {
  6100. return;
  6101. }
  6102. for (let j = 0; j < this.state.leadingComments.length; j++) {
  6103. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  6104. this.state.leadingComments.splice(j, 1);
  6105. j--;
  6106. }
  6107. }
  6108. const newTrailingComments = [];
  6109. for (let i = 0; i < this.state.leadingComments.length; i++) {
  6110. const leadingComment = this.state.leadingComments[i];
  6111. if (leadingComment.end < node.end) {
  6112. newTrailingComments.push(leadingComment);
  6113. if (!takeAllComments) {
  6114. this.state.leadingComments.splice(i, 1);
  6115. i--;
  6116. }
  6117. } else {
  6118. if (node.trailingComments === undefined) {
  6119. node.trailingComments = [];
  6120. }
  6121. node.trailingComments.push(leadingComment);
  6122. }
  6123. }
  6124. if (takeAllComments) this.state.leadingComments = [];
  6125. if (newTrailingComments.length > 0) {
  6126. lastElement.trailingComments = newTrailingComments;
  6127. } else if (lastElement.trailingComments !== undefined) {
  6128. lastElement.trailingComments = [];
  6129. }
  6130. }
  6131. processComment(node) {
  6132. if (node.type === "Program" && node.body.length > 0) return;
  6133. const stack = this.state.commentStack;
  6134. let firstChild, lastChild, trailingComments, i, j;
  6135. if (this.state.trailingComments.length > 0) {
  6136. if (this.state.trailingComments[0].start >= node.end) {
  6137. trailingComments = this.state.trailingComments;
  6138. this.state.trailingComments = [];
  6139. } else {
  6140. this.state.trailingComments.length = 0;
  6141. }
  6142. } else if (stack.length > 0) {
  6143. const lastInStack = last$1(stack);
  6144. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  6145. trailingComments = lastInStack.trailingComments;
  6146. delete lastInStack.trailingComments;
  6147. }
  6148. }
  6149. if (stack.length > 0 && last$1(stack).start >= node.start) {
  6150. firstChild = stack.pop();
  6151. }
  6152. while (stack.length > 0 && last$1(stack).start >= node.start) {
  6153. lastChild = stack.pop();
  6154. }
  6155. if (!lastChild && firstChild) lastChild = firstChild;
  6156. if (firstChild) {
  6157. switch (node.type) {
  6158. case "ObjectExpression":
  6159. this.adjustCommentsAfterTrailingComma(node, node.properties);
  6160. break;
  6161. case "ObjectPattern":
  6162. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  6163. break;
  6164. case "CallExpression":
  6165. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  6166. break;
  6167. case "ArrayExpression":
  6168. this.adjustCommentsAfterTrailingComma(node, node.elements);
  6169. break;
  6170. case "ArrayPattern":
  6171. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  6172. break;
  6173. }
  6174. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  6175. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
  6176. }
  6177. if (lastChild) {
  6178. if (lastChild.leadingComments) {
  6179. if (lastChild !== node && lastChild.leadingComments.length > 0 && last$1(lastChild.leadingComments).end <= node.start) {
  6180. node.leadingComments = lastChild.leadingComments;
  6181. delete lastChild.leadingComments;
  6182. } else {
  6183. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  6184. if (lastChild.leadingComments[i].end <= node.start) {
  6185. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  6186. break;
  6187. }
  6188. }
  6189. }
  6190. }
  6191. } else if (this.state.leadingComments.length > 0) {
  6192. if (last$1(this.state.leadingComments).end <= node.start) {
  6193. if (this.state.commentPreviousNode) {
  6194. for (j = 0; j < this.state.leadingComments.length; j++) {
  6195. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  6196. this.state.leadingComments.splice(j, 1);
  6197. j--;
  6198. }
  6199. }
  6200. }
  6201. if (this.state.leadingComments.length > 0) {
  6202. node.leadingComments = this.state.leadingComments;
  6203. this.state.leadingComments = [];
  6204. }
  6205. } else {
  6206. for (i = 0; i < this.state.leadingComments.length; i++) {
  6207. if (this.state.leadingComments[i].end > node.start) {
  6208. break;
  6209. }
  6210. }
  6211. const leadingComments = this.state.leadingComments.slice(0, i);
  6212. if (leadingComments.length) {
  6213. node.leadingComments = leadingComments;
  6214. }
  6215. trailingComments = this.state.leadingComments.slice(i);
  6216. if (trailingComments.length === 0) {
  6217. trailingComments = null;
  6218. }
  6219. }
  6220. }
  6221. this.state.commentPreviousNode = node;
  6222. if (trailingComments) {
  6223. if (trailingComments.length && trailingComments[0].start >= node.start && last$1(trailingComments).end <= node.end) {
  6224. node.innerComments = trailingComments;
  6225. } else {
  6226. const firstTrailingCommentIndex = trailingComments.findIndex(comment => comment.end >= node.end);
  6227. if (firstTrailingCommentIndex > 0) {
  6228. node.innerComments = trailingComments.slice(0, firstTrailingCommentIndex);
  6229. node.trailingComments = trailingComments.slice(firstTrailingCommentIndex);
  6230. } else {
  6231. node.trailingComments = trailingComments;
  6232. }
  6233. }
  6234. }
  6235. stack.push(node);
  6236. }
  6237. }
  6238. const ErrorMessages = Object.freeze({
  6239. AccessorIsGenerator: "A %0ter cannot be a generator",
  6240. ArgumentsInClass: "'arguments' is only allowed in functions and class methods",
  6241. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block",
  6242. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function",
  6243. AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
  6244. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules",
  6245. AwaitNotInAsyncFunction: "'await' is only allowed within async functions",
  6246. BadGetterArity: "getter must not have any formal parameters",
  6247. BadSetterArity: "setter must have exactly one formal parameter",
  6248. BadSetterRestParameter: "setter function argument must not be a rest parameter",
  6249. ConstructorClassField: "Classes may not have a field named 'constructor'",
  6250. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
  6251. ConstructorIsAccessor: "Class constructor may not be an accessor",
  6252. ConstructorIsAsync: "Constructor can't be an async function",
  6253. ConstructorIsGenerator: "Constructor can't be a generator",
  6254. DeclarationMissingInitializer: "%0 require an initialization value",
  6255. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
  6256. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  6257. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  6258. DecoratorSemicolon: "Decorators must not be followed by a semicolon",
  6259. DecoratorStaticBlock: "Decorators can't be used with a static block",
  6260. DeletePrivateField: "Deleting a private field is not allowed",
  6261. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  6262. DuplicateConstructor: "Duplicate constructor in the same class",
  6263. DuplicateDefaultExport: "Only one default export allowed per module.",
  6264. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  6265. DuplicateProto: "Redefinition of __proto__ property",
  6266. DuplicateRegExpFlags: "Duplicate regular expression flag",
  6267. DuplicateStaticBlock: "Duplicate static block in the same class",
  6268. ElementAfterRest: "Rest element must be last element",
  6269. EscapedCharNotAnIdentifier: "Invalid Unicode escape",
  6270. ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { %0 as '%1' } from 'some-module'`?",
  6271. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'",
  6272. ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
  6273. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block",
  6274. IllegalBreakContinue: "Unsyntactic %0",
  6275. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
  6276. IllegalReturn: "'return' outside of function",
  6277. ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
  6278. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments",
  6279. ImportCallArity: "import() requires exactly %0",
  6280. ImportCallNotNewExpression: "Cannot use new with import(...)",
  6281. ImportCallSpreadArgument: "... is not allowed in import()",
  6282. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  6283. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  6284. InvalidBigIntLiteral: "Invalid BigIntLiteral",
  6285. InvalidCodePoint: "Code point out of bounds",
  6286. InvalidDecimal: "Invalid decimal",
  6287. InvalidDigit: "Expected number in radix %0",
  6288. InvalidEscapeSequence: "Bad character escape sequence",
  6289. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template",
  6290. InvalidEscapedReservedWord: "Escape sequence in keyword %0",
  6291. InvalidIdentifier: "Invalid identifier %0",
  6292. InvalidLhs: "Invalid left-hand side in %0",
  6293. InvalidLhsBinding: "Binding invalid left-hand side in %0",
  6294. InvalidNumber: "Invalid number",
  6295. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'",
  6296. InvalidOrUnexpectedToken: "Unexpected character '%0'",
  6297. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern",
  6298. InvalidPrivateFieldResolution: "Private name #%0 is not defined",
  6299. InvalidPropertyBindingPattern: "Binding member expression",
  6300. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions",
  6301. InvalidRestAssignmentPattern: "Invalid rest operator's argument",
  6302. LabelRedeclaration: "Label '%0' is already declared",
  6303. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  6304. LineTerminatorBeforeArrow: "No line break is allowed before '=>'",
  6305. MalformedRegExpFlags: "Invalid regular expression flag",
  6306. MissingClassName: "A class name is required",
  6307. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  6308. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
  6309. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
  6310. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`",
  6311. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values",
  6312. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes',
  6313. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'",
  6314. ModuleExportUndefined: "Export '%0' is not defined",
  6315. MultipleDefaultsInSwitch: "Multiple default clauses",
  6316. NewlineAfterThrow: "Illegal newline after throw",
  6317. NoCatchOrFinally: "Missing catch or finally clause",
  6318. NumberIdentifier: "Identifier directly after number",
  6319. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
  6320. ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
  6321. OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
  6322. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
  6323. ParamDupe: "Argument name clash",
  6324. PatternHasAccessor: "Object pattern can't contain getter or setter",
  6325. PatternHasMethod: "Object pattern can't contain methods",
  6326. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
  6327. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
  6328. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
  6329. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
  6330. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
  6331. PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
  6332. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`)",
  6333. PrivateNameRedeclaration: "Duplicate private name #%0",
  6334. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  6335. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  6336. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  6337. RecordNoProto: "'__proto__' is not allowed in Record expressions",
  6338. RestTrailingComma: "Unexpected trailing comma after rest element",
  6339. SloppyFunction: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement",
  6340. StaticPrototype: "Classes may not have static property named prototype",
  6341. StrictDelete: "Deleting local variable in strict mode",
  6342. StrictEvalArguments: "Assigning to '%0' in strict mode",
  6343. StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
  6344. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
  6345. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'",
  6346. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
  6347. StrictWith: "'with' in strict mode",
  6348. 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?",
  6349. SuperPrivateField: "Private fields can't be accessed on super",
  6350. TrailingDecorator: "Decorators must be attached to a class element",
  6351. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  6352. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  6353. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  6354. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
  6355. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
  6356. UnexpectedDigitAfterHash: "Unexpected digit after hash token",
  6357. UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
  6358. UnexpectedKeyword: "Unexpected keyword '%0'",
  6359. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
  6360. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
  6361. UnexpectedNewTarget: "new.target can only be used in functions",
  6362. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
  6363. UnexpectedPrivateField: "Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).",
  6364. UnexpectedReservedWord: "Unexpected reserved word '%0'",
  6365. UnexpectedSuper: "super is only allowed in object methods and classes",
  6366. UnexpectedToken: "Unexpected token '%0'",
  6367. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  6368. UnsupportedBind: "Binding should be performed on object property.",
  6369. UnsupportedDecoratorExport: "A decorated export must export a class declaration",
  6370. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  6371. UnsupportedImport: "import can only be used in import() or import.meta",
  6372. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
  6373. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
  6374. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
  6375. UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
  6376. UnterminatedComment: "Unterminated comment",
  6377. UnterminatedRegExp: "Unterminated regular expression",
  6378. UnterminatedString: "Unterminated string constant",
  6379. UnterminatedTemplate: "Unterminated template",
  6380. VarRedeclaration: "Identifier '%0' has already been declared",
  6381. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
  6382. YieldInParameter: "Yield expression is not allowed in formal parameters",
  6383. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
  6384. });
  6385. class ParserError extends CommentsParser {
  6386. getLocationForPosition(pos) {
  6387. let loc;
  6388. if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos);
  6389. return loc;
  6390. }
  6391. raise(pos, errorTemplate, ...params) {
  6392. return this.raiseWithData(pos, undefined, errorTemplate, ...params);
  6393. }
  6394. raiseWithData(pos, data, errorTemplate, ...params) {
  6395. const loc = this.getLocationForPosition(pos);
  6396. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  6397. return this._raise(Object.assign({
  6398. loc,
  6399. pos
  6400. }, data), message);
  6401. }
  6402. _raise(errorContext, message) {
  6403. const err = new SyntaxError(message);
  6404. Object.assign(err, errorContext);
  6405. if (this.options.errorRecovery) {
  6406. if (!this.isLookahead) this.state.errors.push(err);
  6407. return err;
  6408. } else {
  6409. throw err;
  6410. }
  6411. }
  6412. }
  6413. function isSimpleProperty(node) {
  6414. return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
  6415. }
  6416. var estree = (superClass => class extends superClass {
  6417. estreeParseRegExpLiteral({
  6418. pattern,
  6419. flags
  6420. }) {
  6421. let regex = null;
  6422. try {
  6423. regex = new RegExp(pattern, flags);
  6424. } catch (e) {}
  6425. const node = this.estreeParseLiteral(regex);
  6426. node.regex = {
  6427. pattern,
  6428. flags
  6429. };
  6430. return node;
  6431. }
  6432. estreeParseBigIntLiteral(value) {
  6433. const bigInt = typeof BigInt !== "undefined" ? BigInt(value) : null;
  6434. const node = this.estreeParseLiteral(bigInt);
  6435. node.bigint = String(node.value || value);
  6436. return node;
  6437. }
  6438. estreeParseDecimalLiteral(value) {
  6439. const decimal = null;
  6440. const node = this.estreeParseLiteral(decimal);
  6441. node.decimal = String(node.value || value);
  6442. return node;
  6443. }
  6444. estreeParseLiteral(value) {
  6445. return this.parseLiteral(value, "Literal");
  6446. }
  6447. directiveToStmt(directive) {
  6448. const directiveLiteral = directive.value;
  6449. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  6450. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  6451. expression.value = directiveLiteral.value;
  6452. expression.raw = directiveLiteral.extra.raw;
  6453. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  6454. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  6455. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  6456. }
  6457. initFunction(node, isAsync) {
  6458. super.initFunction(node, isAsync);
  6459. node.expression = false;
  6460. }
  6461. checkDeclaration(node) {
  6462. if (isSimpleProperty(node)) {
  6463. this.checkDeclaration(node.value);
  6464. } else {
  6465. super.checkDeclaration(node);
  6466. }
  6467. }
  6468. getObjectOrClassMethodParams(method) {
  6469. return method.value.params;
  6470. }
  6471. checkLVal(expr, contextDescription, ...args) {
  6472. switch (expr.type) {
  6473. case "ObjectPattern":
  6474. expr.properties.forEach(prop => {
  6475. this.checkLVal(prop.type === "Property" ? prop.value : prop, "object destructuring pattern", ...args);
  6476. });
  6477. break;
  6478. default:
  6479. super.checkLVal(expr, contextDescription, ...args);
  6480. }
  6481. }
  6482. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  6483. if (prop.method) {
  6484. return;
  6485. }
  6486. super.checkProto(prop, isRecord, protoRef, refExpressionErrors);
  6487. }
  6488. isValidDirective(stmt) {
  6489. var _stmt$expression$extr;
  6490. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) == null ? void 0 : _stmt$expression$extr.parenthesized);
  6491. }
  6492. stmtToDirective(stmt) {
  6493. const directive = super.stmtToDirective(stmt);
  6494. const value = stmt.expression.value;
  6495. directive.value.value = value;
  6496. return directive;
  6497. }
  6498. parseBlockBody(node, allowDirectives, topLevel, end) {
  6499. super.parseBlockBody(node, allowDirectives, topLevel, end);
  6500. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  6501. node.body = directiveStatements.concat(node.body);
  6502. delete node.directives;
  6503. }
  6504. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  6505. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  6506. if (method.typeParameters) {
  6507. method.value.typeParameters = method.typeParameters;
  6508. delete method.typeParameters;
  6509. }
  6510. classBody.body.push(method);
  6511. }
  6512. parseExprAtom(refExpressionErrors) {
  6513. switch (this.state.type) {
  6514. case types.num:
  6515. case types.string:
  6516. return this.estreeParseLiteral(this.state.value);
  6517. case types.regexp:
  6518. return this.estreeParseRegExpLiteral(this.state.value);
  6519. case types.bigint:
  6520. return this.estreeParseBigIntLiteral(this.state.value);
  6521. case types.decimal:
  6522. return this.estreeParseDecimalLiteral(this.state.value);
  6523. case types._null:
  6524. return this.estreeParseLiteral(null);
  6525. case types._true:
  6526. return this.estreeParseLiteral(true);
  6527. case types._false:
  6528. return this.estreeParseLiteral(false);
  6529. default:
  6530. return super.parseExprAtom(refExpressionErrors);
  6531. }
  6532. }
  6533. parseLiteral(value, type, startPos, startLoc) {
  6534. const node = super.parseLiteral(value, type, startPos, startLoc);
  6535. node.raw = node.extra.raw;
  6536. delete node.extra;
  6537. return node;
  6538. }
  6539. parseFunctionBody(node, allowExpression, isMethod = false) {
  6540. super.parseFunctionBody(node, allowExpression, isMethod);
  6541. node.expression = node.body.type !== "BlockStatement";
  6542. }
  6543. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  6544. let funcNode = this.startNode();
  6545. funcNode.kind = node.kind;
  6546. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  6547. funcNode.type = "FunctionExpression";
  6548. delete funcNode.kind;
  6549. node.value = funcNode;
  6550. type = type === "ClassMethod" ? "MethodDefinition" : type;
  6551. return this.finishNode(node, type);
  6552. }
  6553. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  6554. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  6555. if (node) {
  6556. node.type = "Property";
  6557. if (node.kind === "method") node.kind = "init";
  6558. node.shorthand = false;
  6559. }
  6560. return node;
  6561. }
  6562. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  6563. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  6564. if (node) {
  6565. node.kind = "init";
  6566. node.type = "Property";
  6567. }
  6568. return node;
  6569. }
  6570. toAssignable(node, isLHS = false) {
  6571. if (isSimpleProperty(node)) {
  6572. this.toAssignable(node.value);
  6573. return node;
  6574. }
  6575. return super.toAssignable(node, isLHS);
  6576. }
  6577. toAssignableObjectExpressionProp(prop, ...args) {
  6578. if (prop.kind === "get" || prop.kind === "set") {
  6579. throw this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  6580. } else if (prop.method) {
  6581. throw this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  6582. } else {
  6583. super.toAssignableObjectExpressionProp(prop, ...args);
  6584. }
  6585. }
  6586. finishCallExpression(node, optional) {
  6587. super.finishCallExpression(node, optional);
  6588. if (node.callee.type === "Import") {
  6589. node.type = "ImportExpression";
  6590. node.source = node.arguments[0];
  6591. delete node.arguments;
  6592. delete node.callee;
  6593. }
  6594. return node;
  6595. }
  6596. toReferencedArguments(node) {
  6597. if (node.type === "ImportExpression") {
  6598. return;
  6599. }
  6600. super.toReferencedArguments(node);
  6601. }
  6602. parseExport(node) {
  6603. super.parseExport(node);
  6604. switch (node.type) {
  6605. case "ExportAllDeclaration":
  6606. node.exported = null;
  6607. break;
  6608. case "ExportNamedDeclaration":
  6609. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  6610. node.type = "ExportAllDeclaration";
  6611. node.exported = node.specifiers[0].exported;
  6612. delete node.specifiers;
  6613. }
  6614. break;
  6615. }
  6616. return node;
  6617. }
  6618. parseSubscript(base, startPos, startLoc, noCalls, state) {
  6619. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  6620. if (state.optionalChainMember) {
  6621. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  6622. node.type = node.type.substring(8);
  6623. }
  6624. if (state.stop) {
  6625. const chain = this.startNodeAtNode(node);
  6626. chain.expression = node;
  6627. return this.finishNode(chain, "ChainExpression");
  6628. }
  6629. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  6630. node.optional = false;
  6631. }
  6632. return node;
  6633. }
  6634. });
  6635. class TokContext {
  6636. constructor(token, isExpr, preserveSpace, override) {
  6637. this.token = void 0;
  6638. this.isExpr = void 0;
  6639. this.preserveSpace = void 0;
  6640. this.override = void 0;
  6641. this.token = token;
  6642. this.isExpr = !!isExpr;
  6643. this.preserveSpace = !!preserveSpace;
  6644. this.override = override;
  6645. }
  6646. }
  6647. const types$1 = {
  6648. braceStatement: new TokContext("{", false),
  6649. braceExpression: new TokContext("{", true),
  6650. recordExpression: new TokContext("#{", true),
  6651. templateQuasi: new TokContext("${", false),
  6652. parenStatement: new TokContext("(", false),
  6653. parenExpression: new TokContext("(", true),
  6654. template: new TokContext("`", true, true, p => p.readTmplToken()),
  6655. functionExpression: new TokContext("function", true),
  6656. functionStatement: new TokContext("function", false)
  6657. };
  6658. types.parenR.updateContext = types.braceR.updateContext = function () {
  6659. if (this.state.context.length === 1) {
  6660. this.state.exprAllowed = true;
  6661. return;
  6662. }
  6663. let out = this.state.context.pop();
  6664. if (out === types$1.braceStatement && this.curContext().token === "function") {
  6665. out = this.state.context.pop();
  6666. }
  6667. this.state.exprAllowed = !out.isExpr;
  6668. };
  6669. types.name.updateContext = function (prevType) {
  6670. let allowed = false;
  6671. if (prevType !== types.dot) {
  6672. if (this.state.value === "of" && !this.state.exprAllowed && prevType !== types._function && prevType !== types._class) {
  6673. allowed = true;
  6674. }
  6675. }
  6676. this.state.exprAllowed = allowed;
  6677. if (this.state.isIterator) {
  6678. this.state.isIterator = false;
  6679. }
  6680. };
  6681. types.braceL.updateContext = function (prevType) {
  6682. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  6683. this.state.exprAllowed = true;
  6684. };
  6685. types.dollarBraceL.updateContext = function () {
  6686. this.state.context.push(types$1.templateQuasi);
  6687. this.state.exprAllowed = true;
  6688. };
  6689. types.parenL.updateContext = function (prevType) {
  6690. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  6691. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  6692. this.state.exprAllowed = true;
  6693. };
  6694. types.incDec.updateContext = function () {};
  6695. types._function.updateContext = types._class.updateContext = function (prevType) {
  6696. if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && this.hasPrecedingLineBreak()) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) {
  6697. this.state.context.push(types$1.functionExpression);
  6698. } else {
  6699. this.state.context.push(types$1.functionStatement);
  6700. }
  6701. this.state.exprAllowed = false;
  6702. };
  6703. types.backQuote.updateContext = function () {
  6704. if (this.curContext() === types$1.template) {
  6705. this.state.context.pop();
  6706. } else {
  6707. this.state.context.push(types$1.template);
  6708. }
  6709. this.state.exprAllowed = false;
  6710. };
  6711. types.braceHashL.updateContext = function () {
  6712. this.state.context.push(types$1.recordExpression);
  6713. this.state.exprAllowed = true;
  6714. };
  6715. 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\u08a0-\u08b4\u08b6-\u08c7\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\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\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-\u170c\u170e-\u1711\u1720-\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-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\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-\u2c2e\u2c30-\u2c5e\u2c60-\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-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\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";
  6716. let nonASCIIidentifierChars = "\u200c\u200d\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\u08d3-\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\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\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-\u0ecd\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-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\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-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\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";
  6717. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  6718. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  6719. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  6720. 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, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 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, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 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, 85, 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, 159, 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, 230, 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, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 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, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 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, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  6721. 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, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 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, 406, 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, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 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, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  6722. function isInAstralSet(code, set) {
  6723. let pos = 0x10000;
  6724. for (let i = 0, length = set.length; i < length; i += 2) {
  6725. pos += set[i];
  6726. if (pos > code) return false;
  6727. pos += set[i + 1];
  6728. if (pos >= code) return true;
  6729. }
  6730. return false;
  6731. }
  6732. function isIdentifierStart(code) {
  6733. if (code < 65) return code === 36;
  6734. if (code <= 90) return true;
  6735. if (code < 97) return code === 95;
  6736. if (code <= 122) return true;
  6737. if (code <= 0xffff) {
  6738. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  6739. }
  6740. return isInAstralSet(code, astralIdentifierStartCodes);
  6741. }
  6742. function isIdentifierChar(code) {
  6743. if (code < 48) return code === 36;
  6744. if (code < 58) return true;
  6745. if (code < 65) return false;
  6746. if (code <= 90) return true;
  6747. if (code < 97) return code === 95;
  6748. if (code <= 122) return true;
  6749. if (code <= 0xffff) {
  6750. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  6751. }
  6752. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  6753. }
  6754. const reservedWords = {
  6755. 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"],
  6756. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  6757. strictBind: ["eval", "arguments"]
  6758. };
  6759. const keywords$1 = new Set(reservedWords.keyword);
  6760. const reservedWordsStrictSet = new Set(reservedWords.strict);
  6761. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  6762. function isReservedWord(word, inModule) {
  6763. return inModule && word === "await" || word === "enum";
  6764. }
  6765. function isStrictReservedWord(word, inModule) {
  6766. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  6767. }
  6768. function isStrictBindOnlyReservedWord(word) {
  6769. return reservedWordsStrictBindSet.has(word);
  6770. }
  6771. function isStrictBindReservedWord(word, inModule) {
  6772. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  6773. }
  6774. function isKeyword(word) {
  6775. return keywords$1.has(word);
  6776. }
  6777. const keywordRelationalOperator = /^in(stanceof)?$/;
  6778. function isIteratorStart(current, next) {
  6779. return current === 64 && next === 64;
  6780. }
  6781. const SCOPE_OTHER = 0b00000000,
  6782. SCOPE_PROGRAM = 0b00000001,
  6783. SCOPE_FUNCTION = 0b00000010,
  6784. SCOPE_ARROW = 0b00000100,
  6785. SCOPE_SIMPLE_CATCH = 0b00001000,
  6786. SCOPE_SUPER = 0b00010000,
  6787. SCOPE_DIRECT_SUPER = 0b00100000,
  6788. SCOPE_CLASS = 0b01000000,
  6789. SCOPE_TS_MODULE = 0b10000000,
  6790. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  6791. const BIND_KIND_VALUE = 0b00000000001,
  6792. BIND_KIND_TYPE = 0b00000000010,
  6793. BIND_SCOPE_VAR = 0b00000000100,
  6794. BIND_SCOPE_LEXICAL = 0b00000001000,
  6795. BIND_SCOPE_FUNCTION = 0b00000010000,
  6796. BIND_FLAGS_NONE = 0b00001000000,
  6797. BIND_FLAGS_CLASS = 0b00010000000,
  6798. BIND_FLAGS_TS_ENUM = 0b00100000000,
  6799. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  6800. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  6801. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  6802. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  6803. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  6804. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  6805. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  6806. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  6807. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  6808. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  6809. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  6810. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  6811. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  6812. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
  6813. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  6814. CLASS_ELEMENT_KIND_GETTER = 0b010,
  6815. CLASS_ELEMENT_KIND_SETTER = 0b001,
  6816. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  6817. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  6818. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  6819. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  6820. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  6821. CLASS_ELEMENT_OTHER = 0;
  6822. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  6823. const FlowErrors = Object.freeze({
  6824. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  6825. 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",
  6826. AssignReservedType: "Cannot overwrite reserved type %0",
  6827. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  6828. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  6829. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  6830. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  6831. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  6832. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  6833. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  6834. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  6835. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  6836. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  6837. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  6838. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  6839. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  6840. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  6841. 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",
  6842. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  6843. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  6844. InexactVariance: "Explicit inexact syntax cannot have variance",
  6845. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  6846. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  6847. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  6848. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  6849. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  6850. SpreadVariance: "Spread properties cannot have variance",
  6851. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  6852. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  6853. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  6854. UnexpectedReservedType: "Unexpected reserved type %0",
  6855. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  6856. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  6857. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  6858. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  6859. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  6860. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
  6861. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  6862. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  6863. UnterminatedFlowComment: "Unterminated flow-comment"
  6864. });
  6865. function isEsModuleType(bodyElement) {
  6866. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  6867. }
  6868. function hasTypeImportKind(node) {
  6869. return node.importKind === "type" || node.importKind === "typeof";
  6870. }
  6871. function isMaybeDefaultImport(state) {
  6872. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  6873. }
  6874. const exportSuggestions = {
  6875. const: "declare export var",
  6876. let: "declare export var",
  6877. type: "export type",
  6878. interface: "export interface"
  6879. };
  6880. function partition(list, test) {
  6881. const list1 = [];
  6882. const list2 = [];
  6883. for (let i = 0; i < list.length; i++) {
  6884. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  6885. }
  6886. return [list1, list2];
  6887. }
  6888. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  6889. var flow = (superClass => {
  6890. var _temp;
  6891. return _temp = class extends superClass {
  6892. constructor(options, input) {
  6893. super(options, input);
  6894. this.flowPragma = void 0;
  6895. this.flowPragma = undefined;
  6896. }
  6897. shouldParseTypes() {
  6898. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  6899. }
  6900. shouldParseEnums() {
  6901. return !!this.getPluginOption("flow", "enums");
  6902. }
  6903. finishToken(type, val) {
  6904. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  6905. if (this.flowPragma === undefined) {
  6906. this.flowPragma = null;
  6907. }
  6908. }
  6909. return super.finishToken(type, val);
  6910. }
  6911. addComment(comment) {
  6912. if (this.flowPragma === undefined) {
  6913. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  6914. if (!matches) ; else if (matches[1] === "flow") {
  6915. this.flowPragma = "flow";
  6916. } else if (matches[1] === "noflow") {
  6917. this.flowPragma = "noflow";
  6918. } else {
  6919. throw new Error("Unexpected flow pragma");
  6920. }
  6921. }
  6922. return super.addComment(comment);
  6923. }
  6924. flowParseTypeInitialiser(tok) {
  6925. const oldInType = this.state.inType;
  6926. this.state.inType = true;
  6927. this.expect(tok || types.colon);
  6928. const type = this.flowParseType();
  6929. this.state.inType = oldInType;
  6930. return type;
  6931. }
  6932. flowParsePredicate() {
  6933. const node = this.startNode();
  6934. const moduloLoc = this.state.startLoc;
  6935. const moduloPos = this.state.start;
  6936. this.expect(types.modulo);
  6937. const checksLoc = this.state.startLoc;
  6938. this.expectContextual("checks");
  6939. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  6940. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  6941. }
  6942. if (this.eat(types.parenL)) {
  6943. node.value = this.parseExpression();
  6944. this.expect(types.parenR);
  6945. return this.finishNode(node, "DeclaredPredicate");
  6946. } else {
  6947. return this.finishNode(node, "InferredPredicate");
  6948. }
  6949. }
  6950. flowParseTypeAndPredicateInitialiser() {
  6951. const oldInType = this.state.inType;
  6952. this.state.inType = true;
  6953. this.expect(types.colon);
  6954. let type = null;
  6955. let predicate = null;
  6956. if (this.match(types.modulo)) {
  6957. this.state.inType = oldInType;
  6958. predicate = this.flowParsePredicate();
  6959. } else {
  6960. type = this.flowParseType();
  6961. this.state.inType = oldInType;
  6962. if (this.match(types.modulo)) {
  6963. predicate = this.flowParsePredicate();
  6964. }
  6965. }
  6966. return [type, predicate];
  6967. }
  6968. flowParseDeclareClass(node) {
  6969. this.next();
  6970. this.flowParseInterfaceish(node, true);
  6971. return this.finishNode(node, "DeclareClass");
  6972. }
  6973. flowParseDeclareFunction(node) {
  6974. this.next();
  6975. const id = node.id = this.parseIdentifier();
  6976. const typeNode = this.startNode();
  6977. const typeContainer = this.startNode();
  6978. if (this.isRelational("<")) {
  6979. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  6980. } else {
  6981. typeNode.typeParameters = null;
  6982. }
  6983. this.expect(types.parenL);
  6984. const tmp = this.flowParseFunctionTypeParams();
  6985. typeNode.params = tmp.params;
  6986. typeNode.rest = tmp.rest;
  6987. this.expect(types.parenR);
  6988. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  6989. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  6990. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  6991. this.resetEndLocation(id);
  6992. this.semicolon();
  6993. return this.finishNode(node, "DeclareFunction");
  6994. }
  6995. flowParseDeclare(node, insideModule) {
  6996. if (this.match(types._class)) {
  6997. return this.flowParseDeclareClass(node);
  6998. } else if (this.match(types._function)) {
  6999. return this.flowParseDeclareFunction(node);
  7000. } else if (this.match(types._var)) {
  7001. return this.flowParseDeclareVariable(node);
  7002. } else if (this.eatContextual("module")) {
  7003. if (this.match(types.dot)) {
  7004. return this.flowParseDeclareModuleExports(node);
  7005. } else {
  7006. if (insideModule) {
  7007. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  7008. }
  7009. return this.flowParseDeclareModule(node);
  7010. }
  7011. } else if (this.isContextual("type")) {
  7012. return this.flowParseDeclareTypeAlias(node);
  7013. } else if (this.isContextual("opaque")) {
  7014. return this.flowParseDeclareOpaqueType(node);
  7015. } else if (this.isContextual("interface")) {
  7016. return this.flowParseDeclareInterface(node);
  7017. } else if (this.match(types._export)) {
  7018. return this.flowParseDeclareExportDeclaration(node, insideModule);
  7019. } else {
  7020. throw this.unexpected();
  7021. }
  7022. }
  7023. flowParseDeclareVariable(node) {
  7024. this.next();
  7025. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  7026. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  7027. this.semicolon();
  7028. return this.finishNode(node, "DeclareVariable");
  7029. }
  7030. flowParseDeclareModule(node) {
  7031. this.scope.enter(SCOPE_OTHER);
  7032. if (this.match(types.string)) {
  7033. node.id = this.parseExprAtom();
  7034. } else {
  7035. node.id = this.parseIdentifier();
  7036. }
  7037. const bodyNode = node.body = this.startNode();
  7038. const body = bodyNode.body = [];
  7039. this.expect(types.braceL);
  7040. while (!this.match(types.braceR)) {
  7041. let bodyNode = this.startNode();
  7042. if (this.match(types._import)) {
  7043. this.next();
  7044. if (!this.isContextual("type") && !this.match(types._typeof)) {
  7045. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  7046. }
  7047. this.parseImport(bodyNode);
  7048. } else {
  7049. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  7050. bodyNode = this.flowParseDeclare(bodyNode, true);
  7051. }
  7052. body.push(bodyNode);
  7053. }
  7054. this.scope.exit();
  7055. this.expect(types.braceR);
  7056. this.finishNode(bodyNode, "BlockStatement");
  7057. let kind = null;
  7058. let hasModuleExport = false;
  7059. body.forEach(bodyElement => {
  7060. if (isEsModuleType(bodyElement)) {
  7061. if (kind === "CommonJS") {
  7062. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  7063. }
  7064. kind = "ES";
  7065. } else if (bodyElement.type === "DeclareModuleExports") {
  7066. if (hasModuleExport) {
  7067. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  7068. }
  7069. if (kind === "ES") {
  7070. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  7071. }
  7072. kind = "CommonJS";
  7073. hasModuleExport = true;
  7074. }
  7075. });
  7076. node.kind = kind || "CommonJS";
  7077. return this.finishNode(node, "DeclareModule");
  7078. }
  7079. flowParseDeclareExportDeclaration(node, insideModule) {
  7080. this.expect(types._export);
  7081. if (this.eat(types._default)) {
  7082. if (this.match(types._function) || this.match(types._class)) {
  7083. node.declaration = this.flowParseDeclare(this.startNode());
  7084. } else {
  7085. node.declaration = this.flowParseType();
  7086. this.semicolon();
  7087. }
  7088. node.default = true;
  7089. return this.finishNode(node, "DeclareExportDeclaration");
  7090. } else {
  7091. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  7092. const label = this.state.value;
  7093. const suggestion = exportSuggestions[label];
  7094. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  7095. }
  7096. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  7097. node.declaration = this.flowParseDeclare(this.startNode());
  7098. node.default = false;
  7099. return this.finishNode(node, "DeclareExportDeclaration");
  7100. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  7101. node = this.parseExport(node);
  7102. if (node.type === "ExportNamedDeclaration") {
  7103. node.type = "ExportDeclaration";
  7104. node.default = false;
  7105. delete node.exportKind;
  7106. }
  7107. node.type = "Declare" + node.type;
  7108. return node;
  7109. }
  7110. }
  7111. throw this.unexpected();
  7112. }
  7113. flowParseDeclareModuleExports(node) {
  7114. this.next();
  7115. this.expectContextual("exports");
  7116. node.typeAnnotation = this.flowParseTypeAnnotation();
  7117. this.semicolon();
  7118. return this.finishNode(node, "DeclareModuleExports");
  7119. }
  7120. flowParseDeclareTypeAlias(node) {
  7121. this.next();
  7122. this.flowParseTypeAlias(node);
  7123. node.type = "DeclareTypeAlias";
  7124. return node;
  7125. }
  7126. flowParseDeclareOpaqueType(node) {
  7127. this.next();
  7128. this.flowParseOpaqueType(node, true);
  7129. node.type = "DeclareOpaqueType";
  7130. return node;
  7131. }
  7132. flowParseDeclareInterface(node) {
  7133. this.next();
  7134. this.flowParseInterfaceish(node);
  7135. return this.finishNode(node, "DeclareInterface");
  7136. }
  7137. flowParseInterfaceish(node, isClass = false) {
  7138. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  7139. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  7140. if (this.isRelational("<")) {
  7141. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7142. } else {
  7143. node.typeParameters = null;
  7144. }
  7145. node.extends = [];
  7146. node.implements = [];
  7147. node.mixins = [];
  7148. if (this.eat(types._extends)) {
  7149. do {
  7150. node.extends.push(this.flowParseInterfaceExtends());
  7151. } while (!isClass && this.eat(types.comma));
  7152. }
  7153. if (this.isContextual("mixins")) {
  7154. this.next();
  7155. do {
  7156. node.mixins.push(this.flowParseInterfaceExtends());
  7157. } while (this.eat(types.comma));
  7158. }
  7159. if (this.isContextual("implements")) {
  7160. this.next();
  7161. do {
  7162. node.implements.push(this.flowParseInterfaceExtends());
  7163. } while (this.eat(types.comma));
  7164. }
  7165. node.body = this.flowParseObjectType({
  7166. allowStatic: isClass,
  7167. allowExact: false,
  7168. allowSpread: false,
  7169. allowProto: isClass,
  7170. allowInexact: false
  7171. });
  7172. }
  7173. flowParseInterfaceExtends() {
  7174. const node = this.startNode();
  7175. node.id = this.flowParseQualifiedTypeIdentifier();
  7176. if (this.isRelational("<")) {
  7177. node.typeParameters = this.flowParseTypeParameterInstantiation();
  7178. } else {
  7179. node.typeParameters = null;
  7180. }
  7181. return this.finishNode(node, "InterfaceExtends");
  7182. }
  7183. flowParseInterface(node) {
  7184. this.flowParseInterfaceish(node);
  7185. return this.finishNode(node, "InterfaceDeclaration");
  7186. }
  7187. checkNotUnderscore(word) {
  7188. if (word === "_") {
  7189. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  7190. }
  7191. }
  7192. checkReservedType(word, startLoc, declaration) {
  7193. if (!reservedTypes.has(word)) return;
  7194. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  7195. }
  7196. flowParseRestrictedIdentifier(liberal, declaration) {
  7197. this.checkReservedType(this.state.value, this.state.start, declaration);
  7198. return this.parseIdentifier(liberal);
  7199. }
  7200. flowParseTypeAlias(node) {
  7201. node.id = this.flowParseRestrictedIdentifier(false, true);
  7202. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  7203. if (this.isRelational("<")) {
  7204. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7205. } else {
  7206. node.typeParameters = null;
  7207. }
  7208. node.right = this.flowParseTypeInitialiser(types.eq);
  7209. this.semicolon();
  7210. return this.finishNode(node, "TypeAlias");
  7211. }
  7212. flowParseOpaqueType(node, declare) {
  7213. this.expectContextual("type");
  7214. node.id = this.flowParseRestrictedIdentifier(true, true);
  7215. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  7216. if (this.isRelational("<")) {
  7217. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7218. } else {
  7219. node.typeParameters = null;
  7220. }
  7221. node.supertype = null;
  7222. if (this.match(types.colon)) {
  7223. node.supertype = this.flowParseTypeInitialiser(types.colon);
  7224. }
  7225. node.impltype = null;
  7226. if (!declare) {
  7227. node.impltype = this.flowParseTypeInitialiser(types.eq);
  7228. }
  7229. this.semicolon();
  7230. return this.finishNode(node, "OpaqueType");
  7231. }
  7232. flowParseTypeParameter(requireDefault = false) {
  7233. const nodeStart = this.state.start;
  7234. const node = this.startNode();
  7235. const variance = this.flowParseVariance();
  7236. const ident = this.flowParseTypeAnnotatableIdentifier();
  7237. node.name = ident.name;
  7238. node.variance = variance;
  7239. node.bound = ident.typeAnnotation;
  7240. if (this.match(types.eq)) {
  7241. this.eat(types.eq);
  7242. node.default = this.flowParseType();
  7243. } else {
  7244. if (requireDefault) {
  7245. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  7246. }
  7247. }
  7248. return this.finishNode(node, "TypeParameter");
  7249. }
  7250. flowParseTypeParameterDeclaration() {
  7251. const oldInType = this.state.inType;
  7252. const node = this.startNode();
  7253. node.params = [];
  7254. this.state.inType = true;
  7255. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  7256. this.next();
  7257. } else {
  7258. this.unexpected();
  7259. }
  7260. let defaultRequired = false;
  7261. do {
  7262. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  7263. node.params.push(typeParameter);
  7264. if (typeParameter.default) {
  7265. defaultRequired = true;
  7266. }
  7267. if (!this.isRelational(">")) {
  7268. this.expect(types.comma);
  7269. }
  7270. } while (!this.isRelational(">"));
  7271. this.expectRelational(">");
  7272. this.state.inType = oldInType;
  7273. return this.finishNode(node, "TypeParameterDeclaration");
  7274. }
  7275. flowParseTypeParameterInstantiation() {
  7276. const node = this.startNode();
  7277. const oldInType = this.state.inType;
  7278. node.params = [];
  7279. this.state.inType = true;
  7280. this.expectRelational("<");
  7281. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  7282. this.state.noAnonFunctionType = false;
  7283. while (!this.isRelational(">")) {
  7284. node.params.push(this.flowParseType());
  7285. if (!this.isRelational(">")) {
  7286. this.expect(types.comma);
  7287. }
  7288. }
  7289. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7290. this.expectRelational(">");
  7291. this.state.inType = oldInType;
  7292. return this.finishNode(node, "TypeParameterInstantiation");
  7293. }
  7294. flowParseTypeParameterInstantiationCallOrNew() {
  7295. const node = this.startNode();
  7296. const oldInType = this.state.inType;
  7297. node.params = [];
  7298. this.state.inType = true;
  7299. this.expectRelational("<");
  7300. while (!this.isRelational(">")) {
  7301. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  7302. if (!this.isRelational(">")) {
  7303. this.expect(types.comma);
  7304. }
  7305. }
  7306. this.expectRelational(">");
  7307. this.state.inType = oldInType;
  7308. return this.finishNode(node, "TypeParameterInstantiation");
  7309. }
  7310. flowParseInterfaceType() {
  7311. const node = this.startNode();
  7312. this.expectContextual("interface");
  7313. node.extends = [];
  7314. if (this.eat(types._extends)) {
  7315. do {
  7316. node.extends.push(this.flowParseInterfaceExtends());
  7317. } while (this.eat(types.comma));
  7318. }
  7319. node.body = this.flowParseObjectType({
  7320. allowStatic: false,
  7321. allowExact: false,
  7322. allowSpread: false,
  7323. allowProto: false,
  7324. allowInexact: false
  7325. });
  7326. return this.finishNode(node, "InterfaceTypeAnnotation");
  7327. }
  7328. flowParseObjectPropertyKey() {
  7329. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  7330. }
  7331. flowParseObjectTypeIndexer(node, isStatic, variance) {
  7332. node.static = isStatic;
  7333. if (this.lookahead().type === types.colon) {
  7334. node.id = this.flowParseObjectPropertyKey();
  7335. node.key = this.flowParseTypeInitialiser();
  7336. } else {
  7337. node.id = null;
  7338. node.key = this.flowParseType();
  7339. }
  7340. this.expect(types.bracketR);
  7341. node.value = this.flowParseTypeInitialiser();
  7342. node.variance = variance;
  7343. return this.finishNode(node, "ObjectTypeIndexer");
  7344. }
  7345. flowParseObjectTypeInternalSlot(node, isStatic) {
  7346. node.static = isStatic;
  7347. node.id = this.flowParseObjectPropertyKey();
  7348. this.expect(types.bracketR);
  7349. this.expect(types.bracketR);
  7350. if (this.isRelational("<") || this.match(types.parenL)) {
  7351. node.method = true;
  7352. node.optional = false;
  7353. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  7354. } else {
  7355. node.method = false;
  7356. if (this.eat(types.question)) {
  7357. node.optional = true;
  7358. }
  7359. node.value = this.flowParseTypeInitialiser();
  7360. }
  7361. return this.finishNode(node, "ObjectTypeInternalSlot");
  7362. }
  7363. flowParseObjectTypeMethodish(node) {
  7364. node.params = [];
  7365. node.rest = null;
  7366. node.typeParameters = null;
  7367. if (this.isRelational("<")) {
  7368. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7369. }
  7370. this.expect(types.parenL);
  7371. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  7372. node.params.push(this.flowParseFunctionTypeParam());
  7373. if (!this.match(types.parenR)) {
  7374. this.expect(types.comma);
  7375. }
  7376. }
  7377. if (this.eat(types.ellipsis)) {
  7378. node.rest = this.flowParseFunctionTypeParam();
  7379. }
  7380. this.expect(types.parenR);
  7381. node.returnType = this.flowParseTypeInitialiser();
  7382. return this.finishNode(node, "FunctionTypeAnnotation");
  7383. }
  7384. flowParseObjectTypeCallProperty(node, isStatic) {
  7385. const valueNode = this.startNode();
  7386. node.static = isStatic;
  7387. node.value = this.flowParseObjectTypeMethodish(valueNode);
  7388. return this.finishNode(node, "ObjectTypeCallProperty");
  7389. }
  7390. flowParseObjectType({
  7391. allowStatic,
  7392. allowExact,
  7393. allowSpread,
  7394. allowProto,
  7395. allowInexact
  7396. }) {
  7397. const oldInType = this.state.inType;
  7398. this.state.inType = true;
  7399. const nodeStart = this.startNode();
  7400. nodeStart.callProperties = [];
  7401. nodeStart.properties = [];
  7402. nodeStart.indexers = [];
  7403. nodeStart.internalSlots = [];
  7404. let endDelim;
  7405. let exact;
  7406. let inexact = false;
  7407. if (allowExact && this.match(types.braceBarL)) {
  7408. this.expect(types.braceBarL);
  7409. endDelim = types.braceBarR;
  7410. exact = true;
  7411. } else {
  7412. this.expect(types.braceL);
  7413. endDelim = types.braceR;
  7414. exact = false;
  7415. }
  7416. nodeStart.exact = exact;
  7417. while (!this.match(endDelim)) {
  7418. let isStatic = false;
  7419. let protoStart = null;
  7420. let inexactStart = null;
  7421. const node = this.startNode();
  7422. if (allowProto && this.isContextual("proto")) {
  7423. const lookahead = this.lookahead();
  7424. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  7425. this.next();
  7426. protoStart = this.state.start;
  7427. allowStatic = false;
  7428. }
  7429. }
  7430. if (allowStatic && this.isContextual("static")) {
  7431. const lookahead = this.lookahead();
  7432. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  7433. this.next();
  7434. isStatic = true;
  7435. }
  7436. }
  7437. const variance = this.flowParseVariance();
  7438. if (this.eat(types.bracketL)) {
  7439. if (protoStart != null) {
  7440. this.unexpected(protoStart);
  7441. }
  7442. if (this.eat(types.bracketL)) {
  7443. if (variance) {
  7444. this.unexpected(variance.start);
  7445. }
  7446. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  7447. } else {
  7448. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  7449. }
  7450. } else if (this.match(types.parenL) || this.isRelational("<")) {
  7451. if (protoStart != null) {
  7452. this.unexpected(protoStart);
  7453. }
  7454. if (variance) {
  7455. this.unexpected(variance.start);
  7456. }
  7457. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  7458. } else {
  7459. let kind = "init";
  7460. if (this.isContextual("get") || this.isContextual("set")) {
  7461. const lookahead = this.lookahead();
  7462. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  7463. kind = this.state.value;
  7464. this.next();
  7465. }
  7466. }
  7467. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  7468. if (propOrInexact === null) {
  7469. inexact = true;
  7470. inexactStart = this.state.lastTokStart;
  7471. } else {
  7472. nodeStart.properties.push(propOrInexact);
  7473. }
  7474. }
  7475. this.flowObjectTypeSemicolon();
  7476. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  7477. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  7478. }
  7479. }
  7480. this.expect(endDelim);
  7481. if (allowSpread) {
  7482. nodeStart.inexact = inexact;
  7483. }
  7484. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  7485. this.state.inType = oldInType;
  7486. return out;
  7487. }
  7488. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  7489. if (this.eat(types.ellipsis)) {
  7490. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  7491. if (isInexactToken) {
  7492. if (!allowSpread) {
  7493. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  7494. } else if (!allowInexact) {
  7495. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  7496. }
  7497. if (variance) {
  7498. this.raise(variance.start, FlowErrors.InexactVariance);
  7499. }
  7500. return null;
  7501. }
  7502. if (!allowSpread) {
  7503. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  7504. }
  7505. if (protoStart != null) {
  7506. this.unexpected(protoStart);
  7507. }
  7508. if (variance) {
  7509. this.raise(variance.start, FlowErrors.SpreadVariance);
  7510. }
  7511. node.argument = this.flowParseType();
  7512. return this.finishNode(node, "ObjectTypeSpreadProperty");
  7513. } else {
  7514. node.key = this.flowParseObjectPropertyKey();
  7515. node.static = isStatic;
  7516. node.proto = protoStart != null;
  7517. node.kind = kind;
  7518. let optional = false;
  7519. if (this.isRelational("<") || this.match(types.parenL)) {
  7520. node.method = true;
  7521. if (protoStart != null) {
  7522. this.unexpected(protoStart);
  7523. }
  7524. if (variance) {
  7525. this.unexpected(variance.start);
  7526. }
  7527. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  7528. if (kind === "get" || kind === "set") {
  7529. this.flowCheckGetterSetterParams(node);
  7530. }
  7531. } else {
  7532. if (kind !== "init") this.unexpected();
  7533. node.method = false;
  7534. if (this.eat(types.question)) {
  7535. optional = true;
  7536. }
  7537. node.value = this.flowParseTypeInitialiser();
  7538. node.variance = variance;
  7539. }
  7540. node.optional = optional;
  7541. return this.finishNode(node, "ObjectTypeProperty");
  7542. }
  7543. }
  7544. flowCheckGetterSetterParams(property) {
  7545. const paramCount = property.kind === "get" ? 0 : 1;
  7546. const start = property.start;
  7547. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  7548. if (length !== paramCount) {
  7549. if (property.kind === "get") {
  7550. this.raise(start, ErrorMessages.BadGetterArity);
  7551. } else {
  7552. this.raise(start, ErrorMessages.BadSetterArity);
  7553. }
  7554. }
  7555. if (property.kind === "set" && property.value.rest) {
  7556. this.raise(start, ErrorMessages.BadSetterRestParameter);
  7557. }
  7558. }
  7559. flowObjectTypeSemicolon() {
  7560. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  7561. this.unexpected();
  7562. }
  7563. }
  7564. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  7565. startPos = startPos || this.state.start;
  7566. startLoc = startLoc || this.state.startLoc;
  7567. let node = id || this.flowParseRestrictedIdentifier(true);
  7568. while (this.eat(types.dot)) {
  7569. const node2 = this.startNodeAt(startPos, startLoc);
  7570. node2.qualification = node;
  7571. node2.id = this.flowParseRestrictedIdentifier(true);
  7572. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  7573. }
  7574. return node;
  7575. }
  7576. flowParseGenericType(startPos, startLoc, id) {
  7577. const node = this.startNodeAt(startPos, startLoc);
  7578. node.typeParameters = null;
  7579. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  7580. if (this.isRelational("<")) {
  7581. node.typeParameters = this.flowParseTypeParameterInstantiation();
  7582. }
  7583. return this.finishNode(node, "GenericTypeAnnotation");
  7584. }
  7585. flowParseTypeofType() {
  7586. const node = this.startNode();
  7587. this.expect(types._typeof);
  7588. node.argument = this.flowParsePrimaryType();
  7589. return this.finishNode(node, "TypeofTypeAnnotation");
  7590. }
  7591. flowParseTupleType() {
  7592. const node = this.startNode();
  7593. node.types = [];
  7594. this.expect(types.bracketL);
  7595. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  7596. node.types.push(this.flowParseType());
  7597. if (this.match(types.bracketR)) break;
  7598. this.expect(types.comma);
  7599. }
  7600. this.expect(types.bracketR);
  7601. return this.finishNode(node, "TupleTypeAnnotation");
  7602. }
  7603. flowParseFunctionTypeParam() {
  7604. let name = null;
  7605. let optional = false;
  7606. let typeAnnotation = null;
  7607. const node = this.startNode();
  7608. const lh = this.lookahead();
  7609. if (lh.type === types.colon || lh.type === types.question) {
  7610. name = this.parseIdentifier();
  7611. if (this.eat(types.question)) {
  7612. optional = true;
  7613. }
  7614. typeAnnotation = this.flowParseTypeInitialiser();
  7615. } else {
  7616. typeAnnotation = this.flowParseType();
  7617. }
  7618. node.name = name;
  7619. node.optional = optional;
  7620. node.typeAnnotation = typeAnnotation;
  7621. return this.finishNode(node, "FunctionTypeParam");
  7622. }
  7623. reinterpretTypeAsFunctionTypeParam(type) {
  7624. const node = this.startNodeAt(type.start, type.loc.start);
  7625. node.name = null;
  7626. node.optional = false;
  7627. node.typeAnnotation = type;
  7628. return this.finishNode(node, "FunctionTypeParam");
  7629. }
  7630. flowParseFunctionTypeParams(params = []) {
  7631. let rest = null;
  7632. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  7633. params.push(this.flowParseFunctionTypeParam());
  7634. if (!this.match(types.parenR)) {
  7635. this.expect(types.comma);
  7636. }
  7637. }
  7638. if (this.eat(types.ellipsis)) {
  7639. rest = this.flowParseFunctionTypeParam();
  7640. }
  7641. return {
  7642. params,
  7643. rest
  7644. };
  7645. }
  7646. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  7647. switch (id.name) {
  7648. case "any":
  7649. return this.finishNode(node, "AnyTypeAnnotation");
  7650. case "bool":
  7651. case "boolean":
  7652. return this.finishNode(node, "BooleanTypeAnnotation");
  7653. case "mixed":
  7654. return this.finishNode(node, "MixedTypeAnnotation");
  7655. case "empty":
  7656. return this.finishNode(node, "EmptyTypeAnnotation");
  7657. case "number":
  7658. return this.finishNode(node, "NumberTypeAnnotation");
  7659. case "string":
  7660. return this.finishNode(node, "StringTypeAnnotation");
  7661. case "symbol":
  7662. return this.finishNode(node, "SymbolTypeAnnotation");
  7663. default:
  7664. this.checkNotUnderscore(id.name);
  7665. return this.flowParseGenericType(startPos, startLoc, id);
  7666. }
  7667. }
  7668. flowParsePrimaryType() {
  7669. const startPos = this.state.start;
  7670. const startLoc = this.state.startLoc;
  7671. const node = this.startNode();
  7672. let tmp;
  7673. let type;
  7674. let isGroupedType = false;
  7675. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  7676. switch (this.state.type) {
  7677. case types.name:
  7678. if (this.isContextual("interface")) {
  7679. return this.flowParseInterfaceType();
  7680. }
  7681. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  7682. case types.braceL:
  7683. return this.flowParseObjectType({
  7684. allowStatic: false,
  7685. allowExact: false,
  7686. allowSpread: true,
  7687. allowProto: false,
  7688. allowInexact: true
  7689. });
  7690. case types.braceBarL:
  7691. return this.flowParseObjectType({
  7692. allowStatic: false,
  7693. allowExact: true,
  7694. allowSpread: true,
  7695. allowProto: false,
  7696. allowInexact: false
  7697. });
  7698. case types.bracketL:
  7699. this.state.noAnonFunctionType = false;
  7700. type = this.flowParseTupleType();
  7701. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7702. return type;
  7703. case types.relational:
  7704. if (this.state.value === "<") {
  7705. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7706. this.expect(types.parenL);
  7707. tmp = this.flowParseFunctionTypeParams();
  7708. node.params = tmp.params;
  7709. node.rest = tmp.rest;
  7710. this.expect(types.parenR);
  7711. this.expect(types.arrow);
  7712. node.returnType = this.flowParseType();
  7713. return this.finishNode(node, "FunctionTypeAnnotation");
  7714. }
  7715. break;
  7716. case types.parenL:
  7717. this.next();
  7718. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  7719. if (this.match(types.name)) {
  7720. const token = this.lookahead().type;
  7721. isGroupedType = token !== types.question && token !== types.colon;
  7722. } else {
  7723. isGroupedType = true;
  7724. }
  7725. }
  7726. if (isGroupedType) {
  7727. this.state.noAnonFunctionType = false;
  7728. type = this.flowParseType();
  7729. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7730. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  7731. this.expect(types.parenR);
  7732. return type;
  7733. } else {
  7734. this.eat(types.comma);
  7735. }
  7736. }
  7737. if (type) {
  7738. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  7739. } else {
  7740. tmp = this.flowParseFunctionTypeParams();
  7741. }
  7742. node.params = tmp.params;
  7743. node.rest = tmp.rest;
  7744. this.expect(types.parenR);
  7745. this.expect(types.arrow);
  7746. node.returnType = this.flowParseType();
  7747. node.typeParameters = null;
  7748. return this.finishNode(node, "FunctionTypeAnnotation");
  7749. case types.string:
  7750. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  7751. case types._true:
  7752. case types._false:
  7753. node.value = this.match(types._true);
  7754. this.next();
  7755. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  7756. case types.plusMin:
  7757. if (this.state.value === "-") {
  7758. this.next();
  7759. if (this.match(types.num)) {
  7760. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  7761. }
  7762. if (this.match(types.bigint)) {
  7763. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  7764. }
  7765. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  7766. }
  7767. throw this.unexpected();
  7768. case types.num:
  7769. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  7770. case types.bigint:
  7771. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  7772. case types._void:
  7773. this.next();
  7774. return this.finishNode(node, "VoidTypeAnnotation");
  7775. case types._null:
  7776. this.next();
  7777. return this.finishNode(node, "NullLiteralTypeAnnotation");
  7778. case types._this:
  7779. this.next();
  7780. return this.finishNode(node, "ThisTypeAnnotation");
  7781. case types.star:
  7782. this.next();
  7783. return this.finishNode(node, "ExistsTypeAnnotation");
  7784. default:
  7785. if (this.state.type.keyword === "typeof") {
  7786. return this.flowParseTypeofType();
  7787. } else if (this.state.type.keyword) {
  7788. const label = this.state.type.label;
  7789. this.next();
  7790. return super.createIdentifier(node, label);
  7791. }
  7792. }
  7793. throw this.unexpected();
  7794. }
  7795. flowParsePostfixType() {
  7796. const startPos = this.state.start,
  7797. startLoc = this.state.startLoc;
  7798. let type = this.flowParsePrimaryType();
  7799. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  7800. const node = this.startNodeAt(startPos, startLoc);
  7801. node.elementType = type;
  7802. this.expect(types.bracketL);
  7803. this.expect(types.bracketR);
  7804. type = this.finishNode(node, "ArrayTypeAnnotation");
  7805. }
  7806. return type;
  7807. }
  7808. flowParsePrefixType() {
  7809. const node = this.startNode();
  7810. if (this.eat(types.question)) {
  7811. node.typeAnnotation = this.flowParsePrefixType();
  7812. return this.finishNode(node, "NullableTypeAnnotation");
  7813. } else {
  7814. return this.flowParsePostfixType();
  7815. }
  7816. }
  7817. flowParseAnonFunctionWithoutParens() {
  7818. const param = this.flowParsePrefixType();
  7819. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  7820. const node = this.startNodeAt(param.start, param.loc.start);
  7821. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  7822. node.rest = null;
  7823. node.returnType = this.flowParseType();
  7824. node.typeParameters = null;
  7825. return this.finishNode(node, "FunctionTypeAnnotation");
  7826. }
  7827. return param;
  7828. }
  7829. flowParseIntersectionType() {
  7830. const node = this.startNode();
  7831. this.eat(types.bitwiseAND);
  7832. const type = this.flowParseAnonFunctionWithoutParens();
  7833. node.types = [type];
  7834. while (this.eat(types.bitwiseAND)) {
  7835. node.types.push(this.flowParseAnonFunctionWithoutParens());
  7836. }
  7837. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  7838. }
  7839. flowParseUnionType() {
  7840. const node = this.startNode();
  7841. this.eat(types.bitwiseOR);
  7842. const type = this.flowParseIntersectionType();
  7843. node.types = [type];
  7844. while (this.eat(types.bitwiseOR)) {
  7845. node.types.push(this.flowParseIntersectionType());
  7846. }
  7847. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  7848. }
  7849. flowParseType() {
  7850. const oldInType = this.state.inType;
  7851. this.state.inType = true;
  7852. const type = this.flowParseUnionType();
  7853. this.state.inType = oldInType;
  7854. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  7855. return type;
  7856. }
  7857. flowParseTypeOrImplicitInstantiation() {
  7858. if (this.state.type === types.name && this.state.value === "_") {
  7859. const startPos = this.state.start;
  7860. const startLoc = this.state.startLoc;
  7861. const node = this.parseIdentifier();
  7862. return this.flowParseGenericType(startPos, startLoc, node);
  7863. } else {
  7864. return this.flowParseType();
  7865. }
  7866. }
  7867. flowParseTypeAnnotation() {
  7868. const node = this.startNode();
  7869. node.typeAnnotation = this.flowParseTypeInitialiser();
  7870. return this.finishNode(node, "TypeAnnotation");
  7871. }
  7872. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  7873. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  7874. if (this.match(types.colon)) {
  7875. ident.typeAnnotation = this.flowParseTypeAnnotation();
  7876. this.resetEndLocation(ident);
  7877. }
  7878. return ident;
  7879. }
  7880. typeCastToParameter(node) {
  7881. node.expression.typeAnnotation = node.typeAnnotation;
  7882. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  7883. return node.expression;
  7884. }
  7885. flowParseVariance() {
  7886. let variance = null;
  7887. if (this.match(types.plusMin)) {
  7888. variance = this.startNode();
  7889. if (this.state.value === "+") {
  7890. variance.kind = "plus";
  7891. } else {
  7892. variance.kind = "minus";
  7893. }
  7894. this.next();
  7895. this.finishNode(variance, "Variance");
  7896. }
  7897. return variance;
  7898. }
  7899. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  7900. if (allowExpressionBody) {
  7901. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  7902. }
  7903. return super.parseFunctionBody(node, false, isMethod);
  7904. }
  7905. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  7906. if (this.match(types.colon)) {
  7907. const typeNode = this.startNode();
  7908. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  7909. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  7910. }
  7911. super.parseFunctionBodyAndFinish(node, type, isMethod);
  7912. }
  7913. parseStatement(context, topLevel) {
  7914. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  7915. const lookahead = this.lookahead();
  7916. if (lookahead.type === types.name || isKeyword(lookahead.value)) {
  7917. const node = this.startNode();
  7918. this.next();
  7919. return this.flowParseInterface(node);
  7920. }
  7921. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  7922. const node = this.startNode();
  7923. this.next();
  7924. return this.flowParseEnumDeclaration(node);
  7925. }
  7926. const stmt = super.parseStatement(context, topLevel);
  7927. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  7928. this.flowPragma = null;
  7929. }
  7930. return stmt;
  7931. }
  7932. parseExpressionStatement(node, expr) {
  7933. if (expr.type === "Identifier") {
  7934. if (expr.name === "declare") {
  7935. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  7936. return this.flowParseDeclare(node);
  7937. }
  7938. } else if (this.match(types.name)) {
  7939. if (expr.name === "interface") {
  7940. return this.flowParseInterface(node);
  7941. } else if (expr.name === "type") {
  7942. return this.flowParseTypeAlias(node);
  7943. } else if (expr.name === "opaque") {
  7944. return this.flowParseOpaqueType(node, false);
  7945. }
  7946. }
  7947. }
  7948. return super.parseExpressionStatement(node, expr);
  7949. }
  7950. shouldParseExportDeclaration() {
  7951. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  7952. }
  7953. isExportDefaultSpecifier() {
  7954. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  7955. return false;
  7956. }
  7957. return super.isExportDefaultSpecifier();
  7958. }
  7959. parseExportDefaultExpression() {
  7960. if (this.shouldParseEnums() && this.isContextual("enum")) {
  7961. const node = this.startNode();
  7962. this.next();
  7963. return this.flowParseEnumDeclaration(node);
  7964. }
  7965. return super.parseExportDefaultExpression();
  7966. }
  7967. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  7968. if (!this.match(types.question)) return expr;
  7969. if (refNeedsArrowPos) {
  7970. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  7971. if (!result.node) {
  7972. refNeedsArrowPos.start = result.error.pos || this.state.start;
  7973. return expr;
  7974. }
  7975. if (result.error) this.state = result.failState;
  7976. return result.node;
  7977. }
  7978. this.expect(types.question);
  7979. const state = this.state.clone();
  7980. const originalNoArrowAt = this.state.noArrowAt;
  7981. const node = this.startNodeAt(startPos, startLoc);
  7982. let {
  7983. consequent,
  7984. failed
  7985. } = this.tryParseConditionalConsequent();
  7986. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  7987. if (failed || invalid.length > 0) {
  7988. const noArrowAt = [...originalNoArrowAt];
  7989. if (invalid.length > 0) {
  7990. this.state = state;
  7991. this.state.noArrowAt = noArrowAt;
  7992. for (let i = 0; i < invalid.length; i++) {
  7993. noArrowAt.push(invalid[i].start);
  7994. }
  7995. ({
  7996. consequent,
  7997. failed
  7998. } = this.tryParseConditionalConsequent());
  7999. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  8000. }
  8001. if (failed && valid.length > 1) {
  8002. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  8003. }
  8004. if (failed && valid.length === 1) {
  8005. this.state = state;
  8006. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  8007. ({
  8008. consequent,
  8009. failed
  8010. } = this.tryParseConditionalConsequent());
  8011. }
  8012. }
  8013. this.getArrowLikeExpressions(consequent, true);
  8014. this.state.noArrowAt = originalNoArrowAt;
  8015. this.expect(types.colon);
  8016. node.test = expr;
  8017. node.consequent = consequent;
  8018. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined, undefined));
  8019. return this.finishNode(node, "ConditionalExpression");
  8020. }
  8021. tryParseConditionalConsequent() {
  8022. this.state.noArrowParamsConversionAt.push(this.state.start);
  8023. const consequent = this.parseMaybeAssignAllowIn();
  8024. const failed = !this.match(types.colon);
  8025. this.state.noArrowParamsConversionAt.pop();
  8026. return {
  8027. consequent,
  8028. failed
  8029. };
  8030. }
  8031. getArrowLikeExpressions(node, disallowInvalid) {
  8032. const stack = [node];
  8033. const arrows = [];
  8034. while (stack.length !== 0) {
  8035. const node = stack.pop();
  8036. if (node.type === "ArrowFunctionExpression") {
  8037. if (node.typeParameters || !node.returnType) {
  8038. this.finishArrowValidation(node);
  8039. } else {
  8040. arrows.push(node);
  8041. }
  8042. stack.push(node.body);
  8043. } else if (node.type === "ConditionalExpression") {
  8044. stack.push(node.consequent);
  8045. stack.push(node.alternate);
  8046. }
  8047. }
  8048. if (disallowInvalid) {
  8049. arrows.forEach(node => this.finishArrowValidation(node));
  8050. return [arrows, []];
  8051. }
  8052. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  8053. }
  8054. finishArrowValidation(node) {
  8055. var _node$extra;
  8056. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false);
  8057. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  8058. super.checkParams(node, false, true);
  8059. this.scope.exit();
  8060. }
  8061. forwardNoArrowParamsConversionAt(node, parse) {
  8062. let result;
  8063. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  8064. this.state.noArrowParamsConversionAt.push(this.state.start);
  8065. result = parse();
  8066. this.state.noArrowParamsConversionAt.pop();
  8067. } else {
  8068. result = parse();
  8069. }
  8070. return result;
  8071. }
  8072. parseParenItem(node, startPos, startLoc) {
  8073. node = super.parseParenItem(node, startPos, startLoc);
  8074. if (this.eat(types.question)) {
  8075. node.optional = true;
  8076. this.resetEndLocation(node);
  8077. }
  8078. if (this.match(types.colon)) {
  8079. const typeCastNode = this.startNodeAt(startPos, startLoc);
  8080. typeCastNode.expression = node;
  8081. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  8082. return this.finishNode(typeCastNode, "TypeCastExpression");
  8083. }
  8084. return node;
  8085. }
  8086. assertModuleNodeAllowed(node) {
  8087. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  8088. return;
  8089. }
  8090. super.assertModuleNodeAllowed(node);
  8091. }
  8092. parseExport(node) {
  8093. const decl = super.parseExport(node);
  8094. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  8095. decl.exportKind = decl.exportKind || "value";
  8096. }
  8097. return decl;
  8098. }
  8099. parseExportDeclaration(node) {
  8100. if (this.isContextual("type")) {
  8101. node.exportKind = "type";
  8102. const declarationNode = this.startNode();
  8103. this.next();
  8104. if (this.match(types.braceL)) {
  8105. node.specifiers = this.parseExportSpecifiers();
  8106. this.parseExportFrom(node);
  8107. return null;
  8108. } else {
  8109. return this.flowParseTypeAlias(declarationNode);
  8110. }
  8111. } else if (this.isContextual("opaque")) {
  8112. node.exportKind = "type";
  8113. const declarationNode = this.startNode();
  8114. this.next();
  8115. return this.flowParseOpaqueType(declarationNode, false);
  8116. } else if (this.isContextual("interface")) {
  8117. node.exportKind = "type";
  8118. const declarationNode = this.startNode();
  8119. this.next();
  8120. return this.flowParseInterface(declarationNode);
  8121. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  8122. node.exportKind = "value";
  8123. const declarationNode = this.startNode();
  8124. this.next();
  8125. return this.flowParseEnumDeclaration(declarationNode);
  8126. } else {
  8127. return super.parseExportDeclaration(node);
  8128. }
  8129. }
  8130. eatExportStar(node) {
  8131. if (super.eatExportStar(...arguments)) return true;
  8132. if (this.isContextual("type") && this.lookahead().type === types.star) {
  8133. node.exportKind = "type";
  8134. this.next();
  8135. this.next();
  8136. return true;
  8137. }
  8138. return false;
  8139. }
  8140. maybeParseExportNamespaceSpecifier(node) {
  8141. const pos = this.state.start;
  8142. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  8143. if (hasNamespace && node.exportKind === "type") {
  8144. this.unexpected(pos);
  8145. }
  8146. return hasNamespace;
  8147. }
  8148. parseClassId(node, isStatement, optionalId) {
  8149. super.parseClassId(node, isStatement, optionalId);
  8150. if (this.isRelational("<")) {
  8151. node.typeParameters = this.flowParseTypeParameterDeclaration();
  8152. }
  8153. }
  8154. parseClassMember(classBody, member, state) {
  8155. const pos = this.state.start;
  8156. if (this.isContextual("declare")) {
  8157. if (this.parseClassMemberFromModifier(classBody, member)) {
  8158. return;
  8159. }
  8160. member.declare = true;
  8161. }
  8162. super.parseClassMember(classBody, member, state);
  8163. if (member.declare) {
  8164. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") {
  8165. this.raise(pos, FlowErrors.DeclareClassElement);
  8166. } else if (member.value) {
  8167. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  8168. }
  8169. }
  8170. }
  8171. getTokenFromCode(code) {
  8172. const next = this.input.charCodeAt(this.state.pos + 1);
  8173. if (code === 123 && next === 124) {
  8174. return this.finishOp(types.braceBarL, 2);
  8175. } else if (this.state.inType && (code === 62 || code === 60)) {
  8176. return this.finishOp(types.relational, 1);
  8177. } else if (this.state.inType && code === 63) {
  8178. return this.finishOp(types.question, 1);
  8179. } else if (isIteratorStart(code, next)) {
  8180. this.state.isIterator = true;
  8181. return super.readWord();
  8182. } else {
  8183. return super.getTokenFromCode(code);
  8184. }
  8185. }
  8186. isAssignable(node, isBinding) {
  8187. switch (node.type) {
  8188. case "Identifier":
  8189. case "ObjectPattern":
  8190. case "ArrayPattern":
  8191. case "AssignmentPattern":
  8192. return true;
  8193. case "ObjectExpression":
  8194. {
  8195. const last = node.properties.length - 1;
  8196. return node.properties.every((prop, i) => {
  8197. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  8198. });
  8199. }
  8200. case "ObjectProperty":
  8201. return this.isAssignable(node.value);
  8202. case "SpreadElement":
  8203. return this.isAssignable(node.argument);
  8204. case "ArrayExpression":
  8205. return node.elements.every(element => this.isAssignable(element));
  8206. case "AssignmentExpression":
  8207. return node.operator === "=";
  8208. case "ParenthesizedExpression":
  8209. case "TypeCastExpression":
  8210. return this.isAssignable(node.expression);
  8211. case "MemberExpression":
  8212. case "OptionalMemberExpression":
  8213. return !isBinding;
  8214. default:
  8215. return false;
  8216. }
  8217. }
  8218. toAssignable(node, isLHS = false) {
  8219. if (node.type === "TypeCastExpression") {
  8220. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  8221. } else {
  8222. return super.toAssignable(node, isLHS);
  8223. }
  8224. }
  8225. toAssignableList(exprList, trailingCommaPos, isLHS) {
  8226. for (let i = 0; i < exprList.length; i++) {
  8227. const expr = exprList[i];
  8228. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  8229. exprList[i] = this.typeCastToParameter(expr);
  8230. }
  8231. }
  8232. return super.toAssignableList(exprList, trailingCommaPos, isLHS);
  8233. }
  8234. toReferencedList(exprList, isParenthesizedExpr) {
  8235. for (let i = 0; i < exprList.length; i++) {
  8236. var _expr$extra;
  8237. const expr = exprList[i];
  8238. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) == null ? void 0 : _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  8239. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  8240. }
  8241. }
  8242. return exprList;
  8243. }
  8244. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  8245. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  8246. if (canBePattern && !this.state.maybeInArrowParameters) {
  8247. this.toReferencedList(node.elements);
  8248. }
  8249. return node;
  8250. }
  8251. checkLVal(expr, ...args) {
  8252. if (expr.type !== "TypeCastExpression") {
  8253. return super.checkLVal(expr, ...args);
  8254. }
  8255. }
  8256. parseClassProperty(node) {
  8257. if (this.match(types.colon)) {
  8258. node.typeAnnotation = this.flowParseTypeAnnotation();
  8259. }
  8260. return super.parseClassProperty(node);
  8261. }
  8262. parseClassPrivateProperty(node) {
  8263. if (this.match(types.colon)) {
  8264. node.typeAnnotation = this.flowParseTypeAnnotation();
  8265. }
  8266. return super.parseClassPrivateProperty(node);
  8267. }
  8268. isClassMethod() {
  8269. return this.isRelational("<") || super.isClassMethod();
  8270. }
  8271. isClassProperty() {
  8272. return this.match(types.colon) || super.isClassProperty();
  8273. }
  8274. isNonstaticConstructor(method) {
  8275. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  8276. }
  8277. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  8278. if (method.variance) {
  8279. this.unexpected(method.variance.start);
  8280. }
  8281. delete method.variance;
  8282. if (this.isRelational("<")) {
  8283. method.typeParameters = this.flowParseTypeParameterDeclaration();
  8284. }
  8285. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  8286. }
  8287. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  8288. if (method.variance) {
  8289. this.unexpected(method.variance.start);
  8290. }
  8291. delete method.variance;
  8292. if (this.isRelational("<")) {
  8293. method.typeParameters = this.flowParseTypeParameterDeclaration();
  8294. }
  8295. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  8296. }
  8297. parseClassSuper(node) {
  8298. super.parseClassSuper(node);
  8299. if (node.superClass && this.isRelational("<")) {
  8300. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  8301. }
  8302. if (this.isContextual("implements")) {
  8303. this.next();
  8304. const implemented = node.implements = [];
  8305. do {
  8306. const node = this.startNode();
  8307. node.id = this.flowParseRestrictedIdentifier(true);
  8308. if (this.isRelational("<")) {
  8309. node.typeParameters = this.flowParseTypeParameterInstantiation();
  8310. } else {
  8311. node.typeParameters = null;
  8312. }
  8313. implemented.push(this.finishNode(node, "ClassImplements"));
  8314. } while (this.eat(types.comma));
  8315. }
  8316. }
  8317. parsePropertyName(node, isPrivateNameAllowed) {
  8318. const variance = this.flowParseVariance();
  8319. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  8320. node.variance = variance;
  8321. return key;
  8322. }
  8323. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  8324. if (prop.variance) {
  8325. this.unexpected(prop.variance.start);
  8326. }
  8327. delete prop.variance;
  8328. let typeParameters;
  8329. if (this.isRelational("<") && !isAccessor) {
  8330. typeParameters = this.flowParseTypeParameterDeclaration();
  8331. if (!this.match(types.parenL)) this.unexpected();
  8332. }
  8333. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  8334. if (typeParameters) {
  8335. (prop.value || prop).typeParameters = typeParameters;
  8336. }
  8337. }
  8338. parseAssignableListItemTypes(param) {
  8339. if (this.eat(types.question)) {
  8340. if (param.type !== "Identifier") {
  8341. this.raise(param.start, FlowErrors.OptionalBindingPattern);
  8342. }
  8343. param.optional = true;
  8344. }
  8345. if (this.match(types.colon)) {
  8346. param.typeAnnotation = this.flowParseTypeAnnotation();
  8347. }
  8348. this.resetEndLocation(param);
  8349. return param;
  8350. }
  8351. parseMaybeDefault(startPos, startLoc, left) {
  8352. const node = super.parseMaybeDefault(startPos, startLoc, left);
  8353. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  8354. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  8355. }
  8356. return node;
  8357. }
  8358. shouldParseDefaultImport(node) {
  8359. if (!hasTypeImportKind(node)) {
  8360. return super.shouldParseDefaultImport(node);
  8361. }
  8362. return isMaybeDefaultImport(this.state);
  8363. }
  8364. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  8365. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  8366. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  8367. node.specifiers.push(this.finishNode(specifier, type));
  8368. }
  8369. maybeParseDefaultImportSpecifier(node) {
  8370. node.importKind = "value";
  8371. let kind = null;
  8372. if (this.match(types._typeof)) {
  8373. kind = "typeof";
  8374. } else if (this.isContextual("type")) {
  8375. kind = "type";
  8376. }
  8377. if (kind) {
  8378. const lh = this.lookahead();
  8379. if (kind === "type" && lh.type === types.star) {
  8380. this.unexpected(lh.start);
  8381. }
  8382. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  8383. this.next();
  8384. node.importKind = kind;
  8385. }
  8386. }
  8387. return super.maybeParseDefaultImportSpecifier(node);
  8388. }
  8389. parseImportSpecifier(node) {
  8390. const specifier = this.startNode();
  8391. const firstIdentLoc = this.state.start;
  8392. const firstIdent = this.parseModuleExportName();
  8393. let specifierTypeKind = null;
  8394. if (firstIdent.type === "Identifier") {
  8395. if (firstIdent.name === "type") {
  8396. specifierTypeKind = "type";
  8397. } else if (firstIdent.name === "typeof") {
  8398. specifierTypeKind = "typeof";
  8399. }
  8400. }
  8401. let isBinding = false;
  8402. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  8403. const as_ident = this.parseIdentifier(true);
  8404. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  8405. specifier.imported = as_ident;
  8406. specifier.importKind = specifierTypeKind;
  8407. specifier.local = as_ident.__clone();
  8408. } else {
  8409. specifier.imported = firstIdent;
  8410. specifier.importKind = null;
  8411. specifier.local = this.parseIdentifier();
  8412. }
  8413. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  8414. specifier.imported = this.parseIdentifier(true);
  8415. specifier.importKind = specifierTypeKind;
  8416. if (this.eatContextual("as")) {
  8417. specifier.local = this.parseIdentifier();
  8418. } else {
  8419. isBinding = true;
  8420. specifier.local = specifier.imported.__clone();
  8421. }
  8422. } else {
  8423. if (firstIdent.type === "StringLiteral") {
  8424. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
  8425. }
  8426. isBinding = true;
  8427. specifier.imported = firstIdent;
  8428. specifier.importKind = null;
  8429. specifier.local = specifier.imported.__clone();
  8430. }
  8431. const nodeIsTypeImport = hasTypeImportKind(node);
  8432. const specifierIsTypeImport = hasTypeImportKind(specifier);
  8433. if (nodeIsTypeImport && specifierIsTypeImport) {
  8434. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  8435. }
  8436. if (nodeIsTypeImport || specifierIsTypeImport) {
  8437. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  8438. }
  8439. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  8440. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  8441. }
  8442. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  8443. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  8444. }
  8445. parseFunctionParams(node, allowModifiers) {
  8446. const kind = node.kind;
  8447. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  8448. node.typeParameters = this.flowParseTypeParameterDeclaration();
  8449. }
  8450. super.parseFunctionParams(node, allowModifiers);
  8451. }
  8452. parseVarId(decl, kind) {
  8453. super.parseVarId(decl, kind);
  8454. if (this.match(types.colon)) {
  8455. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  8456. this.resetEndLocation(decl.id);
  8457. }
  8458. }
  8459. parseAsyncArrowFromCallExpression(node, call) {
  8460. if (this.match(types.colon)) {
  8461. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  8462. this.state.noAnonFunctionType = true;
  8463. node.returnType = this.flowParseTypeAnnotation();
  8464. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  8465. }
  8466. return super.parseAsyncArrowFromCallExpression(node, call);
  8467. }
  8468. shouldParseAsyncArrow() {
  8469. return this.match(types.colon) || super.shouldParseAsyncArrow();
  8470. }
  8471. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8472. var _jsx;
  8473. let state = null;
  8474. let jsx;
  8475. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  8476. state = this.state.clone();
  8477. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  8478. if (!jsx.error) return jsx.node;
  8479. const {
  8480. context
  8481. } = this.state;
  8482. if (context[context.length - 1] === types$1.j_oTag) {
  8483. context.length -= 2;
  8484. } else if (context[context.length - 1] === types$1.j_expr) {
  8485. context.length -= 1;
  8486. }
  8487. }
  8488. if (((_jsx = jsx) == null ? void 0 : _jsx.error) || this.isRelational("<")) {
  8489. var _jsx2, _jsx3;
  8490. state = state || this.state.clone();
  8491. let typeParameters;
  8492. const arrow = this.tryParse(abort => {
  8493. var _arrowExpression$extr;
  8494. typeParameters = this.flowParseTypeParameterDeclaration();
  8495. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  8496. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  8497. this.resetStartLocationFromNode(result, typeParameters);
  8498. return result;
  8499. });
  8500. if (arrowExpression.type !== "ArrowFunctionExpression" && ((_arrowExpression$extr = arrowExpression.extra) == null ? void 0 : _arrowExpression$extr.parenthesized)) {
  8501. abort();
  8502. }
  8503. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  8504. expr.typeParameters = typeParameters;
  8505. this.resetStartLocationFromNode(expr, typeParameters);
  8506. return arrowExpression;
  8507. }, state);
  8508. let arrowExpression = null;
  8509. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  8510. if (!arrow.error && !arrow.aborted) {
  8511. if (arrow.node.async) {
  8512. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  8513. }
  8514. return arrow.node;
  8515. }
  8516. arrowExpression = arrow.node;
  8517. }
  8518. if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
  8519. this.state = jsx.failState;
  8520. return jsx.node;
  8521. }
  8522. if (arrowExpression) {
  8523. this.state = arrow.failState;
  8524. return arrowExpression;
  8525. }
  8526. if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
  8527. if (arrow.thrown) throw arrow.error;
  8528. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  8529. }
  8530. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  8531. }
  8532. parseArrow(node) {
  8533. if (this.match(types.colon)) {
  8534. const result = this.tryParse(() => {
  8535. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  8536. this.state.noAnonFunctionType = true;
  8537. const typeNode = this.startNode();
  8538. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  8539. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  8540. if (this.canInsertSemicolon()) this.unexpected();
  8541. if (!this.match(types.arrow)) this.unexpected();
  8542. return typeNode;
  8543. });
  8544. if (result.thrown) return null;
  8545. if (result.error) this.state = result.failState;
  8546. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  8547. }
  8548. return super.parseArrow(node);
  8549. }
  8550. shouldParseArrow() {
  8551. return this.match(types.colon) || super.shouldParseArrow();
  8552. }
  8553. setArrowFunctionParameters(node, params) {
  8554. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  8555. node.params = params;
  8556. } else {
  8557. super.setArrowFunctionParameters(node, params);
  8558. }
  8559. }
  8560. checkParams(node, allowDuplicates, isArrowFunction) {
  8561. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  8562. return;
  8563. }
  8564. return super.checkParams(...arguments);
  8565. }
  8566. parseParenAndDistinguishExpression(canBeArrow) {
  8567. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  8568. }
  8569. parseSubscripts(base, startPos, startLoc, noCalls) {
  8570. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  8571. this.next();
  8572. const node = this.startNodeAt(startPos, startLoc);
  8573. node.callee = base;
  8574. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8575. base = this.finishNode(node, "CallExpression");
  8576. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  8577. const state = this.state.clone();
  8578. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  8579. if (!arrow.error && !arrow.aborted) return arrow.node;
  8580. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  8581. if (result.node && !result.error) return result.node;
  8582. if (arrow.node) {
  8583. this.state = arrow.failState;
  8584. return arrow.node;
  8585. }
  8586. if (result.node) {
  8587. this.state = result.failState;
  8588. return result.node;
  8589. }
  8590. throw arrow.error || result.error;
  8591. }
  8592. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  8593. }
  8594. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  8595. if (this.match(types.questionDot) && this.isLookaheadToken_lt()) {
  8596. subscriptState.optionalChainMember = true;
  8597. if (noCalls) {
  8598. subscriptState.stop = true;
  8599. return base;
  8600. }
  8601. this.next();
  8602. const node = this.startNodeAt(startPos, startLoc);
  8603. node.callee = base;
  8604. node.typeArguments = this.flowParseTypeParameterInstantiation();
  8605. this.expect(types.parenL);
  8606. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8607. node.optional = true;
  8608. return this.finishCallExpression(node, true);
  8609. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  8610. const node = this.startNodeAt(startPos, startLoc);
  8611. node.callee = base;
  8612. const result = this.tryParse(() => {
  8613. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  8614. this.expect(types.parenL);
  8615. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8616. if (subscriptState.optionalChainMember) node.optional = false;
  8617. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  8618. });
  8619. if (result.node) {
  8620. if (result.error) this.state = result.failState;
  8621. return result.node;
  8622. }
  8623. }
  8624. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  8625. }
  8626. parseNewArguments(node) {
  8627. let targs = null;
  8628. if (this.shouldParseTypes() && this.isRelational("<")) {
  8629. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  8630. }
  8631. node.typeArguments = targs;
  8632. super.parseNewArguments(node);
  8633. }
  8634. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  8635. const node = this.startNodeAt(startPos, startLoc);
  8636. this.parseFunctionParams(node);
  8637. if (!this.parseArrow(node)) return;
  8638. return this.parseArrowExpression(node, undefined, true);
  8639. }
  8640. readToken_mult_modulo(code) {
  8641. const next = this.input.charCodeAt(this.state.pos + 1);
  8642. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  8643. this.state.hasFlowComment = false;
  8644. this.state.pos += 2;
  8645. this.nextToken();
  8646. return;
  8647. }
  8648. super.readToken_mult_modulo(code);
  8649. }
  8650. readToken_pipe_amp(code) {
  8651. const next = this.input.charCodeAt(this.state.pos + 1);
  8652. if (code === 124 && next === 125) {
  8653. this.finishOp(types.braceBarR, 2);
  8654. return;
  8655. }
  8656. super.readToken_pipe_amp(code);
  8657. }
  8658. parseTopLevel(file, program) {
  8659. const fileNode = super.parseTopLevel(file, program);
  8660. if (this.state.hasFlowComment) {
  8661. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  8662. }
  8663. return fileNode;
  8664. }
  8665. skipBlockComment() {
  8666. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  8667. if (this.state.hasFlowComment) {
  8668. this.unexpected(null, FlowErrors.NestedFlowComment);
  8669. }
  8670. this.hasFlowCommentCompletion();
  8671. this.state.pos += this.skipFlowComment();
  8672. this.state.hasFlowComment = true;
  8673. return;
  8674. }
  8675. if (this.state.hasFlowComment) {
  8676. const end = this.input.indexOf("*-/", this.state.pos += 2);
  8677. if (end === -1) {
  8678. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  8679. }
  8680. this.state.pos = end + 3;
  8681. return;
  8682. }
  8683. super.skipBlockComment();
  8684. }
  8685. skipFlowComment() {
  8686. const {
  8687. pos
  8688. } = this.state;
  8689. let shiftToFirstNonWhiteSpace = 2;
  8690. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  8691. shiftToFirstNonWhiteSpace++;
  8692. }
  8693. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  8694. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  8695. if (ch2 === 58 && ch3 === 58) {
  8696. return shiftToFirstNonWhiteSpace + 2;
  8697. }
  8698. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  8699. return shiftToFirstNonWhiteSpace + 12;
  8700. }
  8701. if (ch2 === 58 && ch3 !== 58) {
  8702. return shiftToFirstNonWhiteSpace;
  8703. }
  8704. return false;
  8705. }
  8706. hasFlowCommentCompletion() {
  8707. const end = this.input.indexOf("*/", this.state.pos);
  8708. if (end === -1) {
  8709. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  8710. }
  8711. }
  8712. flowEnumErrorBooleanMemberNotInitialized(pos, {
  8713. enumName,
  8714. memberName
  8715. }) {
  8716. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  8717. }
  8718. flowEnumErrorInvalidMemberName(pos, {
  8719. enumName,
  8720. memberName
  8721. }) {
  8722. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  8723. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  8724. }
  8725. flowEnumErrorDuplicateMemberName(pos, {
  8726. enumName,
  8727. memberName
  8728. }) {
  8729. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  8730. }
  8731. flowEnumErrorInconsistentMemberValues(pos, {
  8732. enumName
  8733. }) {
  8734. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  8735. }
  8736. flowEnumErrorInvalidExplicitType(pos, {
  8737. enumName,
  8738. suppliedType
  8739. }) {
  8740. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  8741. }
  8742. flowEnumErrorInvalidMemberInitializer(pos, {
  8743. enumName,
  8744. explicitType,
  8745. memberName
  8746. }) {
  8747. let message = null;
  8748. switch (explicitType) {
  8749. case "boolean":
  8750. case "number":
  8751. case "string":
  8752. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  8753. break;
  8754. case "symbol":
  8755. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  8756. break;
  8757. default:
  8758. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  8759. }
  8760. return this.raise(pos, message, enumName, memberName, explicitType);
  8761. }
  8762. flowEnumErrorNumberMemberNotInitialized(pos, {
  8763. enumName,
  8764. memberName
  8765. }) {
  8766. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  8767. }
  8768. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  8769. enumName
  8770. }) {
  8771. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  8772. }
  8773. flowEnumMemberInit() {
  8774. const startPos = this.state.start;
  8775. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  8776. switch (this.state.type) {
  8777. case types.num:
  8778. {
  8779. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  8780. if (endOfInit()) {
  8781. return {
  8782. type: "number",
  8783. pos: literal.start,
  8784. value: literal
  8785. };
  8786. }
  8787. return {
  8788. type: "invalid",
  8789. pos: startPos
  8790. };
  8791. }
  8792. case types.string:
  8793. {
  8794. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  8795. if (endOfInit()) {
  8796. return {
  8797. type: "string",
  8798. pos: literal.start,
  8799. value: literal
  8800. };
  8801. }
  8802. return {
  8803. type: "invalid",
  8804. pos: startPos
  8805. };
  8806. }
  8807. case types._true:
  8808. case types._false:
  8809. {
  8810. const literal = this.parseBooleanLiteral();
  8811. if (endOfInit()) {
  8812. return {
  8813. type: "boolean",
  8814. pos: literal.start,
  8815. value: literal
  8816. };
  8817. }
  8818. return {
  8819. type: "invalid",
  8820. pos: startPos
  8821. };
  8822. }
  8823. default:
  8824. return {
  8825. type: "invalid",
  8826. pos: startPos
  8827. };
  8828. }
  8829. }
  8830. flowEnumMemberRaw() {
  8831. const pos = this.state.start;
  8832. const id = this.parseIdentifier(true);
  8833. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  8834. type: "none",
  8835. pos
  8836. };
  8837. return {
  8838. id,
  8839. init
  8840. };
  8841. }
  8842. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  8843. const {
  8844. explicitType
  8845. } = context;
  8846. if (explicitType === null) {
  8847. return;
  8848. }
  8849. if (explicitType !== expectedType) {
  8850. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  8851. }
  8852. }
  8853. flowEnumMembers({
  8854. enumName,
  8855. explicitType
  8856. }) {
  8857. const seenNames = new Set();
  8858. const members = {
  8859. booleanMembers: [],
  8860. numberMembers: [],
  8861. stringMembers: [],
  8862. defaultedMembers: []
  8863. };
  8864. while (!this.match(types.braceR)) {
  8865. const memberNode = this.startNode();
  8866. const {
  8867. id,
  8868. init
  8869. } = this.flowEnumMemberRaw();
  8870. const memberName = id.name;
  8871. if (memberName === "") {
  8872. continue;
  8873. }
  8874. if (/^[a-z]/.test(memberName)) {
  8875. this.flowEnumErrorInvalidMemberName(id.start, {
  8876. enumName,
  8877. memberName
  8878. });
  8879. }
  8880. if (seenNames.has(memberName)) {
  8881. this.flowEnumErrorDuplicateMemberName(id.start, {
  8882. enumName,
  8883. memberName
  8884. });
  8885. }
  8886. seenNames.add(memberName);
  8887. const context = {
  8888. enumName,
  8889. explicitType,
  8890. memberName
  8891. };
  8892. memberNode.id = id;
  8893. switch (init.type) {
  8894. case "boolean":
  8895. {
  8896. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  8897. memberNode.init = init.value;
  8898. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  8899. break;
  8900. }
  8901. case "number":
  8902. {
  8903. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  8904. memberNode.init = init.value;
  8905. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  8906. break;
  8907. }
  8908. case "string":
  8909. {
  8910. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  8911. memberNode.init = init.value;
  8912. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  8913. break;
  8914. }
  8915. case "invalid":
  8916. {
  8917. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  8918. }
  8919. case "none":
  8920. {
  8921. switch (explicitType) {
  8922. case "boolean":
  8923. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  8924. break;
  8925. case "number":
  8926. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  8927. break;
  8928. default:
  8929. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  8930. }
  8931. }
  8932. }
  8933. if (!this.match(types.braceR)) {
  8934. this.expect(types.comma);
  8935. }
  8936. }
  8937. return members;
  8938. }
  8939. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  8940. enumName
  8941. }) {
  8942. if (initializedMembers.length === 0) {
  8943. return defaultedMembers;
  8944. } else if (defaultedMembers.length === 0) {
  8945. return initializedMembers;
  8946. } else if (defaultedMembers.length > initializedMembers.length) {
  8947. for (let _i = 0; _i < initializedMembers.length; _i++) {
  8948. const member = initializedMembers[_i];
  8949. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  8950. enumName
  8951. });
  8952. }
  8953. return defaultedMembers;
  8954. } else {
  8955. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  8956. const member = defaultedMembers[_i2];
  8957. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  8958. enumName
  8959. });
  8960. }
  8961. return initializedMembers;
  8962. }
  8963. }
  8964. flowEnumParseExplicitType({
  8965. enumName
  8966. }) {
  8967. if (this.eatContextual("of")) {
  8968. if (!this.match(types.name)) {
  8969. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  8970. enumName,
  8971. suppliedType: null
  8972. });
  8973. }
  8974. const {
  8975. value
  8976. } = this.state;
  8977. this.next();
  8978. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  8979. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  8980. enumName,
  8981. suppliedType: value
  8982. });
  8983. }
  8984. return value;
  8985. }
  8986. return null;
  8987. }
  8988. flowEnumBody(node, {
  8989. enumName,
  8990. nameLoc
  8991. }) {
  8992. const explicitType = this.flowEnumParseExplicitType({
  8993. enumName
  8994. });
  8995. this.expect(types.braceL);
  8996. const members = this.flowEnumMembers({
  8997. enumName,
  8998. explicitType
  8999. });
  9000. switch (explicitType) {
  9001. case "boolean":
  9002. node.explicitType = true;
  9003. node.members = members.booleanMembers;
  9004. this.expect(types.braceR);
  9005. return this.finishNode(node, "EnumBooleanBody");
  9006. case "number":
  9007. node.explicitType = true;
  9008. node.members = members.numberMembers;
  9009. this.expect(types.braceR);
  9010. return this.finishNode(node, "EnumNumberBody");
  9011. case "string":
  9012. node.explicitType = true;
  9013. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  9014. enumName
  9015. });
  9016. this.expect(types.braceR);
  9017. return this.finishNode(node, "EnumStringBody");
  9018. case "symbol":
  9019. node.members = members.defaultedMembers;
  9020. this.expect(types.braceR);
  9021. return this.finishNode(node, "EnumSymbolBody");
  9022. default:
  9023. {
  9024. const empty = () => {
  9025. node.members = [];
  9026. this.expect(types.braceR);
  9027. return this.finishNode(node, "EnumStringBody");
  9028. };
  9029. node.explicitType = false;
  9030. const boolsLen = members.booleanMembers.length;
  9031. const numsLen = members.numberMembers.length;
  9032. const strsLen = members.stringMembers.length;
  9033. const defaultedLen = members.defaultedMembers.length;
  9034. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  9035. return empty();
  9036. } else if (!boolsLen && !numsLen) {
  9037. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  9038. enumName
  9039. });
  9040. this.expect(types.braceR);
  9041. return this.finishNode(node, "EnumStringBody");
  9042. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  9043. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  9044. const member = _members$defaultedMem[_i3];
  9045. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  9046. enumName,
  9047. memberName: member.id.name
  9048. });
  9049. }
  9050. node.members = members.booleanMembers;
  9051. this.expect(types.braceR);
  9052. return this.finishNode(node, "EnumBooleanBody");
  9053. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  9054. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  9055. const member = _members$defaultedMem2[_i4];
  9056. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  9057. enumName,
  9058. memberName: member.id.name
  9059. });
  9060. }
  9061. node.members = members.numberMembers;
  9062. this.expect(types.braceR);
  9063. return this.finishNode(node, "EnumNumberBody");
  9064. } else {
  9065. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  9066. enumName
  9067. });
  9068. return empty();
  9069. }
  9070. }
  9071. }
  9072. }
  9073. flowParseEnumDeclaration(node) {
  9074. const id = this.parseIdentifier();
  9075. node.id = id;
  9076. node.body = this.flowEnumBody(this.startNode(), {
  9077. enumName: id.name,
  9078. nameLoc: id.start
  9079. });
  9080. return this.finishNode(node, "EnumDeclaration");
  9081. }
  9082. updateContext(prevType) {
  9083. if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
  9084. this.state.exprAllowed = false;
  9085. } else {
  9086. super.updateContext(prevType);
  9087. }
  9088. }
  9089. isLookaheadToken_lt() {
  9090. const next = this.nextTokenStart();
  9091. if (this.input.charCodeAt(next) === 60) {
  9092. const afterNext = this.input.charCodeAt(next + 1);
  9093. return afterNext !== 60 && afterNext !== 61;
  9094. }
  9095. return false;
  9096. }
  9097. maybeUnwrapTypeCastExpression(node) {
  9098. return node.type === "TypeCastExpression" ? node.expression : node;
  9099. }
  9100. }, _temp;
  9101. });
  9102. const entities = {
  9103. quot: "\u0022",
  9104. amp: "&",
  9105. apos: "\u0027",
  9106. lt: "<",
  9107. gt: ">",
  9108. nbsp: "\u00A0",
  9109. iexcl: "\u00A1",
  9110. cent: "\u00A2",
  9111. pound: "\u00A3",
  9112. curren: "\u00A4",
  9113. yen: "\u00A5",
  9114. brvbar: "\u00A6",
  9115. sect: "\u00A7",
  9116. uml: "\u00A8",
  9117. copy: "\u00A9",
  9118. ordf: "\u00AA",
  9119. laquo: "\u00AB",
  9120. not: "\u00AC",
  9121. shy: "\u00AD",
  9122. reg: "\u00AE",
  9123. macr: "\u00AF",
  9124. deg: "\u00B0",
  9125. plusmn: "\u00B1",
  9126. sup2: "\u00B2",
  9127. sup3: "\u00B3",
  9128. acute: "\u00B4",
  9129. micro: "\u00B5",
  9130. para: "\u00B6",
  9131. middot: "\u00B7",
  9132. cedil: "\u00B8",
  9133. sup1: "\u00B9",
  9134. ordm: "\u00BA",
  9135. raquo: "\u00BB",
  9136. frac14: "\u00BC",
  9137. frac12: "\u00BD",
  9138. frac34: "\u00BE",
  9139. iquest: "\u00BF",
  9140. Agrave: "\u00C0",
  9141. Aacute: "\u00C1",
  9142. Acirc: "\u00C2",
  9143. Atilde: "\u00C3",
  9144. Auml: "\u00C4",
  9145. Aring: "\u00C5",
  9146. AElig: "\u00C6",
  9147. Ccedil: "\u00C7",
  9148. Egrave: "\u00C8",
  9149. Eacute: "\u00C9",
  9150. Ecirc: "\u00CA",
  9151. Euml: "\u00CB",
  9152. Igrave: "\u00CC",
  9153. Iacute: "\u00CD",
  9154. Icirc: "\u00CE",
  9155. Iuml: "\u00CF",
  9156. ETH: "\u00D0",
  9157. Ntilde: "\u00D1",
  9158. Ograve: "\u00D2",
  9159. Oacute: "\u00D3",
  9160. Ocirc: "\u00D4",
  9161. Otilde: "\u00D5",
  9162. Ouml: "\u00D6",
  9163. times: "\u00D7",
  9164. Oslash: "\u00D8",
  9165. Ugrave: "\u00D9",
  9166. Uacute: "\u00DA",
  9167. Ucirc: "\u00DB",
  9168. Uuml: "\u00DC",
  9169. Yacute: "\u00DD",
  9170. THORN: "\u00DE",
  9171. szlig: "\u00DF",
  9172. agrave: "\u00E0",
  9173. aacute: "\u00E1",
  9174. acirc: "\u00E2",
  9175. atilde: "\u00E3",
  9176. auml: "\u00E4",
  9177. aring: "\u00E5",
  9178. aelig: "\u00E6",
  9179. ccedil: "\u00E7",
  9180. egrave: "\u00E8",
  9181. eacute: "\u00E9",
  9182. ecirc: "\u00EA",
  9183. euml: "\u00EB",
  9184. igrave: "\u00EC",
  9185. iacute: "\u00ED",
  9186. icirc: "\u00EE",
  9187. iuml: "\u00EF",
  9188. eth: "\u00F0",
  9189. ntilde: "\u00F1",
  9190. ograve: "\u00F2",
  9191. oacute: "\u00F3",
  9192. ocirc: "\u00F4",
  9193. otilde: "\u00F5",
  9194. ouml: "\u00F6",
  9195. divide: "\u00F7",
  9196. oslash: "\u00F8",
  9197. ugrave: "\u00F9",
  9198. uacute: "\u00FA",
  9199. ucirc: "\u00FB",
  9200. uuml: "\u00FC",
  9201. yacute: "\u00FD",
  9202. thorn: "\u00FE",
  9203. yuml: "\u00FF",
  9204. OElig: "\u0152",
  9205. oelig: "\u0153",
  9206. Scaron: "\u0160",
  9207. scaron: "\u0161",
  9208. Yuml: "\u0178",
  9209. fnof: "\u0192",
  9210. circ: "\u02C6",
  9211. tilde: "\u02DC",
  9212. Alpha: "\u0391",
  9213. Beta: "\u0392",
  9214. Gamma: "\u0393",
  9215. Delta: "\u0394",
  9216. Epsilon: "\u0395",
  9217. Zeta: "\u0396",
  9218. Eta: "\u0397",
  9219. Theta: "\u0398",
  9220. Iota: "\u0399",
  9221. Kappa: "\u039A",
  9222. Lambda: "\u039B",
  9223. Mu: "\u039C",
  9224. Nu: "\u039D",
  9225. Xi: "\u039E",
  9226. Omicron: "\u039F",
  9227. Pi: "\u03A0",
  9228. Rho: "\u03A1",
  9229. Sigma: "\u03A3",
  9230. Tau: "\u03A4",
  9231. Upsilon: "\u03A5",
  9232. Phi: "\u03A6",
  9233. Chi: "\u03A7",
  9234. Psi: "\u03A8",
  9235. Omega: "\u03A9",
  9236. alpha: "\u03B1",
  9237. beta: "\u03B2",
  9238. gamma: "\u03B3",
  9239. delta: "\u03B4",
  9240. epsilon: "\u03B5",
  9241. zeta: "\u03B6",
  9242. eta: "\u03B7",
  9243. theta: "\u03B8",
  9244. iota: "\u03B9",
  9245. kappa: "\u03BA",
  9246. lambda: "\u03BB",
  9247. mu: "\u03BC",
  9248. nu: "\u03BD",
  9249. xi: "\u03BE",
  9250. omicron: "\u03BF",
  9251. pi: "\u03C0",
  9252. rho: "\u03C1",
  9253. sigmaf: "\u03C2",
  9254. sigma: "\u03C3",
  9255. tau: "\u03C4",
  9256. upsilon: "\u03C5",
  9257. phi: "\u03C6",
  9258. chi: "\u03C7",
  9259. psi: "\u03C8",
  9260. omega: "\u03C9",
  9261. thetasym: "\u03D1",
  9262. upsih: "\u03D2",
  9263. piv: "\u03D6",
  9264. ensp: "\u2002",
  9265. emsp: "\u2003",
  9266. thinsp: "\u2009",
  9267. zwnj: "\u200C",
  9268. zwj: "\u200D",
  9269. lrm: "\u200E",
  9270. rlm: "\u200F",
  9271. ndash: "\u2013",
  9272. mdash: "\u2014",
  9273. lsquo: "\u2018",
  9274. rsquo: "\u2019",
  9275. sbquo: "\u201A",
  9276. ldquo: "\u201C",
  9277. rdquo: "\u201D",
  9278. bdquo: "\u201E",
  9279. dagger: "\u2020",
  9280. Dagger: "\u2021",
  9281. bull: "\u2022",
  9282. hellip: "\u2026",
  9283. permil: "\u2030",
  9284. prime: "\u2032",
  9285. Prime: "\u2033",
  9286. lsaquo: "\u2039",
  9287. rsaquo: "\u203A",
  9288. oline: "\u203E",
  9289. frasl: "\u2044",
  9290. euro: "\u20AC",
  9291. image: "\u2111",
  9292. weierp: "\u2118",
  9293. real: "\u211C",
  9294. trade: "\u2122",
  9295. alefsym: "\u2135",
  9296. larr: "\u2190",
  9297. uarr: "\u2191",
  9298. rarr: "\u2192",
  9299. darr: "\u2193",
  9300. harr: "\u2194",
  9301. crarr: "\u21B5",
  9302. lArr: "\u21D0",
  9303. uArr: "\u21D1",
  9304. rArr: "\u21D2",
  9305. dArr: "\u21D3",
  9306. hArr: "\u21D4",
  9307. forall: "\u2200",
  9308. part: "\u2202",
  9309. exist: "\u2203",
  9310. empty: "\u2205",
  9311. nabla: "\u2207",
  9312. isin: "\u2208",
  9313. notin: "\u2209",
  9314. ni: "\u220B",
  9315. prod: "\u220F",
  9316. sum: "\u2211",
  9317. minus: "\u2212",
  9318. lowast: "\u2217",
  9319. radic: "\u221A",
  9320. prop: "\u221D",
  9321. infin: "\u221E",
  9322. ang: "\u2220",
  9323. and: "\u2227",
  9324. or: "\u2228",
  9325. cap: "\u2229",
  9326. cup: "\u222A",
  9327. int: "\u222B",
  9328. there4: "\u2234",
  9329. sim: "\u223C",
  9330. cong: "\u2245",
  9331. asymp: "\u2248",
  9332. ne: "\u2260",
  9333. equiv: "\u2261",
  9334. le: "\u2264",
  9335. ge: "\u2265",
  9336. sub: "\u2282",
  9337. sup: "\u2283",
  9338. nsub: "\u2284",
  9339. sube: "\u2286",
  9340. supe: "\u2287",
  9341. oplus: "\u2295",
  9342. otimes: "\u2297",
  9343. perp: "\u22A5",
  9344. sdot: "\u22C5",
  9345. lceil: "\u2308",
  9346. rceil: "\u2309",
  9347. lfloor: "\u230A",
  9348. rfloor: "\u230B",
  9349. lang: "\u2329",
  9350. rang: "\u232A",
  9351. loz: "\u25CA",
  9352. spades: "\u2660",
  9353. clubs: "\u2663",
  9354. hearts: "\u2665",
  9355. diams: "\u2666"
  9356. };
  9357. const HEX_NUMBER = /^[\da-fA-F]+$/;
  9358. const DECIMAL_NUMBER = /^\d+$/;
  9359. const JsxErrors = Object.freeze({
  9360. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
  9361. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
  9362. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
  9363. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
  9364. UnterminatedJsxContent: "Unterminated JSX contents",
  9365. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  9366. });
  9367. types$1.j_oTag = new TokContext("<tag", false);
  9368. types$1.j_cTag = new TokContext("</tag", false);
  9369. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  9370. types.jsxName = new TokenType("jsxName");
  9371. types.jsxText = new TokenType("jsxText", {
  9372. beforeExpr: true
  9373. });
  9374. types.jsxTagStart = new TokenType("jsxTagStart", {
  9375. startsExpr: true
  9376. });
  9377. types.jsxTagEnd = new TokenType("jsxTagEnd");
  9378. types.jsxTagStart.updateContext = function () {
  9379. this.state.context.push(types$1.j_expr);
  9380. this.state.context.push(types$1.j_oTag);
  9381. this.state.exprAllowed = false;
  9382. };
  9383. types.jsxTagEnd.updateContext = function (prevType) {
  9384. const out = this.state.context.pop();
  9385. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  9386. this.state.context.pop();
  9387. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  9388. } else {
  9389. this.state.exprAllowed = true;
  9390. }
  9391. };
  9392. function isFragment(object) {
  9393. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  9394. }
  9395. function getQualifiedJSXName(object) {
  9396. if (object.type === "JSXIdentifier") {
  9397. return object.name;
  9398. }
  9399. if (object.type === "JSXNamespacedName") {
  9400. return object.namespace.name + ":" + object.name.name;
  9401. }
  9402. if (object.type === "JSXMemberExpression") {
  9403. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  9404. }
  9405. throw new Error("Node had unexpected type: " + object.type);
  9406. }
  9407. var jsx = (superClass => class extends superClass {
  9408. jsxReadToken() {
  9409. let out = "";
  9410. let chunkStart = this.state.pos;
  9411. for (;;) {
  9412. if (this.state.pos >= this.length) {
  9413. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  9414. }
  9415. const ch = this.input.charCodeAt(this.state.pos);
  9416. switch (ch) {
  9417. case 60:
  9418. case 123:
  9419. if (this.state.pos === this.state.start) {
  9420. if (ch === 60 && this.state.exprAllowed) {
  9421. ++this.state.pos;
  9422. return this.finishToken(types.jsxTagStart);
  9423. }
  9424. return super.getTokenFromCode(ch);
  9425. }
  9426. out += this.input.slice(chunkStart, this.state.pos);
  9427. return this.finishToken(types.jsxText, out);
  9428. case 38:
  9429. out += this.input.slice(chunkStart, this.state.pos);
  9430. out += this.jsxReadEntity();
  9431. chunkStart = this.state.pos;
  9432. break;
  9433. default:
  9434. if (isNewLine(ch)) {
  9435. out += this.input.slice(chunkStart, this.state.pos);
  9436. out += this.jsxReadNewLine(true);
  9437. chunkStart = this.state.pos;
  9438. } else {
  9439. ++this.state.pos;
  9440. }
  9441. }
  9442. }
  9443. }
  9444. jsxReadNewLine(normalizeCRLF) {
  9445. const ch = this.input.charCodeAt(this.state.pos);
  9446. let out;
  9447. ++this.state.pos;
  9448. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  9449. ++this.state.pos;
  9450. out = normalizeCRLF ? "\n" : "\r\n";
  9451. } else {
  9452. out = String.fromCharCode(ch);
  9453. }
  9454. ++this.state.curLine;
  9455. this.state.lineStart = this.state.pos;
  9456. return out;
  9457. }
  9458. jsxReadString(quote) {
  9459. let out = "";
  9460. let chunkStart = ++this.state.pos;
  9461. for (;;) {
  9462. if (this.state.pos >= this.length) {
  9463. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  9464. }
  9465. const ch = this.input.charCodeAt(this.state.pos);
  9466. if (ch === quote) break;
  9467. if (ch === 38) {
  9468. out += this.input.slice(chunkStart, this.state.pos);
  9469. out += this.jsxReadEntity();
  9470. chunkStart = this.state.pos;
  9471. } else if (isNewLine(ch)) {
  9472. out += this.input.slice(chunkStart, this.state.pos);
  9473. out += this.jsxReadNewLine(false);
  9474. chunkStart = this.state.pos;
  9475. } else {
  9476. ++this.state.pos;
  9477. }
  9478. }
  9479. out += this.input.slice(chunkStart, this.state.pos++);
  9480. return this.finishToken(types.string, out);
  9481. }
  9482. jsxReadEntity() {
  9483. let str = "";
  9484. let count = 0;
  9485. let entity;
  9486. let ch = this.input[this.state.pos];
  9487. const startPos = ++this.state.pos;
  9488. while (this.state.pos < this.length && count++ < 10) {
  9489. ch = this.input[this.state.pos++];
  9490. if (ch === ";") {
  9491. if (str[0] === "#") {
  9492. if (str[1] === "x") {
  9493. str = str.substr(2);
  9494. if (HEX_NUMBER.test(str)) {
  9495. entity = String.fromCodePoint(parseInt(str, 16));
  9496. }
  9497. } else {
  9498. str = str.substr(1);
  9499. if (DECIMAL_NUMBER.test(str)) {
  9500. entity = String.fromCodePoint(parseInt(str, 10));
  9501. }
  9502. }
  9503. } else {
  9504. entity = entities[str];
  9505. }
  9506. break;
  9507. }
  9508. str += ch;
  9509. }
  9510. if (!entity) {
  9511. this.state.pos = startPos;
  9512. return "&";
  9513. }
  9514. return entity;
  9515. }
  9516. jsxReadWord() {
  9517. let ch;
  9518. const start = this.state.pos;
  9519. do {
  9520. ch = this.input.charCodeAt(++this.state.pos);
  9521. } while (isIdentifierChar(ch) || ch === 45);
  9522. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  9523. }
  9524. jsxParseIdentifier() {
  9525. const node = this.startNode();
  9526. if (this.match(types.jsxName)) {
  9527. node.name = this.state.value;
  9528. } else if (this.state.type.keyword) {
  9529. node.name = this.state.type.keyword;
  9530. } else {
  9531. this.unexpected();
  9532. }
  9533. this.next();
  9534. return this.finishNode(node, "JSXIdentifier");
  9535. }
  9536. jsxParseNamespacedName() {
  9537. const startPos = this.state.start;
  9538. const startLoc = this.state.startLoc;
  9539. const name = this.jsxParseIdentifier();
  9540. if (!this.eat(types.colon)) return name;
  9541. const node = this.startNodeAt(startPos, startLoc);
  9542. node.namespace = name;
  9543. node.name = this.jsxParseIdentifier();
  9544. return this.finishNode(node, "JSXNamespacedName");
  9545. }
  9546. jsxParseElementName() {
  9547. const startPos = this.state.start;
  9548. const startLoc = this.state.startLoc;
  9549. let node = this.jsxParseNamespacedName();
  9550. if (node.type === "JSXNamespacedName") {
  9551. return node;
  9552. }
  9553. while (this.eat(types.dot)) {
  9554. const newNode = this.startNodeAt(startPos, startLoc);
  9555. newNode.object = node;
  9556. newNode.property = this.jsxParseIdentifier();
  9557. node = this.finishNode(newNode, "JSXMemberExpression");
  9558. }
  9559. return node;
  9560. }
  9561. jsxParseAttributeValue() {
  9562. let node;
  9563. switch (this.state.type) {
  9564. case types.braceL:
  9565. node = this.startNode();
  9566. this.next();
  9567. node = this.jsxParseExpressionContainer(node);
  9568. if (node.expression.type === "JSXEmptyExpression") {
  9569. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  9570. }
  9571. return node;
  9572. case types.jsxTagStart:
  9573. case types.string:
  9574. return this.parseExprAtom();
  9575. default:
  9576. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  9577. }
  9578. }
  9579. jsxParseEmptyExpression() {
  9580. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  9581. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  9582. }
  9583. jsxParseSpreadChild(node) {
  9584. this.next();
  9585. node.expression = this.parseExpression();
  9586. this.expect(types.braceR);
  9587. return this.finishNode(node, "JSXSpreadChild");
  9588. }
  9589. jsxParseExpressionContainer(node) {
  9590. if (this.match(types.braceR)) {
  9591. node.expression = this.jsxParseEmptyExpression();
  9592. } else {
  9593. node.expression = this.parseExpression();
  9594. }
  9595. this.expect(types.braceR);
  9596. return this.finishNode(node, "JSXExpressionContainer");
  9597. }
  9598. jsxParseAttribute() {
  9599. const node = this.startNode();
  9600. if (this.eat(types.braceL)) {
  9601. this.expect(types.ellipsis);
  9602. node.argument = this.parseMaybeAssignAllowIn();
  9603. this.expect(types.braceR);
  9604. return this.finishNode(node, "JSXSpreadAttribute");
  9605. }
  9606. node.name = this.jsxParseNamespacedName();
  9607. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  9608. return this.finishNode(node, "JSXAttribute");
  9609. }
  9610. jsxParseOpeningElementAt(startPos, startLoc) {
  9611. const node = this.startNodeAt(startPos, startLoc);
  9612. if (this.match(types.jsxTagEnd)) {
  9613. this.expect(types.jsxTagEnd);
  9614. return this.finishNode(node, "JSXOpeningFragment");
  9615. }
  9616. node.name = this.jsxParseElementName();
  9617. return this.jsxParseOpeningElementAfterName(node);
  9618. }
  9619. jsxParseOpeningElementAfterName(node) {
  9620. const attributes = [];
  9621. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  9622. attributes.push(this.jsxParseAttribute());
  9623. }
  9624. node.attributes = attributes;
  9625. node.selfClosing = this.eat(types.slash);
  9626. this.expect(types.jsxTagEnd);
  9627. return this.finishNode(node, "JSXOpeningElement");
  9628. }
  9629. jsxParseClosingElementAt(startPos, startLoc) {
  9630. const node = this.startNodeAt(startPos, startLoc);
  9631. if (this.match(types.jsxTagEnd)) {
  9632. this.expect(types.jsxTagEnd);
  9633. return this.finishNode(node, "JSXClosingFragment");
  9634. }
  9635. node.name = this.jsxParseElementName();
  9636. this.expect(types.jsxTagEnd);
  9637. return this.finishNode(node, "JSXClosingElement");
  9638. }
  9639. jsxParseElementAt(startPos, startLoc) {
  9640. const node = this.startNodeAt(startPos, startLoc);
  9641. const children = [];
  9642. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  9643. let closingElement = null;
  9644. if (!openingElement.selfClosing) {
  9645. contents: for (;;) {
  9646. switch (this.state.type) {
  9647. case types.jsxTagStart:
  9648. startPos = this.state.start;
  9649. startLoc = this.state.startLoc;
  9650. this.next();
  9651. if (this.eat(types.slash)) {
  9652. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  9653. break contents;
  9654. }
  9655. children.push(this.jsxParseElementAt(startPos, startLoc));
  9656. break;
  9657. case types.jsxText:
  9658. children.push(this.parseExprAtom());
  9659. break;
  9660. case types.braceL:
  9661. {
  9662. const node = this.startNode();
  9663. this.next();
  9664. if (this.match(types.ellipsis)) {
  9665. children.push(this.jsxParseSpreadChild(node));
  9666. } else {
  9667. children.push(this.jsxParseExpressionContainer(node));
  9668. }
  9669. break;
  9670. }
  9671. default:
  9672. throw this.unexpected();
  9673. }
  9674. }
  9675. if (isFragment(openingElement) && !isFragment(closingElement)) {
  9676. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  9677. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  9678. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  9679. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  9680. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  9681. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  9682. }
  9683. }
  9684. }
  9685. if (isFragment(openingElement)) {
  9686. node.openingFragment = openingElement;
  9687. node.closingFragment = closingElement;
  9688. } else {
  9689. node.openingElement = openingElement;
  9690. node.closingElement = closingElement;
  9691. }
  9692. node.children = children;
  9693. if (this.isRelational("<")) {
  9694. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  9695. }
  9696. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  9697. }
  9698. jsxParseElement() {
  9699. const startPos = this.state.start;
  9700. const startLoc = this.state.startLoc;
  9701. this.next();
  9702. return this.jsxParseElementAt(startPos, startLoc);
  9703. }
  9704. parseExprAtom(refExpressionErrors) {
  9705. if (this.match(types.jsxText)) {
  9706. return this.parseLiteral(this.state.value, "JSXText");
  9707. } else if (this.match(types.jsxTagStart)) {
  9708. return this.jsxParseElement();
  9709. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  9710. this.finishToken(types.jsxTagStart);
  9711. return this.jsxParseElement();
  9712. } else {
  9713. return super.parseExprAtom(refExpressionErrors);
  9714. }
  9715. }
  9716. getTokenFromCode(code) {
  9717. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  9718. const context = this.curContext();
  9719. if (context === types$1.j_expr) {
  9720. return this.jsxReadToken();
  9721. }
  9722. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  9723. if (isIdentifierStart(code)) {
  9724. return this.jsxReadWord();
  9725. }
  9726. if (code === 62) {
  9727. ++this.state.pos;
  9728. return this.finishToken(types.jsxTagEnd);
  9729. }
  9730. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  9731. return this.jsxReadString(code);
  9732. }
  9733. }
  9734. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  9735. ++this.state.pos;
  9736. return this.finishToken(types.jsxTagStart);
  9737. }
  9738. return super.getTokenFromCode(code);
  9739. }
  9740. updateContext(prevType) {
  9741. if (this.match(types.braceL)) {
  9742. const curContext = this.curContext();
  9743. if (curContext === types$1.j_oTag) {
  9744. this.state.context.push(types$1.braceExpression);
  9745. } else if (curContext === types$1.j_expr) {
  9746. this.state.context.push(types$1.templateQuasi);
  9747. } else {
  9748. super.updateContext(prevType);
  9749. }
  9750. this.state.exprAllowed = true;
  9751. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  9752. this.state.context.length -= 2;
  9753. this.state.context.push(types$1.j_cTag);
  9754. this.state.exprAllowed = false;
  9755. } else {
  9756. return super.updateContext(prevType);
  9757. }
  9758. }
  9759. });
  9760. class Scope {
  9761. constructor(flags) {
  9762. this.flags = void 0;
  9763. this.var = [];
  9764. this.lexical = [];
  9765. this.functions = [];
  9766. this.flags = flags;
  9767. }
  9768. }
  9769. class ScopeHandler {
  9770. constructor(raise, inModule) {
  9771. this.scopeStack = [];
  9772. this.undefinedExports = new Map();
  9773. this.undefinedPrivateNames = new Map();
  9774. this.raise = raise;
  9775. this.inModule = inModule;
  9776. }
  9777. get inFunction() {
  9778. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  9779. }
  9780. get allowSuper() {
  9781. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  9782. }
  9783. get allowDirectSuper() {
  9784. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  9785. }
  9786. get inClass() {
  9787. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  9788. }
  9789. get inNonArrowFunction() {
  9790. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  9791. }
  9792. get treatFunctionsAsVar() {
  9793. return this.treatFunctionsAsVarInScope(this.currentScope());
  9794. }
  9795. createScope(flags) {
  9796. return new Scope(flags);
  9797. }
  9798. enter(flags) {
  9799. this.scopeStack.push(this.createScope(flags));
  9800. }
  9801. exit() {
  9802. this.scopeStack.pop();
  9803. }
  9804. treatFunctionsAsVarInScope(scope) {
  9805. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  9806. }
  9807. declareName(name, bindingType, pos) {
  9808. let scope = this.currentScope();
  9809. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  9810. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  9811. if (bindingType & BIND_SCOPE_FUNCTION) {
  9812. scope.functions.push(name);
  9813. } else {
  9814. scope.lexical.push(name);
  9815. }
  9816. if (bindingType & BIND_SCOPE_LEXICAL) {
  9817. this.maybeExportDefined(scope, name);
  9818. }
  9819. } else if (bindingType & BIND_SCOPE_VAR) {
  9820. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  9821. scope = this.scopeStack[i];
  9822. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  9823. scope.var.push(name);
  9824. this.maybeExportDefined(scope, name);
  9825. if (scope.flags & SCOPE_VAR) break;
  9826. }
  9827. }
  9828. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  9829. this.undefinedExports.delete(name);
  9830. }
  9831. }
  9832. maybeExportDefined(scope, name) {
  9833. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  9834. this.undefinedExports.delete(name);
  9835. }
  9836. }
  9837. checkRedeclarationInScope(scope, name, bindingType, pos) {
  9838. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  9839. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  9840. }
  9841. }
  9842. isRedeclaredInScope(scope, name, bindingType) {
  9843. if (!(bindingType & BIND_KIND_VALUE)) return false;
  9844. if (bindingType & BIND_SCOPE_LEXICAL) {
  9845. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  9846. }
  9847. if (bindingType & BIND_SCOPE_FUNCTION) {
  9848. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  9849. }
  9850. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  9851. }
  9852. checkLocalExport(id) {
  9853. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1 && this.scopeStack[0].functions.indexOf(id.name) === -1) {
  9854. this.undefinedExports.set(id.name, id.start);
  9855. }
  9856. }
  9857. currentScope() {
  9858. return this.scopeStack[this.scopeStack.length - 1];
  9859. }
  9860. currentVarScope() {
  9861. for (let i = this.scopeStack.length - 1;; i--) {
  9862. const scope = this.scopeStack[i];
  9863. if (scope.flags & SCOPE_VAR) {
  9864. return scope;
  9865. }
  9866. }
  9867. }
  9868. currentThisScope() {
  9869. for (let i = this.scopeStack.length - 1;; i--) {
  9870. const scope = this.scopeStack[i];
  9871. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  9872. return scope;
  9873. }
  9874. }
  9875. }
  9876. }
  9877. class TypeScriptScope extends Scope {
  9878. constructor(...args) {
  9879. super(...args);
  9880. this.types = [];
  9881. this.enums = [];
  9882. this.constEnums = [];
  9883. this.classes = [];
  9884. this.exportOnlyBindings = [];
  9885. }
  9886. }
  9887. class TypeScriptScopeHandler extends ScopeHandler {
  9888. createScope(flags) {
  9889. return new TypeScriptScope(flags);
  9890. }
  9891. declareName(name, bindingType, pos) {
  9892. const scope = this.currentScope();
  9893. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  9894. this.maybeExportDefined(scope, name);
  9895. scope.exportOnlyBindings.push(name);
  9896. return;
  9897. }
  9898. super.declareName(...arguments);
  9899. if (bindingType & BIND_KIND_TYPE) {
  9900. if (!(bindingType & BIND_KIND_VALUE)) {
  9901. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  9902. this.maybeExportDefined(scope, name);
  9903. }
  9904. scope.types.push(name);
  9905. }
  9906. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  9907. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  9908. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  9909. }
  9910. isRedeclaredInScope(scope, name, bindingType) {
  9911. if (scope.enums.indexOf(name) > -1) {
  9912. if (bindingType & BIND_FLAGS_TS_ENUM) {
  9913. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  9914. const wasConst = scope.constEnums.indexOf(name) > -1;
  9915. return isConst !== wasConst;
  9916. }
  9917. return true;
  9918. }
  9919. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  9920. if (scope.lexical.indexOf(name) > -1) {
  9921. return !!(bindingType & BIND_KIND_VALUE);
  9922. } else {
  9923. return false;
  9924. }
  9925. }
  9926. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  9927. return true;
  9928. }
  9929. return super.isRedeclaredInScope(...arguments);
  9930. }
  9931. checkLocalExport(id) {
  9932. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  9933. super.checkLocalExport(id);
  9934. }
  9935. }
  9936. }
  9937. const PARAM = 0b0000,
  9938. PARAM_YIELD = 0b0001,
  9939. PARAM_AWAIT = 0b0010,
  9940. PARAM_RETURN = 0b0100,
  9941. PARAM_IN = 0b1000;
  9942. class ProductionParameterHandler {
  9943. constructor() {
  9944. this.stacks = [];
  9945. }
  9946. enter(flags) {
  9947. this.stacks.push(flags);
  9948. }
  9949. exit() {
  9950. this.stacks.pop();
  9951. }
  9952. currentFlags() {
  9953. return this.stacks[this.stacks.length - 1];
  9954. }
  9955. get hasAwait() {
  9956. return (this.currentFlags() & PARAM_AWAIT) > 0;
  9957. }
  9958. get hasYield() {
  9959. return (this.currentFlags() & PARAM_YIELD) > 0;
  9960. }
  9961. get hasReturn() {
  9962. return (this.currentFlags() & PARAM_RETURN) > 0;
  9963. }
  9964. get hasIn() {
  9965. return (this.currentFlags() & PARAM_IN) > 0;
  9966. }
  9967. }
  9968. function functionFlags(isAsync, isGenerator) {
  9969. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  9970. }
  9971. function nonNull(x) {
  9972. if (x == null) {
  9973. throw new Error(`Unexpected ${x} value.`);
  9974. }
  9975. return x;
  9976. }
  9977. function assert$1(x) {
  9978. if (!x) {
  9979. throw new Error("Assert fail");
  9980. }
  9981. }
  9982. const TSErrors = Object.freeze({
  9983. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
  9984. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
  9985. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  9986. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  9987. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  9988. DuplicateModifier: "Duplicate modifier: '%0'",
  9989. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  9990. EmptyTypeArguments: "Type argument list cannot be empty.",
  9991. EmptyTypeParameters: "Type parameter list cannot be empty.",
  9992. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
  9993. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
  9994. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
  9995. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier",
  9996. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  9997. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  9998. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  9999. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  10000. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  10001. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
  10002. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  10003. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  10004. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  10005. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  10006. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  10007. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
  10008. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  10009. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
  10010. });
  10011. function keywordTypeFromName(value) {
  10012. switch (value) {
  10013. case "any":
  10014. return "TSAnyKeyword";
  10015. case "boolean":
  10016. return "TSBooleanKeyword";
  10017. case "bigint":
  10018. return "TSBigIntKeyword";
  10019. case "never":
  10020. return "TSNeverKeyword";
  10021. case "number":
  10022. return "TSNumberKeyword";
  10023. case "object":
  10024. return "TSObjectKeyword";
  10025. case "string":
  10026. return "TSStringKeyword";
  10027. case "symbol":
  10028. return "TSSymbolKeyword";
  10029. case "undefined":
  10030. return "TSUndefinedKeyword";
  10031. case "unknown":
  10032. return "TSUnknownKeyword";
  10033. default:
  10034. return undefined;
  10035. }
  10036. }
  10037. var typescript = (superClass => class extends superClass {
  10038. getScopeHandler() {
  10039. return TypeScriptScopeHandler;
  10040. }
  10041. tsIsIdentifier() {
  10042. return this.match(types.name);
  10043. }
  10044. tsNextTokenCanFollowModifier() {
  10045. this.next();
  10046. return (this.match(types.bracketL) || this.match(types.braceL) || this.match(types.star) || this.match(types.ellipsis) || this.match(types.hash) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
  10047. }
  10048. tsParseModifier(allowedModifiers) {
  10049. if (!this.match(types.name)) {
  10050. return undefined;
  10051. }
  10052. const modifier = this.state.value;
  10053. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  10054. return modifier;
  10055. }
  10056. return undefined;
  10057. }
  10058. tsParseModifiers(modified, allowedModifiers) {
  10059. for (;;) {
  10060. const startPos = this.state.start;
  10061. const modifier = this.tsParseModifier(allowedModifiers);
  10062. if (!modifier) break;
  10063. if (Object.hasOwnProperty.call(modified, modifier)) {
  10064. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  10065. }
  10066. modified[modifier] = true;
  10067. }
  10068. }
  10069. tsIsListTerminator(kind) {
  10070. switch (kind) {
  10071. case "EnumMembers":
  10072. case "TypeMembers":
  10073. return this.match(types.braceR);
  10074. case "HeritageClauseElement":
  10075. return this.match(types.braceL);
  10076. case "TupleElementTypes":
  10077. return this.match(types.bracketR);
  10078. case "TypeParametersOrArguments":
  10079. return this.isRelational(">");
  10080. }
  10081. throw new Error("Unreachable");
  10082. }
  10083. tsParseList(kind, parseElement) {
  10084. const result = [];
  10085. while (!this.tsIsListTerminator(kind)) {
  10086. result.push(parseElement());
  10087. }
  10088. return result;
  10089. }
  10090. tsParseDelimitedList(kind, parseElement) {
  10091. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  10092. }
  10093. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  10094. const result = [];
  10095. for (;;) {
  10096. if (this.tsIsListTerminator(kind)) {
  10097. break;
  10098. }
  10099. const element = parseElement();
  10100. if (element == null) {
  10101. return undefined;
  10102. }
  10103. result.push(element);
  10104. if (this.eat(types.comma)) {
  10105. continue;
  10106. }
  10107. if (this.tsIsListTerminator(kind)) {
  10108. break;
  10109. }
  10110. if (expectSuccess) {
  10111. this.expect(types.comma);
  10112. }
  10113. return undefined;
  10114. }
  10115. return result;
  10116. }
  10117. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  10118. if (!skipFirstToken) {
  10119. if (bracket) {
  10120. this.expect(types.bracketL);
  10121. } else {
  10122. this.expectRelational("<");
  10123. }
  10124. }
  10125. const result = this.tsParseDelimitedList(kind, parseElement);
  10126. if (bracket) {
  10127. this.expect(types.bracketR);
  10128. } else {
  10129. this.expectRelational(">");
  10130. }
  10131. return result;
  10132. }
  10133. tsParseImportType() {
  10134. const node = this.startNode();
  10135. this.expect(types._import);
  10136. this.expect(types.parenL);
  10137. if (!this.match(types.string)) {
  10138. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  10139. }
  10140. node.argument = this.parseExprAtom();
  10141. this.expect(types.parenR);
  10142. if (this.eat(types.dot)) {
  10143. node.qualifier = this.tsParseEntityName(true);
  10144. }
  10145. if (this.isRelational("<")) {
  10146. node.typeParameters = this.tsParseTypeArguments();
  10147. }
  10148. return this.finishNode(node, "TSImportType");
  10149. }
  10150. tsParseEntityName(allowReservedWords) {
  10151. let entity = this.parseIdentifier();
  10152. while (this.eat(types.dot)) {
  10153. const node = this.startNodeAtNode(entity);
  10154. node.left = entity;
  10155. node.right = this.parseIdentifier(allowReservedWords);
  10156. entity = this.finishNode(node, "TSQualifiedName");
  10157. }
  10158. return entity;
  10159. }
  10160. tsParseTypeReference() {
  10161. const node = this.startNode();
  10162. node.typeName = this.tsParseEntityName(false);
  10163. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  10164. node.typeParameters = this.tsParseTypeArguments();
  10165. }
  10166. return this.finishNode(node, "TSTypeReference");
  10167. }
  10168. tsParseThisTypePredicate(lhs) {
  10169. this.next();
  10170. const node = this.startNodeAtNode(lhs);
  10171. node.parameterName = lhs;
  10172. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  10173. node.asserts = false;
  10174. return this.finishNode(node, "TSTypePredicate");
  10175. }
  10176. tsParseThisTypeNode() {
  10177. const node = this.startNode();
  10178. this.next();
  10179. return this.finishNode(node, "TSThisType");
  10180. }
  10181. tsParseTypeQuery() {
  10182. const node = this.startNode();
  10183. this.expect(types._typeof);
  10184. if (this.match(types._import)) {
  10185. node.exprName = this.tsParseImportType();
  10186. } else {
  10187. node.exprName = this.tsParseEntityName(true);
  10188. }
  10189. return this.finishNode(node, "TSTypeQuery");
  10190. }
  10191. tsParseTypeParameter() {
  10192. const node = this.startNode();
  10193. node.name = this.parseIdentifierName(node.start);
  10194. node.constraint = this.tsEatThenParseType(types._extends);
  10195. node.default = this.tsEatThenParseType(types.eq);
  10196. return this.finishNode(node, "TSTypeParameter");
  10197. }
  10198. tsTryParseTypeParameters() {
  10199. if (this.isRelational("<")) {
  10200. return this.tsParseTypeParameters();
  10201. }
  10202. }
  10203. tsParseTypeParameters() {
  10204. const node = this.startNode();
  10205. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  10206. this.next();
  10207. } else {
  10208. this.unexpected();
  10209. }
  10210. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  10211. if (node.params.length === 0) {
  10212. this.raise(node.start, TSErrors.EmptyTypeParameters);
  10213. }
  10214. return this.finishNode(node, "TSTypeParameterDeclaration");
  10215. }
  10216. tsTryNextParseConstantContext() {
  10217. if (this.lookahead().type === types._const) {
  10218. this.next();
  10219. return this.tsParseTypeReference();
  10220. }
  10221. return null;
  10222. }
  10223. tsFillSignature(returnToken, signature) {
  10224. const returnTokenRequired = returnToken === types.arrow;
  10225. signature.typeParameters = this.tsTryParseTypeParameters();
  10226. this.expect(types.parenL);
  10227. signature.parameters = this.tsParseBindingListForSignature();
  10228. if (returnTokenRequired) {
  10229. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  10230. } else if (this.match(returnToken)) {
  10231. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  10232. }
  10233. }
  10234. tsParseBindingListForSignature() {
  10235. return this.parseBindingList(types.parenR, 41).map(pattern => {
  10236. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  10237. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  10238. }
  10239. return pattern;
  10240. });
  10241. }
  10242. tsParseTypeMemberSemicolon() {
  10243. if (!this.eat(types.comma)) {
  10244. this.semicolon();
  10245. }
  10246. }
  10247. tsParseSignatureMember(kind, node) {
  10248. this.tsFillSignature(types.colon, node);
  10249. this.tsParseTypeMemberSemicolon();
  10250. return this.finishNode(node, kind);
  10251. }
  10252. tsIsUnambiguouslyIndexSignature() {
  10253. this.next();
  10254. return this.eat(types.name) && this.match(types.colon);
  10255. }
  10256. tsTryParseIndexSignature(node) {
  10257. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  10258. return undefined;
  10259. }
  10260. this.expect(types.bracketL);
  10261. const id = this.parseIdentifier();
  10262. id.typeAnnotation = this.tsParseTypeAnnotation();
  10263. this.resetEndLocation(id);
  10264. this.expect(types.bracketR);
  10265. node.parameters = [id];
  10266. const type = this.tsTryParseTypeAnnotation();
  10267. if (type) node.typeAnnotation = type;
  10268. this.tsParseTypeMemberSemicolon();
  10269. return this.finishNode(node, "TSIndexSignature");
  10270. }
  10271. tsParsePropertyOrMethodSignature(node, readonly) {
  10272. if (this.eat(types.question)) node.optional = true;
  10273. const nodeAny = node;
  10274. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  10275. const method = nodeAny;
  10276. this.tsFillSignature(types.colon, method);
  10277. this.tsParseTypeMemberSemicolon();
  10278. return this.finishNode(method, "TSMethodSignature");
  10279. } else {
  10280. const property = nodeAny;
  10281. if (readonly) property.readonly = true;
  10282. const type = this.tsTryParseTypeAnnotation();
  10283. if (type) property.typeAnnotation = type;
  10284. this.tsParseTypeMemberSemicolon();
  10285. return this.finishNode(property, "TSPropertySignature");
  10286. }
  10287. }
  10288. tsParseTypeMember() {
  10289. const node = this.startNode();
  10290. if (this.match(types.parenL) || this.isRelational("<")) {
  10291. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  10292. }
  10293. if (this.match(types._new)) {
  10294. const id = this.startNode();
  10295. this.next();
  10296. if (this.match(types.parenL) || this.isRelational("<")) {
  10297. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  10298. } else {
  10299. node.key = this.createIdentifier(id, "new");
  10300. return this.tsParsePropertyOrMethodSignature(node, false);
  10301. }
  10302. }
  10303. const readonly = !!this.tsParseModifier(["readonly"]);
  10304. const idx = this.tsTryParseIndexSignature(node);
  10305. if (idx) {
  10306. if (readonly) node.readonly = true;
  10307. return idx;
  10308. }
  10309. this.parsePropertyName(node, false);
  10310. return this.tsParsePropertyOrMethodSignature(node, readonly);
  10311. }
  10312. tsParseTypeLiteral() {
  10313. const node = this.startNode();
  10314. node.members = this.tsParseObjectTypeMembers();
  10315. return this.finishNode(node, "TSTypeLiteral");
  10316. }
  10317. tsParseObjectTypeMembers() {
  10318. this.expect(types.braceL);
  10319. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  10320. this.expect(types.braceR);
  10321. return members;
  10322. }
  10323. tsIsStartOfMappedType() {
  10324. this.next();
  10325. if (this.eat(types.plusMin)) {
  10326. return this.isContextual("readonly");
  10327. }
  10328. if (this.isContextual("readonly")) {
  10329. this.next();
  10330. }
  10331. if (!this.match(types.bracketL)) {
  10332. return false;
  10333. }
  10334. this.next();
  10335. if (!this.tsIsIdentifier()) {
  10336. return false;
  10337. }
  10338. this.next();
  10339. return this.match(types._in);
  10340. }
  10341. tsParseMappedTypeParameter() {
  10342. const node = this.startNode();
  10343. node.name = this.parseIdentifierName(node.start);
  10344. node.constraint = this.tsExpectThenParseType(types._in);
  10345. return this.finishNode(node, "TSTypeParameter");
  10346. }
  10347. tsParseMappedType() {
  10348. const node = this.startNode();
  10349. this.expect(types.braceL);
  10350. if (this.match(types.plusMin)) {
  10351. node.readonly = this.state.value;
  10352. this.next();
  10353. this.expectContextual("readonly");
  10354. } else if (this.eatContextual("readonly")) {
  10355. node.readonly = true;
  10356. }
  10357. this.expect(types.bracketL);
  10358. node.typeParameter = this.tsParseMappedTypeParameter();
  10359. node.nameType = this.eatContextual("as") ? this.tsParseType() : null;
  10360. this.expect(types.bracketR);
  10361. if (this.match(types.plusMin)) {
  10362. node.optional = this.state.value;
  10363. this.next();
  10364. this.expect(types.question);
  10365. } else if (this.eat(types.question)) {
  10366. node.optional = true;
  10367. }
  10368. node.typeAnnotation = this.tsTryParseType();
  10369. this.semicolon();
  10370. this.expect(types.braceR);
  10371. return this.finishNode(node, "TSMappedType");
  10372. }
  10373. tsParseTupleType() {
  10374. const node = this.startNode();
  10375. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  10376. let seenOptionalElement = false;
  10377. let labeledElements = null;
  10378. node.elementTypes.forEach(elementNode => {
  10379. var _labeledElements;
  10380. let {
  10381. type
  10382. } = elementNode;
  10383. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  10384. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  10385. }
  10386. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  10387. if (type === "TSRestType") {
  10388. elementNode = elementNode.typeAnnotation;
  10389. type = elementNode.type;
  10390. }
  10391. const isLabeled = type === "TSNamedTupleMember";
  10392. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  10393. if (labeledElements !== isLabeled) {
  10394. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  10395. }
  10396. });
  10397. return this.finishNode(node, "TSTupleType");
  10398. }
  10399. tsParseTupleElementType() {
  10400. const {
  10401. start: startPos,
  10402. startLoc
  10403. } = this.state;
  10404. const rest = this.eat(types.ellipsis);
  10405. let type = this.tsParseType();
  10406. const optional = this.eat(types.question);
  10407. const labeled = this.eat(types.colon);
  10408. if (labeled) {
  10409. const labeledNode = this.startNodeAtNode(type);
  10410. labeledNode.optional = optional;
  10411. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  10412. labeledNode.label = type.typeName;
  10413. } else {
  10414. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  10415. labeledNode.label = type;
  10416. }
  10417. labeledNode.elementType = this.tsParseType();
  10418. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  10419. } else if (optional) {
  10420. const optionalTypeNode = this.startNodeAtNode(type);
  10421. optionalTypeNode.typeAnnotation = type;
  10422. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  10423. }
  10424. if (rest) {
  10425. const restNode = this.startNodeAt(startPos, startLoc);
  10426. restNode.typeAnnotation = type;
  10427. type = this.finishNode(restNode, "TSRestType");
  10428. }
  10429. return type;
  10430. }
  10431. tsParseParenthesizedType() {
  10432. const node = this.startNode();
  10433. this.expect(types.parenL);
  10434. node.typeAnnotation = this.tsParseType();
  10435. this.expect(types.parenR);
  10436. return this.finishNode(node, "TSParenthesizedType");
  10437. }
  10438. tsParseFunctionOrConstructorType(type) {
  10439. const node = this.startNode();
  10440. if (type === "TSConstructorType") {
  10441. this.expect(types._new);
  10442. }
  10443. this.tsFillSignature(types.arrow, node);
  10444. return this.finishNode(node, type);
  10445. }
  10446. tsParseLiteralTypeNode() {
  10447. const node = this.startNode();
  10448. node.literal = (() => {
  10449. switch (this.state.type) {
  10450. case types.num:
  10451. case types.bigint:
  10452. case types.string:
  10453. case types._true:
  10454. case types._false:
  10455. return this.parseExprAtom();
  10456. default:
  10457. throw this.unexpected();
  10458. }
  10459. })();
  10460. return this.finishNode(node, "TSLiteralType");
  10461. }
  10462. tsParseTemplateLiteralType() {
  10463. const node = this.startNode();
  10464. node.literal = this.parseTemplate(false);
  10465. return this.finishNode(node, "TSLiteralType");
  10466. }
  10467. parseTemplateSubstitution() {
  10468. if (this.state.inType) return this.tsParseType();
  10469. return super.parseTemplateSubstitution();
  10470. }
  10471. tsParseThisTypeOrThisTypePredicate() {
  10472. const thisKeyword = this.tsParseThisTypeNode();
  10473. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  10474. return this.tsParseThisTypePredicate(thisKeyword);
  10475. } else {
  10476. return thisKeyword;
  10477. }
  10478. }
  10479. tsParseNonArrayType() {
  10480. switch (this.state.type) {
  10481. case types.name:
  10482. case types._void:
  10483. case types._null:
  10484. {
  10485. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  10486. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  10487. const node = this.startNode();
  10488. this.next();
  10489. return this.finishNode(node, type);
  10490. }
  10491. return this.tsParseTypeReference();
  10492. }
  10493. case types.string:
  10494. case types.num:
  10495. case types.bigint:
  10496. case types._true:
  10497. case types._false:
  10498. return this.tsParseLiteralTypeNode();
  10499. case types.plusMin:
  10500. if (this.state.value === "-") {
  10501. const node = this.startNode();
  10502. const nextToken = this.lookahead();
  10503. if (nextToken.type !== types.num && nextToken.type !== types.bigint) {
  10504. throw this.unexpected();
  10505. }
  10506. node.literal = this.parseMaybeUnary();
  10507. return this.finishNode(node, "TSLiteralType");
  10508. }
  10509. break;
  10510. case types._this:
  10511. return this.tsParseThisTypeOrThisTypePredicate();
  10512. case types._typeof:
  10513. return this.tsParseTypeQuery();
  10514. case types._import:
  10515. return this.tsParseImportType();
  10516. case types.braceL:
  10517. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  10518. case types.bracketL:
  10519. return this.tsParseTupleType();
  10520. case types.parenL:
  10521. return this.tsParseParenthesizedType();
  10522. case types.backQuote:
  10523. return this.tsParseTemplateLiteralType();
  10524. }
  10525. throw this.unexpected();
  10526. }
  10527. tsParseArrayTypeOrHigher() {
  10528. let type = this.tsParseNonArrayType();
  10529. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  10530. if (this.match(types.bracketR)) {
  10531. const node = this.startNodeAtNode(type);
  10532. node.elementType = type;
  10533. this.expect(types.bracketR);
  10534. type = this.finishNode(node, "TSArrayType");
  10535. } else {
  10536. const node = this.startNodeAtNode(type);
  10537. node.objectType = type;
  10538. node.indexType = this.tsParseType();
  10539. this.expect(types.bracketR);
  10540. type = this.finishNode(node, "TSIndexedAccessType");
  10541. }
  10542. }
  10543. return type;
  10544. }
  10545. tsParseTypeOperator(operator) {
  10546. const node = this.startNode();
  10547. this.expectContextual(operator);
  10548. node.operator = operator;
  10549. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  10550. if (operator === "readonly") {
  10551. this.tsCheckTypeAnnotationForReadOnly(node);
  10552. }
  10553. return this.finishNode(node, "TSTypeOperator");
  10554. }
  10555. tsCheckTypeAnnotationForReadOnly(node) {
  10556. switch (node.typeAnnotation.type) {
  10557. case "TSTupleType":
  10558. case "TSArrayType":
  10559. return;
  10560. default:
  10561. this.raise(node.start, TSErrors.UnexpectedReadonly);
  10562. }
  10563. }
  10564. tsParseInferType() {
  10565. const node = this.startNode();
  10566. this.expectContextual("infer");
  10567. const typeParameter = this.startNode();
  10568. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  10569. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  10570. return this.finishNode(node, "TSInferType");
  10571. }
  10572. tsParseTypeOperatorOrHigher() {
  10573. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  10574. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  10575. }
  10576. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  10577. this.eat(operator);
  10578. let type = parseConstituentType();
  10579. if (this.match(operator)) {
  10580. const types = [type];
  10581. while (this.eat(operator)) {
  10582. types.push(parseConstituentType());
  10583. }
  10584. const node = this.startNodeAtNode(type);
  10585. node.types = types;
  10586. type = this.finishNode(node, kind);
  10587. }
  10588. return type;
  10589. }
  10590. tsParseIntersectionTypeOrHigher() {
  10591. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  10592. }
  10593. tsParseUnionTypeOrHigher() {
  10594. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  10595. }
  10596. tsIsStartOfFunctionType() {
  10597. if (this.isRelational("<")) {
  10598. return true;
  10599. }
  10600. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  10601. }
  10602. tsSkipParameterStart() {
  10603. if (this.match(types.name) || this.match(types._this)) {
  10604. this.next();
  10605. return true;
  10606. }
  10607. if (this.match(types.braceL)) {
  10608. let braceStackCounter = 1;
  10609. this.next();
  10610. while (braceStackCounter > 0) {
  10611. if (this.match(types.braceL)) {
  10612. ++braceStackCounter;
  10613. } else if (this.match(types.braceR)) {
  10614. --braceStackCounter;
  10615. }
  10616. this.next();
  10617. }
  10618. return true;
  10619. }
  10620. if (this.match(types.bracketL)) {
  10621. let braceStackCounter = 1;
  10622. this.next();
  10623. while (braceStackCounter > 0) {
  10624. if (this.match(types.bracketL)) {
  10625. ++braceStackCounter;
  10626. } else if (this.match(types.bracketR)) {
  10627. --braceStackCounter;
  10628. }
  10629. this.next();
  10630. }
  10631. return true;
  10632. }
  10633. return false;
  10634. }
  10635. tsIsUnambiguouslyStartOfFunctionType() {
  10636. this.next();
  10637. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  10638. return true;
  10639. }
  10640. if (this.tsSkipParameterStart()) {
  10641. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  10642. return true;
  10643. }
  10644. if (this.match(types.parenR)) {
  10645. this.next();
  10646. if (this.match(types.arrow)) {
  10647. return true;
  10648. }
  10649. }
  10650. }
  10651. return false;
  10652. }
  10653. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  10654. return this.tsInType(() => {
  10655. const t = this.startNode();
  10656. this.expect(returnToken);
  10657. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  10658. if (asserts && this.match(types._this)) {
  10659. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  10660. if (thisTypePredicate.type === "TSThisType") {
  10661. const node = this.startNodeAtNode(t);
  10662. node.parameterName = thisTypePredicate;
  10663. node.asserts = true;
  10664. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  10665. } else {
  10666. thisTypePredicate.asserts = true;
  10667. }
  10668. t.typeAnnotation = thisTypePredicate;
  10669. return this.finishNode(t, "TSTypeAnnotation");
  10670. }
  10671. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  10672. if (!typePredicateVariable) {
  10673. if (!asserts) {
  10674. return this.tsParseTypeAnnotation(false, t);
  10675. }
  10676. const node = this.startNodeAtNode(t);
  10677. node.parameterName = this.parseIdentifier();
  10678. node.asserts = asserts;
  10679. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  10680. return this.finishNode(t, "TSTypeAnnotation");
  10681. }
  10682. const type = this.tsParseTypeAnnotation(false);
  10683. const node = this.startNodeAtNode(t);
  10684. node.parameterName = typePredicateVariable;
  10685. node.typeAnnotation = type;
  10686. node.asserts = asserts;
  10687. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  10688. return this.finishNode(t, "TSTypeAnnotation");
  10689. });
  10690. }
  10691. tsTryParseTypeOrTypePredicateAnnotation() {
  10692. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  10693. }
  10694. tsTryParseTypeAnnotation() {
  10695. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  10696. }
  10697. tsTryParseType() {
  10698. return this.tsEatThenParseType(types.colon);
  10699. }
  10700. tsParseTypePredicatePrefix() {
  10701. const id = this.parseIdentifier();
  10702. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  10703. this.next();
  10704. return id;
  10705. }
  10706. }
  10707. tsParseTypePredicateAsserts() {
  10708. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  10709. return false;
  10710. }
  10711. const containsEsc = this.state.containsEsc;
  10712. this.next();
  10713. if (!this.match(types.name) && !this.match(types._this)) {
  10714. return false;
  10715. }
  10716. if (containsEsc) {
  10717. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  10718. }
  10719. return true;
  10720. }
  10721. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  10722. this.tsInType(() => {
  10723. if (eatColon) this.expect(types.colon);
  10724. t.typeAnnotation = this.tsParseType();
  10725. });
  10726. return this.finishNode(t, "TSTypeAnnotation");
  10727. }
  10728. tsParseType() {
  10729. assert$1(this.state.inType);
  10730. const type = this.tsParseNonConditionalType();
  10731. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  10732. return type;
  10733. }
  10734. const node = this.startNodeAtNode(type);
  10735. node.checkType = type;
  10736. node.extendsType = this.tsParseNonConditionalType();
  10737. this.expect(types.question);
  10738. node.trueType = this.tsParseType();
  10739. this.expect(types.colon);
  10740. node.falseType = this.tsParseType();
  10741. return this.finishNode(node, "TSConditionalType");
  10742. }
  10743. tsParseNonConditionalType() {
  10744. if (this.tsIsStartOfFunctionType()) {
  10745. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  10746. }
  10747. if (this.match(types._new)) {
  10748. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  10749. }
  10750. return this.tsParseUnionTypeOrHigher();
  10751. }
  10752. tsParseTypeAssertion() {
  10753. const node = this.startNode();
  10754. const _const = this.tsTryNextParseConstantContext();
  10755. node.typeAnnotation = _const || this.tsNextThenParseType();
  10756. this.expectRelational(">");
  10757. node.expression = this.parseMaybeUnary();
  10758. return this.finishNode(node, "TSTypeAssertion");
  10759. }
  10760. tsParseHeritageClause(descriptor) {
  10761. const originalStart = this.state.start;
  10762. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  10763. if (!delimitedList.length) {
  10764. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  10765. }
  10766. return delimitedList;
  10767. }
  10768. tsParseExpressionWithTypeArguments() {
  10769. const node = this.startNode();
  10770. node.expression = this.tsParseEntityName(false);
  10771. if (this.isRelational("<")) {
  10772. node.typeParameters = this.tsParseTypeArguments();
  10773. }
  10774. return this.finishNode(node, "TSExpressionWithTypeArguments");
  10775. }
  10776. tsParseInterfaceDeclaration(node) {
  10777. node.id = this.parseIdentifier();
  10778. this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
  10779. node.typeParameters = this.tsTryParseTypeParameters();
  10780. if (this.eat(types._extends)) {
  10781. node.extends = this.tsParseHeritageClause("extends");
  10782. }
  10783. const body = this.startNode();
  10784. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  10785. node.body = this.finishNode(body, "TSInterfaceBody");
  10786. return this.finishNode(node, "TSInterfaceDeclaration");
  10787. }
  10788. tsParseTypeAliasDeclaration(node) {
  10789. node.id = this.parseIdentifier();
  10790. this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE);
  10791. node.typeParameters = this.tsTryParseTypeParameters();
  10792. node.typeAnnotation = this.tsInType(() => {
  10793. this.expect(types.eq);
  10794. if (this.isContextual("intrinsic") && this.lookahead().type !== types.dot) {
  10795. const node = this.startNode();
  10796. this.next();
  10797. return this.finishNode(node, "TSIntrinsicKeyword");
  10798. }
  10799. return this.tsParseType();
  10800. });
  10801. this.semicolon();
  10802. return this.finishNode(node, "TSTypeAliasDeclaration");
  10803. }
  10804. tsInNoContext(cb) {
  10805. const oldContext = this.state.context;
  10806. this.state.context = [oldContext[0]];
  10807. try {
  10808. return cb();
  10809. } finally {
  10810. this.state.context = oldContext;
  10811. }
  10812. }
  10813. tsInType(cb) {
  10814. const oldInType = this.state.inType;
  10815. this.state.inType = true;
  10816. try {
  10817. return cb();
  10818. } finally {
  10819. this.state.inType = oldInType;
  10820. }
  10821. }
  10822. tsEatThenParseType(token) {
  10823. return !this.match(token) ? undefined : this.tsNextThenParseType();
  10824. }
  10825. tsExpectThenParseType(token) {
  10826. return this.tsDoThenParseType(() => this.expect(token));
  10827. }
  10828. tsNextThenParseType() {
  10829. return this.tsDoThenParseType(() => this.next());
  10830. }
  10831. tsDoThenParseType(cb) {
  10832. return this.tsInType(() => {
  10833. cb();
  10834. return this.tsParseType();
  10835. });
  10836. }
  10837. tsParseEnumMember() {
  10838. const node = this.startNode();
  10839. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  10840. if (this.eat(types.eq)) {
  10841. node.initializer = this.parseMaybeAssignAllowIn();
  10842. }
  10843. return this.finishNode(node, "TSEnumMember");
  10844. }
  10845. tsParseEnumDeclaration(node, isConst) {
  10846. if (isConst) node.const = true;
  10847. node.id = this.parseIdentifier();
  10848. this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
  10849. this.expect(types.braceL);
  10850. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  10851. this.expect(types.braceR);
  10852. return this.finishNode(node, "TSEnumDeclaration");
  10853. }
  10854. tsParseModuleBlock() {
  10855. const node = this.startNode();
  10856. this.scope.enter(SCOPE_OTHER);
  10857. this.expect(types.braceL);
  10858. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  10859. this.scope.exit();
  10860. return this.finishNode(node, "TSModuleBlock");
  10861. }
  10862. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  10863. node.id = this.parseIdentifier();
  10864. if (!nested) {
  10865. this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE);
  10866. }
  10867. if (this.eat(types.dot)) {
  10868. const inner = this.startNode();
  10869. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  10870. node.body = inner;
  10871. } else {
  10872. this.scope.enter(SCOPE_TS_MODULE);
  10873. this.prodParam.enter(PARAM);
  10874. node.body = this.tsParseModuleBlock();
  10875. this.prodParam.exit();
  10876. this.scope.exit();
  10877. }
  10878. return this.finishNode(node, "TSModuleDeclaration");
  10879. }
  10880. tsParseAmbientExternalModuleDeclaration(node) {
  10881. if (this.isContextual("global")) {
  10882. node.global = true;
  10883. node.id = this.parseIdentifier();
  10884. } else if (this.match(types.string)) {
  10885. node.id = this.parseExprAtom();
  10886. } else {
  10887. this.unexpected();
  10888. }
  10889. if (this.match(types.braceL)) {
  10890. this.scope.enter(SCOPE_TS_MODULE);
  10891. this.prodParam.enter(PARAM);
  10892. node.body = this.tsParseModuleBlock();
  10893. this.prodParam.exit();
  10894. this.scope.exit();
  10895. } else {
  10896. this.semicolon();
  10897. }
  10898. return this.finishNode(node, "TSModuleDeclaration");
  10899. }
  10900. tsParseImportEqualsDeclaration(node, isExport) {
  10901. node.isExport = isExport || false;
  10902. node.id = this.parseIdentifier();
  10903. this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL);
  10904. this.expect(types.eq);
  10905. node.moduleReference = this.tsParseModuleReference();
  10906. this.semicolon();
  10907. return this.finishNode(node, "TSImportEqualsDeclaration");
  10908. }
  10909. tsIsExternalModuleReference() {
  10910. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  10911. }
  10912. tsParseModuleReference() {
  10913. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  10914. }
  10915. tsParseExternalModuleReference() {
  10916. const node = this.startNode();
  10917. this.expectContextual("require");
  10918. this.expect(types.parenL);
  10919. if (!this.match(types.string)) {
  10920. throw this.unexpected();
  10921. }
  10922. node.expression = this.parseExprAtom();
  10923. this.expect(types.parenR);
  10924. return this.finishNode(node, "TSExternalModuleReference");
  10925. }
  10926. tsLookAhead(f) {
  10927. const state = this.state.clone();
  10928. const res = f();
  10929. this.state = state;
  10930. return res;
  10931. }
  10932. tsTryParseAndCatch(f) {
  10933. const result = this.tryParse(abort => f() || abort());
  10934. if (result.aborted || !result.node) return undefined;
  10935. if (result.error) this.state = result.failState;
  10936. return result.node;
  10937. }
  10938. tsTryParse(f) {
  10939. const state = this.state.clone();
  10940. const result = f();
  10941. if (result !== undefined && result !== false) {
  10942. return result;
  10943. } else {
  10944. this.state = state;
  10945. return undefined;
  10946. }
  10947. }
  10948. tsTryParseDeclare(nany) {
  10949. if (this.isLineTerminator()) {
  10950. return;
  10951. }
  10952. let starttype = this.state.type;
  10953. let kind;
  10954. if (this.isContextual("let")) {
  10955. starttype = types._var;
  10956. kind = "let";
  10957. }
  10958. return this.tsInDeclareContext(() => {
  10959. switch (starttype) {
  10960. case types._function:
  10961. nany.declare = true;
  10962. return this.parseFunctionStatement(nany, false, true);
  10963. case types._class:
  10964. nany.declare = true;
  10965. return this.parseClass(nany, true, false);
  10966. case types._const:
  10967. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  10968. this.expect(types._const);
  10969. this.expectContextual("enum");
  10970. return this.tsParseEnumDeclaration(nany, true);
  10971. }
  10972. case types._var:
  10973. kind = kind || this.state.value;
  10974. return this.parseVarStatement(nany, kind);
  10975. case types.name:
  10976. {
  10977. const value = this.state.value;
  10978. if (value === "global") {
  10979. return this.tsParseAmbientExternalModuleDeclaration(nany);
  10980. } else {
  10981. return this.tsParseDeclaration(nany, value, true);
  10982. }
  10983. }
  10984. }
  10985. });
  10986. }
  10987. tsTryParseExportDeclaration() {
  10988. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  10989. }
  10990. tsParseExpressionStatement(node, expr) {
  10991. switch (expr.name) {
  10992. case "declare":
  10993. {
  10994. const declaration = this.tsTryParseDeclare(node);
  10995. if (declaration) {
  10996. declaration.declare = true;
  10997. return declaration;
  10998. }
  10999. break;
  11000. }
  11001. case "global":
  11002. if (this.match(types.braceL)) {
  11003. this.scope.enter(SCOPE_TS_MODULE);
  11004. this.prodParam.enter(PARAM);
  11005. const mod = node;
  11006. mod.global = true;
  11007. mod.id = expr;
  11008. mod.body = this.tsParseModuleBlock();
  11009. this.scope.exit();
  11010. this.prodParam.exit();
  11011. return this.finishNode(mod, "TSModuleDeclaration");
  11012. }
  11013. break;
  11014. default:
  11015. return this.tsParseDeclaration(node, expr.name, false);
  11016. }
  11017. }
  11018. tsParseDeclaration(node, value, next) {
  11019. switch (value) {
  11020. case "abstract":
  11021. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  11022. const cls = node;
  11023. cls.abstract = true;
  11024. if (next) {
  11025. this.next();
  11026. if (!this.match(types._class)) {
  11027. this.unexpected(null, types._class);
  11028. }
  11029. }
  11030. return this.parseClass(cls, true, false);
  11031. }
  11032. break;
  11033. case "enum":
  11034. if (next || this.match(types.name)) {
  11035. if (next) this.next();
  11036. return this.tsParseEnumDeclaration(node, false);
  11037. }
  11038. break;
  11039. case "interface":
  11040. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  11041. if (next) this.next();
  11042. return this.tsParseInterfaceDeclaration(node);
  11043. }
  11044. break;
  11045. case "module":
  11046. if (next) this.next();
  11047. if (this.match(types.string)) {
  11048. return this.tsParseAmbientExternalModuleDeclaration(node);
  11049. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  11050. return this.tsParseModuleOrNamespaceDeclaration(node);
  11051. }
  11052. break;
  11053. case "namespace":
  11054. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  11055. if (next) this.next();
  11056. return this.tsParseModuleOrNamespaceDeclaration(node);
  11057. }
  11058. break;
  11059. case "type":
  11060. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  11061. if (next) this.next();
  11062. return this.tsParseTypeAliasDeclaration(node);
  11063. }
  11064. break;
  11065. }
  11066. }
  11067. tsCheckLineTerminatorAndMatch(tokenType, next) {
  11068. return (next || this.match(tokenType)) && !this.isLineTerminator();
  11069. }
  11070. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  11071. if (!this.isRelational("<")) {
  11072. return undefined;
  11073. }
  11074. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11075. this.state.maybeInArrowParameters = true;
  11076. const res = this.tsTryParseAndCatch(() => {
  11077. const node = this.startNodeAt(startPos, startLoc);
  11078. node.typeParameters = this.tsParseTypeParameters();
  11079. super.parseFunctionParams(node);
  11080. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  11081. this.expect(types.arrow);
  11082. return node;
  11083. });
  11084. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11085. if (!res) {
  11086. return undefined;
  11087. }
  11088. return this.parseArrowExpression(res, null, true);
  11089. }
  11090. tsParseTypeArguments() {
  11091. const node = this.startNode();
  11092. node.params = this.tsInType(() => this.tsInNoContext(() => {
  11093. this.expectRelational("<");
  11094. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  11095. }));
  11096. if (node.params.length === 0) {
  11097. this.raise(node.start, TSErrors.EmptyTypeArguments);
  11098. }
  11099. this.state.exprAllowed = false;
  11100. this.expectRelational(">");
  11101. return this.finishNode(node, "TSTypeParameterInstantiation");
  11102. }
  11103. tsIsDeclarationStart() {
  11104. if (this.match(types.name)) {
  11105. switch (this.state.value) {
  11106. case "abstract":
  11107. case "declare":
  11108. case "enum":
  11109. case "interface":
  11110. case "module":
  11111. case "namespace":
  11112. case "type":
  11113. return true;
  11114. }
  11115. }
  11116. return false;
  11117. }
  11118. isExportDefaultSpecifier() {
  11119. if (this.tsIsDeclarationStart()) return false;
  11120. return super.isExportDefaultSpecifier();
  11121. }
  11122. parseAssignableListItem(allowModifiers, decorators) {
  11123. const startPos = this.state.start;
  11124. const startLoc = this.state.startLoc;
  11125. let accessibility;
  11126. let readonly = false;
  11127. if (allowModifiers !== undefined) {
  11128. accessibility = this.parseAccessModifier();
  11129. readonly = !!this.tsParseModifier(["readonly"]);
  11130. if (allowModifiers === false && (accessibility || readonly)) {
  11131. this.raise(startPos, TSErrors.UnexpectedParameterModifier);
  11132. }
  11133. }
  11134. const left = this.parseMaybeDefault();
  11135. this.parseAssignableListItemTypes(left);
  11136. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  11137. if (accessibility || readonly) {
  11138. const pp = this.startNodeAt(startPos, startLoc);
  11139. if (decorators.length) {
  11140. pp.decorators = decorators;
  11141. }
  11142. if (accessibility) pp.accessibility = accessibility;
  11143. if (readonly) pp.readonly = readonly;
  11144. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  11145. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  11146. }
  11147. pp.parameter = elt;
  11148. return this.finishNode(pp, "TSParameterProperty");
  11149. }
  11150. if (decorators.length) {
  11151. left.decorators = decorators;
  11152. }
  11153. return elt;
  11154. }
  11155. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  11156. if (this.match(types.colon)) {
  11157. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  11158. }
  11159. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  11160. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  11161. this.finishNode(node, bodilessType);
  11162. return;
  11163. }
  11164. if (bodilessType === "TSDeclareFunction" && this.state.isDeclareContext) {
  11165. this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
  11166. if (node.declare) {
  11167. super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  11168. return;
  11169. }
  11170. }
  11171. super.parseFunctionBodyAndFinish(node, type, isMethod);
  11172. }
  11173. registerFunctionStatementId(node) {
  11174. if (!node.body && node.id) {
  11175. this.checkLVal(node.id, "function name", BIND_TS_AMBIENT);
  11176. } else {
  11177. super.registerFunctionStatementId(...arguments);
  11178. }
  11179. }
  11180. tsCheckForInvalidTypeCasts(items) {
  11181. items.forEach(node => {
  11182. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  11183. this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
  11184. }
  11185. });
  11186. }
  11187. toReferencedList(exprList, isInParens) {
  11188. this.tsCheckForInvalidTypeCasts(exprList);
  11189. return exprList;
  11190. }
  11191. parseArrayLike(...args) {
  11192. const node = super.parseArrayLike(...args);
  11193. if (node.type === "ArrayExpression") {
  11194. this.tsCheckForInvalidTypeCasts(node.elements);
  11195. }
  11196. return node;
  11197. }
  11198. parseSubscript(base, startPos, startLoc, noCalls, state) {
  11199. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  11200. this.state.exprAllowed = false;
  11201. this.next();
  11202. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  11203. nonNullExpression.expression = base;
  11204. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  11205. }
  11206. if (this.isRelational("<")) {
  11207. const result = this.tsTryParseAndCatch(() => {
  11208. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  11209. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  11210. if (asyncArrowFn) {
  11211. return asyncArrowFn;
  11212. }
  11213. }
  11214. const node = this.startNodeAt(startPos, startLoc);
  11215. node.callee = base;
  11216. const typeArguments = this.tsParseTypeArguments();
  11217. if (typeArguments) {
  11218. if (!noCalls && this.eat(types.parenL)) {
  11219. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  11220. this.tsCheckForInvalidTypeCasts(node.arguments);
  11221. node.typeParameters = typeArguments;
  11222. return this.finishCallExpression(node, state.optionalChainMember);
  11223. } else if (this.match(types.backQuote)) {
  11224. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  11225. result.typeParameters = typeArguments;
  11226. return result;
  11227. }
  11228. }
  11229. this.unexpected();
  11230. });
  11231. if (result) return result;
  11232. }
  11233. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  11234. }
  11235. parseNewArguments(node) {
  11236. if (this.isRelational("<")) {
  11237. const typeParameters = this.tsTryParseAndCatch(() => {
  11238. const args = this.tsParseTypeArguments();
  11239. if (!this.match(types.parenL)) this.unexpected();
  11240. return args;
  11241. });
  11242. if (typeParameters) {
  11243. node.typeParameters = typeParameters;
  11244. }
  11245. }
  11246. super.parseNewArguments(node);
  11247. }
  11248. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  11249. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  11250. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  11251. node.expression = left;
  11252. const _const = this.tsTryNextParseConstantContext();
  11253. if (_const) {
  11254. node.typeAnnotation = _const;
  11255. } else {
  11256. node.typeAnnotation = this.tsNextThenParseType();
  11257. }
  11258. this.finishNode(node, "TSAsExpression");
  11259. this.reScan_lt_gt();
  11260. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  11261. }
  11262. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  11263. }
  11264. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  11265. checkDuplicateExports() {}
  11266. parseImport(node) {
  11267. if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
  11268. const ahead = this.lookahead();
  11269. if (this.match(types.name) && ahead.type === types.eq) {
  11270. return this.tsParseImportEqualsDeclaration(node);
  11271. }
  11272. if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from")) {
  11273. node.importKind = "type";
  11274. this.next();
  11275. }
  11276. }
  11277. if (!node.importKind) {
  11278. node.importKind = "value";
  11279. }
  11280. const importNode = super.parseImport(node);
  11281. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  11282. this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
  11283. }
  11284. return importNode;
  11285. }
  11286. parseExport(node) {
  11287. if (this.match(types._import)) {
  11288. this.expect(types._import);
  11289. return this.tsParseImportEqualsDeclaration(node, true);
  11290. } else if (this.eat(types.eq)) {
  11291. const assign = node;
  11292. assign.expression = this.parseExpression();
  11293. this.semicolon();
  11294. return this.finishNode(assign, "TSExportAssignment");
  11295. } else if (this.eatContextual("as")) {
  11296. const decl = node;
  11297. this.expectContextual("namespace");
  11298. decl.id = this.parseIdentifier();
  11299. this.semicolon();
  11300. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  11301. } else {
  11302. if (this.isContextual("type") && this.lookahead().type === types.braceL) {
  11303. this.next();
  11304. node.exportKind = "type";
  11305. } else {
  11306. node.exportKind = "value";
  11307. }
  11308. return super.parseExport(node);
  11309. }
  11310. }
  11311. isAbstractClass() {
  11312. return this.isContextual("abstract") && this.lookahead().type === types._class;
  11313. }
  11314. parseExportDefaultExpression() {
  11315. if (this.isAbstractClass()) {
  11316. const cls = this.startNode();
  11317. this.next();
  11318. this.parseClass(cls, true, true);
  11319. cls.abstract = true;
  11320. return cls;
  11321. }
  11322. if (this.state.value === "interface") {
  11323. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  11324. if (result) return result;
  11325. }
  11326. return super.parseExportDefaultExpression();
  11327. }
  11328. parseStatementContent(context, topLevel) {
  11329. if (this.state.type === types._const) {
  11330. const ahead = this.lookahead();
  11331. if (ahead.type === types.name && ahead.value === "enum") {
  11332. const node = this.startNode();
  11333. this.expect(types._const);
  11334. this.expectContextual("enum");
  11335. return this.tsParseEnumDeclaration(node, true);
  11336. }
  11337. }
  11338. return super.parseStatementContent(context, topLevel);
  11339. }
  11340. parseAccessModifier() {
  11341. return this.tsParseModifier(["public", "protected", "private"]);
  11342. }
  11343. parseClassMember(classBody, member, state) {
  11344. this.tsParseModifiers(member, ["declare"]);
  11345. const accessibility = this.parseAccessModifier();
  11346. if (accessibility) member.accessibility = accessibility;
  11347. this.tsParseModifiers(member, ["declare"]);
  11348. const callParseClassMember = () => {
  11349. super.parseClassMember(classBody, member, state);
  11350. };
  11351. if (member.declare) {
  11352. this.tsInDeclareContext(callParseClassMember);
  11353. } else {
  11354. callParseClassMember();
  11355. }
  11356. }
  11357. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  11358. this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
  11359. const idx = this.tsTryParseIndexSignature(member);
  11360. if (idx) {
  11361. classBody.body.push(idx);
  11362. if (member.abstract) {
  11363. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  11364. }
  11365. if (isStatic) {
  11366. this.raise(member.start, TSErrors.IndexSignatureHasStatic);
  11367. }
  11368. if (member.accessibility) {
  11369. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  11370. }
  11371. if (member.declare) {
  11372. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  11373. }
  11374. return;
  11375. }
  11376. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  11377. }
  11378. parsePostMemberNameModifiers(methodOrProp) {
  11379. const optional = this.eat(types.question);
  11380. if (optional) methodOrProp.optional = true;
  11381. if (methodOrProp.readonly && this.match(types.parenL)) {
  11382. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  11383. }
  11384. if (methodOrProp.declare && this.match(types.parenL)) {
  11385. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  11386. }
  11387. }
  11388. parseExpressionStatement(node, expr) {
  11389. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  11390. return decl || super.parseExpressionStatement(node, expr);
  11391. }
  11392. shouldParseExportDeclaration() {
  11393. if (this.tsIsDeclarationStart()) return true;
  11394. return super.shouldParseExportDeclaration();
  11395. }
  11396. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  11397. if (!refNeedsArrowPos || !this.match(types.question)) {
  11398. return super.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  11399. }
  11400. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  11401. if (!result.node) {
  11402. refNeedsArrowPos.start = result.error.pos || this.state.start;
  11403. return expr;
  11404. }
  11405. if (result.error) this.state = result.failState;
  11406. return result.node;
  11407. }
  11408. parseParenItem(node, startPos, startLoc) {
  11409. node = super.parseParenItem(node, startPos, startLoc);
  11410. if (this.eat(types.question)) {
  11411. node.optional = true;
  11412. this.resetEndLocation(node);
  11413. }
  11414. if (this.match(types.colon)) {
  11415. const typeCastNode = this.startNodeAt(startPos, startLoc);
  11416. typeCastNode.expression = node;
  11417. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  11418. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  11419. }
  11420. return node;
  11421. }
  11422. parseExportDeclaration(node) {
  11423. const startPos = this.state.start;
  11424. const startLoc = this.state.startLoc;
  11425. const isDeclare = this.eatContextual("declare");
  11426. let declaration;
  11427. if (this.match(types.name)) {
  11428. declaration = this.tsTryParseExportDeclaration();
  11429. }
  11430. if (!declaration) {
  11431. declaration = super.parseExportDeclaration(node);
  11432. }
  11433. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  11434. node.exportKind = "type";
  11435. }
  11436. if (declaration && isDeclare) {
  11437. this.resetStartLocation(declaration, startPos, startLoc);
  11438. declaration.declare = true;
  11439. }
  11440. return declaration;
  11441. }
  11442. parseClassId(node, isStatement, optionalId) {
  11443. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  11444. return;
  11445. }
  11446. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  11447. const typeParameters = this.tsTryParseTypeParameters();
  11448. if (typeParameters) node.typeParameters = typeParameters;
  11449. }
  11450. parseClassPropertyAnnotation(node) {
  11451. if (!node.optional && this.eat(types.bang)) {
  11452. node.definite = true;
  11453. }
  11454. const type = this.tsTryParseTypeAnnotation();
  11455. if (type) node.typeAnnotation = type;
  11456. }
  11457. parseClassProperty(node) {
  11458. this.parseClassPropertyAnnotation(node);
  11459. if (this.state.isDeclareContext && this.match(types.eq)) {
  11460. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  11461. }
  11462. return super.parseClassProperty(node);
  11463. }
  11464. parseClassPrivateProperty(node) {
  11465. if (node.abstract) {
  11466. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  11467. }
  11468. if (node.accessibility) {
  11469. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  11470. }
  11471. this.parseClassPropertyAnnotation(node);
  11472. return super.parseClassPrivateProperty(node);
  11473. }
  11474. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  11475. const typeParameters = this.tsTryParseTypeParameters();
  11476. if (typeParameters && isConstructor) {
  11477. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  11478. }
  11479. if (typeParameters) method.typeParameters = typeParameters;
  11480. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  11481. }
  11482. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  11483. const typeParameters = this.tsTryParseTypeParameters();
  11484. if (typeParameters) method.typeParameters = typeParameters;
  11485. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  11486. }
  11487. parseClassSuper(node) {
  11488. super.parseClassSuper(node);
  11489. if (node.superClass && this.isRelational("<")) {
  11490. node.superTypeParameters = this.tsParseTypeArguments();
  11491. }
  11492. if (this.eatContextual("implements")) {
  11493. node.implements = this.tsParseHeritageClause("implements");
  11494. }
  11495. }
  11496. parseObjPropValue(prop, ...args) {
  11497. const typeParameters = this.tsTryParseTypeParameters();
  11498. if (typeParameters) prop.typeParameters = typeParameters;
  11499. super.parseObjPropValue(prop, ...args);
  11500. }
  11501. parseFunctionParams(node, allowModifiers) {
  11502. const typeParameters = this.tsTryParseTypeParameters();
  11503. if (typeParameters) node.typeParameters = typeParameters;
  11504. super.parseFunctionParams(node, allowModifiers);
  11505. }
  11506. parseVarId(decl, kind) {
  11507. super.parseVarId(decl, kind);
  11508. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  11509. decl.definite = true;
  11510. }
  11511. const type = this.tsTryParseTypeAnnotation();
  11512. if (type) {
  11513. decl.id.typeAnnotation = type;
  11514. this.resetEndLocation(decl.id);
  11515. }
  11516. }
  11517. parseAsyncArrowFromCallExpression(node, call) {
  11518. if (this.match(types.colon)) {
  11519. node.returnType = this.tsParseTypeAnnotation();
  11520. }
  11521. return super.parseAsyncArrowFromCallExpression(node, call);
  11522. }
  11523. parseMaybeAssign(...args) {
  11524. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  11525. let state;
  11526. let jsx;
  11527. let typeCast;
  11528. if (this.match(types.jsxTagStart)) {
  11529. state = this.state.clone();
  11530. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  11531. if (!jsx.error) return jsx.node;
  11532. const {
  11533. context
  11534. } = this.state;
  11535. if (context[context.length - 1] === types$1.j_oTag) {
  11536. context.length -= 2;
  11537. } else if (context[context.length - 1] === types$1.j_expr) {
  11538. context.length -= 1;
  11539. }
  11540. }
  11541. if (!((_jsx = jsx) == null ? void 0 : _jsx.error) && !this.isRelational("<")) {
  11542. return super.parseMaybeAssign(...args);
  11543. }
  11544. let typeParameters;
  11545. state = state || this.state.clone();
  11546. const arrow = this.tryParse(abort => {
  11547. var _typeParameters;
  11548. typeParameters = this.tsParseTypeParameters();
  11549. const expr = super.parseMaybeAssign(...args);
  11550. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  11551. abort();
  11552. }
  11553. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  11554. this.resetStartLocationFromNode(expr, typeParameters);
  11555. }
  11556. expr.typeParameters = typeParameters;
  11557. return expr;
  11558. }, state);
  11559. if (!arrow.error && !arrow.aborted) return arrow.node;
  11560. if (!jsx) {
  11561. assert$1(!this.hasPlugin("jsx"));
  11562. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  11563. if (!typeCast.error) return typeCast.node;
  11564. }
  11565. if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
  11566. this.state = jsx.failState;
  11567. return jsx.node;
  11568. }
  11569. if (arrow.node) {
  11570. this.state = arrow.failState;
  11571. return arrow.node;
  11572. }
  11573. if ((_typeCast = typeCast) == null ? void 0 : _typeCast.node) {
  11574. this.state = typeCast.failState;
  11575. return typeCast.node;
  11576. }
  11577. if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
  11578. if (arrow.thrown) throw arrow.error;
  11579. if ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.thrown) throw typeCast.error;
  11580. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  11581. }
  11582. parseMaybeUnary(refExpressionErrors) {
  11583. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  11584. return this.tsParseTypeAssertion();
  11585. } else {
  11586. return super.parseMaybeUnary(refExpressionErrors);
  11587. }
  11588. }
  11589. parseArrow(node) {
  11590. if (this.match(types.colon)) {
  11591. const result = this.tryParse(abort => {
  11592. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  11593. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  11594. return returnType;
  11595. });
  11596. if (result.aborted) return;
  11597. if (!result.thrown) {
  11598. if (result.error) this.state = result.failState;
  11599. node.returnType = result.node;
  11600. }
  11601. }
  11602. return super.parseArrow(node);
  11603. }
  11604. parseAssignableListItemTypes(param) {
  11605. if (this.eat(types.question)) {
  11606. if (param.type !== "Identifier" && !this.state.isDeclareContext && !this.state.inType) {
  11607. this.raise(param.start, TSErrors.PatternIsOptional);
  11608. }
  11609. param.optional = true;
  11610. }
  11611. const type = this.tsTryParseTypeAnnotation();
  11612. if (type) param.typeAnnotation = type;
  11613. this.resetEndLocation(param);
  11614. return param;
  11615. }
  11616. toAssignable(node, isLHS = false) {
  11617. switch (node.type) {
  11618. case "TSTypeCastExpression":
  11619. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  11620. case "TSParameterProperty":
  11621. return super.toAssignable(node, isLHS);
  11622. case "TSAsExpression":
  11623. case "TSNonNullExpression":
  11624. case "TSTypeAssertion":
  11625. node.expression = this.toAssignable(node.expression, isLHS);
  11626. return node;
  11627. default:
  11628. return super.toAssignable(node, isLHS);
  11629. }
  11630. }
  11631. checkLVal(expr, contextDescription, ...args) {
  11632. switch (expr.type) {
  11633. case "TSTypeCastExpression":
  11634. return;
  11635. case "TSParameterProperty":
  11636. this.checkLVal(expr.parameter, "parameter property", ...args);
  11637. return;
  11638. case "TSAsExpression":
  11639. case "TSNonNullExpression":
  11640. case "TSTypeAssertion":
  11641. this.checkLVal(expr.expression, contextDescription, ...args);
  11642. return;
  11643. default:
  11644. super.checkLVal(expr, contextDescription, ...args);
  11645. return;
  11646. }
  11647. }
  11648. parseBindingAtom() {
  11649. switch (this.state.type) {
  11650. case types._this:
  11651. return this.parseIdentifier(true);
  11652. default:
  11653. return super.parseBindingAtom();
  11654. }
  11655. }
  11656. parseMaybeDecoratorArguments(expr) {
  11657. if (this.isRelational("<")) {
  11658. const typeArguments = this.tsParseTypeArguments();
  11659. if (this.match(types.parenL)) {
  11660. const call = super.parseMaybeDecoratorArguments(expr);
  11661. call.typeParameters = typeArguments;
  11662. return call;
  11663. }
  11664. this.unexpected(this.state.start, types.parenL);
  11665. }
  11666. return super.parseMaybeDecoratorArguments(expr);
  11667. }
  11668. isClassMethod() {
  11669. return this.isRelational("<") || super.isClassMethod();
  11670. }
  11671. isClassProperty() {
  11672. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  11673. }
  11674. parseMaybeDefault(...args) {
  11675. const node = super.parseMaybeDefault(...args);
  11676. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  11677. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  11678. }
  11679. return node;
  11680. }
  11681. getTokenFromCode(code) {
  11682. if (this.state.inType && (code === 62 || code === 60)) {
  11683. return this.finishOp(types.relational, 1);
  11684. } else {
  11685. return super.getTokenFromCode(code);
  11686. }
  11687. }
  11688. reScan_lt_gt() {
  11689. if (this.match(types.relational)) {
  11690. const code = this.input.charCodeAt(this.state.start);
  11691. if (code === 60 || code === 62) {
  11692. this.state.pos -= 1;
  11693. this.readToken_lt_gt(code);
  11694. }
  11695. }
  11696. }
  11697. toAssignableList(exprList) {
  11698. for (let i = 0; i < exprList.length; i++) {
  11699. const expr = exprList[i];
  11700. if (!expr) continue;
  11701. switch (expr.type) {
  11702. case "TSTypeCastExpression":
  11703. exprList[i] = this.typeCastToParameter(expr);
  11704. break;
  11705. case "TSAsExpression":
  11706. case "TSTypeAssertion":
  11707. if (!this.state.maybeInArrowParameters) {
  11708. exprList[i] = this.typeCastToParameter(expr);
  11709. } else {
  11710. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  11711. }
  11712. break;
  11713. }
  11714. }
  11715. return super.toAssignableList(...arguments);
  11716. }
  11717. typeCastToParameter(node) {
  11718. node.expression.typeAnnotation = node.typeAnnotation;
  11719. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  11720. return node.expression;
  11721. }
  11722. shouldParseArrow() {
  11723. return this.match(types.colon) || super.shouldParseArrow();
  11724. }
  11725. shouldParseAsyncArrow() {
  11726. return this.match(types.colon) || super.shouldParseAsyncArrow();
  11727. }
  11728. canHaveLeadingDecorator() {
  11729. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  11730. }
  11731. jsxParseOpeningElementAfterName(node) {
  11732. if (this.isRelational("<")) {
  11733. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  11734. if (typeArguments) node.typeParameters = typeArguments;
  11735. }
  11736. return super.jsxParseOpeningElementAfterName(node);
  11737. }
  11738. getGetterSetterExpectedParamCount(method) {
  11739. const baseCount = super.getGetterSetterExpectedParamCount(method);
  11740. const params = this.getObjectOrClassMethodParams(method);
  11741. const firstParam = params[0];
  11742. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  11743. return hasContextParam ? baseCount + 1 : baseCount;
  11744. }
  11745. parseCatchClauseParam() {
  11746. const param = super.parseCatchClauseParam();
  11747. const type = this.tsTryParseTypeAnnotation();
  11748. if (type) {
  11749. param.typeAnnotation = type;
  11750. this.resetEndLocation(param);
  11751. }
  11752. return param;
  11753. }
  11754. tsInDeclareContext(cb) {
  11755. const oldIsDeclareContext = this.state.isDeclareContext;
  11756. this.state.isDeclareContext = true;
  11757. try {
  11758. return cb();
  11759. } finally {
  11760. this.state.isDeclareContext = oldIsDeclareContext;
  11761. }
  11762. }
  11763. });
  11764. types.placeholder = new TokenType("%%", {
  11765. startsExpr: true
  11766. });
  11767. var placeholders = (superClass => class extends superClass {
  11768. parsePlaceholder(expectedNode) {
  11769. if (this.match(types.placeholder)) {
  11770. const node = this.startNode();
  11771. this.next();
  11772. this.assertNoSpace("Unexpected space in placeholder.");
  11773. node.name = super.parseIdentifier(true);
  11774. this.assertNoSpace("Unexpected space in placeholder.");
  11775. this.expect(types.placeholder);
  11776. return this.finishPlaceholder(node, expectedNode);
  11777. }
  11778. }
  11779. finishPlaceholder(node, expectedNode) {
  11780. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  11781. node.expectedNode = expectedNode;
  11782. return isFinished ? node : this.finishNode(node, "Placeholder");
  11783. }
  11784. getTokenFromCode(code) {
  11785. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  11786. return this.finishOp(types.placeholder, 2);
  11787. }
  11788. return super.getTokenFromCode(...arguments);
  11789. }
  11790. parseExprAtom() {
  11791. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  11792. }
  11793. parseIdentifier() {
  11794. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  11795. }
  11796. checkReservedWord(word) {
  11797. if (word !== undefined) super.checkReservedWord(...arguments);
  11798. }
  11799. parseBindingAtom() {
  11800. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  11801. }
  11802. checkLVal(expr) {
  11803. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  11804. }
  11805. toAssignable(node) {
  11806. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  11807. node.expectedNode = "Pattern";
  11808. return node;
  11809. }
  11810. return super.toAssignable(...arguments);
  11811. }
  11812. verifyBreakContinue(node) {
  11813. if (node.label && node.label.type === "Placeholder") return;
  11814. super.verifyBreakContinue(...arguments);
  11815. }
  11816. parseExpressionStatement(node, expr) {
  11817. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  11818. return super.parseExpressionStatement(...arguments);
  11819. }
  11820. if (this.match(types.colon)) {
  11821. const stmt = node;
  11822. stmt.label = this.finishPlaceholder(expr, "Identifier");
  11823. this.next();
  11824. stmt.body = this.parseStatement("label");
  11825. return this.finishNode(stmt, "LabeledStatement");
  11826. }
  11827. this.semicolon();
  11828. node.name = expr.name;
  11829. return this.finishPlaceholder(node, "Statement");
  11830. }
  11831. parseBlock() {
  11832. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  11833. }
  11834. parseFunctionId() {
  11835. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  11836. }
  11837. parseClass(node, isStatement, optionalId) {
  11838. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  11839. this.next();
  11840. this.takeDecorators(node);
  11841. const oldStrict = this.state.strict;
  11842. const placeholder = this.parsePlaceholder("Identifier");
  11843. if (placeholder) {
  11844. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  11845. node.id = placeholder;
  11846. } else if (optionalId || !isStatement) {
  11847. node.id = null;
  11848. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  11849. return this.finishNode(node, type);
  11850. } else {
  11851. this.unexpected(null, "A class name is required");
  11852. }
  11853. } else {
  11854. this.parseClassId(node, isStatement, optionalId);
  11855. }
  11856. this.parseClassSuper(node);
  11857. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  11858. return this.finishNode(node, type);
  11859. }
  11860. parseExport(node) {
  11861. const placeholder = this.parsePlaceholder("Identifier");
  11862. if (!placeholder) return super.parseExport(...arguments);
  11863. if (!this.isContextual("from") && !this.match(types.comma)) {
  11864. node.specifiers = [];
  11865. node.source = null;
  11866. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  11867. return this.finishNode(node, "ExportNamedDeclaration");
  11868. }
  11869. this.expectPlugin("exportDefaultFrom");
  11870. const specifier = this.startNode();
  11871. specifier.exported = placeholder;
  11872. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  11873. return super.parseExport(node);
  11874. }
  11875. isExportDefaultSpecifier() {
  11876. if (this.match(types._default)) {
  11877. const next = this.nextTokenStart();
  11878. if (this.isUnparsedContextual(next, "from")) {
  11879. if (this.input.startsWith(types.placeholder.label, this.nextTokenStartSince(next + 4))) {
  11880. return true;
  11881. }
  11882. }
  11883. }
  11884. return super.isExportDefaultSpecifier();
  11885. }
  11886. maybeParseExportDefaultSpecifier(node) {
  11887. if (node.specifiers && node.specifiers.length > 0) {
  11888. return true;
  11889. }
  11890. return super.maybeParseExportDefaultSpecifier(...arguments);
  11891. }
  11892. checkExport(node) {
  11893. const {
  11894. specifiers
  11895. } = node;
  11896. if (specifiers == null ? void 0 : specifiers.length) {
  11897. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  11898. }
  11899. super.checkExport(node);
  11900. node.specifiers = specifiers;
  11901. }
  11902. parseImport(node) {
  11903. const placeholder = this.parsePlaceholder("Identifier");
  11904. if (!placeholder) return super.parseImport(...arguments);
  11905. node.specifiers = [];
  11906. if (!this.isContextual("from") && !this.match(types.comma)) {
  11907. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  11908. this.semicolon();
  11909. return this.finishNode(node, "ImportDeclaration");
  11910. }
  11911. const specifier = this.startNodeAtNode(placeholder);
  11912. specifier.local = placeholder;
  11913. this.finishNode(specifier, "ImportDefaultSpecifier");
  11914. node.specifiers.push(specifier);
  11915. if (this.eat(types.comma)) {
  11916. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  11917. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  11918. }
  11919. this.expectContextual("from");
  11920. node.source = this.parseImportSource();
  11921. this.semicolon();
  11922. return this.finishNode(node, "ImportDeclaration");
  11923. }
  11924. parseImportSource() {
  11925. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  11926. }
  11927. });
  11928. var v8intrinsic = (superClass => class extends superClass {
  11929. parseV8Intrinsic() {
  11930. if (this.match(types.modulo)) {
  11931. const v8IntrinsicStart = this.state.start;
  11932. const node = this.startNode();
  11933. this.eat(types.modulo);
  11934. if (this.match(types.name)) {
  11935. const name = this.parseIdentifierName(this.state.start);
  11936. const identifier = this.createIdentifier(node, name);
  11937. identifier.type = "V8IntrinsicIdentifier";
  11938. if (this.match(types.parenL)) {
  11939. return identifier;
  11940. }
  11941. }
  11942. this.unexpected(v8IntrinsicStart);
  11943. }
  11944. }
  11945. parseExprAtom() {
  11946. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  11947. }
  11948. });
  11949. function hasPlugin(plugins, name) {
  11950. return plugins.some(plugin => {
  11951. if (Array.isArray(plugin)) {
  11952. return plugin[0] === name;
  11953. } else {
  11954. return plugin === name;
  11955. }
  11956. });
  11957. }
  11958. function getPluginOption(plugins, name, option) {
  11959. const plugin = plugins.find(plugin => {
  11960. if (Array.isArray(plugin)) {
  11961. return plugin[0] === name;
  11962. } else {
  11963. return plugin === name;
  11964. }
  11965. });
  11966. if (plugin && Array.isArray(plugin)) {
  11967. return plugin[1][option];
  11968. }
  11969. return null;
  11970. }
  11971. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  11972. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  11973. function validatePlugins(plugins) {
  11974. if (hasPlugin(plugins, "decorators")) {
  11975. if (hasPlugin(plugins, "decorators-legacy")) {
  11976. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  11977. }
  11978. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  11979. if (decoratorsBeforeExport == null) {
  11980. throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option," + " whose value must be a boolean. If you are migrating from" + " Babylon/Babel 6 or want to use the old decorators proposal, you" + " should use the 'decorators-legacy' plugin instead of 'decorators'.");
  11981. } else if (typeof decoratorsBeforeExport !== "boolean") {
  11982. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  11983. }
  11984. }
  11985. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  11986. throw new Error("Cannot combine flow and typescript plugins.");
  11987. }
  11988. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  11989. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  11990. }
  11991. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  11992. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  11993. }
  11994. if (hasPlugin(plugins, "moduleAttributes")) {
  11995. if (hasPlugin(plugins, "importAssertions")) {
  11996. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  11997. }
  11998. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  11999. if (moduleAttributesVerionPluginOption !== "may-2020") {
  12000. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  12001. }
  12002. }
  12003. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  12004. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  12005. }
  12006. }
  12007. const mixinPlugins = {
  12008. estree,
  12009. jsx,
  12010. flow,
  12011. typescript,
  12012. v8intrinsic,
  12013. placeholders
  12014. };
  12015. const mixinPluginNames = Object.keys(mixinPlugins);
  12016. const defaultOptions = {
  12017. sourceType: "script",
  12018. sourceFilename: undefined,
  12019. startLine: 1,
  12020. allowAwaitOutsideFunction: false,
  12021. allowReturnOutsideFunction: false,
  12022. allowImportExportEverywhere: false,
  12023. allowSuperOutsideMethod: false,
  12024. allowUndeclaredExports: false,
  12025. plugins: [],
  12026. strictMode: null,
  12027. ranges: false,
  12028. tokens: false,
  12029. createParenthesizedExpressions: false,
  12030. errorRecovery: false
  12031. };
  12032. function getOptions(opts) {
  12033. const options = {};
  12034. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  12035. const key = _Object$keys[_i];
  12036. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  12037. }
  12038. return options;
  12039. }
  12040. class State {
  12041. constructor() {
  12042. this.strict = void 0;
  12043. this.curLine = void 0;
  12044. this.startLoc = void 0;
  12045. this.endLoc = void 0;
  12046. this.errors = [];
  12047. this.potentialArrowAt = -1;
  12048. this.noArrowAt = [];
  12049. this.noArrowParamsConversionAt = [];
  12050. this.maybeInArrowParameters = false;
  12051. this.inPipeline = false;
  12052. this.inType = false;
  12053. this.noAnonFunctionType = false;
  12054. this.inPropertyName = false;
  12055. this.hasFlowComment = false;
  12056. this.isIterator = false;
  12057. this.isDeclareContext = false;
  12058. this.topicContext = {
  12059. maxNumOfResolvableTopics: 0,
  12060. maxTopicIndex: null
  12061. };
  12062. this.soloAwait = false;
  12063. this.inFSharpPipelineDirectBody = false;
  12064. this.labels = [];
  12065. this.decoratorStack = [[]];
  12066. this.comments = [];
  12067. this.trailingComments = [];
  12068. this.leadingComments = [];
  12069. this.commentStack = [];
  12070. this.commentPreviousNode = null;
  12071. this.pos = 0;
  12072. this.lineStart = 0;
  12073. this.type = types.eof;
  12074. this.value = null;
  12075. this.start = 0;
  12076. this.end = 0;
  12077. this.lastTokEndLoc = null;
  12078. this.lastTokStartLoc = null;
  12079. this.lastTokStart = 0;
  12080. this.lastTokEnd = 0;
  12081. this.context = [types$1.braceStatement];
  12082. this.exprAllowed = true;
  12083. this.containsEsc = false;
  12084. this.octalPositions = [];
  12085. this.exportedIdentifiers = [];
  12086. this.tokensLength = 0;
  12087. }
  12088. init(options) {
  12089. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  12090. this.curLine = options.startLine;
  12091. this.startLoc = this.endLoc = this.curPosition();
  12092. }
  12093. curPosition() {
  12094. return new Position(this.curLine, this.pos - this.lineStart);
  12095. }
  12096. clone(skipArrays) {
  12097. const state = new State();
  12098. const keys = Object.keys(this);
  12099. for (let i = 0, length = keys.length; i < length; i++) {
  12100. const key = keys[i];
  12101. let val = this[key];
  12102. if (!skipArrays && Array.isArray(val)) {
  12103. val = val.slice();
  12104. }
  12105. state[key] = val;
  12106. }
  12107. return state;
  12108. }
  12109. }
  12110. var _isDigit = function isDigit(code) {
  12111. return code >= 48 && code <= 57;
  12112. };
  12113. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  12114. const forbiddenNumericSeparatorSiblings = {
  12115. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  12116. hex: [46, 88, 95, 120]
  12117. };
  12118. const allowedNumericSeparatorSiblings = {};
  12119. allowedNumericSeparatorSiblings.bin = [48, 49];
  12120. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  12121. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  12122. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  12123. class Token {
  12124. constructor(state) {
  12125. this.type = state.type;
  12126. this.value = state.value;
  12127. this.start = state.start;
  12128. this.end = state.end;
  12129. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  12130. }
  12131. }
  12132. class Tokenizer extends ParserError {
  12133. constructor(options, input) {
  12134. super();
  12135. this.isLookahead = void 0;
  12136. this.tokens = [];
  12137. this.state = new State();
  12138. this.state.init(options);
  12139. this.input = input;
  12140. this.length = input.length;
  12141. this.isLookahead = false;
  12142. }
  12143. pushToken(token) {
  12144. this.tokens.length = this.state.tokensLength;
  12145. this.tokens.push(token);
  12146. ++this.state.tokensLength;
  12147. }
  12148. next() {
  12149. if (!this.isLookahead) {
  12150. this.checkKeywordEscapes();
  12151. if (this.options.tokens) {
  12152. this.pushToken(new Token(this.state));
  12153. }
  12154. }
  12155. this.state.lastTokEnd = this.state.end;
  12156. this.state.lastTokStart = this.state.start;
  12157. this.state.lastTokEndLoc = this.state.endLoc;
  12158. this.state.lastTokStartLoc = this.state.startLoc;
  12159. this.nextToken();
  12160. }
  12161. eat(type) {
  12162. if (this.match(type)) {
  12163. this.next();
  12164. return true;
  12165. } else {
  12166. return false;
  12167. }
  12168. }
  12169. match(type) {
  12170. return this.state.type === type;
  12171. }
  12172. lookahead() {
  12173. const old = this.state;
  12174. this.state = old.clone(true);
  12175. this.isLookahead = true;
  12176. this.next();
  12177. this.isLookahead = false;
  12178. const curr = this.state;
  12179. this.state = old;
  12180. return curr;
  12181. }
  12182. nextTokenStart() {
  12183. return this.nextTokenStartSince(this.state.pos);
  12184. }
  12185. nextTokenStartSince(pos) {
  12186. skipWhiteSpace.lastIndex = pos;
  12187. const skip = skipWhiteSpace.exec(this.input);
  12188. return pos + skip[0].length;
  12189. }
  12190. lookaheadCharCode() {
  12191. return this.input.charCodeAt(this.nextTokenStart());
  12192. }
  12193. setStrict(strict) {
  12194. this.state.strict = strict;
  12195. if (!this.match(types.num) && !this.match(types.string)) return;
  12196. this.state.pos = this.state.start;
  12197. while (this.state.pos < this.state.lineStart) {
  12198. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  12199. --this.state.curLine;
  12200. }
  12201. this.nextToken();
  12202. }
  12203. curContext() {
  12204. return this.state.context[this.state.context.length - 1];
  12205. }
  12206. nextToken() {
  12207. const curContext = this.curContext();
  12208. if (!(curContext == null ? void 0 : curContext.preserveSpace)) this.skipSpace();
  12209. this.state.octalPositions = [];
  12210. this.state.start = this.state.pos;
  12211. this.state.startLoc = this.state.curPosition();
  12212. if (this.state.pos >= this.length) {
  12213. this.finishToken(types.eof);
  12214. return;
  12215. }
  12216. const override = curContext == null ? void 0 : curContext.override;
  12217. if (override) {
  12218. override(this);
  12219. } else {
  12220. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  12221. }
  12222. }
  12223. pushComment(block, text, start, end, startLoc, endLoc) {
  12224. const comment = {
  12225. type: block ? "CommentBlock" : "CommentLine",
  12226. value: text,
  12227. start: start,
  12228. end: end,
  12229. loc: new SourceLocation(startLoc, endLoc)
  12230. };
  12231. if (this.options.tokens) this.pushToken(comment);
  12232. this.state.comments.push(comment);
  12233. this.addComment(comment);
  12234. }
  12235. skipBlockComment() {
  12236. const startLoc = this.state.curPosition();
  12237. const start = this.state.pos;
  12238. const end = this.input.indexOf("*/", this.state.pos + 2);
  12239. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  12240. this.state.pos = end + 2;
  12241. lineBreakG.lastIndex = start;
  12242. let match;
  12243. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  12244. ++this.state.curLine;
  12245. this.state.lineStart = match.index + match[0].length;
  12246. }
  12247. if (this.isLookahead) return;
  12248. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  12249. }
  12250. skipLineComment(startSkip) {
  12251. const start = this.state.pos;
  12252. const startLoc = this.state.curPosition();
  12253. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  12254. if (this.state.pos < this.length) {
  12255. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  12256. ch = this.input.charCodeAt(this.state.pos);
  12257. }
  12258. }
  12259. if (this.isLookahead) return;
  12260. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  12261. }
  12262. skipSpace() {
  12263. loop: while (this.state.pos < this.length) {
  12264. const ch = this.input.charCodeAt(this.state.pos);
  12265. switch (ch) {
  12266. case 32:
  12267. case 160:
  12268. case 9:
  12269. ++this.state.pos;
  12270. break;
  12271. case 13:
  12272. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  12273. ++this.state.pos;
  12274. }
  12275. case 10:
  12276. case 8232:
  12277. case 8233:
  12278. ++this.state.pos;
  12279. ++this.state.curLine;
  12280. this.state.lineStart = this.state.pos;
  12281. break;
  12282. case 47:
  12283. switch (this.input.charCodeAt(this.state.pos + 1)) {
  12284. case 42:
  12285. this.skipBlockComment();
  12286. break;
  12287. case 47:
  12288. this.skipLineComment(2);
  12289. break;
  12290. default:
  12291. break loop;
  12292. }
  12293. break;
  12294. default:
  12295. if (isWhitespace(ch)) {
  12296. ++this.state.pos;
  12297. } else {
  12298. break loop;
  12299. }
  12300. }
  12301. }
  12302. }
  12303. finishToken(type, val) {
  12304. this.state.end = this.state.pos;
  12305. this.state.endLoc = this.state.curPosition();
  12306. const prevType = this.state.type;
  12307. this.state.type = type;
  12308. this.state.value = val;
  12309. if (!this.isLookahead) this.updateContext(prevType);
  12310. }
  12311. readToken_numberSign() {
  12312. if (this.state.pos === 0 && this.readToken_interpreter()) {
  12313. return;
  12314. }
  12315. const nextPos = this.state.pos + 1;
  12316. const next = this.input.charCodeAt(nextPos);
  12317. if (next >= 48 && next <= 57) {
  12318. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  12319. }
  12320. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  12321. this.expectPlugin("recordAndTuple");
  12322. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  12323. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  12324. }
  12325. if (next === 123) {
  12326. this.finishToken(types.braceHashL);
  12327. } else {
  12328. this.finishToken(types.bracketHashL);
  12329. }
  12330. this.state.pos += 2;
  12331. } else {
  12332. this.finishOp(types.hash, 1);
  12333. }
  12334. }
  12335. readToken_dot() {
  12336. const next = this.input.charCodeAt(this.state.pos + 1);
  12337. if (next >= 48 && next <= 57) {
  12338. this.readNumber(true);
  12339. return;
  12340. }
  12341. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  12342. this.state.pos += 3;
  12343. this.finishToken(types.ellipsis);
  12344. } else {
  12345. ++this.state.pos;
  12346. this.finishToken(types.dot);
  12347. }
  12348. }
  12349. readToken_slash() {
  12350. if (this.state.exprAllowed && !this.state.inType) {
  12351. ++this.state.pos;
  12352. this.readRegexp();
  12353. return;
  12354. }
  12355. const next = this.input.charCodeAt(this.state.pos + 1);
  12356. if (next === 61) {
  12357. this.finishOp(types.assign, 2);
  12358. } else {
  12359. this.finishOp(types.slash, 1);
  12360. }
  12361. }
  12362. readToken_interpreter() {
  12363. if (this.state.pos !== 0 || this.length < 2) return false;
  12364. let ch = this.input.charCodeAt(this.state.pos + 1);
  12365. if (ch !== 33) return false;
  12366. const start = this.state.pos;
  12367. this.state.pos += 1;
  12368. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  12369. ch = this.input.charCodeAt(this.state.pos);
  12370. }
  12371. const value = this.input.slice(start + 2, this.state.pos);
  12372. this.finishToken(types.interpreterDirective, value);
  12373. return true;
  12374. }
  12375. readToken_mult_modulo(code) {
  12376. let type = code === 42 ? types.star : types.modulo;
  12377. let width = 1;
  12378. let next = this.input.charCodeAt(this.state.pos + 1);
  12379. const exprAllowed = this.state.exprAllowed;
  12380. if (code === 42 && next === 42) {
  12381. width++;
  12382. next = this.input.charCodeAt(this.state.pos + 2);
  12383. type = types.exponent;
  12384. }
  12385. if (next === 61 && !exprAllowed) {
  12386. width++;
  12387. type = types.assign;
  12388. }
  12389. this.finishOp(type, width);
  12390. }
  12391. readToken_pipe_amp(code) {
  12392. const next = this.input.charCodeAt(this.state.pos + 1);
  12393. if (next === code) {
  12394. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  12395. this.finishOp(types.assign, 3);
  12396. } else {
  12397. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  12398. }
  12399. return;
  12400. }
  12401. if (code === 124) {
  12402. if (next === 62) {
  12403. this.finishOp(types.pipeline, 2);
  12404. return;
  12405. }
  12406. if (this.hasPlugin("recordAndTuple") && next === 125) {
  12407. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  12408. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  12409. }
  12410. this.finishOp(types.braceBarR, 2);
  12411. return;
  12412. }
  12413. if (this.hasPlugin("recordAndTuple") && next === 93) {
  12414. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  12415. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  12416. }
  12417. this.finishOp(types.bracketBarR, 2);
  12418. return;
  12419. }
  12420. }
  12421. if (next === 61) {
  12422. this.finishOp(types.assign, 2);
  12423. return;
  12424. }
  12425. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  12426. }
  12427. readToken_caret() {
  12428. const next = this.input.charCodeAt(this.state.pos + 1);
  12429. if (next === 61) {
  12430. this.finishOp(types.assign, 2);
  12431. } else {
  12432. this.finishOp(types.bitwiseXOR, 1);
  12433. }
  12434. }
  12435. readToken_plus_min(code) {
  12436. const next = this.input.charCodeAt(this.state.pos + 1);
  12437. if (next === code) {
  12438. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || this.hasPrecedingLineBreak())) {
  12439. this.skipLineComment(3);
  12440. this.skipSpace();
  12441. this.nextToken();
  12442. return;
  12443. }
  12444. this.finishOp(types.incDec, 2);
  12445. return;
  12446. }
  12447. if (next === 61) {
  12448. this.finishOp(types.assign, 2);
  12449. } else {
  12450. this.finishOp(types.plusMin, 1);
  12451. }
  12452. }
  12453. readToken_lt_gt(code) {
  12454. const next = this.input.charCodeAt(this.state.pos + 1);
  12455. let size = 1;
  12456. if (next === code) {
  12457. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  12458. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  12459. this.finishOp(types.assign, size + 1);
  12460. return;
  12461. }
  12462. this.finishOp(types.bitShift, size);
  12463. return;
  12464. }
  12465. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  12466. this.skipLineComment(4);
  12467. this.skipSpace();
  12468. this.nextToken();
  12469. return;
  12470. }
  12471. if (next === 61) {
  12472. size = 2;
  12473. }
  12474. this.finishOp(types.relational, size);
  12475. }
  12476. readToken_eq_excl(code) {
  12477. const next = this.input.charCodeAt(this.state.pos + 1);
  12478. if (next === 61) {
  12479. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  12480. return;
  12481. }
  12482. if (code === 61 && next === 62) {
  12483. this.state.pos += 2;
  12484. this.finishToken(types.arrow);
  12485. return;
  12486. }
  12487. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  12488. }
  12489. readToken_question() {
  12490. const next = this.input.charCodeAt(this.state.pos + 1);
  12491. const next2 = this.input.charCodeAt(this.state.pos + 2);
  12492. if (next === 63) {
  12493. if (next2 === 61) {
  12494. this.finishOp(types.assign, 3);
  12495. } else {
  12496. this.finishOp(types.nullishCoalescing, 2);
  12497. }
  12498. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  12499. this.state.pos += 2;
  12500. this.finishToken(types.questionDot);
  12501. } else {
  12502. ++this.state.pos;
  12503. this.finishToken(types.question);
  12504. }
  12505. }
  12506. getTokenFromCode(code) {
  12507. switch (code) {
  12508. case 46:
  12509. this.readToken_dot();
  12510. return;
  12511. case 40:
  12512. ++this.state.pos;
  12513. this.finishToken(types.parenL);
  12514. return;
  12515. case 41:
  12516. ++this.state.pos;
  12517. this.finishToken(types.parenR);
  12518. return;
  12519. case 59:
  12520. ++this.state.pos;
  12521. this.finishToken(types.semi);
  12522. return;
  12523. case 44:
  12524. ++this.state.pos;
  12525. this.finishToken(types.comma);
  12526. return;
  12527. case 91:
  12528. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  12529. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  12530. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  12531. }
  12532. this.finishToken(types.bracketBarL);
  12533. this.state.pos += 2;
  12534. } else {
  12535. ++this.state.pos;
  12536. this.finishToken(types.bracketL);
  12537. }
  12538. return;
  12539. case 93:
  12540. ++this.state.pos;
  12541. this.finishToken(types.bracketR);
  12542. return;
  12543. case 123:
  12544. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  12545. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  12546. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  12547. }
  12548. this.finishToken(types.braceBarL);
  12549. this.state.pos += 2;
  12550. } else {
  12551. ++this.state.pos;
  12552. this.finishToken(types.braceL);
  12553. }
  12554. return;
  12555. case 125:
  12556. ++this.state.pos;
  12557. this.finishToken(types.braceR);
  12558. return;
  12559. case 58:
  12560. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  12561. this.finishOp(types.doubleColon, 2);
  12562. } else {
  12563. ++this.state.pos;
  12564. this.finishToken(types.colon);
  12565. }
  12566. return;
  12567. case 63:
  12568. this.readToken_question();
  12569. return;
  12570. case 96:
  12571. ++this.state.pos;
  12572. this.finishToken(types.backQuote);
  12573. return;
  12574. case 48:
  12575. {
  12576. const next = this.input.charCodeAt(this.state.pos + 1);
  12577. if (next === 120 || next === 88) {
  12578. this.readRadixNumber(16);
  12579. return;
  12580. }
  12581. if (next === 111 || next === 79) {
  12582. this.readRadixNumber(8);
  12583. return;
  12584. }
  12585. if (next === 98 || next === 66) {
  12586. this.readRadixNumber(2);
  12587. return;
  12588. }
  12589. }
  12590. case 49:
  12591. case 50:
  12592. case 51:
  12593. case 52:
  12594. case 53:
  12595. case 54:
  12596. case 55:
  12597. case 56:
  12598. case 57:
  12599. this.readNumber(false);
  12600. return;
  12601. case 34:
  12602. case 39:
  12603. this.readString(code);
  12604. return;
  12605. case 47:
  12606. this.readToken_slash();
  12607. return;
  12608. case 37:
  12609. case 42:
  12610. this.readToken_mult_modulo(code);
  12611. return;
  12612. case 124:
  12613. case 38:
  12614. this.readToken_pipe_amp(code);
  12615. return;
  12616. case 94:
  12617. this.readToken_caret();
  12618. return;
  12619. case 43:
  12620. case 45:
  12621. this.readToken_plus_min(code);
  12622. return;
  12623. case 60:
  12624. case 62:
  12625. this.readToken_lt_gt(code);
  12626. return;
  12627. case 61:
  12628. case 33:
  12629. this.readToken_eq_excl(code);
  12630. return;
  12631. case 126:
  12632. this.finishOp(types.tilde, 1);
  12633. return;
  12634. case 64:
  12635. ++this.state.pos;
  12636. this.finishToken(types.at);
  12637. return;
  12638. case 35:
  12639. this.readToken_numberSign();
  12640. return;
  12641. case 92:
  12642. this.readWord();
  12643. return;
  12644. default:
  12645. if (isIdentifierStart(code)) {
  12646. this.readWord();
  12647. return;
  12648. }
  12649. }
  12650. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  12651. }
  12652. finishOp(type, size) {
  12653. const str = this.input.slice(this.state.pos, this.state.pos + size);
  12654. this.state.pos += size;
  12655. this.finishToken(type, str);
  12656. }
  12657. readRegexp() {
  12658. const start = this.state.pos;
  12659. let escaped, inClass;
  12660. for (;;) {
  12661. if (this.state.pos >= this.length) {
  12662. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  12663. }
  12664. const ch = this.input.charAt(this.state.pos);
  12665. if (lineBreak.test(ch)) {
  12666. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  12667. }
  12668. if (escaped) {
  12669. escaped = false;
  12670. } else {
  12671. if (ch === "[") {
  12672. inClass = true;
  12673. } else if (ch === "]" && inClass) {
  12674. inClass = false;
  12675. } else if (ch === "/" && !inClass) {
  12676. break;
  12677. }
  12678. escaped = ch === "\\";
  12679. }
  12680. ++this.state.pos;
  12681. }
  12682. const content = this.input.slice(start, this.state.pos);
  12683. ++this.state.pos;
  12684. let mods = "";
  12685. while (this.state.pos < this.length) {
  12686. const char = this.input[this.state.pos];
  12687. const charCode = this.input.codePointAt(this.state.pos);
  12688. if (VALID_REGEX_FLAGS.has(char)) {
  12689. if (mods.indexOf(char) > -1) {
  12690. this.raise(this.state.pos + 1, ErrorMessages.DuplicateRegExpFlags);
  12691. }
  12692. } else if (isIdentifierChar(charCode) || charCode === 92) {
  12693. this.raise(this.state.pos + 1, ErrorMessages.MalformedRegExpFlags);
  12694. } else {
  12695. break;
  12696. }
  12697. ++this.state.pos;
  12698. mods += char;
  12699. }
  12700. this.finishToken(types.regexp, {
  12701. pattern: content,
  12702. flags: mods
  12703. });
  12704. }
  12705. readInt(radix, len, forceLen, allowNumSeparator = true) {
  12706. const start = this.state.pos;
  12707. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  12708. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  12709. let invalid = false;
  12710. let total = 0;
  12711. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  12712. const code = this.input.charCodeAt(this.state.pos);
  12713. let val;
  12714. if (code === 95) {
  12715. const prev = this.input.charCodeAt(this.state.pos - 1);
  12716. const next = this.input.charCodeAt(this.state.pos + 1);
  12717. if (allowedSiblings.indexOf(next) === -1) {
  12718. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  12719. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  12720. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  12721. }
  12722. if (!allowNumSeparator) {
  12723. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  12724. }
  12725. ++this.state.pos;
  12726. continue;
  12727. }
  12728. if (code >= 97) {
  12729. val = code - 97 + 10;
  12730. } else if (code >= 65) {
  12731. val = code - 65 + 10;
  12732. } else if (_isDigit(code)) {
  12733. val = code - 48;
  12734. } else {
  12735. val = Infinity;
  12736. }
  12737. if (val >= radix) {
  12738. if (this.options.errorRecovery && val <= 9) {
  12739. val = 0;
  12740. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  12741. } else if (forceLen) {
  12742. val = 0;
  12743. invalid = true;
  12744. } else {
  12745. break;
  12746. }
  12747. }
  12748. ++this.state.pos;
  12749. total = total * radix + val;
  12750. }
  12751. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  12752. return null;
  12753. }
  12754. return total;
  12755. }
  12756. readRadixNumber(radix) {
  12757. const start = this.state.pos;
  12758. let isBigInt = false;
  12759. this.state.pos += 2;
  12760. const val = this.readInt(radix);
  12761. if (val == null) {
  12762. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  12763. }
  12764. const next = this.input.charCodeAt(this.state.pos);
  12765. if (next === 110) {
  12766. ++this.state.pos;
  12767. isBigInt = true;
  12768. } else if (next === 109) {
  12769. throw this.raise(start, ErrorMessages.InvalidDecimal);
  12770. }
  12771. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  12772. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  12773. }
  12774. if (isBigInt) {
  12775. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  12776. this.finishToken(types.bigint, str);
  12777. return;
  12778. }
  12779. this.finishToken(types.num, val);
  12780. }
  12781. readNumber(startsWithDot) {
  12782. const start = this.state.pos;
  12783. let isFloat = false;
  12784. let isBigInt = false;
  12785. let isDecimal = false;
  12786. let hasExponent = false;
  12787. let isOctal = false;
  12788. if (!startsWithDot && this.readInt(10) === null) {
  12789. this.raise(start, ErrorMessages.InvalidNumber);
  12790. }
  12791. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  12792. if (hasLeadingZero) {
  12793. const integer = this.input.slice(start, this.state.pos);
  12794. if (this.state.strict) {
  12795. this.raise(start, ErrorMessages.StrictOctalLiteral);
  12796. } else {
  12797. const underscorePos = integer.indexOf("_");
  12798. if (underscorePos > 0) {
  12799. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  12800. }
  12801. }
  12802. isOctal = hasLeadingZero && !/[89]/.test(integer);
  12803. }
  12804. let next = this.input.charCodeAt(this.state.pos);
  12805. if (next === 46 && !isOctal) {
  12806. ++this.state.pos;
  12807. this.readInt(10);
  12808. isFloat = true;
  12809. next = this.input.charCodeAt(this.state.pos);
  12810. }
  12811. if ((next === 69 || next === 101) && !isOctal) {
  12812. next = this.input.charCodeAt(++this.state.pos);
  12813. if (next === 43 || next === 45) {
  12814. ++this.state.pos;
  12815. }
  12816. if (this.readInt(10) === null) {
  12817. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  12818. }
  12819. isFloat = true;
  12820. hasExponent = true;
  12821. next = this.input.charCodeAt(this.state.pos);
  12822. }
  12823. if (next === 110) {
  12824. if (isFloat || hasLeadingZero) {
  12825. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  12826. }
  12827. ++this.state.pos;
  12828. isBigInt = true;
  12829. }
  12830. if (next === 109) {
  12831. this.expectPlugin("decimal", this.state.pos);
  12832. if (hasExponent || hasLeadingZero) {
  12833. this.raise(start, ErrorMessages.InvalidDecimal);
  12834. }
  12835. ++this.state.pos;
  12836. isDecimal = true;
  12837. }
  12838. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  12839. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  12840. }
  12841. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  12842. if (isBigInt) {
  12843. this.finishToken(types.bigint, str);
  12844. return;
  12845. }
  12846. if (isDecimal) {
  12847. this.finishToken(types.decimal, str);
  12848. return;
  12849. }
  12850. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  12851. this.finishToken(types.num, val);
  12852. }
  12853. readCodePoint(throwOnInvalid) {
  12854. const ch = this.input.charCodeAt(this.state.pos);
  12855. let code;
  12856. if (ch === 123) {
  12857. const codePos = ++this.state.pos;
  12858. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  12859. ++this.state.pos;
  12860. if (code !== null && code > 0x10ffff) {
  12861. if (throwOnInvalid) {
  12862. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  12863. } else {
  12864. return null;
  12865. }
  12866. }
  12867. } else {
  12868. code = this.readHexChar(4, false, throwOnInvalid);
  12869. }
  12870. return code;
  12871. }
  12872. readString(quote) {
  12873. let out = "",
  12874. chunkStart = ++this.state.pos;
  12875. for (;;) {
  12876. if (this.state.pos >= this.length) {
  12877. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  12878. }
  12879. const ch = this.input.charCodeAt(this.state.pos);
  12880. if (ch === quote) break;
  12881. if (ch === 92) {
  12882. out += this.input.slice(chunkStart, this.state.pos);
  12883. out += this.readEscapedChar(false);
  12884. chunkStart = this.state.pos;
  12885. } else if (ch === 8232 || ch === 8233) {
  12886. ++this.state.pos;
  12887. ++this.state.curLine;
  12888. this.state.lineStart = this.state.pos;
  12889. } else if (isNewLine(ch)) {
  12890. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  12891. } else {
  12892. ++this.state.pos;
  12893. }
  12894. }
  12895. out += this.input.slice(chunkStart, this.state.pos++);
  12896. this.finishToken(types.string, out);
  12897. }
  12898. readTmplToken() {
  12899. let out = "",
  12900. chunkStart = this.state.pos,
  12901. containsInvalid = false;
  12902. for (;;) {
  12903. if (this.state.pos >= this.length) {
  12904. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  12905. }
  12906. const ch = this.input.charCodeAt(this.state.pos);
  12907. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  12908. if (this.state.pos === this.state.start && this.match(types.template)) {
  12909. if (ch === 36) {
  12910. this.state.pos += 2;
  12911. this.finishToken(types.dollarBraceL);
  12912. return;
  12913. } else {
  12914. ++this.state.pos;
  12915. this.finishToken(types.backQuote);
  12916. return;
  12917. }
  12918. }
  12919. out += this.input.slice(chunkStart, this.state.pos);
  12920. this.finishToken(types.template, containsInvalid ? null : out);
  12921. return;
  12922. }
  12923. if (ch === 92) {
  12924. out += this.input.slice(chunkStart, this.state.pos);
  12925. const escaped = this.readEscapedChar(true);
  12926. if (escaped === null) {
  12927. containsInvalid = true;
  12928. } else {
  12929. out += escaped;
  12930. }
  12931. chunkStart = this.state.pos;
  12932. } else if (isNewLine(ch)) {
  12933. out += this.input.slice(chunkStart, this.state.pos);
  12934. ++this.state.pos;
  12935. switch (ch) {
  12936. case 13:
  12937. if (this.input.charCodeAt(this.state.pos) === 10) {
  12938. ++this.state.pos;
  12939. }
  12940. case 10:
  12941. out += "\n";
  12942. break;
  12943. default:
  12944. out += String.fromCharCode(ch);
  12945. break;
  12946. }
  12947. ++this.state.curLine;
  12948. this.state.lineStart = this.state.pos;
  12949. chunkStart = this.state.pos;
  12950. } else {
  12951. ++this.state.pos;
  12952. }
  12953. }
  12954. }
  12955. readEscapedChar(inTemplate) {
  12956. const throwOnInvalid = !inTemplate;
  12957. const ch = this.input.charCodeAt(++this.state.pos);
  12958. ++this.state.pos;
  12959. switch (ch) {
  12960. case 110:
  12961. return "\n";
  12962. case 114:
  12963. return "\r";
  12964. case 120:
  12965. {
  12966. const code = this.readHexChar(2, false, throwOnInvalid);
  12967. return code === null ? null : String.fromCharCode(code);
  12968. }
  12969. case 117:
  12970. {
  12971. const code = this.readCodePoint(throwOnInvalid);
  12972. return code === null ? null : String.fromCodePoint(code);
  12973. }
  12974. case 116:
  12975. return "\t";
  12976. case 98:
  12977. return "\b";
  12978. case 118:
  12979. return "\u000b";
  12980. case 102:
  12981. return "\f";
  12982. case 13:
  12983. if (this.input.charCodeAt(this.state.pos) === 10) {
  12984. ++this.state.pos;
  12985. }
  12986. case 10:
  12987. this.state.lineStart = this.state.pos;
  12988. ++this.state.curLine;
  12989. case 8232:
  12990. case 8233:
  12991. return "";
  12992. case 56:
  12993. case 57:
  12994. if (inTemplate) {
  12995. return null;
  12996. } else if (this.state.strict) {
  12997. this.raise(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  12998. }
  12999. default:
  13000. if (ch >= 48 && ch <= 55) {
  13001. const codePos = this.state.pos - 1;
  13002. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  13003. let octalStr = match[0];
  13004. let octal = parseInt(octalStr, 8);
  13005. if (octal > 255) {
  13006. octalStr = octalStr.slice(0, -1);
  13007. octal = parseInt(octalStr, 8);
  13008. }
  13009. this.state.pos += octalStr.length - 1;
  13010. const next = this.input.charCodeAt(this.state.pos);
  13011. if (octalStr !== "0" || next === 56 || next === 57) {
  13012. if (inTemplate) {
  13013. return null;
  13014. } else if (this.state.strict) {
  13015. this.raise(codePos, ErrorMessages.StrictNumericEscape);
  13016. } else {
  13017. this.state.octalPositions.push(codePos);
  13018. }
  13019. }
  13020. return String.fromCharCode(octal);
  13021. }
  13022. return String.fromCharCode(ch);
  13023. }
  13024. }
  13025. readHexChar(len, forceLen, throwOnInvalid) {
  13026. const codePos = this.state.pos;
  13027. const n = this.readInt(16, len, forceLen, false);
  13028. if (n === null) {
  13029. if (throwOnInvalid) {
  13030. this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
  13031. } else {
  13032. this.state.pos = codePos - 1;
  13033. }
  13034. }
  13035. return n;
  13036. }
  13037. readWord1() {
  13038. let word = "";
  13039. this.state.containsEsc = false;
  13040. const start = this.state.pos;
  13041. let chunkStart = this.state.pos;
  13042. while (this.state.pos < this.length) {
  13043. const ch = this.input.codePointAt(this.state.pos);
  13044. if (isIdentifierChar(ch)) {
  13045. this.state.pos += ch <= 0xffff ? 1 : 2;
  13046. } else if (this.state.isIterator && ch === 64) {
  13047. ++this.state.pos;
  13048. } else if (ch === 92) {
  13049. this.state.containsEsc = true;
  13050. word += this.input.slice(chunkStart, this.state.pos);
  13051. const escStart = this.state.pos;
  13052. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  13053. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  13054. this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
  13055. continue;
  13056. }
  13057. ++this.state.pos;
  13058. const esc = this.readCodePoint(true);
  13059. if (esc !== null) {
  13060. if (!identifierCheck(esc)) {
  13061. this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
  13062. }
  13063. word += String.fromCodePoint(esc);
  13064. }
  13065. chunkStart = this.state.pos;
  13066. } else {
  13067. break;
  13068. }
  13069. }
  13070. return word + this.input.slice(chunkStart, this.state.pos);
  13071. }
  13072. isIterator(word) {
  13073. return word === "@@iterator" || word === "@@asyncIterator";
  13074. }
  13075. readWord() {
  13076. const word = this.readWord1();
  13077. const type = keywords.get(word) || types.name;
  13078. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  13079. this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, word);
  13080. }
  13081. this.finishToken(type, word);
  13082. }
  13083. checkKeywordEscapes() {
  13084. const kw = this.state.type.keyword;
  13085. if (kw && this.state.containsEsc) {
  13086. this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, kw);
  13087. }
  13088. }
  13089. braceIsBlock(prevType) {
  13090. const parent = this.curContext();
  13091. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  13092. return true;
  13093. }
  13094. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  13095. return !parent.isExpr;
  13096. }
  13097. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  13098. return this.hasPrecedingLineBreak();
  13099. }
  13100. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  13101. return true;
  13102. }
  13103. if (prevType === types.braceL) {
  13104. return parent === types$1.braceStatement;
  13105. }
  13106. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  13107. return false;
  13108. }
  13109. if (prevType === types.relational) {
  13110. return true;
  13111. }
  13112. return !this.state.exprAllowed;
  13113. }
  13114. updateContext(prevType) {
  13115. const type = this.state.type;
  13116. let update;
  13117. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  13118. this.state.exprAllowed = false;
  13119. } else if (update = type.updateContext) {
  13120. update.call(this, prevType);
  13121. } else {
  13122. this.state.exprAllowed = type.beforeExpr;
  13123. }
  13124. }
  13125. }
  13126. class UtilParser extends Tokenizer {
  13127. addExtra(node, key, val) {
  13128. if (!node) return;
  13129. const extra = node.extra = node.extra || {};
  13130. extra[key] = val;
  13131. }
  13132. isRelational(op) {
  13133. return this.match(types.relational) && this.state.value === op;
  13134. }
  13135. expectRelational(op) {
  13136. if (this.isRelational(op)) {
  13137. this.next();
  13138. } else {
  13139. this.unexpected(null, types.relational);
  13140. }
  13141. }
  13142. isContextual(name) {
  13143. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  13144. }
  13145. isUnparsedContextual(nameStart, name) {
  13146. const nameEnd = nameStart + name.length;
  13147. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  13148. }
  13149. isLookaheadContextual(name) {
  13150. const next = this.nextTokenStart();
  13151. return this.isUnparsedContextual(next, name);
  13152. }
  13153. eatContextual(name) {
  13154. return this.isContextual(name) && this.eat(types.name);
  13155. }
  13156. expectContextual(name, message) {
  13157. if (!this.eatContextual(name)) this.unexpected(null, message);
  13158. }
  13159. canInsertSemicolon() {
  13160. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  13161. }
  13162. hasPrecedingLineBreak() {
  13163. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  13164. }
  13165. isLineTerminator() {
  13166. return this.eat(types.semi) || this.canInsertSemicolon();
  13167. }
  13168. semicolon() {
  13169. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  13170. }
  13171. expect(type, pos) {
  13172. this.eat(type) || this.unexpected(pos, type);
  13173. }
  13174. assertNoSpace(message = "Unexpected space.") {
  13175. if (this.state.start > this.state.lastTokEnd) {
  13176. this.raise(this.state.lastTokEnd, message);
  13177. }
  13178. }
  13179. unexpected(pos, messageOrType = "Unexpected token") {
  13180. if (typeof messageOrType !== "string") {
  13181. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  13182. }
  13183. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  13184. }
  13185. expectPlugin(name, pos) {
  13186. if (!this.hasPlugin(name)) {
  13187. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  13188. missingPlugin: [name]
  13189. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  13190. }
  13191. return true;
  13192. }
  13193. expectOnePlugin(names, pos) {
  13194. if (!names.some(n => this.hasPlugin(n))) {
  13195. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  13196. missingPlugin: names
  13197. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  13198. }
  13199. }
  13200. tryParse(fn, oldState = this.state.clone()) {
  13201. const abortSignal = {
  13202. node: null
  13203. };
  13204. try {
  13205. const node = fn((node = null) => {
  13206. abortSignal.node = node;
  13207. throw abortSignal;
  13208. });
  13209. if (this.state.errors.length > oldState.errors.length) {
  13210. const failState = this.state;
  13211. this.state = oldState;
  13212. return {
  13213. node,
  13214. error: failState.errors[oldState.errors.length],
  13215. thrown: false,
  13216. aborted: false,
  13217. failState
  13218. };
  13219. }
  13220. return {
  13221. node,
  13222. error: null,
  13223. thrown: false,
  13224. aborted: false,
  13225. failState: null
  13226. };
  13227. } catch (error) {
  13228. const failState = this.state;
  13229. this.state = oldState;
  13230. if (error instanceof SyntaxError) {
  13231. return {
  13232. node: null,
  13233. error,
  13234. thrown: true,
  13235. aborted: false,
  13236. failState
  13237. };
  13238. }
  13239. if (error === abortSignal) {
  13240. return {
  13241. node: abortSignal.node,
  13242. error: null,
  13243. thrown: false,
  13244. aborted: true,
  13245. failState
  13246. };
  13247. }
  13248. throw error;
  13249. }
  13250. }
  13251. checkExpressionErrors(refExpressionErrors, andThrow) {
  13252. if (!refExpressionErrors) return false;
  13253. const {
  13254. shorthandAssign,
  13255. doubleProto
  13256. } = refExpressionErrors;
  13257. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  13258. if (shorthandAssign >= 0) {
  13259. this.unexpected(shorthandAssign);
  13260. }
  13261. if (doubleProto >= 0) {
  13262. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  13263. }
  13264. }
  13265. isLiteralPropertyName() {
  13266. return this.match(types.name) || !!this.state.type.keyword || this.match(types.string) || this.match(types.num) || this.match(types.bigint) || this.match(types.decimal);
  13267. }
  13268. }
  13269. class ExpressionErrors {
  13270. constructor() {
  13271. this.shorthandAssign = -1;
  13272. this.doubleProto = -1;
  13273. }
  13274. }
  13275. class Node {
  13276. constructor(parser, pos, loc) {
  13277. this.type = void 0;
  13278. this.start = void 0;
  13279. this.end = void 0;
  13280. this.loc = void 0;
  13281. this.range = void 0;
  13282. this.leadingComments = void 0;
  13283. this.trailingComments = void 0;
  13284. this.innerComments = void 0;
  13285. this.extra = void 0;
  13286. this.type = "";
  13287. this.start = pos;
  13288. this.end = 0;
  13289. this.loc = new SourceLocation(loc);
  13290. if (parser == null ? void 0 : parser.options.ranges) this.range = [pos, 0];
  13291. if (parser == null ? void 0 : parser.filename) this.loc.filename = parser.filename;
  13292. }
  13293. __clone() {
  13294. const newNode = new Node();
  13295. const keys = Object.keys(this);
  13296. for (let i = 0, length = keys.length; i < length; i++) {
  13297. const key = keys[i];
  13298. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  13299. newNode[key] = this[key];
  13300. }
  13301. }
  13302. return newNode;
  13303. }
  13304. }
  13305. class NodeUtils extends UtilParser {
  13306. startNode() {
  13307. return new Node(this, this.state.start, this.state.startLoc);
  13308. }
  13309. startNodeAt(pos, loc) {
  13310. return new Node(this, pos, loc);
  13311. }
  13312. startNodeAtNode(type) {
  13313. return this.startNodeAt(type.start, type.loc.start);
  13314. }
  13315. finishNode(node, type) {
  13316. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  13317. }
  13318. finishNodeAt(node, type, pos, loc) {
  13319. node.type = type;
  13320. node.end = pos;
  13321. node.loc.end = loc;
  13322. if (this.options.ranges) node.range[1] = pos;
  13323. this.processComment(node);
  13324. return node;
  13325. }
  13326. resetStartLocation(node, start, startLoc) {
  13327. node.start = start;
  13328. node.loc.start = startLoc;
  13329. if (this.options.ranges) node.range[0] = start;
  13330. }
  13331. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  13332. node.end = end;
  13333. node.loc.end = endLoc;
  13334. if (this.options.ranges) node.range[1] = end;
  13335. }
  13336. resetStartLocationFromNode(node, locationNode) {
  13337. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  13338. }
  13339. }
  13340. const unwrapParenthesizedExpression = node => {
  13341. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  13342. };
  13343. class LValParser extends NodeUtils {
  13344. toAssignable(node, isLHS = false) {
  13345. var _node$extra, _node$extra3;
  13346. let parenthesized = undefined;
  13347. if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) {
  13348. parenthesized = unwrapParenthesizedExpression(node);
  13349. if (isLHS) {
  13350. if (parenthesized.type === "Identifier") {
  13351. this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  13352. } else if (parenthesized.type !== "MemberExpression") {
  13353. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  13354. }
  13355. } else {
  13356. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  13357. }
  13358. }
  13359. switch (node.type) {
  13360. case "Identifier":
  13361. case "ObjectPattern":
  13362. case "ArrayPattern":
  13363. case "AssignmentPattern":
  13364. break;
  13365. case "ObjectExpression":
  13366. node.type = "ObjectPattern";
  13367. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  13368. var _node$extra2;
  13369. const prop = node.properties[i];
  13370. const isLast = i === last;
  13371. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  13372. if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) {
  13373. this.raiseRestNotLast(node.extra.trailingComma);
  13374. }
  13375. }
  13376. break;
  13377. case "ObjectProperty":
  13378. this.toAssignable(node.value, isLHS);
  13379. break;
  13380. case "SpreadElement":
  13381. {
  13382. this.checkToRestConversion(node);
  13383. node.type = "RestElement";
  13384. const arg = node.argument;
  13385. this.toAssignable(arg, isLHS);
  13386. break;
  13387. }
  13388. case "ArrayExpression":
  13389. node.type = "ArrayPattern";
  13390. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS);
  13391. break;
  13392. case "AssignmentExpression":
  13393. if (node.operator !== "=") {
  13394. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  13395. }
  13396. node.type = "AssignmentPattern";
  13397. delete node.operator;
  13398. this.toAssignable(node.left, isLHS);
  13399. break;
  13400. case "ParenthesizedExpression":
  13401. this.toAssignable(parenthesized, isLHS);
  13402. break;
  13403. }
  13404. return node;
  13405. }
  13406. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  13407. if (prop.type === "ObjectMethod") {
  13408. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  13409. this.raise(prop.key.start, error);
  13410. } else if (prop.type === "SpreadElement" && !isLast) {
  13411. this.raiseRestNotLast(prop.start);
  13412. } else {
  13413. this.toAssignable(prop, isLHS);
  13414. }
  13415. }
  13416. toAssignableList(exprList, trailingCommaPos, isLHS) {
  13417. let end = exprList.length;
  13418. if (end) {
  13419. const last = exprList[end - 1];
  13420. if ((last == null ? void 0 : last.type) === "RestElement") {
  13421. --end;
  13422. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  13423. last.type = "RestElement";
  13424. let arg = last.argument;
  13425. this.toAssignable(arg, isLHS);
  13426. arg = unwrapParenthesizedExpression(arg);
  13427. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  13428. this.unexpected(arg.start);
  13429. }
  13430. if (trailingCommaPos) {
  13431. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  13432. }
  13433. --end;
  13434. }
  13435. }
  13436. for (let i = 0; i < end; i++) {
  13437. const elt = exprList[i];
  13438. if (elt) {
  13439. this.toAssignable(elt, isLHS);
  13440. if (elt.type === "RestElement") {
  13441. this.raiseRestNotLast(elt.start);
  13442. }
  13443. }
  13444. }
  13445. return exprList;
  13446. }
  13447. toReferencedList(exprList, isParenthesizedExpr) {
  13448. return exprList;
  13449. }
  13450. toReferencedListDeep(exprList, isParenthesizedExpr) {
  13451. this.toReferencedList(exprList, isParenthesizedExpr);
  13452. for (let _i = 0; _i < exprList.length; _i++) {
  13453. const expr = exprList[_i];
  13454. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  13455. this.toReferencedListDeep(expr.elements);
  13456. }
  13457. }
  13458. }
  13459. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  13460. const node = this.startNode();
  13461. this.next();
  13462. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  13463. return this.finishNode(node, "SpreadElement");
  13464. }
  13465. parseRestBinding() {
  13466. const node = this.startNode();
  13467. this.next();
  13468. node.argument = this.parseBindingAtom();
  13469. return this.finishNode(node, "RestElement");
  13470. }
  13471. parseBindingAtom() {
  13472. switch (this.state.type) {
  13473. case types.bracketL:
  13474. {
  13475. const node = this.startNode();
  13476. this.next();
  13477. node.elements = this.parseBindingList(types.bracketR, 93, true);
  13478. return this.finishNode(node, "ArrayPattern");
  13479. }
  13480. case types.braceL:
  13481. return this.parseObjectLike(types.braceR, true);
  13482. }
  13483. return this.parseIdentifier();
  13484. }
  13485. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  13486. const elts = [];
  13487. let first = true;
  13488. while (!this.eat(close)) {
  13489. if (first) {
  13490. first = false;
  13491. } else {
  13492. this.expect(types.comma);
  13493. }
  13494. if (allowEmpty && this.match(types.comma)) {
  13495. elts.push(null);
  13496. } else if (this.eat(close)) {
  13497. break;
  13498. } else if (this.match(types.ellipsis)) {
  13499. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  13500. this.checkCommaAfterRest(closeCharCode);
  13501. this.expect(close);
  13502. break;
  13503. } else {
  13504. const decorators = [];
  13505. if (this.match(types.at) && this.hasPlugin("decorators")) {
  13506. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  13507. }
  13508. while (this.match(types.at)) {
  13509. decorators.push(this.parseDecorator());
  13510. }
  13511. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  13512. }
  13513. }
  13514. return elts;
  13515. }
  13516. parseAssignableListItem(allowModifiers, decorators) {
  13517. const left = this.parseMaybeDefault();
  13518. this.parseAssignableListItemTypes(left);
  13519. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  13520. if (decorators.length) {
  13521. left.decorators = decorators;
  13522. }
  13523. return elt;
  13524. }
  13525. parseAssignableListItemTypes(param) {
  13526. return param;
  13527. }
  13528. parseMaybeDefault(startPos, startLoc, left) {
  13529. var _startLoc, _startPos, _left;
  13530. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  13531. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  13532. left = (_left = left) != null ? _left : this.parseBindingAtom();
  13533. if (!this.eat(types.eq)) return left;
  13534. const node = this.startNodeAt(startPos, startLoc);
  13535. node.left = left;
  13536. node.right = this.parseMaybeAssignAllowIn();
  13537. return this.finishNode(node, "AssignmentPattern");
  13538. }
  13539. checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) {
  13540. switch (expr.type) {
  13541. case "Identifier":
  13542. {
  13543. const {
  13544. name
  13545. } = expr;
  13546. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) {
  13547. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name);
  13548. }
  13549. if (checkClashes) {
  13550. if (checkClashes.has(name)) {
  13551. this.raise(expr.start, ErrorMessages.ParamDupe);
  13552. } else {
  13553. checkClashes.add(name);
  13554. }
  13555. }
  13556. if (disallowLetBinding && name === "let") {
  13557. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  13558. }
  13559. if (!(bindingType & BIND_NONE)) {
  13560. this.scope.declareName(name, bindingType, expr.start);
  13561. }
  13562. break;
  13563. }
  13564. case "MemberExpression":
  13565. if (bindingType !== BIND_NONE) {
  13566. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  13567. }
  13568. break;
  13569. case "ObjectPattern":
  13570. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  13571. let prop = _expr$properties[_i2];
  13572. if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue;
  13573. this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  13574. }
  13575. break;
  13576. case "ArrayPattern":
  13577. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  13578. const elem = _expr$elements[_i3];
  13579. if (elem) {
  13580. this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  13581. }
  13582. }
  13583. break;
  13584. case "AssignmentPattern":
  13585. this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes);
  13586. break;
  13587. case "RestElement":
  13588. this.checkLVal(expr.argument, "rest element", bindingType, checkClashes);
  13589. break;
  13590. case "ParenthesizedExpression":
  13591. this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes);
  13592. break;
  13593. default:
  13594. {
  13595. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  13596. }
  13597. }
  13598. }
  13599. checkToRestConversion(node) {
  13600. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  13601. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  13602. }
  13603. }
  13604. checkCommaAfterRest(close) {
  13605. if (this.match(types.comma)) {
  13606. if (this.lookaheadCharCode() === close) {
  13607. this.raiseTrailingCommaAfterRest(this.state.start);
  13608. } else {
  13609. this.raiseRestNotLast(this.state.start);
  13610. }
  13611. }
  13612. }
  13613. raiseRestNotLast(pos) {
  13614. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  13615. }
  13616. raiseTrailingCommaAfterRest(pos) {
  13617. this.raise(pos, ErrorMessages.RestTrailingComma);
  13618. }
  13619. }
  13620. const kExpression = 0,
  13621. kMaybeArrowParameterDeclaration = 1,
  13622. kMaybeAsyncArrowParameterDeclaration = 2,
  13623. kParameterDeclaration = 3;
  13624. class ExpressionScope {
  13625. constructor(type = kExpression) {
  13626. this.type = void 0;
  13627. this.type = type;
  13628. }
  13629. canBeArrowParameterDeclaration() {
  13630. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  13631. }
  13632. isCertainlyParameterDeclaration() {
  13633. return this.type === kParameterDeclaration;
  13634. }
  13635. }
  13636. class ArrowHeadParsingScope extends ExpressionScope {
  13637. constructor(type) {
  13638. super(type);
  13639. this.errors = new Map();
  13640. }
  13641. recordDeclarationError(pos, message) {
  13642. this.errors.set(pos, message);
  13643. }
  13644. clearDeclarationError(pos) {
  13645. this.errors.delete(pos);
  13646. }
  13647. iterateErrors(iterator) {
  13648. this.errors.forEach(iterator);
  13649. }
  13650. }
  13651. class ExpressionScopeHandler {
  13652. constructor(raise) {
  13653. this.stack = [new ExpressionScope()];
  13654. this.raise = raise;
  13655. }
  13656. enter(scope) {
  13657. this.stack.push(scope);
  13658. }
  13659. exit() {
  13660. this.stack.pop();
  13661. }
  13662. recordParameterInitializerError(pos, message) {
  13663. const {
  13664. stack
  13665. } = this;
  13666. let i = stack.length - 1;
  13667. let scope = stack[i];
  13668. while (!scope.isCertainlyParameterDeclaration()) {
  13669. if (scope.canBeArrowParameterDeclaration()) {
  13670. scope.recordDeclarationError(pos, message);
  13671. } else {
  13672. return;
  13673. }
  13674. scope = stack[--i];
  13675. }
  13676. this.raise(pos, message);
  13677. }
  13678. recordParenthesizedIdentifierError(pos, message) {
  13679. const {
  13680. stack
  13681. } = this;
  13682. const scope = stack[stack.length - 1];
  13683. if (scope.isCertainlyParameterDeclaration()) {
  13684. this.raise(pos, message);
  13685. } else if (scope.canBeArrowParameterDeclaration()) {
  13686. scope.recordDeclarationError(pos, message);
  13687. } else {
  13688. return;
  13689. }
  13690. }
  13691. recordAsyncArrowParametersError(pos, message) {
  13692. const {
  13693. stack
  13694. } = this;
  13695. let i = stack.length - 1;
  13696. let scope = stack[i];
  13697. while (scope.canBeArrowParameterDeclaration()) {
  13698. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  13699. scope.recordDeclarationError(pos, message);
  13700. }
  13701. scope = stack[--i];
  13702. }
  13703. }
  13704. validateAsPattern() {
  13705. const {
  13706. stack
  13707. } = this;
  13708. const currentScope = stack[stack.length - 1];
  13709. if (!currentScope.canBeArrowParameterDeclaration()) return;
  13710. currentScope.iterateErrors((message, pos) => {
  13711. this.raise(pos, message);
  13712. let i = stack.length - 2;
  13713. let scope = stack[i];
  13714. while (scope.canBeArrowParameterDeclaration()) {
  13715. scope.clearDeclarationError(pos);
  13716. scope = stack[--i];
  13717. }
  13718. });
  13719. }
  13720. }
  13721. function newParameterDeclarationScope() {
  13722. return new ExpressionScope(kParameterDeclaration);
  13723. }
  13724. function newArrowHeadScope() {
  13725. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  13726. }
  13727. function newAsyncArrowScope() {
  13728. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  13729. }
  13730. function newExpressionScope() {
  13731. return new ExpressionScope();
  13732. }
  13733. class ExpressionParser extends LValParser {
  13734. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  13735. if (prop.type === "SpreadElement" || prop.type === "ObjectMethod" || prop.computed || prop.shorthand) {
  13736. return;
  13737. }
  13738. const key = prop.key;
  13739. const name = key.type === "Identifier" ? key.name : key.value;
  13740. if (name === "__proto__") {
  13741. if (isRecord) {
  13742. this.raise(key.start, ErrorMessages.RecordNoProto);
  13743. return;
  13744. }
  13745. if (protoRef.used) {
  13746. if (refExpressionErrors) {
  13747. if (refExpressionErrors.doubleProto === -1) {
  13748. refExpressionErrors.doubleProto = key.start;
  13749. }
  13750. } else {
  13751. this.raise(key.start, ErrorMessages.DuplicateProto);
  13752. }
  13753. }
  13754. protoRef.used = true;
  13755. }
  13756. }
  13757. shouldExitDescending(expr, potentialArrowAt) {
  13758. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  13759. }
  13760. getExpression() {
  13761. let paramFlags = PARAM;
  13762. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  13763. paramFlags |= PARAM_AWAIT;
  13764. }
  13765. this.scope.enter(SCOPE_PROGRAM);
  13766. this.prodParam.enter(paramFlags);
  13767. this.nextToken();
  13768. const expr = this.parseExpression();
  13769. if (!this.match(types.eof)) {
  13770. this.unexpected();
  13771. }
  13772. expr.comments = this.state.comments;
  13773. expr.errors = this.state.errors;
  13774. return expr;
  13775. }
  13776. parseExpression(disallowIn, refExpressionErrors) {
  13777. if (disallowIn) {
  13778. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  13779. }
  13780. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  13781. }
  13782. parseExpressionBase(refExpressionErrors) {
  13783. const startPos = this.state.start;
  13784. const startLoc = this.state.startLoc;
  13785. const expr = this.parseMaybeAssign(refExpressionErrors);
  13786. if (this.match(types.comma)) {
  13787. const node = this.startNodeAt(startPos, startLoc);
  13788. node.expressions = [expr];
  13789. while (this.eat(types.comma)) {
  13790. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  13791. }
  13792. this.toReferencedList(node.expressions);
  13793. return this.finishNode(node, "SequenceExpression");
  13794. }
  13795. return expr;
  13796. }
  13797. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  13798. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  13799. }
  13800. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  13801. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  13802. }
  13803. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  13804. const startPos = this.state.start;
  13805. const startLoc = this.state.startLoc;
  13806. if (this.isContextual("yield")) {
  13807. if (this.prodParam.hasYield) {
  13808. this.state.exprAllowed = true;
  13809. let left = this.parseYield();
  13810. if (afterLeftParse) {
  13811. left = afterLeftParse.call(this, left, startPos, startLoc);
  13812. }
  13813. return left;
  13814. }
  13815. }
  13816. let ownExpressionErrors;
  13817. if (refExpressionErrors) {
  13818. ownExpressionErrors = false;
  13819. } else {
  13820. refExpressionErrors = new ExpressionErrors();
  13821. ownExpressionErrors = true;
  13822. }
  13823. if (this.match(types.parenL) || this.match(types.name)) {
  13824. this.state.potentialArrowAt = this.state.start;
  13825. }
  13826. let left = this.parseMaybeConditional(refExpressionErrors, refNeedsArrowPos);
  13827. if (afterLeftParse) {
  13828. left = afterLeftParse.call(this, left, startPos, startLoc);
  13829. }
  13830. if (this.state.type.isAssign) {
  13831. const node = this.startNodeAt(startPos, startLoc);
  13832. const operator = this.state.value;
  13833. node.operator = operator;
  13834. if (this.match(types.eq)) {
  13835. node.left = this.toAssignable(left, true);
  13836. refExpressionErrors.doubleProto = -1;
  13837. } else {
  13838. node.left = left;
  13839. }
  13840. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  13841. refExpressionErrors.shorthandAssign = -1;
  13842. }
  13843. this.checkLVal(left, "assignment expression");
  13844. this.next();
  13845. node.right = this.parseMaybeAssign();
  13846. return this.finishNode(node, "AssignmentExpression");
  13847. } else if (ownExpressionErrors) {
  13848. this.checkExpressionErrors(refExpressionErrors, true);
  13849. }
  13850. return left;
  13851. }
  13852. parseMaybeConditional(refExpressionErrors, refNeedsArrowPos) {
  13853. const startPos = this.state.start;
  13854. const startLoc = this.state.startLoc;
  13855. const potentialArrowAt = this.state.potentialArrowAt;
  13856. const expr = this.parseExprOps(refExpressionErrors);
  13857. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  13858. return expr;
  13859. }
  13860. return this.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  13861. }
  13862. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  13863. if (this.eat(types.question)) {
  13864. const node = this.startNodeAt(startPos, startLoc);
  13865. node.test = expr;
  13866. node.consequent = this.parseMaybeAssignAllowIn();
  13867. this.expect(types.colon);
  13868. node.alternate = this.parseMaybeAssign();
  13869. return this.finishNode(node, "ConditionalExpression");
  13870. }
  13871. return expr;
  13872. }
  13873. parseExprOps(refExpressionErrors) {
  13874. const startPos = this.state.start;
  13875. const startLoc = this.state.startLoc;
  13876. const potentialArrowAt = this.state.potentialArrowAt;
  13877. const expr = this.parseMaybeUnary(refExpressionErrors);
  13878. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  13879. return expr;
  13880. }
  13881. return this.parseExprOp(expr, startPos, startLoc, -1);
  13882. }
  13883. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  13884. let prec = this.state.type.binop;
  13885. if (prec != null && (this.prodParam.hasIn || !this.match(types._in))) {
  13886. if (prec > minPrec) {
  13887. const op = this.state.type;
  13888. if (op === types.pipeline) {
  13889. this.expectPlugin("pipelineOperator");
  13890. if (this.state.inFSharpPipelineDirectBody) {
  13891. return left;
  13892. }
  13893. this.state.inPipeline = true;
  13894. this.checkPipelineAtInfixOperator(left, leftStartPos);
  13895. }
  13896. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  13897. node.left = left;
  13898. node.operator = this.state.value;
  13899. if (op === types.exponent && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  13900. this.raise(left.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  13901. }
  13902. const logical = op === types.logicalOR || op === types.logicalAND;
  13903. const coalesce = op === types.nullishCoalescing;
  13904. if (coalesce) {
  13905. prec = types.logicalAND.binop;
  13906. }
  13907. this.next();
  13908. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  13909. if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
  13910. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  13911. }
  13912. }
  13913. node.right = this.parseExprOpRightExpr(op, prec);
  13914. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  13915. const nextOp = this.state.type;
  13916. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  13917. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  13918. }
  13919. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  13920. }
  13921. }
  13922. return left;
  13923. }
  13924. parseExprOpRightExpr(op, prec) {
  13925. const startPos = this.state.start;
  13926. const startLoc = this.state.startLoc;
  13927. switch (op) {
  13928. case types.pipeline:
  13929. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  13930. case "smart":
  13931. return this.withTopicPermittingContext(() => {
  13932. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  13933. });
  13934. case "fsharp":
  13935. return this.withSoloAwaitPermittingContext(() => {
  13936. return this.parseFSharpPipelineBody(prec);
  13937. });
  13938. }
  13939. default:
  13940. return this.parseExprOpBaseRightExpr(op, prec);
  13941. }
  13942. }
  13943. parseExprOpBaseRightExpr(op, prec) {
  13944. const startPos = this.state.start;
  13945. const startLoc = this.state.startLoc;
  13946. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec);
  13947. }
  13948. parseMaybeUnary(refExpressionErrors) {
  13949. if (this.isContextual("await") && this.isAwaitAllowed()) {
  13950. return this.parseAwait();
  13951. }
  13952. const update = this.match(types.incDec);
  13953. const node = this.startNode();
  13954. if (this.state.type.prefix) {
  13955. node.operator = this.state.value;
  13956. node.prefix = true;
  13957. if (this.match(types._throw)) {
  13958. this.expectPlugin("throwExpressions");
  13959. }
  13960. const isDelete = this.match(types._delete);
  13961. this.next();
  13962. node.argument = this.parseMaybeUnary();
  13963. this.checkExpressionErrors(refExpressionErrors, true);
  13964. if (this.state.strict && isDelete) {
  13965. const arg = node.argument;
  13966. if (arg.type === "Identifier") {
  13967. this.raise(node.start, ErrorMessages.StrictDelete);
  13968. } else if ((arg.type === "MemberExpression" || arg.type === "OptionalMemberExpression") && arg.property.type === "PrivateName") {
  13969. this.raise(node.start, ErrorMessages.DeletePrivateField);
  13970. }
  13971. }
  13972. if (!update) {
  13973. return this.finishNode(node, "UnaryExpression");
  13974. }
  13975. }
  13976. return this.parseUpdate(node, update, refExpressionErrors);
  13977. }
  13978. parseUpdate(node, update, refExpressionErrors) {
  13979. if (update) {
  13980. this.checkLVal(node.argument, "prefix operation");
  13981. return this.finishNode(node, "UpdateExpression");
  13982. }
  13983. const startPos = this.state.start;
  13984. const startLoc = this.state.startLoc;
  13985. let expr = this.parseExprSubscripts(refExpressionErrors);
  13986. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  13987. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  13988. const node = this.startNodeAt(startPos, startLoc);
  13989. node.operator = this.state.value;
  13990. node.prefix = false;
  13991. node.argument = expr;
  13992. this.checkLVal(expr, "postfix operation");
  13993. this.next();
  13994. expr = this.finishNode(node, "UpdateExpression");
  13995. }
  13996. return expr;
  13997. }
  13998. parseExprSubscripts(refExpressionErrors) {
  13999. const startPos = this.state.start;
  14000. const startLoc = this.state.startLoc;
  14001. const potentialArrowAt = this.state.potentialArrowAt;
  14002. const expr = this.parseExprAtom(refExpressionErrors);
  14003. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  14004. return expr;
  14005. }
  14006. return this.parseSubscripts(expr, startPos, startLoc);
  14007. }
  14008. parseSubscripts(base, startPos, startLoc, noCalls) {
  14009. const state = {
  14010. optionalChainMember: false,
  14011. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  14012. stop: false
  14013. };
  14014. do {
  14015. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  14016. state.maybeAsyncArrow = false;
  14017. } while (!state.stop);
  14018. return base;
  14019. }
  14020. parseSubscript(base, startPos, startLoc, noCalls, state) {
  14021. if (!noCalls && this.eat(types.doubleColon)) {
  14022. return this.parseBind(base, startPos, startLoc, noCalls, state);
  14023. } else if (this.match(types.backQuote)) {
  14024. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  14025. }
  14026. let optional = false;
  14027. if (this.match(types.questionDot)) {
  14028. state.optionalChainMember = optional = true;
  14029. if (noCalls && this.lookaheadCharCode() === 40) {
  14030. state.stop = true;
  14031. return base;
  14032. }
  14033. this.next();
  14034. }
  14035. if (!noCalls && this.match(types.parenL)) {
  14036. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  14037. } else if (optional || this.match(types.bracketL) || this.eat(types.dot)) {
  14038. return this.parseMember(base, startPos, startLoc, state, optional);
  14039. } else {
  14040. state.stop = true;
  14041. return base;
  14042. }
  14043. }
  14044. parseMember(base, startPos, startLoc, state, optional) {
  14045. const node = this.startNodeAt(startPos, startLoc);
  14046. const computed = this.eat(types.bracketL);
  14047. node.object = base;
  14048. node.computed = computed;
  14049. const property = computed ? this.parseExpression() : this.parseMaybePrivateName(true);
  14050. if (property.type === "PrivateName") {
  14051. if (node.object.type === "Super") {
  14052. this.raise(startPos, ErrorMessages.SuperPrivateField);
  14053. }
  14054. this.classScope.usePrivateName(property.id.name, property.start);
  14055. }
  14056. node.property = property;
  14057. if (computed) {
  14058. this.expect(types.bracketR);
  14059. }
  14060. if (state.optionalChainMember) {
  14061. node.optional = optional;
  14062. return this.finishNode(node, "OptionalMemberExpression");
  14063. } else {
  14064. return this.finishNode(node, "MemberExpression");
  14065. }
  14066. }
  14067. parseBind(base, startPos, startLoc, noCalls, state) {
  14068. const node = this.startNodeAt(startPos, startLoc);
  14069. node.object = base;
  14070. node.callee = this.parseNoCallExpr();
  14071. state.stop = true;
  14072. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  14073. }
  14074. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  14075. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  14076. this.state.maybeInArrowParameters = true;
  14077. this.next();
  14078. let node = this.startNodeAt(startPos, startLoc);
  14079. node.callee = base;
  14080. if (state.maybeAsyncArrow) {
  14081. this.expressionScope.enter(newAsyncArrowScope());
  14082. }
  14083. if (state.optionalChainMember) {
  14084. node.optional = optional;
  14085. }
  14086. if (optional) {
  14087. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  14088. } else {
  14089. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  14090. }
  14091. this.finishCallExpression(node, state.optionalChainMember);
  14092. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  14093. state.stop = true;
  14094. this.expressionScope.validateAsPattern();
  14095. this.expressionScope.exit();
  14096. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  14097. } else {
  14098. if (state.maybeAsyncArrow) {
  14099. this.expressionScope.exit();
  14100. }
  14101. this.toReferencedArguments(node);
  14102. }
  14103. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  14104. return node;
  14105. }
  14106. toReferencedArguments(node, isParenthesizedExpr) {
  14107. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  14108. }
  14109. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  14110. const node = this.startNodeAt(startPos, startLoc);
  14111. node.tag = base;
  14112. node.quasi = this.parseTemplate(true);
  14113. if (state.optionalChainMember) {
  14114. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  14115. }
  14116. return this.finishNode(node, "TaggedTemplateExpression");
  14117. }
  14118. atPossibleAsyncArrow(base) {
  14119. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  14120. }
  14121. finishCallExpression(node, optional) {
  14122. if (node.callee.type === "Import") {
  14123. if (node.arguments.length === 2) {
  14124. if (!this.hasPlugin("moduleAttributes")) {
  14125. this.expectPlugin("importAssertions");
  14126. }
  14127. }
  14128. if (node.arguments.length === 0 || node.arguments.length > 2) {
  14129. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  14130. } else {
  14131. for (let _i = 0, _node$arguments = node.arguments; _i < _node$arguments.length; _i++) {
  14132. const arg = _node$arguments[_i];
  14133. if (arg.type === "SpreadElement") {
  14134. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  14135. }
  14136. }
  14137. }
  14138. }
  14139. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  14140. }
  14141. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  14142. const elts = [];
  14143. let first = true;
  14144. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  14145. this.state.inFSharpPipelineDirectBody = false;
  14146. while (!this.eat(close)) {
  14147. if (first) {
  14148. first = false;
  14149. } else {
  14150. this.expect(types.comma);
  14151. if (this.match(close)) {
  14152. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  14153. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  14154. }
  14155. if (nodeForExtra) {
  14156. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  14157. }
  14158. this.next();
  14159. break;
  14160. }
  14161. }
  14162. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  14163. start: 0
  14164. } : undefined, allowPlaceholder));
  14165. }
  14166. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  14167. return elts;
  14168. }
  14169. shouldParseAsyncArrow() {
  14170. return this.match(types.arrow) && !this.canInsertSemicolon();
  14171. }
  14172. parseAsyncArrowFromCallExpression(node, call) {
  14173. var _call$extra;
  14174. this.expect(types.arrow);
  14175. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  14176. return node;
  14177. }
  14178. parseNoCallExpr() {
  14179. const startPos = this.state.start;
  14180. const startLoc = this.state.startLoc;
  14181. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  14182. }
  14183. parseExprAtom(refExpressionErrors) {
  14184. if (this.state.type === types.slash) this.readRegexp();
  14185. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  14186. let node;
  14187. switch (this.state.type) {
  14188. case types._super:
  14189. return this.parseSuper();
  14190. case types._import:
  14191. node = this.startNode();
  14192. this.next();
  14193. if (this.match(types.dot)) {
  14194. return this.parseImportMetaProperty(node);
  14195. }
  14196. if (!this.match(types.parenL)) {
  14197. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  14198. }
  14199. return this.finishNode(node, "Import");
  14200. case types._this:
  14201. node = this.startNode();
  14202. this.next();
  14203. return this.finishNode(node, "ThisExpression");
  14204. case types.name:
  14205. {
  14206. const containsEsc = this.state.containsEsc;
  14207. const id = this.parseIdentifier();
  14208. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  14209. if (this.match(types._function)) {
  14210. const last = this.state.context.length - 1;
  14211. if (this.state.context[last] !== types$1.functionStatement) {
  14212. throw new Error("Internal error");
  14213. }
  14214. this.state.context[last] = types$1.functionExpression;
  14215. this.next();
  14216. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  14217. } else if (this.match(types.name)) {
  14218. return this.parseAsyncArrowUnaryFunction(id);
  14219. }
  14220. }
  14221. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  14222. this.next();
  14223. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  14224. }
  14225. return id;
  14226. }
  14227. case types._do:
  14228. {
  14229. return this.parseDo();
  14230. }
  14231. case types.regexp:
  14232. {
  14233. const value = this.state.value;
  14234. node = this.parseLiteral(value.value, "RegExpLiteral");
  14235. node.pattern = value.pattern;
  14236. node.flags = value.flags;
  14237. return node;
  14238. }
  14239. case types.num:
  14240. return this.parseLiteral(this.state.value, "NumericLiteral");
  14241. case types.bigint:
  14242. return this.parseLiteral(this.state.value, "BigIntLiteral");
  14243. case types.decimal:
  14244. return this.parseLiteral(this.state.value, "DecimalLiteral");
  14245. case types.string:
  14246. return this.parseLiteral(this.state.value, "StringLiteral");
  14247. case types._null:
  14248. node = this.startNode();
  14249. this.next();
  14250. return this.finishNode(node, "NullLiteral");
  14251. case types._true:
  14252. case types._false:
  14253. return this.parseBooleanLiteral();
  14254. case types.parenL:
  14255. return this.parseParenAndDistinguishExpression(canBeArrow);
  14256. case types.bracketBarL:
  14257. case types.bracketHashL:
  14258. {
  14259. return this.parseArrayLike(this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR, false, true, refExpressionErrors);
  14260. }
  14261. case types.bracketL:
  14262. {
  14263. return this.parseArrayLike(types.bracketR, true, false, refExpressionErrors);
  14264. }
  14265. case types.braceBarL:
  14266. case types.braceHashL:
  14267. {
  14268. return this.parseObjectLike(this.state.type === types.braceBarL ? types.braceBarR : types.braceR, false, true, refExpressionErrors);
  14269. }
  14270. case types.braceL:
  14271. {
  14272. return this.parseObjectLike(types.braceR, false, false, refExpressionErrors);
  14273. }
  14274. case types._function:
  14275. return this.parseFunctionOrFunctionSent();
  14276. case types.at:
  14277. this.parseDecorators();
  14278. case types._class:
  14279. node = this.startNode();
  14280. this.takeDecorators(node);
  14281. return this.parseClass(node, false);
  14282. case types._new:
  14283. return this.parseNewOrNewTarget();
  14284. case types.backQuote:
  14285. return this.parseTemplate(false);
  14286. case types.doubleColon:
  14287. {
  14288. node = this.startNode();
  14289. this.next();
  14290. node.object = null;
  14291. const callee = node.callee = this.parseNoCallExpr();
  14292. if (callee.type === "MemberExpression") {
  14293. return this.finishNode(node, "BindExpression");
  14294. } else {
  14295. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  14296. }
  14297. }
  14298. case types.hash:
  14299. {
  14300. if (this.state.inPipeline) {
  14301. node = this.startNode();
  14302. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  14303. this.raise(node.start, ErrorMessages.PrimaryTopicRequiresSmartPipeline);
  14304. }
  14305. this.next();
  14306. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  14307. this.raise(node.start, ErrorMessages.PrimaryTopicNotAllowed);
  14308. }
  14309. this.registerTopicReference();
  14310. return this.finishNode(node, "PipelinePrimaryTopicReference");
  14311. }
  14312. const nextCh = this.input.codePointAt(this.state.end);
  14313. if (isIdentifierStart(nextCh) || nextCh === 92) {
  14314. const start = this.state.start;
  14315. node = this.parseMaybePrivateName(true);
  14316. if (this.match(types._in)) {
  14317. this.expectPlugin("privateIn");
  14318. this.classScope.usePrivateName(node.id.name, node.start);
  14319. } else if (this.hasPlugin("privateIn")) {
  14320. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, node.id.name);
  14321. } else {
  14322. throw this.unexpected(start);
  14323. }
  14324. return node;
  14325. }
  14326. }
  14327. case types.relational:
  14328. {
  14329. if (this.state.value === "<") {
  14330. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  14331. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  14332. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  14333. }
  14334. }
  14335. }
  14336. default:
  14337. throw this.unexpected();
  14338. }
  14339. }
  14340. parseAsyncArrowUnaryFunction(id) {
  14341. const node = this.startNodeAtNode(id);
  14342. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  14343. const params = [this.parseIdentifier()];
  14344. this.prodParam.exit();
  14345. if (this.hasPrecedingLineBreak()) {
  14346. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  14347. }
  14348. this.expect(types.arrow);
  14349. this.parseArrowExpression(node, params, true);
  14350. return node;
  14351. }
  14352. parseDo() {
  14353. this.expectPlugin("doExpressions");
  14354. const node = this.startNode();
  14355. this.next();
  14356. const oldLabels = this.state.labels;
  14357. this.state.labels = [];
  14358. node.body = this.parseBlock();
  14359. this.state.labels = oldLabels;
  14360. return this.finishNode(node, "DoExpression");
  14361. }
  14362. parseSuper() {
  14363. const node = this.startNode();
  14364. this.next();
  14365. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  14366. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  14367. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  14368. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  14369. }
  14370. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  14371. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  14372. }
  14373. return this.finishNode(node, "Super");
  14374. }
  14375. parseBooleanLiteral() {
  14376. const node = this.startNode();
  14377. node.value = this.match(types._true);
  14378. this.next();
  14379. return this.finishNode(node, "BooleanLiteral");
  14380. }
  14381. parseMaybePrivateName(isPrivateNameAllowed) {
  14382. const isPrivate = this.match(types.hash);
  14383. if (isPrivate) {
  14384. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  14385. if (!isPrivateNameAllowed) {
  14386. this.raise(this.state.pos, ErrorMessages.UnexpectedPrivateField);
  14387. }
  14388. const node = this.startNode();
  14389. this.next();
  14390. this.assertNoSpace("Unexpected space between # and identifier");
  14391. node.id = this.parseIdentifier(true);
  14392. return this.finishNode(node, "PrivateName");
  14393. } else {
  14394. return this.parseIdentifier(true);
  14395. }
  14396. }
  14397. parseFunctionOrFunctionSent() {
  14398. const node = this.startNode();
  14399. this.next();
  14400. if (this.prodParam.hasYield && this.match(types.dot)) {
  14401. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  14402. this.next();
  14403. return this.parseMetaProperty(node, meta, "sent");
  14404. }
  14405. return this.parseFunction(node);
  14406. }
  14407. parseMetaProperty(node, meta, propertyName) {
  14408. node.meta = meta;
  14409. if (meta.name === "function" && propertyName === "sent") {
  14410. if (this.isContextual(propertyName)) {
  14411. this.expectPlugin("functionSent");
  14412. } else if (!this.hasPlugin("functionSent")) {
  14413. this.unexpected();
  14414. }
  14415. }
  14416. const containsEsc = this.state.containsEsc;
  14417. node.property = this.parseIdentifier(true);
  14418. if (node.property.name !== propertyName || containsEsc) {
  14419. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  14420. }
  14421. return this.finishNode(node, "MetaProperty");
  14422. }
  14423. parseImportMetaProperty(node) {
  14424. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  14425. this.next();
  14426. if (this.isContextual("meta")) {
  14427. if (!this.inModule) {
  14428. this.raiseWithData(id.start, {
  14429. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  14430. }, ErrorMessages.ImportMetaOutsideModule);
  14431. }
  14432. this.sawUnambiguousESM = true;
  14433. }
  14434. return this.parseMetaProperty(node, id, "meta");
  14435. }
  14436. parseLiteral(value, type, startPos, startLoc) {
  14437. startPos = startPos || this.state.start;
  14438. startLoc = startLoc || this.state.startLoc;
  14439. const node = this.startNodeAt(startPos, startLoc);
  14440. this.addExtra(node, "rawValue", value);
  14441. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  14442. node.value = value;
  14443. this.next();
  14444. return this.finishNode(node, type);
  14445. }
  14446. parseParenAndDistinguishExpression(canBeArrow) {
  14447. const startPos = this.state.start;
  14448. const startLoc = this.state.startLoc;
  14449. let val;
  14450. this.next();
  14451. this.expressionScope.enter(newArrowHeadScope());
  14452. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  14453. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  14454. this.state.maybeInArrowParameters = true;
  14455. this.state.inFSharpPipelineDirectBody = false;
  14456. const innerStartPos = this.state.start;
  14457. const innerStartLoc = this.state.startLoc;
  14458. const exprList = [];
  14459. const refExpressionErrors = new ExpressionErrors();
  14460. const refNeedsArrowPos = {
  14461. start: 0
  14462. };
  14463. let first = true;
  14464. let spreadStart;
  14465. let optionalCommaStart;
  14466. while (!this.match(types.parenR)) {
  14467. if (first) {
  14468. first = false;
  14469. } else {
  14470. this.expect(types.comma, refNeedsArrowPos.start || null);
  14471. if (this.match(types.parenR)) {
  14472. optionalCommaStart = this.state.start;
  14473. break;
  14474. }
  14475. }
  14476. if (this.match(types.ellipsis)) {
  14477. const spreadNodeStartPos = this.state.start;
  14478. const spreadNodeStartLoc = this.state.startLoc;
  14479. spreadStart = this.state.start;
  14480. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  14481. this.checkCommaAfterRest(41);
  14482. break;
  14483. } else {
  14484. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  14485. }
  14486. }
  14487. const innerEndPos = this.state.lastTokEnd;
  14488. const innerEndLoc = this.state.lastTokEndLoc;
  14489. this.expect(types.parenR);
  14490. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  14491. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  14492. let arrowNode = this.startNodeAt(startPos, startLoc);
  14493. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  14494. this.expressionScope.validateAsPattern();
  14495. this.expressionScope.exit();
  14496. this.parseArrowExpression(arrowNode, exprList, false);
  14497. return arrowNode;
  14498. }
  14499. this.expressionScope.exit();
  14500. if (!exprList.length) {
  14501. this.unexpected(this.state.lastTokStart);
  14502. }
  14503. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  14504. if (spreadStart) this.unexpected(spreadStart);
  14505. this.checkExpressionErrors(refExpressionErrors, true);
  14506. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  14507. this.toReferencedListDeep(exprList, true);
  14508. if (exprList.length > 1) {
  14509. val = this.startNodeAt(innerStartPos, innerStartLoc);
  14510. val.expressions = exprList;
  14511. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  14512. } else {
  14513. val = exprList[0];
  14514. }
  14515. if (!this.options.createParenthesizedExpressions) {
  14516. this.addExtra(val, "parenthesized", true);
  14517. this.addExtra(val, "parenStart", startPos);
  14518. return val;
  14519. }
  14520. const parenExpression = this.startNodeAt(startPos, startLoc);
  14521. parenExpression.expression = val;
  14522. this.finishNode(parenExpression, "ParenthesizedExpression");
  14523. return parenExpression;
  14524. }
  14525. shouldParseArrow() {
  14526. return !this.canInsertSemicolon();
  14527. }
  14528. parseArrow(node) {
  14529. if (this.eat(types.arrow)) {
  14530. return node;
  14531. }
  14532. }
  14533. parseParenItem(node, startPos, startLoc) {
  14534. return node;
  14535. }
  14536. parseNewOrNewTarget() {
  14537. const node = this.startNode();
  14538. this.next();
  14539. if (this.match(types.dot)) {
  14540. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  14541. this.next();
  14542. const metaProp = this.parseMetaProperty(node, meta, "target");
  14543. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  14544. let error = ErrorMessages.UnexpectedNewTarget;
  14545. if (this.hasPlugin("classProperties")) {
  14546. error += " or class properties";
  14547. }
  14548. this.raise(metaProp.start, error);
  14549. }
  14550. return metaProp;
  14551. }
  14552. return this.parseNew(node);
  14553. }
  14554. parseNew(node) {
  14555. node.callee = this.parseNoCallExpr();
  14556. if (node.callee.type === "Import") {
  14557. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  14558. } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
  14559. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  14560. } else if (this.eat(types.questionDot)) {
  14561. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  14562. }
  14563. this.parseNewArguments(node);
  14564. return this.finishNode(node, "NewExpression");
  14565. }
  14566. parseNewArguments(node) {
  14567. if (this.eat(types.parenL)) {
  14568. const args = this.parseExprList(types.parenR);
  14569. this.toReferencedList(args);
  14570. node.arguments = args;
  14571. } else {
  14572. node.arguments = [];
  14573. }
  14574. }
  14575. parseTemplateElement(isTagged) {
  14576. const elem = this.startNode();
  14577. if (this.state.value === null) {
  14578. if (!isTagged) {
  14579. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  14580. }
  14581. }
  14582. elem.value = {
  14583. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  14584. cooked: this.state.value
  14585. };
  14586. this.next();
  14587. elem.tail = this.match(types.backQuote);
  14588. return this.finishNode(elem, "TemplateElement");
  14589. }
  14590. parseTemplate(isTagged) {
  14591. const node = this.startNode();
  14592. this.next();
  14593. node.expressions = [];
  14594. let curElt = this.parseTemplateElement(isTagged);
  14595. node.quasis = [curElt];
  14596. while (!curElt.tail) {
  14597. this.expect(types.dollarBraceL);
  14598. node.expressions.push(this.parseTemplateSubstitution());
  14599. this.expect(types.braceR);
  14600. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  14601. }
  14602. this.next();
  14603. return this.finishNode(node, "TemplateLiteral");
  14604. }
  14605. parseTemplateSubstitution() {
  14606. return this.parseExpression();
  14607. }
  14608. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  14609. if (isRecord) {
  14610. this.expectPlugin("recordAndTuple");
  14611. }
  14612. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  14613. this.state.inFSharpPipelineDirectBody = false;
  14614. const propHash = Object.create(null);
  14615. let first = true;
  14616. const node = this.startNode();
  14617. node.properties = [];
  14618. this.next();
  14619. while (!this.match(close)) {
  14620. if (first) {
  14621. first = false;
  14622. } else {
  14623. this.expect(types.comma);
  14624. if (this.match(close)) {
  14625. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  14626. break;
  14627. }
  14628. }
  14629. const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
  14630. if (!isPattern) {
  14631. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  14632. }
  14633. if (isRecord && prop.type !== "ObjectProperty" && prop.type !== "SpreadElement") {
  14634. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  14635. }
  14636. if (prop.shorthand) {
  14637. this.addExtra(prop, "shorthand", true);
  14638. }
  14639. node.properties.push(prop);
  14640. }
  14641. this.state.exprAllowed = false;
  14642. this.next();
  14643. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  14644. let type = "ObjectExpression";
  14645. if (isPattern) {
  14646. type = "ObjectPattern";
  14647. } else if (isRecord) {
  14648. type = "RecordExpression";
  14649. }
  14650. return this.finishNode(node, type);
  14651. }
  14652. maybeAsyncOrAccessorProp(prop) {
  14653. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(types.bracketL) || this.match(types.star));
  14654. }
  14655. parsePropertyDefinition(isPattern, refExpressionErrors) {
  14656. let decorators = [];
  14657. if (this.match(types.at)) {
  14658. if (this.hasPlugin("decorators")) {
  14659. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  14660. }
  14661. while (this.match(types.at)) {
  14662. decorators.push(this.parseDecorator());
  14663. }
  14664. }
  14665. const prop = this.startNode();
  14666. let isGenerator = false;
  14667. let isAsync = false;
  14668. let isAccessor = false;
  14669. let startPos;
  14670. let startLoc;
  14671. if (this.match(types.ellipsis)) {
  14672. if (decorators.length) this.unexpected();
  14673. if (isPattern) {
  14674. this.next();
  14675. prop.argument = this.parseIdentifier();
  14676. this.checkCommaAfterRest(125);
  14677. return this.finishNode(prop, "RestElement");
  14678. }
  14679. return this.parseSpread();
  14680. }
  14681. if (decorators.length) {
  14682. prop.decorators = decorators;
  14683. decorators = [];
  14684. }
  14685. prop.method = false;
  14686. if (isPattern || refExpressionErrors) {
  14687. startPos = this.state.start;
  14688. startLoc = this.state.startLoc;
  14689. }
  14690. if (!isPattern) {
  14691. isGenerator = this.eat(types.star);
  14692. }
  14693. const containsEsc = this.state.containsEsc;
  14694. const key = this.parsePropertyName(prop, false);
  14695. if (!isPattern && !isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  14696. const keyName = key.name;
  14697. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  14698. isAsync = true;
  14699. isGenerator = this.eat(types.star);
  14700. this.parsePropertyName(prop, false);
  14701. }
  14702. if (keyName === "get" || keyName === "set") {
  14703. isAccessor = true;
  14704. prop.kind = keyName;
  14705. if (this.match(types.star)) {
  14706. isGenerator = true;
  14707. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  14708. this.next();
  14709. }
  14710. this.parsePropertyName(prop, false);
  14711. }
  14712. }
  14713. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  14714. return prop;
  14715. }
  14716. getGetterSetterExpectedParamCount(method) {
  14717. return method.kind === "get" ? 0 : 1;
  14718. }
  14719. getObjectOrClassMethodParams(method) {
  14720. return method.params;
  14721. }
  14722. checkGetterSetterParams(method) {
  14723. var _params;
  14724. const paramCount = this.getGetterSetterExpectedParamCount(method);
  14725. const params = this.getObjectOrClassMethodParams(method);
  14726. const start = method.start;
  14727. if (params.length !== paramCount) {
  14728. if (method.kind === "get") {
  14729. this.raise(start, ErrorMessages.BadGetterArity);
  14730. } else {
  14731. this.raise(start, ErrorMessages.BadSetterArity);
  14732. }
  14733. }
  14734. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  14735. this.raise(start, ErrorMessages.BadSetterRestParameter);
  14736. }
  14737. }
  14738. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  14739. if (isAccessor) {
  14740. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  14741. this.checkGetterSetterParams(prop);
  14742. return prop;
  14743. }
  14744. if (isAsync || isGenerator || this.match(types.parenL)) {
  14745. if (isPattern) this.unexpected();
  14746. prop.kind = "method";
  14747. prop.method = true;
  14748. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  14749. }
  14750. }
  14751. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  14752. prop.shorthand = false;
  14753. if (this.eat(types.colon)) {
  14754. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  14755. return this.finishNode(prop, "ObjectProperty");
  14756. }
  14757. if (!prop.computed && prop.key.type === "Identifier") {
  14758. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  14759. if (isPattern) {
  14760. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  14761. } else if (this.match(types.eq) && refExpressionErrors) {
  14762. if (refExpressionErrors.shorthandAssign === -1) {
  14763. refExpressionErrors.shorthandAssign = this.state.start;
  14764. }
  14765. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  14766. } else {
  14767. prop.value = prop.key.__clone();
  14768. }
  14769. prop.shorthand = true;
  14770. return this.finishNode(prop, "ObjectProperty");
  14771. }
  14772. }
  14773. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  14774. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  14775. if (!node) this.unexpected();
  14776. return node;
  14777. }
  14778. parsePropertyName(prop, isPrivateNameAllowed) {
  14779. if (this.eat(types.bracketL)) {
  14780. prop.computed = true;
  14781. prop.key = this.parseMaybeAssignAllowIn();
  14782. this.expect(types.bracketR);
  14783. } else {
  14784. const oldInPropertyName = this.state.inPropertyName;
  14785. this.state.inPropertyName = true;
  14786. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) || this.match(types.decimal) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  14787. if (prop.key.type !== "PrivateName") {
  14788. prop.computed = false;
  14789. }
  14790. this.state.inPropertyName = oldInPropertyName;
  14791. }
  14792. return prop.key;
  14793. }
  14794. initFunction(node, isAsync) {
  14795. node.id = null;
  14796. node.generator = false;
  14797. node.async = !!isAsync;
  14798. }
  14799. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  14800. this.initFunction(node, isAsync);
  14801. node.generator = !!isGenerator;
  14802. const allowModifiers = isConstructor;
  14803. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  14804. this.prodParam.enter(functionFlags(isAsync, node.generator));
  14805. this.parseFunctionParams(node, allowModifiers);
  14806. this.parseFunctionBodyAndFinish(node, type, true);
  14807. this.prodParam.exit();
  14808. this.scope.exit();
  14809. return node;
  14810. }
  14811. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  14812. if (isTuple) {
  14813. this.expectPlugin("recordAndTuple");
  14814. }
  14815. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  14816. this.state.inFSharpPipelineDirectBody = false;
  14817. const node = this.startNode();
  14818. this.next();
  14819. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  14820. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  14821. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  14822. }
  14823. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  14824. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  14825. let flags = functionFlags(isAsync, false);
  14826. if (!this.match(types.bracketL) && this.prodParam.hasIn) {
  14827. flags |= PARAM_IN;
  14828. }
  14829. this.prodParam.enter(flags);
  14830. this.initFunction(node, isAsync);
  14831. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  14832. if (params) {
  14833. this.state.maybeInArrowParameters = true;
  14834. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  14835. }
  14836. this.state.maybeInArrowParameters = false;
  14837. this.parseFunctionBody(node, true);
  14838. this.prodParam.exit();
  14839. this.scope.exit();
  14840. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  14841. return this.finishNode(node, "ArrowFunctionExpression");
  14842. }
  14843. setArrowFunctionParameters(node, params, trailingCommaPos) {
  14844. node.params = this.toAssignableList(params, trailingCommaPos, false);
  14845. }
  14846. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  14847. this.parseFunctionBody(node, false, isMethod);
  14848. this.finishNode(node, type);
  14849. }
  14850. parseFunctionBody(node, allowExpression, isMethod = false) {
  14851. const isExpression = allowExpression && !this.match(types.braceL);
  14852. this.expressionScope.enter(newExpressionScope());
  14853. if (isExpression) {
  14854. node.body = this.parseMaybeAssign();
  14855. this.checkParams(node, false, allowExpression, false);
  14856. } else {
  14857. const oldStrict = this.state.strict;
  14858. const oldLabels = this.state.labels;
  14859. this.state.labels = [];
  14860. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  14861. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  14862. const nonSimple = !this.isSimpleParamList(node.params);
  14863. if (hasStrictModeDirective && nonSimple) {
  14864. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  14865. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  14866. }
  14867. const strictModeChanged = !oldStrict && this.state.strict;
  14868. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  14869. if (this.state.strict && node.id) {
  14870. this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged);
  14871. }
  14872. });
  14873. this.prodParam.exit();
  14874. this.expressionScope.exit();
  14875. this.state.labels = oldLabels;
  14876. }
  14877. }
  14878. isSimpleParamList(params) {
  14879. for (let i = 0, len = params.length; i < len; i++) {
  14880. if (params[i].type !== "Identifier") return false;
  14881. }
  14882. return true;
  14883. }
  14884. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  14885. const checkClashes = new Set();
  14886. for (let _i2 = 0, _node$params = node.params; _i2 < _node$params.length; _i2++) {
  14887. const param = _node$params[_i2];
  14888. this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged);
  14889. }
  14890. }
  14891. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  14892. const elts = [];
  14893. let first = true;
  14894. while (!this.eat(close)) {
  14895. if (first) {
  14896. first = false;
  14897. } else {
  14898. this.expect(types.comma);
  14899. if (this.match(close)) {
  14900. if (nodeForExtra) {
  14901. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  14902. }
  14903. this.next();
  14904. break;
  14905. }
  14906. }
  14907. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  14908. }
  14909. return elts;
  14910. }
  14911. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  14912. let elt;
  14913. if (this.match(types.comma)) {
  14914. if (!allowEmpty) {
  14915. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  14916. }
  14917. elt = null;
  14918. } else if (this.match(types.ellipsis)) {
  14919. const spreadNodeStartPos = this.state.start;
  14920. const spreadNodeStartLoc = this.state.startLoc;
  14921. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  14922. } else if (this.match(types.question)) {
  14923. this.expectPlugin("partialApplication");
  14924. if (!allowPlaceholder) {
  14925. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  14926. }
  14927. const node = this.startNode();
  14928. this.next();
  14929. elt = this.finishNode(node, "ArgumentPlaceholder");
  14930. } else {
  14931. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  14932. }
  14933. return elt;
  14934. }
  14935. parseIdentifier(liberal) {
  14936. const node = this.startNode();
  14937. const name = this.parseIdentifierName(node.start, liberal);
  14938. return this.createIdentifier(node, name);
  14939. }
  14940. createIdentifier(node, name) {
  14941. node.name = name;
  14942. node.loc.identifierName = name;
  14943. return this.finishNode(node, "Identifier");
  14944. }
  14945. parseIdentifierName(pos, liberal) {
  14946. let name;
  14947. const {
  14948. start,
  14949. type
  14950. } = this.state;
  14951. if (type === types.name) {
  14952. name = this.state.value;
  14953. } else if (type.keyword) {
  14954. name = type.keyword;
  14955. const curContext = this.curContext();
  14956. if ((type === types._class || type === types._function) && (curContext === types$1.functionStatement || curContext === types$1.functionExpression)) {
  14957. this.state.context.pop();
  14958. }
  14959. } else {
  14960. throw this.unexpected();
  14961. }
  14962. if (liberal) {
  14963. this.state.type = types.name;
  14964. } else {
  14965. this.checkReservedWord(name, start, !!type.keyword, false);
  14966. }
  14967. this.next();
  14968. return name;
  14969. }
  14970. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  14971. if (this.prodParam.hasYield && word === "yield") {
  14972. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  14973. return;
  14974. }
  14975. if (word === "await") {
  14976. if (this.prodParam.hasAwait) {
  14977. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  14978. return;
  14979. } else {
  14980. this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
  14981. }
  14982. }
  14983. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  14984. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  14985. return;
  14986. }
  14987. if (checkKeywords && isKeyword(word)) {
  14988. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  14989. return;
  14990. }
  14991. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  14992. if (reservedTest(word, this.inModule)) {
  14993. if (!this.prodParam.hasAwait && word === "await") {
  14994. this.raise(startLoc, this.hasPlugin("topLevelAwait") ? ErrorMessages.AwaitNotInAsyncContext : ErrorMessages.AwaitNotInAsyncFunction);
  14995. } else {
  14996. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  14997. }
  14998. }
  14999. }
  15000. isAwaitAllowed() {
  15001. if (this.scope.inFunction) return this.prodParam.hasAwait;
  15002. if (this.options.allowAwaitOutsideFunction) return true;
  15003. if (this.hasPlugin("topLevelAwait")) {
  15004. return this.inModule && this.prodParam.hasAwait;
  15005. }
  15006. return false;
  15007. }
  15008. parseAwait() {
  15009. const node = this.startNode();
  15010. this.next();
  15011. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  15012. if (this.eat(types.star)) {
  15013. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  15014. }
  15015. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  15016. if (this.hasPrecedingLineBreak() || this.match(types.plusMin) || this.match(types.parenL) || this.match(types.bracketL) || this.match(types.backQuote) || this.match(types.regexp) || this.match(types.slash) || this.hasPlugin("v8intrinsic") && this.match(types.modulo)) {
  15017. this.ambiguousScriptDifferentAst = true;
  15018. } else {
  15019. this.sawUnambiguousESM = true;
  15020. }
  15021. }
  15022. if (!this.state.soloAwait) {
  15023. node.argument = this.parseMaybeUnary();
  15024. }
  15025. return this.finishNode(node, "AwaitExpression");
  15026. }
  15027. parseYield() {
  15028. const node = this.startNode();
  15029. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
  15030. this.next();
  15031. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  15032. node.delegate = false;
  15033. node.argument = null;
  15034. } else {
  15035. node.delegate = this.eat(types.star);
  15036. node.argument = this.parseMaybeAssign();
  15037. }
  15038. return this.finishNode(node, "YieldExpression");
  15039. }
  15040. checkPipelineAtInfixOperator(left, leftStartPos) {
  15041. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  15042. if (left.type === "SequenceExpression") {
  15043. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  15044. }
  15045. }
  15046. }
  15047. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  15048. this.checkSmartPipelineBodyEarlyErrors(childExpression, startPos);
  15049. return this.parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc);
  15050. }
  15051. checkSmartPipelineBodyEarlyErrors(childExpression, startPos) {
  15052. if (this.match(types.arrow)) {
  15053. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  15054. } else if (childExpression.type === "SequenceExpression") {
  15055. this.raise(startPos, ErrorMessages.PipelineBodySequenceExpression);
  15056. }
  15057. }
  15058. parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc) {
  15059. const bodyNode = this.startNodeAt(startPos, startLoc);
  15060. const isSimpleReference = this.isSimpleReference(childExpression);
  15061. if (isSimpleReference) {
  15062. bodyNode.callee = childExpression;
  15063. } else {
  15064. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  15065. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  15066. }
  15067. bodyNode.expression = childExpression;
  15068. }
  15069. return this.finishNode(bodyNode, isSimpleReference ? "PipelineBareFunction" : "PipelineTopicExpression");
  15070. }
  15071. isSimpleReference(expression) {
  15072. switch (expression.type) {
  15073. case "MemberExpression":
  15074. return !expression.computed && this.isSimpleReference(expression.object);
  15075. case "Identifier":
  15076. return true;
  15077. default:
  15078. return false;
  15079. }
  15080. }
  15081. withTopicPermittingContext(callback) {
  15082. const outerContextTopicState = this.state.topicContext;
  15083. this.state.topicContext = {
  15084. maxNumOfResolvableTopics: 1,
  15085. maxTopicIndex: null
  15086. };
  15087. try {
  15088. return callback();
  15089. } finally {
  15090. this.state.topicContext = outerContextTopicState;
  15091. }
  15092. }
  15093. withTopicForbiddingContext(callback) {
  15094. const outerContextTopicState = this.state.topicContext;
  15095. this.state.topicContext = {
  15096. maxNumOfResolvableTopics: 0,
  15097. maxTopicIndex: null
  15098. };
  15099. try {
  15100. return callback();
  15101. } finally {
  15102. this.state.topicContext = outerContextTopicState;
  15103. }
  15104. }
  15105. withSoloAwaitPermittingContext(callback) {
  15106. const outerContextSoloAwaitState = this.state.soloAwait;
  15107. this.state.soloAwait = true;
  15108. try {
  15109. return callback();
  15110. } finally {
  15111. this.state.soloAwait = outerContextSoloAwaitState;
  15112. }
  15113. }
  15114. allowInAnd(callback) {
  15115. const flags = this.prodParam.currentFlags();
  15116. const prodParamToSet = PARAM_IN & ~flags;
  15117. if (prodParamToSet) {
  15118. this.prodParam.enter(flags | PARAM_IN);
  15119. try {
  15120. return callback();
  15121. } finally {
  15122. this.prodParam.exit();
  15123. }
  15124. }
  15125. return callback();
  15126. }
  15127. disallowInAnd(callback) {
  15128. const flags = this.prodParam.currentFlags();
  15129. const prodParamToClear = PARAM_IN & flags;
  15130. if (prodParamToClear) {
  15131. this.prodParam.enter(flags & ~PARAM_IN);
  15132. try {
  15133. return callback();
  15134. } finally {
  15135. this.prodParam.exit();
  15136. }
  15137. }
  15138. return callback();
  15139. }
  15140. registerTopicReference() {
  15141. this.state.topicContext.maxTopicIndex = 0;
  15142. }
  15143. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  15144. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  15145. }
  15146. topicReferenceWasUsedInCurrentTopicContext() {
  15147. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  15148. }
  15149. parseFSharpPipelineBody(prec) {
  15150. const startPos = this.state.start;
  15151. const startLoc = this.state.startLoc;
  15152. this.state.potentialArrowAt = this.state.start;
  15153. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  15154. this.state.inFSharpPipelineDirectBody = true;
  15155. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec);
  15156. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  15157. return ret;
  15158. }
  15159. }
  15160. const loopLabel = {
  15161. kind: "loop"
  15162. },
  15163. switchLabel = {
  15164. kind: "switch"
  15165. };
  15166. const FUNC_NO_FLAGS = 0b000,
  15167. FUNC_STATEMENT = 0b001,
  15168. FUNC_HANGING_STATEMENT = 0b010,
  15169. FUNC_NULLABLE_ID = 0b100;
  15170. const loneSurrogate = /[\uD800-\uDFFF]/u;
  15171. class StatementParser extends ExpressionParser {
  15172. parseTopLevel(file, program) {
  15173. program.sourceType = this.options.sourceType;
  15174. program.interpreter = this.parseInterpreterDirective();
  15175. this.parseBlockBody(program, true, true, types.eof);
  15176. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  15177. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  15178. const [name] = _Array$from[_i];
  15179. const pos = this.scope.undefinedExports.get(name);
  15180. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  15181. }
  15182. }
  15183. file.program = this.finishNode(program, "Program");
  15184. file.comments = this.state.comments;
  15185. if (this.options.tokens) file.tokens = this.tokens;
  15186. return this.finishNode(file, "File");
  15187. }
  15188. stmtToDirective(stmt) {
  15189. const expr = stmt.expression;
  15190. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  15191. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  15192. const raw = this.input.slice(expr.start, expr.end);
  15193. const val = directiveLiteral.value = raw.slice(1, -1);
  15194. this.addExtra(directiveLiteral, "raw", raw);
  15195. this.addExtra(directiveLiteral, "rawValue", val);
  15196. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  15197. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  15198. }
  15199. parseInterpreterDirective() {
  15200. if (!this.match(types.interpreterDirective)) {
  15201. return null;
  15202. }
  15203. const node = this.startNode();
  15204. node.value = this.state.value;
  15205. this.next();
  15206. return this.finishNode(node, "InterpreterDirective");
  15207. }
  15208. isLet(context) {
  15209. if (!this.isContextual("let")) {
  15210. return false;
  15211. }
  15212. const next = this.nextTokenStart();
  15213. const nextCh = this.input.charCodeAt(next);
  15214. if (nextCh === 91) return true;
  15215. if (context) return false;
  15216. if (nextCh === 123) return true;
  15217. if (isIdentifierStart(nextCh)) {
  15218. let pos = next + 1;
  15219. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  15220. ++pos;
  15221. }
  15222. const ident = this.input.slice(next, pos);
  15223. if (!keywordRelationalOperator.test(ident)) return true;
  15224. }
  15225. return false;
  15226. }
  15227. parseStatement(context, topLevel) {
  15228. if (this.match(types.at)) {
  15229. this.parseDecorators(true);
  15230. }
  15231. return this.parseStatementContent(context, topLevel);
  15232. }
  15233. parseStatementContent(context, topLevel) {
  15234. let starttype = this.state.type;
  15235. const node = this.startNode();
  15236. let kind;
  15237. if (this.isLet(context)) {
  15238. starttype = types._var;
  15239. kind = "let";
  15240. }
  15241. switch (starttype) {
  15242. case types._break:
  15243. case types._continue:
  15244. return this.parseBreakContinueStatement(node, starttype.keyword);
  15245. case types._debugger:
  15246. return this.parseDebuggerStatement(node);
  15247. case types._do:
  15248. return this.parseDoStatement(node);
  15249. case types._for:
  15250. return this.parseForStatement(node);
  15251. case types._function:
  15252. if (this.lookaheadCharCode() === 46) break;
  15253. if (context) {
  15254. if (this.state.strict) {
  15255. this.raise(this.state.start, ErrorMessages.StrictFunction);
  15256. } else if (context !== "if" && context !== "label") {
  15257. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  15258. }
  15259. }
  15260. return this.parseFunctionStatement(node, false, !context);
  15261. case types._class:
  15262. if (context) this.unexpected();
  15263. return this.parseClass(node, true);
  15264. case types._if:
  15265. return this.parseIfStatement(node);
  15266. case types._return:
  15267. return this.parseReturnStatement(node);
  15268. case types._switch:
  15269. return this.parseSwitchStatement(node);
  15270. case types._throw:
  15271. return this.parseThrowStatement(node);
  15272. case types._try:
  15273. return this.parseTryStatement(node);
  15274. case types._const:
  15275. case types._var:
  15276. kind = kind || this.state.value;
  15277. if (context && kind !== "var") {
  15278. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  15279. }
  15280. return this.parseVarStatement(node, kind);
  15281. case types._while:
  15282. return this.parseWhileStatement(node);
  15283. case types._with:
  15284. return this.parseWithStatement(node);
  15285. case types.braceL:
  15286. return this.parseBlock();
  15287. case types.semi:
  15288. return this.parseEmptyStatement(node);
  15289. case types._import:
  15290. {
  15291. const nextTokenCharCode = this.lookaheadCharCode();
  15292. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  15293. break;
  15294. }
  15295. }
  15296. case types._export:
  15297. {
  15298. if (!this.options.allowImportExportEverywhere && !topLevel) {
  15299. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  15300. }
  15301. this.next();
  15302. let result;
  15303. if (starttype === types._import) {
  15304. result = this.parseImport(node);
  15305. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  15306. this.sawUnambiguousESM = true;
  15307. }
  15308. } else {
  15309. result = this.parseExport(node);
  15310. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  15311. this.sawUnambiguousESM = true;
  15312. }
  15313. }
  15314. this.assertModuleNodeAllowed(node);
  15315. return result;
  15316. }
  15317. default:
  15318. {
  15319. if (this.isAsyncFunction()) {
  15320. if (context) {
  15321. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  15322. }
  15323. this.next();
  15324. return this.parseFunctionStatement(node, true, !context);
  15325. }
  15326. }
  15327. }
  15328. const maybeName = this.state.value;
  15329. const expr = this.parseExpression();
  15330. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  15331. return this.parseLabeledStatement(node, maybeName, expr, context);
  15332. } else {
  15333. return this.parseExpressionStatement(node, expr);
  15334. }
  15335. }
  15336. assertModuleNodeAllowed(node) {
  15337. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  15338. this.raiseWithData(node.start, {
  15339. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  15340. }, ErrorMessages.ImportOutsideModule);
  15341. }
  15342. }
  15343. takeDecorators(node) {
  15344. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  15345. if (decorators.length) {
  15346. node.decorators = decorators;
  15347. this.resetStartLocationFromNode(node, decorators[0]);
  15348. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  15349. }
  15350. }
  15351. canHaveLeadingDecorator() {
  15352. return this.match(types._class);
  15353. }
  15354. parseDecorators(allowExport) {
  15355. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  15356. while (this.match(types.at)) {
  15357. const decorator = this.parseDecorator();
  15358. currentContextDecorators.push(decorator);
  15359. }
  15360. if (this.match(types._export)) {
  15361. if (!allowExport) {
  15362. this.unexpected();
  15363. }
  15364. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  15365. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  15366. }
  15367. } else if (!this.canHaveLeadingDecorator()) {
  15368. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  15369. }
  15370. }
  15371. parseDecorator() {
  15372. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  15373. const node = this.startNode();
  15374. this.next();
  15375. if (this.hasPlugin("decorators")) {
  15376. this.state.decoratorStack.push([]);
  15377. const startPos = this.state.start;
  15378. const startLoc = this.state.startLoc;
  15379. let expr;
  15380. if (this.eat(types.parenL)) {
  15381. expr = this.parseExpression();
  15382. this.expect(types.parenR);
  15383. } else {
  15384. expr = this.parseIdentifier(false);
  15385. while (this.eat(types.dot)) {
  15386. const node = this.startNodeAt(startPos, startLoc);
  15387. node.object = expr;
  15388. node.property = this.parseIdentifier(true);
  15389. node.computed = false;
  15390. expr = this.finishNode(node, "MemberExpression");
  15391. }
  15392. }
  15393. node.expression = this.parseMaybeDecoratorArguments(expr);
  15394. this.state.decoratorStack.pop();
  15395. } else {
  15396. node.expression = this.parseExprSubscripts();
  15397. }
  15398. return this.finishNode(node, "Decorator");
  15399. }
  15400. parseMaybeDecoratorArguments(expr) {
  15401. if (this.eat(types.parenL)) {
  15402. const node = this.startNodeAtNode(expr);
  15403. node.callee = expr;
  15404. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  15405. this.toReferencedList(node.arguments);
  15406. return this.finishNode(node, "CallExpression");
  15407. }
  15408. return expr;
  15409. }
  15410. parseBreakContinueStatement(node, keyword) {
  15411. const isBreak = keyword === "break";
  15412. this.next();
  15413. if (this.isLineTerminator()) {
  15414. node.label = null;
  15415. } else {
  15416. node.label = this.parseIdentifier();
  15417. this.semicolon();
  15418. }
  15419. this.verifyBreakContinue(node, keyword);
  15420. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  15421. }
  15422. verifyBreakContinue(node, keyword) {
  15423. const isBreak = keyword === "break";
  15424. let i;
  15425. for (i = 0; i < this.state.labels.length; ++i) {
  15426. const lab = this.state.labels[i];
  15427. if (node.label == null || lab.name === node.label.name) {
  15428. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  15429. if (node.label && isBreak) break;
  15430. }
  15431. }
  15432. if (i === this.state.labels.length) {
  15433. this.raise(node.start, ErrorMessages.IllegalBreakContinue, keyword);
  15434. }
  15435. }
  15436. parseDebuggerStatement(node) {
  15437. this.next();
  15438. this.semicolon();
  15439. return this.finishNode(node, "DebuggerStatement");
  15440. }
  15441. parseHeaderExpression() {
  15442. this.expect(types.parenL);
  15443. const val = this.parseExpression();
  15444. this.expect(types.parenR);
  15445. return val;
  15446. }
  15447. parseDoStatement(node) {
  15448. this.next();
  15449. this.state.labels.push(loopLabel);
  15450. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  15451. this.state.labels.pop();
  15452. this.expect(types._while);
  15453. node.test = this.parseHeaderExpression();
  15454. this.eat(types.semi);
  15455. return this.finishNode(node, "DoWhileStatement");
  15456. }
  15457. parseForStatement(node) {
  15458. this.next();
  15459. this.state.labels.push(loopLabel);
  15460. let awaitAt = -1;
  15461. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  15462. awaitAt = this.state.lastTokStart;
  15463. }
  15464. this.scope.enter(SCOPE_OTHER);
  15465. this.expect(types.parenL);
  15466. if (this.match(types.semi)) {
  15467. if (awaitAt > -1) {
  15468. this.unexpected(awaitAt);
  15469. }
  15470. return this.parseFor(node, null);
  15471. }
  15472. const isLet = this.isLet();
  15473. if (this.match(types._var) || this.match(types._const) || isLet) {
  15474. const init = this.startNode();
  15475. const kind = isLet ? "let" : this.state.value;
  15476. this.next();
  15477. this.parseVar(init, true, kind);
  15478. this.finishNode(init, "VariableDeclaration");
  15479. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  15480. return this.parseForIn(node, init, awaitAt);
  15481. }
  15482. if (awaitAt > -1) {
  15483. this.unexpected(awaitAt);
  15484. }
  15485. return this.parseFor(node, init);
  15486. }
  15487. const refExpressionErrors = new ExpressionErrors();
  15488. const init = this.parseExpression(true, refExpressionErrors);
  15489. if (this.match(types._in) || this.isContextual("of")) {
  15490. this.toAssignable(init, true);
  15491. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  15492. this.checkLVal(init, description);
  15493. return this.parseForIn(node, init, awaitAt);
  15494. } else {
  15495. this.checkExpressionErrors(refExpressionErrors, true);
  15496. }
  15497. if (awaitAt > -1) {
  15498. this.unexpected(awaitAt);
  15499. }
  15500. return this.parseFor(node, init);
  15501. }
  15502. parseFunctionStatement(node, isAsync, declarationPosition) {
  15503. this.next();
  15504. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  15505. }
  15506. parseIfStatement(node) {
  15507. this.next();
  15508. node.test = this.parseHeaderExpression();
  15509. node.consequent = this.parseStatement("if");
  15510. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  15511. return this.finishNode(node, "IfStatement");
  15512. }
  15513. parseReturnStatement(node) {
  15514. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  15515. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  15516. }
  15517. this.next();
  15518. if (this.isLineTerminator()) {
  15519. node.argument = null;
  15520. } else {
  15521. node.argument = this.parseExpression();
  15522. this.semicolon();
  15523. }
  15524. return this.finishNode(node, "ReturnStatement");
  15525. }
  15526. parseSwitchStatement(node) {
  15527. this.next();
  15528. node.discriminant = this.parseHeaderExpression();
  15529. const cases = node.cases = [];
  15530. this.expect(types.braceL);
  15531. this.state.labels.push(switchLabel);
  15532. this.scope.enter(SCOPE_OTHER);
  15533. let cur;
  15534. for (let sawDefault; !this.match(types.braceR);) {
  15535. if (this.match(types._case) || this.match(types._default)) {
  15536. const isCase = this.match(types._case);
  15537. if (cur) this.finishNode(cur, "SwitchCase");
  15538. cases.push(cur = this.startNode());
  15539. cur.consequent = [];
  15540. this.next();
  15541. if (isCase) {
  15542. cur.test = this.parseExpression();
  15543. } else {
  15544. if (sawDefault) {
  15545. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  15546. }
  15547. sawDefault = true;
  15548. cur.test = null;
  15549. }
  15550. this.expect(types.colon);
  15551. } else {
  15552. if (cur) {
  15553. cur.consequent.push(this.parseStatement(null));
  15554. } else {
  15555. this.unexpected();
  15556. }
  15557. }
  15558. }
  15559. this.scope.exit();
  15560. if (cur) this.finishNode(cur, "SwitchCase");
  15561. this.next();
  15562. this.state.labels.pop();
  15563. return this.finishNode(node, "SwitchStatement");
  15564. }
  15565. parseThrowStatement(node) {
  15566. this.next();
  15567. if (this.hasPrecedingLineBreak()) {
  15568. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  15569. }
  15570. node.argument = this.parseExpression();
  15571. this.semicolon();
  15572. return this.finishNode(node, "ThrowStatement");
  15573. }
  15574. parseCatchClauseParam() {
  15575. const param = this.parseBindingAtom();
  15576. const simple = param.type === "Identifier";
  15577. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  15578. this.checkLVal(param, "catch clause", BIND_LEXICAL);
  15579. return param;
  15580. }
  15581. parseTryStatement(node) {
  15582. this.next();
  15583. node.block = this.parseBlock();
  15584. node.handler = null;
  15585. if (this.match(types._catch)) {
  15586. const clause = this.startNode();
  15587. this.next();
  15588. if (this.match(types.parenL)) {
  15589. this.expect(types.parenL);
  15590. clause.param = this.parseCatchClauseParam();
  15591. this.expect(types.parenR);
  15592. } else {
  15593. clause.param = null;
  15594. this.scope.enter(SCOPE_OTHER);
  15595. }
  15596. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  15597. this.scope.exit();
  15598. node.handler = this.finishNode(clause, "CatchClause");
  15599. }
  15600. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  15601. if (!node.handler && !node.finalizer) {
  15602. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  15603. }
  15604. return this.finishNode(node, "TryStatement");
  15605. }
  15606. parseVarStatement(node, kind) {
  15607. this.next();
  15608. this.parseVar(node, false, kind);
  15609. this.semicolon();
  15610. return this.finishNode(node, "VariableDeclaration");
  15611. }
  15612. parseWhileStatement(node) {
  15613. this.next();
  15614. node.test = this.parseHeaderExpression();
  15615. this.state.labels.push(loopLabel);
  15616. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  15617. this.state.labels.pop();
  15618. return this.finishNode(node, "WhileStatement");
  15619. }
  15620. parseWithStatement(node) {
  15621. if (this.state.strict) {
  15622. this.raise(this.state.start, ErrorMessages.StrictWith);
  15623. }
  15624. this.next();
  15625. node.object = this.parseHeaderExpression();
  15626. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  15627. return this.finishNode(node, "WithStatement");
  15628. }
  15629. parseEmptyStatement(node) {
  15630. this.next();
  15631. return this.finishNode(node, "EmptyStatement");
  15632. }
  15633. parseLabeledStatement(node, maybeName, expr, context) {
  15634. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  15635. const label = _this$state$labels[_i2];
  15636. if (label.name === maybeName) {
  15637. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  15638. }
  15639. }
  15640. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  15641. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  15642. const label = this.state.labels[i];
  15643. if (label.statementStart === node.start) {
  15644. label.statementStart = this.state.start;
  15645. label.kind = kind;
  15646. } else {
  15647. break;
  15648. }
  15649. }
  15650. this.state.labels.push({
  15651. name: maybeName,
  15652. kind: kind,
  15653. statementStart: this.state.start
  15654. });
  15655. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  15656. this.state.labels.pop();
  15657. node.label = expr;
  15658. return this.finishNode(node, "LabeledStatement");
  15659. }
  15660. parseExpressionStatement(node, expr) {
  15661. node.expression = expr;
  15662. this.semicolon();
  15663. return this.finishNode(node, "ExpressionStatement");
  15664. }
  15665. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  15666. const node = this.startNode();
  15667. this.expect(types.braceL);
  15668. if (createNewLexicalScope) {
  15669. this.scope.enter(SCOPE_OTHER);
  15670. }
  15671. this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
  15672. if (createNewLexicalScope) {
  15673. this.scope.exit();
  15674. }
  15675. return this.finishNode(node, "BlockStatement");
  15676. }
  15677. isValidDirective(stmt) {
  15678. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  15679. }
  15680. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  15681. const body = node.body = [];
  15682. const directives = node.directives = [];
  15683. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  15684. }
  15685. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  15686. const octalPositions = [];
  15687. const oldStrict = this.state.strict;
  15688. let hasStrictModeDirective = false;
  15689. let parsedNonDirective = false;
  15690. while (!this.match(end)) {
  15691. if (!parsedNonDirective && this.state.octalPositions.length) {
  15692. octalPositions.push(...this.state.octalPositions);
  15693. }
  15694. const stmt = this.parseStatement(null, topLevel);
  15695. if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
  15696. const directive = this.stmtToDirective(stmt);
  15697. directives.push(directive);
  15698. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  15699. hasStrictModeDirective = true;
  15700. this.setStrict(true);
  15701. }
  15702. continue;
  15703. }
  15704. parsedNonDirective = true;
  15705. body.push(stmt);
  15706. }
  15707. if (this.state.strict && octalPositions.length) {
  15708. for (let _i3 = 0; _i3 < octalPositions.length; _i3++) {
  15709. const pos = octalPositions[_i3];
  15710. this.raise(pos, ErrorMessages.StrictOctalLiteral);
  15711. }
  15712. }
  15713. if (afterBlockParse) {
  15714. afterBlockParse.call(this, hasStrictModeDirective);
  15715. }
  15716. if (!oldStrict) {
  15717. this.setStrict(false);
  15718. }
  15719. this.next();
  15720. }
  15721. parseFor(node, init) {
  15722. node.init = init;
  15723. this.expect(types.semi);
  15724. node.test = this.match(types.semi) ? null : this.parseExpression();
  15725. this.expect(types.semi);
  15726. node.update = this.match(types.parenR) ? null : this.parseExpression();
  15727. this.expect(types.parenR);
  15728. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  15729. this.scope.exit();
  15730. this.state.labels.pop();
  15731. return this.finishNode(node, "ForStatement");
  15732. }
  15733. parseForIn(node, init, awaitAt) {
  15734. const isForIn = this.match(types._in);
  15735. this.next();
  15736. if (isForIn) {
  15737. if (awaitAt > -1) this.unexpected(awaitAt);
  15738. } else {
  15739. node.await = awaitAt > -1;
  15740. }
  15741. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  15742. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  15743. } else if (init.type === "AssignmentPattern") {
  15744. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  15745. }
  15746. node.left = init;
  15747. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  15748. this.expect(types.parenR);
  15749. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  15750. this.scope.exit();
  15751. this.state.labels.pop();
  15752. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  15753. }
  15754. parseVar(node, isFor, kind) {
  15755. const declarations = node.declarations = [];
  15756. const isTypescript = this.hasPlugin("typescript");
  15757. node.kind = kind;
  15758. for (;;) {
  15759. const decl = this.startNode();
  15760. this.parseVarId(decl, kind);
  15761. if (this.eat(types.eq)) {
  15762. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  15763. } else {
  15764. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  15765. if (!isTypescript) {
  15766. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  15767. }
  15768. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  15769. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  15770. }
  15771. decl.init = null;
  15772. }
  15773. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  15774. if (!this.eat(types.comma)) break;
  15775. }
  15776. return node;
  15777. }
  15778. parseVarId(decl, kind) {
  15779. decl.id = this.parseBindingAtom();
  15780. this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var");
  15781. }
  15782. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  15783. const isStatement = statement & FUNC_STATEMENT;
  15784. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  15785. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  15786. this.initFunction(node, isAsync);
  15787. if (this.match(types.star) && isHangingStatement) {
  15788. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  15789. }
  15790. node.generator = this.eat(types.star);
  15791. if (isStatement) {
  15792. node.id = this.parseFunctionId(requireId);
  15793. }
  15794. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  15795. this.state.maybeInArrowParameters = false;
  15796. this.scope.enter(SCOPE_FUNCTION);
  15797. this.prodParam.enter(functionFlags(isAsync, node.generator));
  15798. if (!isStatement) {
  15799. node.id = this.parseFunctionId();
  15800. }
  15801. this.parseFunctionParams(node, false);
  15802. this.withTopicForbiddingContext(() => {
  15803. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  15804. });
  15805. this.prodParam.exit();
  15806. this.scope.exit();
  15807. if (isStatement && !isHangingStatement) {
  15808. this.registerFunctionStatementId(node);
  15809. }
  15810. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  15811. return node;
  15812. }
  15813. parseFunctionId(requireId) {
  15814. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  15815. }
  15816. parseFunctionParams(node, allowModifiers) {
  15817. this.expect(types.parenL);
  15818. this.expressionScope.enter(newParameterDeclarationScope());
  15819. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  15820. this.expressionScope.exit();
  15821. }
  15822. registerFunctionStatementId(node) {
  15823. if (!node.id) return;
  15824. this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start);
  15825. }
  15826. parseClass(node, isStatement, optionalId) {
  15827. this.next();
  15828. this.takeDecorators(node);
  15829. const oldStrict = this.state.strict;
  15830. this.state.strict = true;
  15831. this.parseClassId(node, isStatement, optionalId);
  15832. this.parseClassSuper(node);
  15833. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  15834. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  15835. }
  15836. isClassProperty() {
  15837. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  15838. }
  15839. isClassMethod() {
  15840. return this.match(types.parenL);
  15841. }
  15842. isNonstaticConstructor(method) {
  15843. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  15844. }
  15845. parseClassBody(constructorAllowsSuper, oldStrict) {
  15846. this.classScope.enter();
  15847. const state = {
  15848. constructorAllowsSuper,
  15849. hadConstructor: false,
  15850. hadStaticBlock: false
  15851. };
  15852. let decorators = [];
  15853. const classBody = this.startNode();
  15854. classBody.body = [];
  15855. this.expect(types.braceL);
  15856. this.withTopicForbiddingContext(() => {
  15857. while (!this.match(types.braceR)) {
  15858. if (this.eat(types.semi)) {
  15859. if (decorators.length > 0) {
  15860. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  15861. }
  15862. continue;
  15863. }
  15864. if (this.match(types.at)) {
  15865. decorators.push(this.parseDecorator());
  15866. continue;
  15867. }
  15868. const member = this.startNode();
  15869. if (decorators.length) {
  15870. member.decorators = decorators;
  15871. this.resetStartLocationFromNode(member, decorators[0]);
  15872. decorators = [];
  15873. }
  15874. this.parseClassMember(classBody, member, state);
  15875. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  15876. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  15877. }
  15878. }
  15879. });
  15880. this.state.strict = oldStrict;
  15881. this.next();
  15882. if (decorators.length) {
  15883. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  15884. }
  15885. this.classScope.exit();
  15886. return this.finishNode(classBody, "ClassBody");
  15887. }
  15888. parseClassMemberFromModifier(classBody, member) {
  15889. const key = this.parseIdentifier(true);
  15890. if (this.isClassMethod()) {
  15891. const method = member;
  15892. method.kind = "method";
  15893. method.computed = false;
  15894. method.key = key;
  15895. method.static = false;
  15896. this.pushClassMethod(classBody, method, false, false, false, false);
  15897. return true;
  15898. } else if (this.isClassProperty()) {
  15899. const prop = member;
  15900. prop.computed = false;
  15901. prop.key = key;
  15902. prop.static = false;
  15903. classBody.body.push(this.parseClassProperty(prop));
  15904. return true;
  15905. }
  15906. return false;
  15907. }
  15908. parseClassMember(classBody, member, state) {
  15909. const isStatic = this.isContextual("static");
  15910. if (isStatic) {
  15911. if (this.parseClassMemberFromModifier(classBody, member)) {
  15912. return;
  15913. }
  15914. if (this.eat(types.braceL)) {
  15915. this.parseClassStaticBlock(classBody, member, state);
  15916. return;
  15917. }
  15918. }
  15919. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  15920. }
  15921. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  15922. const publicMethod = member;
  15923. const privateMethod = member;
  15924. const publicProp = member;
  15925. const privateProp = member;
  15926. const method = publicMethod;
  15927. const publicMember = publicMethod;
  15928. member.static = isStatic;
  15929. if (this.eat(types.star)) {
  15930. method.kind = "method";
  15931. this.parseClassElementName(method);
  15932. if (method.key.type === "PrivateName") {
  15933. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  15934. return;
  15935. }
  15936. if (this.isNonstaticConstructor(publicMethod)) {
  15937. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  15938. }
  15939. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  15940. return;
  15941. }
  15942. const containsEsc = this.state.containsEsc;
  15943. const key = this.parseClassElementName(member);
  15944. const isPrivate = key.type === "PrivateName";
  15945. const isSimple = key.type === "Identifier";
  15946. const maybeQuestionTokenStart = this.state.start;
  15947. this.parsePostMemberNameModifiers(publicMember);
  15948. if (this.isClassMethod()) {
  15949. method.kind = "method";
  15950. if (isPrivate) {
  15951. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  15952. return;
  15953. }
  15954. const isConstructor = this.isNonstaticConstructor(publicMethod);
  15955. let allowsDirectSuper = false;
  15956. if (isConstructor) {
  15957. publicMethod.kind = "constructor";
  15958. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  15959. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  15960. }
  15961. state.hadConstructor = true;
  15962. allowsDirectSuper = state.constructorAllowsSuper;
  15963. }
  15964. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  15965. } else if (this.isClassProperty()) {
  15966. if (isPrivate) {
  15967. this.pushClassPrivateProperty(classBody, privateProp);
  15968. } else {
  15969. this.pushClassProperty(classBody, publicProp);
  15970. }
  15971. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  15972. const isGenerator = this.eat(types.star);
  15973. if (publicMember.optional) {
  15974. this.unexpected(maybeQuestionTokenStart);
  15975. }
  15976. method.kind = "method";
  15977. this.parseClassElementName(method);
  15978. this.parsePostMemberNameModifiers(publicMember);
  15979. if (method.key.type === "PrivateName") {
  15980. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  15981. } else {
  15982. if (this.isNonstaticConstructor(publicMethod)) {
  15983. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  15984. }
  15985. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  15986. }
  15987. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  15988. method.kind = key.name;
  15989. this.parseClassElementName(publicMethod);
  15990. if (method.key.type === "PrivateName") {
  15991. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  15992. } else {
  15993. if (this.isNonstaticConstructor(publicMethod)) {
  15994. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  15995. }
  15996. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  15997. }
  15998. this.checkGetterSetterParams(publicMethod);
  15999. } else if (this.isLineTerminator()) {
  16000. if (isPrivate) {
  16001. this.pushClassPrivateProperty(classBody, privateProp);
  16002. } else {
  16003. this.pushClassProperty(classBody, publicProp);
  16004. }
  16005. } else {
  16006. this.unexpected();
  16007. }
  16008. }
  16009. parseClassElementName(member) {
  16010. const key = this.parsePropertyName(member, true);
  16011. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  16012. this.raise(key.start, ErrorMessages.StaticPrototype);
  16013. }
  16014. if (key.type === "PrivateName" && key.id.name === "constructor") {
  16015. this.raise(key.start, ErrorMessages.ConstructorClassPrivateField);
  16016. }
  16017. return key;
  16018. }
  16019. parseClassStaticBlock(classBody, member, state) {
  16020. var _member$decorators;
  16021. this.expectPlugin("classStaticBlock", member.start);
  16022. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  16023. this.expressionScope.enter(newExpressionScope());
  16024. const oldLabels = this.state.labels;
  16025. this.state.labels = [];
  16026. this.prodParam.enter(PARAM);
  16027. const body = member.body = [];
  16028. this.parseBlockOrModuleBlockBody(body, undefined, false, types.braceR);
  16029. this.prodParam.exit();
  16030. this.expressionScope.exit();
  16031. this.scope.exit();
  16032. this.state.labels = oldLabels;
  16033. classBody.body.push(this.finishNode(member, "StaticBlock"));
  16034. if (state.hadStaticBlock) {
  16035. this.raise(member.start, ErrorMessages.DuplicateStaticBlock);
  16036. }
  16037. if ((_member$decorators = member.decorators) == null ? void 0 : _member$decorators.length) {
  16038. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  16039. }
  16040. state.hadStaticBlock = true;
  16041. }
  16042. pushClassProperty(classBody, prop) {
  16043. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  16044. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  16045. }
  16046. classBody.body.push(this.parseClassProperty(prop));
  16047. }
  16048. pushClassPrivateProperty(classBody, prop) {
  16049. this.expectPlugin("classPrivateProperties", prop.key.start);
  16050. const node = this.parseClassPrivateProperty(prop);
  16051. classBody.body.push(node);
  16052. this.classScope.declarePrivateName(node.key.id.name, CLASS_ELEMENT_OTHER, node.key.start);
  16053. }
  16054. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  16055. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  16056. }
  16057. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  16058. this.expectPlugin("classPrivateMethods", method.key.start);
  16059. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  16060. classBody.body.push(node);
  16061. const kind = node.kind === "get" ? node.static ? CLASS_ELEMENT_STATIC_GETTER : CLASS_ELEMENT_INSTANCE_GETTER : node.kind === "set" ? node.static ? CLASS_ELEMENT_STATIC_SETTER : CLASS_ELEMENT_INSTANCE_SETTER : CLASS_ELEMENT_OTHER;
  16062. this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start);
  16063. }
  16064. parsePostMemberNameModifiers(methodOrProp) {}
  16065. parseClassPrivateProperty(node) {
  16066. this.parseInitializer(node);
  16067. this.semicolon();
  16068. return this.finishNode(node, "ClassPrivateProperty");
  16069. }
  16070. parseClassProperty(node) {
  16071. if (!node.typeAnnotation || this.match(types.eq)) {
  16072. this.expectPlugin("classProperties");
  16073. }
  16074. this.parseInitializer(node);
  16075. this.semicolon();
  16076. return this.finishNode(node, "ClassProperty");
  16077. }
  16078. parseInitializer(node) {
  16079. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  16080. this.expressionScope.enter(newExpressionScope());
  16081. this.prodParam.enter(PARAM);
  16082. node.value = this.eat(types.eq) ? this.parseMaybeAssignAllowIn() : null;
  16083. this.expressionScope.exit();
  16084. this.prodParam.exit();
  16085. this.scope.exit();
  16086. }
  16087. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  16088. if (this.match(types.name)) {
  16089. node.id = this.parseIdentifier();
  16090. if (isStatement) {
  16091. this.checkLVal(node.id, "class name", bindingType);
  16092. }
  16093. } else {
  16094. if (optionalId || !isStatement) {
  16095. node.id = null;
  16096. } else {
  16097. this.unexpected(null, ErrorMessages.MissingClassName);
  16098. }
  16099. }
  16100. }
  16101. parseClassSuper(node) {
  16102. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  16103. }
  16104. parseExport(node) {
  16105. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  16106. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  16107. const hasStar = parseAfterDefault && this.eatExportStar(node);
  16108. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  16109. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  16110. const isFromRequired = hasDefault || hasStar;
  16111. if (hasStar && !hasNamespace) {
  16112. if (hasDefault) this.unexpected();
  16113. this.parseExportFrom(node, true);
  16114. return this.finishNode(node, "ExportAllDeclaration");
  16115. }
  16116. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  16117. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  16118. throw this.unexpected(null, types.braceL);
  16119. }
  16120. let hasDeclaration;
  16121. if (isFromRequired || hasSpecifiers) {
  16122. hasDeclaration = false;
  16123. this.parseExportFrom(node, isFromRequired);
  16124. } else {
  16125. hasDeclaration = this.maybeParseExportDeclaration(node);
  16126. }
  16127. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  16128. this.checkExport(node, true, false, !!node.source);
  16129. return this.finishNode(node, "ExportNamedDeclaration");
  16130. }
  16131. if (this.eat(types._default)) {
  16132. node.declaration = this.parseExportDefaultExpression();
  16133. this.checkExport(node, true, true);
  16134. return this.finishNode(node, "ExportDefaultDeclaration");
  16135. }
  16136. throw this.unexpected(null, types.braceL);
  16137. }
  16138. eatExportStar(node) {
  16139. return this.eat(types.star);
  16140. }
  16141. maybeParseExportDefaultSpecifier(node) {
  16142. if (this.isExportDefaultSpecifier()) {
  16143. this.expectPlugin("exportDefaultFrom");
  16144. const specifier = this.startNode();
  16145. specifier.exported = this.parseIdentifier(true);
  16146. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  16147. return true;
  16148. }
  16149. return false;
  16150. }
  16151. maybeParseExportNamespaceSpecifier(node) {
  16152. if (this.isContextual("as")) {
  16153. if (!node.specifiers) node.specifiers = [];
  16154. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  16155. this.next();
  16156. specifier.exported = this.parseModuleExportName();
  16157. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  16158. return true;
  16159. }
  16160. return false;
  16161. }
  16162. maybeParseExportNamedSpecifiers(node) {
  16163. if (this.match(types.braceL)) {
  16164. if (!node.specifiers) node.specifiers = [];
  16165. node.specifiers.push(...this.parseExportSpecifiers());
  16166. node.source = null;
  16167. node.declaration = null;
  16168. return true;
  16169. }
  16170. return false;
  16171. }
  16172. maybeParseExportDeclaration(node) {
  16173. if (this.shouldParseExportDeclaration()) {
  16174. node.specifiers = [];
  16175. node.source = null;
  16176. node.declaration = this.parseExportDeclaration(node);
  16177. return true;
  16178. }
  16179. return false;
  16180. }
  16181. isAsyncFunction() {
  16182. if (!this.isContextual("async")) return false;
  16183. const next = this.nextTokenStart();
  16184. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  16185. }
  16186. parseExportDefaultExpression() {
  16187. const expr = this.startNode();
  16188. const isAsync = this.isAsyncFunction();
  16189. if (this.match(types._function) || isAsync) {
  16190. this.next();
  16191. if (isAsync) {
  16192. this.next();
  16193. }
  16194. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  16195. } else if (this.match(types._class)) {
  16196. return this.parseClass(expr, true, true);
  16197. } else if (this.match(types.at)) {
  16198. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  16199. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  16200. }
  16201. this.parseDecorators(false);
  16202. return this.parseClass(expr, true, true);
  16203. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  16204. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  16205. } else {
  16206. const res = this.parseMaybeAssignAllowIn();
  16207. this.semicolon();
  16208. return res;
  16209. }
  16210. }
  16211. parseExportDeclaration(node) {
  16212. return this.parseStatement(null);
  16213. }
  16214. isExportDefaultSpecifier() {
  16215. if (this.match(types.name)) {
  16216. const value = this.state.value;
  16217. if (value === "async" && !this.state.containsEsc || value === "let") {
  16218. return false;
  16219. }
  16220. if ((value === "type" || value === "interface") && !this.state.containsEsc) {
  16221. const l = this.lookahead();
  16222. if (l.type === types.name && l.value !== "from" || l.type === types.braceL) {
  16223. this.expectOnePlugin(["flow", "typescript"]);
  16224. return false;
  16225. }
  16226. }
  16227. } else if (!this.match(types._default)) {
  16228. return false;
  16229. }
  16230. const next = this.nextTokenStart();
  16231. const hasFrom = this.isUnparsedContextual(next, "from");
  16232. if (this.input.charCodeAt(next) === 44 || this.match(types.name) && hasFrom) {
  16233. return true;
  16234. }
  16235. if (this.match(types._default) && hasFrom) {
  16236. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  16237. return nextAfterFrom === 34 || nextAfterFrom === 39;
  16238. }
  16239. return false;
  16240. }
  16241. parseExportFrom(node, expect) {
  16242. if (this.eatContextual("from")) {
  16243. node.source = this.parseImportSource();
  16244. this.checkExport(node);
  16245. const assertions = this.maybeParseImportAssertions();
  16246. if (assertions) {
  16247. node.assertions = assertions;
  16248. }
  16249. } else {
  16250. if (expect) {
  16251. this.unexpected();
  16252. } else {
  16253. node.source = null;
  16254. }
  16255. }
  16256. this.semicolon();
  16257. }
  16258. shouldParseExportDeclaration() {
  16259. if (this.match(types.at)) {
  16260. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  16261. if (this.hasPlugin("decorators")) {
  16262. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  16263. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  16264. } else {
  16265. return true;
  16266. }
  16267. }
  16268. }
  16269. return this.state.type.keyword === "var" || this.state.type.keyword === "const" || this.state.type.keyword === "function" || this.state.type.keyword === "class" || this.isLet() || this.isAsyncFunction();
  16270. }
  16271. checkExport(node, checkNames, isDefault, isFrom) {
  16272. if (checkNames) {
  16273. if (isDefault) {
  16274. this.checkDuplicateExports(node, "default");
  16275. if (this.hasPlugin("exportDefaultFrom")) {
  16276. var _declaration$extra;
  16277. const declaration = node.declaration;
  16278. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) == null ? void 0 : _declaration$extra.parenthesized)) {
  16279. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  16280. }
  16281. }
  16282. } else if (node.specifiers && node.specifiers.length) {
  16283. for (let _i4 = 0, _node$specifiers = node.specifiers; _i4 < _node$specifiers.length; _i4++) {
  16284. const specifier = _node$specifiers[_i4];
  16285. const {
  16286. exported
  16287. } = specifier;
  16288. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  16289. this.checkDuplicateExports(specifier, exportedName);
  16290. if (!isFrom && specifier.local) {
  16291. const {
  16292. local
  16293. } = specifier;
  16294. if (local.type === "StringLiteral") {
  16295. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.extra.raw, exportedName);
  16296. } else {
  16297. this.checkReservedWord(local.name, local.start, true, false);
  16298. this.scope.checkLocalExport(local);
  16299. }
  16300. }
  16301. }
  16302. } else if (node.declaration) {
  16303. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  16304. const id = node.declaration.id;
  16305. if (!id) throw new Error("Assertion failure");
  16306. this.checkDuplicateExports(node, id.name);
  16307. } else if (node.declaration.type === "VariableDeclaration") {
  16308. for (let _i5 = 0, _node$declaration$dec = node.declaration.declarations; _i5 < _node$declaration$dec.length; _i5++) {
  16309. const declaration = _node$declaration$dec[_i5];
  16310. this.checkDeclaration(declaration.id);
  16311. }
  16312. }
  16313. }
  16314. }
  16315. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  16316. if (currentContextDecorators.length) {
  16317. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  16318. }
  16319. }
  16320. checkDeclaration(node) {
  16321. if (node.type === "Identifier") {
  16322. this.checkDuplicateExports(node, node.name);
  16323. } else if (node.type === "ObjectPattern") {
  16324. for (let _i6 = 0, _node$properties = node.properties; _i6 < _node$properties.length; _i6++) {
  16325. const prop = _node$properties[_i6];
  16326. this.checkDeclaration(prop);
  16327. }
  16328. } else if (node.type === "ArrayPattern") {
  16329. for (let _i7 = 0, _node$elements = node.elements; _i7 < _node$elements.length; _i7++) {
  16330. const elem = _node$elements[_i7];
  16331. if (elem) {
  16332. this.checkDeclaration(elem);
  16333. }
  16334. }
  16335. } else if (node.type === "ObjectProperty") {
  16336. this.checkDeclaration(node.value);
  16337. } else if (node.type === "RestElement") {
  16338. this.checkDeclaration(node.argument);
  16339. } else if (node.type === "AssignmentPattern") {
  16340. this.checkDeclaration(node.left);
  16341. }
  16342. }
  16343. checkDuplicateExports(node, name) {
  16344. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  16345. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  16346. }
  16347. this.state.exportedIdentifiers.push(name);
  16348. }
  16349. parseExportSpecifiers() {
  16350. const nodes = [];
  16351. let first = true;
  16352. this.expect(types.braceL);
  16353. while (!this.eat(types.braceR)) {
  16354. if (first) {
  16355. first = false;
  16356. } else {
  16357. this.expect(types.comma);
  16358. if (this.eat(types.braceR)) break;
  16359. }
  16360. const node = this.startNode();
  16361. node.local = this.parseModuleExportName();
  16362. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local.__clone();
  16363. nodes.push(this.finishNode(node, "ExportSpecifier"));
  16364. }
  16365. return nodes;
  16366. }
  16367. parseModuleExportName() {
  16368. if (this.match(types.string)) {
  16369. this.expectPlugin("moduleStringNames");
  16370. const result = this.parseLiteral(this.state.value, "StringLiteral");
  16371. const surrogate = result.value.match(loneSurrogate);
  16372. if (surrogate) {
  16373. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  16374. }
  16375. return result;
  16376. }
  16377. return this.parseIdentifier(true);
  16378. }
  16379. parseImport(node) {
  16380. node.specifiers = [];
  16381. if (!this.match(types.string)) {
  16382. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  16383. const parseNext = !hasDefault || this.eat(types.comma);
  16384. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  16385. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  16386. this.expectContextual("from");
  16387. }
  16388. node.source = this.parseImportSource();
  16389. const assertions = this.maybeParseImportAssertions();
  16390. if (assertions) {
  16391. node.assertions = assertions;
  16392. } else {
  16393. const attributes = this.maybeParseModuleAttributes();
  16394. if (attributes) {
  16395. node.attributes = attributes;
  16396. }
  16397. }
  16398. this.semicolon();
  16399. return this.finishNode(node, "ImportDeclaration");
  16400. }
  16401. parseImportSource() {
  16402. if (!this.match(types.string)) this.unexpected();
  16403. return this.parseExprAtom();
  16404. }
  16405. shouldParseDefaultImport(node) {
  16406. return this.match(types.name);
  16407. }
  16408. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  16409. specifier.local = this.parseIdentifier();
  16410. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  16411. node.specifiers.push(this.finishNode(specifier, type));
  16412. }
  16413. parseAssertEntries() {
  16414. const attrs = [];
  16415. const attrNames = new Set();
  16416. do {
  16417. if (this.match(types.braceR)) {
  16418. break;
  16419. }
  16420. const node = this.startNode();
  16421. const keyName = this.state.value;
  16422. if (this.match(types.string)) {
  16423. node.key = this.parseLiteral(keyName, "StringLiteral");
  16424. } else {
  16425. node.key = this.parseIdentifier(true);
  16426. }
  16427. this.expect(types.colon);
  16428. if (keyName !== "type") {
  16429. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, keyName);
  16430. }
  16431. if (attrNames.has(keyName)) {
  16432. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
  16433. }
  16434. attrNames.add(keyName);
  16435. if (!this.match(types.string)) {
  16436. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  16437. }
  16438. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  16439. this.finishNode(node, "ImportAttribute");
  16440. attrs.push(node);
  16441. } while (this.eat(types.comma));
  16442. return attrs;
  16443. }
  16444. maybeParseModuleAttributes() {
  16445. if (this.match(types._with) && !this.hasPrecedingLineBreak()) {
  16446. this.expectPlugin("moduleAttributes");
  16447. this.next();
  16448. } else {
  16449. if (this.hasPlugin("moduleAttributes")) return [];
  16450. return null;
  16451. }
  16452. const attrs = [];
  16453. const attributes = new Set();
  16454. do {
  16455. const node = this.startNode();
  16456. node.key = this.parseIdentifier(true);
  16457. if (node.key.name !== "type") {
  16458. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  16459. }
  16460. if (attributes.has(node.key.name)) {
  16461. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  16462. }
  16463. attributes.add(node.key.name);
  16464. this.expect(types.colon);
  16465. if (!this.match(types.string)) {
  16466. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  16467. }
  16468. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  16469. this.finishNode(node, "ImportAttribute");
  16470. attrs.push(node);
  16471. } while (this.eat(types.comma));
  16472. return attrs;
  16473. }
  16474. maybeParseImportAssertions() {
  16475. if (this.isContextual("assert") && !this.hasPrecedingLineBreak()) {
  16476. this.expectPlugin("importAssertions");
  16477. this.next();
  16478. } else {
  16479. if (this.hasPlugin("importAssertions")) return [];
  16480. return null;
  16481. }
  16482. this.eat(types.braceL);
  16483. const attrs = this.parseAssertEntries();
  16484. this.eat(types.braceR);
  16485. return attrs;
  16486. }
  16487. maybeParseDefaultImportSpecifier(node) {
  16488. if (this.shouldParseDefaultImport(node)) {
  16489. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  16490. return true;
  16491. }
  16492. return false;
  16493. }
  16494. maybeParseStarImportSpecifier(node) {
  16495. if (this.match(types.star)) {
  16496. const specifier = this.startNode();
  16497. this.next();
  16498. this.expectContextual("as");
  16499. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  16500. return true;
  16501. }
  16502. return false;
  16503. }
  16504. parseNamedImportSpecifiers(node) {
  16505. let first = true;
  16506. this.expect(types.braceL);
  16507. while (!this.eat(types.braceR)) {
  16508. if (first) {
  16509. first = false;
  16510. } else {
  16511. if (this.eat(types.colon)) {
  16512. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  16513. }
  16514. this.expect(types.comma);
  16515. if (this.eat(types.braceR)) break;
  16516. }
  16517. this.parseImportSpecifier(node);
  16518. }
  16519. }
  16520. parseImportSpecifier(node) {
  16521. const specifier = this.startNode();
  16522. specifier.imported = this.parseModuleExportName();
  16523. if (this.eatContextual("as")) {
  16524. specifier.local = this.parseIdentifier();
  16525. } else {
  16526. const {
  16527. imported
  16528. } = specifier;
  16529. if (imported.type === "StringLiteral") {
  16530. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  16531. }
  16532. this.checkReservedWord(imported.name, specifier.start, true, true);
  16533. specifier.local = imported.__clone();
  16534. }
  16535. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  16536. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  16537. }
  16538. }
  16539. class ClassScope {
  16540. constructor() {
  16541. this.privateNames = new Set();
  16542. this.loneAccessors = new Map();
  16543. this.undefinedPrivateNames = new Map();
  16544. }
  16545. }
  16546. class ClassScopeHandler {
  16547. constructor(raise) {
  16548. this.stack = [];
  16549. this.undefinedPrivateNames = new Map();
  16550. this.raise = raise;
  16551. }
  16552. current() {
  16553. return this.stack[this.stack.length - 1];
  16554. }
  16555. enter() {
  16556. this.stack.push(new ClassScope());
  16557. }
  16558. exit() {
  16559. const oldClassScope = this.stack.pop();
  16560. const current = this.current();
  16561. for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) {
  16562. const [name, pos] = _Array$from[_i];
  16563. if (current) {
  16564. if (!current.undefinedPrivateNames.has(name)) {
  16565. current.undefinedPrivateNames.set(name, pos);
  16566. }
  16567. } else {
  16568. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  16569. }
  16570. }
  16571. }
  16572. declarePrivateName(name, elementType, pos) {
  16573. const classScope = this.current();
  16574. let redefined = classScope.privateNames.has(name);
  16575. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  16576. const accessor = redefined && classScope.loneAccessors.get(name);
  16577. if (accessor) {
  16578. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  16579. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  16580. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  16581. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  16582. redefined = oldKind === newKind || oldStatic !== newStatic;
  16583. if (!redefined) classScope.loneAccessors.delete(name);
  16584. } else if (!redefined) {
  16585. classScope.loneAccessors.set(name, elementType);
  16586. }
  16587. }
  16588. if (redefined) {
  16589. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  16590. }
  16591. classScope.privateNames.add(name);
  16592. classScope.undefinedPrivateNames.delete(name);
  16593. }
  16594. usePrivateName(name, pos) {
  16595. let classScope;
  16596. for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) {
  16597. classScope = _this$stack[_i2];
  16598. if (classScope.privateNames.has(name)) return;
  16599. }
  16600. if (classScope) {
  16601. classScope.undefinedPrivateNames.set(name, pos);
  16602. } else {
  16603. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  16604. }
  16605. }
  16606. }
  16607. class Parser extends StatementParser {
  16608. constructor(options, input) {
  16609. options = getOptions(options);
  16610. super(options, input);
  16611. const ScopeHandler = this.getScopeHandler();
  16612. this.options = options;
  16613. this.inModule = this.options.sourceType === "module";
  16614. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  16615. this.prodParam = new ProductionParameterHandler();
  16616. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  16617. this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
  16618. this.plugins = pluginsMap(this.options.plugins);
  16619. this.filename = options.sourceFilename;
  16620. }
  16621. getScopeHandler() {
  16622. return ScopeHandler;
  16623. }
  16624. parse() {
  16625. let paramFlags = PARAM;
  16626. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  16627. paramFlags |= PARAM_AWAIT;
  16628. }
  16629. this.scope.enter(SCOPE_PROGRAM);
  16630. this.prodParam.enter(paramFlags);
  16631. const file = this.startNode();
  16632. const program = this.startNode();
  16633. this.nextToken();
  16634. file.errors = null;
  16635. this.parseTopLevel(file, program);
  16636. file.errors = this.state.errors;
  16637. return file;
  16638. }
  16639. }
  16640. function pluginsMap(plugins) {
  16641. const pluginMap = new Map();
  16642. for (let _i = 0; _i < plugins.length; _i++) {
  16643. const plugin = plugins[_i];
  16644. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  16645. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  16646. }
  16647. return pluginMap;
  16648. }
  16649. function parse(input, options) {
  16650. var _options;
  16651. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  16652. options = Object.assign({}, options);
  16653. try {
  16654. options.sourceType = "module";
  16655. const parser = getParser(options, input);
  16656. const ast = parser.parse();
  16657. if (parser.sawUnambiguousESM) {
  16658. return ast;
  16659. }
  16660. if (parser.ambiguousScriptDifferentAst) {
  16661. try {
  16662. options.sourceType = "script";
  16663. return getParser(options, input).parse();
  16664. } catch (_unused) {}
  16665. } else {
  16666. ast.program.sourceType = "script";
  16667. }
  16668. return ast;
  16669. } catch (moduleError) {
  16670. try {
  16671. options.sourceType = "script";
  16672. return getParser(options, input).parse();
  16673. } catch (_unused2) {}
  16674. throw moduleError;
  16675. }
  16676. } else {
  16677. return getParser(options, input).parse();
  16678. }
  16679. }
  16680. function getParser(options, input) {
  16681. let cls = Parser;
  16682. if (options == null ? void 0 : options.plugins) {
  16683. validatePlugins(options.plugins);
  16684. cls = getParserClass(options.plugins);
  16685. }
  16686. return new cls(options, input);
  16687. }
  16688. const parserClassCache = {};
  16689. function getParserClass(pluginsFromOptions) {
  16690. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  16691. const key = pluginList.join("/");
  16692. let cls = parserClassCache[key];
  16693. if (!cls) {
  16694. cls = Parser;
  16695. for (let _i = 0; _i < pluginList.length; _i++) {
  16696. const plugin = pluginList[_i];
  16697. cls = mixinPlugins[plugin](cls);
  16698. }
  16699. parserClassCache[key] = cls;
  16700. }
  16701. return cls;
  16702. }
  16703. var parse_1 = parse;
  16704. class WalkerBase {constructor() { WalkerBase.prototype.__init.call(this);WalkerBase.prototype.__init2.call(this);WalkerBase.prototype.__init3.call(this);WalkerBase.prototype.__init4.call(this); }
  16705. __init() {this.should_skip = false;}
  16706. __init2() {this.should_remove = false;}
  16707. __init3() {this.replacement = null;}
  16708. __init4() {this.context = {
  16709. skip: () => (this.should_skip = true),
  16710. remove: () => (this.should_remove = true),
  16711. replace: (node) => (this.replacement = node)
  16712. };}
  16713. replace(parent, prop, index, node) {
  16714. if (parent) {
  16715. if (index !== null) {
  16716. parent[prop][index] = node;
  16717. } else {
  16718. parent[prop] = node;
  16719. }
  16720. }
  16721. }
  16722. remove(parent, prop, index) {
  16723. if (parent) {
  16724. if (index !== null) {
  16725. parent[prop].splice(index, 1);
  16726. } else {
  16727. delete parent[prop];
  16728. }
  16729. }
  16730. }
  16731. }
  16732. class SyncWalkerClass extends WalkerBase {
  16733. constructor(walker) {
  16734. super();
  16735. this.enter = walker.enter;
  16736. this.leave = walker.leave;
  16737. }
  16738. visit(
  16739. node,
  16740. parent,
  16741. enter,
  16742. leave,
  16743. prop,
  16744. index
  16745. ) {
  16746. if (node) {
  16747. if (enter) {
  16748. const _should_skip = this.should_skip;
  16749. const _should_remove = this.should_remove;
  16750. const _replacement = this.replacement;
  16751. this.should_skip = false;
  16752. this.should_remove = false;
  16753. this.replacement = null;
  16754. enter.call(this.context, node, parent, prop, index);
  16755. if (this.replacement) {
  16756. node = this.replacement;
  16757. this.replace(parent, prop, index, node);
  16758. }
  16759. if (this.should_remove) {
  16760. this.remove(parent, prop, index);
  16761. }
  16762. const skipped = this.should_skip;
  16763. const removed = this.should_remove;
  16764. this.should_skip = _should_skip;
  16765. this.should_remove = _should_remove;
  16766. this.replacement = _replacement;
  16767. if (skipped) return node;
  16768. if (removed) return null;
  16769. }
  16770. for (const key in node) {
  16771. const value = (node )[key];
  16772. if (typeof value !== "object") {
  16773. continue;
  16774. } else if (Array.isArray(value)) {
  16775. for (let i = 0; i < value.length; i += 1) {
  16776. if (value[i] !== null && typeof value[i].type === 'string') {
  16777. if (!this.visit(value[i], node, enter, leave, key, i)) {
  16778. // removed
  16779. i--;
  16780. }
  16781. }
  16782. }
  16783. } else if (value !== null && typeof value.type === "string") {
  16784. this.visit(value, node, enter, leave, key, null);
  16785. }
  16786. }
  16787. if (leave) {
  16788. const _replacement = this.replacement;
  16789. const _should_remove = this.should_remove;
  16790. this.replacement = null;
  16791. this.should_remove = false;
  16792. leave.call(this.context, node, parent, prop, index);
  16793. if (this.replacement) {
  16794. node = this.replacement;
  16795. this.replace(parent, prop, index, node);
  16796. }
  16797. if (this.should_remove) {
  16798. this.remove(parent, prop, index);
  16799. }
  16800. const removed = this.should_remove;
  16801. this.replacement = _replacement;
  16802. this.should_remove = _should_remove;
  16803. if (removed) return null;
  16804. }
  16805. }
  16806. return node;
  16807. }
  16808. }
  16809. function walk$1(ast, walker) {
  16810. const instance = new SyncWalkerClass(walker);
  16811. return instance.visit(ast, null, walker.enter, walker.leave);
  16812. }
  16813. const isLiteralWhitelisted = /*#__PURE__*/ makeMap('true,false,null,this');
  16814. const transformExpression = (node, context) => {
  16815. if (node.type === 5 /* INTERPOLATION */) {
  16816. node.content = processExpression(node.content, context);
  16817. }
  16818. else if (node.type === 1 /* ELEMENT */) {
  16819. // handle directives on element
  16820. for (let i = 0; i < node.props.length; i++) {
  16821. const dir = node.props[i];
  16822. // do not process for v-on & v-for since they are special handled
  16823. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  16824. const exp = dir.exp;
  16825. const arg = dir.arg;
  16826. // do not process exp if this is v-on:arg - we need special handling
  16827. // for wrapping inline statements.
  16828. if (exp &&
  16829. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  16830. !(dir.name === 'on' && arg)) {
  16831. dir.exp = processExpression(exp, context,
  16832. // slot args must be processed as function params
  16833. dir.name === 'slot');
  16834. }
  16835. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  16836. dir.arg = processExpression(arg, context);
  16837. }
  16838. }
  16839. }
  16840. }
  16841. };
  16842. // Important: since this function uses Node.js only dependencies, it should
  16843. // always be used with a leading !false check so that it can be
  16844. // tree-shaken from the browser build.
  16845. function processExpression(node, context,
  16846. // some expressions like v-slot props & v-for aliases should be parsed as
  16847. // function params
  16848. asParams = false,
  16849. // v-on handler values may contain multiple statements
  16850. asRawStatements = false) {
  16851. if (!context.prefixIdentifiers || !node.content.trim()) {
  16852. return node;
  16853. }
  16854. const { inline, bindingMetadata } = context;
  16855. const rewriteIdentifier = (raw, parent, id) => {
  16856. const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
  16857. if (inline) {
  16858. // x = y
  16859. const isAssignmentLVal = parent && parent.type === 'AssignmentExpression' && parent.left === id;
  16860. // x++
  16861. const isUpdateArg = parent && parent.type === 'UpdateExpression' && parent.argument === id;
  16862. // ({ x } = y)
  16863. const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
  16864. if (type === "setup-const" /* SETUP_CONST */) {
  16865. return raw;
  16866. }
  16867. else if (type === "setup-ref" /* SETUP_REF */) {
  16868. return `${raw}.value`;
  16869. }
  16870. else if (type === "setup-maybe-ref" /* SETUP_MAYBE_REF */) {
  16871. // const binding that may or may not be ref
  16872. // if it's not a ref, then assignments don't make sense -
  16873. // so we ignore the non-ref assignment case and generate code
  16874. // that assumes the value to be a ref for more efficiency
  16875. return isAssignmentLVal || isUpdateArg || isDestructureAssignment
  16876. ? `${raw}.value`
  16877. : `${context.helperString(UNREF)}(${raw})`;
  16878. }
  16879. else if (type === "setup-let" /* SETUP_LET */) {
  16880. if (isAssignmentLVal) {
  16881. // let binding.
  16882. // this is a bit more tricky as we need to cover the case where
  16883. // let is a local non-ref value, and we need to replicate the
  16884. // right hand side value.
  16885. // x = y --> isRef(x) ? x.value = y : x = y
  16886. const rVal = parent.right;
  16887. const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
  16888. const rExpString = stringifyExpression(processExpression(createSimpleExpression(rExp, false), context));
  16889. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${raw}.value = ${rExpString} : ${raw}`;
  16890. }
  16891. else if (isUpdateArg) {
  16892. // make id replace parent in the code range so the raw update operator
  16893. // is removed
  16894. id.start = parent.start;
  16895. id.end = parent.end;
  16896. const { prefix: isPrefix, operator } = parent;
  16897. const prefix = isPrefix ? operator : ``;
  16898. const postfix = isPrefix ? `` : operator;
  16899. // let binding.
  16900. // x++ --> isRef(a) ? a.value++ : a++
  16901. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
  16902. }
  16903. else if (isDestructureAssignment) {
  16904. // TODO
  16905. // let binding in a destructure assignment - it's very tricky to
  16906. // handle both possible cases here without altering the original
  16907. // structure of the code, so we just assume it's not a ref here
  16908. // for now
  16909. return raw;
  16910. }
  16911. else {
  16912. return `${context.helperString(UNREF)}(${raw})`;
  16913. }
  16914. }
  16915. else if (type === "props" /* PROPS */) {
  16916. // use __props which is generated by compileScript so in ts mode
  16917. // it gets correct type
  16918. return `__props.${raw}`;
  16919. }
  16920. }
  16921. else {
  16922. if (type && type.startsWith('setup')) {
  16923. // setup bindings in non-inline mode
  16924. return `$setup.${raw}`;
  16925. }
  16926. else if (type) {
  16927. return `$${type}.${raw}`;
  16928. }
  16929. }
  16930. // fallback to ctx
  16931. return `_ctx.${raw}`;
  16932. };
  16933. // fast path if expression is a simple identifier.
  16934. const rawExp = node.content;
  16935. // bail constant on parens (function invocation) and dot (member access)
  16936. const bailConstant = rawExp.indexOf(`(`) > -1 || rawExp.indexOf('.') > 0;
  16937. if (isSimpleIdentifier(rawExp)) {
  16938. const isScopeVarReference = context.identifiers[rawExp];
  16939. const isAllowedGlobal = isGloballyWhitelisted(rawExp);
  16940. const isLiteral = isLiteralWhitelisted(rawExp);
  16941. if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
  16942. // const bindings exposed from setup can be skipped for patching but
  16943. // cannot be hoisted to module scope
  16944. if (bindingMetadata[node.content] === "setup-const" /* SETUP_CONST */) {
  16945. node.constType = 1 /* CAN_SKIP_PATCH */;
  16946. }
  16947. node.content = rewriteIdentifier(rawExp);
  16948. }
  16949. else if (!isScopeVarReference) {
  16950. if (isLiteral) {
  16951. node.constType = 3 /* CAN_STRINGIFY */;
  16952. }
  16953. else {
  16954. node.constType = 2 /* CAN_HOIST */;
  16955. }
  16956. }
  16957. return node;
  16958. }
  16959. let ast;
  16960. // exp needs to be parsed differently:
  16961. // 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
  16962. // exp, but make sure to pad with spaces for consistent ranges
  16963. // 2. Expressions: wrap with parens (for e.g. object expressions)
  16964. // 3. Function arguments (v-for, v-slot): place in a function argument position
  16965. const source = asRawStatements
  16966. ? ` ${rawExp} `
  16967. : `(${rawExp})${asParams ? `=>{}` : ``}`;
  16968. try {
  16969. ast = parse_1(source, {
  16970. plugins: [...context.expressionPlugins, ...babelParserDefaultPlugins]
  16971. }).program;
  16972. }
  16973. catch (e) {
  16974. context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
  16975. return node;
  16976. }
  16977. const ids = [];
  16978. const knownIds = Object.create(context.identifiers);
  16979. const isDuplicate = (node) => ids.some(id => id.start === node.start);
  16980. const parentStack = [];
  16981. walk$1(ast, {
  16982. enter(node, parent) {
  16983. parent && parentStack.push(parent);
  16984. if (node.type === 'Identifier') {
  16985. if (!isDuplicate(node)) {
  16986. const needPrefix = shouldPrefix(node, parent, parentStack);
  16987. if (!knownIds[node.name] && needPrefix) {
  16988. if (isStaticProperty(parent) && parent.shorthand) {
  16989. // property shorthand like { foo }, we need to add the key since
  16990. // we rewrite the value
  16991. node.prefix = `${node.name}: `;
  16992. }
  16993. node.name = rewriteIdentifier(node.name, parent, node);
  16994. ids.push(node);
  16995. }
  16996. else if (!isStaticPropertyKey(node, parent)) {
  16997. // The identifier is considered constant unless it's pointing to a
  16998. // scope variable (a v-for alias, or a v-slot prop)
  16999. if (!(needPrefix && knownIds[node.name]) && !bailConstant) {
  17000. node.isConstant = true;
  17001. }
  17002. // also generate sub-expressions for other identifiers for better
  17003. // source map support. (except for property keys which are static)
  17004. ids.push(node);
  17005. }
  17006. }
  17007. }
  17008. else if (isFunction$1(node)) {
  17009. // walk function expressions and add its arguments to known identifiers
  17010. // so that we don't prefix them
  17011. node.params.forEach(p => walk$1(p, {
  17012. enter(child, parent) {
  17013. if (child.type === 'Identifier' &&
  17014. // do not record as scope variable if is a destructured key
  17015. !isStaticPropertyKey(child, parent) &&
  17016. // do not record if this is a default value
  17017. // assignment of a destructured variable
  17018. !(parent &&
  17019. parent.type === 'AssignmentPattern' &&
  17020. parent.right === child)) {
  17021. const { name } = child;
  17022. if (node.scopeIds && node.scopeIds.has(name)) {
  17023. return;
  17024. }
  17025. if (name in knownIds) {
  17026. knownIds[name]++;
  17027. }
  17028. else {
  17029. knownIds[name] = 1;
  17030. }
  17031. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  17032. }
  17033. }
  17034. }));
  17035. }
  17036. },
  17037. leave(node, parent) {
  17038. parent && parentStack.pop();
  17039. if (node !== ast.body[0].expression && node.scopeIds) {
  17040. node.scopeIds.forEach((id) => {
  17041. knownIds[id]--;
  17042. if (knownIds[id] === 0) {
  17043. delete knownIds[id];
  17044. }
  17045. });
  17046. }
  17047. }
  17048. });
  17049. // We break up the compound expression into an array of strings and sub
  17050. // expressions (for identifiers that have been prefixed). In codegen, if
  17051. // an ExpressionNode has the `.children` property, it will be used instead of
  17052. // `.content`.
  17053. const children = [];
  17054. ids.sort((a, b) => a.start - b.start);
  17055. ids.forEach((id, i) => {
  17056. // range is offset by -1 due to the wrapping parens when parsed
  17057. const start = id.start - 1;
  17058. const end = id.end - 1;
  17059. const last = ids[i - 1];
  17060. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  17061. if (leadingText.length || id.prefix) {
  17062. children.push(leadingText + (id.prefix || ``));
  17063. }
  17064. const source = rawExp.slice(start, end);
  17065. children.push(createSimpleExpression(id.name, false, {
  17066. source,
  17067. start: advancePositionWithClone(node.loc.start, source, start),
  17068. end: advancePositionWithClone(node.loc.start, source, end)
  17069. }, id.isConstant ? 3 /* CAN_STRINGIFY */ : 0 /* NOT_CONSTANT */));
  17070. if (i === ids.length - 1 && end < rawExp.length) {
  17071. children.push(rawExp.slice(end));
  17072. }
  17073. });
  17074. let ret;
  17075. if (children.length) {
  17076. ret = createCompoundExpression(children, node.loc);
  17077. }
  17078. else {
  17079. ret = node;
  17080. ret.constType = bailConstant
  17081. ? 0 /* NOT_CONSTANT */
  17082. : 3 /* CAN_STRINGIFY */;
  17083. }
  17084. ret.identifiers = Object.keys(knownIds);
  17085. return ret;
  17086. }
  17087. const isFunction$1 = (node) => {
  17088. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  17089. };
  17090. const isStaticProperty = (node) => node &&
  17091. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  17092. !node.computed;
  17093. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  17094. function shouldPrefix(id, parent, parentStack) {
  17095. // declaration id
  17096. if ((parent.type === 'VariableDeclarator' ||
  17097. parent.type === 'ClassDeclaration') &&
  17098. parent.id === id) {
  17099. return false;
  17100. }
  17101. if (isFunction$1(parent)) {
  17102. // function decalration/expression id
  17103. if (parent.id === id) {
  17104. return false;
  17105. }
  17106. // params list
  17107. if (parent.params.includes(id)) {
  17108. return false;
  17109. }
  17110. }
  17111. // property key
  17112. // this also covers object destructure pattern
  17113. if (isStaticPropertyKey(id, parent)) {
  17114. return false;
  17115. }
  17116. // non-assignment array destructure pattern
  17117. if (parent.type === 'ArrayPattern' &&
  17118. !isInDestructureAssignment(parent, parentStack)) {
  17119. return false;
  17120. }
  17121. // member expression property
  17122. if ((parent.type === 'MemberExpression' ||
  17123. parent.type === 'OptionalMemberExpression') &&
  17124. parent.property === id &&
  17125. !parent.computed) {
  17126. return false;
  17127. }
  17128. // is a special keyword but parsed as identifier
  17129. if (id.name === 'arguments') {
  17130. return false;
  17131. }
  17132. // skip whitelisted globals
  17133. if (isGloballyWhitelisted(id.name)) {
  17134. return false;
  17135. }
  17136. // special case for webpack compilation
  17137. if (id.name === 'require') {
  17138. return false;
  17139. }
  17140. return true;
  17141. }
  17142. function isInDestructureAssignment(parent, parentStack) {
  17143. if (parent &&
  17144. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  17145. let i = parentStack.length;
  17146. while (i--) {
  17147. const p = parentStack[i];
  17148. if (p.type === 'AssignmentExpression') {
  17149. return true;
  17150. }
  17151. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  17152. break;
  17153. }
  17154. }
  17155. }
  17156. return false;
  17157. }
  17158. function stringifyExpression(exp) {
  17159. if (isString(exp)) {
  17160. return exp;
  17161. }
  17162. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  17163. return exp.content;
  17164. }
  17165. else {
  17166. return exp.children
  17167. .map(stringifyExpression)
  17168. .join('');
  17169. }
  17170. }
  17171. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  17172. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  17173. // #1587: We need to dynamically increment the key based on the current
  17174. // node's sibling nodes, since chained v-if/else branches are
  17175. // rendered at the same depth
  17176. const siblings = context.parent.children;
  17177. let i = siblings.indexOf(ifNode);
  17178. let key = 0;
  17179. while (i-- >= 0) {
  17180. const sibling = siblings[i];
  17181. if (sibling && sibling.type === 9 /* IF */) {
  17182. key += sibling.branches.length;
  17183. }
  17184. }
  17185. // Exit callback. Complete the codegenNode when all children have been
  17186. // transformed.
  17187. return () => {
  17188. if (isRoot) {
  17189. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  17190. }
  17191. else {
  17192. // attach this branch's codegen node to the v-if root.
  17193. const parentCondition = getParentCondition(ifNode.codegenNode);
  17194. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  17195. }
  17196. };
  17197. });
  17198. });
  17199. // target-agnostic transform used for both Client and SSR
  17200. function processIf(node, dir, context, processCodegen) {
  17201. if (dir.name !== 'else' &&
  17202. (!dir.exp || !dir.exp.content.trim())) {
  17203. const loc = dir.exp ? dir.exp.loc : node.loc;
  17204. context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  17205. dir.exp = createSimpleExpression(`true`, false, loc);
  17206. }
  17207. if (context.prefixIdentifiers && dir.exp) {
  17208. // dir.exp can only be simple expression because vIf transform is applied
  17209. // before expression transform.
  17210. dir.exp = processExpression(dir.exp, context);
  17211. }
  17212. if (dir.name === 'if') {
  17213. const branch = createIfBranch(node, dir);
  17214. const ifNode = {
  17215. type: 9 /* IF */,
  17216. loc: node.loc,
  17217. branches: [branch]
  17218. };
  17219. context.replaceNode(ifNode);
  17220. if (processCodegen) {
  17221. return processCodegen(ifNode, branch, true);
  17222. }
  17223. }
  17224. else {
  17225. // locate the adjacent v-if
  17226. const siblings = context.parent.children;
  17227. const comments = [];
  17228. let i = siblings.indexOf(node);
  17229. while (i-- >= -1) {
  17230. const sibling = siblings[i];
  17231. if (sibling && sibling.type === 3 /* COMMENT */) {
  17232. context.removeNode(sibling);
  17233. comments.unshift(sibling);
  17234. continue;
  17235. }
  17236. if (sibling &&
  17237. sibling.type === 2 /* TEXT */ &&
  17238. !sibling.content.trim().length) {
  17239. context.removeNode(sibling);
  17240. continue;
  17241. }
  17242. if (sibling && sibling.type === 9 /* IF */) {
  17243. // move the node to the if node's branches
  17244. context.removeNode();
  17245. const branch = createIfBranch(node, dir);
  17246. if (comments.length) {
  17247. branch.children = [...comments, ...branch.children];
  17248. }
  17249. // check if user is forcing same key on different branches
  17250. {
  17251. const key = branch.userKey;
  17252. if (key) {
  17253. sibling.branches.forEach(({ userKey }) => {
  17254. if (isSameKey(userKey, key)) {
  17255. context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  17256. }
  17257. });
  17258. }
  17259. }
  17260. sibling.branches.push(branch);
  17261. const onExit = processCodegen && processCodegen(sibling, branch, false);
  17262. // since the branch was removed, it will not be traversed.
  17263. // make sure to traverse here.
  17264. traverseNode(branch, context);
  17265. // call on exit
  17266. if (onExit)
  17267. onExit();
  17268. // make sure to reset currentNode after traversal to indicate this
  17269. // node has been removed.
  17270. context.currentNode = null;
  17271. }
  17272. else {
  17273. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  17274. }
  17275. break;
  17276. }
  17277. }
  17278. }
  17279. function createIfBranch(node, dir) {
  17280. return {
  17281. type: 10 /* IF_BRANCH */,
  17282. loc: node.loc,
  17283. condition: dir.name === 'else' ? undefined : dir.exp,
  17284. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  17285. ? node.children
  17286. : [node],
  17287. userKey: findProp(node, `key`)
  17288. };
  17289. }
  17290. function createCodegenNodeForBranch(branch, keyIndex, context) {
  17291. if (branch.condition) {
  17292. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  17293. // make sure to pass in asBlock: true so that the comment node call
  17294. // closes the current block.
  17295. createCallExpression(context.helper(CREATE_COMMENT), [
  17296. '"v-if"' ,
  17297. 'true'
  17298. ]));
  17299. }
  17300. else {
  17301. return createChildrenCodegenNode(branch, keyIndex, context);
  17302. }
  17303. }
  17304. function createChildrenCodegenNode(branch, keyIndex, context) {
  17305. const { helper } = context;
  17306. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
  17307. const { children } = branch;
  17308. const firstChild = children[0];
  17309. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  17310. if (needFragmentWrapper) {
  17311. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  17312. // optimize away nested fragments when child is a ForNode
  17313. const vnodeCall = firstChild.codegenNode;
  17314. injectProp(vnodeCall, keyProperty, context);
  17315. return vnodeCall;
  17316. }
  17317. else {
  17318. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, 64 /* STABLE_FRAGMENT */ +
  17319. (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  17320. ), undefined, undefined, true, false, branch.loc);
  17321. }
  17322. }
  17323. else {
  17324. const vnodeCall = firstChild
  17325. .codegenNode;
  17326. // Change createVNode to createBlock.
  17327. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  17328. vnodeCall.isBlock = true;
  17329. helper(OPEN_BLOCK);
  17330. helper(CREATE_BLOCK);
  17331. }
  17332. // inject branch key
  17333. injectProp(vnodeCall, keyProperty, context);
  17334. return vnodeCall;
  17335. }
  17336. }
  17337. function isSameKey(a, b) {
  17338. if (!a || a.type !== b.type) {
  17339. return false;
  17340. }
  17341. if (a.type === 6 /* ATTRIBUTE */) {
  17342. if (a.value.content !== b.value.content) {
  17343. return false;
  17344. }
  17345. }
  17346. else {
  17347. // directive
  17348. const exp = a.exp;
  17349. const branchExp = b.exp;
  17350. if (exp.type !== branchExp.type) {
  17351. return false;
  17352. }
  17353. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  17354. (exp.isStatic !== branchExp.isStatic ||
  17355. exp.content !== branchExp.content)) {
  17356. return false;
  17357. }
  17358. }
  17359. return true;
  17360. }
  17361. function getParentCondition(node) {
  17362. while (true) {
  17363. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  17364. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  17365. node = node.alternate;
  17366. }
  17367. else {
  17368. return node;
  17369. }
  17370. }
  17371. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  17372. node = node.value;
  17373. }
  17374. }
  17375. }
  17376. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  17377. const { helper } = context;
  17378. return processFor(node, dir, context, forNode => {
  17379. // create the loop render function expression now, and add the
  17380. // iterator on exit after all children have been traversed
  17381. const renderExp = createCallExpression(helper(RENDER_LIST), [
  17382. forNode.source
  17383. ]);
  17384. const keyProp = findProp(node, `key`);
  17385. const keyProperty = keyProp
  17386. ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
  17387. ? createSimpleExpression(keyProp.value.content, true)
  17388. : keyProp.exp)
  17389. : null;
  17390. if (context.prefixIdentifiers && keyProperty) {
  17391. // #2085 process :key expression needs to be processed in order for it
  17392. // to behave consistently for <template v-for> and <div v-for>.
  17393. // In the case of `<template v-for>`, the node is discarded and never
  17394. // traversed so its key expression won't be processed by the normal
  17395. // transforms.
  17396. keyProperty.value = processExpression(keyProperty.value, context);
  17397. }
  17398. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  17399. forNode.source.constType > 0 /* NOT_CONSTANT */;
  17400. const fragmentFlag = isStableFragment
  17401. ? 64 /* STABLE_FRAGMENT */
  17402. : keyProp
  17403. ? 128 /* KEYED_FRAGMENT */
  17404. : 256 /* UNKEYED_FRAGMENT */;
  17405. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  17406. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
  17407. return () => {
  17408. // finish the codegen now that all children have been traversed
  17409. let childBlock;
  17410. const isTemplate = isTemplateNode(node);
  17411. const { children } = forNode;
  17412. // check <template v-for> key placement
  17413. if (isTemplate) {
  17414. node.children.some(c => {
  17415. if (c.type === 1 /* ELEMENT */) {
  17416. const key = findProp(c, 'key');
  17417. if (key) {
  17418. context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  17419. return true;
  17420. }
  17421. }
  17422. });
  17423. }
  17424. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  17425. const slotOutlet = isSlotOutlet(node)
  17426. ? node
  17427. : isTemplate &&
  17428. node.children.length === 1 &&
  17429. isSlotOutlet(node.children[0])
  17430. ? node.children[0] // api-extractor somehow fails to infer this
  17431. : null;
  17432. if (slotOutlet) {
  17433. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  17434. childBlock = slotOutlet.codegenNode;
  17435. if (isTemplate && keyProperty) {
  17436. // <template v-for="..." :key="..."><slot/></template>
  17437. // we need to inject the key to the renderSlot() call.
  17438. // the props for renderSlot is passed as the 3rd argument.
  17439. injectProp(childBlock, keyProperty, context);
  17440. }
  17441. }
  17442. else if (needFragmentWrapper) {
  17443. // <template v-for="..."> with text or multi-elements
  17444. // should generate a fragment block for each loop
  17445. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
  17446. (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  17447. ), undefined, undefined, true);
  17448. }
  17449. else {
  17450. // Normal element v-for. Directly use the child's codegenNode
  17451. // but mark it as a block.
  17452. childBlock = children[0]
  17453. .codegenNode;
  17454. if (isTemplate && keyProperty) {
  17455. injectProp(childBlock, keyProperty, context);
  17456. }
  17457. childBlock.isBlock = !isStableFragment;
  17458. if (childBlock.isBlock) {
  17459. helper(OPEN_BLOCK);
  17460. helper(CREATE_BLOCK);
  17461. }
  17462. else {
  17463. helper(CREATE_VNODE);
  17464. }
  17465. }
  17466. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  17467. };
  17468. });
  17469. });
  17470. // target-agnostic transform used for both Client and SSR
  17471. function processFor(node, dir, context, processCodegen) {
  17472. if (!dir.exp) {
  17473. context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  17474. return;
  17475. }
  17476. const parseResult = parseForExpression(
  17477. // can only be simple expression because vFor transform is applied
  17478. // before expression transform.
  17479. dir.exp, context);
  17480. if (!parseResult) {
  17481. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  17482. return;
  17483. }
  17484. const { addIdentifiers, removeIdentifiers, scopes } = context;
  17485. const { source, value, key, index } = parseResult;
  17486. const forNode = {
  17487. type: 11 /* FOR */,
  17488. loc: dir.loc,
  17489. source,
  17490. valueAlias: value,
  17491. keyAlias: key,
  17492. objectIndexAlias: index,
  17493. parseResult,
  17494. children: isTemplateNode(node) ? node.children : [node]
  17495. };
  17496. context.replaceNode(forNode);
  17497. // bookkeeping
  17498. scopes.vFor++;
  17499. if (context.prefixIdentifiers) {
  17500. // scope management
  17501. // inject identifiers to context
  17502. value && addIdentifiers(value);
  17503. key && addIdentifiers(key);
  17504. index && addIdentifiers(index);
  17505. }
  17506. const onExit = processCodegen && processCodegen(forNode);
  17507. return () => {
  17508. scopes.vFor--;
  17509. if (context.prefixIdentifiers) {
  17510. value && removeIdentifiers(value);
  17511. key && removeIdentifiers(key);
  17512. index && removeIdentifiers(index);
  17513. }
  17514. if (onExit)
  17515. onExit();
  17516. };
  17517. }
  17518. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  17519. // This regex doesn't cover the case if key or index aliases have destructuring,
  17520. // but those do not make sense in the first place, so this works in practice.
  17521. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  17522. const stripParensRE = /^\(|\)$/g;
  17523. function parseForExpression(input, context) {
  17524. const loc = input.loc;
  17525. const exp = input.content;
  17526. const inMatch = exp.match(forAliasRE);
  17527. if (!inMatch)
  17528. return;
  17529. const [, LHS, RHS] = inMatch;
  17530. const result = {
  17531. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  17532. value: undefined,
  17533. key: undefined,
  17534. index: undefined
  17535. };
  17536. if (context.prefixIdentifiers) {
  17537. result.source = processExpression(result.source, context);
  17538. }
  17539. let valueContent = LHS.trim()
  17540. .replace(stripParensRE, '')
  17541. .trim();
  17542. const trimmedOffset = LHS.indexOf(valueContent);
  17543. const iteratorMatch = valueContent.match(forIteratorRE);
  17544. if (iteratorMatch) {
  17545. valueContent = valueContent.replace(forIteratorRE, '').trim();
  17546. const keyContent = iteratorMatch[1].trim();
  17547. let keyOffset;
  17548. if (keyContent) {
  17549. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  17550. result.key = createAliasExpression(loc, keyContent, keyOffset);
  17551. if (context.prefixIdentifiers) {
  17552. result.key = processExpression(result.key, context, true);
  17553. }
  17554. }
  17555. if (iteratorMatch[2]) {
  17556. const indexContent = iteratorMatch[2].trim();
  17557. if (indexContent) {
  17558. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  17559. ? keyOffset + keyContent.length
  17560. : trimmedOffset + valueContent.length));
  17561. if (context.prefixIdentifiers) {
  17562. result.index = processExpression(result.index, context, true);
  17563. }
  17564. }
  17565. }
  17566. }
  17567. if (valueContent) {
  17568. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  17569. if (context.prefixIdentifiers) {
  17570. result.value = processExpression(result.value, context, true);
  17571. }
  17572. }
  17573. return result;
  17574. }
  17575. function createAliasExpression(range, content, offset) {
  17576. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  17577. }
  17578. function createForLoopParams({ value, key, index }) {
  17579. const params = [];
  17580. if (value) {
  17581. params.push(value);
  17582. }
  17583. if (key) {
  17584. if (!value) {
  17585. params.push(createSimpleExpression(`_`, false));
  17586. }
  17587. params.push(key);
  17588. }
  17589. if (index) {
  17590. if (!key) {
  17591. if (!value) {
  17592. params.push(createSimpleExpression(`_`, false));
  17593. }
  17594. params.push(createSimpleExpression(`__`, false));
  17595. }
  17596. params.push(index);
  17597. }
  17598. return params;
  17599. }
  17600. const defaultFallback = createSimpleExpression(`undefined`, false);
  17601. // A NodeTransform that:
  17602. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  17603. // by transformExpression. This is only applied in non-browser builds with
  17604. // { prefixIdentifiers: true }.
  17605. // 2. Track v-slot depths so that we know a slot is inside another slot.
  17606. // Note the exit callback is executed before buildSlots() on the same node,
  17607. // so only nested slots see positive numbers.
  17608. const trackSlotScopes = (node, context) => {
  17609. if (node.type === 1 /* ELEMENT */ &&
  17610. (node.tagType === 1 /* COMPONENT */ ||
  17611. node.tagType === 3 /* TEMPLATE */)) {
  17612. // We are only checking non-empty v-slot here
  17613. // since we only care about slots that introduce scope variables.
  17614. const vSlot = findDir(node, 'slot');
  17615. if (vSlot) {
  17616. const slotProps = vSlot.exp;
  17617. if (context.prefixIdentifiers) {
  17618. slotProps && context.addIdentifiers(slotProps);
  17619. }
  17620. context.scopes.vSlot++;
  17621. return () => {
  17622. if (context.prefixIdentifiers) {
  17623. slotProps && context.removeIdentifiers(slotProps);
  17624. }
  17625. context.scopes.vSlot--;
  17626. };
  17627. }
  17628. }
  17629. };
  17630. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  17631. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  17632. const trackVForSlotScopes = (node, context) => {
  17633. let vFor;
  17634. if (isTemplateNode(node) &&
  17635. node.props.some(isVSlot) &&
  17636. (vFor = findDir(node, 'for'))) {
  17637. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  17638. if (result) {
  17639. const { value, key, index } = result;
  17640. const { addIdentifiers, removeIdentifiers } = context;
  17641. value && addIdentifiers(value);
  17642. key && addIdentifiers(key);
  17643. index && addIdentifiers(index);
  17644. return () => {
  17645. value && removeIdentifiers(value);
  17646. key && removeIdentifiers(key);
  17647. index && removeIdentifiers(index);
  17648. };
  17649. }
  17650. }
  17651. };
  17652. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  17653. // Instead of being a DirectiveTransform, v-slot processing is called during
  17654. // transformElement to build the slots object for a component.
  17655. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  17656. context.helper(WITH_CTX);
  17657. const { children, loc } = node;
  17658. const slotsProperties = [];
  17659. const dynamicSlots = [];
  17660. const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
  17661. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  17662. // since it likely uses a scope variable.
  17663. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  17664. // with `prefixIdentifiers: true`, this can be further optimized to make
  17665. // it dynamic only when the slot actually uses the scope variables.
  17666. if (!context.ssr && context.prefixIdentifiers) {
  17667. hasDynamicSlots = hasScopeRef(node, context.identifiers);
  17668. }
  17669. // 1. Check for slot with slotProps on component itself.
  17670. // <Comp v-slot="{ prop }"/>
  17671. const onComponentSlot = findDir(node, 'slot', true);
  17672. if (onComponentSlot) {
  17673. const { arg, exp } = onComponentSlot;
  17674. if (arg && !isStaticExp(arg)) {
  17675. hasDynamicSlots = true;
  17676. }
  17677. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  17678. }
  17679. // 2. Iterate through children and check for template slots
  17680. // <template v-slot:foo="{ prop }">
  17681. let hasTemplateSlots = false;
  17682. let hasNamedDefaultSlot = false;
  17683. const implicitDefaultChildren = [];
  17684. const seenSlotNames = new Set();
  17685. for (let i = 0; i < children.length; i++) {
  17686. const slotElement = children[i];
  17687. let slotDir;
  17688. if (!isTemplateNode(slotElement) ||
  17689. !(slotDir = findDir(slotElement, 'slot', true))) {
  17690. // not a <template v-slot>, skip.
  17691. if (slotElement.type !== 3 /* COMMENT */) {
  17692. implicitDefaultChildren.push(slotElement);
  17693. }
  17694. continue;
  17695. }
  17696. if (onComponentSlot) {
  17697. // already has on-component slot - this is incorrect usage.
  17698. context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  17699. break;
  17700. }
  17701. hasTemplateSlots = true;
  17702. const { children: slotChildren, loc: slotLoc } = slotElement;
  17703. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  17704. // check if name is dynamic.
  17705. let staticSlotName;
  17706. if (isStaticExp(slotName)) {
  17707. staticSlotName = slotName ? slotName.content : `default`;
  17708. }
  17709. else {
  17710. hasDynamicSlots = true;
  17711. }
  17712. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  17713. // check if this slot is conditional (v-if/v-for)
  17714. let vIf;
  17715. let vElse;
  17716. let vFor;
  17717. if ((vIf = findDir(slotElement, 'if'))) {
  17718. hasDynamicSlots = true;
  17719. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  17720. }
  17721. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  17722. // find adjacent v-if
  17723. let j = i;
  17724. let prev;
  17725. while (j--) {
  17726. prev = children[j];
  17727. if (prev.type !== 3 /* COMMENT */) {
  17728. break;
  17729. }
  17730. }
  17731. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  17732. // remove node
  17733. children.splice(i, 1);
  17734. i--;
  17735. // attach this slot to previous conditional
  17736. let conditional = dynamicSlots[dynamicSlots.length - 1];
  17737. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  17738. conditional = conditional.alternate;
  17739. }
  17740. conditional.alternate = vElse.exp
  17741. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  17742. : buildDynamicSlot(slotName, slotFunction);
  17743. }
  17744. else {
  17745. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  17746. }
  17747. }
  17748. else if ((vFor = findDir(slotElement, 'for'))) {
  17749. hasDynamicSlots = true;
  17750. const parseResult = vFor.parseResult ||
  17751. parseForExpression(vFor.exp, context);
  17752. if (parseResult) {
  17753. // Render the dynamic slots as an array and add it to the createSlot()
  17754. // args. The runtime knows how to handle it appropriately.
  17755. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  17756. parseResult.source,
  17757. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  17758. ]));
  17759. }
  17760. else {
  17761. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  17762. }
  17763. }
  17764. else {
  17765. // check duplicate static names
  17766. if (staticSlotName) {
  17767. if (seenSlotNames.has(staticSlotName)) {
  17768. context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  17769. continue;
  17770. }
  17771. seenSlotNames.add(staticSlotName);
  17772. if (staticSlotName === 'default') {
  17773. hasNamedDefaultSlot = true;
  17774. }
  17775. }
  17776. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  17777. }
  17778. }
  17779. if (!onComponentSlot) {
  17780. if (!hasTemplateSlots) {
  17781. // implicit default slot (on component)
  17782. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  17783. }
  17784. else if (implicitDefaultChildren.length) {
  17785. // implicit default slot (mixed with named slots)
  17786. if (hasNamedDefaultSlot) {
  17787. context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  17788. }
  17789. else {
  17790. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  17791. }
  17792. }
  17793. }
  17794. const slotFlag = hasDynamicSlots
  17795. ? 2 /* DYNAMIC */
  17796. : hasForwardedSlots(node.children)
  17797. ? 3 /* FORWARDED */
  17798. : 1 /* STABLE */;
  17799. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  17800. // 2 = compiled but dynamic = can skip normalization, but must run diff
  17801. // 1 = compiled and static = can skip normalization AND diff as optimized
  17802. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  17803. if (dynamicSlots.length) {
  17804. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  17805. slots,
  17806. createArrayExpression(dynamicSlots)
  17807. ]);
  17808. }
  17809. return {
  17810. slots,
  17811. hasDynamicSlots
  17812. };
  17813. }
  17814. function buildDynamicSlot(name, fn) {
  17815. return createObjectExpression([
  17816. createObjectProperty(`name`, name),
  17817. createObjectProperty(`fn`, fn)
  17818. ]);
  17819. }
  17820. function hasForwardedSlots(children) {
  17821. for (let i = 0; i < children.length; i++) {
  17822. const child = children[i];
  17823. if (child.type === 1 /* ELEMENT */) {
  17824. if (child.tagType === 2 /* SLOT */ ||
  17825. (child.tagType === 0 /* ELEMENT */ &&
  17826. hasForwardedSlots(child.children))) {
  17827. return true;
  17828. }
  17829. }
  17830. }
  17831. return false;
  17832. }
  17833. // some directive transforms (e.g. v-model) may return a symbol for runtime
  17834. // import, which should be used instead of a resolveDirective call.
  17835. const directiveImportMap = new WeakMap();
  17836. // generate a JavaScript AST for this element's codegen
  17837. const transformElement = (node, context) => {
  17838. if (!(node.type === 1 /* ELEMENT */ &&
  17839. (node.tagType === 0 /* ELEMENT */ ||
  17840. node.tagType === 1 /* COMPONENT */))) {
  17841. return;
  17842. }
  17843. // perform the work on exit, after all child expressions have been
  17844. // processed and merged.
  17845. return function postTransformElement() {
  17846. const { tag, props } = node;
  17847. const isComponent = node.tagType === 1 /* COMPONENT */;
  17848. // The goal of the transform is to create a codegenNode implementing the
  17849. // VNodeCall interface.
  17850. const vnodeTag = isComponent
  17851. ? resolveComponentType(node, context)
  17852. : `"${tag}"`;
  17853. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  17854. let vnodeProps;
  17855. let vnodeChildren;
  17856. let vnodePatchFlag;
  17857. let patchFlag = 0;
  17858. let vnodeDynamicProps;
  17859. let dynamicPropNames;
  17860. let vnodeDirectives;
  17861. let shouldUseBlock =
  17862. // dynamic component may resolve to plain elements
  17863. isDynamicComponent ||
  17864. vnodeTag === TELEPORT ||
  17865. vnodeTag === SUSPENSE ||
  17866. (!isComponent &&
  17867. // <svg> and <foreignObject> must be forced into blocks so that block
  17868. // updates inside get proper isSVG flag at runtime. (#639, #643)
  17869. // This is technically web-specific, but splitting the logic out of core
  17870. // leads to too much unnecessary complexity.
  17871. (tag === 'svg' ||
  17872. tag === 'foreignObject' ||
  17873. // #938: elements with dynamic keys should be forced into blocks
  17874. findProp(node, 'key', true)));
  17875. // props
  17876. if (props.length > 0) {
  17877. const propsBuildResult = buildProps(node, context);
  17878. vnodeProps = propsBuildResult.props;
  17879. patchFlag = propsBuildResult.patchFlag;
  17880. dynamicPropNames = propsBuildResult.dynamicPropNames;
  17881. const directives = propsBuildResult.directives;
  17882. vnodeDirectives =
  17883. directives && directives.length
  17884. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  17885. : undefined;
  17886. }
  17887. // children
  17888. if (node.children.length > 0) {
  17889. if (vnodeTag === KEEP_ALIVE) {
  17890. // Although a built-in component, we compile KeepAlive with raw children
  17891. // instead of slot functions so that it can be used inside Transition
  17892. // or other Transition-wrapping HOCs.
  17893. // To ensure correct updates with block optimizations, we need to:
  17894. // 1. Force keep-alive into a block. This avoids its children being
  17895. // collected by a parent block.
  17896. shouldUseBlock = true;
  17897. // 2. Force keep-alive to always be updated, since it uses raw children.
  17898. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  17899. if (node.children.length > 1) {
  17900. context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  17901. start: node.children[0].loc.start,
  17902. end: node.children[node.children.length - 1].loc.end,
  17903. source: ''
  17904. }));
  17905. }
  17906. }
  17907. const shouldBuildAsSlots = isComponent &&
  17908. // Teleport is not a real component and has dedicated runtime handling
  17909. vnodeTag !== TELEPORT &&
  17910. // explained above.
  17911. vnodeTag !== KEEP_ALIVE;
  17912. if (shouldBuildAsSlots) {
  17913. const { slots, hasDynamicSlots } = buildSlots(node, context);
  17914. vnodeChildren = slots;
  17915. if (hasDynamicSlots) {
  17916. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  17917. }
  17918. }
  17919. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  17920. const child = node.children[0];
  17921. const type = child.type;
  17922. // check for dynamic text children
  17923. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  17924. type === 8 /* COMPOUND_EXPRESSION */;
  17925. if (hasDynamicTextChild &&
  17926. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  17927. patchFlag |= 1 /* TEXT */;
  17928. }
  17929. // pass directly if the only child is a text node
  17930. // (plain / interpolation / expression)
  17931. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  17932. vnodeChildren = child;
  17933. }
  17934. else {
  17935. vnodeChildren = node.children;
  17936. }
  17937. }
  17938. else {
  17939. vnodeChildren = node.children;
  17940. }
  17941. }
  17942. // patchFlag & dynamicPropNames
  17943. if (patchFlag !== 0) {
  17944. {
  17945. if (patchFlag < 0) {
  17946. // special flags (negative and mutually exclusive)
  17947. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  17948. }
  17949. else {
  17950. // bitwise flags
  17951. const flagNames = Object.keys(PatchFlagNames)
  17952. .map(Number)
  17953. .filter(n => n > 0 && patchFlag & n)
  17954. .map(n => PatchFlagNames[n])
  17955. .join(`, `);
  17956. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  17957. }
  17958. }
  17959. if (dynamicPropNames && dynamicPropNames.length) {
  17960. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  17961. }
  17962. }
  17963. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
  17964. };
  17965. };
  17966. function resolveComponentType(node, context, ssr = false) {
  17967. const { tag } = node;
  17968. // 1. dynamic component
  17969. const isProp = node.tag === 'component' ? findProp(node, 'is') : findDir(node, 'is');
  17970. if (isProp) {
  17971. const exp = isProp.type === 6 /* ATTRIBUTE */
  17972. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  17973. : isProp.exp;
  17974. if (exp) {
  17975. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  17976. exp
  17977. ]);
  17978. }
  17979. }
  17980. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  17981. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  17982. if (builtIn) {
  17983. // built-ins are simply fallthroughs / have special handling during ssr
  17984. // so we don't need to import their runtime equivalents
  17985. if (!ssr)
  17986. context.helper(builtIn);
  17987. return builtIn;
  17988. }
  17989. // 3. user component (from setup bindings)
  17990. // this is skipped in browser build since browser builds do not perform
  17991. // binding analysis.
  17992. {
  17993. const fromSetup = resolveSetupReference(tag, context);
  17994. if (fromSetup) {
  17995. return fromSetup;
  17996. }
  17997. }
  17998. // 4. Self referencing component (inferred from filename)
  17999. if (context.selfName) {
  18000. if (capitalize(camelize(tag)) === context.selfName) {
  18001. context.helper(RESOLVE_COMPONENT);
  18002. context.components.add(`_self`);
  18003. return toValidAssetId(`_self`, `component`);
  18004. }
  18005. }
  18006. // 5. user component (resolve)
  18007. context.helper(RESOLVE_COMPONENT);
  18008. context.components.add(tag);
  18009. return toValidAssetId(tag, `component`);
  18010. }
  18011. function resolveSetupReference(name, context) {
  18012. const bindings = context.bindingMetadata;
  18013. if (!bindings) {
  18014. return;
  18015. }
  18016. const camelName = camelize(name);
  18017. const PascalName = capitalize(camelName);
  18018. const checkType = (type) => {
  18019. if (bindings[name] === type) {
  18020. return name;
  18021. }
  18022. if (bindings[camelName] === type) {
  18023. return camelName;
  18024. }
  18025. if (bindings[PascalName] === type) {
  18026. return PascalName;
  18027. }
  18028. };
  18029. const fromConst = checkType("setup-const" /* SETUP_CONST */);
  18030. if (fromConst) {
  18031. return context.inline
  18032. ? // in inline mode, const setup bindings (e.g. imports) can be used as-is
  18033. fromConst
  18034. : `$setup[${JSON.stringify(fromConst)}]`;
  18035. }
  18036. const fromMaybeRef = checkType("setup-let" /* SETUP_LET */) ||
  18037. checkType("setup-ref" /* SETUP_REF */) ||
  18038. checkType("setup-maybe-ref" /* SETUP_MAYBE_REF */);
  18039. if (fromMaybeRef) {
  18040. return context.inline
  18041. ? // setup scope bindings that may be refs need to be unrefed
  18042. `${context.helperString(UNREF)}(${fromMaybeRef})`
  18043. : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  18044. }
  18045. }
  18046. function buildProps(node, context, props = node.props, ssr = false) {
  18047. const { tag, loc: elementLoc } = node;
  18048. const isComponent = node.tagType === 1 /* COMPONENT */;
  18049. let properties = [];
  18050. const mergeArgs = [];
  18051. const runtimeDirectives = [];
  18052. // patchFlag analysis
  18053. let patchFlag = 0;
  18054. let hasRef = false;
  18055. let hasClassBinding = false;
  18056. let hasStyleBinding = false;
  18057. let hasHydrationEventBinding = false;
  18058. let hasDynamicKeys = false;
  18059. let hasVnodeHook = false;
  18060. const dynamicPropNames = [];
  18061. const analyzePatchFlag = ({ key, value }) => {
  18062. if (isStaticExp(key)) {
  18063. const name = key.content;
  18064. const isEventHandler = isOn(name);
  18065. if (!isComponent &&
  18066. isEventHandler &&
  18067. // omit the flag for click handlers because hydration gives click
  18068. // dedicated fast path.
  18069. name.toLowerCase() !== 'onclick' &&
  18070. // omit v-model handlers
  18071. name !== 'onUpdate:modelValue' &&
  18072. // omit onVnodeXXX hooks
  18073. !isReservedProp(name)) {
  18074. hasHydrationEventBinding = true;
  18075. }
  18076. if (isEventHandler && isReservedProp(name)) {
  18077. hasVnodeHook = true;
  18078. }
  18079. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  18080. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  18081. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  18082. getConstantType(value, context) > 0)) {
  18083. // skip if the prop is a cached handler or has constant value
  18084. return;
  18085. }
  18086. if (name === 'ref') {
  18087. hasRef = true;
  18088. }
  18089. else if (name === 'class' && !isComponent) {
  18090. hasClassBinding = true;
  18091. }
  18092. else if (name === 'style' && !isComponent) {
  18093. hasStyleBinding = true;
  18094. }
  18095. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  18096. dynamicPropNames.push(name);
  18097. }
  18098. }
  18099. else {
  18100. hasDynamicKeys = true;
  18101. }
  18102. };
  18103. for (let i = 0; i < props.length; i++) {
  18104. // static attribute
  18105. const prop = props[i];
  18106. if (prop.type === 6 /* ATTRIBUTE */) {
  18107. const { loc, name, value } = prop;
  18108. let isStatic = true;
  18109. if (name === 'ref') {
  18110. hasRef = true;
  18111. // in inline mode there is no setupState object, so we can't use string
  18112. // keys to set the ref. Instead, we need to transform it to pass the
  18113. // acrtual ref instead.
  18114. if (context.inline) {
  18115. isStatic = false;
  18116. }
  18117. }
  18118. // skip :is on <component>
  18119. if (name === 'is' && tag === 'component') {
  18120. continue;
  18121. }
  18122. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  18123. }
  18124. else {
  18125. // directives
  18126. const { name, arg, exp, loc } = prop;
  18127. const isBind = name === 'bind';
  18128. const isOn = name === 'on';
  18129. // skip v-slot - it is handled by its dedicated transform.
  18130. if (name === 'slot') {
  18131. if (!isComponent) {
  18132. context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
  18133. }
  18134. continue;
  18135. }
  18136. // skip v-once - it is handled by its dedicated transform.
  18137. if (name === 'once') {
  18138. continue;
  18139. }
  18140. // skip v-is and :is on <component>
  18141. if (name === 'is' ||
  18142. (isBind && tag === 'component' && isBindKey(arg, 'is'))) {
  18143. continue;
  18144. }
  18145. // skip v-on in SSR compilation
  18146. if (isOn && ssr) {
  18147. continue;
  18148. }
  18149. // special case for v-bind and v-on with no argument
  18150. if (!arg && (isBind || isOn)) {
  18151. hasDynamicKeys = true;
  18152. if (exp) {
  18153. if (properties.length) {
  18154. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  18155. properties = [];
  18156. }
  18157. if (isBind) {
  18158. mergeArgs.push(exp);
  18159. }
  18160. else {
  18161. // v-on="obj" -> toHandlers(obj)
  18162. mergeArgs.push({
  18163. type: 14 /* JS_CALL_EXPRESSION */,
  18164. loc,
  18165. callee: context.helper(TO_HANDLERS),
  18166. arguments: [exp]
  18167. });
  18168. }
  18169. }
  18170. else {
  18171. context.onError(createCompilerError(isBind
  18172. ? 33 /* X_V_BIND_NO_EXPRESSION */
  18173. : 34 /* X_V_ON_NO_EXPRESSION */, loc));
  18174. }
  18175. continue;
  18176. }
  18177. const directiveTransform = context.directiveTransforms[name];
  18178. if (directiveTransform) {
  18179. // has built-in directive transform.
  18180. const { props, needRuntime } = directiveTransform(prop, node, context);
  18181. !ssr && props.forEach(analyzePatchFlag);
  18182. properties.push(...props);
  18183. if (needRuntime) {
  18184. runtimeDirectives.push(prop);
  18185. if (isSymbol(needRuntime)) {
  18186. directiveImportMap.set(prop, needRuntime);
  18187. }
  18188. }
  18189. }
  18190. else {
  18191. // no built-in transform, this is a user custom directive.
  18192. runtimeDirectives.push(prop);
  18193. }
  18194. }
  18195. }
  18196. let propsExpression = undefined;
  18197. // has v-bind="object" or v-on="object", wrap with mergeProps
  18198. if (mergeArgs.length) {
  18199. if (properties.length) {
  18200. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  18201. }
  18202. if (mergeArgs.length > 1) {
  18203. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  18204. }
  18205. else {
  18206. // single v-bind with nothing else - no need for a mergeProps call
  18207. propsExpression = mergeArgs[0];
  18208. }
  18209. }
  18210. else if (properties.length) {
  18211. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  18212. }
  18213. // patchFlag analysis
  18214. if (hasDynamicKeys) {
  18215. patchFlag |= 16 /* FULL_PROPS */;
  18216. }
  18217. else {
  18218. if (hasClassBinding) {
  18219. patchFlag |= 2 /* CLASS */;
  18220. }
  18221. if (hasStyleBinding) {
  18222. patchFlag |= 4 /* STYLE */;
  18223. }
  18224. if (dynamicPropNames.length) {
  18225. patchFlag |= 8 /* PROPS */;
  18226. }
  18227. if (hasHydrationEventBinding) {
  18228. patchFlag |= 32 /* HYDRATE_EVENTS */;
  18229. }
  18230. }
  18231. if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  18232. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  18233. patchFlag |= 512 /* NEED_PATCH */;
  18234. }
  18235. return {
  18236. props: propsExpression,
  18237. directives: runtimeDirectives,
  18238. patchFlag,
  18239. dynamicPropNames
  18240. };
  18241. }
  18242. // Dedupe props in an object literal.
  18243. // Literal duplicated attributes would have been warned during the parse phase,
  18244. // however, it's possible to encounter duplicated `onXXX` handlers with different
  18245. // modifiers. We also need to merge static and dynamic class / style attributes.
  18246. // - onXXX handlers / style: merge into array
  18247. // - class: merge into single expression with concatenation
  18248. function dedupeProperties(properties) {
  18249. const knownProps = new Map();
  18250. const deduped = [];
  18251. for (let i = 0; i < properties.length; i++) {
  18252. const prop = properties[i];
  18253. // dynamic keys are always allowed
  18254. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  18255. deduped.push(prop);
  18256. continue;
  18257. }
  18258. const name = prop.key.content;
  18259. const existing = knownProps.get(name);
  18260. if (existing) {
  18261. if (name === 'style' || name === 'class' || name.startsWith('on')) {
  18262. mergeAsArray(existing, prop);
  18263. }
  18264. // unexpected duplicate, should have emitted error during parse
  18265. }
  18266. else {
  18267. knownProps.set(name, prop);
  18268. deduped.push(prop);
  18269. }
  18270. }
  18271. return deduped;
  18272. }
  18273. function mergeAsArray(existing, incoming) {
  18274. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  18275. existing.value.elements.push(incoming.value);
  18276. }
  18277. else {
  18278. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  18279. }
  18280. }
  18281. function buildDirectiveArgs(dir, context) {
  18282. const dirArgs = [];
  18283. const runtime = directiveImportMap.get(dir);
  18284. if (runtime) {
  18285. // built-in directive with runtime
  18286. dirArgs.push(context.helperString(runtime));
  18287. }
  18288. else {
  18289. // user directive.
  18290. // see if we have directives exposed via <script setup>
  18291. const fromSetup = resolveSetupReference(dir.name, context);
  18292. if (fromSetup) {
  18293. dirArgs.push(fromSetup);
  18294. }
  18295. else {
  18296. // inject statement for resolving directive
  18297. context.helper(RESOLVE_DIRECTIVE);
  18298. context.directives.add(dir.name);
  18299. dirArgs.push(toValidAssetId(dir.name, `directive`));
  18300. }
  18301. }
  18302. const { loc } = dir;
  18303. if (dir.exp)
  18304. dirArgs.push(dir.exp);
  18305. if (dir.arg) {
  18306. if (!dir.exp) {
  18307. dirArgs.push(`void 0`);
  18308. }
  18309. dirArgs.push(dir.arg);
  18310. }
  18311. if (Object.keys(dir.modifiers).length) {
  18312. if (!dir.arg) {
  18313. if (!dir.exp) {
  18314. dirArgs.push(`void 0`);
  18315. }
  18316. dirArgs.push(`void 0`);
  18317. }
  18318. const trueExpression = createSimpleExpression(`true`, false, loc);
  18319. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  18320. }
  18321. return createArrayExpression(dirArgs, dir.loc);
  18322. }
  18323. function stringifyDynamicPropNames(props) {
  18324. let propsNamesString = `[`;
  18325. for (let i = 0, l = props.length; i < l; i++) {
  18326. propsNamesString += JSON.stringify(props[i]);
  18327. if (i < l - 1)
  18328. propsNamesString += ', ';
  18329. }
  18330. return propsNamesString + `]`;
  18331. }
  18332. const transformSlotOutlet = (node, context) => {
  18333. if (isSlotOutlet(node)) {
  18334. const { children, loc } = node;
  18335. const { slotName, slotProps } = processSlotOutlet(node, context);
  18336. const slotArgs = [
  18337. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  18338. slotName
  18339. ];
  18340. if (slotProps) {
  18341. slotArgs.push(slotProps);
  18342. }
  18343. if (children.length) {
  18344. if (!slotProps) {
  18345. slotArgs.push(`{}`);
  18346. }
  18347. slotArgs.push(createFunctionExpression([], children, false, false, loc));
  18348. }
  18349. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  18350. }
  18351. };
  18352. function processSlotOutlet(node, context) {
  18353. let slotName = `"default"`;
  18354. let slotProps = undefined;
  18355. const nonNameProps = [];
  18356. for (let i = 0; i < node.props.length; i++) {
  18357. const p = node.props[i];
  18358. if (p.type === 6 /* ATTRIBUTE */) {
  18359. if (p.value) {
  18360. if (p.name === 'name') {
  18361. slotName = JSON.stringify(p.value.content);
  18362. }
  18363. else {
  18364. p.name = camelize(p.name);
  18365. nonNameProps.push(p);
  18366. }
  18367. }
  18368. }
  18369. else {
  18370. if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
  18371. if (p.exp)
  18372. slotName = p.exp;
  18373. }
  18374. else {
  18375. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  18376. p.arg.content = camelize(p.arg.content);
  18377. }
  18378. nonNameProps.push(p);
  18379. }
  18380. }
  18381. }
  18382. if (nonNameProps.length > 0) {
  18383. const { props, directives } = buildProps(node, context, nonNameProps);
  18384. slotProps = props;
  18385. if (directives.length) {
  18386. context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  18387. }
  18388. }
  18389. return {
  18390. slotName,
  18391. slotProps
  18392. };
  18393. }
  18394. const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
  18395. const transformOn = (dir, node, context, augmentor) => {
  18396. const { loc, modifiers, arg } = dir;
  18397. if (!dir.exp && !modifiers.length) {
  18398. context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
  18399. }
  18400. let eventName;
  18401. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  18402. if (arg.isStatic) {
  18403. const rawName = arg.content;
  18404. // for all event listeners, auto convert it to camelCase. See issue #2249
  18405. eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
  18406. }
  18407. else {
  18408. // #2388
  18409. eventName = createCompoundExpression([
  18410. `${context.helperString(TO_HANDLER_KEY)}(`,
  18411. arg,
  18412. `)`
  18413. ]);
  18414. }
  18415. }
  18416. else {
  18417. // already a compound expression.
  18418. eventName = arg;
  18419. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  18420. eventName.children.push(`)`);
  18421. }
  18422. // handler processing
  18423. let exp = dir.exp;
  18424. if (exp && !exp.content.trim()) {
  18425. exp = undefined;
  18426. }
  18427. let shouldCache = context.cacheHandlers && !exp;
  18428. if (exp) {
  18429. const isMemberExp = isMemberExpression(exp.content);
  18430. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  18431. const hasMultipleStatements = exp.content.includes(`;`);
  18432. // process the expression since it's been skipped
  18433. if (context.prefixIdentifiers) {
  18434. isInlineStatement && context.addIdentifiers(`$event`);
  18435. exp = dir.exp = processExpression(exp, context, false, hasMultipleStatements);
  18436. isInlineStatement && context.removeIdentifiers(`$event`);
  18437. // with scope analysis, the function is hoistable if it has no reference
  18438. // to scope variables.
  18439. shouldCache =
  18440. context.cacheHandlers &&
  18441. // runtime constants don't need to be cached
  18442. // (this is analyzed by compileScript in SFC <script setup>)
  18443. !(exp.type === 4 /* SIMPLE_EXPRESSION */ && exp.constType > 0) &&
  18444. // #1541 bail if this is a member exp handler passed to a component -
  18445. // we need to use the original function to preserve arity,
  18446. // e.g. <transition> relies on checking cb.length to determine
  18447. // transition end handling. Inline function is ok since its arity
  18448. // is preserved even when cached.
  18449. !(isMemberExp && node.tagType === 1 /* COMPONENT */) &&
  18450. // bail if the function references closure variables (v-for, v-slot)
  18451. // it must be passed fresh to avoid stale values.
  18452. !hasScopeRef(exp, context.identifiers);
  18453. // If the expression is optimizable and is a member expression pointing
  18454. // to a function, turn it into invocation (and wrap in an arrow function
  18455. // below) so that it always accesses the latest value when called - thus
  18456. // avoiding the need to be patched.
  18457. if (shouldCache && isMemberExp) {
  18458. if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  18459. exp.content = `${exp.content} && ${exp.content}(...args)`;
  18460. }
  18461. else {
  18462. exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
  18463. }
  18464. }
  18465. }
  18466. if (isInlineStatement || (shouldCache && isMemberExp)) {
  18467. // wrap inline statement in a function expression
  18468. exp = createCompoundExpression([
  18469. `${isInlineStatement
  18470. ? context.isTS
  18471. ? `($event: any)`
  18472. : `$event`
  18473. : `${context.isTS ? `\n//@ts-ignore\n` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  18474. exp,
  18475. hasMultipleStatements ? `}` : `)`
  18476. ]);
  18477. }
  18478. }
  18479. let ret = {
  18480. props: [
  18481. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  18482. ]
  18483. };
  18484. // apply extended compiler augmentor
  18485. if (augmentor) {
  18486. ret = augmentor(ret);
  18487. }
  18488. if (shouldCache) {
  18489. // cache handlers so that it's always the same handler being passed down.
  18490. // this avoids unnecessary re-renders when users use inline handlers on
  18491. // components.
  18492. ret.props[0].value = context.cache(ret.props[0].value);
  18493. }
  18494. return ret;
  18495. };
  18496. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  18497. // codegen for the entire props object. This transform here is only for v-bind
  18498. // *with* args.
  18499. const transformBind = (dir, node, context) => {
  18500. const { exp, modifiers, loc } = dir;
  18501. const arg = dir.arg;
  18502. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  18503. arg.children.unshift(`(`);
  18504. arg.children.push(`) || ""`);
  18505. }
  18506. else if (!arg.isStatic) {
  18507. arg.content = `${arg.content} || ""`;
  18508. }
  18509. // .prop is no longer necessary due to new patch behavior
  18510. // .sync is replaced by v-model:arg
  18511. if (modifiers.includes('camel')) {
  18512. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  18513. if (arg.isStatic) {
  18514. arg.content = camelize(arg.content);
  18515. }
  18516. else {
  18517. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  18518. }
  18519. }
  18520. else {
  18521. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  18522. arg.children.push(`)`);
  18523. }
  18524. }
  18525. if (!exp ||
  18526. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  18527. context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
  18528. return {
  18529. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  18530. };
  18531. }
  18532. return {
  18533. props: [createObjectProperty(arg, exp)]
  18534. };
  18535. };
  18536. // Merge adjacent text nodes and expressions into a single expression
  18537. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  18538. const transformText = (node, context) => {
  18539. if (node.type === 0 /* ROOT */ ||
  18540. node.type === 1 /* ELEMENT */ ||
  18541. node.type === 11 /* FOR */ ||
  18542. node.type === 10 /* IF_BRANCH */) {
  18543. // perform the transform on node exit so that all expressions have already
  18544. // been processed.
  18545. return () => {
  18546. const children = node.children;
  18547. let currentContainer = undefined;
  18548. let hasText = false;
  18549. for (let i = 0; i < children.length; i++) {
  18550. const child = children[i];
  18551. if (isText(child)) {
  18552. hasText = true;
  18553. for (let j = i + 1; j < children.length; j++) {
  18554. const next = children[j];
  18555. if (isText(next)) {
  18556. if (!currentContainer) {
  18557. currentContainer = children[i] = {
  18558. type: 8 /* COMPOUND_EXPRESSION */,
  18559. loc: child.loc,
  18560. children: [child]
  18561. };
  18562. }
  18563. // merge adjacent text node into current
  18564. currentContainer.children.push(` + `, next);
  18565. children.splice(j, 1);
  18566. j--;
  18567. }
  18568. else {
  18569. currentContainer = undefined;
  18570. break;
  18571. }
  18572. }
  18573. }
  18574. }
  18575. if (!hasText ||
  18576. // if this is a plain element with a single text child, leave it
  18577. // as-is since the runtime has dedicated fast path for this by directly
  18578. // setting textContent of the element.
  18579. // for component root it's always normalized anyway.
  18580. (children.length === 1 &&
  18581. (node.type === 0 /* ROOT */ ||
  18582. (node.type === 1 /* ELEMENT */ &&
  18583. node.tagType === 0 /* ELEMENT */)))) {
  18584. return;
  18585. }
  18586. // pre-convert text nodes into createTextVNode(text) calls to avoid
  18587. // runtime normalization.
  18588. for (let i = 0; i < children.length; i++) {
  18589. const child = children[i];
  18590. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  18591. const callArgs = [];
  18592. // createTextVNode defaults to single whitespace, so if it is a
  18593. // single space the code could be an empty call to save bytes.
  18594. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  18595. callArgs.push(child);
  18596. }
  18597. // mark dynamic text with flag so it gets patched inside a block
  18598. if (!context.ssr &&
  18599. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  18600. callArgs.push(1 /* TEXT */ +
  18601. (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
  18602. }
  18603. children[i] = {
  18604. type: 12 /* TEXT_CALL */,
  18605. content: child,
  18606. loc: child.loc,
  18607. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  18608. };
  18609. }
  18610. }
  18611. };
  18612. }
  18613. };
  18614. const seen = new WeakSet();
  18615. const transformOnce = (node, context) => {
  18616. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  18617. if (seen.has(node)) {
  18618. return;
  18619. }
  18620. seen.add(node);
  18621. context.helper(SET_BLOCK_TRACKING);
  18622. return () => {
  18623. const cur = context.currentNode;
  18624. if (cur.codegenNode) {
  18625. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  18626. }
  18627. };
  18628. }
  18629. };
  18630. const transformModel = (dir, node, context) => {
  18631. const { exp, arg } = dir;
  18632. if (!exp) {
  18633. context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  18634. return createTransformProps();
  18635. }
  18636. const rawExp = exp.loc.source;
  18637. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  18638. // im SFC <script setup> inline mode, the exp may have been transformed into
  18639. // _unref(exp)
  18640. const bindingType = context.bindingMetadata[rawExp];
  18641. const maybeRef = context.inline &&
  18642. bindingType &&
  18643. bindingType !== "setup-const" /* SETUP_CONST */;
  18644. if (!isMemberExpression(expString) && !maybeRef) {
  18645. context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  18646. return createTransformProps();
  18647. }
  18648. if (context.prefixIdentifiers &&
  18649. isSimpleIdentifier(expString) &&
  18650. context.identifiers[expString]) {
  18651. context.onError(createCompilerError(42 /* X_V_MODEL_ON_SCOPE_VARIABLE */, exp.loc));
  18652. return createTransformProps();
  18653. }
  18654. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  18655. const eventName = arg
  18656. ? isStaticExp(arg)
  18657. ? `onUpdate:${arg.content}`
  18658. : createCompoundExpression(['"onUpdate:" + ', arg])
  18659. : `onUpdate:modelValue`;
  18660. let assignmentExp;
  18661. const eventArg = context.isTS ? `($event: any)` : `$event`;
  18662. if (maybeRef) {
  18663. if (bindingType === "setup-ref" /* SETUP_REF */) {
  18664. // v-model used on known ref.
  18665. assignmentExp = createCompoundExpression([
  18666. `${eventArg} => (`,
  18667. createSimpleExpression(rawExp, false, exp.loc),
  18668. `.value = $event)`
  18669. ]);
  18670. }
  18671. else {
  18672. // v-model used on a potentially ref binding in <script setup> inline mode.
  18673. // the assignment needs to check whether the binding is actually a ref.
  18674. const altAssignment = bindingType === "setup-let" /* SETUP_LET */ ? `${rawExp} = $event` : `null`;
  18675. assignmentExp = createCompoundExpression([
  18676. `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? `,
  18677. createSimpleExpression(rawExp, false, exp.loc),
  18678. `.value = $event : ${altAssignment})`
  18679. ]);
  18680. }
  18681. }
  18682. else {
  18683. assignmentExp = createCompoundExpression([
  18684. `${eventArg} => (`,
  18685. exp,
  18686. ` = $event)`
  18687. ]);
  18688. }
  18689. const props = [
  18690. // modelValue: foo
  18691. createObjectProperty(propName, dir.exp),
  18692. // "onUpdate:modelValue": $event => (foo = $event)
  18693. createObjectProperty(eventName, assignmentExp)
  18694. ];
  18695. // cache v-model handler if applicable (when it doesn't refer any scope vars)
  18696. if (context.prefixIdentifiers &&
  18697. context.cacheHandlers &&
  18698. !hasScopeRef(exp, context.identifiers)) {
  18699. props[1].value = context.cache(props[1].value);
  18700. }
  18701. // modelModifiers: { foo: true, "bar-baz": true }
  18702. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  18703. const modifiers = dir.modifiers
  18704. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  18705. .join(`, `);
  18706. const modifiersKey = arg
  18707. ? isStaticExp(arg)
  18708. ? `${arg.content}Modifiers`
  18709. : createCompoundExpression([arg, ' + "Modifiers"'])
  18710. : `modelModifiers`;
  18711. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
  18712. }
  18713. return createTransformProps(props);
  18714. };
  18715. function createTransformProps(props = []) {
  18716. return { props };
  18717. }
  18718. function getBaseTransformPreset(prefixIdentifiers) {
  18719. return [
  18720. [
  18721. transformOnce,
  18722. transformIf,
  18723. transformFor,
  18724. ...(prefixIdentifiers
  18725. ? [
  18726. // order is important
  18727. trackVForSlotScopes,
  18728. transformExpression
  18729. ]
  18730. : []),
  18731. transformSlotOutlet,
  18732. transformElement,
  18733. trackSlotScopes,
  18734. transformText
  18735. ],
  18736. {
  18737. on: transformOn,
  18738. bind: transformBind,
  18739. model: transformModel
  18740. }
  18741. ];
  18742. }
  18743. // we name it `baseCompile` so that higher order compilers like
  18744. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  18745. function baseCompile(template, options = {}) {
  18746. const onError = options.onError || defaultOnError;
  18747. const isModuleMode = options.mode === 'module';
  18748. const prefixIdentifiers = (options.prefixIdentifiers === true || isModuleMode);
  18749. if (!prefixIdentifiers && options.cacheHandlers) {
  18750. onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  18751. }
  18752. if (options.scopeId && !isModuleMode) {
  18753. onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
  18754. }
  18755. const ast = isString(template) ? baseParse(template, options) : template;
  18756. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  18757. transform(ast, extend({}, options, {
  18758. prefixIdentifiers,
  18759. nodeTransforms: [
  18760. ...nodeTransforms,
  18761. ...(options.nodeTransforms || []) // user transforms
  18762. ],
  18763. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  18764. )
  18765. }));
  18766. return generate(ast, extend({}, options, {
  18767. prefixIdentifiers
  18768. }));
  18769. }
  18770. const noopDirectiveTransform = () => ({ props: [] });
  18771. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  18772. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  18773. const V_MODEL_TEXT = Symbol(`vModelText` );
  18774. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  18775. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  18776. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  18777. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  18778. const V_SHOW = Symbol(`vShow` );
  18779. const TRANSITION = Symbol(`Transition` );
  18780. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  18781. registerRuntimeHelpers({
  18782. [V_MODEL_RADIO]: `vModelRadio`,
  18783. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  18784. [V_MODEL_TEXT]: `vModelText`,
  18785. [V_MODEL_SELECT]: `vModelSelect`,
  18786. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  18787. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  18788. [V_ON_WITH_KEYS]: `withKeys`,
  18789. [V_SHOW]: `vShow`,
  18790. [TRANSITION]: `Transition`,
  18791. [TRANSITION_GROUP]: `TransitionGroup`
  18792. });
  18793. var namedCharacterReferences = {
  18794. GT: ">",
  18795. gt: ">",
  18796. LT: "<",
  18797. lt: "<",
  18798. "ac;": "∾",
  18799. "af;": "⁡",
  18800. AMP: "&",
  18801. amp: "&",
  18802. "ap;": "≈",
  18803. "DD;": "ⅅ",
  18804. "dd;": "ⅆ",
  18805. deg: "°",
  18806. "ee;": "ⅇ",
  18807. "eg;": "⪚",
  18808. "el;": "⪙",
  18809. ETH: "Ð",
  18810. eth: "ð",
  18811. "gE;": "≧",
  18812. "ge;": "≥",
  18813. "Gg;": "⋙",
  18814. "gg;": "≫",
  18815. "gl;": "≷",
  18816. "GT;": ">",
  18817. "Gt;": "≫",
  18818. "gt;": ">",
  18819. "ic;": "⁣",
  18820. "ii;": "ⅈ",
  18821. "Im;": "ℑ",
  18822. "in;": "∈",
  18823. "it;": "⁢",
  18824. "lE;": "≦",
  18825. "le;": "≤",
  18826. "lg;": "≶",
  18827. "Ll;": "⋘",
  18828. "ll;": "≪",
  18829. "LT;": "<",
  18830. "Lt;": "≪",
  18831. "lt;": "<",
  18832. "mp;": "∓",
  18833. "Mu;": "Μ",
  18834. "mu;": "μ",
  18835. "ne;": "≠",
  18836. "ni;": "∋",
  18837. not: "¬",
  18838. "Nu;": "Ν",
  18839. "nu;": "ν",
  18840. "Or;": "⩔",
  18841. "or;": "∨",
  18842. "oS;": "Ⓢ",
  18843. "Pi;": "Π",
  18844. "pi;": "π",
  18845. "pm;": "±",
  18846. "Pr;": "⪻",
  18847. "pr;": "≺",
  18848. "Re;": "ℜ",
  18849. REG: "®",
  18850. reg: "®",
  18851. "rx;": "℞",
  18852. "Sc;": "⪼",
  18853. "sc;": "≻",
  18854. shy: "­",
  18855. uml: "¨",
  18856. "wp;": "℘",
  18857. "wr;": "≀",
  18858. "Xi;": "Ξ",
  18859. "xi;": "ξ",
  18860. yen: "¥",
  18861. "acd;": "∿",
  18862. "acE;": "∾̳",
  18863. "Acy;": "А",
  18864. "acy;": "а",
  18865. "Afr;": "𝔄",
  18866. "afr;": "𝔞",
  18867. "AMP;": "&",
  18868. "amp;": "&",
  18869. "And;": "⩓",
  18870. "and;": "∧",
  18871. "ang;": "∠",
  18872. "apE;": "⩰",
  18873. "ape;": "≊",
  18874. "ast;": "*",
  18875. Auml: "Ä",
  18876. auml: "ä",
  18877. "Bcy;": "Б",
  18878. "bcy;": "б",
  18879. "Bfr;": "𝔅",
  18880. "bfr;": "𝔟",
  18881. "bne;": "=⃥",
  18882. "bot;": "⊥",
  18883. "Cap;": "⋒",
  18884. "cap;": "∩",
  18885. cent: "¢",
  18886. "Cfr;": "ℭ",
  18887. "cfr;": "𝔠",
  18888. "Chi;": "Χ",
  18889. "chi;": "χ",
  18890. "cir;": "○",
  18891. COPY: "©",
  18892. copy: "©",
  18893. "Cup;": "⋓",
  18894. "cup;": "∪",
  18895. "Dcy;": "Д",
  18896. "dcy;": "д",
  18897. "deg;": "°",
  18898. "Del;": "∇",
  18899. "Dfr;": "𝔇",
  18900. "dfr;": "𝔡",
  18901. "die;": "¨",
  18902. "div;": "÷",
  18903. "Dot;": "¨",
  18904. "dot;": "˙",
  18905. "Ecy;": "Э",
  18906. "ecy;": "э",
  18907. "Efr;": "𝔈",
  18908. "efr;": "𝔢",
  18909. "egs;": "⪖",
  18910. "ell;": "ℓ",
  18911. "els;": "⪕",
  18912. "ENG;": "Ŋ",
  18913. "eng;": "ŋ",
  18914. "Eta;": "Η",
  18915. "eta;": "η",
  18916. "ETH;": "Ð",
  18917. "eth;": "ð",
  18918. Euml: "Ë",
  18919. euml: "ë",
  18920. "Fcy;": "Ф",
  18921. "fcy;": "ф",
  18922. "Ffr;": "𝔉",
  18923. "ffr;": "𝔣",
  18924. "gap;": "⪆",
  18925. "Gcy;": "Г",
  18926. "gcy;": "г",
  18927. "gEl;": "⪌",
  18928. "gel;": "⋛",
  18929. "geq;": "≥",
  18930. "ges;": "⩾",
  18931. "Gfr;": "𝔊",
  18932. "gfr;": "𝔤",
  18933. "ggg;": "⋙",
  18934. "gla;": "⪥",
  18935. "glE;": "⪒",
  18936. "glj;": "⪤",
  18937. "gnE;": "≩",
  18938. "gne;": "⪈",
  18939. "Hat;": "^",
  18940. "Hfr;": "ℌ",
  18941. "hfr;": "𝔥",
  18942. "Icy;": "И",
  18943. "icy;": "и",
  18944. "iff;": "⇔",
  18945. "Ifr;": "ℑ",
  18946. "ifr;": "𝔦",
  18947. "Int;": "∬",
  18948. "int;": "∫",
  18949. Iuml: "Ï",
  18950. iuml: "ï",
  18951. "Jcy;": "Й",
  18952. "jcy;": "й",
  18953. "Jfr;": "𝔍",
  18954. "jfr;": "𝔧",
  18955. "Kcy;": "К",
  18956. "kcy;": "к",
  18957. "Kfr;": "𝔎",
  18958. "kfr;": "𝔨",
  18959. "lap;": "⪅",
  18960. "lat;": "⪫",
  18961. "Lcy;": "Л",
  18962. "lcy;": "л",
  18963. "lEg;": "⪋",
  18964. "leg;": "⋚",
  18965. "leq;": "≤",
  18966. "les;": "⩽",
  18967. "Lfr;": "𝔏",
  18968. "lfr;": "𝔩",
  18969. "lgE;": "⪑",
  18970. "lnE;": "≨",
  18971. "lne;": "⪇",
  18972. "loz;": "◊",
  18973. "lrm;": "‎",
  18974. "Lsh;": "↰",
  18975. "lsh;": "↰",
  18976. macr: "¯",
  18977. "Map;": "⤅",
  18978. "map;": "↦",
  18979. "Mcy;": "М",
  18980. "mcy;": "м",
  18981. "Mfr;": "𝔐",
  18982. "mfr;": "𝔪",
  18983. "mho;": "℧",
  18984. "mid;": "∣",
  18985. "nap;": "≉",
  18986. nbsp: " ",
  18987. "Ncy;": "Н",
  18988. "ncy;": "н",
  18989. "Nfr;": "𝔑",
  18990. "nfr;": "𝔫",
  18991. "ngE;": "≧̸",
  18992. "nge;": "≱",
  18993. "nGg;": "⋙̸",
  18994. "nGt;": "≫⃒",
  18995. "ngt;": "≯",
  18996. "nis;": "⋼",
  18997. "niv;": "∋",
  18998. "nlE;": "≦̸",
  18999. "nle;": "≰",
  19000. "nLl;": "⋘̸",
  19001. "nLt;": "≪⃒",
  19002. "nlt;": "≮",
  19003. "Not;": "⫬",
  19004. "not;": "¬",
  19005. "npr;": "⊀",
  19006. "nsc;": "⊁",
  19007. "num;": "#",
  19008. "Ocy;": "О",
  19009. "ocy;": "о",
  19010. "Ofr;": "𝔒",
  19011. "ofr;": "𝔬",
  19012. "ogt;": "⧁",
  19013. "ohm;": "Ω",
  19014. "olt;": "⧀",
  19015. "ord;": "⩝",
  19016. ordf: "ª",
  19017. ordm: "º",
  19018. "orv;": "⩛",
  19019. Ouml: "Ö",
  19020. ouml: "ö",
  19021. "par;": "∥",
  19022. para: "¶",
  19023. "Pcy;": "П",
  19024. "pcy;": "п",
  19025. "Pfr;": "𝔓",
  19026. "pfr;": "𝔭",
  19027. "Phi;": "Φ",
  19028. "phi;": "φ",
  19029. "piv;": "ϖ",
  19030. "prE;": "⪳",
  19031. "pre;": "⪯",
  19032. "Psi;": "Ψ",
  19033. "psi;": "ψ",
  19034. "Qfr;": "𝔔",
  19035. "qfr;": "𝔮",
  19036. QUOT: "\"",
  19037. quot: "\"",
  19038. "Rcy;": "Р",
  19039. "rcy;": "р",
  19040. "REG;": "®",
  19041. "reg;": "®",
  19042. "Rfr;": "ℜ",
  19043. "rfr;": "𝔯",
  19044. "Rho;": "Ρ",
  19045. "rho;": "ρ",
  19046. "rlm;": "‏",
  19047. "Rsh;": "↱",
  19048. "rsh;": "↱",
  19049. "scE;": "⪴",
  19050. "sce;": "⪰",
  19051. "Scy;": "С",
  19052. "scy;": "с",
  19053. sect: "§",
  19054. "Sfr;": "𝔖",
  19055. "sfr;": "𝔰",
  19056. "shy;": "­",
  19057. "sim;": "∼",
  19058. "smt;": "⪪",
  19059. "sol;": "/",
  19060. "squ;": "□",
  19061. "Sub;": "⋐",
  19062. "sub;": "⊂",
  19063. "Sum;": "∑",
  19064. "sum;": "∑",
  19065. "Sup;": "⋑",
  19066. "sup;": "⊃",
  19067. sup1: "¹",
  19068. sup2: "²",
  19069. sup3: "³",
  19070. "Tab;": "\t",
  19071. "Tau;": "Τ",
  19072. "tau;": "τ",
  19073. "Tcy;": "Т",
  19074. "tcy;": "т",
  19075. "Tfr;": "𝔗",
  19076. "tfr;": "𝔱",
  19077. "top;": "⊤",
  19078. "Ucy;": "У",
  19079. "ucy;": "у",
  19080. "Ufr;": "𝔘",
  19081. "ufr;": "𝔲",
  19082. "uml;": "¨",
  19083. Uuml: "Ü",
  19084. uuml: "ü",
  19085. "Vcy;": "В",
  19086. "vcy;": "в",
  19087. "Vee;": "⋁",
  19088. "vee;": "∨",
  19089. "Vfr;": "𝔙",
  19090. "vfr;": "𝔳",
  19091. "Wfr;": "𝔚",
  19092. "wfr;": "𝔴",
  19093. "Xfr;": "𝔛",
  19094. "xfr;": "𝔵",
  19095. "Ycy;": "Ы",
  19096. "ycy;": "ы",
  19097. "yen;": "¥",
  19098. "Yfr;": "𝔜",
  19099. "yfr;": "𝔶",
  19100. yuml: "ÿ",
  19101. "Zcy;": "З",
  19102. "zcy;": "з",
  19103. "Zfr;": "ℨ",
  19104. "zfr;": "𝔷",
  19105. "zwj;": "‍",
  19106. Acirc: "Â",
  19107. acirc: "â",
  19108. acute: "´",
  19109. AElig: "Æ",
  19110. aelig: "æ",
  19111. "andd;": "⩜",
  19112. "andv;": "⩚",
  19113. "ange;": "⦤",
  19114. "Aopf;": "𝔸",
  19115. "aopf;": "𝕒",
  19116. "apid;": "≋",
  19117. "apos;": "'",
  19118. Aring: "Å",
  19119. aring: "å",
  19120. "Ascr;": "𝒜",
  19121. "ascr;": "𝒶",
  19122. "Auml;": "Ä",
  19123. "auml;": "ä",
  19124. "Barv;": "⫧",
  19125. "bbrk;": "⎵",
  19126. "Beta;": "Β",
  19127. "beta;": "β",
  19128. "beth;": "ℶ",
  19129. "bNot;": "⫭",
  19130. "bnot;": "⌐",
  19131. "Bopf;": "𝔹",
  19132. "bopf;": "𝕓",
  19133. "boxH;": "═",
  19134. "boxh;": "─",
  19135. "boxV;": "║",
  19136. "boxv;": "│",
  19137. "Bscr;": "ℬ",
  19138. "bscr;": "𝒷",
  19139. "bsim;": "∽",
  19140. "bsol;": "\\",
  19141. "bull;": "•",
  19142. "bump;": "≎",
  19143. "caps;": "∩︀",
  19144. "Cdot;": "Ċ",
  19145. "cdot;": "ċ",
  19146. cedil: "¸",
  19147. "cent;": "¢",
  19148. "CHcy;": "Ч",
  19149. "chcy;": "ч",
  19150. "circ;": "ˆ",
  19151. "cirE;": "⧃",
  19152. "cire;": "≗",
  19153. "comp;": "∁",
  19154. "cong;": "≅",
  19155. "Copf;": "ℂ",
  19156. "copf;": "𝕔",
  19157. "COPY;": "©",
  19158. "copy;": "©",
  19159. "Cscr;": "𝒞",
  19160. "cscr;": "𝒸",
  19161. "csub;": "⫏",
  19162. "csup;": "⫐",
  19163. "cups;": "∪︀",
  19164. "Darr;": "↡",
  19165. "dArr;": "⇓",
  19166. "darr;": "↓",
  19167. "dash;": "‐",
  19168. "dHar;": "⥥",
  19169. "diam;": "⋄",
  19170. "DJcy;": "Ђ",
  19171. "djcy;": "ђ",
  19172. "Dopf;": "𝔻",
  19173. "dopf;": "𝕕",
  19174. "Dscr;": "𝒟",
  19175. "dscr;": "𝒹",
  19176. "DScy;": "Ѕ",
  19177. "dscy;": "ѕ",
  19178. "dsol;": "⧶",
  19179. "dtri;": "▿",
  19180. "DZcy;": "Џ",
  19181. "dzcy;": "џ",
  19182. "ecir;": "≖",
  19183. Ecirc: "Ê",
  19184. ecirc: "ê",
  19185. "Edot;": "Ė",
  19186. "eDot;": "≑",
  19187. "edot;": "ė",
  19188. "emsp;": " ",
  19189. "ensp;": " ",
  19190. "Eopf;": "𝔼",
  19191. "eopf;": "𝕖",
  19192. "epar;": "⋕",
  19193. "epsi;": "ε",
  19194. "Escr;": "ℰ",
  19195. "escr;": "ℯ",
  19196. "Esim;": "⩳",
  19197. "esim;": "≂",
  19198. "Euml;": "Ë",
  19199. "euml;": "ë",
  19200. "euro;": "€",
  19201. "excl;": "!",
  19202. "flat;": "♭",
  19203. "fnof;": "ƒ",
  19204. "Fopf;": "𝔽",
  19205. "fopf;": "𝕗",
  19206. "fork;": "⋔",
  19207. "Fscr;": "ℱ",
  19208. "fscr;": "𝒻",
  19209. "Gdot;": "Ġ",
  19210. "gdot;": "ġ",
  19211. "geqq;": "≧",
  19212. "gesl;": "⋛︀",
  19213. "GJcy;": "Ѓ",
  19214. "gjcy;": "ѓ",
  19215. "gnap;": "⪊",
  19216. "gneq;": "⪈",
  19217. "Gopf;": "𝔾",
  19218. "gopf;": "𝕘",
  19219. "Gscr;": "𝒢",
  19220. "gscr;": "ℊ",
  19221. "gsim;": "≳",
  19222. "gtcc;": "⪧",
  19223. "gvnE;": "≩︀",
  19224. "half;": "½",
  19225. "hArr;": "⇔",
  19226. "harr;": "↔",
  19227. "hbar;": "ℏ",
  19228. "Hopf;": "ℍ",
  19229. "hopf;": "𝕙",
  19230. "Hscr;": "ℋ",
  19231. "hscr;": "𝒽",
  19232. Icirc: "Î",
  19233. icirc: "î",
  19234. "Idot;": "İ",
  19235. "IEcy;": "Е",
  19236. "iecy;": "е",
  19237. iexcl: "¡",
  19238. "imof;": "⊷",
  19239. "IOcy;": "Ё",
  19240. "iocy;": "ё",
  19241. "Iopf;": "𝕀",
  19242. "iopf;": "𝕚",
  19243. "Iota;": "Ι",
  19244. "iota;": "ι",
  19245. "Iscr;": "ℐ",
  19246. "iscr;": "𝒾",
  19247. "isin;": "∈",
  19248. "Iuml;": "Ï",
  19249. "iuml;": "ï",
  19250. "Jopf;": "𝕁",
  19251. "jopf;": "𝕛",
  19252. "Jscr;": "𝒥",
  19253. "jscr;": "𝒿",
  19254. "KHcy;": "Х",
  19255. "khcy;": "х",
  19256. "KJcy;": "Ќ",
  19257. "kjcy;": "ќ",
  19258. "Kopf;": "𝕂",
  19259. "kopf;": "𝕜",
  19260. "Kscr;": "𝒦",
  19261. "kscr;": "𝓀",
  19262. "Lang;": "⟪",
  19263. "lang;": "⟨",
  19264. laquo: "«",
  19265. "Larr;": "↞",
  19266. "lArr;": "⇐",
  19267. "larr;": "←",
  19268. "late;": "⪭",
  19269. "lcub;": "{",
  19270. "ldca;": "⤶",
  19271. "ldsh;": "↲",
  19272. "leqq;": "≦",
  19273. "lesg;": "⋚︀",
  19274. "lHar;": "⥢",
  19275. "LJcy;": "Љ",
  19276. "ljcy;": "љ",
  19277. "lnap;": "⪉",
  19278. "lneq;": "⪇",
  19279. "Lopf;": "𝕃",
  19280. "lopf;": "𝕝",
  19281. "lozf;": "⧫",
  19282. "lpar;": "(",
  19283. "Lscr;": "ℒ",
  19284. "lscr;": "𝓁",
  19285. "lsim;": "≲",
  19286. "lsqb;": "[",
  19287. "ltcc;": "⪦",
  19288. "ltri;": "◃",
  19289. "lvnE;": "≨︀",
  19290. "macr;": "¯",
  19291. "male;": "♂",
  19292. "malt;": "✠",
  19293. micro: "µ",
  19294. "mlcp;": "⫛",
  19295. "mldr;": "…",
  19296. "Mopf;": "𝕄",
  19297. "mopf;": "𝕞",
  19298. "Mscr;": "ℳ",
  19299. "mscr;": "𝓂",
  19300. "nang;": "∠⃒",
  19301. "napE;": "⩰̸",
  19302. "nbsp;": " ",
  19303. "ncap;": "⩃",
  19304. "ncup;": "⩂",
  19305. "ngeq;": "≱",
  19306. "nges;": "⩾̸",
  19307. "ngtr;": "≯",
  19308. "nGtv;": "≫̸",
  19309. "nisd;": "⋺",
  19310. "NJcy;": "Њ",
  19311. "njcy;": "њ",
  19312. "nldr;": "‥",
  19313. "nleq;": "≰",
  19314. "nles;": "⩽̸",
  19315. "nLtv;": "≪̸",
  19316. "nmid;": "∤",
  19317. "Nopf;": "ℕ",
  19318. "nopf;": "𝕟",
  19319. "npar;": "∦",
  19320. "npre;": "⪯̸",
  19321. "nsce;": "⪰̸",
  19322. "Nscr;": "𝒩",
  19323. "nscr;": "𝓃",
  19324. "nsim;": "≁",
  19325. "nsub;": "⊄",
  19326. "nsup;": "⊅",
  19327. "ntgl;": "≹",
  19328. "ntlg;": "≸",
  19329. "nvap;": "≍⃒",
  19330. "nvge;": "≥⃒",
  19331. "nvgt;": ">⃒",
  19332. "nvle;": "≤⃒",
  19333. "nvlt;": "<⃒",
  19334. "oast;": "⊛",
  19335. "ocir;": "⊚",
  19336. Ocirc: "Ô",
  19337. ocirc: "ô",
  19338. "odiv;": "⨸",
  19339. "odot;": "⊙",
  19340. "ogon;": "˛",
  19341. "oint;": "∮",
  19342. "omid;": "⦶",
  19343. "Oopf;": "𝕆",
  19344. "oopf;": "𝕠",
  19345. "opar;": "⦷",
  19346. "ordf;": "ª",
  19347. "ordm;": "º",
  19348. "oror;": "⩖",
  19349. "Oscr;": "𝒪",
  19350. "oscr;": "ℴ",
  19351. "osol;": "⊘",
  19352. "Ouml;": "Ö",
  19353. "ouml;": "ö",
  19354. "para;": "¶",
  19355. "part;": "∂",
  19356. "perp;": "⊥",
  19357. "phiv;": "ϕ",
  19358. "plus;": "+",
  19359. "Popf;": "ℙ",
  19360. "popf;": "𝕡",
  19361. pound: "£",
  19362. "prap;": "⪷",
  19363. "prec;": "≺",
  19364. "prnE;": "⪵",
  19365. "prod;": "∏",
  19366. "prop;": "∝",
  19367. "Pscr;": "𝒫",
  19368. "pscr;": "𝓅",
  19369. "qint;": "⨌",
  19370. "Qopf;": "ℚ",
  19371. "qopf;": "𝕢",
  19372. "Qscr;": "𝒬",
  19373. "qscr;": "𝓆",
  19374. "QUOT;": "\"",
  19375. "quot;": "\"",
  19376. "race;": "∽̱",
  19377. "Rang;": "⟫",
  19378. "rang;": "⟩",
  19379. raquo: "»",
  19380. "Rarr;": "↠",
  19381. "rArr;": "⇒",
  19382. "rarr;": "→",
  19383. "rcub;": "}",
  19384. "rdca;": "⤷",
  19385. "rdsh;": "↳",
  19386. "real;": "ℜ",
  19387. "rect;": "▭",
  19388. "rHar;": "⥤",
  19389. "rhov;": "ϱ",
  19390. "ring;": "˚",
  19391. "Ropf;": "ℝ",
  19392. "ropf;": "𝕣",
  19393. "rpar;": ")",
  19394. "Rscr;": "ℛ",
  19395. "rscr;": "𝓇",
  19396. "rsqb;": "]",
  19397. "rtri;": "▹",
  19398. "scap;": "⪸",
  19399. "scnE;": "⪶",
  19400. "sdot;": "⋅",
  19401. "sect;": "§",
  19402. "semi;": ";",
  19403. "sext;": "✶",
  19404. "SHcy;": "Ш",
  19405. "shcy;": "ш",
  19406. "sime;": "≃",
  19407. "simg;": "⪞",
  19408. "siml;": "⪝",
  19409. "smid;": "∣",
  19410. "smte;": "⪬",
  19411. "solb;": "⧄",
  19412. "Sopf;": "𝕊",
  19413. "sopf;": "𝕤",
  19414. "spar;": "∥",
  19415. "Sqrt;": "√",
  19416. "squf;": "▪",
  19417. "Sscr;": "𝒮",
  19418. "sscr;": "𝓈",
  19419. "Star;": "⋆",
  19420. "star;": "☆",
  19421. "subE;": "⫅",
  19422. "sube;": "⊆",
  19423. "succ;": "≻",
  19424. "sung;": "♪",
  19425. "sup1;": "¹",
  19426. "sup2;": "²",
  19427. "sup3;": "³",
  19428. "supE;": "⫆",
  19429. "supe;": "⊇",
  19430. szlig: "ß",
  19431. "tbrk;": "⎴",
  19432. "tdot;": "⃛",
  19433. THORN: "Þ",
  19434. thorn: "þ",
  19435. times: "×",
  19436. "tint;": "∭",
  19437. "toea;": "⤨",
  19438. "Topf;": "𝕋",
  19439. "topf;": "𝕥",
  19440. "tosa;": "⤩",
  19441. "trie;": "≜",
  19442. "Tscr;": "𝒯",
  19443. "tscr;": "𝓉",
  19444. "TScy;": "Ц",
  19445. "tscy;": "ц",
  19446. "Uarr;": "↟",
  19447. "uArr;": "⇑",
  19448. "uarr;": "↑",
  19449. Ucirc: "Û",
  19450. ucirc: "û",
  19451. "uHar;": "⥣",
  19452. "Uopf;": "𝕌",
  19453. "uopf;": "𝕦",
  19454. "Upsi;": "ϒ",
  19455. "upsi;": "υ",
  19456. "Uscr;": "𝒰",
  19457. "uscr;": "𝓊",
  19458. "utri;": "▵",
  19459. "Uuml;": "Ü",
  19460. "uuml;": "ü",
  19461. "vArr;": "⇕",
  19462. "varr;": "↕",
  19463. "Vbar;": "⫫",
  19464. "vBar;": "⫨",
  19465. "Vert;": "‖",
  19466. "vert;": "|",
  19467. "Vopf;": "𝕍",
  19468. "vopf;": "𝕧",
  19469. "Vscr;": "𝒱",
  19470. "vscr;": "𝓋",
  19471. "Wopf;": "𝕎",
  19472. "wopf;": "𝕨",
  19473. "Wscr;": "𝒲",
  19474. "wscr;": "𝓌",
  19475. "xcap;": "⋂",
  19476. "xcup;": "⋃",
  19477. "xmap;": "⟼",
  19478. "xnis;": "⋻",
  19479. "Xopf;": "𝕏",
  19480. "xopf;": "𝕩",
  19481. "Xscr;": "𝒳",
  19482. "xscr;": "𝓍",
  19483. "xvee;": "⋁",
  19484. "YAcy;": "Я",
  19485. "yacy;": "я",
  19486. "YIcy;": "Ї",
  19487. "yicy;": "ї",
  19488. "Yopf;": "𝕐",
  19489. "yopf;": "𝕪",
  19490. "Yscr;": "𝒴",
  19491. "yscr;": "𝓎",
  19492. "YUcy;": "Ю",
  19493. "yucy;": "ю",
  19494. "Yuml;": "Ÿ",
  19495. "yuml;": "ÿ",
  19496. "Zdot;": "Ż",
  19497. "zdot;": "ż",
  19498. "Zeta;": "Ζ",
  19499. "zeta;": "ζ",
  19500. "ZHcy;": "Ж",
  19501. "zhcy;": "ж",
  19502. "Zopf;": "ℤ",
  19503. "zopf;": "𝕫",
  19504. "Zscr;": "𝒵",
  19505. "zscr;": "𝓏",
  19506. "zwnj;": "‌",
  19507. Aacute: "Á",
  19508. aacute: "á",
  19509. "Acirc;": "Â",
  19510. "acirc;": "â",
  19511. "acute;": "´",
  19512. "AElig;": "Æ",
  19513. "aelig;": "æ",
  19514. Agrave: "À",
  19515. agrave: "à",
  19516. "aleph;": "ℵ",
  19517. "Alpha;": "Α",
  19518. "alpha;": "α",
  19519. "Amacr;": "Ā",
  19520. "amacr;": "ā",
  19521. "amalg;": "⨿",
  19522. "angle;": "∠",
  19523. "angrt;": "∟",
  19524. "angst;": "Å",
  19525. "Aogon;": "Ą",
  19526. "aogon;": "ą",
  19527. "Aring;": "Å",
  19528. "aring;": "å",
  19529. "asymp;": "≈",
  19530. Atilde: "Ã",
  19531. atilde: "ã",
  19532. "awint;": "⨑",
  19533. "bcong;": "≌",
  19534. "bdquo;": "„",
  19535. "bepsi;": "϶",
  19536. "blank;": "␣",
  19537. "blk12;": "▒",
  19538. "blk14;": "░",
  19539. "blk34;": "▓",
  19540. "block;": "█",
  19541. "boxDL;": "╗",
  19542. "boxDl;": "╖",
  19543. "boxdL;": "╕",
  19544. "boxdl;": "┐",
  19545. "boxDR;": "╔",
  19546. "boxDr;": "╓",
  19547. "boxdR;": "╒",
  19548. "boxdr;": "┌",
  19549. "boxHD;": "╦",
  19550. "boxHd;": "╤",
  19551. "boxhD;": "╥",
  19552. "boxhd;": "┬",
  19553. "boxHU;": "╩",
  19554. "boxHu;": "╧",
  19555. "boxhU;": "╨",
  19556. "boxhu;": "┴",
  19557. "boxUL;": "╝",
  19558. "boxUl;": "╜",
  19559. "boxuL;": "╛",
  19560. "boxul;": "┘",
  19561. "boxUR;": "╚",
  19562. "boxUr;": "╙",
  19563. "boxuR;": "╘",
  19564. "boxur;": "└",
  19565. "boxVH;": "╬",
  19566. "boxVh;": "╫",
  19567. "boxvH;": "╪",
  19568. "boxvh;": "┼",
  19569. "boxVL;": "╣",
  19570. "boxVl;": "╢",
  19571. "boxvL;": "╡",
  19572. "boxvl;": "┤",
  19573. "boxVR;": "╠",
  19574. "boxVr;": "╟",
  19575. "boxvR;": "╞",
  19576. "boxvr;": "├",
  19577. "Breve;": "˘",
  19578. "breve;": "˘",
  19579. brvbar: "¦",
  19580. "bsemi;": "⁏",
  19581. "bsime;": "⋍",
  19582. "bsolb;": "⧅",
  19583. "bumpE;": "⪮",
  19584. "bumpe;": "≏",
  19585. "caret;": "⁁",
  19586. "caron;": "ˇ",
  19587. "ccaps;": "⩍",
  19588. Ccedil: "Ç",
  19589. ccedil: "ç",
  19590. "Ccirc;": "Ĉ",
  19591. "ccirc;": "ĉ",
  19592. "ccups;": "⩌",
  19593. "cedil;": "¸",
  19594. "check;": "✓",
  19595. "clubs;": "♣",
  19596. "Colon;": "∷",
  19597. "colon;": ":",
  19598. "comma;": ",",
  19599. "crarr;": "↵",
  19600. "Cross;": "⨯",
  19601. "cross;": "✗",
  19602. "csube;": "⫑",
  19603. "csupe;": "⫒",
  19604. "ctdot;": "⋯",
  19605. "cuepr;": "⋞",
  19606. "cuesc;": "⋟",
  19607. "cupor;": "⩅",
  19608. curren: "¤",
  19609. "cuvee;": "⋎",
  19610. "cuwed;": "⋏",
  19611. "cwint;": "∱",
  19612. "Dashv;": "⫤",
  19613. "dashv;": "⊣",
  19614. "dblac;": "˝",
  19615. "ddarr;": "⇊",
  19616. "Delta;": "Δ",
  19617. "delta;": "δ",
  19618. "dharl;": "⇃",
  19619. "dharr;": "⇂",
  19620. "diams;": "♦",
  19621. "disin;": "⋲",
  19622. divide: "÷",
  19623. "doteq;": "≐",
  19624. "dtdot;": "⋱",
  19625. "dtrif;": "▾",
  19626. "duarr;": "⇵",
  19627. "duhar;": "⥯",
  19628. Eacute: "É",
  19629. eacute: "é",
  19630. "Ecirc;": "Ê",
  19631. "ecirc;": "ê",
  19632. "eDDot;": "⩷",
  19633. "efDot;": "≒",
  19634. Egrave: "È",
  19635. egrave: "è",
  19636. "Emacr;": "Ē",
  19637. "emacr;": "ē",
  19638. "empty;": "∅",
  19639. "Eogon;": "Ę",
  19640. "eogon;": "ę",
  19641. "eplus;": "⩱",
  19642. "epsiv;": "ϵ",
  19643. "eqsim;": "≂",
  19644. "Equal;": "⩵",
  19645. "equiv;": "≡",
  19646. "erarr;": "⥱",
  19647. "erDot;": "≓",
  19648. "esdot;": "≐",
  19649. "exist;": "∃",
  19650. "fflig;": "ff",
  19651. "filig;": "fi",
  19652. "fjlig;": "fj",
  19653. "fllig;": "fl",
  19654. "fltns;": "▱",
  19655. "forkv;": "⫙",
  19656. frac12: "½",
  19657. frac14: "¼",
  19658. frac34: "¾",
  19659. "frasl;": "⁄",
  19660. "frown;": "⌢",
  19661. "Gamma;": "Γ",
  19662. "gamma;": "γ",
  19663. "Gcirc;": "Ĝ",
  19664. "gcirc;": "ĝ",
  19665. "gescc;": "⪩",
  19666. "gimel;": "ℷ",
  19667. "gneqq;": "≩",
  19668. "gnsim;": "⋧",
  19669. "grave;": "`",
  19670. "gsime;": "⪎",
  19671. "gsiml;": "⪐",
  19672. "gtcir;": "⩺",
  19673. "gtdot;": "⋗",
  19674. "Hacek;": "ˇ",
  19675. "harrw;": "↭",
  19676. "Hcirc;": "Ĥ",
  19677. "hcirc;": "ĥ",
  19678. "hoarr;": "⇿",
  19679. Iacute: "Í",
  19680. iacute: "í",
  19681. "Icirc;": "Î",
  19682. "icirc;": "î",
  19683. "iexcl;": "¡",
  19684. Igrave: "Ì",
  19685. igrave: "ì",
  19686. "iiint;": "∭",
  19687. "iiota;": "℩",
  19688. "IJlig;": "IJ",
  19689. "ijlig;": "ij",
  19690. "Imacr;": "Ī",
  19691. "imacr;": "ī",
  19692. "image;": "ℑ",
  19693. "imath;": "ı",
  19694. "imped;": "Ƶ",
  19695. "infin;": "∞",
  19696. "Iogon;": "Į",
  19697. "iogon;": "į",
  19698. "iprod;": "⨼",
  19699. iquest: "¿",
  19700. "isinE;": "⋹",
  19701. "isins;": "⋴",
  19702. "isinv;": "∈",
  19703. "Iukcy;": "І",
  19704. "iukcy;": "і",
  19705. "Jcirc;": "Ĵ",
  19706. "jcirc;": "ĵ",
  19707. "jmath;": "ȷ",
  19708. "Jukcy;": "Є",
  19709. "jukcy;": "є",
  19710. "Kappa;": "Κ",
  19711. "kappa;": "κ",
  19712. "lAarr;": "⇚",
  19713. "langd;": "⦑",
  19714. "laquo;": "«",
  19715. "larrb;": "⇤",
  19716. "lates;": "⪭︀",
  19717. "lBarr;": "⤎",
  19718. "lbarr;": "⤌",
  19719. "lbbrk;": "❲",
  19720. "lbrke;": "⦋",
  19721. "lceil;": "⌈",
  19722. "ldquo;": "“",
  19723. "lescc;": "⪨",
  19724. "lhard;": "↽",
  19725. "lharu;": "↼",
  19726. "lhblk;": "▄",
  19727. "llarr;": "⇇",
  19728. "lltri;": "◺",
  19729. "lneqq;": "≨",
  19730. "lnsim;": "⋦",
  19731. "loang;": "⟬",
  19732. "loarr;": "⇽",
  19733. "lobrk;": "⟦",
  19734. "lopar;": "⦅",
  19735. "lrarr;": "⇆",
  19736. "lrhar;": "⇋",
  19737. "lrtri;": "⊿",
  19738. "lsime;": "⪍",
  19739. "lsimg;": "⪏",
  19740. "lsquo;": "‘",
  19741. "ltcir;": "⩹",
  19742. "ltdot;": "⋖",
  19743. "ltrie;": "⊴",
  19744. "ltrif;": "◂",
  19745. "mdash;": "—",
  19746. "mDDot;": "∺",
  19747. "micro;": "µ",
  19748. middot: "·",
  19749. "minus;": "−",
  19750. "mumap;": "⊸",
  19751. "nabla;": "∇",
  19752. "napid;": "≋̸",
  19753. "napos;": "ʼn",
  19754. "natur;": "♮",
  19755. "nbump;": "≎̸",
  19756. "ncong;": "≇",
  19757. "ndash;": "–",
  19758. "neArr;": "⇗",
  19759. "nearr;": "↗",
  19760. "nedot;": "≐̸",
  19761. "nesim;": "≂̸",
  19762. "ngeqq;": "≧̸",
  19763. "ngsim;": "≵",
  19764. "nhArr;": "⇎",
  19765. "nharr;": "↮",
  19766. "nhpar;": "⫲",
  19767. "nlArr;": "⇍",
  19768. "nlarr;": "↚",
  19769. "nleqq;": "≦̸",
  19770. "nless;": "≮",
  19771. "nlsim;": "≴",
  19772. "nltri;": "⋪",
  19773. "notin;": "∉",
  19774. "notni;": "∌",
  19775. "npart;": "∂̸",
  19776. "nprec;": "⊀",
  19777. "nrArr;": "⇏",
  19778. "nrarr;": "↛",
  19779. "nrtri;": "⋫",
  19780. "nsime;": "≄",
  19781. "nsmid;": "∤",
  19782. "nspar;": "∦",
  19783. "nsubE;": "⫅̸",
  19784. "nsube;": "⊈",
  19785. "nsucc;": "⊁",
  19786. "nsupE;": "⫆̸",
  19787. "nsupe;": "⊉",
  19788. Ntilde: "Ñ",
  19789. ntilde: "ñ",
  19790. "numsp;": " ",
  19791. "nvsim;": "∼⃒",
  19792. "nwArr;": "⇖",
  19793. "nwarr;": "↖",
  19794. Oacute: "Ó",
  19795. oacute: "ó",
  19796. "Ocirc;": "Ô",
  19797. "ocirc;": "ô",
  19798. "odash;": "⊝",
  19799. "OElig;": "Œ",
  19800. "oelig;": "œ",
  19801. "ofcir;": "⦿",
  19802. Ograve: "Ò",
  19803. ograve: "ò",
  19804. "ohbar;": "⦵",
  19805. "olarr;": "↺",
  19806. "olcir;": "⦾",
  19807. "oline;": "‾",
  19808. "Omacr;": "Ō",
  19809. "omacr;": "ō",
  19810. "Omega;": "Ω",
  19811. "omega;": "ω",
  19812. "operp;": "⦹",
  19813. "oplus;": "⊕",
  19814. "orarr;": "↻",
  19815. "order;": "ℴ",
  19816. Oslash: "Ø",
  19817. oslash: "ø",
  19818. Otilde: "Õ",
  19819. otilde: "õ",
  19820. "ovbar;": "⌽",
  19821. "parsl;": "⫽",
  19822. "phone;": "☎",
  19823. "plusb;": "⊞",
  19824. "pluse;": "⩲",
  19825. plusmn: "±",
  19826. "pound;": "£",
  19827. "prcue;": "≼",
  19828. "Prime;": "″",
  19829. "prime;": "′",
  19830. "prnap;": "⪹",
  19831. "prsim;": "≾",
  19832. "quest;": "?",
  19833. "rAarr;": "⇛",
  19834. "radic;": "√",
  19835. "rangd;": "⦒",
  19836. "range;": "⦥",
  19837. "raquo;": "»",
  19838. "rarrb;": "⇥",
  19839. "rarrc;": "⤳",
  19840. "rarrw;": "↝",
  19841. "ratio;": "∶",
  19842. "RBarr;": "⤐",
  19843. "rBarr;": "⤏",
  19844. "rbarr;": "⤍",
  19845. "rbbrk;": "❳",
  19846. "rbrke;": "⦌",
  19847. "rceil;": "⌉",
  19848. "rdquo;": "”",
  19849. "reals;": "ℝ",
  19850. "rhard;": "⇁",
  19851. "rharu;": "⇀",
  19852. "rlarr;": "⇄",
  19853. "rlhar;": "⇌",
  19854. "rnmid;": "⫮",
  19855. "roang;": "⟭",
  19856. "roarr;": "⇾",
  19857. "robrk;": "⟧",
  19858. "ropar;": "⦆",
  19859. "rrarr;": "⇉",
  19860. "rsquo;": "’",
  19861. "rtrie;": "⊵",
  19862. "rtrif;": "▸",
  19863. "sbquo;": "‚",
  19864. "sccue;": "≽",
  19865. "Scirc;": "Ŝ",
  19866. "scirc;": "ŝ",
  19867. "scnap;": "⪺",
  19868. "scsim;": "≿",
  19869. "sdotb;": "⊡",
  19870. "sdote;": "⩦",
  19871. "seArr;": "⇘",
  19872. "searr;": "↘",
  19873. "setmn;": "∖",
  19874. "sharp;": "♯",
  19875. "Sigma;": "Σ",
  19876. "sigma;": "σ",
  19877. "simeq;": "≃",
  19878. "simgE;": "⪠",
  19879. "simlE;": "⪟",
  19880. "simne;": "≆",
  19881. "slarr;": "←",
  19882. "smile;": "⌣",
  19883. "smtes;": "⪬︀",
  19884. "sqcap;": "⊓",
  19885. "sqcup;": "⊔",
  19886. "sqsub;": "⊏",
  19887. "sqsup;": "⊐",
  19888. "srarr;": "→",
  19889. "starf;": "★",
  19890. "strns;": "¯",
  19891. "subnE;": "⫋",
  19892. "subne;": "⊊",
  19893. "supnE;": "⫌",
  19894. "supne;": "⊋",
  19895. "swArr;": "⇙",
  19896. "swarr;": "↙",
  19897. "szlig;": "ß",
  19898. "Theta;": "Θ",
  19899. "theta;": "θ",
  19900. "thkap;": "≈",
  19901. "THORN;": "Þ",
  19902. "thorn;": "þ",
  19903. "Tilde;": "∼",
  19904. "tilde;": "˜",
  19905. "times;": "×",
  19906. "TRADE;": "™",
  19907. "trade;": "™",
  19908. "trisb;": "⧍",
  19909. "TSHcy;": "Ћ",
  19910. "tshcy;": "ћ",
  19911. "twixt;": "≬",
  19912. Uacute: "Ú",
  19913. uacute: "ú",
  19914. "Ubrcy;": "Ў",
  19915. "ubrcy;": "ў",
  19916. "Ucirc;": "Û",
  19917. "ucirc;": "û",
  19918. "udarr;": "⇅",
  19919. "udhar;": "⥮",
  19920. Ugrave: "Ù",
  19921. ugrave: "ù",
  19922. "uharl;": "↿",
  19923. "uharr;": "↾",
  19924. "uhblk;": "▀",
  19925. "ultri;": "◸",
  19926. "Umacr;": "Ū",
  19927. "umacr;": "ū",
  19928. "Union;": "⋃",
  19929. "Uogon;": "Ų",
  19930. "uogon;": "ų",
  19931. "uplus;": "⊎",
  19932. "upsih;": "ϒ",
  19933. "UpTee;": "⊥",
  19934. "Uring;": "Ů",
  19935. "uring;": "ů",
  19936. "urtri;": "◹",
  19937. "utdot;": "⋰",
  19938. "utrif;": "▴",
  19939. "uuarr;": "⇈",
  19940. "varpi;": "ϖ",
  19941. "vBarv;": "⫩",
  19942. "VDash;": "⊫",
  19943. "Vdash;": "⊩",
  19944. "vDash;": "⊨",
  19945. "vdash;": "⊢",
  19946. "veeeq;": "≚",
  19947. "vltri;": "⊲",
  19948. "vnsub;": "⊂⃒",
  19949. "vnsup;": "⊃⃒",
  19950. "vprop;": "∝",
  19951. "vrtri;": "⊳",
  19952. "Wcirc;": "Ŵ",
  19953. "wcirc;": "ŵ",
  19954. "Wedge;": "⋀",
  19955. "wedge;": "∧",
  19956. "xcirc;": "◯",
  19957. "xdtri;": "▽",
  19958. "xhArr;": "⟺",
  19959. "xharr;": "⟷",
  19960. "xlArr;": "⟸",
  19961. "xlarr;": "⟵",
  19962. "xodot;": "⨀",
  19963. "xrArr;": "⟹",
  19964. "xrarr;": "⟶",
  19965. "xutri;": "△",
  19966. Yacute: "Ý",
  19967. yacute: "ý",
  19968. "Ycirc;": "Ŷ",
  19969. "ycirc;": "ŷ",
  19970. "Aacute;": "Á",
  19971. "aacute;": "á",
  19972. "Abreve;": "Ă",
  19973. "abreve;": "ă",
  19974. "Agrave;": "À",
  19975. "agrave;": "à",
  19976. "andand;": "⩕",
  19977. "angmsd;": "∡",
  19978. "angsph;": "∢",
  19979. "apacir;": "⩯",
  19980. "approx;": "≈",
  19981. "Assign;": "≔",
  19982. "Atilde;": "Ã",
  19983. "atilde;": "ã",
  19984. "barvee;": "⊽",
  19985. "Barwed;": "⌆",
  19986. "barwed;": "⌅",
  19987. "becaus;": "∵",
  19988. "bernou;": "ℬ",
  19989. "bigcap;": "⋂",
  19990. "bigcup;": "⋃",
  19991. "bigvee;": "⋁",
  19992. "bkarow;": "⤍",
  19993. "bottom;": "⊥",
  19994. "bowtie;": "⋈",
  19995. "boxbox;": "⧉",
  19996. "bprime;": "‵",
  19997. "brvbar;": "¦",
  19998. "bullet;": "•",
  19999. "Bumpeq;": "≎",
  20000. "bumpeq;": "≏",
  20001. "Cacute;": "Ć",
  20002. "cacute;": "ć",
  20003. "capand;": "⩄",
  20004. "capcap;": "⩋",
  20005. "capcup;": "⩇",
  20006. "capdot;": "⩀",
  20007. "Ccaron;": "Č",
  20008. "ccaron;": "č",
  20009. "Ccedil;": "Ç",
  20010. "ccedil;": "ç",
  20011. "circeq;": "≗",
  20012. "cirmid;": "⫯",
  20013. "Colone;": "⩴",
  20014. "colone;": "≔",
  20015. "commat;": "@",
  20016. "compfn;": "∘",
  20017. "Conint;": "∯",
  20018. "conint;": "∮",
  20019. "coprod;": "∐",
  20020. "copysr;": "℗",
  20021. "cularr;": "↶",
  20022. "CupCap;": "≍",
  20023. "cupcap;": "⩆",
  20024. "cupcup;": "⩊",
  20025. "cupdot;": "⊍",
  20026. "curarr;": "↷",
  20027. "curren;": "¤",
  20028. "cylcty;": "⌭",
  20029. "Dagger;": "‡",
  20030. "dagger;": "†",
  20031. "daleth;": "ℸ",
  20032. "Dcaron;": "Ď",
  20033. "dcaron;": "ď",
  20034. "dfisht;": "⥿",
  20035. "divide;": "÷",
  20036. "divonx;": "⋇",
  20037. "dlcorn;": "⌞",
  20038. "dlcrop;": "⌍",
  20039. "dollar;": "$",
  20040. "DotDot;": "⃜",
  20041. "drcorn;": "⌟",
  20042. "drcrop;": "⌌",
  20043. "Dstrok;": "Đ",
  20044. "dstrok;": "đ",
  20045. "Eacute;": "É",
  20046. "eacute;": "é",
  20047. "easter;": "⩮",
  20048. "Ecaron;": "Ě",
  20049. "ecaron;": "ě",
  20050. "ecolon;": "≕",
  20051. "Egrave;": "È",
  20052. "egrave;": "è",
  20053. "egsdot;": "⪘",
  20054. "elsdot;": "⪗",
  20055. "emptyv;": "∅",
  20056. "emsp13;": " ",
  20057. "emsp14;": " ",
  20058. "eparsl;": "⧣",
  20059. "eqcirc;": "≖",
  20060. "equals;": "=",
  20061. "equest;": "≟",
  20062. "Exists;": "∃",
  20063. "female;": "♀",
  20064. "ffilig;": "ffi",
  20065. "ffllig;": "ffl",
  20066. "ForAll;": "∀",
  20067. "forall;": "∀",
  20068. "frac12;": "½",
  20069. "frac13;": "⅓",
  20070. "frac14;": "¼",
  20071. "frac15;": "⅕",
  20072. "frac16;": "⅙",
  20073. "frac18;": "⅛",
  20074. "frac23;": "⅔",
  20075. "frac25;": "⅖",
  20076. "frac34;": "¾",
  20077. "frac35;": "⅗",
  20078. "frac38;": "⅜",
  20079. "frac45;": "⅘",
  20080. "frac56;": "⅚",
  20081. "frac58;": "⅝",
  20082. "frac78;": "⅞",
  20083. "gacute;": "ǵ",
  20084. "Gammad;": "Ϝ",
  20085. "gammad;": "ϝ",
  20086. "Gbreve;": "Ğ",
  20087. "gbreve;": "ğ",
  20088. "Gcedil;": "Ģ",
  20089. "gesdot;": "⪀",
  20090. "gesles;": "⪔",
  20091. "gtlPar;": "⦕",
  20092. "gtrarr;": "⥸",
  20093. "gtrdot;": "⋗",
  20094. "gtrsim;": "≳",
  20095. "hairsp;": " ",
  20096. "hamilt;": "ℋ",
  20097. "HARDcy;": "Ъ",
  20098. "hardcy;": "ъ",
  20099. "hearts;": "♥",
  20100. "hellip;": "…",
  20101. "hercon;": "⊹",
  20102. "homtht;": "∻",
  20103. "horbar;": "―",
  20104. "hslash;": "ℏ",
  20105. "Hstrok;": "Ħ",
  20106. "hstrok;": "ħ",
  20107. "hybull;": "⁃",
  20108. "hyphen;": "‐",
  20109. "Iacute;": "Í",
  20110. "iacute;": "í",
  20111. "Igrave;": "Ì",
  20112. "igrave;": "ì",
  20113. "iiiint;": "⨌",
  20114. "iinfin;": "⧜",
  20115. "incare;": "℅",
  20116. "inodot;": "ı",
  20117. "intcal;": "⊺",
  20118. "iquest;": "¿",
  20119. "isinsv;": "⋳",
  20120. "Itilde;": "Ĩ",
  20121. "itilde;": "ĩ",
  20122. "Jsercy;": "Ј",
  20123. "jsercy;": "ј",
  20124. "kappav;": "ϰ",
  20125. "Kcedil;": "Ķ",
  20126. "kcedil;": "ķ",
  20127. "kgreen;": "ĸ",
  20128. "Lacute;": "Ĺ",
  20129. "lacute;": "ĺ",
  20130. "lagran;": "ℒ",
  20131. "Lambda;": "Λ",
  20132. "lambda;": "λ",
  20133. "langle;": "⟨",
  20134. "larrfs;": "⤝",
  20135. "larrhk;": "↩",
  20136. "larrlp;": "↫",
  20137. "larrpl;": "⤹",
  20138. "larrtl;": "↢",
  20139. "lAtail;": "⤛",
  20140. "latail;": "⤙",
  20141. "lbrace;": "{",
  20142. "lbrack;": "[",
  20143. "Lcaron;": "Ľ",
  20144. "lcaron;": "ľ",
  20145. "Lcedil;": "Ļ",
  20146. "lcedil;": "ļ",
  20147. "ldquor;": "„",
  20148. "lesdot;": "⩿",
  20149. "lesges;": "⪓",
  20150. "lfisht;": "⥼",
  20151. "lfloor;": "⌊",
  20152. "lharul;": "⥪",
  20153. "llhard;": "⥫",
  20154. "Lmidot;": "Ŀ",
  20155. "lmidot;": "ŀ",
  20156. "lmoust;": "⎰",
  20157. "loplus;": "⨭",
  20158. "lowast;": "∗",
  20159. "lowbar;": "_",
  20160. "lparlt;": "⦓",
  20161. "lrhard;": "⥭",
  20162. "lsaquo;": "‹",
  20163. "lsquor;": "‚",
  20164. "Lstrok;": "Ł",
  20165. "lstrok;": "ł",
  20166. "lthree;": "⋋",
  20167. "ltimes;": "⋉",
  20168. "ltlarr;": "⥶",
  20169. "ltrPar;": "⦖",
  20170. "mapsto;": "↦",
  20171. "marker;": "▮",
  20172. "mcomma;": "⨩",
  20173. "midast;": "*",
  20174. "midcir;": "⫰",
  20175. "middot;": "·",
  20176. "minusb;": "⊟",
  20177. "minusd;": "∸",
  20178. "mnplus;": "∓",
  20179. "models;": "⊧",
  20180. "mstpos;": "∾",
  20181. "Nacute;": "Ń",
  20182. "nacute;": "ń",
  20183. "nbumpe;": "≏̸",
  20184. "Ncaron;": "Ň",
  20185. "ncaron;": "ň",
  20186. "Ncedil;": "Ņ",
  20187. "ncedil;": "ņ",
  20188. "nearhk;": "⤤",
  20189. "nequiv;": "≢",
  20190. "nesear;": "⤨",
  20191. "nexist;": "∄",
  20192. "nltrie;": "⋬",
  20193. "notinE;": "⋹̸",
  20194. "nparsl;": "⫽⃥",
  20195. "nprcue;": "⋠",
  20196. "nrarrc;": "⤳̸",
  20197. "nrarrw;": "↝̸",
  20198. "nrtrie;": "⋭",
  20199. "nsccue;": "⋡",
  20200. "nsimeq;": "≄",
  20201. "Ntilde;": "Ñ",
  20202. "ntilde;": "ñ",
  20203. "numero;": "№",
  20204. "nVDash;": "⊯",
  20205. "nVdash;": "⊮",
  20206. "nvDash;": "⊭",
  20207. "nvdash;": "⊬",
  20208. "nvHarr;": "⤄",
  20209. "nvlArr;": "⤂",
  20210. "nvrArr;": "⤃",
  20211. "nwarhk;": "⤣",
  20212. "nwnear;": "⤧",
  20213. "Oacute;": "Ó",
  20214. "oacute;": "ó",
  20215. "Odblac;": "Ő",
  20216. "odblac;": "ő",
  20217. "odsold;": "⦼",
  20218. "Ograve;": "Ò",
  20219. "ograve;": "ò",
  20220. "ominus;": "⊖",
  20221. "origof;": "⊶",
  20222. "Oslash;": "Ø",
  20223. "oslash;": "ø",
  20224. "Otilde;": "Õ",
  20225. "otilde;": "õ",
  20226. "Otimes;": "⨷",
  20227. "otimes;": "⊗",
  20228. "parsim;": "⫳",
  20229. "percnt;": "%",
  20230. "period;": ".",
  20231. "permil;": "‰",
  20232. "phmmat;": "ℳ",
  20233. "planck;": "ℏ",
  20234. "plankv;": "ℏ",
  20235. "plusdo;": "∔",
  20236. "plusdu;": "⨥",
  20237. "plusmn;": "±",
  20238. "preceq;": "⪯",
  20239. "primes;": "ℙ",
  20240. "prnsim;": "⋨",
  20241. "propto;": "∝",
  20242. "prurel;": "⊰",
  20243. "puncsp;": " ",
  20244. "qprime;": "⁗",
  20245. "Racute;": "Ŕ",
  20246. "racute;": "ŕ",
  20247. "rangle;": "⟩",
  20248. "rarrap;": "⥵",
  20249. "rarrfs;": "⤞",
  20250. "rarrhk;": "↪",
  20251. "rarrlp;": "↬",
  20252. "rarrpl;": "⥅",
  20253. "Rarrtl;": "⤖",
  20254. "rarrtl;": "↣",
  20255. "rAtail;": "⤜",
  20256. "ratail;": "⤚",
  20257. "rbrace;": "}",
  20258. "rbrack;": "]",
  20259. "Rcaron;": "Ř",
  20260. "rcaron;": "ř",
  20261. "Rcedil;": "Ŗ",
  20262. "rcedil;": "ŗ",
  20263. "rdquor;": "”",
  20264. "rfisht;": "⥽",
  20265. "rfloor;": "⌋",
  20266. "rharul;": "⥬",
  20267. "rmoust;": "⎱",
  20268. "roplus;": "⨮",
  20269. "rpargt;": "⦔",
  20270. "rsaquo;": "›",
  20271. "rsquor;": "’",
  20272. "rthree;": "⋌",
  20273. "rtimes;": "⋊",
  20274. "Sacute;": "Ś",
  20275. "sacute;": "ś",
  20276. "Scaron;": "Š",
  20277. "scaron;": "š",
  20278. "Scedil;": "Ş",
  20279. "scedil;": "ş",
  20280. "scnsim;": "⋩",
  20281. "searhk;": "⤥",
  20282. "seswar;": "⤩",
  20283. "sfrown;": "⌢",
  20284. "SHCHcy;": "Щ",
  20285. "shchcy;": "щ",
  20286. "sigmaf;": "ς",
  20287. "sigmav;": "ς",
  20288. "simdot;": "⩪",
  20289. "smashp;": "⨳",
  20290. "SOFTcy;": "Ь",
  20291. "softcy;": "ь",
  20292. "solbar;": "⌿",
  20293. "spades;": "♠",
  20294. "sqcaps;": "⊓︀",
  20295. "sqcups;": "⊔︀",
  20296. "sqsube;": "⊑",
  20297. "sqsupe;": "⊒",
  20298. "Square;": "□",
  20299. "square;": "□",
  20300. "squarf;": "▪",
  20301. "ssetmn;": "∖",
  20302. "ssmile;": "⌣",
  20303. "sstarf;": "⋆",
  20304. "subdot;": "⪽",
  20305. "Subset;": "⋐",
  20306. "subset;": "⊂",
  20307. "subsim;": "⫇",
  20308. "subsub;": "⫕",
  20309. "subsup;": "⫓",
  20310. "succeq;": "⪰",
  20311. "supdot;": "⪾",
  20312. "Supset;": "⋑",
  20313. "supset;": "⊃",
  20314. "supsim;": "⫈",
  20315. "supsub;": "⫔",
  20316. "supsup;": "⫖",
  20317. "swarhk;": "⤦",
  20318. "swnwar;": "⤪",
  20319. "target;": "⌖",
  20320. "Tcaron;": "Ť",
  20321. "tcaron;": "ť",
  20322. "Tcedil;": "Ţ",
  20323. "tcedil;": "ţ",
  20324. "telrec;": "⌕",
  20325. "there4;": "∴",
  20326. "thetav;": "ϑ",
  20327. "thinsp;": " ",
  20328. "thksim;": "∼",
  20329. "timesb;": "⊠",
  20330. "timesd;": "⨰",
  20331. "topbot;": "⌶",
  20332. "topcir;": "⫱",
  20333. "tprime;": "‴",
  20334. "tridot;": "◬",
  20335. "Tstrok;": "Ŧ",
  20336. "tstrok;": "ŧ",
  20337. "Uacute;": "Ú",
  20338. "uacute;": "ú",
  20339. "Ubreve;": "Ŭ",
  20340. "ubreve;": "ŭ",
  20341. "Udblac;": "Ű",
  20342. "udblac;": "ű",
  20343. "ufisht;": "⥾",
  20344. "Ugrave;": "Ù",
  20345. "ugrave;": "ù",
  20346. "ulcorn;": "⌜",
  20347. "ulcrop;": "⌏",
  20348. "urcorn;": "⌝",
  20349. "urcrop;": "⌎",
  20350. "Utilde;": "Ũ",
  20351. "utilde;": "ũ",
  20352. "vangrt;": "⦜",
  20353. "varphi;": "ϕ",
  20354. "varrho;": "ϱ",
  20355. "Vdashl;": "⫦",
  20356. "veebar;": "⊻",
  20357. "vellip;": "⋮",
  20358. "Verbar;": "‖",
  20359. "verbar;": "|",
  20360. "vsubnE;": "⫋︀",
  20361. "vsubne;": "⊊︀",
  20362. "vsupnE;": "⫌︀",
  20363. "vsupne;": "⊋︀",
  20364. "Vvdash;": "⊪",
  20365. "wedbar;": "⩟",
  20366. "wedgeq;": "≙",
  20367. "weierp;": "℘",
  20368. "wreath;": "≀",
  20369. "xoplus;": "⨁",
  20370. "xotime;": "⨂",
  20371. "xsqcup;": "⨆",
  20372. "xuplus;": "⨄",
  20373. "xwedge;": "⋀",
  20374. "Yacute;": "Ý",
  20375. "yacute;": "ý",
  20376. "Zacute;": "Ź",
  20377. "zacute;": "ź",
  20378. "Zcaron;": "Ž",
  20379. "zcaron;": "ž",
  20380. "zeetrf;": "ℨ",
  20381. "alefsym;": "ℵ",
  20382. "angrtvb;": "⊾",
  20383. "angzarr;": "⍼",
  20384. "asympeq;": "≍",
  20385. "backsim;": "∽",
  20386. "Because;": "∵",
  20387. "because;": "∵",
  20388. "bemptyv;": "⦰",
  20389. "between;": "≬",
  20390. "bigcirc;": "◯",
  20391. "bigodot;": "⨀",
  20392. "bigstar;": "★",
  20393. "bnequiv;": "≡⃥",
  20394. "boxplus;": "⊞",
  20395. "Cayleys;": "ℭ",
  20396. "Cconint;": "∰",
  20397. "ccupssm;": "⩐",
  20398. "Cedilla;": "¸",
  20399. "cemptyv;": "⦲",
  20400. "cirscir;": "⧂",
  20401. "coloneq;": "≔",
  20402. "congdot;": "⩭",
  20403. "cudarrl;": "⤸",
  20404. "cudarrr;": "⤵",
  20405. "cularrp;": "⤽",
  20406. "curarrm;": "⤼",
  20407. "dbkarow;": "⤏",
  20408. "ddagger;": "‡",
  20409. "ddotseq;": "⩷",
  20410. "demptyv;": "⦱",
  20411. "Diamond;": "⋄",
  20412. "diamond;": "⋄",
  20413. "digamma;": "ϝ",
  20414. "dotplus;": "∔",
  20415. "DownTee;": "⊤",
  20416. "dwangle;": "⦦",
  20417. "Element;": "∈",
  20418. "Epsilon;": "Ε",
  20419. "epsilon;": "ε",
  20420. "eqcolon;": "≕",
  20421. "equivDD;": "⩸",
  20422. "gesdoto;": "⪂",
  20423. "gtquest;": "⩼",
  20424. "gtrless;": "≷",
  20425. "harrcir;": "⥈",
  20426. "Implies;": "⇒",
  20427. "intprod;": "⨼",
  20428. "isindot;": "⋵",
  20429. "larrbfs;": "⤟",
  20430. "larrsim;": "⥳",
  20431. "lbrksld;": "⦏",
  20432. "lbrkslu;": "⦍",
  20433. "ldrdhar;": "⥧",
  20434. "LeftTee;": "⊣",
  20435. "lesdoto;": "⪁",
  20436. "lessdot;": "⋖",
  20437. "lessgtr;": "≶",
  20438. "lesssim;": "≲",
  20439. "lotimes;": "⨴",
  20440. "lozenge;": "◊",
  20441. "ltquest;": "⩻",
  20442. "luruhar;": "⥦",
  20443. "maltese;": "✠",
  20444. "minusdu;": "⨪",
  20445. "napprox;": "≉",
  20446. "natural;": "♮",
  20447. "nearrow;": "↗",
  20448. "NewLine;": "\n",
  20449. "nexists;": "∄",
  20450. "NoBreak;": "⁠",
  20451. "notinva;": "∉",
  20452. "notinvb;": "⋷",
  20453. "notinvc;": "⋶",
  20454. "NotLess;": "≮",
  20455. "notniva;": "∌",
  20456. "notnivb;": "⋾",
  20457. "notnivc;": "⋽",
  20458. "npolint;": "⨔",
  20459. "npreceq;": "⪯̸",
  20460. "nsqsube;": "⋢",
  20461. "nsqsupe;": "⋣",
  20462. "nsubset;": "⊂⃒",
  20463. "nsucceq;": "⪰̸",
  20464. "nsupset;": "⊃⃒",
  20465. "nvinfin;": "⧞",
  20466. "nvltrie;": "⊴⃒",
  20467. "nvrtrie;": "⊵⃒",
  20468. "nwarrow;": "↖",
  20469. "olcross;": "⦻",
  20470. "Omicron;": "Ο",
  20471. "omicron;": "ο",
  20472. "orderof;": "ℴ",
  20473. "orslope;": "⩗",
  20474. "OverBar;": "‾",
  20475. "pertenk;": "‱",
  20476. "planckh;": "ℎ",
  20477. "pluscir;": "⨢",
  20478. "plussim;": "⨦",
  20479. "plustwo;": "⨧",
  20480. "precsim;": "≾",
  20481. "Product;": "∏",
  20482. "quatint;": "⨖",
  20483. "questeq;": "≟",
  20484. "rarrbfs;": "⤠",
  20485. "rarrsim;": "⥴",
  20486. "rbrksld;": "⦎",
  20487. "rbrkslu;": "⦐",
  20488. "rdldhar;": "⥩",
  20489. "realine;": "ℛ",
  20490. "rotimes;": "⨵",
  20491. "ruluhar;": "⥨",
  20492. "searrow;": "↘",
  20493. "simplus;": "⨤",
  20494. "simrarr;": "⥲",
  20495. "subedot;": "⫃",
  20496. "submult;": "⫁",
  20497. "subplus;": "⪿",
  20498. "subrarr;": "⥹",
  20499. "succsim;": "≿",
  20500. "supdsub;": "⫘",
  20501. "supedot;": "⫄",
  20502. "suphsol;": "⟉",
  20503. "suphsub;": "⫗",
  20504. "suplarr;": "⥻",
  20505. "supmult;": "⫂",
  20506. "supplus;": "⫀",
  20507. "swarrow;": "↙",
  20508. "topfork;": "⫚",
  20509. "triplus;": "⨹",
  20510. "tritime;": "⨻",
  20511. "UpArrow;": "↑",
  20512. "Uparrow;": "⇑",
  20513. "uparrow;": "↑",
  20514. "Upsilon;": "Υ",
  20515. "upsilon;": "υ",
  20516. "uwangle;": "⦧",
  20517. "vzigzag;": "⦚",
  20518. "zigrarr;": "⇝",
  20519. "andslope;": "⩘",
  20520. "angmsdaa;": "⦨",
  20521. "angmsdab;": "⦩",
  20522. "angmsdac;": "⦪",
  20523. "angmsdad;": "⦫",
  20524. "angmsdae;": "⦬",
  20525. "angmsdaf;": "⦭",
  20526. "angmsdag;": "⦮",
  20527. "angmsdah;": "⦯",
  20528. "angrtvbd;": "⦝",
  20529. "approxeq;": "≊",
  20530. "awconint;": "∳",
  20531. "backcong;": "≌",
  20532. "barwedge;": "⌅",
  20533. "bbrktbrk;": "⎶",
  20534. "bigoplus;": "⨁",
  20535. "bigsqcup;": "⨆",
  20536. "biguplus;": "⨄",
  20537. "bigwedge;": "⋀",
  20538. "boxminus;": "⊟",
  20539. "boxtimes;": "⊠",
  20540. "bsolhsub;": "⟈",
  20541. "capbrcup;": "⩉",
  20542. "circledR;": "®",
  20543. "circledS;": "Ⓢ",
  20544. "cirfnint;": "⨐",
  20545. "clubsuit;": "♣",
  20546. "cupbrcap;": "⩈",
  20547. "curlyvee;": "⋎",
  20548. "cwconint;": "∲",
  20549. "DDotrahd;": "⤑",
  20550. "doteqdot;": "≑",
  20551. "DotEqual;": "≐",
  20552. "dotminus;": "∸",
  20553. "drbkarow;": "⤐",
  20554. "dzigrarr;": "⟿",
  20555. "elinters;": "⏧",
  20556. "emptyset;": "∅",
  20557. "eqvparsl;": "⧥",
  20558. "fpartint;": "⨍",
  20559. "geqslant;": "⩾",
  20560. "gesdotol;": "⪄",
  20561. "gnapprox;": "⪊",
  20562. "hksearow;": "⤥",
  20563. "hkswarow;": "⤦",
  20564. "imagline;": "ℐ",
  20565. "imagpart;": "ℑ",
  20566. "infintie;": "⧝",
  20567. "integers;": "ℤ",
  20568. "Integral;": "∫",
  20569. "intercal;": "⊺",
  20570. "intlarhk;": "⨗",
  20571. "laemptyv;": "⦴",
  20572. "ldrushar;": "⥋",
  20573. "leqslant;": "⩽",
  20574. "lesdotor;": "⪃",
  20575. "LessLess;": "⪡",
  20576. "llcorner;": "⌞",
  20577. "lnapprox;": "⪉",
  20578. "lrcorner;": "⌟",
  20579. "lurdshar;": "⥊",
  20580. "mapstoup;": "↥",
  20581. "multimap;": "⊸",
  20582. "naturals;": "ℕ",
  20583. "ncongdot;": "⩭̸",
  20584. "NotEqual;": "≠",
  20585. "notindot;": "⋵̸",
  20586. "NotTilde;": "≁",
  20587. "otimesas;": "⨶",
  20588. "parallel;": "∥",
  20589. "PartialD;": "∂",
  20590. "plusacir;": "⨣",
  20591. "pointint;": "⨕",
  20592. "Precedes;": "≺",
  20593. "precneqq;": "⪵",
  20594. "precnsim;": "⋨",
  20595. "profalar;": "⌮",
  20596. "profline;": "⌒",
  20597. "profsurf;": "⌓",
  20598. "raemptyv;": "⦳",
  20599. "realpart;": "ℜ",
  20600. "RightTee;": "⊢",
  20601. "rppolint;": "⨒",
  20602. "rtriltri;": "⧎",
  20603. "scpolint;": "⨓",
  20604. "setminus;": "∖",
  20605. "shortmid;": "∣",
  20606. "smeparsl;": "⧤",
  20607. "sqsubset;": "⊏",
  20608. "sqsupset;": "⊐",
  20609. "subseteq;": "⊆",
  20610. "Succeeds;": "≻",
  20611. "succneqq;": "⪶",
  20612. "succnsim;": "⋩",
  20613. "SuchThat;": "∋",
  20614. "Superset;": "⊃",
  20615. "supseteq;": "⊇",
  20616. "thetasym;": "ϑ",
  20617. "thicksim;": "∼",
  20618. "timesbar;": "⨱",
  20619. "triangle;": "▵",
  20620. "triminus;": "⨺",
  20621. "trpezium;": "⏢",
  20622. "Uarrocir;": "⥉",
  20623. "ulcorner;": "⌜",
  20624. "UnderBar;": "_",
  20625. "urcorner;": "⌝",
  20626. "varkappa;": "ϰ",
  20627. "varsigma;": "ς",
  20628. "vartheta;": "ϑ",
  20629. "backprime;": "‵",
  20630. "backsimeq;": "⋍",
  20631. "Backslash;": "∖",
  20632. "bigotimes;": "⨂",
  20633. "CenterDot;": "·",
  20634. "centerdot;": "·",
  20635. "checkmark;": "✓",
  20636. "CircleDot;": "⊙",
  20637. "complexes;": "ℂ",
  20638. "Congruent;": "≡",
  20639. "Coproduct;": "∐",
  20640. "dotsquare;": "⊡",
  20641. "DoubleDot;": "¨",
  20642. "DownArrow;": "↓",
  20643. "Downarrow;": "⇓",
  20644. "downarrow;": "↓",
  20645. "DownBreve;": "̑",
  20646. "gtrapprox;": "⪆",
  20647. "gtreqless;": "⋛",
  20648. "gvertneqq;": "≩︀",
  20649. "heartsuit;": "♥",
  20650. "HumpEqual;": "≏",
  20651. "LeftArrow;": "←",
  20652. "Leftarrow;": "⇐",
  20653. "leftarrow;": "←",
  20654. "LeftFloor;": "⌊",
  20655. "lesseqgtr;": "⋚",
  20656. "LessTilde;": "≲",
  20657. "lvertneqq;": "≨︀",
  20658. "Mellintrf;": "ℳ",
  20659. "MinusPlus;": "∓",
  20660. "ngeqslant;": "⩾̸",
  20661. "nleqslant;": "⩽̸",
  20662. "NotCupCap;": "≭",
  20663. "NotExists;": "∄",
  20664. "NotSubset;": "⊂⃒",
  20665. "nparallel;": "∦",
  20666. "nshortmid;": "∤",
  20667. "nsubseteq;": "⊈",
  20668. "nsupseteq;": "⊉",
  20669. "OverBrace;": "⏞",
  20670. "pitchfork;": "⋔",
  20671. "PlusMinus;": "±",
  20672. "rationals;": "ℚ",
  20673. "spadesuit;": "♠",
  20674. "subseteqq;": "⫅",
  20675. "subsetneq;": "⊊",
  20676. "supseteqq;": "⫆",
  20677. "supsetneq;": "⊋",
  20678. "Therefore;": "∴",
  20679. "therefore;": "∴",
  20680. "ThinSpace;": " ",
  20681. "triangleq;": "≜",
  20682. "TripleDot;": "⃛",
  20683. "UnionPlus;": "⊎",
  20684. "varpropto;": "∝",
  20685. "Bernoullis;": "ℬ",
  20686. "circledast;": "⊛",
  20687. "CirclePlus;": "⊕",
  20688. "complement;": "∁",
  20689. "curlywedge;": "⋏",
  20690. "eqslantgtr;": "⪖",
  20691. "EqualTilde;": "≂",
  20692. "Fouriertrf;": "ℱ",
  20693. "gtreqqless;": "⪌",
  20694. "ImaginaryI;": "ⅈ",
  20695. "Laplacetrf;": "ℒ",
  20696. "LeftVector;": "↼",
  20697. "lessapprox;": "⪅",
  20698. "lesseqqgtr;": "⪋",
  20699. "Lleftarrow;": "⇚",
  20700. "lmoustache;": "⎰",
  20701. "longmapsto;": "⟼",
  20702. "mapstodown;": "↧",
  20703. "mapstoleft;": "↤",
  20704. "nLeftarrow;": "⇍",
  20705. "nleftarrow;": "↚",
  20706. "NotElement;": "∉",
  20707. "NotGreater;": "≯",
  20708. "nsubseteqq;": "⫅̸",
  20709. "nsupseteqq;": "⫆̸",
  20710. "precapprox;": "⪷",
  20711. "Proportion;": "∷",
  20712. "RightArrow;": "→",
  20713. "Rightarrow;": "⇒",
  20714. "rightarrow;": "→",
  20715. "RightFloor;": "⌋",
  20716. "rmoustache;": "⎱",
  20717. "sqsubseteq;": "⊑",
  20718. "sqsupseteq;": "⊒",
  20719. "subsetneqq;": "⫋",
  20720. "succapprox;": "⪸",
  20721. "supsetneqq;": "⫌",
  20722. "ThickSpace;": "  ",
  20723. "TildeEqual;": "≃",
  20724. "TildeTilde;": "≈",
  20725. "UnderBrace;": "⏟",
  20726. "UpArrowBar;": "⤒",
  20727. "UpTeeArrow;": "↥",
  20728. "upuparrows;": "⇈",
  20729. "varepsilon;": "ϵ",
  20730. "varnothing;": "∅",
  20731. "backepsilon;": "϶",
  20732. "blacksquare;": "▪",
  20733. "circledcirc;": "⊚",
  20734. "circleddash;": "⊝",
  20735. "CircleMinus;": "⊖",
  20736. "CircleTimes;": "⊗",
  20737. "curlyeqprec;": "⋞",
  20738. "curlyeqsucc;": "⋟",
  20739. "diamondsuit;": "♦",
  20740. "eqslantless;": "⪕",
  20741. "Equilibrium;": "⇌",
  20742. "expectation;": "ℰ",
  20743. "GreaterLess;": "≷",
  20744. "LeftCeiling;": "⌈",
  20745. "LessGreater;": "≶",
  20746. "MediumSpace;": " ",
  20747. "NotLessLess;": "≪̸",
  20748. "NotPrecedes;": "⊀",
  20749. "NotSucceeds;": "⊁",
  20750. "NotSuperset;": "⊃⃒",
  20751. "nRightarrow;": "⇏",
  20752. "nrightarrow;": "↛",
  20753. "OverBracket;": "⎴",
  20754. "preccurlyeq;": "≼",
  20755. "precnapprox;": "⪹",
  20756. "quaternions;": "ℍ",
  20757. "RightVector;": "⇀",
  20758. "Rrightarrow;": "⇛",
  20759. "RuleDelayed;": "⧴",
  20760. "SmallCircle;": "∘",
  20761. "SquareUnion;": "⊔",
  20762. "straightphi;": "ϕ",
  20763. "SubsetEqual;": "⊆",
  20764. "succcurlyeq;": "≽",
  20765. "succnapprox;": "⪺",
  20766. "thickapprox;": "≈",
  20767. "UpDownArrow;": "↕",
  20768. "Updownarrow;": "⇕",
  20769. "updownarrow;": "↕",
  20770. "VerticalBar;": "∣",
  20771. "blacklozenge;": "⧫",
  20772. "DownArrowBar;": "⤓",
  20773. "DownTeeArrow;": "↧",
  20774. "ExponentialE;": "ⅇ",
  20775. "exponentiale;": "ⅇ",
  20776. "GreaterEqual;": "≥",
  20777. "GreaterTilde;": "≳",
  20778. "HilbertSpace;": "ℋ",
  20779. "HumpDownHump;": "≎",
  20780. "Intersection;": "⋂",
  20781. "LeftArrowBar;": "⇤",
  20782. "LeftTeeArrow;": "↤",
  20783. "LeftTriangle;": "⊲",
  20784. "LeftUpVector;": "↿",
  20785. "NotCongruent;": "≢",
  20786. "NotHumpEqual;": "≏̸",
  20787. "NotLessEqual;": "≰",
  20788. "NotLessTilde;": "≴",
  20789. "Proportional;": "∝",
  20790. "RightCeiling;": "⌉",
  20791. "risingdotseq;": "≓",
  20792. "RoundImplies;": "⥰",
  20793. "ShortUpArrow;": "↑",
  20794. "SquareSubset;": "⊏",
  20795. "triangledown;": "▿",
  20796. "triangleleft;": "◃",
  20797. "UnderBracket;": "⎵",
  20798. "varsubsetneq;": "⊊︀",
  20799. "varsupsetneq;": "⊋︀",
  20800. "VerticalLine;": "|",
  20801. "ApplyFunction;": "⁡",
  20802. "bigtriangleup;": "△",
  20803. "blacktriangle;": "▴",
  20804. "DifferentialD;": "ⅆ",
  20805. "divideontimes;": "⋇",
  20806. "DoubleLeftTee;": "⫤",
  20807. "DoubleUpArrow;": "⇑",
  20808. "fallingdotseq;": "≒",
  20809. "hookleftarrow;": "↩",
  20810. "leftarrowtail;": "↢",
  20811. "leftharpoonup;": "↼",
  20812. "LeftTeeVector;": "⥚",
  20813. "LeftVectorBar;": "⥒",
  20814. "LessFullEqual;": "≦",
  20815. "LongLeftArrow;": "⟵",
  20816. "Longleftarrow;": "⟸",
  20817. "longleftarrow;": "⟵",
  20818. "looparrowleft;": "↫",
  20819. "measuredangle;": "∡",
  20820. "NotEqualTilde;": "≂̸",
  20821. "NotTildeEqual;": "≄",
  20822. "NotTildeTilde;": "≉",
  20823. "ntriangleleft;": "⋪",
  20824. "Poincareplane;": "ℌ",
  20825. "PrecedesEqual;": "⪯",
  20826. "PrecedesTilde;": "≾",
  20827. "RightArrowBar;": "⇥",
  20828. "RightTeeArrow;": "↦",
  20829. "RightTriangle;": "⊳",
  20830. "RightUpVector;": "↾",
  20831. "shortparallel;": "∥",
  20832. "smallsetminus;": "∖",
  20833. "SucceedsEqual;": "⪰",
  20834. "SucceedsTilde;": "≿",
  20835. "SupersetEqual;": "⊇",
  20836. "triangleright;": "▹",
  20837. "UpEquilibrium;": "⥮",
  20838. "upharpoonleft;": "↿",
  20839. "varsubsetneqq;": "⫋︀",
  20840. "varsupsetneqq;": "⫌︀",
  20841. "VerticalTilde;": "≀",
  20842. "VeryThinSpace;": " ",
  20843. "curvearrowleft;": "↶",
  20844. "DiacriticalDot;": "˙",
  20845. "doublebarwedge;": "⌆",
  20846. "DoubleRightTee;": "⊨",
  20847. "downdownarrows;": "⇊",
  20848. "DownLeftVector;": "↽",
  20849. "GreaterGreater;": "⪢",
  20850. "hookrightarrow;": "↪",
  20851. "HorizontalLine;": "─",
  20852. "InvisibleComma;": "⁣",
  20853. "InvisibleTimes;": "⁢",
  20854. "LeftDownVector;": "⇃",
  20855. "leftleftarrows;": "⇇",
  20856. "LeftRightArrow;": "↔",
  20857. "Leftrightarrow;": "⇔",
  20858. "leftrightarrow;": "↔",
  20859. "leftthreetimes;": "⋋",
  20860. "LessSlantEqual;": "⩽",
  20861. "LongRightArrow;": "⟶",
  20862. "Longrightarrow;": "⟹",
  20863. "longrightarrow;": "⟶",
  20864. "looparrowright;": "↬",
  20865. "LowerLeftArrow;": "↙",
  20866. "NestedLessLess;": "≪",
  20867. "NotGreaterLess;": "≹",
  20868. "NotLessGreater;": "≸",
  20869. "NotSubsetEqual;": "⊈",
  20870. "NotVerticalBar;": "∤",
  20871. "nshortparallel;": "∦",
  20872. "ntriangleright;": "⋫",
  20873. "OpenCurlyQuote;": "‘",
  20874. "ReverseElement;": "∋",
  20875. "rightarrowtail;": "↣",
  20876. "rightharpoonup;": "⇀",
  20877. "RightTeeVector;": "⥛",
  20878. "RightVectorBar;": "⥓",
  20879. "ShortDownArrow;": "↓",
  20880. "ShortLeftArrow;": "←",
  20881. "SquareSuperset;": "⊐",
  20882. "TildeFullEqual;": "≅",
  20883. "trianglelefteq;": "⊴",
  20884. "upharpoonright;": "↾",
  20885. "UpperLeftArrow;": "↖",
  20886. "ZeroWidthSpace;": "​",
  20887. "bigtriangledown;": "▽",
  20888. "circlearrowleft;": "↺",
  20889. "CloseCurlyQuote;": "’",
  20890. "ContourIntegral;": "∮",
  20891. "curvearrowright;": "↷",
  20892. "DoubleDownArrow;": "⇓",
  20893. "DoubleLeftArrow;": "⇐",
  20894. "downharpoonleft;": "⇃",
  20895. "DownRightVector;": "⇁",
  20896. "leftharpoondown;": "↽",
  20897. "leftrightarrows;": "⇆",
  20898. "LeftRightVector;": "⥎",
  20899. "LeftTriangleBar;": "⧏",
  20900. "LeftUpTeeVector;": "⥠",
  20901. "LeftUpVectorBar;": "⥘",
  20902. "LowerRightArrow;": "↘",
  20903. "nLeftrightarrow;": "⇎",
  20904. "nleftrightarrow;": "↮",
  20905. "NotGreaterEqual;": "≱",
  20906. "NotGreaterTilde;": "≵",
  20907. "NotHumpDownHump;": "≎̸",
  20908. "NotLeftTriangle;": "⋪",
  20909. "NotSquareSubset;": "⊏̸",
  20910. "ntrianglelefteq;": "⋬",
  20911. "OverParenthesis;": "⏜",
  20912. "RightDownVector;": "⇂",
  20913. "rightleftarrows;": "⇄",
  20914. "rightsquigarrow;": "↝",
  20915. "rightthreetimes;": "⋌",
  20916. "ShortRightArrow;": "→",
  20917. "straightepsilon;": "ϵ",
  20918. "trianglerighteq;": "⊵",
  20919. "UpperRightArrow;": "↗",
  20920. "vartriangleleft;": "⊲",
  20921. "circlearrowright;": "↻",
  20922. "DiacriticalAcute;": "´",
  20923. "DiacriticalGrave;": "`",
  20924. "DiacriticalTilde;": "˜",
  20925. "DoubleRightArrow;": "⇒",
  20926. "DownArrowUpArrow;": "⇵",
  20927. "downharpoonright;": "⇂",
  20928. "EmptySmallSquare;": "◻",
  20929. "GreaterEqualLess;": "⋛",
  20930. "GreaterFullEqual;": "≧",
  20931. "LeftAngleBracket;": "⟨",
  20932. "LeftUpDownVector;": "⥑",
  20933. "LessEqualGreater;": "⋚",
  20934. "NonBreakingSpace;": " ",
  20935. "NotPrecedesEqual;": "⪯̸",
  20936. "NotRightTriangle;": "⋫",
  20937. "NotSucceedsEqual;": "⪰̸",
  20938. "NotSucceedsTilde;": "≿̸",
  20939. "NotSupersetEqual;": "⊉",
  20940. "ntrianglerighteq;": "⋭",
  20941. "rightharpoondown;": "⇁",
  20942. "rightrightarrows;": "⇉",
  20943. "RightTriangleBar;": "⧐",
  20944. "RightUpTeeVector;": "⥜",
  20945. "RightUpVectorBar;": "⥔",
  20946. "twoheadleftarrow;": "↞",
  20947. "UnderParenthesis;": "⏝",
  20948. "UpArrowDownArrow;": "⇅",
  20949. "vartriangleright;": "⊳",
  20950. "blacktriangledown;": "▾",
  20951. "blacktriangleleft;": "◂",
  20952. "DoubleUpDownArrow;": "⇕",
  20953. "DoubleVerticalBar;": "∥",
  20954. "DownLeftTeeVector;": "⥞",
  20955. "DownLeftVectorBar;": "⥖",
  20956. "FilledSmallSquare;": "◼",
  20957. "GreaterSlantEqual;": "⩾",
  20958. "LeftDoubleBracket;": "⟦",
  20959. "LeftDownTeeVector;": "⥡",
  20960. "LeftDownVectorBar;": "⥙",
  20961. "leftrightharpoons;": "⇋",
  20962. "LeftTriangleEqual;": "⊴",
  20963. "NegativeThinSpace;": "​",
  20964. "NotGreaterGreater;": "≫̸",
  20965. "NotLessSlantEqual;": "⩽̸",
  20966. "NotNestedLessLess;": "⪡̸",
  20967. "NotReverseElement;": "∌",
  20968. "NotSquareSuperset;": "⊐̸",
  20969. "NotTildeFullEqual;": "≇",
  20970. "RightAngleBracket;": "⟩",
  20971. "rightleftharpoons;": "⇌",
  20972. "RightUpDownVector;": "⥏",
  20973. "SquareSubsetEqual;": "⊑",
  20974. "twoheadrightarrow;": "↠",
  20975. "VerticalSeparator;": "❘",
  20976. "blacktriangleright;": "▸",
  20977. "DownRightTeeVector;": "⥟",
  20978. "DownRightVectorBar;": "⥗",
  20979. "LongLeftRightArrow;": "⟷",
  20980. "Longleftrightarrow;": "⟺",
  20981. "longleftrightarrow;": "⟷",
  20982. "NegativeThickSpace;": "​",
  20983. "NotLeftTriangleBar;": "⧏̸",
  20984. "PrecedesSlantEqual;": "≼",
  20985. "ReverseEquilibrium;": "⇋",
  20986. "RightDoubleBracket;": "⟧",
  20987. "RightDownTeeVector;": "⥝",
  20988. "RightDownVectorBar;": "⥕",
  20989. "RightTriangleEqual;": "⊵",
  20990. "SquareIntersection;": "⊓",
  20991. "SucceedsSlantEqual;": "≽",
  20992. "DoubleLongLeftArrow;": "⟸",
  20993. "DownLeftRightVector;": "⥐",
  20994. "LeftArrowRightArrow;": "⇆",
  20995. "leftrightsquigarrow;": "↭",
  20996. "NegativeMediumSpace;": "​",
  20997. "NotGreaterFullEqual;": "≧̸",
  20998. "NotRightTriangleBar;": "⧐̸",
  20999. "RightArrowLeftArrow;": "⇄",
  21000. "SquareSupersetEqual;": "⊒",
  21001. "CapitalDifferentialD;": "ⅅ",
  21002. "DoubleLeftRightArrow;": "⇔",
  21003. "DoubleLongRightArrow;": "⟹",
  21004. "EmptyVerySmallSquare;": "▫",
  21005. "NestedGreaterGreater;": "≫",
  21006. "NotDoubleVerticalBar;": "∦",
  21007. "NotGreaterSlantEqual;": "⩾̸",
  21008. "NotLeftTriangleEqual;": "⋬",
  21009. "NotSquareSubsetEqual;": "⋢",
  21010. "OpenCurlyDoubleQuote;": "“",
  21011. "ReverseUpEquilibrium;": "⥯",
  21012. "CloseCurlyDoubleQuote;": "”",
  21013. "DoubleContourIntegral;": "∯",
  21014. "FilledVerySmallSquare;": "▪",
  21015. "NegativeVeryThinSpace;": "​",
  21016. "NotPrecedesSlantEqual;": "⋠",
  21017. "NotRightTriangleEqual;": "⋭",
  21018. "NotSucceedsSlantEqual;": "⋡",
  21019. "DiacriticalDoubleAcute;": "˝",
  21020. "NotSquareSupersetEqual;": "⋣",
  21021. "NotNestedGreaterGreater;": "⪢̸",
  21022. "ClockwiseContourIntegral;": "∲",
  21023. "DoubleLongLeftRightArrow;": "⟺",
  21024. "CounterClockwiseContourIntegral;": "∳"
  21025. };
  21026. // lazy compute this to make this file tree-shakable for browser
  21027. let maxCRNameLength;
  21028. const decodeHtml = (rawText, asAttr) => {
  21029. let offset = 0;
  21030. const end = rawText.length;
  21031. let decodedText = '';
  21032. function advance(length) {
  21033. offset += length;
  21034. rawText = rawText.slice(length);
  21035. }
  21036. while (offset < end) {
  21037. const head = /&(?:#x?)?/i.exec(rawText);
  21038. if (!head || offset + head.index >= end) {
  21039. const remaining = end - offset;
  21040. decodedText += rawText.slice(0, remaining);
  21041. advance(remaining);
  21042. break;
  21043. }
  21044. // Advance to the "&".
  21045. decodedText += rawText.slice(0, head.index);
  21046. advance(head.index);
  21047. if (head[0] === '&') {
  21048. // Named character reference.
  21049. let name = '';
  21050. let value = undefined;
  21051. if (/[0-9a-z]/i.test(rawText[1])) {
  21052. if (!maxCRNameLength) {
  21053. maxCRNameLength = Object.keys(namedCharacterReferences).reduce((max, name) => Math.max(max, name.length), 0);
  21054. }
  21055. for (let length = maxCRNameLength; !value && length > 0; --length) {
  21056. name = rawText.substr(1, length);
  21057. value = namedCharacterReferences[name];
  21058. }
  21059. if (value) {
  21060. const semi = name.endsWith(';');
  21061. if (asAttr &&
  21062. !semi &&
  21063. /[=a-z0-9]/i.test(rawText[name.length + 1] || '')) {
  21064. decodedText += '&' + name;
  21065. advance(1 + name.length);
  21066. }
  21067. else {
  21068. decodedText += value;
  21069. advance(1 + name.length);
  21070. }
  21071. }
  21072. else {
  21073. decodedText += '&' + name;
  21074. advance(1 + name.length);
  21075. }
  21076. }
  21077. else {
  21078. decodedText += '&';
  21079. advance(1);
  21080. }
  21081. }
  21082. else {
  21083. // Numeric character reference.
  21084. const hex = head[0] === '&#x';
  21085. const pattern = hex ? /^&#x([0-9a-f]+);?/i : /^&#([0-9]+);?/;
  21086. const body = pattern.exec(rawText);
  21087. if (!body) {
  21088. decodedText += head[0];
  21089. advance(head[0].length);
  21090. }
  21091. else {
  21092. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  21093. let cp = Number.parseInt(body[1], hex ? 16 : 10);
  21094. if (cp === 0) {
  21095. cp = 0xfffd;
  21096. }
  21097. else if (cp > 0x10ffff) {
  21098. cp = 0xfffd;
  21099. }
  21100. else if (cp >= 0xd800 && cp <= 0xdfff) {
  21101. cp = 0xfffd;
  21102. }
  21103. else if ((cp >= 0xfdd0 && cp <= 0xfdef) || (cp & 0xfffe) === 0xfffe) ;
  21104. else if ((cp >= 0x01 && cp <= 0x08) ||
  21105. cp === 0x0b ||
  21106. (cp >= 0x0d && cp <= 0x1f) ||
  21107. (cp >= 0x7f && cp <= 0x9f)) {
  21108. cp = CCR_REPLACEMENTS[cp] || cp;
  21109. }
  21110. decodedText += String.fromCodePoint(cp);
  21111. advance(body[0].length);
  21112. }
  21113. }
  21114. }
  21115. return decodedText;
  21116. };
  21117. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  21118. const CCR_REPLACEMENTS = {
  21119. 0x80: 0x20ac,
  21120. 0x82: 0x201a,
  21121. 0x83: 0x0192,
  21122. 0x84: 0x201e,
  21123. 0x85: 0x2026,
  21124. 0x86: 0x2020,
  21125. 0x87: 0x2021,
  21126. 0x88: 0x02c6,
  21127. 0x89: 0x2030,
  21128. 0x8a: 0x0160,
  21129. 0x8b: 0x2039,
  21130. 0x8c: 0x0152,
  21131. 0x8e: 0x017d,
  21132. 0x91: 0x2018,
  21133. 0x92: 0x2019,
  21134. 0x93: 0x201c,
  21135. 0x94: 0x201d,
  21136. 0x95: 0x2022,
  21137. 0x96: 0x2013,
  21138. 0x97: 0x2014,
  21139. 0x98: 0x02dc,
  21140. 0x99: 0x2122,
  21141. 0x9a: 0x0161,
  21142. 0x9b: 0x203a,
  21143. 0x9c: 0x0153,
  21144. 0x9e: 0x017e,
  21145. 0x9f: 0x0178
  21146. };
  21147. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  21148. const parserOptions = {
  21149. isVoidTag,
  21150. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  21151. isPreTag: tag => tag === 'pre',
  21152. decodeEntities: decodeHtml,
  21153. isBuiltInComponent: (tag) => {
  21154. if (isBuiltInType(tag, `Transition`)) {
  21155. return TRANSITION;
  21156. }
  21157. else if (isBuiltInType(tag, `TransitionGroup`)) {
  21158. return TRANSITION_GROUP;
  21159. }
  21160. },
  21161. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  21162. getNamespace(tag, parent) {
  21163. let ns = parent ? parent.ns : 0 /* HTML */;
  21164. if (parent && ns === 2 /* MATH_ML */) {
  21165. if (parent.tag === 'annotation-xml') {
  21166. if (tag === 'svg') {
  21167. return 1 /* SVG */;
  21168. }
  21169. if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
  21170. a.name === 'encoding' &&
  21171. a.value != null &&
  21172. (a.value.content === 'text/html' ||
  21173. a.value.content === 'application/xhtml+xml'))) {
  21174. ns = 0 /* HTML */;
  21175. }
  21176. }
  21177. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  21178. tag !== 'mglyph' &&
  21179. tag !== 'malignmark') {
  21180. ns = 0 /* HTML */;
  21181. }
  21182. }
  21183. else if (parent && ns === 1 /* SVG */) {
  21184. if (parent.tag === 'foreignObject' ||
  21185. parent.tag === 'desc' ||
  21186. parent.tag === 'title') {
  21187. ns = 0 /* HTML */;
  21188. }
  21189. }
  21190. if (ns === 0 /* HTML */) {
  21191. if (tag === 'svg') {
  21192. return 1 /* SVG */;
  21193. }
  21194. if (tag === 'math') {
  21195. return 2 /* MATH_ML */;
  21196. }
  21197. }
  21198. return ns;
  21199. },
  21200. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  21201. getTextMode({ tag, ns }) {
  21202. if (ns === 0 /* HTML */) {
  21203. if (tag === 'textarea' || tag === 'title') {
  21204. return 1 /* RCDATA */;
  21205. }
  21206. if (isRawTextContainer(tag)) {
  21207. return 2 /* RAWTEXT */;
  21208. }
  21209. }
  21210. return 0 /* DATA */;
  21211. }
  21212. };
  21213. // Parse inline CSS strings for static style attributes into an object.
  21214. // This is a NodeTransform since it works on the static `style` attribute and
  21215. // converts it into a dynamic equivalent:
  21216. // style="color: red" -> :style='{ "color": "red" }'
  21217. // It is then processed by `transformElement` and included in the generated
  21218. // props.
  21219. const transformStyle = node => {
  21220. if (node.type === 1 /* ELEMENT */) {
  21221. node.props.forEach((p, i) => {
  21222. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  21223. // replace p with an expression node
  21224. node.props[i] = {
  21225. type: 7 /* DIRECTIVE */,
  21226. name: `bind`,
  21227. arg: createSimpleExpression(`style`, true, p.loc),
  21228. exp: parseInlineCSS(p.value.content, p.loc),
  21229. modifiers: [],
  21230. loc: p.loc
  21231. };
  21232. }
  21233. });
  21234. }
  21235. };
  21236. const parseInlineCSS = (cssText, loc) => {
  21237. const normalized = parseStringStyle(cssText);
  21238. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
  21239. };
  21240. function createDOMCompilerError(code, loc) {
  21241. return createCompilerError(code, loc, DOMErrorMessages );
  21242. }
  21243. const DOMErrorMessages = {
  21244. [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  21245. [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  21246. [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  21247. [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  21248. [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  21249. [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  21250. [55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  21251. [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  21252. [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  21253. [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  21254. [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  21255. };
  21256. const transformVHtml = (dir, node, context) => {
  21257. const { exp, loc } = dir;
  21258. if (!exp) {
  21259. context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
  21260. }
  21261. if (node.children.length) {
  21262. context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
  21263. node.children.length = 0;
  21264. }
  21265. return {
  21266. props: [
  21267. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  21268. ]
  21269. };
  21270. };
  21271. const transformVText = (dir, node, context) => {
  21272. const { exp, loc } = dir;
  21273. if (!exp) {
  21274. context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
  21275. }
  21276. if (node.children.length) {
  21277. context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
  21278. node.children.length = 0;
  21279. }
  21280. return {
  21281. props: [
  21282. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  21283. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  21284. : createSimpleExpression('', true))
  21285. ]
  21286. };
  21287. };
  21288. const transformModel$1 = (dir, node, context) => {
  21289. const baseResult = transformModel(dir, node, context);
  21290. // base transform has errors OR component v-model (only need props)
  21291. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  21292. return baseResult;
  21293. }
  21294. if (dir.arg) {
  21295. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  21296. }
  21297. function checkDuplicatedValue() {
  21298. const value = findProp(node, 'value');
  21299. if (value) {
  21300. context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  21301. }
  21302. }
  21303. const { tag } = node;
  21304. const isCustomElement = context.isCustomElement(tag);
  21305. if (tag === 'input' ||
  21306. tag === 'textarea' ||
  21307. tag === 'select' ||
  21308. isCustomElement) {
  21309. let directiveToUse = V_MODEL_TEXT;
  21310. let isInvalidType = false;
  21311. if (tag === 'input' || isCustomElement) {
  21312. const type = findProp(node, `type`);
  21313. if (type) {
  21314. if (type.type === 7 /* DIRECTIVE */) {
  21315. // :type="foo"
  21316. directiveToUse = V_MODEL_DYNAMIC;
  21317. }
  21318. else if (type.value) {
  21319. switch (type.value.content) {
  21320. case 'radio':
  21321. directiveToUse = V_MODEL_RADIO;
  21322. break;
  21323. case 'checkbox':
  21324. directiveToUse = V_MODEL_CHECKBOX;
  21325. break;
  21326. case 'file':
  21327. isInvalidType = true;
  21328. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  21329. break;
  21330. default:
  21331. // text type
  21332. checkDuplicatedValue();
  21333. break;
  21334. }
  21335. }
  21336. }
  21337. else if (hasDynamicKeyVBind(node)) {
  21338. // element has bindings with dynamic keys, which can possibly contain
  21339. // "type".
  21340. directiveToUse = V_MODEL_DYNAMIC;
  21341. }
  21342. else {
  21343. // text type
  21344. checkDuplicatedValue();
  21345. }
  21346. }
  21347. else if (tag === 'select') {
  21348. directiveToUse = V_MODEL_SELECT;
  21349. }
  21350. else {
  21351. // textarea
  21352. checkDuplicatedValue();
  21353. }
  21354. // inject runtime directive
  21355. // by returning the helper symbol via needRuntime
  21356. // the import will replaced a resolveDirective call.
  21357. if (!isInvalidType) {
  21358. baseResult.needRuntime = context.helper(directiveToUse);
  21359. }
  21360. }
  21361. else {
  21362. context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  21363. }
  21364. // native vmodel doesn't need the `modelValue` props since they are also
  21365. // passed to the runtime as `binding.value`. removing it reduces code size.
  21366. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  21367. p.key.content === 'modelValue'));
  21368. return baseResult;
  21369. };
  21370. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  21371. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  21372. // event propagation management
  21373. `stop,prevent,self,` +
  21374. // system modifiers + exact
  21375. `ctrl,shift,alt,meta,exact,` +
  21376. // mouse
  21377. `middle`);
  21378. // left & right could be mouse or key modifiers based on event type
  21379. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  21380. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  21381. const resolveModifiers = (key, modifiers) => {
  21382. const keyModifiers = [];
  21383. const nonKeyModifiers = [];
  21384. const eventOptionModifiers = [];
  21385. for (let i = 0; i < modifiers.length; i++) {
  21386. const modifier = modifiers[i];
  21387. if (isEventOptionModifier(modifier)) {
  21388. // eventOptionModifiers: modifiers for addEventListener() options,
  21389. // e.g. .passive & .capture
  21390. eventOptionModifiers.push(modifier);
  21391. }
  21392. else {
  21393. // runtimeModifiers: modifiers that needs runtime guards
  21394. if (maybeKeyModifier(modifier)) {
  21395. if (isStaticExp(key)) {
  21396. if (isKeyboardEvent(key.content)) {
  21397. keyModifiers.push(modifier);
  21398. }
  21399. else {
  21400. nonKeyModifiers.push(modifier);
  21401. }
  21402. }
  21403. else {
  21404. keyModifiers.push(modifier);
  21405. nonKeyModifiers.push(modifier);
  21406. }
  21407. }
  21408. else {
  21409. if (isNonKeyModifier(modifier)) {
  21410. nonKeyModifiers.push(modifier);
  21411. }
  21412. else {
  21413. keyModifiers.push(modifier);
  21414. }
  21415. }
  21416. }
  21417. }
  21418. return {
  21419. keyModifiers,
  21420. nonKeyModifiers,
  21421. eventOptionModifiers
  21422. };
  21423. };
  21424. const transformClick = (key, event) => {
  21425. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  21426. return isStaticClick
  21427. ? createSimpleExpression(event, true)
  21428. : key.type !== 4 /* SIMPLE_EXPRESSION */
  21429. ? createCompoundExpression([
  21430. `(`,
  21431. key,
  21432. `) === "onClick" ? "${event}" : (`,
  21433. key,
  21434. `)`
  21435. ])
  21436. : key;
  21437. };
  21438. const transformOn$1 = (dir, node, context) => {
  21439. return transformOn(dir, node, context, baseResult => {
  21440. const { modifiers } = dir;
  21441. if (!modifiers.length)
  21442. return baseResult;
  21443. let { key, value: handlerExp } = baseResult.props[0];
  21444. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
  21445. // normalize click.right and click.middle since they don't actually fire
  21446. if (nonKeyModifiers.includes('right')) {
  21447. key = transformClick(key, `onContextmenu`);
  21448. }
  21449. if (nonKeyModifiers.includes('middle')) {
  21450. key = transformClick(key, `onMouseup`);
  21451. }
  21452. if (nonKeyModifiers.length) {
  21453. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  21454. handlerExp,
  21455. JSON.stringify(nonKeyModifiers)
  21456. ]);
  21457. }
  21458. if (keyModifiers.length &&
  21459. // if event name is dynamic, always wrap with keys guard
  21460. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  21461. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  21462. handlerExp,
  21463. JSON.stringify(keyModifiers)
  21464. ]);
  21465. }
  21466. if (eventOptionModifiers.length) {
  21467. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  21468. key = isStaticExp(key)
  21469. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  21470. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  21471. }
  21472. return {
  21473. props: [createObjectProperty(key, handlerExp)]
  21474. };
  21475. });
  21476. };
  21477. const transformShow = (dir, node, context) => {
  21478. const { exp, loc } = dir;
  21479. if (!exp) {
  21480. context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
  21481. }
  21482. return {
  21483. props: [],
  21484. needRuntime: context.helper(V_SHOW)
  21485. };
  21486. };
  21487. const warnTransitionChildren = (node, context) => {
  21488. if (node.type === 1 /* ELEMENT */ &&
  21489. node.tagType === 1 /* COMPONENT */) {
  21490. const component = context.isBuiltInComponent(node.tag);
  21491. if (component === TRANSITION) {
  21492. return () => {
  21493. if (node.children.length && hasMultipleChildren(node)) {
  21494. context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
  21495. start: node.children[0].loc.start,
  21496. end: node.children[node.children.length - 1].loc.end,
  21497. source: ''
  21498. }));
  21499. }
  21500. };
  21501. }
  21502. }
  21503. };
  21504. function hasMultipleChildren(node) {
  21505. // #1352 filter out potential comment nodes.
  21506. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
  21507. const child = children[0];
  21508. return (children.length !== 1 ||
  21509. child.type === 11 /* FOR */ ||
  21510. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  21511. }
  21512. /**
  21513. * This module is Node-only.
  21514. */
  21515. /**
  21516. * Turn eligible hoisted static trees into stringified static nodes, e.g.
  21517. *
  21518. * ```js
  21519. * const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`)
  21520. * ```
  21521. *
  21522. * A single static vnode can contain stringified content for **multiple**
  21523. * consecutive nodes (element and plain text), called a "chunk".
  21524. * `@vue/runtime-dom` will create the content via innerHTML in a hidden
  21525. * container element and insert all the nodes in place. The call must also
  21526. * provide the number of nodes contained in the chunk so that during hydration
  21527. * we can know how many nodes the static vnode should adopt.
  21528. *
  21529. * The optimization scans a children list that contains hoisted nodes, and
  21530. * tries to find the largest chunk of consecutive hoisted nodes before running
  21531. * into a non-hoisted node or the end of the list. A chunk is then converted
  21532. * into a single static vnode and replaces the hoisted expression of the first
  21533. * node in the chunk. Other nodes in the chunk are considered "merged" and
  21534. * therefore removed from both the hoist list and the children array.
  21535. *
  21536. * This optimization is only performed in Node.js.
  21537. */
  21538. const stringifyStatic = (children, context, parent) => {
  21539. if (parent.type === 1 /* ELEMENT */ &&
  21540. (parent.tagType === 1 /* COMPONENT */ ||
  21541. parent.tagType === 3 /* TEMPLATE */)) {
  21542. return;
  21543. }
  21544. let nc = 0; // current node count
  21545. let ec = 0; // current element with binding count
  21546. const currentChunk = [];
  21547. const stringifyCurrentChunk = (currentIndex) => {
  21548. if (nc >= 20 /* NODE_COUNT */ ||
  21549. ec >= 5 /* ELEMENT_WITH_BINDING_COUNT */) {
  21550. // combine all currently eligible nodes into a single static vnode call
  21551. const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
  21552. JSON.stringify(currentChunk.map(node => stringifyNode(node, context)).join('')),
  21553. // the 2nd argument indicates the number of DOM nodes this static vnode
  21554. // will insert / hydrate
  21555. String(currentChunk.length)
  21556. ]);
  21557. // replace the first node's hoisted expression with the static vnode call
  21558. replaceHoist(currentChunk[0], staticCall, context);
  21559. if (currentChunk.length > 1) {
  21560. for (let i = 1; i < currentChunk.length; i++) {
  21561. // for the merged nodes, set their hoisted expression to null
  21562. replaceHoist(currentChunk[i], null, context);
  21563. }
  21564. // also remove merged nodes from children
  21565. const deleteCount = currentChunk.length - 1;
  21566. children.splice(currentIndex - currentChunk.length + 1, deleteCount);
  21567. return deleteCount;
  21568. }
  21569. }
  21570. return 0;
  21571. };
  21572. let i = 0;
  21573. for (; i < children.length; i++) {
  21574. const child = children[i];
  21575. const hoisted = getHoistedNode(child);
  21576. if (hoisted) {
  21577. // presence of hoisted means child must be a stringifiable node
  21578. const node = child;
  21579. const result = analyzeNode(node);
  21580. if (result) {
  21581. // node is stringifiable, record state
  21582. nc += result[0];
  21583. ec += result[1];
  21584. currentChunk.push(node);
  21585. continue;
  21586. }
  21587. }
  21588. // we only reach here if we ran into a node that is not stringifiable
  21589. // check if currently analyzed nodes meet criteria for stringification.
  21590. // adjust iteration index
  21591. i -= stringifyCurrentChunk(i);
  21592. // reset state
  21593. nc = 0;
  21594. ec = 0;
  21595. currentChunk.length = 0;
  21596. }
  21597. // in case the last node was also stringifiable
  21598. stringifyCurrentChunk(i);
  21599. };
  21600. const getHoistedNode = (node) => ((node.type === 1 /* ELEMENT */ && node.tagType === 0 /* ELEMENT */) ||
  21601. node.type == 12 /* TEXT_CALL */) &&
  21602. node.codegenNode &&
  21603. node.codegenNode.type === 4 /* SIMPLE_EXPRESSION */ &&
  21604. node.codegenNode.hoisted;
  21605. const dataAriaRE = /^(data|aria)-/;
  21606. const isStringifiableAttr = (name) => {
  21607. return isKnownAttr(name) || dataAriaRE.test(name);
  21608. };
  21609. const replaceHoist = (node, replacement, context) => {
  21610. const hoistToReplace = node.codegenNode.hoisted;
  21611. context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement;
  21612. };
  21613. const isNonStringifiable = /*#__PURE__*/ makeMap(`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`);
  21614. /**
  21615. * for a hoisted node, analyze it and return:
  21616. * - false: bailed (contains runtime constant)
  21617. * - [nc, ec] where
  21618. * - nc is the number of nodes inside
  21619. * - ec is the number of element with bindings inside
  21620. */
  21621. function analyzeNode(node) {
  21622. if (node.type === 1 /* ELEMENT */ && isNonStringifiable(node.tag)) {
  21623. return false;
  21624. }
  21625. if (node.type === 12 /* TEXT_CALL */) {
  21626. return [1, 0];
  21627. }
  21628. let nc = 1; // node count
  21629. let ec = node.props.length > 0 ? 1 : 0; // element w/ binding count
  21630. let bailed = false;
  21631. const bail = () => {
  21632. bailed = true;
  21633. return false;
  21634. };
  21635. // TODO: check for cases where using innerHTML will result in different
  21636. // output compared to imperative node insertions.
  21637. // probably only need to check for most common case
  21638. // i.e. non-phrasing-content tags inside `<p>`
  21639. function walk(node) {
  21640. for (let i = 0; i < node.props.length; i++) {
  21641. const p = node.props[i];
  21642. // bail on non-attr bindings
  21643. if (p.type === 6 /* ATTRIBUTE */ && !isStringifiableAttr(p.name)) {
  21644. return bail();
  21645. }
  21646. if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind') {
  21647. // bail on non-attr bindings
  21648. if (p.arg &&
  21649. (p.arg.type === 8 /* COMPOUND_EXPRESSION */ ||
  21650. (p.arg.isStatic && !isStringifiableAttr(p.arg.content)))) {
  21651. return bail();
  21652. }
  21653. }
  21654. }
  21655. for (let i = 0; i < node.children.length; i++) {
  21656. nc++;
  21657. const child = node.children[i];
  21658. if (child.type === 1 /* ELEMENT */) {
  21659. if (child.props.length > 0) {
  21660. ec++;
  21661. }
  21662. walk(child);
  21663. if (bailed) {
  21664. return false;
  21665. }
  21666. }
  21667. }
  21668. return true;
  21669. }
  21670. return walk(node) ? [nc, ec] : false;
  21671. }
  21672. function stringifyNode(node, context) {
  21673. if (isString(node)) {
  21674. return node;
  21675. }
  21676. if (isSymbol(node)) {
  21677. return ``;
  21678. }
  21679. switch (node.type) {
  21680. case 1 /* ELEMENT */:
  21681. return stringifyElement(node, context);
  21682. case 2 /* TEXT */:
  21683. return escapeHtml(node.content);
  21684. case 3 /* COMMENT */:
  21685. return `<!--${escapeHtml(node.content)}-->`;
  21686. case 5 /* INTERPOLATION */:
  21687. return escapeHtml(toDisplayString(evaluateConstant(node.content)));
  21688. case 8 /* COMPOUND_EXPRESSION */:
  21689. return escapeHtml(evaluateConstant(node));
  21690. case 12 /* TEXT_CALL */:
  21691. return stringifyNode(node.content, context);
  21692. default:
  21693. // static trees will not contain if/for nodes
  21694. return '';
  21695. }
  21696. }
  21697. function stringifyElement(node, context) {
  21698. let res = `<${node.tag}`;
  21699. for (let i = 0; i < node.props.length; i++) {
  21700. const p = node.props[i];
  21701. if (p.type === 6 /* ATTRIBUTE */) {
  21702. res += ` ${p.name}`;
  21703. if (p.value) {
  21704. res += `="${escapeHtml(p.value.content)}"`;
  21705. }
  21706. }
  21707. else if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind') {
  21708. // constant v-bind, e.g. :foo="1"
  21709. let evaluated = evaluateConstant(p.exp);
  21710. const arg = p.arg && p.arg.content;
  21711. if (arg === 'class') {
  21712. evaluated = normalizeClass(evaluated);
  21713. }
  21714. else if (arg === 'style') {
  21715. evaluated = stringifyStyle(normalizeStyle(evaluated));
  21716. }
  21717. res += ` ${p.arg.content}="${escapeHtml(evaluated)}"`;
  21718. }
  21719. }
  21720. if (context.scopeId) {
  21721. res += ` ${context.scopeId}`;
  21722. }
  21723. res += `>`;
  21724. for (let i = 0; i < node.children.length; i++) {
  21725. res += stringifyNode(node.children[i], context);
  21726. }
  21727. if (!isVoidTag(node.tag)) {
  21728. res += `</${node.tag}>`;
  21729. }
  21730. return res;
  21731. }
  21732. // __UNSAFE__
  21733. // Reason: eval.
  21734. // It's technically safe to eval because only constant expressions are possible
  21735. // here, e.g. `{{ 1 }}` or `{{ 'foo' }}`
  21736. // in addition, constant exps bail on presence of parens so you can't even
  21737. // run JSFuck in here. But we mark it unsafe for security review purposes.
  21738. // (see compiler-core/src/transformExpressions)
  21739. function evaluateConstant(exp) {
  21740. if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  21741. return new Function(`return ${exp.content}`)();
  21742. }
  21743. else {
  21744. // compound
  21745. let res = ``;
  21746. exp.children.forEach(c => {
  21747. if (isString(c) || isSymbol(c)) {
  21748. return;
  21749. }
  21750. if (c.type === 2 /* TEXT */) {
  21751. res += c.content;
  21752. }
  21753. else if (c.type === 5 /* INTERPOLATION */) {
  21754. res += toDisplayString(evaluateConstant(c.content));
  21755. }
  21756. else {
  21757. res += evaluateConstant(c);
  21758. }
  21759. });
  21760. return res;
  21761. }
  21762. }
  21763. const ignoreSideEffectTags = (node, context) => {
  21764. if (node.type === 1 /* ELEMENT */ &&
  21765. node.tagType === 0 /* ELEMENT */ &&
  21766. (node.tag === 'script' || node.tag === 'style')) {
  21767. context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  21768. context.removeNode();
  21769. }
  21770. };
  21771. const DOMNodeTransforms = [
  21772. transformStyle,
  21773. ...([warnTransitionChildren] )
  21774. ];
  21775. const DOMDirectiveTransforms = {
  21776. cloak: noopDirectiveTransform,
  21777. html: transformVHtml,
  21778. text: transformVText,
  21779. model: transformModel$1,
  21780. on: transformOn$1,
  21781. show: transformShow
  21782. };
  21783. function compile(template, options = {}) {
  21784. return baseCompile(template, extend({}, parserOptions, options, {
  21785. nodeTransforms: [
  21786. // ignore <script> and <tag>
  21787. // this is not put inside DOMNodeTransforms because that list is used
  21788. // by compiler-ssr to generate vnode fallback branches
  21789. ignoreSideEffectTags,
  21790. ...DOMNodeTransforms,
  21791. ...(options.nodeTransforms || [])
  21792. ],
  21793. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  21794. transformHoist: stringifyStatic
  21795. }));
  21796. }
  21797. function parse$1(template, options = {}) {
  21798. return baseParse(template, extend({}, parserOptions, options));
  21799. }
  21800. var CompilerDOM = /*#__PURE__*/Object.freeze({
  21801. __proto__: null,
  21802. parserOptions: parserOptions,
  21803. DOMNodeTransforms: DOMNodeTransforms,
  21804. DOMDirectiveTransforms: DOMDirectiveTransforms,
  21805. compile: compile,
  21806. parse: parse$1,
  21807. transformStyle: transformStyle,
  21808. createDOMCompilerError: createDOMCompilerError,
  21809. V_MODEL_RADIO: V_MODEL_RADIO,
  21810. V_MODEL_CHECKBOX: V_MODEL_CHECKBOX,
  21811. V_MODEL_TEXT: V_MODEL_TEXT,
  21812. V_MODEL_SELECT: V_MODEL_SELECT,
  21813. V_MODEL_DYNAMIC: V_MODEL_DYNAMIC,
  21814. V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS,
  21815. V_ON_WITH_KEYS: V_ON_WITH_KEYS,
  21816. V_SHOW: V_SHOW,
  21817. TRANSITION: TRANSITION,
  21818. TRANSITION_GROUP: TRANSITION_GROUP,
  21819. baseCompile: baseCompile,
  21820. baseParse: baseParse,
  21821. transform: transform,
  21822. createTransformContext: createTransformContext,
  21823. traverseNode: traverseNode,
  21824. createStructuralDirectiveTransform: createStructuralDirectiveTransform,
  21825. generate: generate,
  21826. createCompilerError: createCompilerError,
  21827. getBaseTransformPreset: getBaseTransformPreset,
  21828. transformModel: transformModel,
  21829. transformOn: transformOn,
  21830. transformBind: transformBind,
  21831. noopDirectiveTransform: noopDirectiveTransform,
  21832. processIf: processIf,
  21833. processFor: processFor,
  21834. createForLoopParams: createForLoopParams,
  21835. transformExpression: transformExpression,
  21836. processExpression: processExpression,
  21837. buildSlots: buildSlots,
  21838. trackVForSlotScopes: trackVForSlotScopes,
  21839. trackSlotScopes: trackSlotScopes,
  21840. transformElement: transformElement,
  21841. resolveComponentType: resolveComponentType,
  21842. buildProps: buildProps,
  21843. processSlotOutlet: processSlotOutlet,
  21844. generateCodeFrame: generateCodeFrame,
  21845. locStub: locStub,
  21846. createRoot: createRoot,
  21847. createVNodeCall: createVNodeCall,
  21848. createArrayExpression: createArrayExpression,
  21849. createObjectExpression: createObjectExpression,
  21850. createObjectProperty: createObjectProperty,
  21851. createSimpleExpression: createSimpleExpression,
  21852. createInterpolation: createInterpolation,
  21853. createCompoundExpression: createCompoundExpression,
  21854. createCallExpression: createCallExpression,
  21855. createFunctionExpression: createFunctionExpression,
  21856. createConditionalExpression: createConditionalExpression,
  21857. createCacheExpression: createCacheExpression,
  21858. createBlockStatement: createBlockStatement,
  21859. createTemplateLiteral: createTemplateLiteral,
  21860. createIfStatement: createIfStatement,
  21861. createAssignmentExpression: createAssignmentExpression,
  21862. createSequenceExpression: createSequenceExpression,
  21863. createReturnStatement: createReturnStatement,
  21864. isStaticExp: isStaticExp,
  21865. isBuiltInType: isBuiltInType,
  21866. isCoreComponent: isCoreComponent,
  21867. isSimpleIdentifier: isSimpleIdentifier,
  21868. isMemberExpression: isMemberExpression,
  21869. getInnerRange: getInnerRange,
  21870. advancePositionWithClone: advancePositionWithClone,
  21871. advancePositionWithMutation: advancePositionWithMutation,
  21872. assert: assert,
  21873. findDir: findDir,
  21874. findProp: findProp,
  21875. isBindKey: isBindKey,
  21876. hasDynamicKeyVBind: hasDynamicKeyVBind,
  21877. isText: isText,
  21878. isVSlot: isVSlot,
  21879. isTemplateNode: isTemplateNode,
  21880. isSlotOutlet: isSlotOutlet,
  21881. injectProp: injectProp,
  21882. toValidAssetId: toValidAssetId,
  21883. hasScopeRef: hasScopeRef,
  21884. FRAGMENT: FRAGMENT,
  21885. TELEPORT: TELEPORT,
  21886. SUSPENSE: SUSPENSE,
  21887. KEEP_ALIVE: KEEP_ALIVE,
  21888. BASE_TRANSITION: BASE_TRANSITION,
  21889. OPEN_BLOCK: OPEN_BLOCK,
  21890. CREATE_BLOCK: CREATE_BLOCK,
  21891. CREATE_VNODE: CREATE_VNODE,
  21892. CREATE_COMMENT: CREATE_COMMENT,
  21893. CREATE_TEXT: CREATE_TEXT,
  21894. CREATE_STATIC: CREATE_STATIC,
  21895. RESOLVE_COMPONENT: RESOLVE_COMPONENT,
  21896. RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT,
  21897. RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE,
  21898. WITH_DIRECTIVES: WITH_DIRECTIVES,
  21899. RENDER_LIST: RENDER_LIST,
  21900. RENDER_SLOT: RENDER_SLOT,
  21901. CREATE_SLOTS: CREATE_SLOTS,
  21902. TO_DISPLAY_STRING: TO_DISPLAY_STRING,
  21903. MERGE_PROPS: MERGE_PROPS,
  21904. TO_HANDLERS: TO_HANDLERS,
  21905. CAMELIZE: CAMELIZE,
  21906. CAPITALIZE: CAPITALIZE,
  21907. TO_HANDLER_KEY: TO_HANDLER_KEY,
  21908. SET_BLOCK_TRACKING: SET_BLOCK_TRACKING,
  21909. PUSH_SCOPE_ID: PUSH_SCOPE_ID,
  21910. POP_SCOPE_ID: POP_SCOPE_ID,
  21911. WITH_SCOPE_ID: WITH_SCOPE_ID,
  21912. WITH_CTX: WITH_CTX,
  21913. UNREF: UNREF,
  21914. IS_REF: IS_REF,
  21915. helperNameMap: helperNameMap,
  21916. registerRuntimeHelpers: registerRuntimeHelpers
  21917. });
  21918. function pad (hash, len) {
  21919. while (hash.length < len) {
  21920. hash = '0' + hash;
  21921. }
  21922. return hash;
  21923. }
  21924. function fold (hash, text) {
  21925. var i;
  21926. var chr;
  21927. var len;
  21928. if (text.length === 0) {
  21929. return hash;
  21930. }
  21931. for (i = 0, len = text.length; i < len; i++) {
  21932. chr = text.charCodeAt(i);
  21933. hash = ((hash << 5) - hash) + chr;
  21934. hash |= 0;
  21935. }
  21936. return hash < 0 ? hash * -2 : hash;
  21937. }
  21938. function foldObject (hash, o, seen) {
  21939. return Object.keys(o).sort().reduce(foldKey, hash);
  21940. function foldKey (hash, key) {
  21941. return foldValue(hash, o[key], key, seen);
  21942. }
  21943. }
  21944. function foldValue (input, value, key, seen) {
  21945. var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  21946. if (value === null) {
  21947. return fold(hash, 'null');
  21948. }
  21949. if (value === undefined) {
  21950. return fold(hash, 'undefined');
  21951. }
  21952. if (typeof value === 'object' || typeof value === 'function') {
  21953. if (seen.indexOf(value) !== -1) {
  21954. return fold(hash, '[Circular]' + key);
  21955. }
  21956. seen.push(value);
  21957. var objHash = foldObject(hash, value, seen);
  21958. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  21959. return objHash;
  21960. }
  21961. try {
  21962. return fold(objHash, String(value.valueOf()))
  21963. } catch (err) {
  21964. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  21965. }
  21966. }
  21967. return fold(hash, value.toString());
  21968. }
  21969. function toString (o) {
  21970. return Object.prototype.toString.call(o);
  21971. }
  21972. function sum (o) {
  21973. return pad(foldValue(0, o, '', []).toString(16), 8);
  21974. }
  21975. var hashSum = sum;
  21976. const CSS_VARS_HELPER = `useCssVars`;
  21977. const cssVarRE = /\bv-bind\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^)]*))\s*\)/g;
  21978. function genCssVarsFromList(vars, id, isProd) {
  21979. return `{\n ${vars
  21980. .map(key => `"${genVarName(id, key, isProd)}": (${key})`)
  21981. .join(',\n ')}\n}`;
  21982. }
  21983. function genVarName(id, raw, isProd) {
  21984. if (isProd) {
  21985. return hashSum(id + raw);
  21986. }
  21987. else {
  21988. return `${id}-${raw.replace(/([^\w-])/g, '_')}`;
  21989. }
  21990. }
  21991. function parseCssVars(sfc) {
  21992. const vars = [];
  21993. sfc.styles.forEach(style => {
  21994. let match;
  21995. while ((match = cssVarRE.exec(style.content))) {
  21996. vars.push(match[1] || match[2] || match[3]);
  21997. }
  21998. });
  21999. return vars;
  22000. }
  22001. const cssVarsPlugin = opts => {
  22002. const { id, isProd } = opts;
  22003. return {
  22004. postcssPlugin: 'vue-sfc-vars',
  22005. Declaration(decl) {
  22006. // rewrite CSS variables
  22007. if (cssVarRE.test(decl.value)) {
  22008. decl.value = decl.value.replace(cssVarRE, (_, $1, $2, $3) => {
  22009. return `var(--${genVarName(id, $1 || $2 || $3, isProd)})`;
  22010. });
  22011. }
  22012. }
  22013. };
  22014. };
  22015. cssVarsPlugin.postcss = true;
  22016. function genCssVarsCode(vars, bindings, id, isProd) {
  22017. const varsExp = genCssVarsFromList(vars, id, isProd);
  22018. const exp = createSimpleExpression(varsExp, false);
  22019. const context = createTransformContext(createRoot([]), {
  22020. prefixIdentifiers: true,
  22021. inline: true,
  22022. bindingMetadata: bindings
  22023. });
  22024. const transformed = processExpression(exp, context);
  22025. const transformedString = transformed.type === 4 /* SIMPLE_EXPRESSION */
  22026. ? transformed.content
  22027. : transformed.children
  22028. .map(c => {
  22029. return typeof c === 'string'
  22030. ? c
  22031. : c.content;
  22032. })
  22033. .join('');
  22034. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  22035. }
  22036. // <script setup> already gets the calls injected as part of the transform
  22037. // this is only for single normal <script>
  22038. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd) {
  22039. return (`\nimport { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'\n` +
  22040. `const __injectCSSVars__ = () => {\n${genCssVarsCode(cssVars, bindings, id, isProd)}}\n` +
  22041. `const __setup__ = __default__.setup\n` +
  22042. `__default__.setup = __setup__\n` +
  22043. ` ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }\n` +
  22044. ` : __injectCSSVars__\n`);
  22045. }
  22046. const hasWarned = {};
  22047. function warnOnce(msg) {
  22048. const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
  22049. if (!isNodeProd && !false && !hasWarned[msg]) {
  22050. hasWarned[msg] = true;
  22051. warn(msg);
  22052. }
  22053. }
  22054. function warn(msg) {
  22055. console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  22056. }
  22057. function warnExperimental(feature, rfcId) {
  22058. warnOnce(`${feature} is still an experimental proposal.\n` +
  22059. `Follow its status at https://github.com/vuejs/rfcs/pull/${rfcId}.`);
  22060. warnOnce(`When using experimental features,\n` +
  22061. `it is recommended to pin your vue dependencies to exact versions to avoid breakage.`);
  22062. }
  22063. const sourceToSFC = new Map()
  22064. ;
  22065. function parse$2(source, { sourceMap = true, filename = 'anonymous.vue', sourceRoot = '', pad = false, compiler = CompilerDOM } = {}) {
  22066. const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
  22067. const cache = sourceToSFC.get(sourceKey);
  22068. if (cache) {
  22069. return cache;
  22070. }
  22071. const descriptor = {
  22072. filename,
  22073. source,
  22074. template: null,
  22075. script: null,
  22076. scriptSetup: null,
  22077. styles: [],
  22078. customBlocks: [],
  22079. cssVars: []
  22080. };
  22081. const errors = [];
  22082. const ast = compiler.parse(source, {
  22083. // there are no components at SFC parsing level
  22084. isNativeTag: () => true,
  22085. // preserve all whitespaces
  22086. isPreTag: () => true,
  22087. getTextMode: ({ tag, props }, parent) => {
  22088. // all top level elements except <template> are parsed as raw text
  22089. // containers
  22090. if ((!parent && tag !== 'template') ||
  22091. // <template lang="xxx"> should also be treated as raw text
  22092. (tag === 'template' &&
  22093. props.some(p => p.type === 6 /* ATTRIBUTE */ &&
  22094. p.name === 'lang' &&
  22095. p.value &&
  22096. p.value.content &&
  22097. p.value.content !== 'html'))) {
  22098. return 2 /* RAWTEXT */;
  22099. }
  22100. else {
  22101. return 0 /* DATA */;
  22102. }
  22103. },
  22104. onError: e => {
  22105. errors.push(e);
  22106. }
  22107. });
  22108. ast.children.forEach(node => {
  22109. if (node.type !== 1 /* ELEMENT */) {
  22110. return;
  22111. }
  22112. if (!node.children.length && !hasSrc(node) && node.tag !== 'template') {
  22113. return;
  22114. }
  22115. switch (node.tag) {
  22116. case 'template':
  22117. if (!descriptor.template) {
  22118. const templateBlock = (descriptor.template = createBlock(node, source, false));
  22119. templateBlock.ast = node;
  22120. }
  22121. else {
  22122. errors.push(createDuplicateBlockError(node));
  22123. }
  22124. break;
  22125. case 'script':
  22126. const scriptBlock = createBlock(node, source, pad);
  22127. const isSetup = !!scriptBlock.attrs.setup;
  22128. if (isSetup && !descriptor.scriptSetup) {
  22129. descriptor.scriptSetup = scriptBlock;
  22130. break;
  22131. }
  22132. if (!isSetup && !descriptor.script) {
  22133. descriptor.script = scriptBlock;
  22134. break;
  22135. }
  22136. errors.push(createDuplicateBlockError(node, isSetup));
  22137. break;
  22138. case 'style':
  22139. const styleBlock = createBlock(node, source, pad);
  22140. if (styleBlock.attrs.vars) {
  22141. errors.push(new SyntaxError(`<style vars> has been replaced by a new proposal: ` +
  22142. `https://github.com/vuejs/rfcs/pull/231`));
  22143. }
  22144. descriptor.styles.push(styleBlock);
  22145. break;
  22146. default:
  22147. descriptor.customBlocks.push(createBlock(node, source, pad));
  22148. break;
  22149. }
  22150. });
  22151. if (descriptor.scriptSetup) {
  22152. if (descriptor.scriptSetup.src) {
  22153. errors.push(new SyntaxError(`<script setup> cannot use the "src" attribute because ` +
  22154. `its syntax will be ambiguous outside of the component.`));
  22155. descriptor.scriptSetup = null;
  22156. }
  22157. if (descriptor.script && descriptor.script.src) {
  22158. errors.push(new SyntaxError(`<script> cannot use the "src" attribute when <script setup> is ` +
  22159. `also present because they must be processed together.`));
  22160. descriptor.script = null;
  22161. }
  22162. }
  22163. if (sourceMap) {
  22164. const genMap = (block) => {
  22165. if (block && !block.src) {
  22166. block.map = generateSourceMap(filename, source, block.content, sourceRoot, !pad || block.type === 'template' ? block.loc.start.line - 1 : 0);
  22167. }
  22168. };
  22169. genMap(descriptor.template);
  22170. genMap(descriptor.script);
  22171. descriptor.styles.forEach(genMap);
  22172. descriptor.customBlocks.forEach(genMap);
  22173. }
  22174. // parse CSS vars
  22175. descriptor.cssVars = parseCssVars(descriptor);
  22176. if (descriptor.cssVars.length) {
  22177. warnExperimental(`v-bind() CSS variable injection`, 231);
  22178. }
  22179. const result = {
  22180. descriptor,
  22181. errors
  22182. };
  22183. sourceToSFC.set(sourceKey, result);
  22184. return result;
  22185. }
  22186. function createDuplicateBlockError(node, isScriptSetup = false) {
  22187. const err = new SyntaxError(`Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`);
  22188. err.loc = node.loc;
  22189. return err;
  22190. }
  22191. function createBlock(node, source, pad) {
  22192. const type = node.tag;
  22193. let { start, end } = node.loc;
  22194. let content = '';
  22195. if (node.children.length) {
  22196. start = node.children[0].loc.start;
  22197. end = node.children[node.children.length - 1].loc.end;
  22198. content = source.slice(start.offset, end.offset);
  22199. }
  22200. const loc = {
  22201. source: content,
  22202. start,
  22203. end
  22204. };
  22205. const attrs = {};
  22206. const block = {
  22207. type,
  22208. content,
  22209. loc,
  22210. attrs
  22211. };
  22212. if (pad) {
  22213. block.content = padContent(source, block, pad) + block.content;
  22214. }
  22215. node.props.forEach(p => {
  22216. if (p.type === 6 /* ATTRIBUTE */) {
  22217. attrs[p.name] = p.value ? p.value.content || true : true;
  22218. if (p.name === 'lang') {
  22219. block.lang = p.value && p.value.content;
  22220. }
  22221. else if (p.name === 'src') {
  22222. block.src = p.value && p.value.content;
  22223. }
  22224. else if (type === 'style') {
  22225. if (p.name === 'scoped') {
  22226. block.scoped = true;
  22227. }
  22228. else if (p.name === 'module') {
  22229. block.module = attrs[p.name];
  22230. }
  22231. }
  22232. else if (type === 'script' && p.name === 'setup') {
  22233. block.setup = attrs.setup;
  22234. }
  22235. }
  22236. });
  22237. return block;
  22238. }
  22239. const splitRE = /\r?\n/g;
  22240. const emptyRE = /^(?:\/\/)?\s*$/;
  22241. const replaceRE = /./g;
  22242. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
  22243. const map = new SourceMapGenerator$2({
  22244. file: filename.replace(/\\/g, '/'),
  22245. sourceRoot: sourceRoot.replace(/\\/g, '/')
  22246. });
  22247. map.setSourceContent(filename, source);
  22248. generated.split(splitRE).forEach((line, index) => {
  22249. if (!emptyRE.test(line)) {
  22250. const originalLine = index + 1 + lineOffset;
  22251. const generatedLine = index + 1;
  22252. for (let i = 0; i < line.length; i++) {
  22253. if (!/\s/.test(line[i])) {
  22254. map.addMapping({
  22255. source: filename,
  22256. original: {
  22257. line: originalLine,
  22258. column: i
  22259. },
  22260. generated: {
  22261. line: generatedLine,
  22262. column: i
  22263. }
  22264. });
  22265. }
  22266. }
  22267. }
  22268. });
  22269. return JSON.parse(map.toString());
  22270. }
  22271. function padContent(content, block, pad) {
  22272. content = content.slice(0, block.loc.start.offset);
  22273. if (pad === 'space') {
  22274. return content.replace(replaceRE, ' ');
  22275. }
  22276. else {
  22277. const offset = content.split(splitRE).length;
  22278. const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n';
  22279. return Array(offset).join(padChar);
  22280. }
  22281. }
  22282. function hasSrc(node) {
  22283. return node.props.some(p => {
  22284. if (p.type !== 6 /* ATTRIBUTE */) {
  22285. return false;
  22286. }
  22287. return p.name === 'src';
  22288. });
  22289. }
  22290. function isRelativeUrl(url) {
  22291. const firstChar = url.charAt(0);
  22292. return firstChar === '.' || firstChar === '~' || firstChar === '@';
  22293. }
  22294. const externalRE = /^https?:\/\//;
  22295. function isExternalUrl(url) {
  22296. return externalRE.test(url);
  22297. }
  22298. const dataUrlRE = /^\s*data:/i;
  22299. function isDataUrl(url) {
  22300. return dataUrlRE.test(url);
  22301. }
  22302. /**
  22303. * Parses string url into URL object.
  22304. */
  22305. function parseUrl(url) {
  22306. const firstChar = url.charAt(0);
  22307. if (firstChar === '~') {
  22308. const secondChar = url.charAt(1);
  22309. url = url.slice(secondChar === '/' ? 2 : 1);
  22310. }
  22311. return parseUriParts(url);
  22312. }
  22313. /**
  22314. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  22315. * @param urlString an url as a string
  22316. */
  22317. function parseUriParts(urlString) {
  22318. // A TypeError is thrown if urlString is not a string
  22319. // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
  22320. return url.parse(isString(urlString) ? urlString : '', false, true);
  22321. }
  22322. const defaultAssetUrlOptions = {
  22323. base: null,
  22324. includeAbsolute: false,
  22325. tags: {
  22326. video: ['src', 'poster'],
  22327. source: ['src'],
  22328. img: ['src'],
  22329. image: ['xlink:href', 'href'],
  22330. use: ['xlink:href', 'href']
  22331. }
  22332. };
  22333. const normalizeOptions = (options) => {
  22334. if (Object.keys(options).some(key => isArray(options[key]))) {
  22335. // legacy option format which directly passes in tags config
  22336. return {
  22337. ...defaultAssetUrlOptions,
  22338. tags: options
  22339. };
  22340. }
  22341. return {
  22342. ...defaultAssetUrlOptions,
  22343. ...options
  22344. };
  22345. };
  22346. const createAssetUrlTransformWithOptions = (options) => {
  22347. return (node, context) => transformAssetUrl(node, context, options);
  22348. };
  22349. /**
  22350. * A `@vue/compiler-core` plugin that transforms relative asset urls into
  22351. * either imports or absolute urls.
  22352. *
  22353. * ``` js
  22354. * // Before
  22355. * createVNode('img', { src: './logo.png' })
  22356. *
  22357. * // After
  22358. * import _imports_0 from './logo.png'
  22359. * createVNode('img', { src: _imports_0 })
  22360. * ```
  22361. */
  22362. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  22363. if (node.type === 1 /* ELEMENT */) {
  22364. if (!node.props.length) {
  22365. return;
  22366. }
  22367. const tags = options.tags || defaultAssetUrlOptions.tags;
  22368. const attrs = tags[node.tag];
  22369. const wildCardAttrs = tags['*'];
  22370. if (!attrs && !wildCardAttrs) {
  22371. return;
  22372. }
  22373. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  22374. node.props.forEach((attr, index) => {
  22375. if (attr.type !== 6 /* ATTRIBUTE */ ||
  22376. !assetAttrs.includes(attr.name) ||
  22377. !attr.value ||
  22378. isExternalUrl(attr.value.content) ||
  22379. isDataUrl(attr.value.content) ||
  22380. attr.value.content[0] === '#' ||
  22381. (!options.includeAbsolute && !isRelativeUrl(attr.value.content))) {
  22382. return;
  22383. }
  22384. const url = parseUrl(attr.value.content);
  22385. if (options.base && attr.value.content[0] === '.') {
  22386. // explicit base - directly rewrite relative urls into absolute url
  22387. // to avoid generating extra imports
  22388. // Allow for full hostnames provided in options.base
  22389. const base = parseUrl(options.base);
  22390. const protocol = base.protocol || '';
  22391. const host = base.host ? protocol + '//' + base.host : '';
  22392. const basePath = base.path || '/';
  22393. // when packaged in the browser, path will be using the posix-
  22394. // only version provided by rollup-plugin-node-builtins.
  22395. attr.value.content =
  22396. host +
  22397. (path__default.posix || path__default).join(basePath, url.path + (url.hash || ''));
  22398. return;
  22399. }
  22400. // otherwise, transform the url into an import.
  22401. // this assumes a bundler will resolve the import into the correct
  22402. // absolute url (e.g. webpack file-loader)
  22403. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  22404. node.props[index] = {
  22405. type: 7 /* DIRECTIVE */,
  22406. name: 'bind',
  22407. arg: createSimpleExpression(attr.name, true, attr.loc),
  22408. exp,
  22409. modifiers: [],
  22410. loc: attr.loc
  22411. };
  22412. });
  22413. }
  22414. };
  22415. function getImportsExpressionExp(path, hash, loc, context) {
  22416. if (path) {
  22417. const existing = context.imports.find(i => i.path === path);
  22418. if (existing) {
  22419. return existing.exp;
  22420. }
  22421. const name = `_imports_${context.imports.length}`;
  22422. const exp = createSimpleExpression(name, false, loc, 2 /* CAN_HOIST */);
  22423. context.imports.push({ exp, path });
  22424. if (hash && path) {
  22425. return context.hoist(createSimpleExpression(`${name} + '${hash}'`, false, loc, 2 /* CAN_HOIST */));
  22426. }
  22427. else {
  22428. return exp;
  22429. }
  22430. }
  22431. else {
  22432. return createSimpleExpression(`''`, false, loc, 2 /* CAN_HOIST */);
  22433. }
  22434. }
  22435. const srcsetTags = ['img', 'source'];
  22436. // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
  22437. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  22438. const createSrcsetTransformWithOptions = (options) => {
  22439. return (node, context) => transformSrcset(node, context, options);
  22440. };
  22441. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  22442. if (node.type === 1 /* ELEMENT */) {
  22443. if (srcsetTags.includes(node.tag) && node.props.length) {
  22444. node.props.forEach((attr, index) => {
  22445. if (attr.name === 'srcset' && attr.type === 6 /* ATTRIBUTE */) {
  22446. if (!attr.value)
  22447. return;
  22448. const value = attr.value.content;
  22449. if (!value)
  22450. return;
  22451. const imageCandidates = value.split(',').map(s => {
  22452. // The attribute value arrives here with all whitespace, except
  22453. // normal spaces, represented by escape sequences
  22454. const [url, descriptor] = s
  22455. .replace(escapedSpaceCharacters, ' ')
  22456. .trim()
  22457. .split(' ', 2);
  22458. return { url, descriptor };
  22459. });
  22460. // for data url need recheck url
  22461. for (let i = 0; i < imageCandidates.length; i++) {
  22462. if (imageCandidates[i].url.trim().startsWith('data:')) {
  22463. imageCandidates[i + 1].url =
  22464. imageCandidates[i].url + ',' + imageCandidates[i + 1].url;
  22465. imageCandidates.splice(i, 1);
  22466. }
  22467. }
  22468. // When srcset does not contain any relative URLs, skip transforming
  22469. if (!options.includeAbsolute &&
  22470. !imageCandidates.some(({ url }) => isRelativeUrl(url))) {
  22471. return;
  22472. }
  22473. if (options.base) {
  22474. const base = options.base;
  22475. const set = [];
  22476. imageCandidates.forEach(({ url, descriptor }) => {
  22477. descriptor = descriptor ? ` ${descriptor}` : ``;
  22478. if (isRelativeUrl(url)) {
  22479. set.push((path__default.posix || path__default).join(base, url) + descriptor);
  22480. }
  22481. else {
  22482. set.push(url + descriptor);
  22483. }
  22484. });
  22485. attr.value.content = set.join(', ');
  22486. return;
  22487. }
  22488. const compoundExpression = createCompoundExpression([], attr.loc);
  22489. imageCandidates.forEach(({ url, descriptor }, index) => {
  22490. if (!isExternalUrl(url) &&
  22491. !isDataUrl(url) &&
  22492. (options.includeAbsolute || isRelativeUrl(url))) {
  22493. const { path } = parseUrl(url);
  22494. let exp;
  22495. if (path) {
  22496. const existingImportsIndex = context.imports.findIndex(i => i.path === path);
  22497. if (existingImportsIndex > -1) {
  22498. exp = createSimpleExpression(`_imports_${existingImportsIndex}`, false, attr.loc, 2 /* CAN_HOIST */);
  22499. }
  22500. else {
  22501. exp = createSimpleExpression(`_imports_${context.imports.length}`, false, attr.loc, 2 /* CAN_HOIST */);
  22502. context.imports.push({ exp, path });
  22503. }
  22504. compoundExpression.children.push(exp);
  22505. }
  22506. }
  22507. else {
  22508. const exp = createSimpleExpression(`"${url}"`, false, attr.loc, 2 /* CAN_HOIST */);
  22509. compoundExpression.children.push(exp);
  22510. }
  22511. const isNotLast = imageCandidates.length - 1 > index;
  22512. if (descriptor && isNotLast) {
  22513. compoundExpression.children.push(` + '${descriptor}, ' + `);
  22514. }
  22515. else if (descriptor) {
  22516. compoundExpression.children.push(` + '${descriptor}'`);
  22517. }
  22518. else if (isNotLast) {
  22519. compoundExpression.children.push(` + ', ' + `);
  22520. }
  22521. });
  22522. const hoisted = context.hoist(compoundExpression);
  22523. hoisted.constType = 2 /* CAN_HOIST */;
  22524. node.props[index] = {
  22525. type: 7 /* DIRECTIVE */,
  22526. name: 'bind',
  22527. arg: createSimpleExpression('srcset', true, attr.loc),
  22528. exp: hoisted,
  22529. modifiers: [],
  22530. loc: attr.loc
  22531. };
  22532. }
  22533. });
  22534. }
  22535. }
  22536. };
  22537. const SSR_INTERPOLATE = Symbol(`ssrInterpolate`);
  22538. const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`);
  22539. const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`);
  22540. const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`);
  22541. const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`);
  22542. const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`);
  22543. const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`);
  22544. const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`);
  22545. const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`);
  22546. const SSR_RENDER_LIST = Symbol(`ssrRenderList`);
  22547. const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`);
  22548. const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`);
  22549. const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`);
  22550. const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`);
  22551. const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`);
  22552. const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`);
  22553. const ssrHelpers = {
  22554. [SSR_INTERPOLATE]: `ssrInterpolate`,
  22555. [SSR_RENDER_VNODE]: `ssrRenderVNode`,
  22556. [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
  22557. [SSR_RENDER_SLOT]: `ssrRenderSlot`,
  22558. [SSR_RENDER_CLASS]: `ssrRenderClass`,
  22559. [SSR_RENDER_STYLE]: `ssrRenderStyle`,
  22560. [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
  22561. [SSR_RENDER_ATTR]: `ssrRenderAttr`,
  22562. [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
  22563. [SSR_RENDER_LIST]: `ssrRenderList`,
  22564. [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
  22565. [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
  22566. [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
  22567. [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
  22568. [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
  22569. [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`
  22570. };
  22571. // Note: these are helpers imported from @vue/server-renderer
  22572. // make sure the names match!
  22573. registerRuntimeHelpers(ssrHelpers);
  22574. // Plugin for the first transform pass, which simply constructs the AST node
  22575. const ssrTransformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, processIf);
  22576. // This is called during the 2nd transform pass to construct the SSR-specific
  22577. // codegen nodes.
  22578. function ssrProcessIf(node, context, disableNestedFragments = false) {
  22579. const [rootBranch] = node.branches;
  22580. const ifStatement = createIfStatement(rootBranch.condition, processIfBranch(rootBranch, context, disableNestedFragments));
  22581. context.pushStatement(ifStatement);
  22582. let currentIf = ifStatement;
  22583. for (let i = 1; i < node.branches.length; i++) {
  22584. const branch = node.branches[i];
  22585. const branchBlockStatement = processIfBranch(branch, context, disableNestedFragments);
  22586. if (branch.condition) {
  22587. // else-if
  22588. currentIf = currentIf.alternate = createIfStatement(branch.condition, branchBlockStatement);
  22589. }
  22590. else {
  22591. // else
  22592. currentIf.alternate = branchBlockStatement;
  22593. }
  22594. }
  22595. if (!currentIf.alternate) {
  22596. currentIf.alternate = createBlockStatement([
  22597. createCallExpression(`_push`, ['`<!---->`'])
  22598. ]);
  22599. }
  22600. }
  22601. function processIfBranch(branch, context, disableNestedFragments = false) {
  22602. const { children } = branch;
  22603. const needFragmentWrapper = !disableNestedFragments &&
  22604. (children.length !== 1 || children[0].type !== 1 /* ELEMENT */) &&
  22605. // optimize away nested fragments when the only child is a ForNode
  22606. !(children.length === 1 && children[0].type === 11 /* FOR */);
  22607. return processChildrenAsStatement(children, context, needFragmentWrapper);
  22608. }
  22609. // Plugin for the first transform pass, which simply constructs the AST node
  22610. const ssrTransformFor = createStructuralDirectiveTransform('for', processFor);
  22611. // This is called during the 2nd transform pass to construct the SSR-specific
  22612. // codegen nodes.
  22613. function ssrProcessFor(node, context, disableNestedFragments = false) {
  22614. const needFragmentWrapper = !disableNestedFragments &&
  22615. (node.children.length !== 1 || node.children[0].type !== 1 /* ELEMENT */);
  22616. const renderLoop = createFunctionExpression(createForLoopParams(node.parseResult));
  22617. renderLoop.body = processChildrenAsStatement(node.children, context, needFragmentWrapper);
  22618. // v-for always renders a fragment unless explicitly disabled
  22619. if (!disableNestedFragments) {
  22620. context.pushStringPart(`<!--[-->`);
  22621. }
  22622. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_LIST), [
  22623. node.source,
  22624. renderLoop
  22625. ]));
  22626. if (!disableNestedFragments) {
  22627. context.pushStringPart(`<!--]-->`);
  22628. }
  22629. }
  22630. const ssrTransformSlotOutlet = (node, context) => {
  22631. if (isSlotOutlet(node)) {
  22632. const { slotName, slotProps } = processSlotOutlet(node, context);
  22633. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_SLOT), [
  22634. `_ctx.$slots`,
  22635. slotName,
  22636. slotProps || `{}`,
  22637. `null`,
  22638. `_push`,
  22639. `_parent`
  22640. ]);
  22641. }
  22642. };
  22643. function ssrProcessSlotOutlet(node, context) {
  22644. const renderCall = node.ssrCodegenNode;
  22645. // has fallback content
  22646. if (node.children.length) {
  22647. const fallbackRenderFn = createFunctionExpression([]);
  22648. fallbackRenderFn.body = processChildrenAsStatement(node.children, context);
  22649. // _renderSlot(slots, name, props, fallback, ...)
  22650. renderCall.arguments[3] = fallbackRenderFn;
  22651. }
  22652. context.pushStatement(node.ssrCodegenNode);
  22653. }
  22654. function createSSRCompilerError(code, loc) {
  22655. return createCompilerError(code, loc, SSRErrorMessages);
  22656. }
  22657. const SSRErrorMessages = {
  22658. [60 /* X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM */]: `Custom directive is missing corresponding SSR transform and will be ignored.`,
  22659. [61 /* X_SSR_UNSAFE_ATTR_NAME */]: `Unsafe attribute name for SSR.`,
  22660. [62 /* X_SSR_NO_TELEPORT_TARGET */]: `Missing the 'to' prop on teleport element.`,
  22661. [63 /* X_SSR_INVALID_AST_NODE */]: `Invalid AST node during SSR transform.`
  22662. };
  22663. // Note: this is a 2nd-pass codegen transform.
  22664. function ssrProcessTeleport(node, context) {
  22665. const targetProp = findProp(node, 'to');
  22666. if (!targetProp) {
  22667. context.onError(createSSRCompilerError(62 /* X_SSR_NO_TELEPORT_TARGET */, node.loc));
  22668. return;
  22669. }
  22670. let target;
  22671. if (targetProp.type === 6 /* ATTRIBUTE */) {
  22672. target =
  22673. targetProp.value && createSimpleExpression(targetProp.value.content, true);
  22674. }
  22675. else {
  22676. target = targetProp.exp;
  22677. }
  22678. if (!target) {
  22679. context.onError(createSSRCompilerError(62 /* X_SSR_NO_TELEPORT_TARGET */, targetProp.loc));
  22680. return;
  22681. }
  22682. const disabledProp = findProp(node, 'disabled', false, true /* allow empty */);
  22683. const disabled = disabledProp
  22684. ? disabledProp.type === 6 /* ATTRIBUTE */
  22685. ? `true`
  22686. : disabledProp.exp || `false`
  22687. : `false`;
  22688. const contentRenderFn = createFunctionExpression([`_push`], undefined, // Body is added later
  22689. true, // newline
  22690. false, // isSlot
  22691. node.loc);
  22692. contentRenderFn.body = processChildrenAsStatement(node.children, context);
  22693. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
  22694. `_push`,
  22695. contentRenderFn,
  22696. target,
  22697. disabled,
  22698. `_parent`
  22699. ]));
  22700. }
  22701. const wipMap = new WeakMap();
  22702. // phase 1
  22703. function ssrTransformSuspense(node, context) {
  22704. return () => {
  22705. if (node.children.length) {
  22706. const wipEntry = {
  22707. slotsExp: null,
  22708. wipSlots: []
  22709. };
  22710. wipMap.set(node, wipEntry);
  22711. wipEntry.slotsExp = buildSlots(node, context, (_props, children, loc) => {
  22712. const fn = createFunctionExpression([], undefined, // no return, assign body later
  22713. true, // newline
  22714. false, // suspense slots are not treated as normal slots
  22715. loc);
  22716. wipEntry.wipSlots.push({
  22717. fn,
  22718. children
  22719. });
  22720. return fn;
  22721. }).slots;
  22722. }
  22723. };
  22724. }
  22725. // phase 2
  22726. function ssrProcessSuspense(node, context) {
  22727. // complete wip slots with ssr code
  22728. const wipEntry = wipMap.get(node);
  22729. if (!wipEntry) {
  22730. return;
  22731. }
  22732. const { slotsExp, wipSlots } = wipEntry;
  22733. for (let i = 0; i < wipSlots.length; i++) {
  22734. const { fn, children } = wipSlots[i];
  22735. fn.body = processChildrenAsStatement(children, context);
  22736. }
  22737. // _push(ssrRenderSuspense(slots))
  22738. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
  22739. `_push`,
  22740. slotsExp
  22741. ]));
  22742. }
  22743. function ssrProcessTransitionGroup(node, context) {
  22744. const tag = findProp(node, 'tag');
  22745. if (tag) {
  22746. if (tag.type === 7 /* DIRECTIVE */) {
  22747. // dynamic :tag
  22748. context.pushStringPart(`<`);
  22749. context.pushStringPart(tag.exp);
  22750. context.pushStringPart(`>`);
  22751. processChildren(node.children, context, false,
  22752. /**
  22753. * TransitionGroup has the special runtime behavior of flattening and
  22754. * concatenating all children into a single fragment (in order for them to
  22755. * be pathced using the same key map) so we need to account for that here
  22756. * by disabling nested fragment wrappers from being generated.
  22757. */
  22758. true);
  22759. context.pushStringPart(`</`);
  22760. context.pushStringPart(tag.exp);
  22761. context.pushStringPart(`>`);
  22762. }
  22763. else {
  22764. // static tag
  22765. context.pushStringPart(`<${tag.value.content}>`);
  22766. processChildren(node.children, context, false, true);
  22767. context.pushStringPart(`</${tag.value.content}>`);
  22768. }
  22769. }
  22770. else {
  22771. // fragment
  22772. processChildren(node.children, context, true, true);
  22773. }
  22774. }
  22775. // We need to construct the slot functions in the 1st pass to ensure proper
  22776. // scope tracking, but the children of each slot cannot be processed until
  22777. // the 2nd pass, so we store the WIP slot functions in a weakmap during the 1st
  22778. // pass and complete them in the 2nd pass.
  22779. const wipMap$1 = new WeakMap();
  22780. const componentTypeMap = new WeakMap();
  22781. // ssr component transform is done in two phases:
  22782. // In phase 1. we use `buildSlot` to analyze the children of the component into
  22783. // WIP slot functions (it must be done in phase 1 because `buildSlot` relies on
  22784. // the core transform context).
  22785. // In phase 2. we convert the WIP slots from phase 1 into ssr-specific codegen
  22786. // nodes.
  22787. const ssrTransformComponent = (node, context) => {
  22788. if (node.type !== 1 /* ELEMENT */ ||
  22789. node.tagType !== 1 /* COMPONENT */) {
  22790. return;
  22791. }
  22792. const component = resolveComponentType(node, context, true /* ssr */);
  22793. componentTypeMap.set(node, component);
  22794. if (isSymbol(component)) {
  22795. if (component === SUSPENSE) {
  22796. return ssrTransformSuspense(node, context);
  22797. }
  22798. return; // built-in component: fallthrough
  22799. }
  22800. // Build the fallback vnode-based branch for the component's slots.
  22801. // We need to clone the node into a fresh copy and use the buildSlots' logic
  22802. // to get access to the children of each slot. We then compile them with
  22803. // a child transform pipeline using vnode-based transforms (instead of ssr-
  22804. // based ones), and save the result branch (a ReturnStatement) in an array.
  22805. // The branch is retrieved when processing slots again in ssr mode.
  22806. const vnodeBranches = [];
  22807. const clonedNode = clone(node);
  22808. return function ssrPostTransformComponent() {
  22809. // Using the cloned node, build the normal VNode-based branches (for
  22810. // fallback in case the child is render-fn based). Store them in an array
  22811. // for later use.
  22812. if (clonedNode.children.length) {
  22813. buildSlots(clonedNode, context, (props, children) => {
  22814. vnodeBranches.push(createVNodeSlotBranch(props, children, context));
  22815. return createFunctionExpression(undefined);
  22816. });
  22817. }
  22818. const props = node.props.length > 0
  22819. ? // note we are not passing ssr: true here because for components, v-on
  22820. // handlers should still be passed
  22821. buildProps(node, context).props || `null`
  22822. : `null`;
  22823. const wipEntries = [];
  22824. wipMap$1.set(node, wipEntries);
  22825. const buildSSRSlotFn = (props, children, loc) => {
  22826. const fn = createFunctionExpression([props || `_`, `_push`, `_parent`, `_scopeId`], undefined, // no return, assign body later
  22827. true, // newline
  22828. true, // isSlot
  22829. loc);
  22830. wipEntries.push({
  22831. fn,
  22832. children,
  22833. // also collect the corresponding vnode branch built earlier
  22834. vnodeBranch: vnodeBranches[wipEntries.length]
  22835. });
  22836. return fn;
  22837. };
  22838. const slots = node.children.length
  22839. ? buildSlots(node, context, buildSSRSlotFn).slots
  22840. : `null`;
  22841. if (typeof component !== 'string') {
  22842. // dynamic component that resolved to a `resolveDynamicComponent` call
  22843. // expression - since the resolved result may be a plain element (string)
  22844. // or a VNode, handle it with `renderVNode`.
  22845. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_VNODE), [
  22846. `_push`,
  22847. createCallExpression(context.helper(CREATE_VNODE), [
  22848. component,
  22849. props,
  22850. slots
  22851. ]),
  22852. `_parent`
  22853. ]);
  22854. }
  22855. else {
  22856. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_COMPONENT), [component, props, slots, `_parent`]);
  22857. }
  22858. };
  22859. };
  22860. function ssrProcessComponent(node, context) {
  22861. const component = componentTypeMap.get(node);
  22862. if (!node.ssrCodegenNode) {
  22863. // this is a built-in component that fell-through.
  22864. if (component === TELEPORT) {
  22865. return ssrProcessTeleport(node, context);
  22866. }
  22867. else if (component === SUSPENSE) {
  22868. return ssrProcessSuspense(node, context);
  22869. }
  22870. else if (component === TRANSITION_GROUP) {
  22871. return ssrProcessTransitionGroup(node, context);
  22872. }
  22873. else {
  22874. // real fall-through (e.g. KeepAlive): just render its children.
  22875. processChildren(node.children, context);
  22876. }
  22877. }
  22878. else {
  22879. // finish up slot function expressions from the 1st pass.
  22880. const wipEntries = wipMap$1.get(node) || [];
  22881. for (let i = 0; i < wipEntries.length; i++) {
  22882. const { fn, children, vnodeBranch } = wipEntries[i];
  22883. // For each slot, we generate two branches: one SSR-optimized branch and
  22884. // one normal vnode-based branch. The branches are taken based on the
  22885. // presence of the 2nd `_push` argument (which is only present if the slot
  22886. // is called by `_ssrRenderSlot`.
  22887. fn.body = createIfStatement(createSimpleExpression(`_push`, false), processChildrenAsStatement(children, context, false, true /* withSlotScopeId */), vnodeBranch);
  22888. }
  22889. if (typeof component === 'string') {
  22890. // static component
  22891. context.pushStatement(createCallExpression(`_push`, [node.ssrCodegenNode]));
  22892. }
  22893. else {
  22894. // dynamic component (`resolveDynamicComponent` call)
  22895. // the codegen node is a `renderVNode` call
  22896. context.pushStatement(node.ssrCodegenNode);
  22897. }
  22898. }
  22899. }
  22900. const rawOptionsMap = new WeakMap();
  22901. const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
  22902. const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms];
  22903. const vnodeDirectiveTransforms = {
  22904. ...baseDirectiveTransforms,
  22905. ...DOMDirectiveTransforms
  22906. };
  22907. function createVNodeSlotBranch(props, children, parentContext) {
  22908. // apply a sub-transform using vnode-based transforms.
  22909. const rawOptions = rawOptionsMap.get(parentContext.root);
  22910. const subOptions = {
  22911. ...rawOptions,
  22912. // overwrite with vnode-based transforms
  22913. nodeTransforms: [
  22914. ...vnodeNodeTransforms,
  22915. ...(rawOptions.nodeTransforms || [])
  22916. ],
  22917. directiveTransforms: {
  22918. ...vnodeDirectiveTransforms,
  22919. ...(rawOptions.directiveTransforms || {})
  22920. }
  22921. };
  22922. // wrap the children with a wrapper template for proper children treatment.
  22923. const wrapperNode = {
  22924. type: 1 /* ELEMENT */,
  22925. ns: 0 /* HTML */,
  22926. tag: 'template',
  22927. tagType: 3 /* TEMPLATE */,
  22928. isSelfClosing: false,
  22929. // important: provide v-slot="props" on the wrapper for proper
  22930. // scope analysis
  22931. props: [
  22932. {
  22933. type: 7 /* DIRECTIVE */,
  22934. name: 'slot',
  22935. exp: props,
  22936. arg: undefined,
  22937. modifiers: [],
  22938. loc: locStub
  22939. }
  22940. ],
  22941. children,
  22942. loc: locStub,
  22943. codegenNode: undefined
  22944. };
  22945. subTransform(wrapperNode, subOptions, parentContext);
  22946. return createReturnStatement(children);
  22947. }
  22948. function subTransform(node, options, parentContext) {
  22949. const childRoot = createRoot([node]);
  22950. const childContext = createTransformContext(childRoot, options);
  22951. // this sub transform is for vnode fallback branch so it should be handled
  22952. // like normal render functions
  22953. childContext.ssr = false;
  22954. // inherit parent scope analysis state
  22955. childContext.scopes = { ...parentContext.scopes };
  22956. childContext.identifiers = { ...parentContext.identifiers };
  22957. // traverse
  22958. traverseNode(childRoot, childContext);
  22959. ['helpers', 'components', 'directives'].forEach(key => {
  22960. childContext[key].forEach((value) => {
  22961. parentContext[key].add(value);
  22962. });
  22963. });
  22964. // imports/hoists are not merged because:
  22965. // - imports are only used for asset urls and should be consistent between
  22966. // node/client branches
  22967. // - hoists are not enabled for the client branch here
  22968. }
  22969. function clone(v) {
  22970. if (isArray(v)) {
  22971. return v.map(clone);
  22972. }
  22973. else if (isObject(v)) {
  22974. const res = {};
  22975. for (const key in v) {
  22976. res[key] = clone(v[key]);
  22977. }
  22978. return res;
  22979. }
  22980. else {
  22981. return v;
  22982. }
  22983. }
  22984. // for directives with children overwrite (e.g. v-html & v-text), we need to
  22985. // store the raw children so that they can be added in the 2nd pass.
  22986. const rawChildrenMap = new WeakMap();
  22987. const ssrTransformElement = (node, context) => {
  22988. if (node.type !== 1 /* ELEMENT */ ||
  22989. node.tagType !== 0 /* ELEMENT */) {
  22990. return;
  22991. }
  22992. return function ssrPostTransformElement() {
  22993. // element
  22994. // generate the template literal representing the open tag.
  22995. const openTag = [`<${node.tag}`];
  22996. // some tags need to be passed to runtime for special checks
  22997. const needTagForRuntime = node.tag === 'textarea' || node.tag.indexOf('-') > 0;
  22998. // v-bind="obj" or v-bind:[key] can potentially overwrite other static
  22999. // attrs and can affect final rendering result, so when they are present
  23000. // we need to bail out to full `renderAttrs`
  23001. const hasDynamicVBind = hasDynamicKeyVBind(node);
  23002. if (hasDynamicVBind) {
  23003. const { props } = buildProps(node, context, node.props, true /* ssr */);
  23004. if (props) {
  23005. const propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [props]);
  23006. if (node.tag === 'textarea') {
  23007. const existingText = node.children[0];
  23008. // If interpolation, this is dynamic <textarea> content, potentially
  23009. // injected by v-model and takes higher priority than v-bind value
  23010. if (!existingText || existingText.type !== 5 /* INTERPOLATION */) {
  23011. // <textarea> with dynamic v-bind. We don't know if the final props
  23012. // will contain .value, so we will have to do something special:
  23013. // assign the merged props to a temp variable, and check whether
  23014. // it contains value (if yes, render is as children).
  23015. const tempId = `_temp${context.temps++}`;
  23016. propsExp.arguments = [
  23017. createAssignmentExpression(createSimpleExpression(tempId, false), props)
  23018. ];
  23019. rawChildrenMap.set(node, createCallExpression(context.helper(SSR_INTERPOLATE), [
  23020. createConditionalExpression(createSimpleExpression(`"value" in ${tempId}`, false), createSimpleExpression(`${tempId}.value`, false), createSimpleExpression(existingText ? existingText.content : ``, true), false)
  23021. ]));
  23022. }
  23023. }
  23024. else if (node.tag === 'input') {
  23025. // <input v-bind="obj" v-model>
  23026. // we need to determine the props to render for the dynamic v-model
  23027. // and merge it with the v-bind expression.
  23028. const vModel = findVModel(node);
  23029. if (vModel) {
  23030. // 1. save the props (san v-model) in a temp variable
  23031. const tempId = `_temp${context.temps++}`;
  23032. const tempExp = createSimpleExpression(tempId, false);
  23033. propsExp.arguments = [
  23034. createSequenceExpression([
  23035. createAssignmentExpression(tempExp, props),
  23036. createCallExpression(context.helper(MERGE_PROPS), [
  23037. tempExp,
  23038. createCallExpression(context.helper(SSR_GET_DYNAMIC_MODEL_PROPS), [
  23039. tempExp,
  23040. vModel.exp // model
  23041. ])
  23042. ])
  23043. ])
  23044. ];
  23045. }
  23046. }
  23047. if (needTagForRuntime) {
  23048. propsExp.arguments.push(`"${node.tag}"`);
  23049. }
  23050. openTag.push(propsExp);
  23051. }
  23052. }
  23053. // book keeping static/dynamic class merging.
  23054. let dynamicClassBinding = undefined;
  23055. let staticClassBinding = undefined;
  23056. // all style bindings are converted to dynamic by transformStyle.
  23057. // but we need to make sure to merge them.
  23058. let dynamicStyleBinding = undefined;
  23059. for (let i = 0; i < node.props.length; i++) {
  23060. const prop = node.props[i];
  23061. // ignore true-value/false-value on input
  23062. if (node.tag === 'input' && isTrueFalseValue(prop)) {
  23063. continue;
  23064. }
  23065. // special cases with children override
  23066. if (prop.type === 7 /* DIRECTIVE */) {
  23067. if (prop.name === 'html' && prop.exp) {
  23068. rawChildrenMap.set(node, prop.exp);
  23069. }
  23070. else if (prop.name === 'text' && prop.exp) {
  23071. node.children = [createInterpolation(prop.exp, prop.loc)];
  23072. }
  23073. else if (prop.name === 'slot') {
  23074. context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, prop.loc));
  23075. }
  23076. else if (isTextareaWithValue(node, prop) && prop.exp) {
  23077. if (!hasDynamicVBind) {
  23078. node.children = [createInterpolation(prop.exp, prop.loc)];
  23079. }
  23080. }
  23081. else {
  23082. // Directive transforms.
  23083. const directiveTransform = context.directiveTransforms[prop.name];
  23084. if (!directiveTransform) {
  23085. // no corresponding ssr directive transform found.
  23086. context.onError(createSSRCompilerError(60 /* X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM */, prop.loc));
  23087. }
  23088. else if (!hasDynamicVBind) {
  23089. const { props, ssrTagParts } = directiveTransform(prop, node, context);
  23090. if (ssrTagParts) {
  23091. openTag.push(...ssrTagParts);
  23092. }
  23093. for (let j = 0; j < props.length; j++) {
  23094. const { key, value } = props[j];
  23095. if (isStaticExp(key)) {
  23096. let attrName = key.content;
  23097. // static key attr
  23098. if (attrName === 'key' || attrName === 'ref') {
  23099. continue;
  23100. }
  23101. if (attrName === 'class') {
  23102. openTag.push(` class="`, (dynamicClassBinding = createCallExpression(context.helper(SSR_RENDER_CLASS), [value])), `"`);
  23103. }
  23104. else if (attrName === 'style') {
  23105. if (dynamicStyleBinding) {
  23106. // already has style binding, merge into it.
  23107. mergeCall(dynamicStyleBinding, value);
  23108. }
  23109. else {
  23110. openTag.push(` style="`, (dynamicStyleBinding = createCallExpression(context.helper(SSR_RENDER_STYLE), [value])), `"`);
  23111. }
  23112. }
  23113. else {
  23114. attrName =
  23115. node.tag.indexOf('-') > 0
  23116. ? attrName // preserve raw name on custom elements
  23117. : propsToAttrMap[attrName] || attrName.toLowerCase();
  23118. if (isBooleanAttr(attrName)) {
  23119. openTag.push(createConditionalExpression(value, createSimpleExpression(' ' + attrName, true), createSimpleExpression('', true), false /* no newline */));
  23120. }
  23121. else if (isSSRSafeAttrName(attrName)) {
  23122. openTag.push(createCallExpression(context.helper(SSR_RENDER_ATTR), [
  23123. key,
  23124. value
  23125. ]));
  23126. }
  23127. else {
  23128. context.onError(createSSRCompilerError(61 /* X_SSR_UNSAFE_ATTR_NAME */, key.loc));
  23129. }
  23130. }
  23131. }
  23132. else {
  23133. // dynamic key attr
  23134. // this branch is only encountered for custom directive
  23135. // transforms that returns properties with dynamic keys
  23136. const args = [key, value];
  23137. if (needTagForRuntime) {
  23138. args.push(`"${node.tag}"`);
  23139. }
  23140. openTag.push(createCallExpression(context.helper(SSR_RENDER_DYNAMIC_ATTR), args));
  23141. }
  23142. }
  23143. }
  23144. }
  23145. }
  23146. else {
  23147. // special case: value on <textarea>
  23148. if (node.tag === 'textarea' && prop.name === 'value' && prop.value) {
  23149. rawChildrenMap.set(node, escapeHtml(prop.value.content));
  23150. }
  23151. else if (!hasDynamicVBind) {
  23152. if (prop.name === 'key' || prop.name === 'ref') {
  23153. continue;
  23154. }
  23155. // static prop
  23156. if (prop.name === 'class' && prop.value) {
  23157. staticClassBinding = JSON.stringify(prop.value.content);
  23158. }
  23159. openTag.push(` ${prop.name}` +
  23160. (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``));
  23161. }
  23162. }
  23163. }
  23164. // handle co-existence of dynamic + static class bindings
  23165. if (dynamicClassBinding && staticClassBinding) {
  23166. mergeCall(dynamicClassBinding, staticClassBinding);
  23167. removeStaticBinding(openTag, 'class');
  23168. }
  23169. if (context.scopeId) {
  23170. openTag.push(` ${context.scopeId}`);
  23171. }
  23172. node.ssrCodegenNode = createTemplateLiteral(openTag);
  23173. };
  23174. };
  23175. function isTrueFalseValue(prop) {
  23176. if (prop.type === 7 /* DIRECTIVE */) {
  23177. return (prop.name === 'bind' &&
  23178. prop.arg &&
  23179. isStaticExp(prop.arg) &&
  23180. (prop.arg.content === 'true-value' || prop.arg.content === 'false-value'));
  23181. }
  23182. else {
  23183. return prop.name === 'true-value' || prop.name === 'false-value';
  23184. }
  23185. }
  23186. function isTextareaWithValue(node, prop) {
  23187. return !!(node.tag === 'textarea' &&
  23188. prop.name === 'bind' &&
  23189. isBindKey(prop.arg, 'value'));
  23190. }
  23191. function mergeCall(call, arg) {
  23192. const existing = call.arguments[0];
  23193. if (existing.type === 17 /* JS_ARRAY_EXPRESSION */) {
  23194. existing.elements.push(arg);
  23195. }
  23196. else {
  23197. call.arguments[0] = createArrayExpression([existing, arg]);
  23198. }
  23199. }
  23200. function removeStaticBinding(tag, binding) {
  23201. const regExp = new RegExp(`^ ${binding}=".+"$`);
  23202. const i = tag.findIndex(e => typeof e === 'string' && regExp.test(e));
  23203. if (i > -1) {
  23204. tag.splice(i, 1);
  23205. }
  23206. }
  23207. function findVModel(node) {
  23208. return node.props.find(p => p.type === 7 /* DIRECTIVE */ && p.name === 'model' && p.exp);
  23209. }
  23210. function ssrProcessElement(node, context) {
  23211. const isVoidTag = context.options.isVoidTag || NO;
  23212. const elementsToAdd = node.ssrCodegenNode.elements;
  23213. for (let j = 0; j < elementsToAdd.length; j++) {
  23214. context.pushStringPart(elementsToAdd[j]);
  23215. }
  23216. // Handle slot scopeId
  23217. if (context.withSlotScopeId) {
  23218. context.pushStringPart(createSimpleExpression(`_scopeId`, false));
  23219. }
  23220. // close open tag
  23221. context.pushStringPart(`>`);
  23222. const rawChildren = rawChildrenMap.get(node);
  23223. if (rawChildren) {
  23224. context.pushStringPart(rawChildren);
  23225. }
  23226. else if (node.children.length) {
  23227. processChildren(node.children, context);
  23228. }
  23229. if (!isVoidTag(node.tag)) {
  23230. // push closing tag
  23231. context.pushStringPart(`</${node.tag}>`);
  23232. }
  23233. }
  23234. // Because SSR codegen output is completely different from client-side output
  23235. // (e.g. multiple elements can be concatenated into a single template literal
  23236. // instead of each getting a corresponding call), we need to apply an extra
  23237. // transform pass to convert the template AST into a fresh JS AST before
  23238. // passing it to codegen.
  23239. function ssrCodegenTransform(ast, options) {
  23240. const context = createSSRTransformContext(ast, options);
  23241. // inject SFC <style> CSS variables
  23242. // we do this instead of inlining the expression to ensure the vars are
  23243. // only resolved once per render
  23244. if (options.ssrCssVars) {
  23245. const varsExp = processExpression(createSimpleExpression(options.ssrCssVars, false), createTransformContext(createRoot([]), options));
  23246. context.body.push(createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]));
  23247. }
  23248. const isFragment = ast.children.length > 1 && ast.children.some(c => !isText(c));
  23249. processChildren(ast.children, context, isFragment);
  23250. ast.codegenNode = createBlockStatement(context.body);
  23251. // Finalize helpers.
  23252. // We need to separate helpers imported from 'vue' vs. '@vue/server-renderer'
  23253. ast.ssrHelpers = [
  23254. ...ast.helpers.filter(h => h in ssrHelpers),
  23255. ...context.helpers
  23256. ];
  23257. ast.helpers = ast.helpers.filter(h => !(h in ssrHelpers));
  23258. }
  23259. function createSSRTransformContext(root, options, helpers = new Set(), withSlotScopeId = false) {
  23260. const body = [];
  23261. let currentString = null;
  23262. return {
  23263. root,
  23264. options,
  23265. body,
  23266. helpers,
  23267. withSlotScopeId,
  23268. onError: options.onError ||
  23269. (e => {
  23270. throw e;
  23271. }),
  23272. helper(name) {
  23273. helpers.add(name);
  23274. return name;
  23275. },
  23276. pushStringPart(part) {
  23277. if (!currentString) {
  23278. const currentCall = createCallExpression(`_push`);
  23279. body.push(currentCall);
  23280. currentString = createTemplateLiteral([]);
  23281. currentCall.arguments.push(currentString);
  23282. }
  23283. const bufferedElements = currentString.elements;
  23284. const lastItem = bufferedElements[bufferedElements.length - 1];
  23285. if (isString(part) && isString(lastItem)) {
  23286. bufferedElements[bufferedElements.length - 1] += part;
  23287. }
  23288. else {
  23289. bufferedElements.push(part);
  23290. }
  23291. },
  23292. pushStatement(statement) {
  23293. // close current string
  23294. currentString = null;
  23295. body.push(statement);
  23296. }
  23297. };
  23298. }
  23299. function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
  23300. // ensure child inherits parent helpers
  23301. return createSSRTransformContext(parent.root, parent.options, parent.helpers, withSlotScopeId);
  23302. }
  23303. function processChildren(children, context, asFragment = false, disableNestedFragments = false) {
  23304. if (asFragment) {
  23305. context.pushStringPart(`<!--[-->`);
  23306. }
  23307. for (let i = 0; i < children.length; i++) {
  23308. const child = children[i];
  23309. switch (child.type) {
  23310. case 1 /* ELEMENT */:
  23311. switch (child.tagType) {
  23312. case 0 /* ELEMENT */:
  23313. ssrProcessElement(child, context);
  23314. break;
  23315. case 1 /* COMPONENT */:
  23316. ssrProcessComponent(child, context);
  23317. break;
  23318. case 2 /* SLOT */:
  23319. ssrProcessSlotOutlet(child, context);
  23320. break;
  23321. case 3 /* TEMPLATE */:
  23322. // TODO
  23323. break;
  23324. default:
  23325. context.onError(createSSRCompilerError(63 /* X_SSR_INVALID_AST_NODE */, child.loc));
  23326. // make sure we exhaust all possible types
  23327. const exhaustiveCheck = child;
  23328. return exhaustiveCheck;
  23329. }
  23330. break;
  23331. case 2 /* TEXT */:
  23332. context.pushStringPart(escapeHtml(child.content));
  23333. break;
  23334. case 3 /* COMMENT */:
  23335. // no need to escape comment here because the AST can only
  23336. // contain valid comments.
  23337. context.pushStringPart(`<!--${child.content}-->`);
  23338. break;
  23339. case 5 /* INTERPOLATION */:
  23340. context.pushStringPart(createCallExpression(context.helper(SSR_INTERPOLATE), [child.content]));
  23341. break;
  23342. case 9 /* IF */:
  23343. ssrProcessIf(child, context, disableNestedFragments);
  23344. break;
  23345. case 11 /* FOR */:
  23346. ssrProcessFor(child, context, disableNestedFragments);
  23347. break;
  23348. case 10 /* IF_BRANCH */:
  23349. // no-op - handled by ssrProcessIf
  23350. break;
  23351. case 12 /* TEXT_CALL */:
  23352. case 8 /* COMPOUND_EXPRESSION */:
  23353. // no-op - these two types can never appear as template child node since
  23354. // `transformText` is not used during SSR compile.
  23355. break;
  23356. default:
  23357. context.onError(createSSRCompilerError(63 /* X_SSR_INVALID_AST_NODE */, child.loc));
  23358. // make sure we exhaust all possible types
  23359. const exhaustiveCheck = child;
  23360. return exhaustiveCheck;
  23361. }
  23362. }
  23363. if (asFragment) {
  23364. context.pushStringPart(`<!--]-->`);
  23365. }
  23366. }
  23367. function processChildrenAsStatement(children, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
  23368. const childContext = createChildContext(parentContext, withSlotScopeId);
  23369. processChildren(children, childContext, asFragment);
  23370. return createBlockStatement(childContext.body);
  23371. }
  23372. const ssrTransformModel = (dir, node, context) => {
  23373. const model = dir.exp;
  23374. function checkDuplicatedValue() {
  23375. const value = findProp(node, 'value');
  23376. if (value) {
  23377. context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  23378. }
  23379. }
  23380. if (node.tagType === 0 /* ELEMENT */) {
  23381. const res = { props: [] };
  23382. const defaultProps = [
  23383. // default value binding for text type inputs
  23384. createObjectProperty(`value`, model)
  23385. ];
  23386. if (node.tag === 'input') {
  23387. const type = findProp(node, 'type');
  23388. if (type) {
  23389. const value = findValueBinding(node);
  23390. if (type.type === 7 /* DIRECTIVE */) {
  23391. // dynamic type
  23392. res.ssrTagParts = [
  23393. createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
  23394. type.exp,
  23395. model,
  23396. value
  23397. ])
  23398. ];
  23399. }
  23400. else if (type.value) {
  23401. // static type
  23402. switch (type.value.content) {
  23403. case 'radio':
  23404. res.props = [
  23405. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  23406. model,
  23407. value
  23408. ]))
  23409. ];
  23410. break;
  23411. case 'checkbox':
  23412. const trueValueBinding = findProp(node, 'true-value');
  23413. if (trueValueBinding) {
  23414. const trueValue = trueValueBinding.type === 6 /* ATTRIBUTE */
  23415. ? JSON.stringify(trueValueBinding.value.content)
  23416. : trueValueBinding.exp;
  23417. res.props = [
  23418. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  23419. model,
  23420. trueValue
  23421. ]))
  23422. ];
  23423. }
  23424. else {
  23425. res.props = [
  23426. createObjectProperty(`checked`, createConditionalExpression(createCallExpression(`Array.isArray`, [model]), createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  23427. model,
  23428. value
  23429. ]), model))
  23430. ];
  23431. }
  23432. break;
  23433. case 'file':
  23434. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  23435. break;
  23436. default:
  23437. checkDuplicatedValue();
  23438. res.props = defaultProps;
  23439. break;
  23440. }
  23441. }
  23442. }
  23443. else if (hasDynamicKeyVBind(node)) ;
  23444. else {
  23445. // text type
  23446. checkDuplicatedValue();
  23447. res.props = defaultProps;
  23448. }
  23449. }
  23450. else if (node.tag === 'textarea') {
  23451. checkDuplicatedValue();
  23452. node.children = [createInterpolation(model, model.loc)];
  23453. }
  23454. else if (node.tag === 'select') ;
  23455. else {
  23456. context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  23457. }
  23458. return res;
  23459. }
  23460. else {
  23461. // component v-model
  23462. return transformModel(dir, node, context);
  23463. }
  23464. };
  23465. function findValueBinding(node) {
  23466. const valueBinding = findProp(node, 'value');
  23467. return valueBinding
  23468. ? valueBinding.type === 7 /* DIRECTIVE */
  23469. ? valueBinding.exp
  23470. : createSimpleExpression(valueBinding.value.content, true)
  23471. : createSimpleExpression(`null`, false);
  23472. }
  23473. const ssrTransformShow = (dir, node, context) => {
  23474. if (!dir.exp) {
  23475. context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */));
  23476. }
  23477. return {
  23478. props: [
  23479. createObjectProperty(`style`, createConditionalExpression(dir.exp, createSimpleExpression(`null`, false), createObjectExpression([
  23480. createObjectProperty(`display`, createSimpleExpression(`none`, true))
  23481. ]), false /* no newline */))
  23482. ]
  23483. };
  23484. };
  23485. const hasSingleChild = (node) => node.children.filter(n => n.type !== 3 /* COMMENT */).length === 1;
  23486. const ssrInjectFallthroughAttrs = (node, context) => {
  23487. // _attrs is provided as a function argument.
  23488. // mark it as a known identifier so that it doesn't get prefixed by
  23489. // transformExpression.
  23490. if (node.type === 0 /* ROOT */) {
  23491. context.identifiers._attrs = 1;
  23492. }
  23493. const parent = context.parent;
  23494. if (!parent || parent.type !== 0 /* ROOT */) {
  23495. return;
  23496. }
  23497. if (node.type === 10 /* IF_BRANCH */ && hasSingleChild(node)) {
  23498. injectFallthroughAttrs(node.children[0]);
  23499. }
  23500. else if (hasSingleChild(parent)) {
  23501. injectFallthroughAttrs(node);
  23502. }
  23503. };
  23504. function injectFallthroughAttrs(node) {
  23505. if (node.type === 1 /* ELEMENT */ &&
  23506. (node.tagType === 0 /* ELEMENT */ ||
  23507. node.tagType === 1 /* COMPONENT */) &&
  23508. !findDir(node, 'for')) {
  23509. node.props.push({
  23510. type: 7 /* DIRECTIVE */,
  23511. name: 'bind',
  23512. arg: undefined,
  23513. exp: createSimpleExpression(`_attrs`, false),
  23514. modifiers: [],
  23515. loc: locStub
  23516. });
  23517. }
  23518. }
  23519. const ssrInjectCssVars = (node, context) => {
  23520. if (!context.ssrCssVars) {
  23521. return;
  23522. }
  23523. // _cssVars is initialized once per render function
  23524. // the code is injected in ssrCodegenTransform when creating the
  23525. // ssr transform context
  23526. if (node.type === 0 /* ROOT */) {
  23527. context.identifiers._cssVars = 1;
  23528. }
  23529. const parent = context.parent;
  23530. if (!parent || parent.type !== 0 /* ROOT */) {
  23531. return;
  23532. }
  23533. if (node.type === 10 /* IF_BRANCH */) {
  23534. for (const child of node.children) {
  23535. injectCssVars(child);
  23536. }
  23537. }
  23538. else {
  23539. injectCssVars(node);
  23540. }
  23541. };
  23542. function injectCssVars(node) {
  23543. if (node.type === 1 /* ELEMENT */ &&
  23544. (node.tagType === 0 /* ELEMENT */ ||
  23545. node.tagType === 1 /* COMPONENT */) &&
  23546. !findDir(node, 'for')) {
  23547. if (isBuiltInType(node.tag, 'Suspense')) {
  23548. for (const child of node.children) {
  23549. if (child.type === 1 /* ELEMENT */ &&
  23550. child.tagType === 3 /* TEMPLATE */) {
  23551. // suspense slot
  23552. child.children.forEach(injectCssVars);
  23553. }
  23554. else {
  23555. injectCssVars(child);
  23556. }
  23557. }
  23558. }
  23559. else {
  23560. node.props.push({
  23561. type: 7 /* DIRECTIVE */,
  23562. name: 'bind',
  23563. arg: undefined,
  23564. exp: createSimpleExpression(`_cssVars`, false),
  23565. modifiers: [],
  23566. loc: locStub
  23567. });
  23568. }
  23569. }
  23570. }
  23571. function compile$1(template, options = {}) {
  23572. options = {
  23573. ...options,
  23574. // apply DOM-specific parsing options
  23575. ...parserOptions,
  23576. ssr: true,
  23577. scopeId: options.mode === 'function' ? null : options.scopeId,
  23578. // always prefix since compiler-ssr doesn't have size concern
  23579. prefixIdentifiers: true,
  23580. // disable optimizations that are unnecessary for ssr
  23581. cacheHandlers: false,
  23582. hoistStatic: false
  23583. };
  23584. const ast = baseParse(template, options);
  23585. // Save raw options for AST. This is needed when performing sub-transforms
  23586. // on slot vnode branches.
  23587. rawOptionsMap.set(ast, options);
  23588. transform(ast, {
  23589. ...options,
  23590. nodeTransforms: [
  23591. ssrTransformIf,
  23592. ssrTransformFor,
  23593. trackVForSlotScopes,
  23594. transformExpression,
  23595. ssrTransformSlotOutlet,
  23596. ssrInjectFallthroughAttrs,
  23597. ssrInjectCssVars,
  23598. ssrTransformElement,
  23599. ssrTransformComponent,
  23600. trackSlotScopes,
  23601. transformStyle,
  23602. ...(options.nodeTransforms || []) // user transforms
  23603. ],
  23604. directiveTransforms: {
  23605. // reusing core v-bind
  23606. bind: transformBind,
  23607. // model and show has dedicated SSR handling
  23608. model: ssrTransformModel,
  23609. show: ssrTransformShow,
  23610. // the following are ignored during SSR
  23611. on: noopDirectiveTransform,
  23612. cloak: noopDirectiveTransform,
  23613. once: noopDirectiveTransform,
  23614. ...(options.directiveTransforms || {}) // user transforms
  23615. }
  23616. });
  23617. // traverse the template AST and convert into SSR codegen AST
  23618. // by replacing ast.codegenNode.
  23619. ssrCodegenTransform(ast, options);
  23620. return generate(ast, options);
  23621. }
  23622. var CompilerSSR = /*#__PURE__*/Object.freeze({
  23623. __proto__: null,
  23624. compile: compile$1
  23625. });
  23626. function preprocess({ source, filename, preprocessOptions }, preprocessor) {
  23627. // Consolidate exposes a callback based API, but the callback is in fact
  23628. // called synchronously for most templating engines. In our case, we have to
  23629. // expose a synchronous API so that it is usable in Jest transforms (which
  23630. // have to be sync because they are applied via Node.js require hooks)
  23631. let res = '';
  23632. let err = null;
  23633. preprocessor.render(source, { filename, ...preprocessOptions }, (_err, _res) => {
  23634. if (_err)
  23635. err = _err;
  23636. res = _res;
  23637. });
  23638. if (err)
  23639. throw err;
  23640. return res;
  23641. }
  23642. function compileTemplate(options) {
  23643. const { preprocessLang, preprocessCustomRequire } = options;
  23644. if (preprocessLang &&
  23645. !preprocessCustomRequire) {
  23646. throw new Error(`[@vue/compiler-sfc] Template preprocessing in the browser build must ` +
  23647. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  23648. `version of the preprocessor in the shape of { render(): string }.`);
  23649. }
  23650. const preprocessor = preprocessLang
  23651. ? preprocessCustomRequire
  23652. ? preprocessCustomRequire(preprocessLang)
  23653. : require('consolidate')[preprocessLang]
  23654. : false;
  23655. if (preprocessor) {
  23656. try {
  23657. return doCompileTemplate({
  23658. ...options,
  23659. source: preprocess(options, preprocessor)
  23660. });
  23661. }
  23662. catch (e) {
  23663. return {
  23664. code: `export default function render() {}`,
  23665. source: options.source,
  23666. tips: [],
  23667. errors: [e]
  23668. };
  23669. }
  23670. }
  23671. else if (preprocessLang) {
  23672. return {
  23673. code: `export default function render() {}`,
  23674. source: options.source,
  23675. tips: [
  23676. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  23677. ],
  23678. errors: [
  23679. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  23680. ]
  23681. };
  23682. }
  23683. else {
  23684. return doCompileTemplate(options);
  23685. }
  23686. }
  23687. function doCompileTemplate({ filename, id, scoped, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR : CompilerDOM, compilerOptions = {}, transformAssetUrls }) {
  23688. const errors = [];
  23689. let nodeTransforms = [];
  23690. if (isObject(transformAssetUrls)) {
  23691. const assetOptions = normalizeOptions(transformAssetUrls);
  23692. nodeTransforms = [
  23693. createAssetUrlTransformWithOptions(assetOptions),
  23694. createSrcsetTransformWithOptions(assetOptions)
  23695. ];
  23696. }
  23697. else if (transformAssetUrls !== false) {
  23698. nodeTransforms = [transformAssetUrl, transformSrcset];
  23699. }
  23700. if (ssr && !ssrCssVars) {
  23701. warnOnce(`compileTemplate is called with \`ssr: true\` but no ` +
  23702. `corresponding \`cssVars\` option.\`.`);
  23703. }
  23704. if (!id) {
  23705. warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
  23706. id = '';
  23707. }
  23708. const shortId = id.replace(/^data-v-/, '');
  23709. const longId = `data-v-${shortId}`;
  23710. let { code, ast, preamble, map } = compiler.compile(source, {
  23711. mode: 'module',
  23712. prefixIdentifiers: true,
  23713. hoistStatic: true,
  23714. cacheHandlers: true,
  23715. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length
  23716. ? genCssVarsFromList(ssrCssVars, shortId, isProd)
  23717. : '',
  23718. scopeId: scoped ? longId : undefined,
  23719. ...compilerOptions,
  23720. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  23721. filename,
  23722. sourceMap: true,
  23723. onError: e => errors.push(e)
  23724. });
  23725. // inMap should be the map produced by ./parse.ts which is a simple line-only
  23726. // mapping. If it is present, we need to adjust the final map and errors to
  23727. // reflect the original line numbers.
  23728. if (inMap) {
  23729. if (map) {
  23730. map = mapLines(inMap, map);
  23731. }
  23732. if (errors.length) {
  23733. patchErrors(errors, source, inMap);
  23734. }
  23735. }
  23736. return { code, ast, preamble, source, errors, tips: [], map };
  23737. }
  23738. function mapLines(oldMap, newMap) {
  23739. if (!oldMap)
  23740. return newMap;
  23741. if (!newMap)
  23742. return oldMap;
  23743. const oldMapConsumer = new SourceMapConsumer$1(oldMap);
  23744. const newMapConsumer = new SourceMapConsumer$1(newMap);
  23745. const mergedMapGenerator = new SourceMapGenerator$2();
  23746. newMapConsumer.eachMapping(m => {
  23747. if (m.originalLine == null) {
  23748. return;
  23749. }
  23750. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  23751. line: m.originalLine,
  23752. column: m.originalColumn
  23753. });
  23754. if (origPosInOldMap.source == null) {
  23755. return;
  23756. }
  23757. mergedMapGenerator.addMapping({
  23758. generated: {
  23759. line: m.generatedLine,
  23760. column: m.generatedColumn
  23761. },
  23762. original: {
  23763. line: origPosInOldMap.line,
  23764. // use current column, since the oldMap produced by @vue/compiler-sfc
  23765. // does not
  23766. column: m.originalColumn
  23767. },
  23768. source: origPosInOldMap.source,
  23769. name: origPosInOldMap.name
  23770. });
  23771. });
  23772. // source-map's type definition is incomplete
  23773. const generator = mergedMapGenerator;
  23774. oldMapConsumer.sources.forEach((sourceFile) => {
  23775. generator._sources.add(sourceFile);
  23776. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  23777. if (sourceContent != null) {
  23778. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  23779. }
  23780. });
  23781. generator._sourceRoot = oldMap.sourceRoot;
  23782. generator._file = oldMap.file;
  23783. return generator.toJSON();
  23784. }
  23785. function patchErrors(errors, source, inMap) {
  23786. const originalSource = inMap.sourcesContent[0];
  23787. const offset = originalSource.indexOf(source);
  23788. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  23789. errors.forEach(err => {
  23790. if (err.loc) {
  23791. err.loc.start.line += lineOffset;
  23792. err.loc.start.offset += offset;
  23793. if (err.loc.end !== err.loc.start) {
  23794. err.loc.end.line += lineOffset;
  23795. err.loc.end.offset += offset;
  23796. }
  23797. }
  23798. });
  23799. }
  23800. const trimPlugin = () => {
  23801. return {
  23802. postcssPlugin: 'vue-sfc-trim',
  23803. Once(root) {
  23804. root.walk(({ type, raws }) => {
  23805. if (type === 'rule' || type === 'atrule') {
  23806. if (raws.before)
  23807. raws.before = '\n';
  23808. if ('after' in raws && raws.after)
  23809. raws.after = '\n';
  23810. }
  23811. });
  23812. }
  23813. };
  23814. };
  23815. trimPlugin.postcss = true;
  23816. var indexesOf = function (ary, item) {
  23817. var i = -1, indexes = [];
  23818. while((i = ary.indexOf(item, i + 1)) !== -1)
  23819. indexes.push(i);
  23820. return indexes
  23821. };
  23822. function unique_pred(list, compare) {
  23823. var ptr = 1
  23824. , len = list.length
  23825. , a=list[0], b=list[0];
  23826. for(var i=1; i<len; ++i) {
  23827. b = a;
  23828. a = list[i];
  23829. if(compare(a, b)) {
  23830. if(i === ptr) {
  23831. ptr++;
  23832. continue
  23833. }
  23834. list[ptr++] = a;
  23835. }
  23836. }
  23837. list.length = ptr;
  23838. return list
  23839. }
  23840. function unique_eq(list) {
  23841. var ptr = 1
  23842. , len = list.length
  23843. , a=list[0], b = list[0];
  23844. for(var i=1; i<len; ++i, b=a) {
  23845. b = a;
  23846. a = list[i];
  23847. if(a !== b) {
  23848. if(i === ptr) {
  23849. ptr++;
  23850. continue
  23851. }
  23852. list[ptr++] = a;
  23853. }
  23854. }
  23855. list.length = ptr;
  23856. return list
  23857. }
  23858. function unique(list, compare, sorted) {
  23859. if(list.length === 0) {
  23860. return list
  23861. }
  23862. if(compare) {
  23863. if(!sorted) {
  23864. list.sort(compare);
  23865. }
  23866. return unique_pred(list, compare)
  23867. }
  23868. if(!sorted) {
  23869. list.sort();
  23870. }
  23871. return unique_eq(list)
  23872. }
  23873. var uniq = unique;
  23874. var unesc_1 = createCommonjsModule(function (module, exports) {
  23875. exports.__esModule = true;
  23876. exports.default = unesc;
  23877. var whitespace = '[\\x20\\t\\r\\n\\f]';
  23878. var unescapeRegExp = new RegExp('\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)', 'ig');
  23879. function unesc(str) {
  23880. return str.replace(unescapeRegExp, function (_, escaped, escapedWhitespace) {
  23881. var high = '0x' + escaped - 0x10000; // NaN means non-codepoint
  23882. // Workaround erroneous numeric interpretation of +"0x"
  23883. // eslint-disable-next-line no-self-compare
  23884. return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint
  23885. String.fromCharCode(high + 0x10000) : // Supplemental Plane codepoint (surrogate pair)
  23886. String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
  23887. });
  23888. }
  23889. module.exports = exports.default;
  23890. });
  23891. var getProp_1 = createCommonjsModule(function (module, exports) {
  23892. exports.__esModule = true;
  23893. exports.default = getProp;
  23894. function getProp(obj) {
  23895. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  23896. props[_key - 1] = arguments[_key];
  23897. }
  23898. while (props.length > 0) {
  23899. var prop = props.shift();
  23900. if (!obj[prop]) {
  23901. return undefined;
  23902. }
  23903. obj = obj[prop];
  23904. }
  23905. return obj;
  23906. }
  23907. module.exports = exports.default;
  23908. });
  23909. var ensureObject_1 = createCommonjsModule(function (module, exports) {
  23910. exports.__esModule = true;
  23911. exports.default = ensureObject;
  23912. function ensureObject(obj) {
  23913. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  23914. props[_key - 1] = arguments[_key];
  23915. }
  23916. while (props.length > 0) {
  23917. var prop = props.shift();
  23918. if (!obj[prop]) {
  23919. obj[prop] = {};
  23920. }
  23921. obj = obj[prop];
  23922. }
  23923. }
  23924. module.exports = exports.default;
  23925. });
  23926. var stripComments_1 = createCommonjsModule(function (module, exports) {
  23927. exports.__esModule = true;
  23928. exports.default = stripComments;
  23929. function stripComments(str) {
  23930. var s = "";
  23931. var commentStart = str.indexOf("/*");
  23932. var lastEnd = 0;
  23933. while (commentStart >= 0) {
  23934. s = s + str.slice(lastEnd, commentStart);
  23935. var commentEnd = str.indexOf("*/", commentStart + 2);
  23936. if (commentEnd < 0) {
  23937. return s;
  23938. }
  23939. lastEnd = commentEnd + 2;
  23940. commentStart = str.indexOf("/*", lastEnd);
  23941. }
  23942. s = s + str.slice(lastEnd);
  23943. return s;
  23944. }
  23945. module.exports = exports.default;
  23946. });
  23947. var util$1 = createCommonjsModule(function (module, exports) {
  23948. exports.__esModule = true;
  23949. exports.stripComments = exports.ensureObject = exports.getProp = exports.unesc = void 0;
  23950. var _unesc = _interopRequireDefault(unesc_1);
  23951. exports.unesc = _unesc.default;
  23952. var _getProp = _interopRequireDefault(getProp_1);
  23953. exports.getProp = _getProp.default;
  23954. var _ensureObject = _interopRequireDefault(ensureObject_1);
  23955. exports.ensureObject = _ensureObject.default;
  23956. var _stripComments = _interopRequireDefault(stripComments_1);
  23957. exports.stripComments = _stripComments.default;
  23958. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  23959. });
  23960. var node = createCommonjsModule(function (module, exports) {
  23961. exports.__esModule = true;
  23962. exports.default = void 0;
  23963. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  23964. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  23965. var cloneNode = function cloneNode(obj, parent) {
  23966. if (typeof obj !== 'object' || obj === null) {
  23967. return obj;
  23968. }
  23969. var cloned = new obj.constructor();
  23970. for (var i in obj) {
  23971. if (!obj.hasOwnProperty(i)) {
  23972. continue;
  23973. }
  23974. var value = obj[i];
  23975. var type = typeof value;
  23976. if (i === 'parent' && type === 'object') {
  23977. if (parent) {
  23978. cloned[i] = parent;
  23979. }
  23980. } else if (value instanceof Array) {
  23981. cloned[i] = value.map(function (j) {
  23982. return cloneNode(j, cloned);
  23983. });
  23984. } else {
  23985. cloned[i] = cloneNode(value, cloned);
  23986. }
  23987. }
  23988. return cloned;
  23989. };
  23990. var Node =
  23991. /*#__PURE__*/
  23992. function () {
  23993. function Node(opts) {
  23994. if (opts === void 0) {
  23995. opts = {};
  23996. }
  23997. Object.assign(this, opts);
  23998. this.spaces = this.spaces || {};
  23999. this.spaces.before = this.spaces.before || '';
  24000. this.spaces.after = this.spaces.after || '';
  24001. }
  24002. var _proto = Node.prototype;
  24003. _proto.remove = function remove() {
  24004. if (this.parent) {
  24005. this.parent.removeChild(this);
  24006. }
  24007. this.parent = undefined;
  24008. return this;
  24009. };
  24010. _proto.replaceWith = function replaceWith() {
  24011. if (this.parent) {
  24012. for (var index in arguments) {
  24013. this.parent.insertBefore(this, arguments[index]);
  24014. }
  24015. this.remove();
  24016. }
  24017. return this;
  24018. };
  24019. _proto.next = function next() {
  24020. return this.parent.at(this.parent.index(this) + 1);
  24021. };
  24022. _proto.prev = function prev() {
  24023. return this.parent.at(this.parent.index(this) - 1);
  24024. };
  24025. _proto.clone = function clone(overrides) {
  24026. if (overrides === void 0) {
  24027. overrides = {};
  24028. }
  24029. var cloned = cloneNode(this);
  24030. for (var name in overrides) {
  24031. cloned[name] = overrides[name];
  24032. }
  24033. return cloned;
  24034. }
  24035. /**
  24036. * Some non-standard syntax doesn't follow normal escaping rules for css.
  24037. * This allows non standard syntax to be appended to an existing property
  24038. * by specifying the escaped value. By specifying the escaped value,
  24039. * illegal characters are allowed to be directly inserted into css output.
  24040. * @param {string} name the property to set
  24041. * @param {any} value the unescaped value of the property
  24042. * @param {string} valueEscaped optional. the escaped value of the property.
  24043. */
  24044. ;
  24045. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  24046. if (!this.raws) {
  24047. this.raws = {};
  24048. }
  24049. var originalValue = this[name];
  24050. var originalEscaped = this.raws[name];
  24051. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  24052. if (originalEscaped || valueEscaped !== value) {
  24053. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  24054. } else {
  24055. delete this.raws[name]; // delete any escaped value that was created by the setter.
  24056. }
  24057. }
  24058. /**
  24059. * Some non-standard syntax doesn't follow normal escaping rules for css.
  24060. * This allows the escaped value to be specified directly, allowing illegal
  24061. * characters to be directly inserted into css output.
  24062. * @param {string} name the property to set
  24063. * @param {any} value the unescaped value of the property
  24064. * @param {string} valueEscaped the escaped value of the property.
  24065. */
  24066. ;
  24067. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  24068. if (!this.raws) {
  24069. this.raws = {};
  24070. }
  24071. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  24072. this.raws[name] = valueEscaped;
  24073. }
  24074. /**
  24075. * When you want a value to passed through to CSS directly. This method
  24076. * deletes the corresponding raw value causing the stringifier to fallback
  24077. * to the unescaped value.
  24078. * @param {string} name the property to set.
  24079. * @param {any} value The value that is both escaped and unescaped.
  24080. */
  24081. ;
  24082. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  24083. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  24084. if (this.raws) {
  24085. delete this.raws[name];
  24086. }
  24087. }
  24088. /**
  24089. *
  24090. * @param {number} line The number (starting with 1)
  24091. * @param {number} column The column number (starting with 1)
  24092. */
  24093. ;
  24094. _proto.isAtPosition = function isAtPosition(line, column) {
  24095. if (this.source && this.source.start && this.source.end) {
  24096. if (this.source.start.line > line) {
  24097. return false;
  24098. }
  24099. if (this.source.end.line < line) {
  24100. return false;
  24101. }
  24102. if (this.source.start.line === line && this.source.start.column > column) {
  24103. return false;
  24104. }
  24105. if (this.source.end.line === line && this.source.end.column < column) {
  24106. return false;
  24107. }
  24108. return true;
  24109. }
  24110. return undefined;
  24111. };
  24112. _proto.stringifyProperty = function stringifyProperty(name) {
  24113. return this.raws && this.raws[name] || this[name];
  24114. };
  24115. _proto.valueToString = function valueToString() {
  24116. return String(this.stringifyProperty("value"));
  24117. };
  24118. _proto.toString = function toString() {
  24119. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  24120. };
  24121. _createClass(Node, [{
  24122. key: "rawSpaceBefore",
  24123. get: function get() {
  24124. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  24125. if (rawSpace === undefined) {
  24126. rawSpace = this.spaces && this.spaces.before;
  24127. }
  24128. return rawSpace || "";
  24129. },
  24130. set: function set(raw) {
  24131. (0, util$1.ensureObject)(this, "raws", "spaces");
  24132. this.raws.spaces.before = raw;
  24133. }
  24134. }, {
  24135. key: "rawSpaceAfter",
  24136. get: function get() {
  24137. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  24138. if (rawSpace === undefined) {
  24139. rawSpace = this.spaces.after;
  24140. }
  24141. return rawSpace || "";
  24142. },
  24143. set: function set(raw) {
  24144. (0, util$1.ensureObject)(this, "raws", "spaces");
  24145. this.raws.spaces.after = raw;
  24146. }
  24147. }]);
  24148. return Node;
  24149. }();
  24150. exports.default = Node;
  24151. module.exports = exports.default;
  24152. });
  24153. var types$2 = createCommonjsModule(function (module, exports) {
  24154. exports.__esModule = true;
  24155. exports.UNIVERSAL = exports.ATTRIBUTE = exports.CLASS = exports.COMBINATOR = exports.COMMENT = exports.ID = exports.NESTING = exports.PSEUDO = exports.ROOT = exports.SELECTOR = exports.STRING = exports.TAG = void 0;
  24156. var TAG = 'tag';
  24157. exports.TAG = TAG;
  24158. var STRING = 'string';
  24159. exports.STRING = STRING;
  24160. var SELECTOR = 'selector';
  24161. exports.SELECTOR = SELECTOR;
  24162. var ROOT = 'root';
  24163. exports.ROOT = ROOT;
  24164. var PSEUDO = 'pseudo';
  24165. exports.PSEUDO = PSEUDO;
  24166. var NESTING = 'nesting';
  24167. exports.NESTING = NESTING;
  24168. var ID = 'id';
  24169. exports.ID = ID;
  24170. var COMMENT = 'comment';
  24171. exports.COMMENT = COMMENT;
  24172. var COMBINATOR = 'combinator';
  24173. exports.COMBINATOR = COMBINATOR;
  24174. var CLASS = 'class';
  24175. exports.CLASS = CLASS;
  24176. var ATTRIBUTE = 'attribute';
  24177. exports.ATTRIBUTE = ATTRIBUTE;
  24178. var UNIVERSAL = 'universal';
  24179. exports.UNIVERSAL = UNIVERSAL;
  24180. });
  24181. var container = createCommonjsModule(function (module, exports) {
  24182. exports.__esModule = true;
  24183. exports.default = void 0;
  24184. var _node = _interopRequireDefault(node);
  24185. var types = _interopRequireWildcard(types$2);
  24186. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
  24187. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24188. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  24189. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  24190. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24191. var Container =
  24192. /*#__PURE__*/
  24193. function (_Node) {
  24194. _inheritsLoose(Container, _Node);
  24195. function Container(opts) {
  24196. var _this;
  24197. _this = _Node.call(this, opts) || this;
  24198. if (!_this.nodes) {
  24199. _this.nodes = [];
  24200. }
  24201. return _this;
  24202. }
  24203. var _proto = Container.prototype;
  24204. _proto.append = function append(selector) {
  24205. selector.parent = this;
  24206. this.nodes.push(selector);
  24207. return this;
  24208. };
  24209. _proto.prepend = function prepend(selector) {
  24210. selector.parent = this;
  24211. this.nodes.unshift(selector);
  24212. return this;
  24213. };
  24214. _proto.at = function at(index) {
  24215. return this.nodes[index];
  24216. };
  24217. _proto.index = function index(child) {
  24218. if (typeof child === 'number') {
  24219. return child;
  24220. }
  24221. return this.nodes.indexOf(child);
  24222. };
  24223. _proto.removeChild = function removeChild(child) {
  24224. child = this.index(child);
  24225. this.at(child).parent = undefined;
  24226. this.nodes.splice(child, 1);
  24227. var index;
  24228. for (var id in this.indexes) {
  24229. index = this.indexes[id];
  24230. if (index >= child) {
  24231. this.indexes[id] = index - 1;
  24232. }
  24233. }
  24234. return this;
  24235. };
  24236. _proto.removeAll = function removeAll() {
  24237. for (var _iterator = this.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  24238. var _ref;
  24239. if (_isArray) {
  24240. if (_i >= _iterator.length) break;
  24241. _ref = _iterator[_i++];
  24242. } else {
  24243. _i = _iterator.next();
  24244. if (_i.done) break;
  24245. _ref = _i.value;
  24246. }
  24247. var node = _ref;
  24248. node.parent = undefined;
  24249. }
  24250. this.nodes = [];
  24251. return this;
  24252. };
  24253. _proto.empty = function empty() {
  24254. return this.removeAll();
  24255. };
  24256. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  24257. newNode.parent = this;
  24258. var oldIndex = this.index(oldNode);
  24259. this.nodes.splice(oldIndex + 1, 0, newNode);
  24260. newNode.parent = this;
  24261. var index;
  24262. for (var id in this.indexes) {
  24263. index = this.indexes[id];
  24264. if (oldIndex <= index) {
  24265. this.indexes[id] = index + 1;
  24266. }
  24267. }
  24268. return this;
  24269. };
  24270. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  24271. newNode.parent = this;
  24272. var oldIndex = this.index(oldNode);
  24273. this.nodes.splice(oldIndex, 0, newNode);
  24274. newNode.parent = this;
  24275. var index;
  24276. for (var id in this.indexes) {
  24277. index = this.indexes[id];
  24278. if (index <= oldIndex) {
  24279. this.indexes[id] = index + 1;
  24280. }
  24281. }
  24282. return this;
  24283. };
  24284. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  24285. var found = undefined;
  24286. this.each(function (node) {
  24287. if (node.atPosition) {
  24288. var foundChild = node.atPosition(line, col);
  24289. if (foundChild) {
  24290. found = foundChild;
  24291. return false;
  24292. }
  24293. } else if (node.isAtPosition(line, col)) {
  24294. found = node;
  24295. return false;
  24296. }
  24297. });
  24298. return found;
  24299. }
  24300. /**
  24301. * Return the most specific node at the line and column number given.
  24302. * The source location is based on the original parsed location, locations aren't
  24303. * updated as selector nodes are mutated.
  24304. *
  24305. * Note that this location is relative to the location of the first character
  24306. * of the selector, and not the location of the selector in the overall document
  24307. * when used in conjunction with postcss.
  24308. *
  24309. * If not found, returns undefined.
  24310. * @param {number} line The line number of the node to find. (1-based index)
  24311. * @param {number} col The column number of the node to find. (1-based index)
  24312. */
  24313. ;
  24314. _proto.atPosition = function atPosition(line, col) {
  24315. if (this.isAtPosition(line, col)) {
  24316. return this._findChildAtPosition(line, col) || this;
  24317. } else {
  24318. return undefined;
  24319. }
  24320. };
  24321. _proto._inferEndPosition = function _inferEndPosition() {
  24322. if (this.last && this.last.source && this.last.source.end) {
  24323. this.source = this.source || {};
  24324. this.source.end = this.source.end || {};
  24325. Object.assign(this.source.end, this.last.source.end);
  24326. }
  24327. };
  24328. _proto.each = function each(callback) {
  24329. if (!this.lastEach) {
  24330. this.lastEach = 0;
  24331. }
  24332. if (!this.indexes) {
  24333. this.indexes = {};
  24334. }
  24335. this.lastEach++;
  24336. var id = this.lastEach;
  24337. this.indexes[id] = 0;
  24338. if (!this.length) {
  24339. return undefined;
  24340. }
  24341. var index, result;
  24342. while (this.indexes[id] < this.length) {
  24343. index = this.indexes[id];
  24344. result = callback(this.at(index), index);
  24345. if (result === false) {
  24346. break;
  24347. }
  24348. this.indexes[id] += 1;
  24349. }
  24350. delete this.indexes[id];
  24351. if (result === false) {
  24352. return false;
  24353. }
  24354. };
  24355. _proto.walk = function walk(callback) {
  24356. return this.each(function (node, i) {
  24357. var result = callback(node, i);
  24358. if (result !== false && node.length) {
  24359. result = node.walk(callback);
  24360. }
  24361. if (result === false) {
  24362. return false;
  24363. }
  24364. });
  24365. };
  24366. _proto.walkAttributes = function walkAttributes(callback) {
  24367. var _this2 = this;
  24368. return this.walk(function (selector) {
  24369. if (selector.type === types.ATTRIBUTE) {
  24370. return callback.call(_this2, selector);
  24371. }
  24372. });
  24373. };
  24374. _proto.walkClasses = function walkClasses(callback) {
  24375. var _this3 = this;
  24376. return this.walk(function (selector) {
  24377. if (selector.type === types.CLASS) {
  24378. return callback.call(_this3, selector);
  24379. }
  24380. });
  24381. };
  24382. _proto.walkCombinators = function walkCombinators(callback) {
  24383. var _this4 = this;
  24384. return this.walk(function (selector) {
  24385. if (selector.type === types.COMBINATOR) {
  24386. return callback.call(_this4, selector);
  24387. }
  24388. });
  24389. };
  24390. _proto.walkComments = function walkComments(callback) {
  24391. var _this5 = this;
  24392. return this.walk(function (selector) {
  24393. if (selector.type === types.COMMENT) {
  24394. return callback.call(_this5, selector);
  24395. }
  24396. });
  24397. };
  24398. _proto.walkIds = function walkIds(callback) {
  24399. var _this6 = this;
  24400. return this.walk(function (selector) {
  24401. if (selector.type === types.ID) {
  24402. return callback.call(_this6, selector);
  24403. }
  24404. });
  24405. };
  24406. _proto.walkNesting = function walkNesting(callback) {
  24407. var _this7 = this;
  24408. return this.walk(function (selector) {
  24409. if (selector.type === types.NESTING) {
  24410. return callback.call(_this7, selector);
  24411. }
  24412. });
  24413. };
  24414. _proto.walkPseudos = function walkPseudos(callback) {
  24415. var _this8 = this;
  24416. return this.walk(function (selector) {
  24417. if (selector.type === types.PSEUDO) {
  24418. return callback.call(_this8, selector);
  24419. }
  24420. });
  24421. };
  24422. _proto.walkTags = function walkTags(callback) {
  24423. var _this9 = this;
  24424. return this.walk(function (selector) {
  24425. if (selector.type === types.TAG) {
  24426. return callback.call(_this9, selector);
  24427. }
  24428. });
  24429. };
  24430. _proto.walkUniversals = function walkUniversals(callback) {
  24431. var _this10 = this;
  24432. return this.walk(function (selector) {
  24433. if (selector.type === types.UNIVERSAL) {
  24434. return callback.call(_this10, selector);
  24435. }
  24436. });
  24437. };
  24438. _proto.split = function split(callback) {
  24439. var _this11 = this;
  24440. var current = [];
  24441. return this.reduce(function (memo, node, index) {
  24442. var split = callback.call(_this11, node);
  24443. current.push(node);
  24444. if (split) {
  24445. memo.push(current);
  24446. current = [];
  24447. } else if (index === _this11.length - 1) {
  24448. memo.push(current);
  24449. }
  24450. return memo;
  24451. }, []);
  24452. };
  24453. _proto.map = function map(callback) {
  24454. return this.nodes.map(callback);
  24455. };
  24456. _proto.reduce = function reduce(callback, memo) {
  24457. return this.nodes.reduce(callback, memo);
  24458. };
  24459. _proto.every = function every(callback) {
  24460. return this.nodes.every(callback);
  24461. };
  24462. _proto.some = function some(callback) {
  24463. return this.nodes.some(callback);
  24464. };
  24465. _proto.filter = function filter(callback) {
  24466. return this.nodes.filter(callback);
  24467. };
  24468. _proto.sort = function sort(callback) {
  24469. return this.nodes.sort(callback);
  24470. };
  24471. _proto.toString = function toString() {
  24472. return this.map(String).join('');
  24473. };
  24474. _createClass(Container, [{
  24475. key: "first",
  24476. get: function get() {
  24477. return this.at(0);
  24478. }
  24479. }, {
  24480. key: "last",
  24481. get: function get() {
  24482. return this.at(this.length - 1);
  24483. }
  24484. }, {
  24485. key: "length",
  24486. get: function get() {
  24487. return this.nodes.length;
  24488. }
  24489. }]);
  24490. return Container;
  24491. }(_node.default);
  24492. exports.default = Container;
  24493. module.exports = exports.default;
  24494. });
  24495. var root = createCommonjsModule(function (module, exports) {
  24496. exports.__esModule = true;
  24497. exports.default = void 0;
  24498. var _container = _interopRequireDefault(container);
  24499. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24500. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  24501. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  24502. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24503. var Root =
  24504. /*#__PURE__*/
  24505. function (_Container) {
  24506. _inheritsLoose(Root, _Container);
  24507. function Root(opts) {
  24508. var _this;
  24509. _this = _Container.call(this, opts) || this;
  24510. _this.type = types$2.ROOT;
  24511. return _this;
  24512. }
  24513. var _proto = Root.prototype;
  24514. _proto.toString = function toString() {
  24515. var str = this.reduce(function (memo, selector) {
  24516. memo.push(String(selector));
  24517. return memo;
  24518. }, []).join(',');
  24519. return this.trailingComma ? str + ',' : str;
  24520. };
  24521. _proto.error = function error(message, options) {
  24522. if (this._error) {
  24523. return this._error(message, options);
  24524. } else {
  24525. return new Error(message);
  24526. }
  24527. };
  24528. _createClass(Root, [{
  24529. key: "errorGenerator",
  24530. set: function set(handler) {
  24531. this._error = handler;
  24532. }
  24533. }]);
  24534. return Root;
  24535. }(_container.default);
  24536. exports.default = Root;
  24537. module.exports = exports.default;
  24538. });
  24539. var selector = createCommonjsModule(function (module, exports) {
  24540. exports.__esModule = true;
  24541. exports.default = void 0;
  24542. var _container = _interopRequireDefault(container);
  24543. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24544. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24545. var Selector =
  24546. /*#__PURE__*/
  24547. function (_Container) {
  24548. _inheritsLoose(Selector, _Container);
  24549. function Selector(opts) {
  24550. var _this;
  24551. _this = _Container.call(this, opts) || this;
  24552. _this.type = types$2.SELECTOR;
  24553. return _this;
  24554. }
  24555. return Selector;
  24556. }(_container.default);
  24557. exports.default = Selector;
  24558. module.exports = exports.default;
  24559. });
  24560. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  24561. var object = {};
  24562. var hasOwnProperty$1 = object.hasOwnProperty;
  24563. var merge = function merge(options, defaults) {
  24564. if (!options) {
  24565. return defaults;
  24566. }
  24567. var result = {};
  24568. for (var key in defaults) {
  24569. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  24570. // only recognized option names are used.
  24571. result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key];
  24572. }
  24573. return result;
  24574. };
  24575. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  24576. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  24577. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  24578. // https://mathiasbynens.be/notes/css-escapes#css
  24579. var cssesc = function cssesc(string, options) {
  24580. options = merge(options, cssesc.options);
  24581. if (options.quotes != 'single' && options.quotes != 'double') {
  24582. options.quotes = 'single';
  24583. }
  24584. var quote = options.quotes == 'double' ? '"' : '\'';
  24585. var isIdentifier = options.isIdentifier;
  24586. var firstChar = string.charAt(0);
  24587. var output = '';
  24588. var counter = 0;
  24589. var length = string.length;
  24590. while (counter < length) {
  24591. var character = string.charAt(counter++);
  24592. var codePoint = character.charCodeAt();
  24593. var value = void 0;
  24594. // If it’s not a printable ASCII character…
  24595. if (codePoint < 0x20 || codePoint > 0x7E) {
  24596. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  24597. // It’s a high surrogate, and there is a next character.
  24598. var extra = string.charCodeAt(counter++);
  24599. if ((extra & 0xFC00) == 0xDC00) {
  24600. // next character is low surrogate
  24601. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  24602. } else {
  24603. // It’s an unmatched surrogate; only append this code unit, in case
  24604. // the next code unit is the high surrogate of a surrogate pair.
  24605. counter--;
  24606. }
  24607. }
  24608. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  24609. } else {
  24610. if (options.escapeEverything) {
  24611. if (regexAnySingleEscape.test(character)) {
  24612. value = '\\' + character;
  24613. } else {
  24614. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  24615. }
  24616. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  24617. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  24618. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  24619. value = '\\' + character;
  24620. } else {
  24621. value = character;
  24622. }
  24623. }
  24624. output += value;
  24625. }
  24626. if (isIdentifier) {
  24627. if (/^-[-\d]/.test(output)) {
  24628. output = '\\-' + output.slice(1);
  24629. } else if (/\d/.test(firstChar)) {
  24630. output = '\\3' + firstChar + ' ' + output.slice(1);
  24631. }
  24632. }
  24633. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  24634. // since they’re redundant. Note that this is only possible if the escape
  24635. // sequence isn’t preceded by an odd number of backslashes.
  24636. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  24637. if ($1 && $1.length % 2) {
  24638. // It’s not safe to remove the space, so don’t.
  24639. return $0;
  24640. }
  24641. // Strip the space.
  24642. return ($1 || '') + $2;
  24643. });
  24644. if (!isIdentifier && options.wrap) {
  24645. return quote + output + quote;
  24646. }
  24647. return output;
  24648. };
  24649. // Expose default options (so they can be overridden globally).
  24650. cssesc.options = {
  24651. 'escapeEverything': false,
  24652. 'isIdentifier': false,
  24653. 'quotes': 'single',
  24654. 'wrap': false
  24655. };
  24656. cssesc.version = '3.0.0';
  24657. var cssesc_1 = cssesc;
  24658. var className = createCommonjsModule(function (module, exports) {
  24659. exports.__esModule = true;
  24660. exports.default = void 0;
  24661. var _cssesc = _interopRequireDefault(cssesc_1);
  24662. var _node = _interopRequireDefault(node);
  24663. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24664. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  24665. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  24666. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24667. var ClassName =
  24668. /*#__PURE__*/
  24669. function (_Node) {
  24670. _inheritsLoose(ClassName, _Node);
  24671. function ClassName(opts) {
  24672. var _this;
  24673. _this = _Node.call(this, opts) || this;
  24674. _this.type = types$2.CLASS;
  24675. _this._constructed = true;
  24676. return _this;
  24677. }
  24678. var _proto = ClassName.prototype;
  24679. _proto.valueToString = function valueToString() {
  24680. return '.' + _Node.prototype.valueToString.call(this);
  24681. };
  24682. _createClass(ClassName, [{
  24683. key: "value",
  24684. set: function set(v) {
  24685. if (this._constructed) {
  24686. var escaped = (0, _cssesc.default)(v, {
  24687. isIdentifier: true
  24688. });
  24689. if (escaped !== v) {
  24690. (0, util$1.ensureObject)(this, "raws");
  24691. this.raws.value = escaped;
  24692. } else if (this.raws) {
  24693. delete this.raws.value;
  24694. }
  24695. }
  24696. this._value = v;
  24697. },
  24698. get: function get() {
  24699. return this._value;
  24700. }
  24701. }]);
  24702. return ClassName;
  24703. }(_node.default);
  24704. exports.default = ClassName;
  24705. module.exports = exports.default;
  24706. });
  24707. var comment = createCommonjsModule(function (module, exports) {
  24708. exports.__esModule = true;
  24709. exports.default = void 0;
  24710. var _node = _interopRequireDefault(node);
  24711. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24712. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24713. var Comment =
  24714. /*#__PURE__*/
  24715. function (_Node) {
  24716. _inheritsLoose(Comment, _Node);
  24717. function Comment(opts) {
  24718. var _this;
  24719. _this = _Node.call(this, opts) || this;
  24720. _this.type = types$2.COMMENT;
  24721. return _this;
  24722. }
  24723. return Comment;
  24724. }(_node.default);
  24725. exports.default = Comment;
  24726. module.exports = exports.default;
  24727. });
  24728. var id = createCommonjsModule(function (module, exports) {
  24729. exports.__esModule = true;
  24730. exports.default = void 0;
  24731. var _node = _interopRequireDefault(node);
  24732. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24733. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24734. var ID =
  24735. /*#__PURE__*/
  24736. function (_Node) {
  24737. _inheritsLoose(ID, _Node);
  24738. function ID(opts) {
  24739. var _this;
  24740. _this = _Node.call(this, opts) || this;
  24741. _this.type = types$2.ID;
  24742. return _this;
  24743. }
  24744. var _proto = ID.prototype;
  24745. _proto.valueToString = function valueToString() {
  24746. return '#' + _Node.prototype.valueToString.call(this);
  24747. };
  24748. return ID;
  24749. }(_node.default);
  24750. exports.default = ID;
  24751. module.exports = exports.default;
  24752. });
  24753. var namespace = createCommonjsModule(function (module, exports) {
  24754. exports.__esModule = true;
  24755. exports.default = void 0;
  24756. var _cssesc = _interopRequireDefault(cssesc_1);
  24757. var _node = _interopRequireDefault(node);
  24758. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24759. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  24760. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  24761. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24762. var Namespace =
  24763. /*#__PURE__*/
  24764. function (_Node) {
  24765. _inheritsLoose(Namespace, _Node);
  24766. function Namespace() {
  24767. return _Node.apply(this, arguments) || this;
  24768. }
  24769. var _proto = Namespace.prototype;
  24770. _proto.qualifiedName = function qualifiedName(value) {
  24771. if (this.namespace) {
  24772. return this.namespaceString + "|" + value;
  24773. } else {
  24774. return value;
  24775. }
  24776. };
  24777. _proto.valueToString = function valueToString() {
  24778. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  24779. };
  24780. _createClass(Namespace, [{
  24781. key: "namespace",
  24782. get: function get() {
  24783. return this._namespace;
  24784. },
  24785. set: function set(namespace) {
  24786. if (namespace === true || namespace === "*" || namespace === "&") {
  24787. this._namespace = namespace;
  24788. if (this.raws) {
  24789. delete this.raws.namespace;
  24790. }
  24791. return;
  24792. }
  24793. var escaped = (0, _cssesc.default)(namespace, {
  24794. isIdentifier: true
  24795. });
  24796. this._namespace = namespace;
  24797. if (escaped !== namespace) {
  24798. (0, util$1.ensureObject)(this, "raws");
  24799. this.raws.namespace = escaped;
  24800. } else if (this.raws) {
  24801. delete this.raws.namespace;
  24802. }
  24803. }
  24804. }, {
  24805. key: "ns",
  24806. get: function get() {
  24807. return this._namespace;
  24808. },
  24809. set: function set(namespace) {
  24810. this.namespace = namespace;
  24811. }
  24812. }, {
  24813. key: "namespaceString",
  24814. get: function get() {
  24815. if (this.namespace) {
  24816. var ns = this.stringifyProperty("namespace");
  24817. if (ns === true) {
  24818. return '';
  24819. } else {
  24820. return ns;
  24821. }
  24822. } else {
  24823. return '';
  24824. }
  24825. }
  24826. }]);
  24827. return Namespace;
  24828. }(_node.default);
  24829. exports.default = Namespace;
  24830. module.exports = exports.default;
  24831. });
  24832. var tag = createCommonjsModule(function (module, exports) {
  24833. exports.__esModule = true;
  24834. exports.default = void 0;
  24835. var _namespace = _interopRequireDefault(namespace);
  24836. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24837. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24838. var Tag =
  24839. /*#__PURE__*/
  24840. function (_Namespace) {
  24841. _inheritsLoose(Tag, _Namespace);
  24842. function Tag(opts) {
  24843. var _this;
  24844. _this = _Namespace.call(this, opts) || this;
  24845. _this.type = types$2.TAG;
  24846. return _this;
  24847. }
  24848. return Tag;
  24849. }(_namespace.default);
  24850. exports.default = Tag;
  24851. module.exports = exports.default;
  24852. });
  24853. var string = createCommonjsModule(function (module, exports) {
  24854. exports.__esModule = true;
  24855. exports.default = void 0;
  24856. var _node = _interopRequireDefault(node);
  24857. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24858. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24859. var String =
  24860. /*#__PURE__*/
  24861. function (_Node) {
  24862. _inheritsLoose(String, _Node);
  24863. function String(opts) {
  24864. var _this;
  24865. _this = _Node.call(this, opts) || this;
  24866. _this.type = types$2.STRING;
  24867. return _this;
  24868. }
  24869. return String;
  24870. }(_node.default);
  24871. exports.default = String;
  24872. module.exports = exports.default;
  24873. });
  24874. var pseudo = createCommonjsModule(function (module, exports) {
  24875. exports.__esModule = true;
  24876. exports.default = void 0;
  24877. var _container = _interopRequireDefault(container);
  24878. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24879. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24880. var Pseudo =
  24881. /*#__PURE__*/
  24882. function (_Container) {
  24883. _inheritsLoose(Pseudo, _Container);
  24884. function Pseudo(opts) {
  24885. var _this;
  24886. _this = _Container.call(this, opts) || this;
  24887. _this.type = types$2.PSEUDO;
  24888. return _this;
  24889. }
  24890. var _proto = Pseudo.prototype;
  24891. _proto.toString = function toString() {
  24892. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  24893. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  24894. };
  24895. return Pseudo;
  24896. }(_container.default);
  24897. exports.default = Pseudo;
  24898. module.exports = exports.default;
  24899. });
  24900. /**
  24901. * For Node.js, simply re-export the core `util.deprecate` function.
  24902. */
  24903. var node$1 = require$$0__default.deprecate;
  24904. var attribute = createCommonjsModule(function (module, exports) {
  24905. exports.__esModule = true;
  24906. exports.unescapeValue = unescapeValue;
  24907. exports.default = void 0;
  24908. var _cssesc = _interopRequireDefault(cssesc_1);
  24909. var _unesc = _interopRequireDefault(unesc_1);
  24910. var _namespace = _interopRequireDefault(namespace);
  24911. var _CSSESC_QUOTE_OPTIONS;
  24912. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24913. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  24914. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  24915. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24916. var WRAPPED_IN_QUOTES = /^('|")(.*)\1$/;
  24917. var warnOfDeprecatedValueAssignment = node$1(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  24918. var warnOfDeprecatedQuotedAssignment = node$1(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  24919. var warnOfDeprecatedConstructor = node$1(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  24920. function unescapeValue(value) {
  24921. var deprecatedUsage = false;
  24922. var quoteMark = null;
  24923. var unescaped = value;
  24924. var m = unescaped.match(WRAPPED_IN_QUOTES);
  24925. if (m) {
  24926. quoteMark = m[1];
  24927. unescaped = m[2];
  24928. }
  24929. unescaped = (0, _unesc.default)(unescaped);
  24930. if (unescaped !== value) {
  24931. deprecatedUsage = true;
  24932. }
  24933. return {
  24934. deprecatedUsage: deprecatedUsage,
  24935. unescaped: unescaped,
  24936. quoteMark: quoteMark
  24937. };
  24938. }
  24939. function handleDeprecatedContructorOpts(opts) {
  24940. if (opts.quoteMark !== undefined) {
  24941. return opts;
  24942. }
  24943. if (opts.value === undefined) {
  24944. return opts;
  24945. }
  24946. warnOfDeprecatedConstructor();
  24947. var _unescapeValue = unescapeValue(opts.value),
  24948. quoteMark = _unescapeValue.quoteMark,
  24949. unescaped = _unescapeValue.unescaped;
  24950. if (!opts.raws) {
  24951. opts.raws = {};
  24952. }
  24953. if (opts.raws.value === undefined) {
  24954. opts.raws.value = opts.value;
  24955. }
  24956. opts.value = unescaped;
  24957. opts.quoteMark = quoteMark;
  24958. return opts;
  24959. }
  24960. var Attribute =
  24961. /*#__PURE__*/
  24962. function (_Namespace) {
  24963. _inheritsLoose(Attribute, _Namespace);
  24964. function Attribute(opts) {
  24965. var _this;
  24966. if (opts === void 0) {
  24967. opts = {};
  24968. }
  24969. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  24970. _this.type = types$2.ATTRIBUTE;
  24971. _this.raws = _this.raws || {};
  24972. Object.defineProperty(_this.raws, 'unquoted', {
  24973. get: node$1(function () {
  24974. return _this.value;
  24975. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  24976. set: node$1(function () {
  24977. return _this.value;
  24978. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  24979. });
  24980. _this._constructed = true;
  24981. return _this;
  24982. }
  24983. /**
  24984. * Returns the Attribute's value quoted such that it would be legal to use
  24985. * in the value of a css file. The original value's quotation setting
  24986. * used for stringification is left unchanged. See `setValue(value, options)`
  24987. * if you want to control the quote settings of a new value for the attribute.
  24988. *
  24989. * You can also change the quotation used for the current value by setting quoteMark.
  24990. *
  24991. * Options:
  24992. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  24993. * option is not set, the original value for quoteMark will be used. If
  24994. * indeterminate, a double quote is used. The legal values are:
  24995. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  24996. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  24997. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  24998. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  24999. * over the quoteMark option value.
  25000. * * smart {boolean} - if true, will select a quote mark based on the value
  25001. * and the other options specified here. See the `smartQuoteMark()`
  25002. * method.
  25003. **/
  25004. var _proto = Attribute.prototype;
  25005. _proto.getQuotedValue = function getQuotedValue(options) {
  25006. if (options === void 0) {
  25007. options = {};
  25008. }
  25009. var quoteMark = this._determineQuoteMark(options);
  25010. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  25011. var escaped = (0, _cssesc.default)(this._value, cssescopts);
  25012. return escaped;
  25013. };
  25014. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  25015. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  25016. }
  25017. /**
  25018. * Set the unescaped value with the specified quotation options. The value
  25019. * provided must not include any wrapping quote marks -- those quotes will
  25020. * be interpreted as part of the value and escaped accordingly.
  25021. */
  25022. ;
  25023. _proto.setValue = function setValue(value, options) {
  25024. if (options === void 0) {
  25025. options = {};
  25026. }
  25027. this._value = value;
  25028. this._quoteMark = this._determineQuoteMark(options);
  25029. this._syncRawValue();
  25030. }
  25031. /**
  25032. * Intelligently select a quoteMark value based on the value's contents. If
  25033. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  25034. * mark will be picked that minimizes the number of escapes.
  25035. *
  25036. * If there's no clear winner, the quote mark from these options is used,
  25037. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  25038. * true). If the quoteMark is unspecified, a double quote is used.
  25039. *
  25040. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  25041. * from the quoteValue method.
  25042. */
  25043. ;
  25044. _proto.smartQuoteMark = function smartQuoteMark(options) {
  25045. var v = this.value;
  25046. var numSingleQuotes = v.replace(/[^']/g, '').length;
  25047. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  25048. if (numSingleQuotes + numDoubleQuotes === 0) {
  25049. var escaped = (0, _cssesc.default)(v, {
  25050. isIdentifier: true
  25051. });
  25052. if (escaped === v) {
  25053. return Attribute.NO_QUOTE;
  25054. } else {
  25055. var pref = this.preferredQuoteMark(options);
  25056. if (pref === Attribute.NO_QUOTE) {
  25057. // pick a quote mark that isn't none and see if it's smaller
  25058. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  25059. var opts = CSSESC_QUOTE_OPTIONS[quote];
  25060. var quoteValue = (0, _cssesc.default)(v, opts);
  25061. if (quoteValue.length < escaped.length) {
  25062. return quote;
  25063. }
  25064. }
  25065. return pref;
  25066. }
  25067. } else if (numDoubleQuotes === numSingleQuotes) {
  25068. return this.preferredQuoteMark(options);
  25069. } else if (numDoubleQuotes < numSingleQuotes) {
  25070. return Attribute.DOUBLE_QUOTE;
  25071. } else {
  25072. return Attribute.SINGLE_QUOTE;
  25073. }
  25074. }
  25075. /**
  25076. * Selects the preferred quote mark based on the options and the current quote mark value.
  25077. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  25078. * instead.
  25079. */
  25080. ;
  25081. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  25082. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  25083. if (quoteMark === undefined) {
  25084. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  25085. }
  25086. if (quoteMark === undefined) {
  25087. quoteMark = Attribute.DOUBLE_QUOTE;
  25088. }
  25089. return quoteMark;
  25090. };
  25091. _proto._syncRawValue = function _syncRawValue() {
  25092. var rawValue = (0, _cssesc.default)(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  25093. if (rawValue === this._value) {
  25094. if (this.raws) {
  25095. delete this.raws.value;
  25096. }
  25097. } else {
  25098. this.raws.value = rawValue;
  25099. }
  25100. };
  25101. _proto._handleEscapes = function _handleEscapes(prop, value) {
  25102. if (this._constructed) {
  25103. var escaped = (0, _cssesc.default)(value, {
  25104. isIdentifier: true
  25105. });
  25106. if (escaped !== value) {
  25107. this.raws[prop] = escaped;
  25108. } else {
  25109. delete this.raws[prop];
  25110. }
  25111. }
  25112. };
  25113. _proto._spacesFor = function _spacesFor(name) {
  25114. var attrSpaces = {
  25115. before: '',
  25116. after: ''
  25117. };
  25118. var spaces = this.spaces[name] || {};
  25119. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  25120. return Object.assign(attrSpaces, spaces, rawSpaces);
  25121. };
  25122. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  25123. if (spaceName === void 0) {
  25124. spaceName = name;
  25125. }
  25126. if (concat === void 0) {
  25127. concat = defaultAttrConcat;
  25128. }
  25129. var attrSpaces = this._spacesFor(spaceName);
  25130. return concat(this.stringifyProperty(name), attrSpaces);
  25131. }
  25132. /**
  25133. * returns the offset of the attribute part specified relative to the
  25134. * start of the node of the output string.
  25135. *
  25136. * * "ns" - alias for "namespace"
  25137. * * "namespace" - the namespace if it exists.
  25138. * * "attribute" - the attribute name
  25139. * * "attributeNS" - the start of the attribute or its namespace
  25140. * * "operator" - the match operator of the attribute
  25141. * * "value" - The value (string or identifier)
  25142. * * "insensitive" - the case insensitivity flag;
  25143. * @param part One of the possible values inside an attribute.
  25144. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  25145. */
  25146. ;
  25147. _proto.offsetOf = function offsetOf(name) {
  25148. var count = 1;
  25149. var attributeSpaces = this._spacesFor("attribute");
  25150. count += attributeSpaces.before.length;
  25151. if (name === "namespace" || name === "ns") {
  25152. return this.namespace ? count : -1;
  25153. }
  25154. if (name === "attributeNS") {
  25155. return count;
  25156. }
  25157. count += this.namespaceString.length;
  25158. if (this.namespace) {
  25159. count += 1;
  25160. }
  25161. if (name === "attribute") {
  25162. return count;
  25163. }
  25164. count += this.stringifyProperty("attribute").length;
  25165. count += attributeSpaces.after.length;
  25166. var operatorSpaces = this._spacesFor("operator");
  25167. count += operatorSpaces.before.length;
  25168. var operator = this.stringifyProperty("operator");
  25169. if (name === "operator") {
  25170. return operator ? count : -1;
  25171. }
  25172. count += operator.length;
  25173. count += operatorSpaces.after.length;
  25174. var valueSpaces = this._spacesFor("value");
  25175. count += valueSpaces.before.length;
  25176. var value = this.stringifyProperty("value");
  25177. if (name === "value") {
  25178. return value ? count : -1;
  25179. }
  25180. count += value.length;
  25181. count += valueSpaces.after.length;
  25182. var insensitiveSpaces = this._spacesFor("insensitive");
  25183. count += insensitiveSpaces.before.length;
  25184. if (name === "insensitive") {
  25185. return this.insensitive ? count : -1;
  25186. }
  25187. return -1;
  25188. };
  25189. _proto.toString = function toString() {
  25190. var _this2 = this;
  25191. var selector = [this.rawSpaceBefore, '['];
  25192. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  25193. if (this.operator && (this.value || this.value === '')) {
  25194. selector.push(this._stringFor('operator'));
  25195. selector.push(this._stringFor('value'));
  25196. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  25197. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  25198. attrSpaces.before = " ";
  25199. }
  25200. return defaultAttrConcat(attrValue, attrSpaces);
  25201. }));
  25202. }
  25203. selector.push(']');
  25204. selector.push(this.rawSpaceAfter);
  25205. return selector.join('');
  25206. };
  25207. _createClass(Attribute, [{
  25208. key: "quoted",
  25209. get: function get() {
  25210. var qm = this.quoteMark;
  25211. return qm === "'" || qm === '"';
  25212. },
  25213. set: function set(value) {
  25214. warnOfDeprecatedQuotedAssignment();
  25215. }
  25216. /**
  25217. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  25218. * returns `null` if the value is not quoted.
  25219. * returns `undefined` if the quotation state is unknown (this can happen when
  25220. * the attribute is constructed without specifying a quote mark.)
  25221. */
  25222. }, {
  25223. key: "quoteMark",
  25224. get: function get() {
  25225. return this._quoteMark;
  25226. }
  25227. /**
  25228. * Set the quote mark to be used by this attribute's value.
  25229. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  25230. * value is updated accordingly.
  25231. *
  25232. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  25233. */
  25234. ,
  25235. set: function set(quoteMark) {
  25236. if (!this._constructed) {
  25237. this._quoteMark = quoteMark;
  25238. return;
  25239. }
  25240. if (this._quoteMark !== quoteMark) {
  25241. this._quoteMark = quoteMark;
  25242. this._syncRawValue();
  25243. }
  25244. }
  25245. }, {
  25246. key: "qualifiedAttribute",
  25247. get: function get() {
  25248. return this.qualifiedName(this.raws.attribute || this.attribute);
  25249. }
  25250. }, {
  25251. key: "insensitiveFlag",
  25252. get: function get() {
  25253. return this.insensitive ? 'i' : '';
  25254. }
  25255. }, {
  25256. key: "value",
  25257. get: function get() {
  25258. return this._value;
  25259. }
  25260. /**
  25261. * Before 3.0, the value had to be set to an escaped value including any wrapped
  25262. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  25263. * is unescaped during parsing and any quote marks are removed.
  25264. *
  25265. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  25266. * a deprecation warning is raised when the new value contains any characters that would
  25267. * require escaping (including if it contains wrapped quotes).
  25268. *
  25269. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  25270. * how the new value is quoted.
  25271. */
  25272. ,
  25273. set: function set(v) {
  25274. if (this._constructed) {
  25275. var _unescapeValue2 = unescapeValue(v),
  25276. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  25277. unescaped = _unescapeValue2.unescaped,
  25278. quoteMark = _unescapeValue2.quoteMark;
  25279. if (deprecatedUsage) {
  25280. warnOfDeprecatedValueAssignment();
  25281. }
  25282. if (unescaped === this._value && quoteMark === this._quoteMark) {
  25283. return;
  25284. }
  25285. this._value = unescaped;
  25286. this._quoteMark = quoteMark;
  25287. this._syncRawValue();
  25288. } else {
  25289. this._value = v;
  25290. }
  25291. }
  25292. }, {
  25293. key: "attribute",
  25294. get: function get() {
  25295. return this._attribute;
  25296. },
  25297. set: function set(name) {
  25298. this._handleEscapes("attribute", name);
  25299. this._attribute = name;
  25300. }
  25301. }]);
  25302. return Attribute;
  25303. }(_namespace.default);
  25304. exports.default = Attribute;
  25305. Attribute.NO_QUOTE = null;
  25306. Attribute.SINGLE_QUOTE = "'";
  25307. Attribute.DOUBLE_QUOTE = '"';
  25308. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  25309. "'": {
  25310. quotes: 'single',
  25311. wrap: true
  25312. },
  25313. '"': {
  25314. quotes: 'double',
  25315. wrap: true
  25316. }
  25317. }, _CSSESC_QUOTE_OPTIONS[null] = {
  25318. isIdentifier: true
  25319. }, _CSSESC_QUOTE_OPTIONS);
  25320. function defaultAttrConcat(attrValue, attrSpaces) {
  25321. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  25322. }
  25323. });
  25324. var universal = createCommonjsModule(function (module, exports) {
  25325. exports.__esModule = true;
  25326. exports.default = void 0;
  25327. var _namespace = _interopRequireDefault(namespace);
  25328. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25329. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  25330. var Universal =
  25331. /*#__PURE__*/
  25332. function (_Namespace) {
  25333. _inheritsLoose(Universal, _Namespace);
  25334. function Universal(opts) {
  25335. var _this;
  25336. _this = _Namespace.call(this, opts) || this;
  25337. _this.type = types$2.UNIVERSAL;
  25338. _this.value = '*';
  25339. return _this;
  25340. }
  25341. return Universal;
  25342. }(_namespace.default);
  25343. exports.default = Universal;
  25344. module.exports = exports.default;
  25345. });
  25346. var combinator = createCommonjsModule(function (module, exports) {
  25347. exports.__esModule = true;
  25348. exports.default = void 0;
  25349. var _node = _interopRequireDefault(node);
  25350. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25351. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  25352. var Combinator =
  25353. /*#__PURE__*/
  25354. function (_Node) {
  25355. _inheritsLoose(Combinator, _Node);
  25356. function Combinator(opts) {
  25357. var _this;
  25358. _this = _Node.call(this, opts) || this;
  25359. _this.type = types$2.COMBINATOR;
  25360. return _this;
  25361. }
  25362. return Combinator;
  25363. }(_node.default);
  25364. exports.default = Combinator;
  25365. module.exports = exports.default;
  25366. });
  25367. var nesting = createCommonjsModule(function (module, exports) {
  25368. exports.__esModule = true;
  25369. exports.default = void 0;
  25370. var _node = _interopRequireDefault(node);
  25371. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25372. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  25373. var Nesting =
  25374. /*#__PURE__*/
  25375. function (_Node) {
  25376. _inheritsLoose(Nesting, _Node);
  25377. function Nesting(opts) {
  25378. var _this;
  25379. _this = _Node.call(this, opts) || this;
  25380. _this.type = types$2.NESTING;
  25381. _this.value = '&';
  25382. return _this;
  25383. }
  25384. return Nesting;
  25385. }(_node.default);
  25386. exports.default = Nesting;
  25387. module.exports = exports.default;
  25388. });
  25389. var sortAscending_1 = createCommonjsModule(function (module, exports) {
  25390. exports.__esModule = true;
  25391. exports.default = sortAscending;
  25392. function sortAscending(list) {
  25393. return list.sort(function (a, b) {
  25394. return a - b;
  25395. });
  25396. }
  25397. module.exports = exports.default;
  25398. });
  25399. var tokenTypes = createCommonjsModule(function (module, exports) {
  25400. exports.__esModule = true;
  25401. exports.combinator = exports.word = exports.comment = exports.str = exports.tab = exports.newline = exports.feed = exports.cr = exports.backslash = exports.bang = exports.slash = exports.doubleQuote = exports.singleQuote = exports.space = exports.greaterThan = exports.pipe = exports.equals = exports.plus = exports.caret = exports.tilde = exports.dollar = exports.closeSquare = exports.openSquare = exports.closeParenthesis = exports.openParenthesis = exports.semicolon = exports.colon = exports.comma = exports.at = exports.asterisk = exports.ampersand = void 0;
  25402. var ampersand = 38; // `&`.charCodeAt(0);
  25403. exports.ampersand = ampersand;
  25404. var asterisk = 42; // `*`.charCodeAt(0);
  25405. exports.asterisk = asterisk;
  25406. var at = 64; // `@`.charCodeAt(0);
  25407. exports.at = at;
  25408. var comma = 44; // `,`.charCodeAt(0);
  25409. exports.comma = comma;
  25410. var colon = 58; // `:`.charCodeAt(0);
  25411. exports.colon = colon;
  25412. var semicolon = 59; // `;`.charCodeAt(0);
  25413. exports.semicolon = semicolon;
  25414. var openParenthesis = 40; // `(`.charCodeAt(0);
  25415. exports.openParenthesis = openParenthesis;
  25416. var closeParenthesis = 41; // `)`.charCodeAt(0);
  25417. exports.closeParenthesis = closeParenthesis;
  25418. var openSquare = 91; // `[`.charCodeAt(0);
  25419. exports.openSquare = openSquare;
  25420. var closeSquare = 93; // `]`.charCodeAt(0);
  25421. exports.closeSquare = closeSquare;
  25422. var dollar = 36; // `$`.charCodeAt(0);
  25423. exports.dollar = dollar;
  25424. var tilde = 126; // `~`.charCodeAt(0);
  25425. exports.tilde = tilde;
  25426. var caret = 94; // `^`.charCodeAt(0);
  25427. exports.caret = caret;
  25428. var plus = 43; // `+`.charCodeAt(0);
  25429. exports.plus = plus;
  25430. var equals = 61; // `=`.charCodeAt(0);
  25431. exports.equals = equals;
  25432. var pipe = 124; // `|`.charCodeAt(0);
  25433. exports.pipe = pipe;
  25434. var greaterThan = 62; // `>`.charCodeAt(0);
  25435. exports.greaterThan = greaterThan;
  25436. var space = 32; // ` `.charCodeAt(0);
  25437. exports.space = space;
  25438. var singleQuote = 39; // `'`.charCodeAt(0);
  25439. exports.singleQuote = singleQuote;
  25440. var doubleQuote = 34; // `"`.charCodeAt(0);
  25441. exports.doubleQuote = doubleQuote;
  25442. var slash = 47; // `/`.charCodeAt(0);
  25443. exports.slash = slash;
  25444. var bang = 33; // `!`.charCodeAt(0);
  25445. exports.bang = bang;
  25446. var backslash = 92; // '\\'.charCodeAt(0);
  25447. exports.backslash = backslash;
  25448. var cr = 13; // '\r'.charCodeAt(0);
  25449. exports.cr = cr;
  25450. var feed = 12; // '\f'.charCodeAt(0);
  25451. exports.feed = feed;
  25452. var newline = 10; // '\n'.charCodeAt(0);
  25453. exports.newline = newline;
  25454. var tab = 9; // '\t'.charCodeAt(0);
  25455. // Expose aliases primarily for readability.
  25456. exports.tab = tab;
  25457. var str = singleQuote; // No good single character representation!
  25458. exports.str = str;
  25459. var comment = -1;
  25460. exports.comment = comment;
  25461. var word = -2;
  25462. exports.word = word;
  25463. var combinator = -3;
  25464. exports.combinator = combinator;
  25465. });
  25466. var tokenize_1 = createCommonjsModule(function (module, exports) {
  25467. exports.__esModule = true;
  25468. exports.default = tokenize;
  25469. exports.FIELDS = void 0;
  25470. var t = _interopRequireWildcard(tokenTypes);
  25471. var _unescapable, _wordDelimiters;
  25472. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
  25473. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  25474. 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);
  25475. var hex = {};
  25476. var hexChars = "0123456789abcdefABCDEF";
  25477. for (var i = 0; i < hexChars.length; i++) {
  25478. hex[hexChars.charCodeAt(i)] = true;
  25479. }
  25480. /**
  25481. * Returns the last index of the bar css word
  25482. * @param {string} css The string in which the word begins
  25483. * @param {number} start The index into the string where word's first letter occurs
  25484. */
  25485. function consumeWord(css, start) {
  25486. var next = start;
  25487. var code;
  25488. do {
  25489. code = css.charCodeAt(next);
  25490. if (wordDelimiters[code]) {
  25491. return next - 1;
  25492. } else if (code === t.backslash) {
  25493. next = consumeEscape(css, next) + 1;
  25494. } else {
  25495. // All other characters are part of the word
  25496. next++;
  25497. }
  25498. } while (next < css.length);
  25499. return next - 1;
  25500. }
  25501. /**
  25502. * Returns the last index of the escape sequence
  25503. * @param {string} css The string in which the sequence begins
  25504. * @param {number} start The index into the string where escape character (`\`) occurs.
  25505. */
  25506. function consumeEscape(css, start) {
  25507. var next = start;
  25508. var code = css.charCodeAt(next + 1);
  25509. if (unescapable[code]) ; else if (hex[code]) {
  25510. var hexDigits = 0; // consume up to 6 hex chars
  25511. do {
  25512. next++;
  25513. hexDigits++;
  25514. code = css.charCodeAt(next + 1);
  25515. } while (hex[code] && hexDigits < 6); // if fewer than 6 hex chars, a trailing space ends the escape
  25516. if (hexDigits < 6 && code === t.space) {
  25517. next++;
  25518. }
  25519. } else {
  25520. // the next char is part of the current word
  25521. next++;
  25522. }
  25523. return next;
  25524. }
  25525. var FIELDS = {
  25526. TYPE: 0,
  25527. START_LINE: 1,
  25528. START_COL: 2,
  25529. END_LINE: 3,
  25530. END_COL: 4,
  25531. START_POS: 5,
  25532. END_POS: 6
  25533. };
  25534. exports.FIELDS = FIELDS;
  25535. function tokenize(input) {
  25536. var tokens = [];
  25537. var css = input.css.valueOf();
  25538. var _css = css,
  25539. length = _css.length;
  25540. var offset = -1;
  25541. var line = 1;
  25542. var start = 0;
  25543. var end = 0;
  25544. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  25545. function unclosed(what, fix) {
  25546. if (input.safe) {
  25547. // fyi: this is never set to true.
  25548. css += fix;
  25549. next = css.length - 1;
  25550. } else {
  25551. throw input.error('Unclosed ' + what, line, start - offset, start);
  25552. }
  25553. }
  25554. while (start < length) {
  25555. code = css.charCodeAt(start);
  25556. if (code === t.newline) {
  25557. offset = start;
  25558. line += 1;
  25559. }
  25560. switch (code) {
  25561. case t.space:
  25562. case t.tab:
  25563. case t.newline:
  25564. case t.cr:
  25565. case t.feed:
  25566. next = start;
  25567. do {
  25568. next += 1;
  25569. code = css.charCodeAt(next);
  25570. if (code === t.newline) {
  25571. offset = next;
  25572. line += 1;
  25573. }
  25574. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  25575. tokenType = t.space;
  25576. endLine = line;
  25577. endColumn = next - offset - 1;
  25578. end = next;
  25579. break;
  25580. case t.plus:
  25581. case t.greaterThan:
  25582. case t.tilde:
  25583. case t.pipe:
  25584. next = start;
  25585. do {
  25586. next += 1;
  25587. code = css.charCodeAt(next);
  25588. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  25589. tokenType = t.combinator;
  25590. endLine = line;
  25591. endColumn = start - offset;
  25592. end = next;
  25593. break;
  25594. // Consume these characters as single tokens.
  25595. case t.asterisk:
  25596. case t.ampersand:
  25597. case t.bang:
  25598. case t.comma:
  25599. case t.equals:
  25600. case t.dollar:
  25601. case t.caret:
  25602. case t.openSquare:
  25603. case t.closeSquare:
  25604. case t.colon:
  25605. case t.semicolon:
  25606. case t.openParenthesis:
  25607. case t.closeParenthesis:
  25608. next = start;
  25609. tokenType = code;
  25610. endLine = line;
  25611. endColumn = start - offset;
  25612. end = next + 1;
  25613. break;
  25614. case t.singleQuote:
  25615. case t.doubleQuote:
  25616. quote = code === t.singleQuote ? "'" : '"';
  25617. next = start;
  25618. do {
  25619. escaped = false;
  25620. next = css.indexOf(quote, next + 1);
  25621. if (next === -1) {
  25622. unclosed('quote', quote);
  25623. }
  25624. escapePos = next;
  25625. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  25626. escapePos -= 1;
  25627. escaped = !escaped;
  25628. }
  25629. } while (escaped);
  25630. tokenType = t.str;
  25631. endLine = line;
  25632. endColumn = start - offset;
  25633. end = next + 1;
  25634. break;
  25635. default:
  25636. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  25637. next = css.indexOf('*/', start + 2) + 1;
  25638. if (next === 0) {
  25639. unclosed('comment', '*/');
  25640. }
  25641. content = css.slice(start, next + 1);
  25642. lines = content.split('\n');
  25643. last = lines.length - 1;
  25644. if (last > 0) {
  25645. nextLine = line + last;
  25646. nextOffset = next - lines[last].length;
  25647. } else {
  25648. nextLine = line;
  25649. nextOffset = offset;
  25650. }
  25651. tokenType = t.comment;
  25652. line = nextLine;
  25653. endLine = nextLine;
  25654. endColumn = next - nextOffset;
  25655. } else if (code === t.slash) {
  25656. next = start;
  25657. tokenType = code;
  25658. endLine = line;
  25659. endColumn = start - offset;
  25660. end = next + 1;
  25661. } else {
  25662. next = consumeWord(css, start);
  25663. tokenType = t.word;
  25664. endLine = line;
  25665. endColumn = next - offset;
  25666. }
  25667. end = next + 1;
  25668. break;
  25669. } // Ensure that the token structure remains consistent
  25670. tokens.push([tokenType, // [0] Token type
  25671. line, // [1] Starting line
  25672. start - offset, // [2] Starting column
  25673. endLine, // [3] Ending line
  25674. endColumn, // [4] Ending column
  25675. start, // [5] Start position / Source index
  25676. end]); // Reset offset for the next token
  25677. if (nextOffset) {
  25678. offset = nextOffset;
  25679. nextOffset = null;
  25680. }
  25681. start = end;
  25682. }
  25683. return tokens;
  25684. }
  25685. });
  25686. var parser = createCommonjsModule(function (module, exports) {
  25687. exports.__esModule = true;
  25688. exports.default = void 0;
  25689. var _indexesOf = _interopRequireDefault(indexesOf);
  25690. var _uniq = _interopRequireDefault(uniq);
  25691. var _root = _interopRequireDefault(root);
  25692. var _selector = _interopRequireDefault(selector);
  25693. var _className = _interopRequireDefault(className);
  25694. var _comment = _interopRequireDefault(comment);
  25695. var _id = _interopRequireDefault(id);
  25696. var _tag = _interopRequireDefault(tag);
  25697. var _string = _interopRequireDefault(string);
  25698. var _pseudo = _interopRequireDefault(pseudo);
  25699. var _attribute = _interopRequireWildcard(attribute);
  25700. var _universal = _interopRequireDefault(universal);
  25701. var _combinator = _interopRequireDefault(combinator);
  25702. var _nesting = _interopRequireDefault(nesting);
  25703. var _sortAscending = _interopRequireDefault(sortAscending_1);
  25704. var _tokenize = _interopRequireWildcard(tokenize_1);
  25705. var tokens = _interopRequireWildcard(tokenTypes);
  25706. var types = _interopRequireWildcard(types$2);
  25707. var _WHITESPACE_TOKENS, _Object$assign;
  25708. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
  25709. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25710. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  25711. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  25712. 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);
  25713. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  25714. function tokenStart(token) {
  25715. return {
  25716. line: token[_tokenize.FIELDS.START_LINE],
  25717. column: token[_tokenize.FIELDS.START_COL]
  25718. };
  25719. }
  25720. function tokenEnd(token) {
  25721. return {
  25722. line: token[_tokenize.FIELDS.END_LINE],
  25723. column: token[_tokenize.FIELDS.END_COL]
  25724. };
  25725. }
  25726. function getSource(startLine, startColumn, endLine, endColumn) {
  25727. return {
  25728. start: {
  25729. line: startLine,
  25730. column: startColumn
  25731. },
  25732. end: {
  25733. line: endLine,
  25734. column: endColumn
  25735. }
  25736. };
  25737. }
  25738. function getTokenSource(token) {
  25739. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  25740. }
  25741. function getTokenSourceSpan(startToken, endToken) {
  25742. if (!startToken) {
  25743. return undefined;
  25744. }
  25745. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  25746. }
  25747. function unescapeProp(node, prop) {
  25748. var value = node[prop];
  25749. if (typeof value !== "string") {
  25750. return;
  25751. }
  25752. if (value.indexOf("\\") !== -1) {
  25753. (0, util$1.ensureObject)(node, 'raws');
  25754. node[prop] = (0, util$1.unesc)(value);
  25755. if (node.raws[prop] === undefined) {
  25756. node.raws[prop] = value;
  25757. }
  25758. }
  25759. return node;
  25760. }
  25761. var Parser =
  25762. /*#__PURE__*/
  25763. function () {
  25764. function Parser(rule, options) {
  25765. if (options === void 0) {
  25766. options = {};
  25767. }
  25768. this.rule = rule;
  25769. this.options = Object.assign({
  25770. lossy: false,
  25771. safe: false
  25772. }, options);
  25773. this.position = 0;
  25774. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  25775. this.tokens = (0, _tokenize.default)({
  25776. css: this.css,
  25777. error: this._errorGenerator(),
  25778. safe: this.options.safe
  25779. });
  25780. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  25781. this.root = new _root.default({
  25782. source: rootSource
  25783. });
  25784. this.root.errorGenerator = this._errorGenerator();
  25785. var selector = new _selector.default({
  25786. source: {
  25787. start: {
  25788. line: 1,
  25789. column: 1
  25790. }
  25791. }
  25792. });
  25793. this.root.append(selector);
  25794. this.current = selector;
  25795. this.loop();
  25796. }
  25797. var _proto = Parser.prototype;
  25798. _proto._errorGenerator = function _errorGenerator() {
  25799. var _this = this;
  25800. return function (message, errorOptions) {
  25801. if (typeof _this.rule === 'string') {
  25802. return new Error(message);
  25803. }
  25804. return _this.rule.error(message, errorOptions);
  25805. };
  25806. };
  25807. _proto.attribute = function attribute() {
  25808. var attr = [];
  25809. var startingToken = this.currToken;
  25810. this.position++;
  25811. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  25812. attr.push(this.currToken);
  25813. this.position++;
  25814. }
  25815. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  25816. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  25817. }
  25818. var len = attr.length;
  25819. var node = {
  25820. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  25821. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  25822. };
  25823. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  25824. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  25825. }
  25826. var pos = 0;
  25827. var spaceBefore = '';
  25828. var commentBefore = '';
  25829. var lastAdded = null;
  25830. var spaceAfterMeaningfulToken = false;
  25831. while (pos < len) {
  25832. var token = attr[pos];
  25833. var content = this.content(token);
  25834. var next = attr[pos + 1];
  25835. switch (token[_tokenize.FIELDS.TYPE]) {
  25836. case tokens.space:
  25837. // if (
  25838. // len === 1 ||
  25839. // pos === 0 && this.content(next) === '|'
  25840. // ) {
  25841. // return this.expected('attribute', token[TOKEN.START_POS], content);
  25842. // }
  25843. spaceAfterMeaningfulToken = true;
  25844. if (this.options.lossy) {
  25845. break;
  25846. }
  25847. if (lastAdded) {
  25848. (0, util$1.ensureObject)(node, 'spaces', lastAdded);
  25849. var prevContent = node.spaces[lastAdded].after || '';
  25850. node.spaces[lastAdded].after = prevContent + content;
  25851. var existingComment = (0, util$1.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  25852. if (existingComment) {
  25853. node.raws.spaces[lastAdded].after = existingComment + content;
  25854. }
  25855. } else {
  25856. spaceBefore = spaceBefore + content;
  25857. commentBefore = commentBefore + content;
  25858. }
  25859. break;
  25860. case tokens.asterisk:
  25861. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  25862. node.operator = content;
  25863. lastAdded = 'operator';
  25864. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  25865. if (spaceBefore) {
  25866. (0, util$1.ensureObject)(node, 'spaces', 'attribute');
  25867. node.spaces.attribute.before = spaceBefore;
  25868. spaceBefore = '';
  25869. }
  25870. if (commentBefore) {
  25871. (0, util$1.ensureObject)(node, 'raws', 'spaces', 'attribute');
  25872. node.raws.spaces.attribute.before = spaceBefore;
  25873. commentBefore = '';
  25874. }
  25875. node.namespace = (node.namespace || "") + content;
  25876. var rawValue = (0, util$1.getProp)(node, 'raws', 'namespace') || null;
  25877. if (rawValue) {
  25878. node.raws.namespace += content;
  25879. }
  25880. lastAdded = 'namespace';
  25881. }
  25882. spaceAfterMeaningfulToken = false;
  25883. break;
  25884. case tokens.dollar:
  25885. if (lastAdded === "value") {
  25886. var oldRawValue = (0, util$1.getProp)(node, 'raws', 'value');
  25887. node.value += "$";
  25888. if (oldRawValue) {
  25889. node.raws.value = oldRawValue + "$";
  25890. }
  25891. break;
  25892. }
  25893. // Falls through
  25894. case tokens.caret:
  25895. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  25896. node.operator = content;
  25897. lastAdded = 'operator';
  25898. }
  25899. spaceAfterMeaningfulToken = false;
  25900. break;
  25901. case tokens.combinator:
  25902. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  25903. node.operator = content;
  25904. lastAdded = 'operator';
  25905. }
  25906. if (content !== '|') {
  25907. spaceAfterMeaningfulToken = false;
  25908. break;
  25909. }
  25910. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  25911. node.operator = content;
  25912. lastAdded = 'operator';
  25913. } else if (!node.namespace && !node.attribute) {
  25914. node.namespace = true;
  25915. }
  25916. spaceAfterMeaningfulToken = false;
  25917. break;
  25918. case tokens.word:
  25919. if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && // this look-ahead probably fails with comment nodes involved.
  25920. !node.operator && !node.namespace) {
  25921. node.namespace = content;
  25922. lastAdded = 'namespace';
  25923. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  25924. if (spaceBefore) {
  25925. (0, util$1.ensureObject)(node, 'spaces', 'attribute');
  25926. node.spaces.attribute.before = spaceBefore;
  25927. spaceBefore = '';
  25928. }
  25929. if (commentBefore) {
  25930. (0, util$1.ensureObject)(node, 'raws', 'spaces', 'attribute');
  25931. node.raws.spaces.attribute.before = commentBefore;
  25932. commentBefore = '';
  25933. }
  25934. node.attribute = (node.attribute || "") + content;
  25935. var _rawValue = (0, util$1.getProp)(node, 'raws', 'attribute') || null;
  25936. if (_rawValue) {
  25937. node.raws.attribute += content;
  25938. }
  25939. lastAdded = 'attribute';
  25940. } else if (!node.value && node.value !== "" || lastAdded === "value" && !spaceAfterMeaningfulToken) {
  25941. var _unescaped = (0, util$1.unesc)(content);
  25942. var _oldRawValue = (0, util$1.getProp)(node, 'raws', 'value') || '';
  25943. var oldValue = node.value || '';
  25944. node.value = oldValue + _unescaped;
  25945. node.quoteMark = null;
  25946. if (_unescaped !== content || _oldRawValue) {
  25947. (0, util$1.ensureObject)(node, 'raws');
  25948. node.raws.value = (_oldRawValue || oldValue) + content;
  25949. }
  25950. lastAdded = 'value';
  25951. } else {
  25952. var insensitive = content === 'i' || content === "I";
  25953. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  25954. node.insensitive = insensitive;
  25955. if (!insensitive || content === "I") {
  25956. (0, util$1.ensureObject)(node, 'raws');
  25957. node.raws.insensitiveFlag = content;
  25958. }
  25959. lastAdded = 'insensitive';
  25960. if (spaceBefore) {
  25961. (0, util$1.ensureObject)(node, 'spaces', 'insensitive');
  25962. node.spaces.insensitive.before = spaceBefore;
  25963. spaceBefore = '';
  25964. }
  25965. if (commentBefore) {
  25966. (0, util$1.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  25967. node.raws.spaces.insensitive.before = commentBefore;
  25968. commentBefore = '';
  25969. }
  25970. } else if (node.value || node.value === '') {
  25971. lastAdded = 'value';
  25972. node.value += content;
  25973. if (node.raws.value) {
  25974. node.raws.value += content;
  25975. }
  25976. }
  25977. }
  25978. spaceAfterMeaningfulToken = false;
  25979. break;
  25980. case tokens.str:
  25981. if (!node.attribute || !node.operator) {
  25982. return this.error("Expected an attribute followed by an operator preceding the string.", {
  25983. index: token[_tokenize.FIELDS.START_POS]
  25984. });
  25985. }
  25986. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  25987. unescaped = _unescapeValue.unescaped,
  25988. quoteMark = _unescapeValue.quoteMark;
  25989. node.value = unescaped;
  25990. node.quoteMark = quoteMark;
  25991. lastAdded = 'value';
  25992. (0, util$1.ensureObject)(node, 'raws');
  25993. node.raws.value = content;
  25994. spaceAfterMeaningfulToken = false;
  25995. break;
  25996. case tokens.equals:
  25997. if (!node.attribute) {
  25998. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  25999. }
  26000. if (node.value) {
  26001. return this.error('Unexpected "=" found; an operator was already defined.', {
  26002. index: token[_tokenize.FIELDS.START_POS]
  26003. });
  26004. }
  26005. node.operator = node.operator ? node.operator + content : content;
  26006. lastAdded = 'operator';
  26007. spaceAfterMeaningfulToken = false;
  26008. break;
  26009. case tokens.comment:
  26010. if (lastAdded) {
  26011. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  26012. var lastComment = (0, util$1.getProp)(node, 'spaces', lastAdded, 'after') || '';
  26013. var rawLastComment = (0, util$1.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  26014. (0, util$1.ensureObject)(node, 'raws', 'spaces', lastAdded);
  26015. node.raws.spaces[lastAdded].after = rawLastComment + content;
  26016. } else {
  26017. var lastValue = node[lastAdded] || '';
  26018. var rawLastValue = (0, util$1.getProp)(node, 'raws', lastAdded) || lastValue;
  26019. (0, util$1.ensureObject)(node, 'raws');
  26020. node.raws[lastAdded] = rawLastValue + content;
  26021. }
  26022. } else {
  26023. commentBefore = commentBefore + content;
  26024. }
  26025. break;
  26026. default:
  26027. return this.error("Unexpected \"" + content + "\" found.", {
  26028. index: token[_tokenize.FIELDS.START_POS]
  26029. });
  26030. }
  26031. pos++;
  26032. }
  26033. unescapeProp(node, "attribute");
  26034. unescapeProp(node, "namespace");
  26035. this.newNode(new _attribute.default(node));
  26036. this.position++;
  26037. }
  26038. /**
  26039. * return a node containing meaningless garbage up to (but not including) the specified token position.
  26040. * if the token position is negative, all remaining tokens are consumed.
  26041. *
  26042. * This returns an array containing a single string node if all whitespace,
  26043. * otherwise an array of comment nodes with space before and after.
  26044. *
  26045. * These tokens are not added to the current selector, the caller can add them or use them to amend
  26046. * a previous node's space metadata.
  26047. *
  26048. * In lossy mode, this returns only comments.
  26049. */
  26050. ;
  26051. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  26052. if (stopPosition < 0) {
  26053. stopPosition = this.tokens.length;
  26054. }
  26055. var startPosition = this.position;
  26056. var nodes = [];
  26057. var space = "";
  26058. var lastComment = undefined;
  26059. do {
  26060. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  26061. if (!this.options.lossy) {
  26062. space += this.content();
  26063. }
  26064. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  26065. var spaces = {};
  26066. if (space) {
  26067. spaces.before = space;
  26068. space = "";
  26069. }
  26070. lastComment = new _comment.default({
  26071. value: this.content(),
  26072. source: getTokenSource(this.currToken),
  26073. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  26074. spaces: spaces
  26075. });
  26076. nodes.push(lastComment);
  26077. }
  26078. } while (++this.position < stopPosition);
  26079. if (space) {
  26080. if (lastComment) {
  26081. lastComment.spaces.after = space;
  26082. } else if (!this.options.lossy) {
  26083. var firstToken = this.tokens[startPosition];
  26084. var lastToken = this.tokens[this.position - 1];
  26085. nodes.push(new _string.default({
  26086. value: '',
  26087. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  26088. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  26089. spaces: {
  26090. before: space,
  26091. after: ''
  26092. }
  26093. }));
  26094. }
  26095. }
  26096. return nodes;
  26097. }
  26098. /**
  26099. *
  26100. * @param {*} nodes
  26101. */
  26102. ;
  26103. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  26104. var _this2 = this;
  26105. if (requiredSpace === void 0) {
  26106. requiredSpace = false;
  26107. }
  26108. var space = "";
  26109. var rawSpace = "";
  26110. nodes.forEach(function (n) {
  26111. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  26112. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  26113. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  26114. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  26115. });
  26116. if (rawSpace === space) {
  26117. rawSpace = undefined;
  26118. }
  26119. var result = {
  26120. space: space,
  26121. rawSpace: rawSpace
  26122. };
  26123. return result;
  26124. };
  26125. _proto.isNamedCombinator = function isNamedCombinator(position) {
  26126. if (position === void 0) {
  26127. position = this.position;
  26128. }
  26129. 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;
  26130. };
  26131. _proto.namedCombinator = function namedCombinator() {
  26132. if (this.isNamedCombinator()) {
  26133. var nameRaw = this.content(this.tokens[this.position + 1]);
  26134. var name = (0, util$1.unesc)(nameRaw).toLowerCase();
  26135. var raws = {};
  26136. if (name !== nameRaw) {
  26137. raws.value = "/" + nameRaw + "/";
  26138. }
  26139. var node = new _combinator.default({
  26140. value: "/" + name + "/",
  26141. 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]),
  26142. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  26143. raws: raws
  26144. });
  26145. this.position = this.position + 3;
  26146. return node;
  26147. } else {
  26148. this.unexpected();
  26149. }
  26150. };
  26151. _proto.combinator = function combinator() {
  26152. var _this3 = this;
  26153. if (this.content() === '|') {
  26154. return this.namespace();
  26155. } // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  26156. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  26157. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  26158. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  26159. if (nodes.length > 0) {
  26160. var last = this.current.last;
  26161. if (last) {
  26162. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  26163. space = _this$convertWhitespa.space,
  26164. rawSpace = _this$convertWhitespa.rawSpace;
  26165. if (rawSpace !== undefined) {
  26166. last.rawSpaceAfter += rawSpace;
  26167. }
  26168. last.spaces.after += space;
  26169. } else {
  26170. nodes.forEach(function (n) {
  26171. return _this3.newNode(n);
  26172. });
  26173. }
  26174. }
  26175. return;
  26176. }
  26177. var firstToken = this.currToken;
  26178. var spaceOrDescendantSelectorNodes = undefined;
  26179. if (nextSigTokenPos > this.position) {
  26180. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  26181. }
  26182. var node;
  26183. if (this.isNamedCombinator()) {
  26184. node = this.namedCombinator();
  26185. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  26186. node = new _combinator.default({
  26187. value: this.content(),
  26188. source: getTokenSource(this.currToken),
  26189. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  26190. });
  26191. this.position++;
  26192. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  26193. this.unexpected();
  26194. }
  26195. if (node) {
  26196. if (spaceOrDescendantSelectorNodes) {
  26197. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  26198. _space = _this$convertWhitespa2.space,
  26199. _rawSpace = _this$convertWhitespa2.rawSpace;
  26200. node.spaces.before = _space;
  26201. node.rawSpaceBefore = _rawSpace;
  26202. }
  26203. } else {
  26204. // descendant combinator
  26205. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  26206. _space2 = _this$convertWhitespa3.space,
  26207. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  26208. if (!_rawSpace2) {
  26209. _rawSpace2 = _space2;
  26210. }
  26211. var spaces = {};
  26212. var raws = {
  26213. spaces: {}
  26214. };
  26215. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  26216. spaces.before = _space2.slice(0, _space2.length - 1);
  26217. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  26218. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  26219. spaces.after = _space2.slice(1);
  26220. raws.spaces.after = _rawSpace2.slice(1);
  26221. } else {
  26222. raws.value = _rawSpace2;
  26223. }
  26224. node = new _combinator.default({
  26225. value: ' ',
  26226. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  26227. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  26228. spaces: spaces,
  26229. raws: raws
  26230. });
  26231. }
  26232. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  26233. node.spaces.after = this.optionalSpace(this.content());
  26234. this.position++;
  26235. }
  26236. return this.newNode(node);
  26237. };
  26238. _proto.comma = function comma() {
  26239. if (this.position === this.tokens.length - 1) {
  26240. this.root.trailingComma = true;
  26241. this.position++;
  26242. return;
  26243. }
  26244. this.current._inferEndPosition();
  26245. var selector = new _selector.default({
  26246. source: {
  26247. start: tokenStart(this.tokens[this.position + 1])
  26248. }
  26249. });
  26250. this.current.parent.append(selector);
  26251. this.current = selector;
  26252. this.position++;
  26253. };
  26254. _proto.comment = function comment() {
  26255. var current = this.currToken;
  26256. this.newNode(new _comment.default({
  26257. value: this.content(),
  26258. source: getTokenSource(current),
  26259. sourceIndex: current[_tokenize.FIELDS.START_POS]
  26260. }));
  26261. this.position++;
  26262. };
  26263. _proto.error = function error(message, opts) {
  26264. throw this.root.error(message, opts);
  26265. };
  26266. _proto.missingBackslash = function missingBackslash() {
  26267. return this.error('Expected a backslash preceding the semicolon.', {
  26268. index: this.currToken[_tokenize.FIELDS.START_POS]
  26269. });
  26270. };
  26271. _proto.missingParenthesis = function missingParenthesis() {
  26272. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  26273. };
  26274. _proto.missingSquareBracket = function missingSquareBracket() {
  26275. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  26276. };
  26277. _proto.unexpected = function unexpected() {
  26278. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  26279. };
  26280. _proto.namespace = function namespace() {
  26281. var before = this.prevToken && this.content(this.prevToken) || true;
  26282. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  26283. this.position++;
  26284. return this.word(before);
  26285. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  26286. this.position++;
  26287. return this.universal(before);
  26288. }
  26289. };
  26290. _proto.nesting = function nesting() {
  26291. if (this.nextToken) {
  26292. var nextContent = this.content(this.nextToken);
  26293. if (nextContent === "|") {
  26294. this.position++;
  26295. return;
  26296. }
  26297. }
  26298. var current = this.currToken;
  26299. this.newNode(new _nesting.default({
  26300. value: this.content(),
  26301. source: getTokenSource(current),
  26302. sourceIndex: current[_tokenize.FIELDS.START_POS]
  26303. }));
  26304. this.position++;
  26305. };
  26306. _proto.parentheses = function parentheses() {
  26307. var last = this.current.last;
  26308. var unbalanced = 1;
  26309. this.position++;
  26310. if (last && last.type === types.PSEUDO) {
  26311. var selector = new _selector.default({
  26312. source: {
  26313. start: tokenStart(this.tokens[this.position - 1])
  26314. }
  26315. });
  26316. var cache = this.current;
  26317. last.append(selector);
  26318. this.current = selector;
  26319. while (this.position < this.tokens.length && unbalanced) {
  26320. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  26321. unbalanced++;
  26322. }
  26323. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  26324. unbalanced--;
  26325. }
  26326. if (unbalanced) {
  26327. this.parse();
  26328. } else {
  26329. this.current.source.end = tokenEnd(this.currToken);
  26330. this.current.parent.source.end = tokenEnd(this.currToken);
  26331. this.position++;
  26332. }
  26333. }
  26334. this.current = cache;
  26335. } else {
  26336. // I think this case should be an error. It's used to implement a basic parse of media queries
  26337. // but I don't think it's a good idea.
  26338. var parenStart = this.currToken;
  26339. var parenValue = "(";
  26340. var parenEnd;
  26341. while (this.position < this.tokens.length && unbalanced) {
  26342. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  26343. unbalanced++;
  26344. }
  26345. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  26346. unbalanced--;
  26347. }
  26348. parenEnd = this.currToken;
  26349. parenValue += this.parseParenthesisToken(this.currToken);
  26350. this.position++;
  26351. }
  26352. if (last) {
  26353. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  26354. } else {
  26355. this.newNode(new _string.default({
  26356. value: parenValue,
  26357. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  26358. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  26359. }));
  26360. }
  26361. }
  26362. if (unbalanced) {
  26363. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  26364. }
  26365. };
  26366. _proto.pseudo = function pseudo() {
  26367. var _this4 = this;
  26368. var pseudoStr = '';
  26369. var startingToken = this.currToken;
  26370. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  26371. pseudoStr += this.content();
  26372. this.position++;
  26373. }
  26374. if (!this.currToken) {
  26375. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  26376. }
  26377. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  26378. this.splitWord(false, function (first, length) {
  26379. pseudoStr += first;
  26380. _this4.newNode(new _pseudo.default({
  26381. value: pseudoStr,
  26382. source: getTokenSourceSpan(startingToken, _this4.currToken),
  26383. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  26384. }));
  26385. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  26386. _this4.error('Misplaced parenthesis.', {
  26387. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  26388. });
  26389. }
  26390. });
  26391. } else {
  26392. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  26393. }
  26394. };
  26395. _proto.space = function space() {
  26396. var content = this.content(); // Handle space before and after the selector
  26397. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  26398. return node.type === 'comment';
  26399. })) {
  26400. this.spaces = this.optionalSpace(content);
  26401. this.position++;
  26402. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  26403. this.current.last.spaces.after = this.optionalSpace(content);
  26404. this.position++;
  26405. } else {
  26406. this.combinator();
  26407. }
  26408. };
  26409. _proto.string = function string() {
  26410. var current = this.currToken;
  26411. this.newNode(new _string.default({
  26412. value: this.content(),
  26413. source: getTokenSource(current),
  26414. sourceIndex: current[_tokenize.FIELDS.START_POS]
  26415. }));
  26416. this.position++;
  26417. };
  26418. _proto.universal = function universal(namespace) {
  26419. var nextToken = this.nextToken;
  26420. if (nextToken && this.content(nextToken) === '|') {
  26421. this.position++;
  26422. return this.namespace();
  26423. }
  26424. var current = this.currToken;
  26425. this.newNode(new _universal.default({
  26426. value: this.content(),
  26427. source: getTokenSource(current),
  26428. sourceIndex: current[_tokenize.FIELDS.START_POS]
  26429. }), namespace);
  26430. this.position++;
  26431. };
  26432. _proto.splitWord = function splitWord(namespace, firstCallback) {
  26433. var _this5 = this;
  26434. var nextToken = this.nextToken;
  26435. var word = this.content();
  26436. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  26437. this.position++;
  26438. var current = this.content();
  26439. word += current;
  26440. if (current.lastIndexOf('\\') === current.length - 1) {
  26441. var next = this.nextToken;
  26442. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  26443. word += this.requiredSpace(this.content(next));
  26444. this.position++;
  26445. }
  26446. }
  26447. nextToken = this.nextToken;
  26448. }
  26449. var hasClass = (0, _indexesOf.default)(word, '.').filter(function (i) {
  26450. return word[i - 1] !== '\\';
  26451. });
  26452. var hasId = (0, _indexesOf.default)(word, '#').filter(function (i) {
  26453. return word[i - 1] !== '\\';
  26454. }); // Eliminate Sass interpolations from the list of id indexes
  26455. var interpolations = (0, _indexesOf.default)(word, '#{');
  26456. if (interpolations.length) {
  26457. hasId = hasId.filter(function (hashIndex) {
  26458. return !~interpolations.indexOf(hashIndex);
  26459. });
  26460. }
  26461. var indices = (0, _sortAscending.default)((0, _uniq.default)([0].concat(hasClass, hasId)));
  26462. indices.forEach(function (ind, i) {
  26463. var index = indices[i + 1] || word.length;
  26464. var value = word.slice(ind, index);
  26465. if (i === 0 && firstCallback) {
  26466. return firstCallback.call(_this5, value, indices.length);
  26467. }
  26468. var node;
  26469. var current = _this5.currToken;
  26470. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  26471. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  26472. if (~hasClass.indexOf(ind)) {
  26473. var classNameOpts = {
  26474. value: value.slice(1),
  26475. source: source,
  26476. sourceIndex: sourceIndex
  26477. };
  26478. node = new _className.default(unescapeProp(classNameOpts, "value"));
  26479. } else if (~hasId.indexOf(ind)) {
  26480. var idOpts = {
  26481. value: value.slice(1),
  26482. source: source,
  26483. sourceIndex: sourceIndex
  26484. };
  26485. node = new _id.default(unescapeProp(idOpts, "value"));
  26486. } else {
  26487. var tagOpts = {
  26488. value: value,
  26489. source: source,
  26490. sourceIndex: sourceIndex
  26491. };
  26492. unescapeProp(tagOpts, "value");
  26493. node = new _tag.default(tagOpts);
  26494. }
  26495. _this5.newNode(node, namespace); // Ensure that the namespace is used only once
  26496. namespace = null;
  26497. });
  26498. this.position++;
  26499. };
  26500. _proto.word = function word(namespace) {
  26501. var nextToken = this.nextToken;
  26502. if (nextToken && this.content(nextToken) === '|') {
  26503. this.position++;
  26504. return this.namespace();
  26505. }
  26506. return this.splitWord(namespace);
  26507. };
  26508. _proto.loop = function loop() {
  26509. while (this.position < this.tokens.length) {
  26510. this.parse(true);
  26511. }
  26512. this.current._inferEndPosition();
  26513. return this.root;
  26514. };
  26515. _proto.parse = function parse(throwOnParenthesis) {
  26516. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  26517. case tokens.space:
  26518. this.space();
  26519. break;
  26520. case tokens.comment:
  26521. this.comment();
  26522. break;
  26523. case tokens.openParenthesis:
  26524. this.parentheses();
  26525. break;
  26526. case tokens.closeParenthesis:
  26527. if (throwOnParenthesis) {
  26528. this.missingParenthesis();
  26529. }
  26530. break;
  26531. case tokens.openSquare:
  26532. this.attribute();
  26533. break;
  26534. case tokens.dollar:
  26535. case tokens.caret:
  26536. case tokens.equals:
  26537. case tokens.word:
  26538. this.word();
  26539. break;
  26540. case tokens.colon:
  26541. this.pseudo();
  26542. break;
  26543. case tokens.comma:
  26544. this.comma();
  26545. break;
  26546. case tokens.asterisk:
  26547. this.universal();
  26548. break;
  26549. case tokens.ampersand:
  26550. this.nesting();
  26551. break;
  26552. case tokens.slash:
  26553. case tokens.combinator:
  26554. this.combinator();
  26555. break;
  26556. case tokens.str:
  26557. this.string();
  26558. break;
  26559. // These cases throw; no break needed.
  26560. case tokens.closeSquare:
  26561. this.missingSquareBracket();
  26562. case tokens.semicolon:
  26563. this.missingBackslash();
  26564. default:
  26565. this.unexpected();
  26566. }
  26567. }
  26568. /**
  26569. * Helpers
  26570. */
  26571. ;
  26572. _proto.expected = function expected(description, index, found) {
  26573. if (Array.isArray(description)) {
  26574. var last = description.pop();
  26575. description = description.join(', ') + " or " + last;
  26576. }
  26577. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  26578. if (!found) {
  26579. return this.error("Expected " + an + " " + description + ".", {
  26580. index: index
  26581. });
  26582. }
  26583. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  26584. index: index
  26585. });
  26586. };
  26587. _proto.requiredSpace = function requiredSpace(space) {
  26588. return this.options.lossy ? ' ' : space;
  26589. };
  26590. _proto.optionalSpace = function optionalSpace(space) {
  26591. return this.options.lossy ? '' : space;
  26592. };
  26593. _proto.lossySpace = function lossySpace(space, required) {
  26594. if (this.options.lossy) {
  26595. return required ? ' ' : '';
  26596. } else {
  26597. return space;
  26598. }
  26599. };
  26600. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  26601. var content = this.content(token);
  26602. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  26603. return this.requiredSpace(content);
  26604. } else {
  26605. return content;
  26606. }
  26607. };
  26608. _proto.newNode = function newNode(node, namespace) {
  26609. if (namespace) {
  26610. if (/^ +$/.test(namespace)) {
  26611. if (!this.options.lossy) {
  26612. this.spaces = (this.spaces || '') + namespace;
  26613. }
  26614. namespace = true;
  26615. }
  26616. node.namespace = namespace;
  26617. unescapeProp(node, "namespace");
  26618. }
  26619. if (this.spaces) {
  26620. node.spaces.before = this.spaces;
  26621. this.spaces = '';
  26622. }
  26623. return this.current.append(node);
  26624. };
  26625. _proto.content = function content(token) {
  26626. if (token === void 0) {
  26627. token = this.currToken;
  26628. }
  26629. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  26630. };
  26631. /**
  26632. * returns the index of the next non-whitespace, non-comment token.
  26633. * returns -1 if no meaningful token is found.
  26634. */
  26635. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  26636. if (startPosition === void 0) {
  26637. startPosition = this.position + 1;
  26638. }
  26639. var searchPosition = startPosition;
  26640. while (searchPosition < this.tokens.length) {
  26641. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  26642. searchPosition++;
  26643. continue;
  26644. } else {
  26645. return searchPosition;
  26646. }
  26647. }
  26648. return -1;
  26649. };
  26650. _createClass(Parser, [{
  26651. key: "currToken",
  26652. get: function get() {
  26653. return this.tokens[this.position];
  26654. }
  26655. }, {
  26656. key: "nextToken",
  26657. get: function get() {
  26658. return this.tokens[this.position + 1];
  26659. }
  26660. }, {
  26661. key: "prevToken",
  26662. get: function get() {
  26663. return this.tokens[this.position - 1];
  26664. }
  26665. }]);
  26666. return Parser;
  26667. }();
  26668. exports.default = Parser;
  26669. module.exports = exports.default;
  26670. });
  26671. var processor = createCommonjsModule(function (module, exports) {
  26672. exports.__esModule = true;
  26673. exports.default = void 0;
  26674. var _parser = _interopRequireDefault(parser);
  26675. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26676. var Processor =
  26677. /*#__PURE__*/
  26678. function () {
  26679. function Processor(func, options) {
  26680. this.func = func || function noop() {};
  26681. this.funcRes = null;
  26682. this.options = options;
  26683. }
  26684. var _proto = Processor.prototype;
  26685. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  26686. if (options === void 0) {
  26687. options = {};
  26688. }
  26689. var merged = Object.assign({}, this.options, options);
  26690. if (merged.updateSelector === false) {
  26691. return false;
  26692. } else {
  26693. return typeof rule !== "string";
  26694. }
  26695. };
  26696. _proto._isLossy = function _isLossy(options) {
  26697. if (options === void 0) {
  26698. options = {};
  26699. }
  26700. var merged = Object.assign({}, this.options, options);
  26701. if (merged.lossless === false) {
  26702. return true;
  26703. } else {
  26704. return false;
  26705. }
  26706. };
  26707. _proto._root = function _root(rule, options) {
  26708. if (options === void 0) {
  26709. options = {};
  26710. }
  26711. var parser = new _parser.default(rule, this._parseOptions(options));
  26712. return parser.root;
  26713. };
  26714. _proto._parseOptions = function _parseOptions(options) {
  26715. return {
  26716. lossy: this._isLossy(options)
  26717. };
  26718. };
  26719. _proto._run = function _run(rule, options) {
  26720. var _this = this;
  26721. if (options === void 0) {
  26722. options = {};
  26723. }
  26724. return new Promise(function (resolve, reject) {
  26725. try {
  26726. var root = _this._root(rule, options);
  26727. Promise.resolve(_this.func(root)).then(function (transform) {
  26728. var string = undefined;
  26729. if (_this._shouldUpdateSelector(rule, options)) {
  26730. string = root.toString();
  26731. rule.selector = string;
  26732. }
  26733. return {
  26734. transform: transform,
  26735. root: root,
  26736. string: string
  26737. };
  26738. }).then(resolve, reject);
  26739. } catch (e) {
  26740. reject(e);
  26741. return;
  26742. }
  26743. });
  26744. };
  26745. _proto._runSync = function _runSync(rule, options) {
  26746. if (options === void 0) {
  26747. options = {};
  26748. }
  26749. var root = this._root(rule, options);
  26750. var transform = this.func(root);
  26751. if (transform && typeof transform.then === "function") {
  26752. throw new Error("Selector processor returned a promise to a synchronous call.");
  26753. }
  26754. var string = undefined;
  26755. if (options.updateSelector && typeof rule !== "string") {
  26756. string = root.toString();
  26757. rule.selector = string;
  26758. }
  26759. return {
  26760. transform: transform,
  26761. root: root,
  26762. string: string
  26763. };
  26764. }
  26765. /**
  26766. * Process rule into a selector AST.
  26767. *
  26768. * @param rule {postcss.Rule | string} The css selector to be processed
  26769. * @param options The options for processing
  26770. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  26771. */
  26772. ;
  26773. _proto.ast = function ast(rule, options) {
  26774. return this._run(rule, options).then(function (result) {
  26775. return result.root;
  26776. });
  26777. }
  26778. /**
  26779. * Process rule into a selector AST synchronously.
  26780. *
  26781. * @param rule {postcss.Rule | string} The css selector to be processed
  26782. * @param options The options for processing
  26783. * @returns {parser.Root} The AST of the selector after processing it.
  26784. */
  26785. ;
  26786. _proto.astSync = function astSync(rule, options) {
  26787. return this._runSync(rule, options).root;
  26788. }
  26789. /**
  26790. * Process a selector into a transformed value asynchronously
  26791. *
  26792. * @param rule {postcss.Rule | string} The css selector to be processed
  26793. * @param options The options for processing
  26794. * @returns {Promise<any>} The value returned by the processor.
  26795. */
  26796. ;
  26797. _proto.transform = function transform(rule, options) {
  26798. return this._run(rule, options).then(function (result) {
  26799. return result.transform;
  26800. });
  26801. }
  26802. /**
  26803. * Process a selector into a transformed value synchronously.
  26804. *
  26805. * @param rule {postcss.Rule | string} The css selector to be processed
  26806. * @param options The options for processing
  26807. * @returns {any} The value returned by the processor.
  26808. */
  26809. ;
  26810. _proto.transformSync = function transformSync(rule, options) {
  26811. return this._runSync(rule, options).transform;
  26812. }
  26813. /**
  26814. * Process a selector into a new selector string asynchronously.
  26815. *
  26816. * @param rule {postcss.Rule | string} The css selector to be processed
  26817. * @param options The options for processing
  26818. * @returns {string} the selector after processing.
  26819. */
  26820. ;
  26821. _proto.process = function process(rule, options) {
  26822. return this._run(rule, options).then(function (result) {
  26823. return result.string || result.root.toString();
  26824. });
  26825. }
  26826. /**
  26827. * Process a selector into a new selector string synchronously.
  26828. *
  26829. * @param rule {postcss.Rule | string} The css selector to be processed
  26830. * @param options The options for processing
  26831. * @returns {string} the selector after processing.
  26832. */
  26833. ;
  26834. _proto.processSync = function processSync(rule, options) {
  26835. var result = this._runSync(rule, options);
  26836. return result.string || result.root.toString();
  26837. };
  26838. return Processor;
  26839. }();
  26840. exports.default = Processor;
  26841. module.exports = exports.default;
  26842. });
  26843. var constructors = createCommonjsModule(function (module, exports) {
  26844. exports.__esModule = true;
  26845. exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0;
  26846. var _attribute = _interopRequireDefault(attribute);
  26847. var _className = _interopRequireDefault(className);
  26848. var _combinator = _interopRequireDefault(combinator);
  26849. var _comment = _interopRequireDefault(comment);
  26850. var _id = _interopRequireDefault(id);
  26851. var _nesting = _interopRequireDefault(nesting);
  26852. var _pseudo = _interopRequireDefault(pseudo);
  26853. var _root = _interopRequireDefault(root);
  26854. var _selector = _interopRequireDefault(selector);
  26855. var _string = _interopRequireDefault(string);
  26856. var _tag = _interopRequireDefault(tag);
  26857. var _universal = _interopRequireDefault(universal);
  26858. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26859. var attribute$1 = function attribute(opts) {
  26860. return new _attribute.default(opts);
  26861. };
  26862. exports.attribute = attribute$1;
  26863. var className$1 = function className(opts) {
  26864. return new _className.default(opts);
  26865. };
  26866. exports.className = className$1;
  26867. var combinator$1 = function combinator(opts) {
  26868. return new _combinator.default(opts);
  26869. };
  26870. exports.combinator = combinator$1;
  26871. var comment$1 = function comment(opts) {
  26872. return new _comment.default(opts);
  26873. };
  26874. exports.comment = comment$1;
  26875. var id$1 = function id(opts) {
  26876. return new _id.default(opts);
  26877. };
  26878. exports.id = id$1;
  26879. var nesting$1 = function nesting(opts) {
  26880. return new _nesting.default(opts);
  26881. };
  26882. exports.nesting = nesting$1;
  26883. var pseudo$1 = function pseudo(opts) {
  26884. return new _pseudo.default(opts);
  26885. };
  26886. exports.pseudo = pseudo$1;
  26887. var root$1 = function root(opts) {
  26888. return new _root.default(opts);
  26889. };
  26890. exports.root = root$1;
  26891. var selector$1 = function selector(opts) {
  26892. return new _selector.default(opts);
  26893. };
  26894. exports.selector = selector$1;
  26895. var string$1 = function string(opts) {
  26896. return new _string.default(opts);
  26897. };
  26898. exports.string = string$1;
  26899. var tag$1 = function tag(opts) {
  26900. return new _tag.default(opts);
  26901. };
  26902. exports.tag = tag$1;
  26903. var universal$1 = function universal(opts) {
  26904. return new _universal.default(opts);
  26905. };
  26906. exports.universal = universal$1;
  26907. });
  26908. var guards = createCommonjsModule(function (module, exports) {
  26909. exports.__esModule = true;
  26910. exports.isNode = isNode;
  26911. exports.isPseudoElement = isPseudoElement;
  26912. exports.isPseudoClass = isPseudoClass;
  26913. exports.isContainer = isContainer;
  26914. exports.isNamespace = isNamespace;
  26915. exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = exports.isPseudo = exports.isNesting = exports.isIdentifier = exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0;
  26916. var _IS_TYPE;
  26917. var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[types$2.ATTRIBUTE] = true, _IS_TYPE[types$2.CLASS] = true, _IS_TYPE[types$2.COMBINATOR] = true, _IS_TYPE[types$2.COMMENT] = true, _IS_TYPE[types$2.ID] = true, _IS_TYPE[types$2.NESTING] = true, _IS_TYPE[types$2.PSEUDO] = true, _IS_TYPE[types$2.ROOT] = true, _IS_TYPE[types$2.SELECTOR] = true, _IS_TYPE[types$2.STRING] = true, _IS_TYPE[types$2.TAG] = true, _IS_TYPE[types$2.UNIVERSAL] = true, _IS_TYPE);
  26918. function isNode(node) {
  26919. return typeof node === "object" && IS_TYPE[node.type];
  26920. }
  26921. function isNodeType(type, node) {
  26922. return isNode(node) && node.type === type;
  26923. }
  26924. var isAttribute = isNodeType.bind(null, types$2.ATTRIBUTE);
  26925. exports.isAttribute = isAttribute;
  26926. var isClassName = isNodeType.bind(null, types$2.CLASS);
  26927. exports.isClassName = isClassName;
  26928. var isCombinator = isNodeType.bind(null, types$2.COMBINATOR);
  26929. exports.isCombinator = isCombinator;
  26930. var isComment = isNodeType.bind(null, types$2.COMMENT);
  26931. exports.isComment = isComment;
  26932. var isIdentifier = isNodeType.bind(null, types$2.ID);
  26933. exports.isIdentifier = isIdentifier;
  26934. var isNesting = isNodeType.bind(null, types$2.NESTING);
  26935. exports.isNesting = isNesting;
  26936. var isPseudo = isNodeType.bind(null, types$2.PSEUDO);
  26937. exports.isPseudo = isPseudo;
  26938. var isRoot = isNodeType.bind(null, types$2.ROOT);
  26939. exports.isRoot = isRoot;
  26940. var isSelector = isNodeType.bind(null, types$2.SELECTOR);
  26941. exports.isSelector = isSelector;
  26942. var isString = isNodeType.bind(null, types$2.STRING);
  26943. exports.isString = isString;
  26944. var isTag = isNodeType.bind(null, types$2.TAG);
  26945. exports.isTag = isTag;
  26946. var isUniversal = isNodeType.bind(null, types$2.UNIVERSAL);
  26947. exports.isUniversal = isUniversal;
  26948. function isPseudoElement(node) {
  26949. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after");
  26950. }
  26951. function isPseudoClass(node) {
  26952. return isPseudo(node) && !isPseudoElement(node);
  26953. }
  26954. function isContainer(node) {
  26955. return !!(isNode(node) && node.walk);
  26956. }
  26957. function isNamespace(node) {
  26958. return isAttribute(node) || isTag(node);
  26959. }
  26960. });
  26961. var selectors = createCommonjsModule(function (module, exports) {
  26962. exports.__esModule = true;
  26963. Object.keys(types$2).forEach(function (key) {
  26964. if (key === "default" || key === "__esModule") return;
  26965. exports[key] = types$2[key];
  26966. });
  26967. Object.keys(constructors).forEach(function (key) {
  26968. if (key === "default" || key === "__esModule") return;
  26969. exports[key] = constructors[key];
  26970. });
  26971. Object.keys(guards).forEach(function (key) {
  26972. if (key === "default" || key === "__esModule") return;
  26973. exports[key] = guards[key];
  26974. });
  26975. });
  26976. var dist = createCommonjsModule(function (module, exports) {
  26977. exports.__esModule = true;
  26978. exports.default = void 0;
  26979. var _processor = _interopRequireDefault(processor);
  26980. var selectors$1 = _interopRequireWildcard(selectors);
  26981. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
  26982. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26983. var parser = function parser(processor) {
  26984. return new _processor.default(processor);
  26985. };
  26986. Object.assign(parser, selectors$1);
  26987. delete parser.__esModule;
  26988. var _default = parser;
  26989. exports.default = _default;
  26990. module.exports = exports.default;
  26991. });
  26992. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(dist);
  26993. const animationNameRE = /^(-\w+-)?animation-name$/;
  26994. const animationRE = /^(-\w+-)?animation$/;
  26995. const scopedPlugin = (id = '') => {
  26996. const keyframes = Object.create(null);
  26997. const shortId = id.replace(/^data-v-/, '');
  26998. return {
  26999. postcssPlugin: 'vue-sfc-scoped',
  27000. Rule(rule) {
  27001. processRule(id, rule);
  27002. },
  27003. AtRule(node) {
  27004. if (/-?keyframes$/.test(node.name) &&
  27005. !node.params.endsWith(`-${shortId}`)) {
  27006. // register keyframes
  27007. keyframes[node.params] = node.params = node.params + '-' + shortId;
  27008. }
  27009. },
  27010. OnceExit(root) {
  27011. if (Object.keys(keyframes).length) {
  27012. // If keyframes are found in this <style>, find and rewrite animation names
  27013. // in declarations.
  27014. // Caveat: this only works for keyframes and animation rules in the same
  27015. // <style> element.
  27016. // individual animation-name declaration
  27017. root.walkDecls(decl => {
  27018. if (animationNameRE.test(decl.prop)) {
  27019. decl.value = decl.value
  27020. .split(',')
  27021. .map(v => keyframes[v.trim()] || v.trim())
  27022. .join(',');
  27023. }
  27024. // shorthand
  27025. if (animationRE.test(decl.prop)) {
  27026. decl.value = decl.value
  27027. .split(',')
  27028. .map(v => {
  27029. const vals = v.trim().split(/\s+/);
  27030. const i = vals.findIndex(val => keyframes[val]);
  27031. if (i !== -1) {
  27032. vals.splice(i, 1, keyframes[vals[i]]);
  27033. return vals.join(' ');
  27034. }
  27035. else {
  27036. return v;
  27037. }
  27038. })
  27039. .join(',');
  27040. }
  27041. });
  27042. }
  27043. }
  27044. };
  27045. };
  27046. const processedRules = new WeakSet();
  27047. function processRule(id, rule) {
  27048. if (processedRules.has(rule)) {
  27049. return;
  27050. }
  27051. processedRules.add(rule);
  27052. rule.selector = selectorParser(selectorRoot => {
  27053. selectorRoot.each(selector => {
  27054. rewriteSelector(id, selector, selectorRoot);
  27055. });
  27056. }).processSync(rule.selector);
  27057. }
  27058. function rewriteSelector(id, selector, selectorRoot, slotted = false) {
  27059. let node = null;
  27060. let shouldInject = true;
  27061. // find the last child node to insert attribute selector
  27062. selector.each(n => {
  27063. // DEPRECATED ">>>" and "/deep/" combinator
  27064. if (n.type === 'combinator' &&
  27065. (n.value === '>>>' || n.value === '/deep/')) {
  27066. n.value = ' ';
  27067. n.spaces.before = n.spaces.after = '';
  27068. warn(`the >>> and /deep/ combinators have been deprecated. ` +
  27069. `Use :deep() instead.`);
  27070. return false;
  27071. }
  27072. if (n.type === 'pseudo') {
  27073. const { value } = n;
  27074. // deep: inject [id] attribute at the node before the ::v-deep
  27075. // combinator.
  27076. if (value === ':deep' || value === '::v-deep') {
  27077. if (n.nodes.length) {
  27078. // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
  27079. // replace the current node with ::v-deep's inner selector
  27080. let last = n;
  27081. n.nodes[0].each(ss => {
  27082. selector.insertAfter(last, ss);
  27083. last = ss;
  27084. });
  27085. // insert a space combinator before if it doesn't already have one
  27086. const prev = selector.at(selector.index(n) - 1);
  27087. if (!prev || !isSpaceCombinator(prev)) {
  27088. selector.insertAfter(n, selectorParser.combinator({
  27089. value: ' '
  27090. }));
  27091. }
  27092. selector.removeChild(n);
  27093. }
  27094. else {
  27095. // DEPRECATED usage
  27096. // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
  27097. warn(`::v-deep usage as a combinator has ` +
  27098. `been deprecated. Use :deep(<inner-selector>) instead.`);
  27099. const prev = selector.at(selector.index(n) - 1);
  27100. if (prev && isSpaceCombinator(prev)) {
  27101. selector.removeChild(prev);
  27102. }
  27103. selector.removeChild(n);
  27104. }
  27105. return false;
  27106. }
  27107. // slot: use selector inside `::v-slotted` and inject [id + '-s']
  27108. // instead.
  27109. // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
  27110. if (value === ':slotted' || value === '::v-slotted') {
  27111. rewriteSelector(id, n.nodes[0], selectorRoot, true /* slotted */);
  27112. let last = n;
  27113. n.nodes[0].each(ss => {
  27114. selector.insertAfter(last, ss);
  27115. last = ss;
  27116. });
  27117. // selector.insertAfter(n, n.nodes[0])
  27118. selector.removeChild(n);
  27119. // since slotted attribute already scopes the selector there's no
  27120. // need for the non-slot attribute.
  27121. shouldInject = false;
  27122. return false;
  27123. }
  27124. // global: replace with inner selector and do not inject [id].
  27125. // ::v-global(.foo) -> .foo
  27126. if (value === ':global' || value === '::v-global') {
  27127. selectorRoot.insertAfter(selector, n.nodes[0]);
  27128. selectorRoot.removeChild(selector);
  27129. return false;
  27130. }
  27131. }
  27132. if (n.type !== 'pseudo' && n.type !== 'combinator') {
  27133. node = n;
  27134. }
  27135. });
  27136. if (node) {
  27137. node.spaces.after = '';
  27138. }
  27139. else {
  27140. // For deep selectors & standalone pseudo selectors,
  27141. // the attribute selectors are prepended rather than appended.
  27142. // So all leading spaces must be eliminated to avoid problems.
  27143. selector.first.spaces.before = '';
  27144. }
  27145. if (shouldInject) {
  27146. const idToAdd = slotted ? id + '-s' : id;
  27147. selector.insertAfter(
  27148. // If node is null it means we need to inject [id] at the start
  27149. // insertAfter can handle `null` here
  27150. node, selectorParser.attribute({
  27151. attribute: idToAdd,
  27152. value: idToAdd,
  27153. raws: {},
  27154. quoteMark: `"`
  27155. }));
  27156. }
  27157. }
  27158. function isSpaceCombinator(node) {
  27159. return node.type === 'combinator' && /^\s+$/.test(node.value);
  27160. }
  27161. scopedPlugin.postcss = true;
  27162. var SourceMapConsumer$2 = sourceMap.SourceMapConsumer;
  27163. var SourceMapGenerator$3 = sourceMap.SourceMapGenerator;
  27164. var mergeSourceMap = merge$1;
  27165. /**
  27166. * Merge old source map and new source map and return merged.
  27167. * If old or new source map value is falsy, return another one as it is.
  27168. *
  27169. * @param {object|string} [oldMap] old source map object
  27170. * @param {object|string} [newmap] new source map object
  27171. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  27172. */
  27173. function merge$1(oldMap, newMap) {
  27174. if (!oldMap) return newMap
  27175. if (!newMap) return oldMap
  27176. var oldMapConsumer = new SourceMapConsumer$2(oldMap);
  27177. var newMapConsumer = new SourceMapConsumer$2(newMap);
  27178. var mergedMapGenerator = new SourceMapGenerator$3();
  27179. // iterate on new map and overwrite original position of new map with one of old map
  27180. newMapConsumer.eachMapping(function(m) {
  27181. // pass when `originalLine` is null.
  27182. // It occurs in case that the node does not have origin in original code.
  27183. if (m.originalLine == null) return
  27184. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  27185. line: m.originalLine,
  27186. column: m.originalColumn
  27187. });
  27188. if (origPosInOldMap.source == null) return
  27189. mergedMapGenerator.addMapping({
  27190. original: {
  27191. line: origPosInOldMap.line,
  27192. column: origPosInOldMap.column
  27193. },
  27194. generated: {
  27195. line: m.generatedLine,
  27196. column: m.generatedColumn
  27197. },
  27198. source: origPosInOldMap.source,
  27199. name: origPosInOldMap.name
  27200. });
  27201. });
  27202. var consumers = [oldMapConsumer, newMapConsumer];
  27203. consumers.forEach(function(consumer) {
  27204. consumer.sources.forEach(function(sourceFile) {
  27205. mergedMapGenerator._sources.add(sourceFile);
  27206. var sourceContent = consumer.sourceContentFor(sourceFile);
  27207. if (sourceContent != null) {
  27208. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  27209. }
  27210. });
  27211. });
  27212. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  27213. mergedMapGenerator._file = oldMap.file;
  27214. return JSON.parse(mergedMapGenerator.toString())
  27215. }
  27216. // .scss/.sass processor
  27217. const scss = (source, map, options, load = require) => {
  27218. const nodeSass = load('sass');
  27219. const finalOptions = {
  27220. ...options,
  27221. data: getSource(source, options.filename, options.additionalData),
  27222. file: options.filename,
  27223. outFile: options.filename,
  27224. sourceMap: !!map
  27225. };
  27226. try {
  27227. const result = nodeSass.renderSync(finalOptions);
  27228. const dependencies = result.stats.includedFiles;
  27229. if (map) {
  27230. return {
  27231. code: result.css.toString(),
  27232. map: mergeSourceMap(map, JSON.parse(result.map.toString())),
  27233. errors: [],
  27234. dependencies
  27235. };
  27236. }
  27237. return { code: result.css.toString(), errors: [], dependencies };
  27238. }
  27239. catch (e) {
  27240. return { code: '', errors: [e], dependencies: [] };
  27241. }
  27242. };
  27243. const sass = (source, map, options, load) => scss(source, map, {
  27244. ...options,
  27245. indentedSyntax: true
  27246. }, load);
  27247. // .less
  27248. const less = (source, map, options, load = require) => {
  27249. const nodeLess = load('less');
  27250. let result;
  27251. let error = null;
  27252. nodeLess.render(getSource(source, options.filename, options.additionalData), { ...options, syncImport: true }, (err, output) => {
  27253. error = err;
  27254. result = output;
  27255. });
  27256. if (error)
  27257. return { code: '', errors: [error], dependencies: [] };
  27258. const dependencies = result.imports;
  27259. if (map) {
  27260. return {
  27261. code: result.css.toString(),
  27262. map: mergeSourceMap(map, result.map),
  27263. errors: [],
  27264. dependencies: dependencies
  27265. };
  27266. }
  27267. return {
  27268. code: result.css.toString(),
  27269. errors: [],
  27270. dependencies: dependencies
  27271. };
  27272. };
  27273. // .styl
  27274. const styl = (source, map, options, load = require) => {
  27275. const nodeStylus = load('stylus');
  27276. try {
  27277. const ref = nodeStylus(source);
  27278. Object.keys(options).forEach(key => ref.set(key, options[key]));
  27279. if (map)
  27280. ref.set('sourcemap', { inline: false, comment: false });
  27281. const result = ref.render();
  27282. const dependencies = ref.deps();
  27283. if (map) {
  27284. return {
  27285. code: result,
  27286. map: mergeSourceMap(map, ref.sourcemap),
  27287. errors: [],
  27288. dependencies
  27289. };
  27290. }
  27291. return { code: result, errors: [], dependencies };
  27292. }
  27293. catch (e) {
  27294. return { code: '', errors: [e], dependencies: [] };
  27295. }
  27296. };
  27297. function getSource(source, filename, additionalData) {
  27298. if (!additionalData)
  27299. return source;
  27300. if (isFunction(additionalData)) {
  27301. return additionalData(source, filename);
  27302. }
  27303. return additionalData + source;
  27304. }
  27305. const processors = {
  27306. less,
  27307. sass,
  27308. scss,
  27309. styl,
  27310. stylus: styl
  27311. };
  27312. function compileStyle(options) {
  27313. return doCompileStyle({
  27314. ...options,
  27315. isAsync: false
  27316. });
  27317. }
  27318. function compileStyleAsync(options) {
  27319. return doCompileStyle({ ...options, isAsync: true });
  27320. }
  27321. function doCompileStyle(options) {
  27322. const { filename, id, scoped = false, trim = true, isProd = false, modules = false, modulesOptions = {}, preprocessLang, postcssOptions, postcssPlugins } = options;
  27323. const preprocessor = preprocessLang && processors[preprocessLang];
  27324. const preProcessedSource = preprocessor && preprocess$1(options, preprocessor);
  27325. const map = preProcessedSource
  27326. ? preProcessedSource.map
  27327. : options.inMap || options.map;
  27328. const source = preProcessedSource ? preProcessedSource.code : options.source;
  27329. const shortId = id.replace(/^data-v-/, '');
  27330. const longId = `data-v-${shortId}`;
  27331. const plugins = (postcssPlugins || []).slice();
  27332. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  27333. if (trim) {
  27334. plugins.push(trimPlugin());
  27335. }
  27336. if (scoped) {
  27337. plugins.push(scopedPlugin(longId));
  27338. }
  27339. let cssModules;
  27340. if (modules) {
  27341. {
  27342. throw new Error('[@vue/compiler-sfc] `modules` option is not supported in the browser build.');
  27343. }
  27344. }
  27345. const postCSSOptions = {
  27346. ...postcssOptions,
  27347. to: filename,
  27348. from: filename
  27349. };
  27350. if (map) {
  27351. postCSSOptions.map = {
  27352. inline: false,
  27353. annotation: false,
  27354. prev: map
  27355. };
  27356. }
  27357. let result;
  27358. let code;
  27359. let outMap;
  27360. // stylus output include plain css. so need remove the repeat item
  27361. const dependencies = new Set(preProcessedSource ? preProcessedSource.dependencies : []);
  27362. // sass has filename self when provided filename option
  27363. dependencies.delete(filename);
  27364. const errors = [];
  27365. if (preProcessedSource && preProcessedSource.errors.length) {
  27366. errors.push(...preProcessedSource.errors);
  27367. }
  27368. const recordPlainCssDependencies = (messages) => {
  27369. messages.forEach(msg => {
  27370. if (msg.type === 'dependency') {
  27371. // postcss output path is absolute position path
  27372. dependencies.add(msg.file);
  27373. }
  27374. });
  27375. return dependencies;
  27376. };
  27377. try {
  27378. result = postcss__default(plugins).process(source, postCSSOptions);
  27379. // In async mode, return a promise.
  27380. if (options.isAsync) {
  27381. return result
  27382. .then(result => ({
  27383. code: result.css || '',
  27384. map: result.map && result.map.toJSON(),
  27385. errors,
  27386. modules: cssModules,
  27387. rawResult: result,
  27388. dependencies: recordPlainCssDependencies(result.messages)
  27389. }))
  27390. .catch(error => ({
  27391. code: '',
  27392. map: undefined,
  27393. errors: [...errors, error],
  27394. rawResult: undefined,
  27395. dependencies
  27396. }));
  27397. }
  27398. recordPlainCssDependencies(result.messages);
  27399. // force synchronous transform (we know we only have sync plugins)
  27400. code = result.css;
  27401. outMap = result.map;
  27402. }
  27403. catch (e) {
  27404. errors.push(e);
  27405. }
  27406. return {
  27407. code: code || ``,
  27408. map: outMap && outMap.toJSON(),
  27409. errors,
  27410. rawResult: result,
  27411. dependencies
  27412. };
  27413. }
  27414. function preprocess$1(options, preprocessor) {
  27415. if (!options.preprocessCustomRequire) {
  27416. throw new Error(`[@vue/compiler-sfc] Style preprocessing in the browser build must ` +
  27417. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  27418. `version of the preprocessor.`);
  27419. }
  27420. return preprocessor(options.source, options.inMap || options.map, {
  27421. filename: options.filename,
  27422. ...options.preprocessOptions
  27423. }, options.preprocessCustomRequire);
  27424. }
  27425. var global$1 = (typeof global !== "undefined" ? global :
  27426. typeof self !== "undefined" ? self :
  27427. typeof window !== "undefined" ? window : {});
  27428. var lookup = [];
  27429. var revLookup = [];
  27430. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  27431. var inited = false;
  27432. function init () {
  27433. inited = true;
  27434. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  27435. for (var i = 0, len = code.length; i < len; ++i) {
  27436. lookup[i] = code[i];
  27437. revLookup[code.charCodeAt(i)] = i;
  27438. }
  27439. revLookup['-'.charCodeAt(0)] = 62;
  27440. revLookup['_'.charCodeAt(0)] = 63;
  27441. }
  27442. function toByteArray (b64) {
  27443. if (!inited) {
  27444. init();
  27445. }
  27446. var i, j, l, tmp, placeHolders, arr;
  27447. var len = b64.length;
  27448. if (len % 4 > 0) {
  27449. throw new Error('Invalid string. Length must be a multiple of 4')
  27450. }
  27451. // the number of equal signs (place holders)
  27452. // if there are two placeholders, than the two characters before it
  27453. // represent one byte
  27454. // if there is only one, then the three characters before it represent 2 bytes
  27455. // this is just a cheap hack to not do indexOf twice
  27456. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  27457. // base64 is 4/3 + up to two characters of the original data
  27458. arr = new Arr(len * 3 / 4 - placeHolders);
  27459. // if there are placeholders, only get up to the last complete 4 chars
  27460. l = placeHolders > 0 ? len - 4 : len;
  27461. var L = 0;
  27462. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  27463. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  27464. arr[L++] = (tmp >> 16) & 0xFF;
  27465. arr[L++] = (tmp >> 8) & 0xFF;
  27466. arr[L++] = tmp & 0xFF;
  27467. }
  27468. if (placeHolders === 2) {
  27469. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  27470. arr[L++] = tmp & 0xFF;
  27471. } else if (placeHolders === 1) {
  27472. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  27473. arr[L++] = (tmp >> 8) & 0xFF;
  27474. arr[L++] = tmp & 0xFF;
  27475. }
  27476. return arr
  27477. }
  27478. function tripletToBase64 (num) {
  27479. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  27480. }
  27481. function encodeChunk (uint8, start, end) {
  27482. var tmp;
  27483. var output = [];
  27484. for (var i = start; i < end; i += 3) {
  27485. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  27486. output.push(tripletToBase64(tmp));
  27487. }
  27488. return output.join('')
  27489. }
  27490. function fromByteArray (uint8) {
  27491. if (!inited) {
  27492. init();
  27493. }
  27494. var tmp;
  27495. var len = uint8.length;
  27496. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  27497. var output = '';
  27498. var parts = [];
  27499. var maxChunkLength = 16383; // must be multiple of 3
  27500. // go through the array every three bytes, we'll deal with trailing stuff later
  27501. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  27502. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  27503. }
  27504. // pad the end with zeros, but make sure to not forget the extra bytes
  27505. if (extraBytes === 1) {
  27506. tmp = uint8[len - 1];
  27507. output += lookup[tmp >> 2];
  27508. output += lookup[(tmp << 4) & 0x3F];
  27509. output += '==';
  27510. } else if (extraBytes === 2) {
  27511. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  27512. output += lookup[tmp >> 10];
  27513. output += lookup[(tmp >> 4) & 0x3F];
  27514. output += lookup[(tmp << 2) & 0x3F];
  27515. output += '=';
  27516. }
  27517. parts.push(output);
  27518. return parts.join('')
  27519. }
  27520. function read (buffer, offset, isLE, mLen, nBytes) {
  27521. var e, m;
  27522. var eLen = nBytes * 8 - mLen - 1;
  27523. var eMax = (1 << eLen) - 1;
  27524. var eBias = eMax >> 1;
  27525. var nBits = -7;
  27526. var i = isLE ? (nBytes - 1) : 0;
  27527. var d = isLE ? -1 : 1;
  27528. var s = buffer[offset + i];
  27529. i += d;
  27530. e = s & ((1 << (-nBits)) - 1);
  27531. s >>= (-nBits);
  27532. nBits += eLen;
  27533. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  27534. m = e & ((1 << (-nBits)) - 1);
  27535. e >>= (-nBits);
  27536. nBits += mLen;
  27537. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  27538. if (e === 0) {
  27539. e = 1 - eBias;
  27540. } else if (e === eMax) {
  27541. return m ? NaN : ((s ? -1 : 1) * Infinity)
  27542. } else {
  27543. m = m + Math.pow(2, mLen);
  27544. e = e - eBias;
  27545. }
  27546. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  27547. }
  27548. function write (buffer, value, offset, isLE, mLen, nBytes) {
  27549. var e, m, c;
  27550. var eLen = nBytes * 8 - mLen - 1;
  27551. var eMax = (1 << eLen) - 1;
  27552. var eBias = eMax >> 1;
  27553. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  27554. var i = isLE ? 0 : (nBytes - 1);
  27555. var d = isLE ? 1 : -1;
  27556. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  27557. value = Math.abs(value);
  27558. if (isNaN(value) || value === Infinity) {
  27559. m = isNaN(value) ? 1 : 0;
  27560. e = eMax;
  27561. } else {
  27562. e = Math.floor(Math.log(value) / Math.LN2);
  27563. if (value * (c = Math.pow(2, -e)) < 1) {
  27564. e--;
  27565. c *= 2;
  27566. }
  27567. if (e + eBias >= 1) {
  27568. value += rt / c;
  27569. } else {
  27570. value += rt * Math.pow(2, 1 - eBias);
  27571. }
  27572. if (value * c >= 2) {
  27573. e++;
  27574. c /= 2;
  27575. }
  27576. if (e + eBias >= eMax) {
  27577. m = 0;
  27578. e = eMax;
  27579. } else if (e + eBias >= 1) {
  27580. m = (value * c - 1) * Math.pow(2, mLen);
  27581. e = e + eBias;
  27582. } else {
  27583. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  27584. e = 0;
  27585. }
  27586. }
  27587. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  27588. e = (e << mLen) | m;
  27589. eLen += mLen;
  27590. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  27591. buffer[offset + i - d] |= s * 128;
  27592. }
  27593. var toString$1 = {}.toString;
  27594. var isArray$1 = Array.isArray || function (arr) {
  27595. return toString$1.call(arr) == '[object Array]';
  27596. };
  27597. var INSPECT_MAX_BYTES = 50;
  27598. /**
  27599. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  27600. * === true Use Uint8Array implementation (fastest)
  27601. * === false Use Object implementation (most compatible, even IE6)
  27602. *
  27603. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  27604. * Opera 11.6+, iOS 4.2+.
  27605. *
  27606. * Due to various browser bugs, sometimes the Object implementation will be used even
  27607. * when the browser supports typed arrays.
  27608. *
  27609. * Note:
  27610. *
  27611. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  27612. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  27613. *
  27614. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  27615. *
  27616. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  27617. * incorrect length in some situations.
  27618. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  27619. * get the Object implementation, which is slower but behaves correctly.
  27620. */
  27621. Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
  27622. ? global$1.TYPED_ARRAY_SUPPORT
  27623. : true;
  27624. function kMaxLength () {
  27625. return Buffer.TYPED_ARRAY_SUPPORT
  27626. ? 0x7fffffff
  27627. : 0x3fffffff
  27628. }
  27629. function createBuffer (that, length) {
  27630. if (kMaxLength() < length) {
  27631. throw new RangeError('Invalid typed array length')
  27632. }
  27633. if (Buffer.TYPED_ARRAY_SUPPORT) {
  27634. // Return an augmented `Uint8Array` instance, for best performance
  27635. that = new Uint8Array(length);
  27636. that.__proto__ = Buffer.prototype;
  27637. } else {
  27638. // Fallback: Return an object instance of the Buffer class
  27639. if (that === null) {
  27640. that = new Buffer(length);
  27641. }
  27642. that.length = length;
  27643. }
  27644. return that
  27645. }
  27646. /**
  27647. * The Buffer constructor returns instances of `Uint8Array` that have their
  27648. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  27649. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  27650. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  27651. * returns a single octet.
  27652. *
  27653. * The `Uint8Array` prototype remains unmodified.
  27654. */
  27655. function Buffer (arg, encodingOrOffset, length) {
  27656. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  27657. return new Buffer(arg, encodingOrOffset, length)
  27658. }
  27659. // Common case.
  27660. if (typeof arg === 'number') {
  27661. if (typeof encodingOrOffset === 'string') {
  27662. throw new Error(
  27663. 'If encoding is specified then the first argument must be a string'
  27664. )
  27665. }
  27666. return allocUnsafe(this, arg)
  27667. }
  27668. return from(this, arg, encodingOrOffset, length)
  27669. }
  27670. Buffer.poolSize = 8192; // not used by this implementation
  27671. // TODO: Legacy, not needed anymore. Remove in next major version.
  27672. Buffer._augment = function (arr) {
  27673. arr.__proto__ = Buffer.prototype;
  27674. return arr
  27675. };
  27676. function from (that, value, encodingOrOffset, length) {
  27677. if (typeof value === 'number') {
  27678. throw new TypeError('"value" argument must not be a number')
  27679. }
  27680. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  27681. return fromArrayBuffer(that, value, encodingOrOffset, length)
  27682. }
  27683. if (typeof value === 'string') {
  27684. return fromString(that, value, encodingOrOffset)
  27685. }
  27686. return fromObject(that, value)
  27687. }
  27688. /**
  27689. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  27690. * if value is a number.
  27691. * Buffer.from(str[, encoding])
  27692. * Buffer.from(array)
  27693. * Buffer.from(buffer)
  27694. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  27695. **/
  27696. Buffer.from = function (value, encodingOrOffset, length) {
  27697. return from(null, value, encodingOrOffset, length)
  27698. };
  27699. if (Buffer.TYPED_ARRAY_SUPPORT) {
  27700. Buffer.prototype.__proto__ = Uint8Array.prototype;
  27701. Buffer.__proto__ = Uint8Array;
  27702. }
  27703. function assertSize (size) {
  27704. if (typeof size !== 'number') {
  27705. throw new TypeError('"size" argument must be a number')
  27706. } else if (size < 0) {
  27707. throw new RangeError('"size" argument must not be negative')
  27708. }
  27709. }
  27710. function alloc (that, size, fill, encoding) {
  27711. assertSize(size);
  27712. if (size <= 0) {
  27713. return createBuffer(that, size)
  27714. }
  27715. if (fill !== undefined) {
  27716. // Only pay attention to encoding if it's a string. This
  27717. // prevents accidentally sending in a number that would
  27718. // be interpretted as a start offset.
  27719. return typeof encoding === 'string'
  27720. ? createBuffer(that, size).fill(fill, encoding)
  27721. : createBuffer(that, size).fill(fill)
  27722. }
  27723. return createBuffer(that, size)
  27724. }
  27725. /**
  27726. * Creates a new filled Buffer instance.
  27727. * alloc(size[, fill[, encoding]])
  27728. **/
  27729. Buffer.alloc = function (size, fill, encoding) {
  27730. return alloc(null, size, fill, encoding)
  27731. };
  27732. function allocUnsafe (that, size) {
  27733. assertSize(size);
  27734. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  27735. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  27736. for (var i = 0; i < size; ++i) {
  27737. that[i] = 0;
  27738. }
  27739. }
  27740. return that
  27741. }
  27742. /**
  27743. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  27744. * */
  27745. Buffer.allocUnsafe = function (size) {
  27746. return allocUnsafe(null, size)
  27747. };
  27748. /**
  27749. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  27750. */
  27751. Buffer.allocUnsafeSlow = function (size) {
  27752. return allocUnsafe(null, size)
  27753. };
  27754. function fromString (that, string, encoding) {
  27755. if (typeof encoding !== 'string' || encoding === '') {
  27756. encoding = 'utf8';
  27757. }
  27758. if (!Buffer.isEncoding(encoding)) {
  27759. throw new TypeError('"encoding" must be a valid string encoding')
  27760. }
  27761. var length = byteLength(string, encoding) | 0;
  27762. that = createBuffer(that, length);
  27763. var actual = that.write(string, encoding);
  27764. if (actual !== length) {
  27765. // Writing a hex string, for example, that contains invalid characters will
  27766. // cause everything after the first invalid character to be ignored. (e.g.
  27767. // 'abxxcd' will be treated as 'ab')
  27768. that = that.slice(0, actual);
  27769. }
  27770. return that
  27771. }
  27772. function fromArrayLike (that, array) {
  27773. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  27774. that = createBuffer(that, length);
  27775. for (var i = 0; i < length; i += 1) {
  27776. that[i] = array[i] & 255;
  27777. }
  27778. return that
  27779. }
  27780. function fromArrayBuffer (that, array, byteOffset, length) {
  27781. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  27782. if (byteOffset < 0 || array.byteLength < byteOffset) {
  27783. throw new RangeError('\'offset\' is out of bounds')
  27784. }
  27785. if (array.byteLength < byteOffset + (length || 0)) {
  27786. throw new RangeError('\'length\' is out of bounds')
  27787. }
  27788. if (byteOffset === undefined && length === undefined) {
  27789. array = new Uint8Array(array);
  27790. } else if (length === undefined) {
  27791. array = new Uint8Array(array, byteOffset);
  27792. } else {
  27793. array = new Uint8Array(array, byteOffset, length);
  27794. }
  27795. if (Buffer.TYPED_ARRAY_SUPPORT) {
  27796. // Return an augmented `Uint8Array` instance, for best performance
  27797. that = array;
  27798. that.__proto__ = Buffer.prototype;
  27799. } else {
  27800. // Fallback: Return an object instance of the Buffer class
  27801. that = fromArrayLike(that, array);
  27802. }
  27803. return that
  27804. }
  27805. function fromObject (that, obj) {
  27806. if (internalIsBuffer(obj)) {
  27807. var len = checked(obj.length) | 0;
  27808. that = createBuffer(that, len);
  27809. if (that.length === 0) {
  27810. return that
  27811. }
  27812. obj.copy(that, 0, 0, len);
  27813. return that
  27814. }
  27815. if (obj) {
  27816. if ((typeof ArrayBuffer !== 'undefined' &&
  27817. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  27818. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  27819. return createBuffer(that, 0)
  27820. }
  27821. return fromArrayLike(that, obj)
  27822. }
  27823. if (obj.type === 'Buffer' && isArray$1(obj.data)) {
  27824. return fromArrayLike(that, obj.data)
  27825. }
  27826. }
  27827. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  27828. }
  27829. function checked (length) {
  27830. // Note: cannot use `length < kMaxLength()` here because that fails when
  27831. // length is NaN (which is otherwise coerced to zero.)
  27832. if (length >= kMaxLength()) {
  27833. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  27834. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  27835. }
  27836. return length | 0
  27837. }
  27838. Buffer.isBuffer = isBuffer;
  27839. function internalIsBuffer (b) {
  27840. return !!(b != null && b._isBuffer)
  27841. }
  27842. Buffer.compare = function compare (a, b) {
  27843. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  27844. throw new TypeError('Arguments must be Buffers')
  27845. }
  27846. if (a === b) return 0
  27847. var x = a.length;
  27848. var y = b.length;
  27849. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  27850. if (a[i] !== b[i]) {
  27851. x = a[i];
  27852. y = b[i];
  27853. break
  27854. }
  27855. }
  27856. if (x < y) return -1
  27857. if (y < x) return 1
  27858. return 0
  27859. };
  27860. Buffer.isEncoding = function isEncoding (encoding) {
  27861. switch (String(encoding).toLowerCase()) {
  27862. case 'hex':
  27863. case 'utf8':
  27864. case 'utf-8':
  27865. case 'ascii':
  27866. case 'latin1':
  27867. case 'binary':
  27868. case 'base64':
  27869. case 'ucs2':
  27870. case 'ucs-2':
  27871. case 'utf16le':
  27872. case 'utf-16le':
  27873. return true
  27874. default:
  27875. return false
  27876. }
  27877. };
  27878. Buffer.concat = function concat (list, length) {
  27879. if (!isArray$1(list)) {
  27880. throw new TypeError('"list" argument must be an Array of Buffers')
  27881. }
  27882. if (list.length === 0) {
  27883. return Buffer.alloc(0)
  27884. }
  27885. var i;
  27886. if (length === undefined) {
  27887. length = 0;
  27888. for (i = 0; i < list.length; ++i) {
  27889. length += list[i].length;
  27890. }
  27891. }
  27892. var buffer = Buffer.allocUnsafe(length);
  27893. var pos = 0;
  27894. for (i = 0; i < list.length; ++i) {
  27895. var buf = list[i];
  27896. if (!internalIsBuffer(buf)) {
  27897. throw new TypeError('"list" argument must be an Array of Buffers')
  27898. }
  27899. buf.copy(buffer, pos);
  27900. pos += buf.length;
  27901. }
  27902. return buffer
  27903. };
  27904. function byteLength (string, encoding) {
  27905. if (internalIsBuffer(string)) {
  27906. return string.length
  27907. }
  27908. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  27909. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  27910. return string.byteLength
  27911. }
  27912. if (typeof string !== 'string') {
  27913. string = '' + string;
  27914. }
  27915. var len = string.length;
  27916. if (len === 0) return 0
  27917. // Use a for loop to avoid recursion
  27918. var loweredCase = false;
  27919. for (;;) {
  27920. switch (encoding) {
  27921. case 'ascii':
  27922. case 'latin1':
  27923. case 'binary':
  27924. return len
  27925. case 'utf8':
  27926. case 'utf-8':
  27927. case undefined:
  27928. return utf8ToBytes(string).length
  27929. case 'ucs2':
  27930. case 'ucs-2':
  27931. case 'utf16le':
  27932. case 'utf-16le':
  27933. return len * 2
  27934. case 'hex':
  27935. return len >>> 1
  27936. case 'base64':
  27937. return base64ToBytes(string).length
  27938. default:
  27939. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  27940. encoding = ('' + encoding).toLowerCase();
  27941. loweredCase = true;
  27942. }
  27943. }
  27944. }
  27945. Buffer.byteLength = byteLength;
  27946. function slowToString (encoding, start, end) {
  27947. var loweredCase = false;
  27948. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  27949. // property of a typed array.
  27950. // This behaves neither like String nor Uint8Array in that we set start/end
  27951. // to their upper/lower bounds if the value passed is out of range.
  27952. // undefined is handled specially as per ECMA-262 6th Edition,
  27953. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  27954. if (start === undefined || start < 0) {
  27955. start = 0;
  27956. }
  27957. // Return early if start > this.length. Done here to prevent potential uint32
  27958. // coercion fail below.
  27959. if (start > this.length) {
  27960. return ''
  27961. }
  27962. if (end === undefined || end > this.length) {
  27963. end = this.length;
  27964. }
  27965. if (end <= 0) {
  27966. return ''
  27967. }
  27968. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  27969. end >>>= 0;
  27970. start >>>= 0;
  27971. if (end <= start) {
  27972. return ''
  27973. }
  27974. if (!encoding) encoding = 'utf8';
  27975. while (true) {
  27976. switch (encoding) {
  27977. case 'hex':
  27978. return hexSlice(this, start, end)
  27979. case 'utf8':
  27980. case 'utf-8':
  27981. return utf8Slice(this, start, end)
  27982. case 'ascii':
  27983. return asciiSlice(this, start, end)
  27984. case 'latin1':
  27985. case 'binary':
  27986. return latin1Slice(this, start, end)
  27987. case 'base64':
  27988. return base64Slice(this, start, end)
  27989. case 'ucs2':
  27990. case 'ucs-2':
  27991. case 'utf16le':
  27992. case 'utf-16le':
  27993. return utf16leSlice(this, start, end)
  27994. default:
  27995. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  27996. encoding = (encoding + '').toLowerCase();
  27997. loweredCase = true;
  27998. }
  27999. }
  28000. }
  28001. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  28002. // Buffer instances.
  28003. Buffer.prototype._isBuffer = true;
  28004. function swap$1 (b, n, m) {
  28005. var i = b[n];
  28006. b[n] = b[m];
  28007. b[m] = i;
  28008. }
  28009. Buffer.prototype.swap16 = function swap16 () {
  28010. var len = this.length;
  28011. if (len % 2 !== 0) {
  28012. throw new RangeError('Buffer size must be a multiple of 16-bits')
  28013. }
  28014. for (var i = 0; i < len; i += 2) {
  28015. swap$1(this, i, i + 1);
  28016. }
  28017. return this
  28018. };
  28019. Buffer.prototype.swap32 = function swap32 () {
  28020. var len = this.length;
  28021. if (len % 4 !== 0) {
  28022. throw new RangeError('Buffer size must be a multiple of 32-bits')
  28023. }
  28024. for (var i = 0; i < len; i += 4) {
  28025. swap$1(this, i, i + 3);
  28026. swap$1(this, i + 1, i + 2);
  28027. }
  28028. return this
  28029. };
  28030. Buffer.prototype.swap64 = function swap64 () {
  28031. var len = this.length;
  28032. if (len % 8 !== 0) {
  28033. throw new RangeError('Buffer size must be a multiple of 64-bits')
  28034. }
  28035. for (var i = 0; i < len; i += 8) {
  28036. swap$1(this, i, i + 7);
  28037. swap$1(this, i + 1, i + 6);
  28038. swap$1(this, i + 2, i + 5);
  28039. swap$1(this, i + 3, i + 4);
  28040. }
  28041. return this
  28042. };
  28043. Buffer.prototype.toString = function toString () {
  28044. var length = this.length | 0;
  28045. if (length === 0) return ''
  28046. if (arguments.length === 0) return utf8Slice(this, 0, length)
  28047. return slowToString.apply(this, arguments)
  28048. };
  28049. Buffer.prototype.equals = function equals (b) {
  28050. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  28051. if (this === b) return true
  28052. return Buffer.compare(this, b) === 0
  28053. };
  28054. Buffer.prototype.inspect = function inspect () {
  28055. var str = '';
  28056. var max = INSPECT_MAX_BYTES;
  28057. if (this.length > 0) {
  28058. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  28059. if (this.length > max) str += ' ... ';
  28060. }
  28061. return '<Buffer ' + str + '>'
  28062. };
  28063. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  28064. if (!internalIsBuffer(target)) {
  28065. throw new TypeError('Argument must be a Buffer')
  28066. }
  28067. if (start === undefined) {
  28068. start = 0;
  28069. }
  28070. if (end === undefined) {
  28071. end = target ? target.length : 0;
  28072. }
  28073. if (thisStart === undefined) {
  28074. thisStart = 0;
  28075. }
  28076. if (thisEnd === undefined) {
  28077. thisEnd = this.length;
  28078. }
  28079. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  28080. throw new RangeError('out of range index')
  28081. }
  28082. if (thisStart >= thisEnd && start >= end) {
  28083. return 0
  28084. }
  28085. if (thisStart >= thisEnd) {
  28086. return -1
  28087. }
  28088. if (start >= end) {
  28089. return 1
  28090. }
  28091. start >>>= 0;
  28092. end >>>= 0;
  28093. thisStart >>>= 0;
  28094. thisEnd >>>= 0;
  28095. if (this === target) return 0
  28096. var x = thisEnd - thisStart;
  28097. var y = end - start;
  28098. var len = Math.min(x, y);
  28099. var thisCopy = this.slice(thisStart, thisEnd);
  28100. var targetCopy = target.slice(start, end);
  28101. for (var i = 0; i < len; ++i) {
  28102. if (thisCopy[i] !== targetCopy[i]) {
  28103. x = thisCopy[i];
  28104. y = targetCopy[i];
  28105. break
  28106. }
  28107. }
  28108. if (x < y) return -1
  28109. if (y < x) return 1
  28110. return 0
  28111. };
  28112. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  28113. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  28114. //
  28115. // Arguments:
  28116. // - buffer - a Buffer to search
  28117. // - val - a string, Buffer, or number
  28118. // - byteOffset - an index into `buffer`; will be clamped to an int32
  28119. // - encoding - an optional encoding, relevant is val is a string
  28120. // - dir - true for indexOf, false for lastIndexOf
  28121. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  28122. // Empty buffer means no match
  28123. if (buffer.length === 0) return -1
  28124. // Normalize byteOffset
  28125. if (typeof byteOffset === 'string') {
  28126. encoding = byteOffset;
  28127. byteOffset = 0;
  28128. } else if (byteOffset > 0x7fffffff) {
  28129. byteOffset = 0x7fffffff;
  28130. } else if (byteOffset < -0x80000000) {
  28131. byteOffset = -0x80000000;
  28132. }
  28133. byteOffset = +byteOffset; // Coerce to Number.
  28134. if (isNaN(byteOffset)) {
  28135. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  28136. byteOffset = dir ? 0 : (buffer.length - 1);
  28137. }
  28138. // Normalize byteOffset: negative offsets start from the end of the buffer
  28139. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  28140. if (byteOffset >= buffer.length) {
  28141. if (dir) return -1
  28142. else byteOffset = buffer.length - 1;
  28143. } else if (byteOffset < 0) {
  28144. if (dir) byteOffset = 0;
  28145. else return -1
  28146. }
  28147. // Normalize val
  28148. if (typeof val === 'string') {
  28149. val = Buffer.from(val, encoding);
  28150. }
  28151. // Finally, search either indexOf (if dir is true) or lastIndexOf
  28152. if (internalIsBuffer(val)) {
  28153. // Special case: looking for empty string/buffer always fails
  28154. if (val.length === 0) {
  28155. return -1
  28156. }
  28157. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  28158. } else if (typeof val === 'number') {
  28159. val = val & 0xFF; // Search for a byte value [0-255]
  28160. if (Buffer.TYPED_ARRAY_SUPPORT &&
  28161. typeof Uint8Array.prototype.indexOf === 'function') {
  28162. if (dir) {
  28163. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  28164. } else {
  28165. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  28166. }
  28167. }
  28168. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  28169. }
  28170. throw new TypeError('val must be string, number or Buffer')
  28171. }
  28172. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  28173. var indexSize = 1;
  28174. var arrLength = arr.length;
  28175. var valLength = val.length;
  28176. if (encoding !== undefined) {
  28177. encoding = String(encoding).toLowerCase();
  28178. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  28179. encoding === 'utf16le' || encoding === 'utf-16le') {
  28180. if (arr.length < 2 || val.length < 2) {
  28181. return -1
  28182. }
  28183. indexSize = 2;
  28184. arrLength /= 2;
  28185. valLength /= 2;
  28186. byteOffset /= 2;
  28187. }
  28188. }
  28189. function read (buf, i) {
  28190. if (indexSize === 1) {
  28191. return buf[i]
  28192. } else {
  28193. return buf.readUInt16BE(i * indexSize)
  28194. }
  28195. }
  28196. var i;
  28197. if (dir) {
  28198. var foundIndex = -1;
  28199. for (i = byteOffset; i < arrLength; i++) {
  28200. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  28201. if (foundIndex === -1) foundIndex = i;
  28202. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  28203. } else {
  28204. if (foundIndex !== -1) i -= i - foundIndex;
  28205. foundIndex = -1;
  28206. }
  28207. }
  28208. } else {
  28209. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  28210. for (i = byteOffset; i >= 0; i--) {
  28211. var found = true;
  28212. for (var j = 0; j < valLength; j++) {
  28213. if (read(arr, i + j) !== read(val, j)) {
  28214. found = false;
  28215. break
  28216. }
  28217. }
  28218. if (found) return i
  28219. }
  28220. }
  28221. return -1
  28222. }
  28223. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  28224. return this.indexOf(val, byteOffset, encoding) !== -1
  28225. };
  28226. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  28227. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  28228. };
  28229. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  28230. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  28231. };
  28232. function hexWrite (buf, string, offset, length) {
  28233. offset = Number(offset) || 0;
  28234. var remaining = buf.length - offset;
  28235. if (!length) {
  28236. length = remaining;
  28237. } else {
  28238. length = Number(length);
  28239. if (length > remaining) {
  28240. length = remaining;
  28241. }
  28242. }
  28243. // must be an even number of digits
  28244. var strLen = string.length;
  28245. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  28246. if (length > strLen / 2) {
  28247. length = strLen / 2;
  28248. }
  28249. for (var i = 0; i < length; ++i) {
  28250. var parsed = parseInt(string.substr(i * 2, 2), 16);
  28251. if (isNaN(parsed)) return i
  28252. buf[offset + i] = parsed;
  28253. }
  28254. return i
  28255. }
  28256. function utf8Write (buf, string, offset, length) {
  28257. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  28258. }
  28259. function asciiWrite (buf, string, offset, length) {
  28260. return blitBuffer(asciiToBytes(string), buf, offset, length)
  28261. }
  28262. function latin1Write (buf, string, offset, length) {
  28263. return asciiWrite(buf, string, offset, length)
  28264. }
  28265. function base64Write (buf, string, offset, length) {
  28266. return blitBuffer(base64ToBytes(string), buf, offset, length)
  28267. }
  28268. function ucs2Write (buf, string, offset, length) {
  28269. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  28270. }
  28271. Buffer.prototype.write = function write (string, offset, length, encoding) {
  28272. // Buffer#write(string)
  28273. if (offset === undefined) {
  28274. encoding = 'utf8';
  28275. length = this.length;
  28276. offset = 0;
  28277. // Buffer#write(string, encoding)
  28278. } else if (length === undefined && typeof offset === 'string') {
  28279. encoding = offset;
  28280. length = this.length;
  28281. offset = 0;
  28282. // Buffer#write(string, offset[, length][, encoding])
  28283. } else if (isFinite(offset)) {
  28284. offset = offset | 0;
  28285. if (isFinite(length)) {
  28286. length = length | 0;
  28287. if (encoding === undefined) encoding = 'utf8';
  28288. } else {
  28289. encoding = length;
  28290. length = undefined;
  28291. }
  28292. // legacy write(string, encoding, offset, length) - remove in v0.13
  28293. } else {
  28294. throw new Error(
  28295. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  28296. )
  28297. }
  28298. var remaining = this.length - offset;
  28299. if (length === undefined || length > remaining) length = remaining;
  28300. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  28301. throw new RangeError('Attempt to write outside buffer bounds')
  28302. }
  28303. if (!encoding) encoding = 'utf8';
  28304. var loweredCase = false;
  28305. for (;;) {
  28306. switch (encoding) {
  28307. case 'hex':
  28308. return hexWrite(this, string, offset, length)
  28309. case 'utf8':
  28310. case 'utf-8':
  28311. return utf8Write(this, string, offset, length)
  28312. case 'ascii':
  28313. return asciiWrite(this, string, offset, length)
  28314. case 'latin1':
  28315. case 'binary':
  28316. return latin1Write(this, string, offset, length)
  28317. case 'base64':
  28318. // Warning: maxLength not taken into account in base64Write
  28319. return base64Write(this, string, offset, length)
  28320. case 'ucs2':
  28321. case 'ucs-2':
  28322. case 'utf16le':
  28323. case 'utf-16le':
  28324. return ucs2Write(this, string, offset, length)
  28325. default:
  28326. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  28327. encoding = ('' + encoding).toLowerCase();
  28328. loweredCase = true;
  28329. }
  28330. }
  28331. };
  28332. Buffer.prototype.toJSON = function toJSON () {
  28333. return {
  28334. type: 'Buffer',
  28335. data: Array.prototype.slice.call(this._arr || this, 0)
  28336. }
  28337. };
  28338. function base64Slice (buf, start, end) {
  28339. if (start === 0 && end === buf.length) {
  28340. return fromByteArray(buf)
  28341. } else {
  28342. return fromByteArray(buf.slice(start, end))
  28343. }
  28344. }
  28345. function utf8Slice (buf, start, end) {
  28346. end = Math.min(buf.length, end);
  28347. var res = [];
  28348. var i = start;
  28349. while (i < end) {
  28350. var firstByte = buf[i];
  28351. var codePoint = null;
  28352. var bytesPerSequence = (firstByte > 0xEF) ? 4
  28353. : (firstByte > 0xDF) ? 3
  28354. : (firstByte > 0xBF) ? 2
  28355. : 1;
  28356. if (i + bytesPerSequence <= end) {
  28357. var secondByte, thirdByte, fourthByte, tempCodePoint;
  28358. switch (bytesPerSequence) {
  28359. case 1:
  28360. if (firstByte < 0x80) {
  28361. codePoint = firstByte;
  28362. }
  28363. break
  28364. case 2:
  28365. secondByte = buf[i + 1];
  28366. if ((secondByte & 0xC0) === 0x80) {
  28367. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  28368. if (tempCodePoint > 0x7F) {
  28369. codePoint = tempCodePoint;
  28370. }
  28371. }
  28372. break
  28373. case 3:
  28374. secondByte = buf[i + 1];
  28375. thirdByte = buf[i + 2];
  28376. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  28377. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  28378. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  28379. codePoint = tempCodePoint;
  28380. }
  28381. }
  28382. break
  28383. case 4:
  28384. secondByte = buf[i + 1];
  28385. thirdByte = buf[i + 2];
  28386. fourthByte = buf[i + 3];
  28387. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  28388. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  28389. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  28390. codePoint = tempCodePoint;
  28391. }
  28392. }
  28393. }
  28394. }
  28395. if (codePoint === null) {
  28396. // we did not generate a valid codePoint so insert a
  28397. // replacement char (U+FFFD) and advance only 1 byte
  28398. codePoint = 0xFFFD;
  28399. bytesPerSequence = 1;
  28400. } else if (codePoint > 0xFFFF) {
  28401. // encode to utf16 (surrogate pair dance)
  28402. codePoint -= 0x10000;
  28403. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  28404. codePoint = 0xDC00 | codePoint & 0x3FF;
  28405. }
  28406. res.push(codePoint);
  28407. i += bytesPerSequence;
  28408. }
  28409. return decodeCodePointsArray(res)
  28410. }
  28411. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  28412. // the lowest limit is Chrome, with 0x10000 args.
  28413. // We go 1 magnitude less, for safety
  28414. var MAX_ARGUMENTS_LENGTH = 0x1000;
  28415. function decodeCodePointsArray (codePoints) {
  28416. var len = codePoints.length;
  28417. if (len <= MAX_ARGUMENTS_LENGTH) {
  28418. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  28419. }
  28420. // Decode in chunks to avoid "call stack size exceeded".
  28421. var res = '';
  28422. var i = 0;
  28423. while (i < len) {
  28424. res += String.fromCharCode.apply(
  28425. String,
  28426. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  28427. );
  28428. }
  28429. return res
  28430. }
  28431. function asciiSlice (buf, start, end) {
  28432. var ret = '';
  28433. end = Math.min(buf.length, end);
  28434. for (var i = start; i < end; ++i) {
  28435. ret += String.fromCharCode(buf[i] & 0x7F);
  28436. }
  28437. return ret
  28438. }
  28439. function latin1Slice (buf, start, end) {
  28440. var ret = '';
  28441. end = Math.min(buf.length, end);
  28442. for (var i = start; i < end; ++i) {
  28443. ret += String.fromCharCode(buf[i]);
  28444. }
  28445. return ret
  28446. }
  28447. function hexSlice (buf, start, end) {
  28448. var len = buf.length;
  28449. if (!start || start < 0) start = 0;
  28450. if (!end || end < 0 || end > len) end = len;
  28451. var out = '';
  28452. for (var i = start; i < end; ++i) {
  28453. out += toHex(buf[i]);
  28454. }
  28455. return out
  28456. }
  28457. function utf16leSlice (buf, start, end) {
  28458. var bytes = buf.slice(start, end);
  28459. var res = '';
  28460. for (var i = 0; i < bytes.length; i += 2) {
  28461. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  28462. }
  28463. return res
  28464. }
  28465. Buffer.prototype.slice = function slice (start, end) {
  28466. var len = this.length;
  28467. start = ~~start;
  28468. end = end === undefined ? len : ~~end;
  28469. if (start < 0) {
  28470. start += len;
  28471. if (start < 0) start = 0;
  28472. } else if (start > len) {
  28473. start = len;
  28474. }
  28475. if (end < 0) {
  28476. end += len;
  28477. if (end < 0) end = 0;
  28478. } else if (end > len) {
  28479. end = len;
  28480. }
  28481. if (end < start) end = start;
  28482. var newBuf;
  28483. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28484. newBuf = this.subarray(start, end);
  28485. newBuf.__proto__ = Buffer.prototype;
  28486. } else {
  28487. var sliceLen = end - start;
  28488. newBuf = new Buffer(sliceLen, undefined);
  28489. for (var i = 0; i < sliceLen; ++i) {
  28490. newBuf[i] = this[i + start];
  28491. }
  28492. }
  28493. return newBuf
  28494. };
  28495. /*
  28496. * Need to make sure that buffer isn't trying to write out of bounds.
  28497. */
  28498. function checkOffset (offset, ext, length) {
  28499. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  28500. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  28501. }
  28502. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  28503. offset = offset | 0;
  28504. byteLength = byteLength | 0;
  28505. if (!noAssert) checkOffset(offset, byteLength, this.length);
  28506. var val = this[offset];
  28507. var mul = 1;
  28508. var i = 0;
  28509. while (++i < byteLength && (mul *= 0x100)) {
  28510. val += this[offset + i] * mul;
  28511. }
  28512. return val
  28513. };
  28514. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  28515. offset = offset | 0;
  28516. byteLength = byteLength | 0;
  28517. if (!noAssert) {
  28518. checkOffset(offset, byteLength, this.length);
  28519. }
  28520. var val = this[offset + --byteLength];
  28521. var mul = 1;
  28522. while (byteLength > 0 && (mul *= 0x100)) {
  28523. val += this[offset + --byteLength] * mul;
  28524. }
  28525. return val
  28526. };
  28527. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  28528. if (!noAssert) checkOffset(offset, 1, this.length);
  28529. return this[offset]
  28530. };
  28531. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  28532. if (!noAssert) checkOffset(offset, 2, this.length);
  28533. return this[offset] | (this[offset + 1] << 8)
  28534. };
  28535. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  28536. if (!noAssert) checkOffset(offset, 2, this.length);
  28537. return (this[offset] << 8) | this[offset + 1]
  28538. };
  28539. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  28540. if (!noAssert) checkOffset(offset, 4, this.length);
  28541. return ((this[offset]) |
  28542. (this[offset + 1] << 8) |
  28543. (this[offset + 2] << 16)) +
  28544. (this[offset + 3] * 0x1000000)
  28545. };
  28546. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  28547. if (!noAssert) checkOffset(offset, 4, this.length);
  28548. return (this[offset] * 0x1000000) +
  28549. ((this[offset + 1] << 16) |
  28550. (this[offset + 2] << 8) |
  28551. this[offset + 3])
  28552. };
  28553. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  28554. offset = offset | 0;
  28555. byteLength = byteLength | 0;
  28556. if (!noAssert) checkOffset(offset, byteLength, this.length);
  28557. var val = this[offset];
  28558. var mul = 1;
  28559. var i = 0;
  28560. while (++i < byteLength && (mul *= 0x100)) {
  28561. val += this[offset + i] * mul;
  28562. }
  28563. mul *= 0x80;
  28564. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  28565. return val
  28566. };
  28567. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  28568. offset = offset | 0;
  28569. byteLength = byteLength | 0;
  28570. if (!noAssert) checkOffset(offset, byteLength, this.length);
  28571. var i = byteLength;
  28572. var mul = 1;
  28573. var val = this[offset + --i];
  28574. while (i > 0 && (mul *= 0x100)) {
  28575. val += this[offset + --i] * mul;
  28576. }
  28577. mul *= 0x80;
  28578. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  28579. return val
  28580. };
  28581. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  28582. if (!noAssert) checkOffset(offset, 1, this.length);
  28583. if (!(this[offset] & 0x80)) return (this[offset])
  28584. return ((0xff - this[offset] + 1) * -1)
  28585. };
  28586. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  28587. if (!noAssert) checkOffset(offset, 2, this.length);
  28588. var val = this[offset] | (this[offset + 1] << 8);
  28589. return (val & 0x8000) ? val | 0xFFFF0000 : val
  28590. };
  28591. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  28592. if (!noAssert) checkOffset(offset, 2, this.length);
  28593. var val = this[offset + 1] | (this[offset] << 8);
  28594. return (val & 0x8000) ? val | 0xFFFF0000 : val
  28595. };
  28596. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  28597. if (!noAssert) checkOffset(offset, 4, this.length);
  28598. return (this[offset]) |
  28599. (this[offset + 1] << 8) |
  28600. (this[offset + 2] << 16) |
  28601. (this[offset + 3] << 24)
  28602. };
  28603. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  28604. if (!noAssert) checkOffset(offset, 4, this.length);
  28605. return (this[offset] << 24) |
  28606. (this[offset + 1] << 16) |
  28607. (this[offset + 2] << 8) |
  28608. (this[offset + 3])
  28609. };
  28610. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  28611. if (!noAssert) checkOffset(offset, 4, this.length);
  28612. return read(this, offset, true, 23, 4)
  28613. };
  28614. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  28615. if (!noAssert) checkOffset(offset, 4, this.length);
  28616. return read(this, offset, false, 23, 4)
  28617. };
  28618. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  28619. if (!noAssert) checkOffset(offset, 8, this.length);
  28620. return read(this, offset, true, 52, 8)
  28621. };
  28622. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  28623. if (!noAssert) checkOffset(offset, 8, this.length);
  28624. return read(this, offset, false, 52, 8)
  28625. };
  28626. function checkInt (buf, value, offset, ext, max, min) {
  28627. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  28628. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  28629. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  28630. }
  28631. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  28632. value = +value;
  28633. offset = offset | 0;
  28634. byteLength = byteLength | 0;
  28635. if (!noAssert) {
  28636. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  28637. checkInt(this, value, offset, byteLength, maxBytes, 0);
  28638. }
  28639. var mul = 1;
  28640. var i = 0;
  28641. this[offset] = value & 0xFF;
  28642. while (++i < byteLength && (mul *= 0x100)) {
  28643. this[offset + i] = (value / mul) & 0xFF;
  28644. }
  28645. return offset + byteLength
  28646. };
  28647. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  28648. value = +value;
  28649. offset = offset | 0;
  28650. byteLength = byteLength | 0;
  28651. if (!noAssert) {
  28652. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  28653. checkInt(this, value, offset, byteLength, maxBytes, 0);
  28654. }
  28655. var i = byteLength - 1;
  28656. var mul = 1;
  28657. this[offset + i] = value & 0xFF;
  28658. while (--i >= 0 && (mul *= 0x100)) {
  28659. this[offset + i] = (value / mul) & 0xFF;
  28660. }
  28661. return offset + byteLength
  28662. };
  28663. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  28664. value = +value;
  28665. offset = offset | 0;
  28666. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  28667. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  28668. this[offset] = (value & 0xff);
  28669. return offset + 1
  28670. };
  28671. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  28672. if (value < 0) value = 0xffff + value + 1;
  28673. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  28674. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  28675. (littleEndian ? i : 1 - i) * 8;
  28676. }
  28677. }
  28678. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  28679. value = +value;
  28680. offset = offset | 0;
  28681. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  28682. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28683. this[offset] = (value & 0xff);
  28684. this[offset + 1] = (value >>> 8);
  28685. } else {
  28686. objectWriteUInt16(this, value, offset, true);
  28687. }
  28688. return offset + 2
  28689. };
  28690. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  28691. value = +value;
  28692. offset = offset | 0;
  28693. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  28694. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28695. this[offset] = (value >>> 8);
  28696. this[offset + 1] = (value & 0xff);
  28697. } else {
  28698. objectWriteUInt16(this, value, offset, false);
  28699. }
  28700. return offset + 2
  28701. };
  28702. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  28703. if (value < 0) value = 0xffffffff + value + 1;
  28704. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  28705. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  28706. }
  28707. }
  28708. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  28709. value = +value;
  28710. offset = offset | 0;
  28711. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  28712. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28713. this[offset + 3] = (value >>> 24);
  28714. this[offset + 2] = (value >>> 16);
  28715. this[offset + 1] = (value >>> 8);
  28716. this[offset] = (value & 0xff);
  28717. } else {
  28718. objectWriteUInt32(this, value, offset, true);
  28719. }
  28720. return offset + 4
  28721. };
  28722. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  28723. value = +value;
  28724. offset = offset | 0;
  28725. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  28726. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28727. this[offset] = (value >>> 24);
  28728. this[offset + 1] = (value >>> 16);
  28729. this[offset + 2] = (value >>> 8);
  28730. this[offset + 3] = (value & 0xff);
  28731. } else {
  28732. objectWriteUInt32(this, value, offset, false);
  28733. }
  28734. return offset + 4
  28735. };
  28736. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  28737. value = +value;
  28738. offset = offset | 0;
  28739. if (!noAssert) {
  28740. var limit = Math.pow(2, 8 * byteLength - 1);
  28741. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  28742. }
  28743. var i = 0;
  28744. var mul = 1;
  28745. var sub = 0;
  28746. this[offset] = value & 0xFF;
  28747. while (++i < byteLength && (mul *= 0x100)) {
  28748. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  28749. sub = 1;
  28750. }
  28751. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  28752. }
  28753. return offset + byteLength
  28754. };
  28755. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  28756. value = +value;
  28757. offset = offset | 0;
  28758. if (!noAssert) {
  28759. var limit = Math.pow(2, 8 * byteLength - 1);
  28760. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  28761. }
  28762. var i = byteLength - 1;
  28763. var mul = 1;
  28764. var sub = 0;
  28765. this[offset + i] = value & 0xFF;
  28766. while (--i >= 0 && (mul *= 0x100)) {
  28767. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  28768. sub = 1;
  28769. }
  28770. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  28771. }
  28772. return offset + byteLength
  28773. };
  28774. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  28775. value = +value;
  28776. offset = offset | 0;
  28777. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  28778. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  28779. if (value < 0) value = 0xff + value + 1;
  28780. this[offset] = (value & 0xff);
  28781. return offset + 1
  28782. };
  28783. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  28784. value = +value;
  28785. offset = offset | 0;
  28786. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  28787. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28788. this[offset] = (value & 0xff);
  28789. this[offset + 1] = (value >>> 8);
  28790. } else {
  28791. objectWriteUInt16(this, value, offset, true);
  28792. }
  28793. return offset + 2
  28794. };
  28795. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  28796. value = +value;
  28797. offset = offset | 0;
  28798. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  28799. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28800. this[offset] = (value >>> 8);
  28801. this[offset + 1] = (value & 0xff);
  28802. } else {
  28803. objectWriteUInt16(this, value, offset, false);
  28804. }
  28805. return offset + 2
  28806. };
  28807. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  28808. value = +value;
  28809. offset = offset | 0;
  28810. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  28811. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28812. this[offset] = (value & 0xff);
  28813. this[offset + 1] = (value >>> 8);
  28814. this[offset + 2] = (value >>> 16);
  28815. this[offset + 3] = (value >>> 24);
  28816. } else {
  28817. objectWriteUInt32(this, value, offset, true);
  28818. }
  28819. return offset + 4
  28820. };
  28821. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  28822. value = +value;
  28823. offset = offset | 0;
  28824. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  28825. if (value < 0) value = 0xffffffff + value + 1;
  28826. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28827. this[offset] = (value >>> 24);
  28828. this[offset + 1] = (value >>> 16);
  28829. this[offset + 2] = (value >>> 8);
  28830. this[offset + 3] = (value & 0xff);
  28831. } else {
  28832. objectWriteUInt32(this, value, offset, false);
  28833. }
  28834. return offset + 4
  28835. };
  28836. function checkIEEE754 (buf, value, offset, ext, max, min) {
  28837. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  28838. if (offset < 0) throw new RangeError('Index out of range')
  28839. }
  28840. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  28841. if (!noAssert) {
  28842. checkIEEE754(buf, value, offset, 4);
  28843. }
  28844. write(buf, value, offset, littleEndian, 23, 4);
  28845. return offset + 4
  28846. }
  28847. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  28848. return writeFloat(this, value, offset, true, noAssert)
  28849. };
  28850. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  28851. return writeFloat(this, value, offset, false, noAssert)
  28852. };
  28853. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  28854. if (!noAssert) {
  28855. checkIEEE754(buf, value, offset, 8);
  28856. }
  28857. write(buf, value, offset, littleEndian, 52, 8);
  28858. return offset + 8
  28859. }
  28860. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  28861. return writeDouble(this, value, offset, true, noAssert)
  28862. };
  28863. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  28864. return writeDouble(this, value, offset, false, noAssert)
  28865. };
  28866. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  28867. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  28868. if (!start) start = 0;
  28869. if (!end && end !== 0) end = this.length;
  28870. if (targetStart >= target.length) targetStart = target.length;
  28871. if (!targetStart) targetStart = 0;
  28872. if (end > 0 && end < start) end = start;
  28873. // Copy 0 bytes; we're done
  28874. if (end === start) return 0
  28875. if (target.length === 0 || this.length === 0) return 0
  28876. // Fatal error conditions
  28877. if (targetStart < 0) {
  28878. throw new RangeError('targetStart out of bounds')
  28879. }
  28880. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  28881. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  28882. // Are we oob?
  28883. if (end > this.length) end = this.length;
  28884. if (target.length - targetStart < end - start) {
  28885. end = target.length - targetStart + start;
  28886. }
  28887. var len = end - start;
  28888. var i;
  28889. if (this === target && start < targetStart && targetStart < end) {
  28890. // descending copy from end
  28891. for (i = len - 1; i >= 0; --i) {
  28892. target[i + targetStart] = this[i + start];
  28893. }
  28894. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  28895. // ascending copy from start
  28896. for (i = 0; i < len; ++i) {
  28897. target[i + targetStart] = this[i + start];
  28898. }
  28899. } else {
  28900. Uint8Array.prototype.set.call(
  28901. target,
  28902. this.subarray(start, start + len),
  28903. targetStart
  28904. );
  28905. }
  28906. return len
  28907. };
  28908. // Usage:
  28909. // buffer.fill(number[, offset[, end]])
  28910. // buffer.fill(buffer[, offset[, end]])
  28911. // buffer.fill(string[, offset[, end]][, encoding])
  28912. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  28913. // Handle string cases:
  28914. if (typeof val === 'string') {
  28915. if (typeof start === 'string') {
  28916. encoding = start;
  28917. start = 0;
  28918. end = this.length;
  28919. } else if (typeof end === 'string') {
  28920. encoding = end;
  28921. end = this.length;
  28922. }
  28923. if (val.length === 1) {
  28924. var code = val.charCodeAt(0);
  28925. if (code < 256) {
  28926. val = code;
  28927. }
  28928. }
  28929. if (encoding !== undefined && typeof encoding !== 'string') {
  28930. throw new TypeError('encoding must be a string')
  28931. }
  28932. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  28933. throw new TypeError('Unknown encoding: ' + encoding)
  28934. }
  28935. } else if (typeof val === 'number') {
  28936. val = val & 255;
  28937. }
  28938. // Invalid ranges are not set to a default, so can range check early.
  28939. if (start < 0 || this.length < start || this.length < end) {
  28940. throw new RangeError('Out of range index')
  28941. }
  28942. if (end <= start) {
  28943. return this
  28944. }
  28945. start = start >>> 0;
  28946. end = end === undefined ? this.length : end >>> 0;
  28947. if (!val) val = 0;
  28948. var i;
  28949. if (typeof val === 'number') {
  28950. for (i = start; i < end; ++i) {
  28951. this[i] = val;
  28952. }
  28953. } else {
  28954. var bytes = internalIsBuffer(val)
  28955. ? val
  28956. : utf8ToBytes(new Buffer(val, encoding).toString());
  28957. var len = bytes.length;
  28958. for (i = 0; i < end - start; ++i) {
  28959. this[i + start] = bytes[i % len];
  28960. }
  28961. }
  28962. return this
  28963. };
  28964. // HELPER FUNCTIONS
  28965. // ================
  28966. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  28967. function base64clean (str) {
  28968. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  28969. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  28970. // Node converts strings with length < 2 to ''
  28971. if (str.length < 2) return ''
  28972. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  28973. while (str.length % 4 !== 0) {
  28974. str = str + '=';
  28975. }
  28976. return str
  28977. }
  28978. function stringtrim (str) {
  28979. if (str.trim) return str.trim()
  28980. return str.replace(/^\s+|\s+$/g, '')
  28981. }
  28982. function toHex (n) {
  28983. if (n < 16) return '0' + n.toString(16)
  28984. return n.toString(16)
  28985. }
  28986. function utf8ToBytes (string, units) {
  28987. units = units || Infinity;
  28988. var codePoint;
  28989. var length = string.length;
  28990. var leadSurrogate = null;
  28991. var bytes = [];
  28992. for (var i = 0; i < length; ++i) {
  28993. codePoint = string.charCodeAt(i);
  28994. // is surrogate component
  28995. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  28996. // last char was a lead
  28997. if (!leadSurrogate) {
  28998. // no lead yet
  28999. if (codePoint > 0xDBFF) {
  29000. // unexpected trail
  29001. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  29002. continue
  29003. } else if (i + 1 === length) {
  29004. // unpaired lead
  29005. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  29006. continue
  29007. }
  29008. // valid lead
  29009. leadSurrogate = codePoint;
  29010. continue
  29011. }
  29012. // 2 leads in a row
  29013. if (codePoint < 0xDC00) {
  29014. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  29015. leadSurrogate = codePoint;
  29016. continue
  29017. }
  29018. // valid surrogate pair
  29019. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  29020. } else if (leadSurrogate) {
  29021. // valid bmp char, but last char was a lead
  29022. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  29023. }
  29024. leadSurrogate = null;
  29025. // encode utf8
  29026. if (codePoint < 0x80) {
  29027. if ((units -= 1) < 0) break
  29028. bytes.push(codePoint);
  29029. } else if (codePoint < 0x800) {
  29030. if ((units -= 2) < 0) break
  29031. bytes.push(
  29032. codePoint >> 0x6 | 0xC0,
  29033. codePoint & 0x3F | 0x80
  29034. );
  29035. } else if (codePoint < 0x10000) {
  29036. if ((units -= 3) < 0) break
  29037. bytes.push(
  29038. codePoint >> 0xC | 0xE0,
  29039. codePoint >> 0x6 & 0x3F | 0x80,
  29040. codePoint & 0x3F | 0x80
  29041. );
  29042. } else if (codePoint < 0x110000) {
  29043. if ((units -= 4) < 0) break
  29044. bytes.push(
  29045. codePoint >> 0x12 | 0xF0,
  29046. codePoint >> 0xC & 0x3F | 0x80,
  29047. codePoint >> 0x6 & 0x3F | 0x80,
  29048. codePoint & 0x3F | 0x80
  29049. );
  29050. } else {
  29051. throw new Error('Invalid code point')
  29052. }
  29053. }
  29054. return bytes
  29055. }
  29056. function asciiToBytes (str) {
  29057. var byteArray = [];
  29058. for (var i = 0; i < str.length; ++i) {
  29059. // Node's code seems to be doing this and not & 0x7F..
  29060. byteArray.push(str.charCodeAt(i) & 0xFF);
  29061. }
  29062. return byteArray
  29063. }
  29064. function utf16leToBytes (str, units) {
  29065. var c, hi, lo;
  29066. var byteArray = [];
  29067. for (var i = 0; i < str.length; ++i) {
  29068. if ((units -= 2) < 0) break
  29069. c = str.charCodeAt(i);
  29070. hi = c >> 8;
  29071. lo = c % 256;
  29072. byteArray.push(lo);
  29073. byteArray.push(hi);
  29074. }
  29075. return byteArray
  29076. }
  29077. function base64ToBytes (str) {
  29078. return toByteArray(base64clean(str))
  29079. }
  29080. function blitBuffer (src, dst, offset, length) {
  29081. for (var i = 0; i < length; ++i) {
  29082. if ((i + offset >= dst.length) || (i >= src.length)) break
  29083. dst[i + offset] = src[i];
  29084. }
  29085. return i
  29086. }
  29087. function isnan (val) {
  29088. return val !== val // eslint-disable-line no-self-compare
  29089. }
  29090. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  29091. // The _isBuffer check is for Safari 5-7 support, because it's missing
  29092. // Object.prototype.constructor. Remove this eventually
  29093. function isBuffer(obj) {
  29094. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  29095. }
  29096. function isFastBuffer (obj) {
  29097. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  29098. }
  29099. // For Node v0.10 support. Remove this eventually.
  29100. function isSlowBuffer (obj) {
  29101. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  29102. }
  29103. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  29104. function encode$2(decoded) {
  29105. var sourceFileIndex = 0; // second field
  29106. var sourceCodeLine = 0; // third field
  29107. var sourceCodeColumn = 0; // fourth field
  29108. var nameIndex = 0; // fifth field
  29109. var mappings = '';
  29110. for (var i = 0; i < decoded.length; i++) {
  29111. var line = decoded[i];
  29112. if (i > 0)
  29113. mappings += ';';
  29114. if (line.length === 0)
  29115. continue;
  29116. var generatedCodeColumn = 0; // first field
  29117. var lineMappings = [];
  29118. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  29119. var segment = line_1[_i];
  29120. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  29121. generatedCodeColumn = segment[0];
  29122. if (segment.length > 1) {
  29123. segmentMappings +=
  29124. encodeInteger(segment[1] - sourceFileIndex) +
  29125. encodeInteger(segment[2] - sourceCodeLine) +
  29126. encodeInteger(segment[3] - sourceCodeColumn);
  29127. sourceFileIndex = segment[1];
  29128. sourceCodeLine = segment[2];
  29129. sourceCodeColumn = segment[3];
  29130. }
  29131. if (segment.length === 5) {
  29132. segmentMappings += encodeInteger(segment[4] - nameIndex);
  29133. nameIndex = segment[4];
  29134. }
  29135. lineMappings.push(segmentMappings);
  29136. }
  29137. mappings += lineMappings.join(',');
  29138. }
  29139. return mappings;
  29140. }
  29141. function encodeInteger(num) {
  29142. var result = '';
  29143. num = num < 0 ? (-num << 1) | 1 : num << 1;
  29144. do {
  29145. var clamped = num & 31;
  29146. num >>>= 5;
  29147. if (num > 0) {
  29148. clamped |= 32;
  29149. }
  29150. result += chars[clamped];
  29151. } while (num > 0);
  29152. return result;
  29153. }
  29154. var BitSet = function BitSet(arg) {
  29155. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  29156. };
  29157. BitSet.prototype.add = function add (n) {
  29158. this.bits[n >> 5] |= 1 << (n & 31);
  29159. };
  29160. BitSet.prototype.has = function has (n) {
  29161. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  29162. };
  29163. var Chunk = function Chunk(start, end, content) {
  29164. this.start = start;
  29165. this.end = end;
  29166. this.original = content;
  29167. this.intro = '';
  29168. this.outro = '';
  29169. this.content = content;
  29170. this.storeName = false;
  29171. this.edited = false;
  29172. // we make these non-enumerable, for sanity while debugging
  29173. Object.defineProperties(this, {
  29174. previous: { writable: true, value: null },
  29175. next: { writable: true, value: null }
  29176. });
  29177. };
  29178. Chunk.prototype.appendLeft = function appendLeft (content) {
  29179. this.outro += content;
  29180. };
  29181. Chunk.prototype.appendRight = function appendRight (content) {
  29182. this.intro = this.intro + content;
  29183. };
  29184. Chunk.prototype.clone = function clone () {
  29185. var chunk = new Chunk(this.start, this.end, this.original);
  29186. chunk.intro = this.intro;
  29187. chunk.outro = this.outro;
  29188. chunk.content = this.content;
  29189. chunk.storeName = this.storeName;
  29190. chunk.edited = this.edited;
  29191. return chunk;
  29192. };
  29193. Chunk.prototype.contains = function contains (index) {
  29194. return this.start < index && index < this.end;
  29195. };
  29196. Chunk.prototype.eachNext = function eachNext (fn) {
  29197. var chunk = this;
  29198. while (chunk) {
  29199. fn(chunk);
  29200. chunk = chunk.next;
  29201. }
  29202. };
  29203. Chunk.prototype.eachPrevious = function eachPrevious (fn) {
  29204. var chunk = this;
  29205. while (chunk) {
  29206. fn(chunk);
  29207. chunk = chunk.previous;
  29208. }
  29209. };
  29210. Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
  29211. this.content = content;
  29212. if (!contentOnly) {
  29213. this.intro = '';
  29214. this.outro = '';
  29215. }
  29216. this.storeName = storeName;
  29217. this.edited = true;
  29218. return this;
  29219. };
  29220. Chunk.prototype.prependLeft = function prependLeft (content) {
  29221. this.outro = content + this.outro;
  29222. };
  29223. Chunk.prototype.prependRight = function prependRight (content) {
  29224. this.intro = content + this.intro;
  29225. };
  29226. Chunk.prototype.split = function split (index) {
  29227. var sliceIndex = index - this.start;
  29228. var originalBefore = this.original.slice(0, sliceIndex);
  29229. var originalAfter = this.original.slice(sliceIndex);
  29230. this.original = originalBefore;
  29231. var newChunk = new Chunk(index, this.end, originalAfter);
  29232. newChunk.outro = this.outro;
  29233. this.outro = '';
  29234. this.end = index;
  29235. if (this.edited) {
  29236. // TODO is this block necessary?...
  29237. newChunk.edit('', false);
  29238. this.content = '';
  29239. } else {
  29240. this.content = originalBefore;
  29241. }
  29242. newChunk.next = this.next;
  29243. if (newChunk.next) { newChunk.next.previous = newChunk; }
  29244. newChunk.previous = this;
  29245. this.next = newChunk;
  29246. return newChunk;
  29247. };
  29248. Chunk.prototype.toString = function toString () {
  29249. return this.intro + this.content + this.outro;
  29250. };
  29251. Chunk.prototype.trimEnd = function trimEnd (rx) {
  29252. this.outro = this.outro.replace(rx, '');
  29253. if (this.outro.length) { return true; }
  29254. var trimmed = this.content.replace(rx, '');
  29255. if (trimmed.length) {
  29256. if (trimmed !== this.content) {
  29257. this.split(this.start + trimmed.length).edit('', undefined, true);
  29258. }
  29259. return true;
  29260. } else {
  29261. this.edit('', undefined, true);
  29262. this.intro = this.intro.replace(rx, '');
  29263. if (this.intro.length) { return true; }
  29264. }
  29265. };
  29266. Chunk.prototype.trimStart = function trimStart (rx) {
  29267. this.intro = this.intro.replace(rx, '');
  29268. if (this.intro.length) { return true; }
  29269. var trimmed = this.content.replace(rx, '');
  29270. if (trimmed.length) {
  29271. if (trimmed !== this.content) {
  29272. this.split(this.end - trimmed.length);
  29273. this.edit('', undefined, true);
  29274. }
  29275. return true;
  29276. } else {
  29277. this.edit('', undefined, true);
  29278. this.outro = this.outro.replace(rx, '');
  29279. if (this.outro.length) { return true; }
  29280. }
  29281. };
  29282. var btoa = function () {
  29283. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  29284. };
  29285. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  29286. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  29287. } else if (typeof Buffer === 'function') {
  29288. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  29289. }
  29290. var SourceMap = function SourceMap(properties) {
  29291. this.version = 3;
  29292. this.file = properties.file;
  29293. this.sources = properties.sources;
  29294. this.sourcesContent = properties.sourcesContent;
  29295. this.names = properties.names;
  29296. this.mappings = encode$2(properties.mappings);
  29297. };
  29298. SourceMap.prototype.toString = function toString () {
  29299. return JSON.stringify(this);
  29300. };
  29301. SourceMap.prototype.toUrl = function toUrl () {
  29302. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  29303. };
  29304. function guessIndent(code) {
  29305. var lines = code.split('\n');
  29306. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  29307. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  29308. if (tabbed.length === 0 && spaced.length === 0) {
  29309. return null;
  29310. }
  29311. // More lines tabbed than spaced? Assume tabs, and
  29312. // default to tabs in the case of a tie (or nothing
  29313. // to go on)
  29314. if (tabbed.length >= spaced.length) {
  29315. return '\t';
  29316. }
  29317. // Otherwise, we need to guess the multiple
  29318. var min = spaced.reduce(function (previous, current) {
  29319. var numSpaces = /^ +/.exec(current)[0].length;
  29320. return Math.min(numSpaces, previous);
  29321. }, Infinity);
  29322. return new Array(min + 1).join(' ');
  29323. }
  29324. function getRelativePath(from, to) {
  29325. var fromParts = from.split(/[/\\]/);
  29326. var toParts = to.split(/[/\\]/);
  29327. fromParts.pop(); // get dirname
  29328. while (fromParts[0] === toParts[0]) {
  29329. fromParts.shift();
  29330. toParts.shift();
  29331. }
  29332. if (fromParts.length) {
  29333. var i = fromParts.length;
  29334. while (i--) { fromParts[i] = '..'; }
  29335. }
  29336. return fromParts.concat(toParts).join('/');
  29337. }
  29338. var toString$2 = Object.prototype.toString;
  29339. function isObject$1(thing) {
  29340. return toString$2.call(thing) === '[object Object]';
  29341. }
  29342. function getLocator(source) {
  29343. var originalLines = source.split('\n');
  29344. var lineOffsets = [];
  29345. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  29346. lineOffsets.push(pos);
  29347. pos += originalLines[i].length + 1;
  29348. }
  29349. return function locate(index) {
  29350. var i = 0;
  29351. var j = lineOffsets.length;
  29352. while (i < j) {
  29353. var m = (i + j) >> 1;
  29354. if (index < lineOffsets[m]) {
  29355. j = m;
  29356. } else {
  29357. i = m + 1;
  29358. }
  29359. }
  29360. var line = i - 1;
  29361. var column = index - lineOffsets[line];
  29362. return { line: line, column: column };
  29363. };
  29364. }
  29365. var Mappings = function Mappings(hires) {
  29366. this.hires = hires;
  29367. this.generatedCodeLine = 0;
  29368. this.generatedCodeColumn = 0;
  29369. this.raw = [];
  29370. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  29371. this.pending = null;
  29372. };
  29373. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  29374. if (content.length) {
  29375. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  29376. if (nameIndex >= 0) {
  29377. segment.push(nameIndex);
  29378. }
  29379. this.rawSegments.push(segment);
  29380. } else if (this.pending) {
  29381. this.rawSegments.push(this.pending);
  29382. }
  29383. this.advance(content);
  29384. this.pending = null;
  29385. };
  29386. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  29387. var originalCharIndex = chunk.start;
  29388. var first = true;
  29389. while (originalCharIndex < chunk.end) {
  29390. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  29391. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  29392. }
  29393. if (original[originalCharIndex] === '\n') {
  29394. loc.line += 1;
  29395. loc.column = 0;
  29396. this.generatedCodeLine += 1;
  29397. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  29398. this.generatedCodeColumn = 0;
  29399. first = true;
  29400. } else {
  29401. loc.column += 1;
  29402. this.generatedCodeColumn += 1;
  29403. first = false;
  29404. }
  29405. originalCharIndex += 1;
  29406. }
  29407. this.pending = null;
  29408. };
  29409. Mappings.prototype.advance = function advance (str) {
  29410. if (!str) { return; }
  29411. var lines = str.split('\n');
  29412. if (lines.length > 1) {
  29413. for (var i = 0; i < lines.length - 1; i++) {
  29414. this.generatedCodeLine++;
  29415. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  29416. }
  29417. this.generatedCodeColumn = 0;
  29418. }
  29419. this.generatedCodeColumn += lines[lines.length - 1].length;
  29420. };
  29421. var n = '\n';
  29422. var warned = {
  29423. insertLeft: false,
  29424. insertRight: false,
  29425. storeName: false
  29426. };
  29427. var MagicString = function MagicString(string, options) {
  29428. if ( options === void 0 ) options = {};
  29429. var chunk = new Chunk(0, string.length, string);
  29430. Object.defineProperties(this, {
  29431. original: { writable: true, value: string },
  29432. outro: { writable: true, value: '' },
  29433. intro: { writable: true, value: '' },
  29434. firstChunk: { writable: true, value: chunk },
  29435. lastChunk: { writable: true, value: chunk },
  29436. lastSearchedChunk: { writable: true, value: chunk },
  29437. byStart: { writable: true, value: {} },
  29438. byEnd: { writable: true, value: {} },
  29439. filename: { writable: true, value: options.filename },
  29440. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  29441. sourcemapLocations: { writable: true, value: new BitSet() },
  29442. storedNames: { writable: true, value: {} },
  29443. indentStr: { writable: true, value: guessIndent(string) }
  29444. });
  29445. this.byStart[0] = chunk;
  29446. this.byEnd[string.length] = chunk;
  29447. };
  29448. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  29449. this.sourcemapLocations.add(char);
  29450. };
  29451. MagicString.prototype.append = function append (content) {
  29452. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  29453. this.outro += content;
  29454. return this;
  29455. };
  29456. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  29457. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  29458. this._split(index);
  29459. var chunk = this.byEnd[index];
  29460. if (chunk) {
  29461. chunk.appendLeft(content);
  29462. } else {
  29463. this.intro += content;
  29464. }
  29465. return this;
  29466. };
  29467. MagicString.prototype.appendRight = function appendRight (index, content) {
  29468. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  29469. this._split(index);
  29470. var chunk = this.byStart[index];
  29471. if (chunk) {
  29472. chunk.appendRight(content);
  29473. } else {
  29474. this.outro += content;
  29475. }
  29476. return this;
  29477. };
  29478. MagicString.prototype.clone = function clone () {
  29479. var cloned = new MagicString(this.original, { filename: this.filename });
  29480. var originalChunk = this.firstChunk;
  29481. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  29482. while (originalChunk) {
  29483. cloned.byStart[clonedChunk.start] = clonedChunk;
  29484. cloned.byEnd[clonedChunk.end] = clonedChunk;
  29485. var nextOriginalChunk = originalChunk.next;
  29486. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  29487. if (nextClonedChunk) {
  29488. clonedChunk.next = nextClonedChunk;
  29489. nextClonedChunk.previous = clonedChunk;
  29490. clonedChunk = nextClonedChunk;
  29491. }
  29492. originalChunk = nextOriginalChunk;
  29493. }
  29494. cloned.lastChunk = clonedChunk;
  29495. if (this.indentExclusionRanges) {
  29496. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  29497. }
  29498. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  29499. cloned.intro = this.intro;
  29500. cloned.outro = this.outro;
  29501. return cloned;
  29502. };
  29503. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  29504. var this$1 = this;
  29505. options = options || {};
  29506. var sourceIndex = 0;
  29507. var names = Object.keys(this.storedNames);
  29508. var mappings = new Mappings(options.hires);
  29509. var locate = getLocator(this.original);
  29510. if (this.intro) {
  29511. mappings.advance(this.intro);
  29512. }
  29513. this.firstChunk.eachNext(function (chunk) {
  29514. var loc = locate(chunk.start);
  29515. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  29516. if (chunk.edited) {
  29517. mappings.addEdit(
  29518. sourceIndex,
  29519. chunk.content,
  29520. loc,
  29521. chunk.storeName ? names.indexOf(chunk.original) : -1
  29522. );
  29523. } else {
  29524. mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
  29525. }
  29526. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  29527. });
  29528. return {
  29529. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  29530. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  29531. sourcesContent: options.includeContent ? [this.original] : [null],
  29532. names: names,
  29533. mappings: mappings.raw
  29534. };
  29535. };
  29536. MagicString.prototype.generateMap = function generateMap (options) {
  29537. return new SourceMap(this.generateDecodedMap(options));
  29538. };
  29539. MagicString.prototype.getIndentString = function getIndentString () {
  29540. return this.indentStr === null ? '\t' : this.indentStr;
  29541. };
  29542. MagicString.prototype.indent = function indent (indentStr, options) {
  29543. var pattern = /^[^\r\n]/gm;
  29544. if (isObject$1(indentStr)) {
  29545. options = indentStr;
  29546. indentStr = undefined;
  29547. }
  29548. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  29549. if (indentStr === '') { return this; } // noop
  29550. options = options || {};
  29551. // Process exclusion ranges
  29552. var isExcluded = {};
  29553. if (options.exclude) {
  29554. var exclusions =
  29555. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  29556. exclusions.forEach(function (exclusion) {
  29557. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  29558. isExcluded[i] = true;
  29559. }
  29560. });
  29561. }
  29562. var shouldIndentNextCharacter = options.indentStart !== false;
  29563. var replacer = function (match) {
  29564. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  29565. shouldIndentNextCharacter = true;
  29566. return match;
  29567. };
  29568. this.intro = this.intro.replace(pattern, replacer);
  29569. var charIndex = 0;
  29570. var chunk = this.firstChunk;
  29571. while (chunk) {
  29572. var end = chunk.end;
  29573. if (chunk.edited) {
  29574. if (!isExcluded[charIndex]) {
  29575. chunk.content = chunk.content.replace(pattern, replacer);
  29576. if (chunk.content.length) {
  29577. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  29578. }
  29579. }
  29580. } else {
  29581. charIndex = chunk.start;
  29582. while (charIndex < end) {
  29583. if (!isExcluded[charIndex]) {
  29584. var char = this.original[charIndex];
  29585. if (char === '\n') {
  29586. shouldIndentNextCharacter = true;
  29587. } else if (char !== '\r' && shouldIndentNextCharacter) {
  29588. shouldIndentNextCharacter = false;
  29589. if (charIndex === chunk.start) {
  29590. chunk.prependRight(indentStr);
  29591. } else {
  29592. this._splitChunk(chunk, charIndex);
  29593. chunk = chunk.next;
  29594. chunk.prependRight(indentStr);
  29595. }
  29596. }
  29597. }
  29598. charIndex += 1;
  29599. }
  29600. }
  29601. charIndex = chunk.end;
  29602. chunk = chunk.next;
  29603. }
  29604. this.outro = this.outro.replace(pattern, replacer);
  29605. return this;
  29606. };
  29607. MagicString.prototype.insert = function insert () {
  29608. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  29609. };
  29610. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  29611. if (!warned.insertLeft) {
  29612. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  29613. warned.insertLeft = true;
  29614. }
  29615. return this.appendLeft(index, content);
  29616. };
  29617. MagicString.prototype.insertRight = function insertRight (index, content) {
  29618. if (!warned.insertRight) {
  29619. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  29620. warned.insertRight = true;
  29621. }
  29622. return this.prependRight(index, content);
  29623. };
  29624. MagicString.prototype.move = function move (start, end, index) {
  29625. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  29626. this._split(start);
  29627. this._split(end);
  29628. this._split(index);
  29629. var first = this.byStart[start];
  29630. var last = this.byEnd[end];
  29631. var oldLeft = first.previous;
  29632. var oldRight = last.next;
  29633. var newRight = this.byStart[index];
  29634. if (!newRight && last === this.lastChunk) { return this; }
  29635. var newLeft = newRight ? newRight.previous : this.lastChunk;
  29636. if (oldLeft) { oldLeft.next = oldRight; }
  29637. if (oldRight) { oldRight.previous = oldLeft; }
  29638. if (newLeft) { newLeft.next = first; }
  29639. if (newRight) { newRight.previous = last; }
  29640. if (!first.previous) { this.firstChunk = last.next; }
  29641. if (!last.next) {
  29642. this.lastChunk = first.previous;
  29643. this.lastChunk.next = null;
  29644. }
  29645. first.previous = newLeft;
  29646. last.next = newRight || null;
  29647. if (!newLeft) { this.firstChunk = first; }
  29648. if (!newRight) { this.lastChunk = last; }
  29649. return this;
  29650. };
  29651. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  29652. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  29653. while (start < 0) { start += this.original.length; }
  29654. while (end < 0) { end += this.original.length; }
  29655. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  29656. if (start === end)
  29657. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  29658. this._split(start);
  29659. this._split(end);
  29660. if (options === true) {
  29661. if (!warned.storeName) {
  29662. console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
  29663. warned.storeName = true;
  29664. }
  29665. options = { storeName: true };
  29666. }
  29667. var storeName = options !== undefined ? options.storeName : false;
  29668. var contentOnly = options !== undefined ? options.contentOnly : false;
  29669. if (storeName) {
  29670. var original = this.original.slice(start, end);
  29671. this.storedNames[original] = true;
  29672. }
  29673. var first = this.byStart[start];
  29674. var last = this.byEnd[end];
  29675. if (first) {
  29676. if (end > first.end && first.next !== this.byStart[first.end]) {
  29677. throw new Error('Cannot overwrite across a split point');
  29678. }
  29679. first.edit(content, storeName, contentOnly);
  29680. if (first !== last) {
  29681. var chunk = first.next;
  29682. while (chunk !== last) {
  29683. chunk.edit('', false);
  29684. chunk = chunk.next;
  29685. }
  29686. chunk.edit('', false);
  29687. }
  29688. } else {
  29689. // must be inserting at the end
  29690. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  29691. // TODO last chunk in the array may not be the last chunk, if it's moved...
  29692. last.next = newChunk;
  29693. newChunk.previous = last;
  29694. }
  29695. return this;
  29696. };
  29697. MagicString.prototype.prepend = function prepend (content) {
  29698. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  29699. this.intro = content + this.intro;
  29700. return this;
  29701. };
  29702. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  29703. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  29704. this._split(index);
  29705. var chunk = this.byEnd[index];
  29706. if (chunk) {
  29707. chunk.prependLeft(content);
  29708. } else {
  29709. this.intro = content + this.intro;
  29710. }
  29711. return this;
  29712. };
  29713. MagicString.prototype.prependRight = function prependRight (index, content) {
  29714. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  29715. this._split(index);
  29716. var chunk = this.byStart[index];
  29717. if (chunk) {
  29718. chunk.prependRight(content);
  29719. } else {
  29720. this.outro = content + this.outro;
  29721. }
  29722. return this;
  29723. };
  29724. MagicString.prototype.remove = function remove (start, end) {
  29725. while (start < 0) { start += this.original.length; }
  29726. while (end < 0) { end += this.original.length; }
  29727. if (start === end) { return this; }
  29728. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  29729. if (start > end) { throw new Error('end must be greater than start'); }
  29730. this._split(start);
  29731. this._split(end);
  29732. var chunk = this.byStart[start];
  29733. while (chunk) {
  29734. chunk.intro = '';
  29735. chunk.outro = '';
  29736. chunk.edit('');
  29737. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  29738. }
  29739. return this;
  29740. };
  29741. MagicString.prototype.lastChar = function lastChar () {
  29742. if (this.outro.length)
  29743. { return this.outro[this.outro.length - 1]; }
  29744. var chunk = this.lastChunk;
  29745. do {
  29746. if (chunk.outro.length)
  29747. { return chunk.outro[chunk.outro.length - 1]; }
  29748. if (chunk.content.length)
  29749. { return chunk.content[chunk.content.length - 1]; }
  29750. if (chunk.intro.length)
  29751. { return chunk.intro[chunk.intro.length - 1]; }
  29752. } while (chunk = chunk.previous);
  29753. if (this.intro.length)
  29754. { return this.intro[this.intro.length - 1]; }
  29755. return '';
  29756. };
  29757. MagicString.prototype.lastLine = function lastLine () {
  29758. var lineIndex = this.outro.lastIndexOf(n);
  29759. if (lineIndex !== -1)
  29760. { return this.outro.substr(lineIndex + 1); }
  29761. var lineStr = this.outro;
  29762. var chunk = this.lastChunk;
  29763. do {
  29764. if (chunk.outro.length > 0) {
  29765. lineIndex = chunk.outro.lastIndexOf(n);
  29766. if (lineIndex !== -1)
  29767. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  29768. lineStr = chunk.outro + lineStr;
  29769. }
  29770. if (chunk.content.length > 0) {
  29771. lineIndex = chunk.content.lastIndexOf(n);
  29772. if (lineIndex !== -1)
  29773. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  29774. lineStr = chunk.content + lineStr;
  29775. }
  29776. if (chunk.intro.length > 0) {
  29777. lineIndex = chunk.intro.lastIndexOf(n);
  29778. if (lineIndex !== -1)
  29779. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  29780. lineStr = chunk.intro + lineStr;
  29781. }
  29782. } while (chunk = chunk.previous);
  29783. lineIndex = this.intro.lastIndexOf(n);
  29784. if (lineIndex !== -1)
  29785. { return this.intro.substr(lineIndex + 1) + lineStr; }
  29786. return this.intro + lineStr;
  29787. };
  29788. MagicString.prototype.slice = function slice (start, end) {
  29789. if ( start === void 0 ) start = 0;
  29790. if ( end === void 0 ) end = this.original.length;
  29791. while (start < 0) { start += this.original.length; }
  29792. while (end < 0) { end += this.original.length; }
  29793. var result = '';
  29794. // find start chunk
  29795. var chunk = this.firstChunk;
  29796. while (chunk && (chunk.start > start || chunk.end <= start)) {
  29797. // found end chunk before start
  29798. if (chunk.start < end && chunk.end >= end) {
  29799. return result;
  29800. }
  29801. chunk = chunk.next;
  29802. }
  29803. if (chunk && chunk.edited && chunk.start !== start)
  29804. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  29805. var startChunk = chunk;
  29806. while (chunk) {
  29807. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  29808. result += chunk.intro;
  29809. }
  29810. var containsEnd = chunk.start < end && chunk.end >= end;
  29811. if (containsEnd && chunk.edited && chunk.end !== end)
  29812. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  29813. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  29814. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  29815. result += chunk.content.slice(sliceStart, sliceEnd);
  29816. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  29817. result += chunk.outro;
  29818. }
  29819. if (containsEnd) {
  29820. break;
  29821. }
  29822. chunk = chunk.next;
  29823. }
  29824. return result;
  29825. };
  29826. // TODO deprecate this? not really very useful
  29827. MagicString.prototype.snip = function snip (start, end) {
  29828. var clone = this.clone();
  29829. clone.remove(0, start);
  29830. clone.remove(end, clone.original.length);
  29831. return clone;
  29832. };
  29833. MagicString.prototype._split = function _split (index) {
  29834. if (this.byStart[index] || this.byEnd[index]) { return; }
  29835. var chunk = this.lastSearchedChunk;
  29836. var searchForward = index > chunk.end;
  29837. while (chunk) {
  29838. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  29839. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  29840. }
  29841. };
  29842. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  29843. if (chunk.edited && chunk.content.length) {
  29844. // zero-length edited chunks are a special case (overlapping replacements)
  29845. var loc = getLocator(this.original)(index);
  29846. throw new Error(
  29847. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  29848. );
  29849. }
  29850. var newChunk = chunk.split(index);
  29851. this.byEnd[index] = chunk;
  29852. this.byStart[index] = newChunk;
  29853. this.byEnd[newChunk.end] = newChunk;
  29854. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  29855. this.lastSearchedChunk = chunk;
  29856. return true;
  29857. };
  29858. MagicString.prototype.toString = function toString () {
  29859. var str = this.intro;
  29860. var chunk = this.firstChunk;
  29861. while (chunk) {
  29862. str += chunk.toString();
  29863. chunk = chunk.next;
  29864. }
  29865. return str + this.outro;
  29866. };
  29867. MagicString.prototype.isEmpty = function isEmpty () {
  29868. var chunk = this.firstChunk;
  29869. do {
  29870. if (chunk.intro.length && chunk.intro.trim() ||
  29871. chunk.content.length && chunk.content.trim() ||
  29872. chunk.outro.length && chunk.outro.trim())
  29873. { return false; }
  29874. } while (chunk = chunk.next);
  29875. return true;
  29876. };
  29877. MagicString.prototype.length = function length () {
  29878. var chunk = this.firstChunk;
  29879. var length = 0;
  29880. do {
  29881. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  29882. } while (chunk = chunk.next);
  29883. return length;
  29884. };
  29885. MagicString.prototype.trimLines = function trimLines () {
  29886. return this.trim('[\\r\\n]');
  29887. };
  29888. MagicString.prototype.trim = function trim (charType) {
  29889. return this.trimStart(charType).trimEnd(charType);
  29890. };
  29891. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  29892. var rx = new RegExp((charType || '\\s') + '+$');
  29893. this.outro = this.outro.replace(rx, '');
  29894. if (this.outro.length) { return true; }
  29895. var chunk = this.lastChunk;
  29896. do {
  29897. var end = chunk.end;
  29898. var aborted = chunk.trimEnd(rx);
  29899. // if chunk was trimmed, we have a new lastChunk
  29900. if (chunk.end !== end) {
  29901. if (this.lastChunk === chunk) {
  29902. this.lastChunk = chunk.next;
  29903. }
  29904. this.byEnd[chunk.end] = chunk;
  29905. this.byStart[chunk.next.start] = chunk.next;
  29906. this.byEnd[chunk.next.end] = chunk.next;
  29907. }
  29908. if (aborted) { return true; }
  29909. chunk = chunk.previous;
  29910. } while (chunk);
  29911. return false;
  29912. };
  29913. MagicString.prototype.trimEnd = function trimEnd (charType) {
  29914. this.trimEndAborted(charType);
  29915. return this;
  29916. };
  29917. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  29918. var rx = new RegExp('^' + (charType || '\\s') + '+');
  29919. this.intro = this.intro.replace(rx, '');
  29920. if (this.intro.length) { return true; }
  29921. var chunk = this.firstChunk;
  29922. do {
  29923. var end = chunk.end;
  29924. var aborted = chunk.trimStart(rx);
  29925. if (chunk.end !== end) {
  29926. // special case...
  29927. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  29928. this.byEnd[chunk.end] = chunk;
  29929. this.byStart[chunk.next.start] = chunk.next;
  29930. this.byEnd[chunk.next.end] = chunk.next;
  29931. }
  29932. if (aborted) { return true; }
  29933. chunk = chunk.next;
  29934. } while (chunk);
  29935. return false;
  29936. };
  29937. MagicString.prototype.trimStart = function trimStart (charType) {
  29938. this.trimStartAborted(charType);
  29939. return this;
  29940. };
  29941. const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/;
  29942. const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/;
  29943. /**
  29944. * Utility for rewriting `export default` in a script block into a variable
  29945. * declaration so that we can inject things into it
  29946. */
  29947. function rewriteDefault(input, as, parserPlugins) {
  29948. if (!hasDefaultExport(input)) {
  29949. return input + `\nconst ${as} = {}`;
  29950. }
  29951. const replaced = input.replace(defaultExportRE, `$1const ${as} =`);
  29952. if (!hasDefaultExport(replaced)) {
  29953. return replaced;
  29954. }
  29955. // if the script somehow still contains `default export`, it probably has
  29956. // multi-line comments or template strings. fallback to a full parse.
  29957. const s = new MagicString(input);
  29958. const ast = parse_1(input, {
  29959. sourceType: 'module',
  29960. plugins: parserPlugins
  29961. }).program.body;
  29962. ast.forEach(node => {
  29963. if (node.type === 'ExportDefaultDeclaration') {
  29964. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  29965. }
  29966. if (node.type === 'ExportNamedDeclaration') {
  29967. node.specifiers.forEach(specifier => {
  29968. if (specifier.type === 'ExportSpecifier' &&
  29969. specifier.exported.type === 'Identifier' &&
  29970. specifier.exported.name === 'default') {
  29971. const end = specifier.end;
  29972. s.overwrite(specifier.start, input.charAt(end) === ',' ? end + 1 : end, ``);
  29973. s.append(`\nconst ${as} = ${specifier.local.name}`);
  29974. }
  29975. });
  29976. }
  29977. });
  29978. return s.toString();
  29979. }
  29980. function hasDefaultExport(input) {
  29981. return defaultExportRE.test(input) || namedDefaultExportRE.test(input);
  29982. }
  29983. const DEFINE_PROPS = 'defineProps';
  29984. const DEFINE_EMIT = 'defineEmit';
  29985. /**
  29986. * Compile `<script setup>`
  29987. * It requires the whole SFC descriptor because we need to handle and merge
  29988. * normal `<script>` + `<script setup>` if both are present.
  29989. */
  29990. function compileScript(sfc, options) {
  29991. const { script, scriptSetup, source, filename } = sfc;
  29992. if (scriptSetup) {
  29993. warnExperimental(`<script setup>`, 227);
  29994. }
  29995. // for backwards compat
  29996. if (!options) {
  29997. options = { id: '' };
  29998. }
  29999. if (!options.id) {
  30000. warnOnce(`compileScript now requires passing the \`id\` option.\n` +
  30001. `Upgrade your vite or vue-loader version for compatibility with ` +
  30002. `the latest experimental proposals.`);
  30003. }
  30004. const scopeId = options.id ? options.id.replace(/^data-v-/, '') : '';
  30005. const cssVars = sfc.cssVars;
  30006. const hasInheritAttrsFlag = sfc.template && sfc.template.attrs['inherit-attrs'] === 'false';
  30007. const scriptLang = script && script.lang;
  30008. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  30009. const isTS = scriptLang === 'ts' || scriptSetupLang === 'ts';
  30010. const plugins = [...babelParserDefaultPlugins, 'jsx'];
  30011. if (options.babelParserPlugins)
  30012. plugins.push(...options.babelParserPlugins);
  30013. if (isTS)
  30014. plugins.push('typescript', 'decorators-legacy');
  30015. if (!scriptSetup) {
  30016. if (!script) {
  30017. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  30018. }
  30019. if (scriptLang && scriptLang !== 'ts') {
  30020. // do not process non js/ts script blocks
  30021. return script;
  30022. }
  30023. try {
  30024. const scriptAst = parse_1(script.content, {
  30025. plugins,
  30026. sourceType: 'module'
  30027. }).program.body;
  30028. const bindings = analyzeScriptBindings(scriptAst);
  30029. const needRewrite = cssVars.length || hasInheritAttrsFlag;
  30030. let content = script.content;
  30031. if (needRewrite) {
  30032. content = rewriteDefault(content, `__default__`, plugins);
  30033. if (cssVars.length) {
  30034. content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, !!options.isProd);
  30035. }
  30036. if (hasInheritAttrsFlag) {
  30037. content += `__default__.inheritAttrs = false`;
  30038. }
  30039. content += `\nexport default __default__`;
  30040. }
  30041. return {
  30042. ...script,
  30043. content,
  30044. bindings,
  30045. scriptAst
  30046. };
  30047. }
  30048. catch (e) {
  30049. // silently fallback if parse fails since user may be using custom
  30050. // babel syntax
  30051. return script;
  30052. }
  30053. }
  30054. if (script && scriptLang !== scriptSetupLang) {
  30055. throw new Error(`[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`);
  30056. }
  30057. if (scriptSetupLang && scriptSetupLang !== 'ts') {
  30058. // do not process non js/ts script blocks
  30059. return scriptSetup;
  30060. }
  30061. const defaultTempVar = `__default__`;
  30062. const bindingMetadata = {};
  30063. const helperImports = new Set();
  30064. const userImports = Object.create(null);
  30065. const userImportAlias = Object.create(null);
  30066. const setupBindings = Object.create(null);
  30067. const refBindings = Object.create(null);
  30068. const refIdentifiers = new Set();
  30069. const enableRefSugar = options.refSugar !== false;
  30070. let defaultExport;
  30071. let hasDefinePropsCall = false;
  30072. let hasDefineEmitCall = false;
  30073. let propsRuntimeDecl;
  30074. let propsTypeDecl;
  30075. let propsIdentifier;
  30076. let emitRuntimeDecl;
  30077. let emitTypeDecl;
  30078. let emitIdentifier;
  30079. let hasAwait = false;
  30080. let hasInlinedSsrRenderFn = false;
  30081. // props/emits declared via types
  30082. const typeDeclaredProps = {};
  30083. const typeDeclaredEmits = new Set();
  30084. // record declared types for runtime props type generation
  30085. const declaredTypes = {};
  30086. // magic-string state
  30087. const s = new MagicString(source);
  30088. const startOffset = scriptSetup.loc.start.offset;
  30089. const endOffset = scriptSetup.loc.end.offset;
  30090. const scriptStartOffset = script && script.loc.start.offset;
  30091. const scriptEndOffset = script && script.loc.end.offset;
  30092. function helper(key) {
  30093. helperImports.add(key);
  30094. return `_${key}`;
  30095. }
  30096. function parse(input, options, offset) {
  30097. try {
  30098. return parse_1(input, options).program.body;
  30099. }
  30100. catch (e) {
  30101. e.message = `[@vue/compiler-sfc] ${e.message}\n\n${sfc.filename}\n${generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`;
  30102. throw e;
  30103. }
  30104. }
  30105. function error(msg, node, end = node.end + startOffset) {
  30106. throw new Error(`[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${generateCodeFrame(source, node.start + startOffset, end)}`);
  30107. }
  30108. function registerUserImport(source, local, imported, isType) {
  30109. if (source === 'vue' && imported) {
  30110. userImportAlias[imported] = local;
  30111. }
  30112. userImports[local] = {
  30113. isType,
  30114. imported: imported || 'default',
  30115. source
  30116. };
  30117. }
  30118. function processDefineProps(node) {
  30119. if (isCallOf(node, DEFINE_PROPS)) {
  30120. if (hasDefinePropsCall) {
  30121. error(`duplicate ${DEFINE_PROPS}() call`, node);
  30122. }
  30123. hasDefinePropsCall = true;
  30124. propsRuntimeDecl = node.arguments[0];
  30125. // context call has type parameters - infer runtime types from it
  30126. if (node.typeParameters) {
  30127. if (propsRuntimeDecl) {
  30128. error(`${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
  30129. `at the same time. Use one or the other.`, node);
  30130. }
  30131. const typeArg = node.typeParameters.params[0];
  30132. if (typeArg.type === 'TSTypeLiteral') {
  30133. propsTypeDecl = typeArg;
  30134. }
  30135. else {
  30136. error(`type argument passed to ${DEFINE_PROPS}() must be a literal type.`, typeArg);
  30137. }
  30138. }
  30139. return true;
  30140. }
  30141. return false;
  30142. }
  30143. function processDefineEmit(node) {
  30144. if (isCallOf(node, DEFINE_EMIT)) {
  30145. if (hasDefineEmitCall) {
  30146. error(`duplicate ${DEFINE_EMIT}() call`, node);
  30147. }
  30148. hasDefineEmitCall = true;
  30149. emitRuntimeDecl = node.arguments[0];
  30150. if (node.typeParameters) {
  30151. if (emitRuntimeDecl) {
  30152. error(`${DEFINE_EMIT}() cannot accept both type and non-type arguments ` +
  30153. `at the same time. Use one or the other.`, node);
  30154. }
  30155. const typeArg = node.typeParameters.params[0];
  30156. if (typeArg.type === 'TSFunctionType' ||
  30157. typeArg.type === 'TSUnionType') {
  30158. emitTypeDecl = typeArg;
  30159. }
  30160. else {
  30161. error(`type argument passed to ${DEFINE_EMIT}() must be a function type ` +
  30162. `or a union of function types.`, typeArg);
  30163. }
  30164. }
  30165. return true;
  30166. }
  30167. return false;
  30168. }
  30169. function checkInvalidScopeReference(node, method) {
  30170. if (!node)
  30171. return;
  30172. walkIdentifiers(node, id => {
  30173. if (setupBindings[id.name]) {
  30174. error(`\`${method}()\` in <script setup> cannot reference locally ` +
  30175. `declared variables because it will be hoisted outside of the ` +
  30176. `setup() function. If your component options requires initialization ` +
  30177. `in the module scope, use a separate normal <script> to export ` +
  30178. `the options instead.`, id);
  30179. }
  30180. });
  30181. }
  30182. function processRefExpression(exp, statement) {
  30183. if (exp.type === 'AssignmentExpression') {
  30184. const { left, right } = exp;
  30185. if (left.type === 'Identifier') {
  30186. registerRefBinding(left);
  30187. s.prependRight(right.start + startOffset, `${helper('ref')}(`);
  30188. s.appendLeft(right.end + startOffset, ')');
  30189. }
  30190. else if (left.type === 'ObjectPattern') {
  30191. // remove wrapping parens
  30192. for (let i = left.start; i > 0; i--) {
  30193. const char = source[i + startOffset];
  30194. if (char === '(') {
  30195. s.remove(i + startOffset, i + startOffset + 1);
  30196. break;
  30197. }
  30198. }
  30199. for (let i = left.end; i > 0; i++) {
  30200. const char = source[i + startOffset];
  30201. if (char === ')') {
  30202. s.remove(i + startOffset, i + startOffset + 1);
  30203. break;
  30204. }
  30205. }
  30206. processRefObjectPattern(left, statement);
  30207. }
  30208. else if (left.type === 'ArrayPattern') {
  30209. processRefArrayPattern(left, statement);
  30210. }
  30211. }
  30212. else if (exp.type === 'SequenceExpression') {
  30213. // possible multiple declarations
  30214. // ref: x = 1, y = 2
  30215. exp.expressions.forEach(e => processRefExpression(e, statement));
  30216. }
  30217. else if (exp.type === 'Identifier') {
  30218. registerRefBinding(exp);
  30219. s.appendLeft(exp.end + startOffset, ` = ${helper('ref')}()`);
  30220. }
  30221. else {
  30222. error(`ref: statements can only contain assignment expressions.`, exp);
  30223. }
  30224. }
  30225. function registerRefBinding(id) {
  30226. if (id.name[0] === '$') {
  30227. error(`ref variable identifiers cannot start with $.`, id);
  30228. }
  30229. refBindings[id.name] = setupBindings[id.name] = "setup-ref" /* SETUP_REF */;
  30230. refIdentifiers.add(id);
  30231. }
  30232. function processRefObjectPattern(pattern, statement) {
  30233. for (const p of pattern.properties) {
  30234. let nameId;
  30235. if (p.type === 'ObjectProperty') {
  30236. if (p.key.start === p.value.start) {
  30237. // shorthand { foo } --> { foo: __foo }
  30238. nameId = p.key;
  30239. s.appendLeft(nameId.end + startOffset, `: __${nameId.name}`);
  30240. if (p.value.type === 'AssignmentPattern') {
  30241. // { foo = 1 }
  30242. refIdentifiers.add(p.value.left);
  30243. }
  30244. }
  30245. else {
  30246. if (p.value.type === 'Identifier') {
  30247. // { foo: bar } --> { foo: __bar }
  30248. nameId = p.value;
  30249. s.prependRight(nameId.start + startOffset, `__`);
  30250. }
  30251. else if (p.value.type === 'ObjectPattern') {
  30252. processRefObjectPattern(p.value, statement);
  30253. }
  30254. else if (p.value.type === 'ArrayPattern') {
  30255. processRefArrayPattern(p.value, statement);
  30256. }
  30257. else if (p.value.type === 'AssignmentPattern') {
  30258. // { foo: bar = 1 } --> { foo: __bar = 1 }
  30259. nameId = p.value.left;
  30260. s.prependRight(nameId.start + startOffset, `__`);
  30261. }
  30262. }
  30263. }
  30264. else {
  30265. // rest element { ...foo } --> { ...__foo }
  30266. nameId = p.argument;
  30267. s.prependRight(nameId.start + startOffset, `__`);
  30268. }
  30269. if (nameId) {
  30270. registerRefBinding(nameId);
  30271. // append binding declarations after the parent statement
  30272. s.appendLeft(statement.end + startOffset, `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`);
  30273. }
  30274. }
  30275. }
  30276. function processRefArrayPattern(pattern, statement) {
  30277. for (const e of pattern.elements) {
  30278. if (!e)
  30279. continue;
  30280. let nameId;
  30281. if (e.type === 'Identifier') {
  30282. // [a] --> [__a]
  30283. nameId = e;
  30284. }
  30285. else if (e.type === 'AssignmentPattern') {
  30286. // [a = 1] --> [__a = 1]
  30287. nameId = e.left;
  30288. }
  30289. else if (e.type === 'RestElement') {
  30290. // [...a] --> [...__a]
  30291. nameId = e.argument;
  30292. }
  30293. else if (e.type === 'ObjectPattern') {
  30294. processRefObjectPattern(e, statement);
  30295. }
  30296. else if (e.type === 'ArrayPattern') {
  30297. processRefArrayPattern(e, statement);
  30298. }
  30299. if (nameId) {
  30300. registerRefBinding(nameId);
  30301. // prefix original
  30302. s.prependRight(nameId.start + startOffset, `__`);
  30303. // append binding declarations after the parent statement
  30304. s.appendLeft(statement.end + startOffset, `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`);
  30305. }
  30306. }
  30307. }
  30308. // 1. process normal <script> first if it exists
  30309. let scriptAst;
  30310. if (script) {
  30311. // import dedupe between <script> and <script setup>
  30312. scriptAst = parse(script.content, {
  30313. plugins,
  30314. sourceType: 'module'
  30315. }, scriptStartOffset);
  30316. for (const node of scriptAst) {
  30317. if (node.type === 'ImportDeclaration') {
  30318. // record imports for dedupe
  30319. for (const specifier of node.specifiers) {
  30320. const imported = specifier.type === 'ImportSpecifier' &&
  30321. specifier.imported.type === 'Identifier' &&
  30322. specifier.imported.name;
  30323. registerUserImport(node.source.value, specifier.local.name, imported, node.importKind === 'type');
  30324. }
  30325. }
  30326. else if (node.type === 'ExportDefaultDeclaration') {
  30327. // export default
  30328. defaultExport = node;
  30329. const start = node.start + scriptStartOffset;
  30330. s.overwrite(start, start + `export default`.length, `const ${defaultTempVar} =`);
  30331. }
  30332. else if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
  30333. const defaultSpecifier = node.specifiers.find(s => s.exported.type === 'Identifier' && s.exported.name === 'default');
  30334. if (defaultSpecifier) {
  30335. defaultExport = node;
  30336. // 1. remove specifier
  30337. if (node.specifiers.length > 1) {
  30338. s.remove(defaultSpecifier.start + scriptStartOffset, defaultSpecifier.end + scriptStartOffset);
  30339. }
  30340. else {
  30341. s.remove(node.start + scriptStartOffset, node.end + scriptStartOffset);
  30342. }
  30343. if (node.source) {
  30344. // export { x as default } from './x'
  30345. // rewrite to `import { x as __default__ } from './x'` and
  30346. // add to top
  30347. s.prepend(`import { ${defaultSpecifier.local.name} as ${defaultTempVar} } from '${node.source.value}'\n`);
  30348. }
  30349. else {
  30350. // export { x as default }
  30351. // rewrite to `const __default__ = x` and move to end
  30352. s.append(`\nconst ${defaultTempVar} = ${defaultSpecifier.local.name}\n`);
  30353. }
  30354. }
  30355. }
  30356. }
  30357. }
  30358. // 2. parse <script setup> and walk over top level statements
  30359. const scriptSetupAst = parse(scriptSetup.content, {
  30360. plugins: [
  30361. ...plugins,
  30362. // allow top level await but only inside <script setup>
  30363. 'topLevelAwait'
  30364. ],
  30365. sourceType: 'module'
  30366. }, startOffset);
  30367. for (const node of scriptSetupAst) {
  30368. const start = node.start + startOffset;
  30369. let end = node.end + startOffset;
  30370. // import or type declarations: move to top
  30371. // locate comment
  30372. if (node.trailingComments && node.trailingComments.length > 0) {
  30373. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  30374. end = lastCommentNode.end + startOffset;
  30375. }
  30376. // locate the end of whitespace between this statement and the next
  30377. while (end <= source.length) {
  30378. if (!/\s/.test(source.charAt(end))) {
  30379. break;
  30380. }
  30381. end++;
  30382. }
  30383. // process `ref: x` bindings (convert to refs)
  30384. if (node.type === 'LabeledStatement' &&
  30385. node.label.name === 'ref' &&
  30386. node.body.type === 'ExpressionStatement') {
  30387. if (enableRefSugar) {
  30388. warnExperimental(`ref: sugar`, 228);
  30389. s.overwrite(node.label.start + startOffset, node.body.start + startOffset, 'const ');
  30390. processRefExpression(node.body.expression, node);
  30391. }
  30392. else {
  30393. // TODO if we end up shipping ref: sugar as an opt-in feature,
  30394. // need to proxy the option in vite, vue-loader and rollup-plugin-vue.
  30395. error(`ref: sugar needs to be explicitly enabled via vite or vue-loader options.`, node);
  30396. }
  30397. }
  30398. if (node.type === 'ImportDeclaration') {
  30399. // import declarations are moved to top
  30400. s.move(start, end, 0);
  30401. // dedupe imports
  30402. let removed = 0;
  30403. const removeSpecifier = (i) => {
  30404. const removeLeft = i > removed;
  30405. removed++;
  30406. const current = node.specifiers[i];
  30407. const next = node.specifiers[i + 1];
  30408. s.remove(removeLeft
  30409. ? node.specifiers[i - 1].end + startOffset
  30410. : current.start + startOffset, next && !removeLeft
  30411. ? next.start + startOffset
  30412. : current.end + startOffset);
  30413. };
  30414. for (let i = 0; i < node.specifiers.length; i++) {
  30415. const specifier = node.specifiers[i];
  30416. const local = specifier.local.name;
  30417. const imported = specifier.type === 'ImportSpecifier' &&
  30418. specifier.imported.type === 'Identifier' &&
  30419. specifier.imported.name;
  30420. const source = node.source.value;
  30421. const existing = userImports[local];
  30422. if (source === 'vue' &&
  30423. (imported === DEFINE_PROPS || imported === DEFINE_EMIT)) {
  30424. removeSpecifier(i);
  30425. }
  30426. else if (existing) {
  30427. if (existing.source === source && existing.imported === imported) {
  30428. // already imported in <script setup>, dedupe
  30429. removeSpecifier(i);
  30430. }
  30431. else {
  30432. error(`different imports aliased to same local name.`, specifier);
  30433. }
  30434. }
  30435. else {
  30436. registerUserImport(source, local, imported, node.importKind === 'type');
  30437. }
  30438. }
  30439. if (node.specifiers.length && removed === node.specifiers.length) {
  30440. s.remove(node.start + startOffset, node.end + startOffset);
  30441. }
  30442. }
  30443. // process `defineProps` and `defineEmit` calls
  30444. if (node.type === 'ExpressionStatement' &&
  30445. (processDefineProps(node.expression) ||
  30446. processDefineEmit(node.expression))) {
  30447. s.remove(node.start + startOffset, node.end + startOffset);
  30448. }
  30449. if (node.type === 'VariableDeclaration' && !node.declare) {
  30450. for (const decl of node.declarations) {
  30451. if (decl.init) {
  30452. const isDefineProps = processDefineProps(decl.init);
  30453. if (isDefineProps) {
  30454. propsIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
  30455. }
  30456. const isDefineEmit = processDefineEmit(decl.init);
  30457. if (isDefineEmit) {
  30458. emitIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
  30459. }
  30460. if (isDefineProps || isDefineEmit)
  30461. if (node.declarations.length === 1) {
  30462. s.remove(node.start + startOffset, node.end + startOffset);
  30463. }
  30464. else {
  30465. s.remove(decl.start + startOffset, decl.end + startOffset);
  30466. }
  30467. }
  30468. }
  30469. }
  30470. // walk decalrations to record declared bindings
  30471. if ((node.type === 'VariableDeclaration' ||
  30472. node.type === 'FunctionDeclaration' ||
  30473. node.type === 'ClassDeclaration') &&
  30474. !node.declare) {
  30475. walkDeclaration(node, setupBindings, userImportAlias);
  30476. }
  30477. // Type declarations
  30478. if (node.type === 'VariableDeclaration' && node.declare) {
  30479. s.remove(start, end);
  30480. }
  30481. // move all type declarations to outer scope
  30482. if (node.type.startsWith('TS') ||
  30483. (node.type === 'ExportNamedDeclaration' && node.exportKind === 'type')) {
  30484. recordType(node, declaredTypes);
  30485. s.move(start, end, 0);
  30486. }
  30487. // walk statements & named exports / variable declarations for top level
  30488. // await
  30489. if ((node.type === 'VariableDeclaration' && !node.declare) ||
  30490. node.type.endsWith('Statement')) {
  30491. walk$1(node, {
  30492. enter(node) {
  30493. if (isFunction$2(node)) {
  30494. this.skip();
  30495. }
  30496. if (node.type === 'AwaitExpression') {
  30497. hasAwait = true;
  30498. }
  30499. }
  30500. });
  30501. }
  30502. if ((node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
  30503. node.type === 'ExportAllDeclaration' ||
  30504. node.type === 'ExportDefaultDeclaration') {
  30505. error(`<script setup> cannot contain ES module exports. ` +
  30506. `If you are using a previous version of <script setup>, please ` +
  30507. `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, node);
  30508. }
  30509. }
  30510. // 3. Do a full walk to rewrite identifiers referencing let exports with ref
  30511. // value access
  30512. if (enableRefSugar && Object.keys(refBindings).length) {
  30513. for (const node of scriptSetupAst) {
  30514. if (node.type !== 'ImportDeclaration') {
  30515. walkIdentifiers(node, (id, parent, parentStack) => {
  30516. if (refBindings[id.name] && !refIdentifiers.has(id)) {
  30517. if (isStaticProperty$1(parent) && parent.shorthand) {
  30518. // let binding used in a property shorthand
  30519. // { foo } -> { foo: foo.value }
  30520. // skip for destructure patterns
  30521. if (!parent.inPattern ||
  30522. isInDestructureAssignment$1(parent, parentStack)) {
  30523. s.appendLeft(id.end + startOffset, `: ${id.name}.value`);
  30524. }
  30525. }
  30526. else {
  30527. s.appendLeft(id.end + startOffset, '.value');
  30528. }
  30529. }
  30530. else if (id.name[0] === '$' && refBindings[id.name.slice(1)]) {
  30531. // $xxx raw ref access variables, remove the $ prefix
  30532. s.remove(id.start + startOffset, id.start + startOffset + 1);
  30533. }
  30534. });
  30535. }
  30536. }
  30537. }
  30538. // 4. extract runtime props/emits code from setup context type
  30539. if (propsTypeDecl) {
  30540. extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
  30541. }
  30542. if (emitTypeDecl) {
  30543. extractRuntimeEmits(emitTypeDecl, typeDeclaredEmits);
  30544. }
  30545. // 5. check useOptions args to make sure it doesn't reference setup scope
  30546. // variables
  30547. checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
  30548. checkInvalidScopeReference(emitRuntimeDecl, DEFINE_PROPS);
  30549. // 6. remove non-script content
  30550. if (script) {
  30551. if (startOffset < scriptStartOffset) {
  30552. // <script setup> before <script>
  30553. s.remove(0, startOffset);
  30554. s.remove(endOffset, scriptStartOffset);
  30555. s.remove(scriptEndOffset, source.length);
  30556. }
  30557. else {
  30558. // <script> before <script setup>
  30559. s.remove(0, scriptStartOffset);
  30560. s.remove(scriptEndOffset, startOffset);
  30561. s.remove(endOffset, source.length);
  30562. }
  30563. }
  30564. else {
  30565. // only <script setup>
  30566. s.remove(0, startOffset);
  30567. s.remove(endOffset, source.length);
  30568. }
  30569. // 7. analyze binding metadata
  30570. if (scriptAst) {
  30571. Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst));
  30572. }
  30573. if (propsRuntimeDecl) {
  30574. for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
  30575. bindingMetadata[key] = "props" /* PROPS */;
  30576. }
  30577. }
  30578. for (const key in typeDeclaredProps) {
  30579. bindingMetadata[key] = "props" /* PROPS */;
  30580. }
  30581. for (const [key, { isType, imported, source }] of Object.entries(userImports)) {
  30582. if (isType)
  30583. continue;
  30584. bindingMetadata[key] =
  30585. (imported === 'default' && source.endsWith('.vue')) || source === 'vue'
  30586. ? "setup-const" /* SETUP_CONST */
  30587. : "setup-maybe-ref" /* SETUP_MAYBE_REF */;
  30588. }
  30589. for (const key in setupBindings) {
  30590. bindingMetadata[key] = setupBindings[key];
  30591. }
  30592. // 8. inject `useCssVars` calls
  30593. if (cssVars.length) {
  30594. helperImports.add(CSS_VARS_HELPER);
  30595. helperImports.add('unref');
  30596. s.prependRight(startOffset, `\n${genCssVarsCode(cssVars, bindingMetadata, scopeId, !!options.isProd)}\n`);
  30597. }
  30598. // 9. finalize setup() argument signature
  30599. let args = `__props`;
  30600. if (propsTypeDecl) {
  30601. args += `: ${scriptSetup.content.slice(propsTypeDecl.start, propsTypeDecl.end)}`;
  30602. }
  30603. // inject user assignment of props
  30604. // we use a default __props so that template expressions referencing props
  30605. // can use it directly
  30606. if (propsIdentifier) {
  30607. s.prependRight(startOffset, `\nconst ${propsIdentifier} = __props`);
  30608. }
  30609. if (emitIdentifier) {
  30610. args +=
  30611. emitIdentifier === `emit` ? `, { emit }` : `, { emit: ${emitIdentifier} }`;
  30612. if (emitTypeDecl) {
  30613. args += `: {
  30614. emit: (${scriptSetup.content.slice(emitTypeDecl.start, emitTypeDecl.end)}),
  30615. slots: any,
  30616. attrs: any
  30617. }`;
  30618. }
  30619. }
  30620. // 10. generate return statement
  30621. let returned;
  30622. if (options.inlineTemplate) {
  30623. if (sfc.template && !sfc.template.src) {
  30624. if (options.templateOptions && options.templateOptions.ssr) {
  30625. hasInlinedSsrRenderFn = true;
  30626. }
  30627. // inline render function mode - we are going to compile the template and
  30628. // inline it right here
  30629. const { code, ast, preamble, tips, errors } = compileTemplate({
  30630. filename,
  30631. source: sfc.template.content,
  30632. inMap: sfc.template.map,
  30633. ...options.templateOptions,
  30634. id: scopeId,
  30635. scoped: sfc.styles.some(s => s.scoped),
  30636. isProd: options.isProd,
  30637. ssrCssVars: sfc.cssVars,
  30638. compilerOptions: {
  30639. ...(options.templateOptions &&
  30640. options.templateOptions.compilerOptions),
  30641. inline: true,
  30642. isTS,
  30643. bindingMetadata
  30644. }
  30645. });
  30646. if (tips.length) {
  30647. tips.forEach(warnOnce);
  30648. }
  30649. const err = errors[0];
  30650. if (typeof err === 'string') {
  30651. throw new Error(err);
  30652. }
  30653. else if (err) {
  30654. if (err.loc) {
  30655. err.message +=
  30656. `\n\n` +
  30657. sfc.filename +
  30658. '\n' +
  30659. generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
  30660. `\n`;
  30661. }
  30662. throw err;
  30663. }
  30664. if (preamble) {
  30665. s.prepend(preamble);
  30666. }
  30667. // avoid duplicated unref import
  30668. // as this may get injected by the render function preamble OR the
  30669. // css vars codegen
  30670. if (ast && ast.helpers.includes(UNREF)) {
  30671. helperImports.delete('unref');
  30672. }
  30673. returned = code;
  30674. }
  30675. else {
  30676. returned = `() => {}`;
  30677. }
  30678. }
  30679. else {
  30680. // return bindings from setup
  30681. const allBindings = { ...setupBindings };
  30682. for (const key in userImports) {
  30683. if (!userImports[key].isType) {
  30684. allBindings[key] = true;
  30685. }
  30686. }
  30687. returned = `{ ${Object.keys(allBindings).join(', ')} }`;
  30688. }
  30689. s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
  30690. // 11. finalize default export
  30691. // expose: [] makes <script setup> components "closed" by default.
  30692. let runtimeOptions = `\n expose: [],`;
  30693. if (hasInheritAttrsFlag) {
  30694. runtimeOptions += `\n inheritAttrs: false,`;
  30695. }
  30696. if (hasInlinedSsrRenderFn) {
  30697. runtimeOptions += `\n __ssrInlineRender: true,`;
  30698. }
  30699. if (propsRuntimeDecl) {
  30700. runtimeOptions += `\n props: ${scriptSetup.content
  30701. .slice(propsRuntimeDecl.start, propsRuntimeDecl.end)
  30702. .trim()},`;
  30703. }
  30704. else if (propsTypeDecl) {
  30705. runtimeOptions += genRuntimeProps(typeDeclaredProps);
  30706. }
  30707. if (emitRuntimeDecl) {
  30708. runtimeOptions += `\n emits: ${scriptSetup.content
  30709. .slice(emitRuntimeDecl.start, emitRuntimeDecl.end)
  30710. .trim()},`;
  30711. }
  30712. else if (emitTypeDecl) {
  30713. runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
  30714. }
  30715. if (isTS) {
  30716. // for TS, make sure the exported type is still valid type with
  30717. // correct props information
  30718. // we have to use object spread for types to be merged properly
  30719. // user's TS setting should compile it down to proper targets
  30720. const def = defaultExport ? `\n ...${defaultTempVar},` : ``;
  30721. // wrap setup code with function.
  30722. // export the content of <script setup> as a named export, `setup`.
  30723. // this allows `import { setup } from '*.vue'` for testing purposes.
  30724. s.prependLeft(startOffset, `\nexport default ${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n`);
  30725. s.appendRight(endOffset, `})`);
  30726. }
  30727. else {
  30728. if (defaultExport) {
  30729. // can't rely on spread operator in non ts mode
  30730. s.prependLeft(startOffset, `\n${hasAwait ? `async ` : ``}function setup(${args}) {\n`);
  30731. s.append(`\nexport default /*#__PURE__*/ Object.assign(${defaultTempVar}, {${runtimeOptions}\n setup\n})\n`);
  30732. }
  30733. else {
  30734. s.prependLeft(startOffset, `\nexport default {${runtimeOptions}\n ` +
  30735. `${hasAwait ? `async ` : ``}setup(${args}) {\n`);
  30736. s.appendRight(endOffset, `}`);
  30737. }
  30738. }
  30739. // 12. finalize Vue helper imports
  30740. if (helperImports.size > 0) {
  30741. s.prepend(`import { ${[...helperImports]
  30742. .map(h => `${h} as _${h}`)
  30743. .join(', ')} } from 'vue'\n`);
  30744. }
  30745. s.trim();
  30746. return {
  30747. ...scriptSetup,
  30748. bindings: bindingMetadata,
  30749. content: s.toString(),
  30750. map: s.generateMap({
  30751. source: filename,
  30752. hires: true,
  30753. includeContent: true
  30754. }),
  30755. scriptAst,
  30756. scriptSetupAst
  30757. };
  30758. }
  30759. function walkDeclaration(node, bindings, userImportAlias) {
  30760. if (node.type === 'VariableDeclaration') {
  30761. const isConst = node.kind === 'const';
  30762. // export const foo = ...
  30763. for (const { id, init } of node.declarations) {
  30764. const isDefineCall = !!(isConst &&
  30765. (isCallOf(init, DEFINE_PROPS) || isCallOf(init, DEFINE_EMIT)));
  30766. if (id.type === 'Identifier') {
  30767. let bindingType;
  30768. const userReactiveBinding = userImportAlias['reactive'] || 'reactive';
  30769. if (isCallOf(init, userReactiveBinding)) {
  30770. // treat reactive() calls as let since it's meant to be mutable
  30771. bindingType = "setup-let" /* SETUP_LET */;
  30772. }
  30773. else if (
  30774. // if a declaration is a const literal, we can mark it so that
  30775. // the generated render fn code doesn't need to unref() it
  30776. isDefineCall ||
  30777. (isConst && canNeverBeRef(init, userReactiveBinding))) {
  30778. bindingType = "setup-const" /* SETUP_CONST */;
  30779. }
  30780. else if (isConst) {
  30781. if (isCallOf(init, userImportAlias['ref'] || 'ref')) {
  30782. bindingType = "setup-ref" /* SETUP_REF */;
  30783. }
  30784. else {
  30785. bindingType = "setup-maybe-ref" /* SETUP_MAYBE_REF */;
  30786. }
  30787. }
  30788. else {
  30789. bindingType = "setup-let" /* SETUP_LET */;
  30790. }
  30791. bindings[id.name] = bindingType;
  30792. }
  30793. else if (id.type === 'ObjectPattern') {
  30794. walkObjectPattern(id, bindings, isConst, isDefineCall);
  30795. }
  30796. else if (id.type === 'ArrayPattern') {
  30797. walkArrayPattern(id, bindings, isConst, isDefineCall);
  30798. }
  30799. }
  30800. }
  30801. else if (node.type === 'FunctionDeclaration' ||
  30802. node.type === 'ClassDeclaration') {
  30803. // export function foo() {} / export class Foo {}
  30804. // export declarations must be named.
  30805. bindings[node.id.name] = "setup-const" /* SETUP_CONST */;
  30806. }
  30807. }
  30808. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  30809. for (const p of node.properties) {
  30810. if (p.type === 'ObjectProperty') {
  30811. // key can only be Identifier in ObjectPattern
  30812. if (p.key.type === 'Identifier') {
  30813. if (p.key === p.value) {
  30814. // const { x } = ...
  30815. bindings[p.key.name] = isDefineCall
  30816. ? "setup-const" /* SETUP_CONST */
  30817. : isConst
  30818. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  30819. : "setup-let" /* SETUP_LET */;
  30820. }
  30821. else {
  30822. walkPattern(p.value, bindings, isConst, isDefineCall);
  30823. }
  30824. }
  30825. }
  30826. else {
  30827. // ...rest
  30828. // argument can only be identifer when destructuring
  30829. bindings[p.argument.name] = isConst
  30830. ? "setup-const" /* SETUP_CONST */
  30831. : "setup-let" /* SETUP_LET */;
  30832. }
  30833. }
  30834. }
  30835. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  30836. for (const e of node.elements) {
  30837. e && walkPattern(e, bindings, isConst, isDefineCall);
  30838. }
  30839. }
  30840. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  30841. if (node.type === 'Identifier') {
  30842. bindings[node.name] = isDefineCall
  30843. ? "setup-const" /* SETUP_CONST */
  30844. : isConst
  30845. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  30846. : "setup-let" /* SETUP_LET */;
  30847. }
  30848. else if (node.type === 'RestElement') {
  30849. // argument can only be identifer when destructuring
  30850. bindings[node.argument.name] = isConst
  30851. ? "setup-const" /* SETUP_CONST */
  30852. : "setup-let" /* SETUP_LET */;
  30853. }
  30854. else if (node.type === 'ObjectPattern') {
  30855. walkObjectPattern(node, bindings, isConst);
  30856. }
  30857. else if (node.type === 'ArrayPattern') {
  30858. walkArrayPattern(node, bindings, isConst);
  30859. }
  30860. else if (node.type === 'AssignmentPattern') {
  30861. if (node.left.type === 'Identifier') {
  30862. bindings[node.left.name] = isDefineCall
  30863. ? "setup-const" /* SETUP_CONST */
  30864. : isConst
  30865. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  30866. : "setup-let" /* SETUP_LET */;
  30867. }
  30868. else {
  30869. walkPattern(node.left, bindings, isConst);
  30870. }
  30871. }
  30872. }
  30873. function recordType(node, declaredTypes) {
  30874. if (node.type === 'TSInterfaceDeclaration') {
  30875. declaredTypes[node.id.name] = [`Object`];
  30876. }
  30877. else if (node.type === 'TSTypeAliasDeclaration') {
  30878. declaredTypes[node.id.name] = inferRuntimeType(node.typeAnnotation, declaredTypes);
  30879. }
  30880. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  30881. recordType(node.declaration, declaredTypes);
  30882. }
  30883. }
  30884. function extractRuntimeProps(node, props, declaredTypes) {
  30885. for (const m of node.members) {
  30886. if (m.type === 'TSPropertySignature' && m.key.type === 'Identifier') {
  30887. props[m.key.name] = {
  30888. key: m.key.name,
  30889. required: !m.optional,
  30890. type: m.typeAnnotation
  30891. ? inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes)
  30892. : [`null`]
  30893. };
  30894. }
  30895. }
  30896. }
  30897. function inferRuntimeType(node, declaredTypes) {
  30898. switch (node.type) {
  30899. case 'TSStringKeyword':
  30900. return ['String'];
  30901. case 'TSNumberKeyword':
  30902. return ['Number'];
  30903. case 'TSBooleanKeyword':
  30904. return ['Boolean'];
  30905. case 'TSObjectKeyword':
  30906. return ['Object'];
  30907. case 'TSTypeLiteral':
  30908. // TODO (nice to have) generate runtime property validation
  30909. return ['Object'];
  30910. case 'TSFunctionType':
  30911. return ['Function'];
  30912. case 'TSArrayType':
  30913. case 'TSTupleType':
  30914. // TODO (nice to have) generate runtime element type/length checks
  30915. return ['Array'];
  30916. case 'TSLiteralType':
  30917. switch (node.literal.type) {
  30918. case 'StringLiteral':
  30919. return ['String'];
  30920. case 'BooleanLiteral':
  30921. return ['Boolean'];
  30922. case 'NumericLiteral':
  30923. case 'BigIntLiteral':
  30924. return ['Number'];
  30925. default:
  30926. return [`null`];
  30927. }
  30928. case 'TSTypeReference':
  30929. if (node.typeName.type === 'Identifier') {
  30930. if (declaredTypes[node.typeName.name]) {
  30931. return declaredTypes[node.typeName.name];
  30932. }
  30933. switch (node.typeName.name) {
  30934. case 'Array':
  30935. case 'Function':
  30936. case 'Object':
  30937. case 'Set':
  30938. case 'Map':
  30939. case 'WeakSet':
  30940. case 'WeakMap':
  30941. return [node.typeName.name];
  30942. case 'Record':
  30943. case 'Partial':
  30944. case 'Readonly':
  30945. case 'Pick':
  30946. case 'Omit':
  30947. case 'Exclude':
  30948. case 'Extract':
  30949. case 'Required':
  30950. case 'InstanceType':
  30951. return ['Object'];
  30952. }
  30953. }
  30954. return [`null`];
  30955. case 'TSUnionType':
  30956. return [
  30957. ...new Set([].concat(node.types.map(t => inferRuntimeType(t, declaredTypes))))
  30958. ];
  30959. case 'TSIntersectionType':
  30960. return ['Object'];
  30961. default:
  30962. return [`null`]; // no runtime check
  30963. }
  30964. }
  30965. function genRuntimeProps(props) {
  30966. const keys = Object.keys(props);
  30967. if (!keys.length) {
  30968. return ``;
  30969. }
  30970. return `\n props: {\n ${keys
  30971. .map(key => {
  30972. const { type, required } = props[key];
  30973. return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required} }`;
  30974. })
  30975. .join(',\n ')}\n } as unknown as undefined,`;
  30976. }
  30977. function toRuntimeTypeString(types) {
  30978. return types.some(t => t === 'null')
  30979. ? `null`
  30980. : types.length > 1
  30981. ? `[${types.join(', ')}]`
  30982. : types[0];
  30983. }
  30984. function extractRuntimeEmits(node, emits) {
  30985. if (node.type === 'TSUnionType') {
  30986. for (let t of node.types) {
  30987. if (t.type === 'TSParenthesizedType')
  30988. t = t.typeAnnotation;
  30989. if (t.type === 'TSFunctionType') {
  30990. extractRuntimeEmits(t, emits);
  30991. }
  30992. }
  30993. return;
  30994. }
  30995. const eventName = node.parameters[0];
  30996. if (eventName.type === 'Identifier' &&
  30997. eventName.typeAnnotation &&
  30998. eventName.typeAnnotation.type === 'TSTypeAnnotation') {
  30999. const typeNode = eventName.typeAnnotation.typeAnnotation;
  31000. if (typeNode.type === 'TSLiteralType') {
  31001. emits.add(String(typeNode.literal.value));
  31002. }
  31003. else if (typeNode.type === 'TSUnionType') {
  31004. for (const t of typeNode.types) {
  31005. if (t.type === 'TSLiteralType') {
  31006. emits.add(String(t.literal.value));
  31007. }
  31008. }
  31009. }
  31010. }
  31011. }
  31012. function genRuntimeEmits(emits) {
  31013. return emits.size
  31014. ? `\n emits: [${Array.from(emits)
  31015. .map(p => JSON.stringify(p))
  31016. .join(', ')}] as unknown as undefined,`
  31017. : ``;
  31018. }
  31019. /**
  31020. * Walk an AST and find identifiers that are variable references.
  31021. * This is largely the same logic with `transformExpressions` in compiler-core
  31022. * but with some subtle differences as this needs to handle a wider range of
  31023. * possible syntax.
  31024. */
  31025. function walkIdentifiers(root, onIdentifier) {
  31026. const parentStack = [];
  31027. const knownIds = Object.create(null);
  31028. walk$1(root, {
  31029. enter(node, parent) {
  31030. parent && parentStack.push(parent);
  31031. if (node.type === 'Identifier') {
  31032. if (!knownIds[node.name] &&
  31033. isRefIdentifier(node, parent, parentStack)) {
  31034. onIdentifier(node, parent, parentStack);
  31035. }
  31036. }
  31037. else if (isFunction$2(node)) {
  31038. // walk function expressions and add its arguments to known identifiers
  31039. // so that we don't prefix them
  31040. node.params.forEach(p => walk$1(p, {
  31041. enter(child, parent) {
  31042. if (child.type === 'Identifier' &&
  31043. // do not record as scope variable if is a destructured key
  31044. !isStaticPropertyKey$1(child, parent) &&
  31045. // do not record if this is a default value
  31046. // assignment of a destructured variable
  31047. !(parent &&
  31048. parent.type === 'AssignmentPattern' &&
  31049. parent.right === child)) {
  31050. const { name } = child;
  31051. if (node.scopeIds && node.scopeIds.has(name)) {
  31052. return;
  31053. }
  31054. if (name in knownIds) {
  31055. knownIds[name]++;
  31056. }
  31057. else {
  31058. knownIds[name] = 1;
  31059. }
  31060. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  31061. }
  31062. }
  31063. }));
  31064. }
  31065. else if (node.type === 'ObjectProperty' &&
  31066. parent.type === 'ObjectPattern') {
  31067. node.inPattern = true;
  31068. }
  31069. },
  31070. leave(node, parent) {
  31071. parent && parentStack.pop();
  31072. if (node.scopeIds) {
  31073. node.scopeIds.forEach((id) => {
  31074. knownIds[id]--;
  31075. if (knownIds[id] === 0) {
  31076. delete knownIds[id];
  31077. }
  31078. });
  31079. }
  31080. }
  31081. });
  31082. }
  31083. function isRefIdentifier(id, parent, parentStack) {
  31084. // declaration id
  31085. if ((parent.type === 'VariableDeclarator' ||
  31086. parent.type === 'ClassDeclaration') &&
  31087. parent.id === id) {
  31088. return false;
  31089. }
  31090. if (isFunction$2(parent)) {
  31091. // function decalration/expression id
  31092. if (parent.id === id) {
  31093. return false;
  31094. }
  31095. // params list
  31096. if (parent.params.includes(id)) {
  31097. return false;
  31098. }
  31099. }
  31100. // property key
  31101. // this also covers object destructure pattern
  31102. if (isStaticPropertyKey$1(id, parent)) {
  31103. return false;
  31104. }
  31105. // non-assignment array destructure pattern
  31106. if (parent.type === 'ArrayPattern' &&
  31107. !isInDestructureAssignment$1(parent, parentStack)) {
  31108. return false;
  31109. }
  31110. // member expression property
  31111. if ((parent.type === 'MemberExpression' ||
  31112. parent.type === 'OptionalMemberExpression') &&
  31113. parent.property === id &&
  31114. !parent.computed) {
  31115. return false;
  31116. }
  31117. // is a special keyword but parsed as identifier
  31118. if (id.name === 'arguments') {
  31119. return false;
  31120. }
  31121. return true;
  31122. }
  31123. const isStaticProperty$1 = (node) => node &&
  31124. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  31125. !node.computed;
  31126. const isStaticPropertyKey$1 = (node, parent) => isStaticProperty$1(parent) && parent.key === node;
  31127. function isFunction$2(node) {
  31128. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  31129. }
  31130. function isCallOf(node, name) {
  31131. return !!(node &&
  31132. node.type === 'CallExpression' &&
  31133. node.callee.type === 'Identifier' &&
  31134. node.callee.name === name);
  31135. }
  31136. function canNeverBeRef(node, userReactiveImport) {
  31137. if (isCallOf(node, userReactiveImport)) {
  31138. return true;
  31139. }
  31140. switch (node.type) {
  31141. case 'UnaryExpression':
  31142. case 'BinaryExpression':
  31143. case 'ArrayExpression':
  31144. case 'ObjectExpression':
  31145. case 'FunctionExpression':
  31146. case 'ArrowFunctionExpression':
  31147. case 'UpdateExpression':
  31148. case 'ClassExpression':
  31149. case 'TaggedTemplateExpression':
  31150. return true;
  31151. case 'SequenceExpression':
  31152. return canNeverBeRef(node.expressions[node.expressions.length - 1], userReactiveImport);
  31153. default:
  31154. if (node.type.endsWith('Literal')) {
  31155. return true;
  31156. }
  31157. return false;
  31158. }
  31159. }
  31160. function isInDestructureAssignment$1(parent, parentStack) {
  31161. if (parent &&
  31162. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  31163. let i = parentStack.length;
  31164. while (i--) {
  31165. const p = parentStack[i];
  31166. if (p.type === 'AssignmentExpression') {
  31167. const root = parentStack[0];
  31168. // if this is a ref: destructure, it should be treated like a
  31169. // variable decalration!
  31170. return !(root.type === 'LabeledStatement' && root.label.name === 'ref');
  31171. }
  31172. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  31173. break;
  31174. }
  31175. }
  31176. }
  31177. return false;
  31178. }
  31179. /**
  31180. * Analyze bindings in normal `<script>`
  31181. * Note that `compileScriptSetup` already analyzes bindings as part of its
  31182. * compilation process so this should only be used on single `<script>` SFCs.
  31183. */
  31184. function analyzeScriptBindings(ast) {
  31185. for (const node of ast) {
  31186. if (node.type === 'ExportDefaultDeclaration' &&
  31187. node.declaration.type === 'ObjectExpression') {
  31188. return analyzeBindingsFromOptions(node.declaration);
  31189. }
  31190. }
  31191. return {};
  31192. }
  31193. function analyzeBindingsFromOptions(node) {
  31194. const bindings = {};
  31195. for (const property of node.properties) {
  31196. if (property.type === 'ObjectProperty' &&
  31197. !property.computed &&
  31198. property.key.type === 'Identifier') {
  31199. // props
  31200. if (property.key.name === 'props') {
  31201. // props: ['foo']
  31202. // props: { foo: ... }
  31203. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  31204. bindings[key] = "props" /* PROPS */;
  31205. }
  31206. }
  31207. // inject
  31208. else if (property.key.name === 'inject') {
  31209. // inject: ['foo']
  31210. // inject: { foo: {} }
  31211. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  31212. bindings[key] = "options" /* OPTIONS */;
  31213. }
  31214. }
  31215. // computed & methods
  31216. else if (property.value.type === 'ObjectExpression' &&
  31217. (property.key.name === 'computed' || property.key.name === 'methods')) {
  31218. // methods: { foo() {} }
  31219. // computed: { foo() {} }
  31220. for (const key of getObjectExpressionKeys(property.value)) {
  31221. bindings[key] = "options" /* OPTIONS */;
  31222. }
  31223. }
  31224. }
  31225. // setup & data
  31226. else if (property.type === 'ObjectMethod' &&
  31227. property.key.type === 'Identifier' &&
  31228. (property.key.name === 'setup' || property.key.name === 'data')) {
  31229. for (const bodyItem of property.body.body) {
  31230. // setup() {
  31231. // return {
  31232. // foo: null
  31233. // }
  31234. // }
  31235. if (bodyItem.type === 'ReturnStatement' &&
  31236. bodyItem.argument &&
  31237. bodyItem.argument.type === 'ObjectExpression') {
  31238. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  31239. bindings[key] =
  31240. property.key.name === 'setup'
  31241. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  31242. : "data" /* DATA */;
  31243. }
  31244. }
  31245. }
  31246. }
  31247. }
  31248. return bindings;
  31249. }
  31250. function getObjectExpressionKeys(node) {
  31251. const keys = [];
  31252. for (const prop of node.properties) {
  31253. if ((prop.type === 'ObjectProperty' || prop.type === 'ObjectMethod') &&
  31254. !prop.computed) {
  31255. if (prop.key.type === 'Identifier') {
  31256. keys.push(prop.key.name);
  31257. }
  31258. else if (prop.key.type === 'StringLiteral') {
  31259. keys.push(prop.key.value);
  31260. }
  31261. }
  31262. }
  31263. return keys;
  31264. }
  31265. function getArrayExpressionKeys(node) {
  31266. const keys = [];
  31267. for (const element of node.elements) {
  31268. if (element && element.type === 'StringLiteral') {
  31269. keys.push(element.value);
  31270. }
  31271. }
  31272. return keys;
  31273. }
  31274. function getObjectOrArrayExpressionKeys(value) {
  31275. if (value.type === 'ArrayExpression') {
  31276. return getArrayExpressionKeys(value);
  31277. }
  31278. if (value.type === 'ObjectExpression') {
  31279. return getObjectExpressionKeys(value);
  31280. }
  31281. return [];
  31282. }
  31283. exports.compileScript = compileScript;
  31284. exports.compileStyle = compileStyle;
  31285. exports.compileStyleAsync = compileStyleAsync;
  31286. exports.compileTemplate = compileTemplate;
  31287. exports.generateCodeFrame = generateCodeFrame;
  31288. exports.parse = parse$2;
  31289. exports.rewriteDefault = rewriteDefault;
  31290. Object.defineProperty(exports, '__esModule', { value: true });
  31291. return exports;
  31292. }({}, path, url, postcss, require$$0));