compiler-sfc.global.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666
  1. var VueCompilerSFC = (function (exports, postcss, path, url, require$$0) {
  2. 'use strict';
  3. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
  4. var postcss__default = /*#__PURE__*/_interopDefaultLegacy(postcss);
  5. var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
  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';
  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. res += normalizeClass(value[i]) + ' ';
  210. }
  211. }
  212. else if (isObject(value)) {
  213. for (const name in value) {
  214. if (value[name]) {
  215. res += name + ' ';
  216. }
  217. }
  218. }
  219. return res.trim();
  220. }
  221. // These tag configs are shared between compiler-dom and runtime-dom, so they
  222. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  223. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  224. 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
  225. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  226. 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
  227. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  228. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  229. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  230. 'option,output,progress,select,textarea,details,dialog,menu,' +
  231. 'summary,template,blockquote,iframe,tfoot';
  232. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  233. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  234. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  235. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  236. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  237. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  238. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  239. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  240. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  241. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  242. 'text,textPath,title,tspan,unknown,use,view';
  243. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  244. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  245. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  246. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  247. const escapeRE = /["'&<>]/;
  248. function escapeHtml(string) {
  249. const str = '' + string;
  250. const match = escapeRE.exec(str);
  251. if (!match) {
  252. return str;
  253. }
  254. let html = '';
  255. let escaped;
  256. let index;
  257. let lastIndex = 0;
  258. for (index = match.index; index < str.length; index++) {
  259. switch (str.charCodeAt(index)) {
  260. case 34: // "
  261. escaped = '&quot;';
  262. break;
  263. case 38: // &
  264. escaped = '&amp;';
  265. break;
  266. case 39: // '
  267. escaped = '&#39;';
  268. break;
  269. case 60: // <
  270. escaped = '&lt;';
  271. break;
  272. case 62: // >
  273. escaped = '&gt;';
  274. break;
  275. default:
  276. continue;
  277. }
  278. if (lastIndex !== index) {
  279. html += str.substring(lastIndex, index);
  280. }
  281. lastIndex = index + 1;
  282. html += escaped;
  283. }
  284. return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
  285. }
  286. /**
  287. * For converting {{ interpolation }} values to displayed strings.
  288. * @private
  289. */
  290. const toDisplayString = (val) => {
  291. return val == null
  292. ? ''
  293. : isObject(val)
  294. ? JSON.stringify(val, replacer, 2)
  295. : String(val);
  296. };
  297. const replacer = (_key, val) => {
  298. if (isMap(val)) {
  299. return {
  300. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  301. entries[`${key} =>`] = val;
  302. return entries;
  303. }, {})
  304. };
  305. }
  306. else if (isSet(val)) {
  307. return {
  308. [`Set(${val.size})`]: [...val.values()]
  309. };
  310. }
  311. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  312. return String(val);
  313. }
  314. return val;
  315. };
  316. /**
  317. * List of @babel/parser plugins that are used for template expression
  318. * transforms and SFC script transforms. By default we enable proposals slated
  319. * for ES2020. This will need to be updated as the spec moves forward.
  320. * Full list at https://babeljs.io/docs/en/next/babel-parser#plugins
  321. */
  322. const babelParserDefaultPlugins = [
  323. 'bigInt',
  324. 'optionalChaining',
  325. 'nullishCoalescingOperator'
  326. ];
  327. const EMPTY_OBJ = Object.freeze({})
  328. ;
  329. const EMPTY_ARR = Object.freeze([]) ;
  330. const NOOP = () => { };
  331. /**
  332. * Always return false.
  333. */
  334. const NO = () => false;
  335. const onRE = /^on[^a-z]/;
  336. const isOn = (key) => onRE.test(key);
  337. const extend = Object.assign;
  338. const hasOwnProperty = Object.prototype.hasOwnProperty;
  339. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  340. const isArray = Array.isArray;
  341. const isMap = (val) => toTypeString(val) === '[object Map]';
  342. const isSet = (val) => toTypeString(val) === '[object Set]';
  343. const isFunction = (val) => typeof val === 'function';
  344. const isString = (val) => typeof val === 'string';
  345. const isSymbol = (val) => typeof val === 'symbol';
  346. const isObject = (val) => val !== null && typeof val === 'object';
  347. const objectToString = Object.prototype.toString;
  348. const toTypeString = (value) => objectToString.call(value);
  349. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  350. const isReservedProp = /*#__PURE__*/ makeMap(
  351. // the leading comma is intentional so empty string "" is also included
  352. ',key,ref,' +
  353. 'onVnodeBeforeMount,onVnodeMounted,' +
  354. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  355. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  356. const cacheStringFunction = (fn) => {
  357. const cache = Object.create(null);
  358. return ((str) => {
  359. const hit = cache[str];
  360. return hit || (cache[str] = fn(str));
  361. });
  362. };
  363. const camelizeRE = /-(\w)/g;
  364. /**
  365. * @private
  366. */
  367. const camelize = cacheStringFunction((str) => {
  368. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  369. });
  370. const hyphenateRE = /\B([A-Z])/g;
  371. /**
  372. * @private
  373. */
  374. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  375. /**
  376. * @private
  377. */
  378. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  379. /**
  380. * @private
  381. */
  382. const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
  383. function defaultOnError(error) {
  384. throw error;
  385. }
  386. function createCompilerError(code, loc, messages, additionalMessage) {
  387. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  388. ;
  389. const error = new SyntaxError(String(msg));
  390. error.code = code;
  391. error.loc = loc;
  392. return error;
  393. }
  394. const errorMessages = {
  395. // parse errors
  396. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  397. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  398. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  399. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  400. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  401. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  402. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  403. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  404. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  405. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  406. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  407. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  408. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  409. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  410. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  411. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  412. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  413. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  414. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  415. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  416. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  417. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  418. // Vue-specific parse errors
  419. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  420. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  421. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  422. [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  423. 'Note that dynamic directive argument cannot contain spaces.',
  424. // transform errors
  425. [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  426. [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  427. [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
  428. [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  429. [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  430. [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  431. [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  432. [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  433. [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  434. [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  435. `When there are multiple named slots, all slots should use <template> ` +
  436. `syntax to avoid scope ambiguity.`,
  437. [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  438. [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  439. `default slot. These children will be ignored.`,
  440. [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  441. [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  442. [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  443. [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.`,
  444. [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  445. [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  446. // generic errors
  447. [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  448. [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  449. [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  450. [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
  451. };
  452. const FRAGMENT = Symbol( `Fragment` );
  453. const TELEPORT = Symbol( `Teleport` );
  454. const SUSPENSE = Symbol( `Suspense` );
  455. const KEEP_ALIVE = Symbol( `KeepAlive` );
  456. const BASE_TRANSITION = Symbol( `BaseTransition` );
  457. const OPEN_BLOCK = Symbol( `openBlock` );
  458. const CREATE_BLOCK = Symbol( `createBlock` );
  459. const CREATE_VNODE = Symbol( `createVNode` );
  460. const CREATE_COMMENT = Symbol( `createCommentVNode` );
  461. const CREATE_TEXT = Symbol( `createTextVNode` );
  462. const CREATE_STATIC = Symbol( `createStaticVNode` );
  463. const RESOLVE_COMPONENT = Symbol( `resolveComponent` );
  464. const RESOLVE_DYNAMIC_COMPONENT = Symbol( `resolveDynamicComponent` );
  465. const RESOLVE_DIRECTIVE = Symbol( `resolveDirective` );
  466. const WITH_DIRECTIVES = Symbol( `withDirectives` );
  467. const RENDER_LIST = Symbol( `renderList` );
  468. const RENDER_SLOT = Symbol( `renderSlot` );
  469. const CREATE_SLOTS = Symbol( `createSlots` );
  470. const TO_DISPLAY_STRING = Symbol( `toDisplayString` );
  471. const MERGE_PROPS = Symbol( `mergeProps` );
  472. const TO_HANDLERS = Symbol( `toHandlers` );
  473. const CAMELIZE = Symbol( `camelize` );
  474. const CAPITALIZE = Symbol( `capitalize` );
  475. const TO_HANDLER_KEY = Symbol( `toHandlerKey` );
  476. const SET_BLOCK_TRACKING = Symbol( `setBlockTracking` );
  477. const PUSH_SCOPE_ID = Symbol( `pushScopeId` );
  478. const POP_SCOPE_ID = Symbol( `popScopeId` );
  479. const WITH_SCOPE_ID = Symbol( `withScopeId` );
  480. const WITH_CTX = Symbol( `withCtx` );
  481. const UNREF = Symbol( `unref` );
  482. const IS_REF = Symbol( `isRef` );
  483. // Name mapping for runtime helpers that need to be imported from 'vue' in
  484. // generated code. Make sure these are correctly exported in the runtime!
  485. // Using `any` here because TS doesn't allow symbols as index type.
  486. const helperNameMap = {
  487. [FRAGMENT]: `Fragment`,
  488. [TELEPORT]: `Teleport`,
  489. [SUSPENSE]: `Suspense`,
  490. [KEEP_ALIVE]: `KeepAlive`,
  491. [BASE_TRANSITION]: `BaseTransition`,
  492. [OPEN_BLOCK]: `openBlock`,
  493. [CREATE_BLOCK]: `createBlock`,
  494. [CREATE_VNODE]: `createVNode`,
  495. [CREATE_COMMENT]: `createCommentVNode`,
  496. [CREATE_TEXT]: `createTextVNode`,
  497. [CREATE_STATIC]: `createStaticVNode`,
  498. [RESOLVE_COMPONENT]: `resolveComponent`,
  499. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  500. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  501. [WITH_DIRECTIVES]: `withDirectives`,
  502. [RENDER_LIST]: `renderList`,
  503. [RENDER_SLOT]: `renderSlot`,
  504. [CREATE_SLOTS]: `createSlots`,
  505. [TO_DISPLAY_STRING]: `toDisplayString`,
  506. [MERGE_PROPS]: `mergeProps`,
  507. [TO_HANDLERS]: `toHandlers`,
  508. [CAMELIZE]: `camelize`,
  509. [CAPITALIZE]: `capitalize`,
  510. [TO_HANDLER_KEY]: `toHandlerKey`,
  511. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  512. [PUSH_SCOPE_ID]: `pushScopeId`,
  513. [POP_SCOPE_ID]: `popScopeId`,
  514. [WITH_SCOPE_ID]: `withScopeId`,
  515. [WITH_CTX]: `withCtx`,
  516. [UNREF]: `unref`,
  517. [IS_REF]: `isRef`
  518. };
  519. function registerRuntimeHelpers(helpers) {
  520. Object.getOwnPropertySymbols(helpers).forEach(s => {
  521. helperNameMap[s] = helpers[s];
  522. });
  523. }
  524. // AST Utilities ---------------------------------------------------------------
  525. // Some expressions, e.g. sequence and conditional expressions, are never
  526. // associated with template nodes, so their source locations are just a stub.
  527. // Container types like CompoundExpression also don't need a real location.
  528. const locStub = {
  529. source: '',
  530. start: { line: 1, column: 1, offset: 0 },
  531. end: { line: 1, column: 1, offset: 0 }
  532. };
  533. function createRoot(children, loc = locStub) {
  534. return {
  535. type: 0 /* ROOT */,
  536. children,
  537. helpers: [],
  538. components: [],
  539. directives: [],
  540. hoists: [],
  541. imports: [],
  542. cached: 0,
  543. temps: 0,
  544. codegenNode: undefined,
  545. loc
  546. };
  547. }
  548. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
  549. if (context) {
  550. if (isBlock) {
  551. context.helper(OPEN_BLOCK);
  552. context.helper(CREATE_BLOCK);
  553. }
  554. else {
  555. context.helper(CREATE_VNODE);
  556. }
  557. if (directives) {
  558. context.helper(WITH_DIRECTIVES);
  559. }
  560. }
  561. return {
  562. type: 13 /* VNODE_CALL */,
  563. tag,
  564. props,
  565. children,
  566. patchFlag,
  567. dynamicProps,
  568. directives,
  569. isBlock,
  570. disableTracking,
  571. loc
  572. };
  573. }
  574. function createArrayExpression(elements, loc = locStub) {
  575. return {
  576. type: 17 /* JS_ARRAY_EXPRESSION */,
  577. loc,
  578. elements
  579. };
  580. }
  581. function createObjectExpression(properties, loc = locStub) {
  582. return {
  583. type: 15 /* JS_OBJECT_EXPRESSION */,
  584. loc,
  585. properties
  586. };
  587. }
  588. function createObjectProperty(key, value) {
  589. return {
  590. type: 16 /* JS_PROPERTY */,
  591. loc: locStub,
  592. key: isString(key) ? createSimpleExpression(key, true) : key,
  593. value
  594. };
  595. }
  596. function createSimpleExpression(content, isStatic, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
  597. return {
  598. type: 4 /* SIMPLE_EXPRESSION */,
  599. loc,
  600. content,
  601. isStatic,
  602. constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
  603. };
  604. }
  605. function createInterpolation(content, loc) {
  606. return {
  607. type: 5 /* INTERPOLATION */,
  608. loc,
  609. content: isString(content)
  610. ? createSimpleExpression(content, false, loc)
  611. : content
  612. };
  613. }
  614. function createCompoundExpression(children, loc = locStub) {
  615. return {
  616. type: 8 /* COMPOUND_EXPRESSION */,
  617. loc,
  618. children
  619. };
  620. }
  621. function createCallExpression(callee, args = [], loc = locStub) {
  622. return {
  623. type: 14 /* JS_CALL_EXPRESSION */,
  624. loc,
  625. callee,
  626. arguments: args
  627. };
  628. }
  629. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  630. return {
  631. type: 18 /* JS_FUNCTION_EXPRESSION */,
  632. params,
  633. returns,
  634. newline,
  635. isSlot,
  636. loc
  637. };
  638. }
  639. function createConditionalExpression(test, consequent, alternate, newline = true) {
  640. return {
  641. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  642. test,
  643. consequent,
  644. alternate,
  645. newline,
  646. loc: locStub
  647. };
  648. }
  649. function createCacheExpression(index, value, isVNode = false) {
  650. return {
  651. type: 20 /* JS_CACHE_EXPRESSION */,
  652. index,
  653. value,
  654. isVNode,
  655. loc: locStub
  656. };
  657. }
  658. function createBlockStatement(body) {
  659. return {
  660. type: 21 /* JS_BLOCK_STATEMENT */,
  661. body,
  662. loc: locStub
  663. };
  664. }
  665. function createTemplateLiteral(elements) {
  666. return {
  667. type: 22 /* JS_TEMPLATE_LITERAL */,
  668. elements,
  669. loc: locStub
  670. };
  671. }
  672. function createIfStatement(test, consequent, alternate) {
  673. return {
  674. type: 23 /* JS_IF_STATEMENT */,
  675. test,
  676. consequent,
  677. alternate,
  678. loc: locStub
  679. };
  680. }
  681. function createAssignmentExpression(left, right) {
  682. return {
  683. type: 24 /* JS_ASSIGNMENT_EXPRESSION */,
  684. left,
  685. right,
  686. loc: locStub
  687. };
  688. }
  689. function createSequenceExpression(expressions) {
  690. return {
  691. type: 25 /* JS_SEQUENCE_EXPRESSION */,
  692. expressions,
  693. loc: locStub
  694. };
  695. }
  696. function createReturnStatement(returns) {
  697. return {
  698. type: 26 /* JS_RETURN_STATEMENT */,
  699. returns,
  700. loc: locStub
  701. };
  702. }
  703. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  704. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  705. function isCoreComponent(tag) {
  706. if (isBuiltInType(tag, 'Teleport')) {
  707. return TELEPORT;
  708. }
  709. else if (isBuiltInType(tag, 'Suspense')) {
  710. return SUSPENSE;
  711. }
  712. else if (isBuiltInType(tag, 'KeepAlive')) {
  713. return KEEP_ALIVE;
  714. }
  715. else if (isBuiltInType(tag, 'BaseTransition')) {
  716. return BASE_TRANSITION;
  717. }
  718. }
  719. const nonIdentifierRE = /^\d|[^\$\w]/;
  720. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  721. const memberExpRE = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]]+\])*$/;
  722. const isMemberExpression = (path) => {
  723. if (!path)
  724. return false;
  725. return memberExpRE.test(path.trim());
  726. };
  727. function getInnerRange(loc, offset, length) {
  728. const source = loc.source.substr(offset, length);
  729. const newLoc = {
  730. source,
  731. start: advancePositionWithClone(loc.start, loc.source, offset),
  732. end: loc.end
  733. };
  734. if (length != null) {
  735. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  736. }
  737. return newLoc;
  738. }
  739. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  740. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  741. }
  742. // advance by mutation without cloning (for performance reasons), since this
  743. // gets called a lot in the parser
  744. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  745. let linesCount = 0;
  746. let lastNewLinePos = -1;
  747. for (let i = 0; i < numberOfCharacters; i++) {
  748. if (source.charCodeAt(i) === 10 /* newline char code */) {
  749. linesCount++;
  750. lastNewLinePos = i;
  751. }
  752. }
  753. pos.offset += numberOfCharacters;
  754. pos.line += linesCount;
  755. pos.column =
  756. lastNewLinePos === -1
  757. ? pos.column + numberOfCharacters
  758. : numberOfCharacters - lastNewLinePos;
  759. return pos;
  760. }
  761. function assert(condition, msg) {
  762. /* istanbul ignore if */
  763. if (!condition) {
  764. throw new Error(msg || `unexpected compiler condition`);
  765. }
  766. }
  767. function findDir(node, name, allowEmpty = false) {
  768. for (let i = 0; i < node.props.length; i++) {
  769. const p = node.props[i];
  770. if (p.type === 7 /* DIRECTIVE */ &&
  771. (allowEmpty || p.exp) &&
  772. (isString(name) ? p.name === name : name.test(p.name))) {
  773. return p;
  774. }
  775. }
  776. }
  777. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  778. for (let i = 0; i < node.props.length; i++) {
  779. const p = node.props[i];
  780. if (p.type === 6 /* ATTRIBUTE */) {
  781. if (dynamicOnly)
  782. continue;
  783. if (p.name === name && (p.value || allowEmpty)) {
  784. return p;
  785. }
  786. }
  787. else if (p.name === 'bind' &&
  788. (p.exp || allowEmpty) &&
  789. isBindKey(p.arg, name)) {
  790. return p;
  791. }
  792. }
  793. }
  794. function isBindKey(arg, name) {
  795. return !!(arg && isStaticExp(arg) && arg.content === name);
  796. }
  797. function hasDynamicKeyVBind(node) {
  798. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  799. p.name === 'bind' &&
  800. (!p.arg || // v-bind="obj"
  801. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  802. !p.arg.isStatic) // v-bind:[foo]
  803. );
  804. }
  805. function isText(node) {
  806. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  807. }
  808. function isVSlot(p) {
  809. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  810. }
  811. function isTemplateNode(node) {
  812. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  813. }
  814. function isSlotOutlet(node) {
  815. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  816. }
  817. function injectProp(node, prop, context) {
  818. let propsWithInjection;
  819. const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  820. if (props == null || isString(props)) {
  821. propsWithInjection = createObjectExpression([prop]);
  822. }
  823. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  824. // merged props... add ours
  825. // only inject key to object literal if it's the first argument so that
  826. // if doesn't override user provided keys
  827. const first = props.arguments[0];
  828. if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  829. first.properties.unshift(prop);
  830. }
  831. else {
  832. if (props.callee === TO_HANDLERS) {
  833. // #2366
  834. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  835. createObjectExpression([prop]),
  836. props
  837. ]);
  838. }
  839. else {
  840. props.arguments.unshift(createObjectExpression([prop]));
  841. }
  842. }
  843. !propsWithInjection && (propsWithInjection = props);
  844. }
  845. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  846. let alreadyExists = false;
  847. // check existing key to avoid overriding user provided keys
  848. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  849. const propKeyName = prop.key.content;
  850. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  851. p.key.content === propKeyName);
  852. }
  853. if (!alreadyExists) {
  854. props.properties.unshift(prop);
  855. }
  856. propsWithInjection = props;
  857. }
  858. else {
  859. // single v-bind with expression, return a merged replacement
  860. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  861. createObjectExpression([prop]),
  862. props
  863. ]);
  864. }
  865. if (node.type === 13 /* VNODE_CALL */) {
  866. node.props = propsWithInjection;
  867. }
  868. else {
  869. node.arguments[2] = propsWithInjection;
  870. }
  871. }
  872. function toValidAssetId(name, type) {
  873. return `_${type}_${name.replace(/[^\w]/g, '_')}`;
  874. }
  875. // Check if a node contains expressions that reference current context scope ids
  876. function hasScopeRef(node, ids) {
  877. if (!node || Object.keys(ids).length === 0) {
  878. return false;
  879. }
  880. switch (node.type) {
  881. case 1 /* ELEMENT */:
  882. for (let i = 0; i < node.props.length; i++) {
  883. const p = node.props[i];
  884. if (p.type === 7 /* DIRECTIVE */ &&
  885. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  886. return true;
  887. }
  888. }
  889. return node.children.some(c => hasScopeRef(c, ids));
  890. case 11 /* FOR */:
  891. if (hasScopeRef(node.source, ids)) {
  892. return true;
  893. }
  894. return node.children.some(c => hasScopeRef(c, ids));
  895. case 9 /* IF */:
  896. return node.branches.some(b => hasScopeRef(b, ids));
  897. case 10 /* IF_BRANCH */:
  898. if (hasScopeRef(node.condition, ids)) {
  899. return true;
  900. }
  901. return node.children.some(c => hasScopeRef(c, ids));
  902. case 4 /* SIMPLE_EXPRESSION */:
  903. return (!node.isStatic &&
  904. isSimpleIdentifier(node.content) &&
  905. !!ids[node.content]);
  906. case 8 /* COMPOUND_EXPRESSION */:
  907. return node.children.some(c => isObject(c) && hasScopeRef(c, ids));
  908. case 5 /* INTERPOLATION */:
  909. case 12 /* TEXT_CALL */:
  910. return hasScopeRef(node.content, ids);
  911. case 2 /* TEXT */:
  912. case 3 /* COMMENT */:
  913. return false;
  914. default:
  915. return false;
  916. }
  917. }
  918. // The default decoder only provides escapes for characters reserved as part of
  919. // the template syntax, and is only used if the custom renderer did not provide
  920. // a platform-specific decoder.
  921. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  922. const decodeMap = {
  923. gt: '>',
  924. lt: '<',
  925. amp: '&',
  926. apos: "'",
  927. quot: '"'
  928. };
  929. const defaultParserOptions = {
  930. delimiters: [`{{`, `}}`],
  931. getNamespace: () => 0 /* HTML */,
  932. getTextMode: () => 0 /* DATA */,
  933. isVoidTag: NO,
  934. isPreTag: NO,
  935. isCustomElement: NO,
  936. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  937. onError: defaultOnError,
  938. comments: false
  939. };
  940. function baseParse(content, options = {}) {
  941. const context = createParserContext(content, options);
  942. const start = getCursor(context);
  943. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  944. }
  945. function createParserContext(content, rawOptions) {
  946. const options = extend({}, defaultParserOptions);
  947. for (const key in rawOptions) {
  948. // @ts-ignore
  949. options[key] = rawOptions[key] || defaultParserOptions[key];
  950. }
  951. return {
  952. options,
  953. column: 1,
  954. line: 1,
  955. offset: 0,
  956. originalSource: content,
  957. source: content,
  958. inPre: false,
  959. inVPre: false
  960. };
  961. }
  962. function parseChildren(context, mode, ancestors) {
  963. const parent = last(ancestors);
  964. const ns = parent ? parent.ns : 0 /* HTML */;
  965. const nodes = [];
  966. while (!isEnd(context, mode, ancestors)) {
  967. const s = context.source;
  968. let node = undefined;
  969. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  970. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  971. // '{{'
  972. node = parseInterpolation(context, mode);
  973. }
  974. else if (mode === 0 /* DATA */ && s[0] === '<') {
  975. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  976. if (s.length === 1) {
  977. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  978. }
  979. else if (s[1] === '!') {
  980. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  981. if (startsWith(s, '<!--')) {
  982. node = parseComment(context);
  983. }
  984. else if (startsWith(s, '<!DOCTYPE')) {
  985. // Ignore DOCTYPE by a limitation.
  986. node = parseBogusComment(context);
  987. }
  988. else if (startsWith(s, '<![CDATA[')) {
  989. if (ns !== 0 /* HTML */) {
  990. node = parseCDATA(context, ancestors);
  991. }
  992. else {
  993. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  994. node = parseBogusComment(context);
  995. }
  996. }
  997. else {
  998. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  999. node = parseBogusComment(context);
  1000. }
  1001. }
  1002. else if (s[1] === '/') {
  1003. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  1004. if (s.length === 2) {
  1005. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  1006. }
  1007. else if (s[2] === '>') {
  1008. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  1009. advanceBy(context, 3);
  1010. continue;
  1011. }
  1012. else if (/[a-z]/i.test(s[2])) {
  1013. emitError(context, 23 /* X_INVALID_END_TAG */);
  1014. parseTag(context, 1 /* End */, parent);
  1015. continue;
  1016. }
  1017. else {
  1018. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  1019. node = parseBogusComment(context);
  1020. }
  1021. }
  1022. else if (/[a-z]/i.test(s[1])) {
  1023. node = parseElement(context, ancestors);
  1024. }
  1025. else if (s[1] === '?') {
  1026. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  1027. node = parseBogusComment(context);
  1028. }
  1029. else {
  1030. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  1031. }
  1032. }
  1033. }
  1034. if (!node) {
  1035. node = parseText(context, mode);
  1036. }
  1037. if (isArray(node)) {
  1038. for (let i = 0; i < node.length; i++) {
  1039. pushNode(nodes, node[i]);
  1040. }
  1041. }
  1042. else {
  1043. pushNode(nodes, node);
  1044. }
  1045. }
  1046. // Whitespace management for more efficient output
  1047. // (same as v2 whitespace: 'condense')
  1048. let removedWhitespace = false;
  1049. if (mode !== 2 /* RAWTEXT */) {
  1050. for (let i = 0; i < nodes.length; i++) {
  1051. const node = nodes[i];
  1052. if (!context.inPre && node.type === 2 /* TEXT */) {
  1053. if (!/[^\t\r\n\f ]/.test(node.content)) {
  1054. const prev = nodes[i - 1];
  1055. const next = nodes[i + 1];
  1056. // If:
  1057. // - the whitespace is the first or last node, or:
  1058. // - the whitespace is adjacent to a comment, or:
  1059. // - the whitespace is between two elements AND contains newline
  1060. // Then the whitespace is ignored.
  1061. if (!prev ||
  1062. !next ||
  1063. prev.type === 3 /* COMMENT */ ||
  1064. next.type === 3 /* COMMENT */ ||
  1065. (prev.type === 1 /* ELEMENT */ &&
  1066. next.type === 1 /* ELEMENT */ &&
  1067. /[\r\n]/.test(node.content))) {
  1068. removedWhitespace = true;
  1069. nodes[i] = null;
  1070. }
  1071. else {
  1072. // Otherwise, condensed consecutive whitespace inside the text
  1073. // down to a single space
  1074. node.content = ' ';
  1075. }
  1076. }
  1077. else {
  1078. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  1079. }
  1080. }
  1081. }
  1082. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  1083. // remove leading newline per html spec
  1084. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  1085. const first = nodes[0];
  1086. if (first && first.type === 2 /* TEXT */) {
  1087. first.content = first.content.replace(/^\r?\n/, '');
  1088. }
  1089. }
  1090. }
  1091. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  1092. }
  1093. function pushNode(nodes, node) {
  1094. if (node.type === 2 /* TEXT */) {
  1095. const prev = last(nodes);
  1096. // Merge if both this and the previous node are text and those are
  1097. // consecutive. This happens for cases like "a < b".
  1098. if (prev &&
  1099. prev.type === 2 /* TEXT */ &&
  1100. prev.loc.end.offset === node.loc.start.offset) {
  1101. prev.content += node.content;
  1102. prev.loc.end = node.loc.end;
  1103. prev.loc.source += node.loc.source;
  1104. return;
  1105. }
  1106. }
  1107. nodes.push(node);
  1108. }
  1109. function parseCDATA(context, ancestors) {
  1110. advanceBy(context, 9);
  1111. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  1112. if (context.source.length === 0) {
  1113. emitError(context, 6 /* EOF_IN_CDATA */);
  1114. }
  1115. else {
  1116. advanceBy(context, 3);
  1117. }
  1118. return nodes;
  1119. }
  1120. function parseComment(context) {
  1121. const start = getCursor(context);
  1122. let content;
  1123. // Regular comment.
  1124. const match = /--(\!)?>/.exec(context.source);
  1125. if (!match) {
  1126. content = context.source.slice(4);
  1127. advanceBy(context, context.source.length);
  1128. emitError(context, 7 /* EOF_IN_COMMENT */);
  1129. }
  1130. else {
  1131. if (match.index <= 3) {
  1132. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  1133. }
  1134. if (match[1]) {
  1135. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  1136. }
  1137. content = context.source.slice(4, match.index);
  1138. // Advancing with reporting nested comments.
  1139. const s = context.source.slice(0, match.index);
  1140. let prevIndex = 1, nestedIndex = 0;
  1141. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  1142. advanceBy(context, nestedIndex - prevIndex + 1);
  1143. if (nestedIndex + 4 < s.length) {
  1144. emitError(context, 16 /* NESTED_COMMENT */);
  1145. }
  1146. prevIndex = nestedIndex + 1;
  1147. }
  1148. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  1149. }
  1150. return {
  1151. type: 3 /* COMMENT */,
  1152. content,
  1153. loc: getSelection(context, start)
  1154. };
  1155. }
  1156. function parseBogusComment(context) {
  1157. const start = getCursor(context);
  1158. const contentStart = context.source[1] === '?' ? 1 : 2;
  1159. let content;
  1160. const closeIndex = context.source.indexOf('>');
  1161. if (closeIndex === -1) {
  1162. content = context.source.slice(contentStart);
  1163. advanceBy(context, context.source.length);
  1164. }
  1165. else {
  1166. content = context.source.slice(contentStart, closeIndex);
  1167. advanceBy(context, closeIndex + 1);
  1168. }
  1169. return {
  1170. type: 3 /* COMMENT */,
  1171. content,
  1172. loc: getSelection(context, start)
  1173. };
  1174. }
  1175. function parseElement(context, ancestors) {
  1176. // Start tag.
  1177. const wasInPre = context.inPre;
  1178. const wasInVPre = context.inVPre;
  1179. const parent = last(ancestors);
  1180. const element = parseTag(context, 0 /* Start */, parent);
  1181. const isPreBoundary = context.inPre && !wasInPre;
  1182. const isVPreBoundary = context.inVPre && !wasInVPre;
  1183. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  1184. return element;
  1185. }
  1186. // Children.
  1187. ancestors.push(element);
  1188. const mode = context.options.getTextMode(element, parent);
  1189. const children = parseChildren(context, mode, ancestors);
  1190. ancestors.pop();
  1191. element.children = children;
  1192. // End tag.
  1193. if (startsWithEndTagOpen(context.source, element.tag)) {
  1194. parseTag(context, 1 /* End */, parent);
  1195. }
  1196. else {
  1197. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  1198. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  1199. const first = children[0];
  1200. if (first && startsWith(first.loc.source, '<!--')) {
  1201. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  1202. }
  1203. }
  1204. }
  1205. element.loc = getSelection(context, element.loc.start);
  1206. if (isPreBoundary) {
  1207. context.inPre = false;
  1208. }
  1209. if (isVPreBoundary) {
  1210. context.inVPre = false;
  1211. }
  1212. return element;
  1213. }
  1214. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  1215. /**
  1216. * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
  1217. */
  1218. function parseTag(context, type, parent) {
  1219. // Tag open.
  1220. const start = getCursor(context);
  1221. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  1222. const tag = match[1];
  1223. const ns = context.options.getNamespace(tag, parent);
  1224. advanceBy(context, match[0].length);
  1225. advanceSpaces(context);
  1226. // save current state in case we need to re-parse attributes with v-pre
  1227. const cursor = getCursor(context);
  1228. const currentSource = context.source;
  1229. // Attributes.
  1230. let props = parseAttributes(context, type);
  1231. // check <pre> tag
  1232. if (context.options.isPreTag(tag)) {
  1233. context.inPre = true;
  1234. }
  1235. // check v-pre
  1236. if (!context.inVPre &&
  1237. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  1238. context.inVPre = true;
  1239. // reset context
  1240. extend(context, cursor);
  1241. context.source = currentSource;
  1242. // re-parse attrs and filter out v-pre itself
  1243. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  1244. }
  1245. // Tag close.
  1246. let isSelfClosing = false;
  1247. if (context.source.length === 0) {
  1248. emitError(context, 9 /* EOF_IN_TAG */);
  1249. }
  1250. else {
  1251. isSelfClosing = startsWith(context.source, '/>');
  1252. if (type === 1 /* End */ && isSelfClosing) {
  1253. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  1254. }
  1255. advanceBy(context, isSelfClosing ? 2 : 1);
  1256. }
  1257. let tagType = 0 /* ELEMENT */;
  1258. const options = context.options;
  1259. if (!context.inVPre && !options.isCustomElement(tag)) {
  1260. const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
  1261. if (options.isNativeTag && !hasVIs) {
  1262. if (!options.isNativeTag(tag))
  1263. tagType = 1 /* COMPONENT */;
  1264. }
  1265. else if (hasVIs ||
  1266. isCoreComponent(tag) ||
  1267. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  1268. /^[A-Z]/.test(tag) ||
  1269. tag === 'component') {
  1270. tagType = 1 /* COMPONENT */;
  1271. }
  1272. if (tag === 'slot') {
  1273. tagType = 2 /* SLOT */;
  1274. }
  1275. else if (tag === 'template' &&
  1276. props.some(p => {
  1277. return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
  1278. })) {
  1279. tagType = 3 /* TEMPLATE */;
  1280. }
  1281. }
  1282. return {
  1283. type: 1 /* ELEMENT */,
  1284. ns,
  1285. tag,
  1286. tagType,
  1287. props,
  1288. isSelfClosing,
  1289. children: [],
  1290. loc: getSelection(context, start),
  1291. codegenNode: undefined // to be created during transform phase
  1292. };
  1293. }
  1294. function parseAttributes(context, type) {
  1295. const props = [];
  1296. const attributeNames = new Set();
  1297. while (context.source.length > 0 &&
  1298. !startsWith(context.source, '>') &&
  1299. !startsWith(context.source, '/>')) {
  1300. if (startsWith(context.source, '/')) {
  1301. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  1302. advanceBy(context, 1);
  1303. advanceSpaces(context);
  1304. continue;
  1305. }
  1306. if (type === 1 /* End */) {
  1307. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  1308. }
  1309. const attr = parseAttribute(context, attributeNames);
  1310. if (type === 0 /* Start */) {
  1311. props.push(attr);
  1312. }
  1313. if (/^[^\t\r\n\f />]/.test(context.source)) {
  1314. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  1315. }
  1316. advanceSpaces(context);
  1317. }
  1318. return props;
  1319. }
  1320. function parseAttribute(context, nameSet) {
  1321. // Name.
  1322. const start = getCursor(context);
  1323. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  1324. const name = match[0];
  1325. if (nameSet.has(name)) {
  1326. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  1327. }
  1328. nameSet.add(name);
  1329. if (name[0] === '=') {
  1330. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  1331. }
  1332. {
  1333. const pattern = /["'<]/g;
  1334. let m;
  1335. while ((m = pattern.exec(name))) {
  1336. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  1337. }
  1338. }
  1339. advanceBy(context, name.length);
  1340. // Value
  1341. let value = undefined;
  1342. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  1343. advanceSpaces(context);
  1344. advanceBy(context, 1);
  1345. advanceSpaces(context);
  1346. value = parseAttributeValue(context);
  1347. if (!value) {
  1348. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  1349. }
  1350. }
  1351. const loc = getSelection(context, start);
  1352. if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
  1353. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  1354. const dirName = match[1] ||
  1355. (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
  1356. let arg;
  1357. if (match[2]) {
  1358. const isSlot = dirName === 'slot';
  1359. const startOffset = name.indexOf(match[2]);
  1360. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  1361. let content = match[2];
  1362. let isStatic = true;
  1363. if (content.startsWith('[')) {
  1364. isStatic = false;
  1365. if (!content.endsWith(']')) {
  1366. emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  1367. }
  1368. content = content.substr(1, content.length - 2);
  1369. }
  1370. else if (isSlot) {
  1371. // #1241 special case for v-slot: vuetify relies extensively on slot
  1372. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  1373. // supports such usage so we are keeping it consistent with 2.x.
  1374. content += match[3] || '';
  1375. }
  1376. arg = {
  1377. type: 4 /* SIMPLE_EXPRESSION */,
  1378. content,
  1379. isStatic,
  1380. constType: isStatic
  1381. ? 3 /* CAN_STRINGIFY */
  1382. : 0 /* NOT_CONSTANT */,
  1383. loc
  1384. };
  1385. }
  1386. if (value && value.isQuoted) {
  1387. const valueLoc = value.loc;
  1388. valueLoc.start.offset++;
  1389. valueLoc.start.column++;
  1390. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  1391. valueLoc.source = valueLoc.source.slice(1, -1);
  1392. }
  1393. return {
  1394. type: 7 /* DIRECTIVE */,
  1395. name: dirName,
  1396. exp: value && {
  1397. type: 4 /* SIMPLE_EXPRESSION */,
  1398. content: value.content,
  1399. isStatic: false,
  1400. // Treat as non-constant by default. This can be potentially set to
  1401. // other values by `transformExpression` to make it eligible for hoisting.
  1402. constType: 0 /* NOT_CONSTANT */,
  1403. loc: value.loc
  1404. },
  1405. arg,
  1406. modifiers: match[3] ? match[3].substr(1).split('.') : [],
  1407. loc
  1408. };
  1409. }
  1410. return {
  1411. type: 6 /* ATTRIBUTE */,
  1412. name,
  1413. value: value && {
  1414. type: 2 /* TEXT */,
  1415. content: value.content,
  1416. loc: value.loc
  1417. },
  1418. loc
  1419. };
  1420. }
  1421. function parseAttributeValue(context) {
  1422. const start = getCursor(context);
  1423. let content;
  1424. const quote = context.source[0];
  1425. const isQuoted = quote === `"` || quote === `'`;
  1426. if (isQuoted) {
  1427. // Quoted value.
  1428. advanceBy(context, 1);
  1429. const endIndex = context.source.indexOf(quote);
  1430. if (endIndex === -1) {
  1431. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  1432. }
  1433. else {
  1434. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  1435. advanceBy(context, 1);
  1436. }
  1437. }
  1438. else {
  1439. // Unquoted
  1440. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  1441. if (!match) {
  1442. return undefined;
  1443. }
  1444. const unexpectedChars = /["'<=`]/g;
  1445. let m;
  1446. while ((m = unexpectedChars.exec(match[0]))) {
  1447. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  1448. }
  1449. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  1450. }
  1451. return { content, isQuoted, loc: getSelection(context, start) };
  1452. }
  1453. function parseInterpolation(context, mode) {
  1454. const [open, close] = context.options.delimiters;
  1455. const closeIndex = context.source.indexOf(close, open.length);
  1456. if (closeIndex === -1) {
  1457. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  1458. return undefined;
  1459. }
  1460. const start = getCursor(context);
  1461. advanceBy(context, open.length);
  1462. const innerStart = getCursor(context);
  1463. const innerEnd = getCursor(context);
  1464. const rawContentLength = closeIndex - open.length;
  1465. const rawContent = context.source.slice(0, rawContentLength);
  1466. const preTrimContent = parseTextData(context, rawContentLength, mode);
  1467. const content = preTrimContent.trim();
  1468. const startOffset = preTrimContent.indexOf(content);
  1469. if (startOffset > 0) {
  1470. advancePositionWithMutation(innerStart, rawContent, startOffset);
  1471. }
  1472. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  1473. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  1474. advanceBy(context, close.length);
  1475. return {
  1476. type: 5 /* INTERPOLATION */,
  1477. content: {
  1478. type: 4 /* SIMPLE_EXPRESSION */,
  1479. isStatic: false,
  1480. // Set `isConstant` to false by default and will decide in transformExpression
  1481. constType: 0 /* NOT_CONSTANT */,
  1482. content,
  1483. loc: getSelection(context, innerStart, innerEnd)
  1484. },
  1485. loc: getSelection(context, start)
  1486. };
  1487. }
  1488. function parseText(context, mode) {
  1489. const endTokens = ['<', context.options.delimiters[0]];
  1490. if (mode === 3 /* CDATA */) {
  1491. endTokens.push(']]>');
  1492. }
  1493. let endIndex = context.source.length;
  1494. for (let i = 0; i < endTokens.length; i++) {
  1495. const index = context.source.indexOf(endTokens[i], 1);
  1496. if (index !== -1 && endIndex > index) {
  1497. endIndex = index;
  1498. }
  1499. }
  1500. const start = getCursor(context);
  1501. const content = parseTextData(context, endIndex, mode);
  1502. return {
  1503. type: 2 /* TEXT */,
  1504. content,
  1505. loc: getSelection(context, start)
  1506. };
  1507. }
  1508. /**
  1509. * Get text data with a given length from the current location.
  1510. * This translates HTML entities in the text data.
  1511. */
  1512. function parseTextData(context, length, mode) {
  1513. const rawText = context.source.slice(0, length);
  1514. advanceBy(context, length);
  1515. if (mode === 2 /* RAWTEXT */ ||
  1516. mode === 3 /* CDATA */ ||
  1517. rawText.indexOf('&') === -1) {
  1518. return rawText;
  1519. }
  1520. else {
  1521. // DATA or RCDATA containing "&"". Entity decoding required.
  1522. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  1523. }
  1524. }
  1525. function getCursor(context) {
  1526. const { column, line, offset } = context;
  1527. return { column, line, offset };
  1528. }
  1529. function getSelection(context, start, end) {
  1530. end = end || getCursor(context);
  1531. return {
  1532. start,
  1533. end,
  1534. source: context.originalSource.slice(start.offset, end.offset)
  1535. };
  1536. }
  1537. function last(xs) {
  1538. return xs[xs.length - 1];
  1539. }
  1540. function startsWith(source, searchString) {
  1541. return source.startsWith(searchString);
  1542. }
  1543. function advanceBy(context, numberOfCharacters) {
  1544. const { source } = context;
  1545. advancePositionWithMutation(context, source, numberOfCharacters);
  1546. context.source = source.slice(numberOfCharacters);
  1547. }
  1548. function advanceSpaces(context) {
  1549. const match = /^[\t\r\n\f ]+/.exec(context.source);
  1550. if (match) {
  1551. advanceBy(context, match[0].length);
  1552. }
  1553. }
  1554. function getNewPosition(context, start, numberOfCharacters) {
  1555. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  1556. }
  1557. function emitError(context, code, offset, loc = getCursor(context)) {
  1558. if (offset) {
  1559. loc.offset += offset;
  1560. loc.column += offset;
  1561. }
  1562. context.options.onError(createCompilerError(code, {
  1563. start: loc,
  1564. end: loc,
  1565. source: ''
  1566. }));
  1567. }
  1568. function isEnd(context, mode, ancestors) {
  1569. const s = context.source;
  1570. switch (mode) {
  1571. case 0 /* DATA */:
  1572. if (startsWith(s, '</')) {
  1573. //TODO: probably bad performance
  1574. for (let i = ancestors.length - 1; i >= 0; --i) {
  1575. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  1576. return true;
  1577. }
  1578. }
  1579. }
  1580. break;
  1581. case 1 /* RCDATA */:
  1582. case 2 /* RAWTEXT */: {
  1583. const parent = last(ancestors);
  1584. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  1585. return true;
  1586. }
  1587. break;
  1588. }
  1589. case 3 /* CDATA */:
  1590. if (startsWith(s, ']]>')) {
  1591. return true;
  1592. }
  1593. break;
  1594. }
  1595. return !s;
  1596. }
  1597. function startsWithEndTagOpen(source, tag) {
  1598. return (startsWith(source, '</') &&
  1599. source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
  1600. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  1601. }
  1602. function hoistStatic(root, context) {
  1603. walk(root, context,
  1604. // Root node is unfortunately non-hoistable due to potential parent
  1605. // fallthrough attributes.
  1606. isSingleElementRoot(root, root.children[0]));
  1607. }
  1608. function isSingleElementRoot(root, child) {
  1609. const { children } = root;
  1610. return (children.length === 1 &&
  1611. child.type === 1 /* ELEMENT */ &&
  1612. !isSlotOutlet(child));
  1613. }
  1614. function walk(node, context, doNotHoistNode = false) {
  1615. let hasHoistedNode = false;
  1616. // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
  1617. // static bindings with expressions. These expressions are guaranteed to be
  1618. // constant so they are still eligible for hoisting, but they are only
  1619. // available at runtime and therefore cannot be evaluated ahead of time.
  1620. // This is only a concern for pre-stringification (via transformHoist by
  1621. // @vue/compiler-dom), but doing it here allows us to perform only one full
  1622. // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
  1623. // stringficiation threshold is met.
  1624. let canStringify = true;
  1625. const { children } = node;
  1626. for (let i = 0; i < children.length; i++) {
  1627. const child = children[i];
  1628. // only plain elements & text calls are eligible for hoisting.
  1629. if (child.type === 1 /* ELEMENT */ &&
  1630. child.tagType === 0 /* ELEMENT */) {
  1631. const constantType = doNotHoistNode
  1632. ? 0 /* NOT_CONSTANT */
  1633. : getConstantType(child, context);
  1634. if (constantType > 0 /* NOT_CONSTANT */) {
  1635. if (constantType < 3 /* CAN_STRINGIFY */) {
  1636. canStringify = false;
  1637. }
  1638. if (constantType >= 2 /* CAN_HOIST */) {
  1639. child.codegenNode.patchFlag =
  1640. -1 /* HOISTED */ + ( ` /* HOISTED */` );
  1641. child.codegenNode = context.hoist(child.codegenNode);
  1642. hasHoistedNode = true;
  1643. continue;
  1644. }
  1645. }
  1646. else {
  1647. // node may contain dynamic children, but its props may be eligible for
  1648. // hoisting.
  1649. const codegenNode = child.codegenNode;
  1650. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1651. const flag = getPatchFlag(codegenNode);
  1652. if ((!flag ||
  1653. flag === 512 /* NEED_PATCH */ ||
  1654. flag === 1 /* TEXT */) &&
  1655. getGeneratedPropsConstantType(child, context) >=
  1656. 2 /* CAN_HOIST */) {
  1657. const props = getNodeProps(child);
  1658. if (props) {
  1659. codegenNode.props = context.hoist(props);
  1660. }
  1661. }
  1662. }
  1663. }
  1664. }
  1665. else if (child.type === 12 /* TEXT_CALL */) {
  1666. const contentType = getConstantType(child.content, context);
  1667. if (contentType > 0) {
  1668. if (contentType < 3 /* CAN_STRINGIFY */) {
  1669. canStringify = false;
  1670. }
  1671. if (contentType >= 2 /* CAN_HOIST */) {
  1672. child.codegenNode = context.hoist(child.codegenNode);
  1673. hasHoistedNode = true;
  1674. }
  1675. }
  1676. }
  1677. // walk further
  1678. if (child.type === 1 /* ELEMENT */) {
  1679. walk(child, context);
  1680. }
  1681. else if (child.type === 11 /* FOR */) {
  1682. // Do not hoist v-for single child because it has to be a block
  1683. walk(child, context, child.children.length === 1);
  1684. }
  1685. else if (child.type === 9 /* IF */) {
  1686. for (let i = 0; i < child.branches.length; i++) {
  1687. // Do not hoist v-if single child because it has to be a block
  1688. walk(child.branches[i], context, child.branches[i].children.length === 1);
  1689. }
  1690. }
  1691. }
  1692. if (canStringify && hasHoistedNode && context.transformHoist) {
  1693. context.transformHoist(children, context, node);
  1694. }
  1695. }
  1696. function getConstantType(node, context) {
  1697. const { constantCache } = context;
  1698. switch (node.type) {
  1699. case 1 /* ELEMENT */:
  1700. if (node.tagType !== 0 /* ELEMENT */) {
  1701. return 0 /* NOT_CONSTANT */;
  1702. }
  1703. const cached = constantCache.get(node);
  1704. if (cached !== undefined) {
  1705. return cached;
  1706. }
  1707. const codegenNode = node.codegenNode;
  1708. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  1709. return 0 /* NOT_CONSTANT */;
  1710. }
  1711. const flag = getPatchFlag(codegenNode);
  1712. if (!flag) {
  1713. let returnType = 3 /* CAN_STRINGIFY */;
  1714. // Element itself has no patch flag. However we still need to check:
  1715. // 1. Even for a node with no patch flag, it is possible for it to contain
  1716. // non-hoistable expressions that refers to scope variables, e.g. compiler
  1717. // injected keys or cached event handlers. Therefore we need to always
  1718. // check the codegenNode's props to be sure.
  1719. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  1720. if (generatedPropsType === 0 /* NOT_CONSTANT */) {
  1721. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1722. return 0 /* NOT_CONSTANT */;
  1723. }
  1724. if (generatedPropsType < returnType) {
  1725. returnType = generatedPropsType;
  1726. }
  1727. // 2. its children.
  1728. for (let i = 0; i < node.children.length; i++) {
  1729. const childType = getConstantType(node.children[i], context);
  1730. if (childType === 0 /* NOT_CONSTANT */) {
  1731. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1732. return 0 /* NOT_CONSTANT */;
  1733. }
  1734. if (childType < returnType) {
  1735. returnType = childType;
  1736. }
  1737. }
  1738. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  1739. // type, check if any of the props can cause the type to be lowered
  1740. // we can skip can_patch because it's guaranteed by the absence of a
  1741. // patchFlag.
  1742. if (returnType > 1 /* CAN_SKIP_PATCH */) {
  1743. for (let i = 0; i < node.props.length; i++) {
  1744. const p = node.props[i];
  1745. if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
  1746. const expType = getConstantType(p.exp, context);
  1747. if (expType === 0 /* NOT_CONSTANT */) {
  1748. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1749. return 0 /* NOT_CONSTANT */;
  1750. }
  1751. if (expType < returnType) {
  1752. returnType = expType;
  1753. }
  1754. }
  1755. }
  1756. }
  1757. // only svg/foreignObject could be block here, however if they are
  1758. // static then they don't need to be blocks since there will be no
  1759. // nested updates.
  1760. if (codegenNode.isBlock) {
  1761. codegenNode.isBlock = false;
  1762. context.helper(CREATE_VNODE);
  1763. }
  1764. constantCache.set(node, returnType);
  1765. return returnType;
  1766. }
  1767. else {
  1768. constantCache.set(node, 0 /* NOT_CONSTANT */);
  1769. return 0 /* NOT_CONSTANT */;
  1770. }
  1771. case 2 /* TEXT */:
  1772. case 3 /* COMMENT */:
  1773. return 3 /* CAN_STRINGIFY */;
  1774. case 9 /* IF */:
  1775. case 11 /* FOR */:
  1776. case 10 /* IF_BRANCH */:
  1777. return 0 /* NOT_CONSTANT */;
  1778. case 5 /* INTERPOLATION */:
  1779. case 12 /* TEXT_CALL */:
  1780. return getConstantType(node.content, context);
  1781. case 4 /* SIMPLE_EXPRESSION */:
  1782. return node.constType;
  1783. case 8 /* COMPOUND_EXPRESSION */:
  1784. let returnType = 3 /* CAN_STRINGIFY */;
  1785. for (let i = 0; i < node.children.length; i++) {
  1786. const child = node.children[i];
  1787. if (isString(child) || isSymbol(child)) {
  1788. continue;
  1789. }
  1790. const childType = getConstantType(child, context);
  1791. if (childType === 0 /* NOT_CONSTANT */) {
  1792. return 0 /* NOT_CONSTANT */;
  1793. }
  1794. else if (childType < returnType) {
  1795. returnType = childType;
  1796. }
  1797. }
  1798. return returnType;
  1799. default:
  1800. return 0 /* NOT_CONSTANT */;
  1801. }
  1802. }
  1803. function getGeneratedPropsConstantType(node, context) {
  1804. let returnType = 3 /* CAN_STRINGIFY */;
  1805. const props = getNodeProps(node);
  1806. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  1807. const { properties } = props;
  1808. for (let i = 0; i < properties.length; i++) {
  1809. const { key, value } = properties[i];
  1810. const keyType = getConstantType(key, context);
  1811. if (keyType === 0 /* NOT_CONSTANT */) {
  1812. return keyType;
  1813. }
  1814. if (keyType < returnType) {
  1815. returnType = keyType;
  1816. }
  1817. if (value.type !== 4 /* SIMPLE_EXPRESSION */) {
  1818. return 0 /* NOT_CONSTANT */;
  1819. }
  1820. const valueType = getConstantType(value, context);
  1821. if (valueType === 0 /* NOT_CONSTANT */) {
  1822. return valueType;
  1823. }
  1824. if (valueType < returnType) {
  1825. returnType = valueType;
  1826. }
  1827. }
  1828. }
  1829. return returnType;
  1830. }
  1831. function getNodeProps(node) {
  1832. const codegenNode = node.codegenNode;
  1833. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1834. return codegenNode.props;
  1835. }
  1836. }
  1837. function getPatchFlag(node) {
  1838. const flag = node.patchFlag;
  1839. return flag ? parseInt(flag, 10) : undefined;
  1840. }
  1841. 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 }) {
  1842. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  1843. const context = {
  1844. // options
  1845. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  1846. prefixIdentifiers,
  1847. hoistStatic,
  1848. cacheHandlers,
  1849. nodeTransforms,
  1850. directiveTransforms,
  1851. transformHoist,
  1852. isBuiltInComponent,
  1853. isCustomElement,
  1854. expressionPlugins,
  1855. scopeId,
  1856. ssr,
  1857. ssrCssVars,
  1858. bindingMetadata,
  1859. inline,
  1860. isTS,
  1861. onError,
  1862. // state
  1863. root,
  1864. helpers: new Set(),
  1865. components: new Set(),
  1866. directives: new Set(),
  1867. hoists: [],
  1868. imports: new Set(),
  1869. constantCache: new Map(),
  1870. temps: 0,
  1871. cached: 0,
  1872. identifiers: Object.create(null),
  1873. scopes: {
  1874. vFor: 0,
  1875. vSlot: 0,
  1876. vPre: 0,
  1877. vOnce: 0
  1878. },
  1879. parent: null,
  1880. currentNode: root,
  1881. childIndex: 0,
  1882. // methods
  1883. helper(name) {
  1884. context.helpers.add(name);
  1885. return name;
  1886. },
  1887. helperString(name) {
  1888. return `_${helperNameMap[context.helper(name)]}`;
  1889. },
  1890. replaceNode(node) {
  1891. /* istanbul ignore if */
  1892. {
  1893. if (!context.currentNode) {
  1894. throw new Error(`Node being replaced is already removed.`);
  1895. }
  1896. if (!context.parent) {
  1897. throw new Error(`Cannot replace root node.`);
  1898. }
  1899. }
  1900. context.parent.children[context.childIndex] = context.currentNode = node;
  1901. },
  1902. removeNode(node) {
  1903. if ( !context.parent) {
  1904. throw new Error(`Cannot remove root node.`);
  1905. }
  1906. const list = context.parent.children;
  1907. const removalIndex = node
  1908. ? list.indexOf(node)
  1909. : context.currentNode
  1910. ? context.childIndex
  1911. : -1;
  1912. /* istanbul ignore if */
  1913. if ( removalIndex < 0) {
  1914. throw new Error(`node being removed is not a child of current parent`);
  1915. }
  1916. if (!node || node === context.currentNode) {
  1917. // current node removed
  1918. context.currentNode = null;
  1919. context.onNodeRemoved();
  1920. }
  1921. else {
  1922. // sibling node removed
  1923. if (context.childIndex > removalIndex) {
  1924. context.childIndex--;
  1925. context.onNodeRemoved();
  1926. }
  1927. }
  1928. context.parent.children.splice(removalIndex, 1);
  1929. },
  1930. onNodeRemoved: () => { },
  1931. addIdentifiers(exp) {
  1932. // identifier tracking only happens in non-browser builds.
  1933. {
  1934. if (isString(exp)) {
  1935. addId(exp);
  1936. }
  1937. else if (exp.identifiers) {
  1938. exp.identifiers.forEach(addId);
  1939. }
  1940. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  1941. addId(exp.content);
  1942. }
  1943. }
  1944. },
  1945. removeIdentifiers(exp) {
  1946. {
  1947. if (isString(exp)) {
  1948. removeId(exp);
  1949. }
  1950. else if (exp.identifiers) {
  1951. exp.identifiers.forEach(removeId);
  1952. }
  1953. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  1954. removeId(exp.content);
  1955. }
  1956. }
  1957. },
  1958. hoist(exp) {
  1959. context.hoists.push(exp);
  1960. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
  1961. identifier.hoisted = exp;
  1962. return identifier;
  1963. },
  1964. cache(exp, isVNode = false) {
  1965. return createCacheExpression(++context.cached, exp, isVNode);
  1966. }
  1967. };
  1968. function addId(id) {
  1969. const { identifiers } = context;
  1970. if (identifiers[id] === undefined) {
  1971. identifiers[id] = 0;
  1972. }
  1973. identifiers[id]++;
  1974. }
  1975. function removeId(id) {
  1976. context.identifiers[id]--;
  1977. }
  1978. return context;
  1979. }
  1980. function transform(root, options) {
  1981. const context = createTransformContext(root, options);
  1982. traverseNode(root, context);
  1983. if (options.hoistStatic) {
  1984. hoistStatic(root, context);
  1985. }
  1986. if (!options.ssr) {
  1987. createRootCodegen(root, context);
  1988. }
  1989. // finalize meta information
  1990. root.helpers = [...context.helpers];
  1991. root.components = [...context.components];
  1992. root.directives = [...context.directives];
  1993. root.imports = [...context.imports];
  1994. root.hoists = context.hoists;
  1995. root.temps = context.temps;
  1996. root.cached = context.cached;
  1997. }
  1998. function createRootCodegen(root, context) {
  1999. const { helper } = context;
  2000. const { children } = root;
  2001. if (children.length === 1) {
  2002. const child = children[0];
  2003. // if the single child is an element, turn it into a block.
  2004. if (isSingleElementRoot(root, child) && child.codegenNode) {
  2005. // single element root is never hoisted so codegenNode will never be
  2006. // SimpleExpressionNode
  2007. const codegenNode = child.codegenNode;
  2008. if (codegenNode.type === 13 /* VNODE_CALL */) {
  2009. codegenNode.isBlock = true;
  2010. helper(OPEN_BLOCK);
  2011. helper(CREATE_BLOCK);
  2012. }
  2013. root.codegenNode = codegenNode;
  2014. }
  2015. else {
  2016. // - single <slot/>, IfNode, ForNode: already blocks.
  2017. // - single text node: always patched.
  2018. // root codegen falls through via genNode()
  2019. root.codegenNode = child;
  2020. }
  2021. }
  2022. else if (children.length > 1) {
  2023. // root has multiple nodes - return a fragment block.
  2024. let patchFlag = 64 /* STABLE_FRAGMENT */;
  2025. let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
  2026. // check if the fragment actually contains a single valid child with
  2027. // the rest being comments
  2028. if (
  2029. children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
  2030. patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
  2031. patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
  2032. }
  2033. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + ( ` /* ${patchFlagText} */` ), undefined, undefined, true);
  2034. }
  2035. else ;
  2036. }
  2037. function traverseChildren(parent, context) {
  2038. let i = 0;
  2039. const nodeRemoved = () => {
  2040. i--;
  2041. };
  2042. for (; i < parent.children.length; i++) {
  2043. const child = parent.children[i];
  2044. if (isString(child))
  2045. continue;
  2046. context.parent = parent;
  2047. context.childIndex = i;
  2048. context.onNodeRemoved = nodeRemoved;
  2049. traverseNode(child, context);
  2050. }
  2051. }
  2052. function traverseNode(node, context) {
  2053. context.currentNode = node;
  2054. // apply transform plugins
  2055. const { nodeTransforms } = context;
  2056. const exitFns = [];
  2057. for (let i = 0; i < nodeTransforms.length; i++) {
  2058. const onExit = nodeTransforms[i](node, context);
  2059. if (onExit) {
  2060. if (isArray(onExit)) {
  2061. exitFns.push(...onExit);
  2062. }
  2063. else {
  2064. exitFns.push(onExit);
  2065. }
  2066. }
  2067. if (!context.currentNode) {
  2068. // node was removed
  2069. return;
  2070. }
  2071. else {
  2072. // node may have been replaced
  2073. node = context.currentNode;
  2074. }
  2075. }
  2076. switch (node.type) {
  2077. case 3 /* COMMENT */:
  2078. if (!context.ssr) {
  2079. // inject import for the Comment symbol, which is needed for creating
  2080. // comment nodes with `createVNode`
  2081. context.helper(CREATE_COMMENT);
  2082. }
  2083. break;
  2084. case 5 /* INTERPOLATION */:
  2085. // no need to traverse, but we need to inject toString helper
  2086. if (!context.ssr) {
  2087. context.helper(TO_DISPLAY_STRING);
  2088. }
  2089. break;
  2090. // for container types, further traverse downwards
  2091. case 9 /* IF */:
  2092. for (let i = 0; i < node.branches.length; i++) {
  2093. traverseNode(node.branches[i], context);
  2094. }
  2095. break;
  2096. case 10 /* IF_BRANCH */:
  2097. case 11 /* FOR */:
  2098. case 1 /* ELEMENT */:
  2099. case 0 /* ROOT */:
  2100. traverseChildren(node, context);
  2101. break;
  2102. }
  2103. // exit transforms
  2104. context.currentNode = node;
  2105. let i = exitFns.length;
  2106. while (i--) {
  2107. exitFns[i]();
  2108. }
  2109. }
  2110. function createStructuralDirectiveTransform(name, fn) {
  2111. const matches = isString(name)
  2112. ? (n) => n === name
  2113. : (n) => name.test(n);
  2114. return (node, context) => {
  2115. if (node.type === 1 /* ELEMENT */) {
  2116. const { props } = node;
  2117. // structural directive transforms are not concerned with slots
  2118. // as they are handled separately in vSlot.ts
  2119. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  2120. return;
  2121. }
  2122. const exitFns = [];
  2123. for (let i = 0; i < props.length; i++) {
  2124. const prop = props[i];
  2125. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  2126. // structural directives are removed to avoid infinite recursion
  2127. // also we remove them *before* applying so that it can further
  2128. // traverse itself in case it moves the node around
  2129. props.splice(i, 1);
  2130. i--;
  2131. const onExit = fn(node, prop, context);
  2132. if (onExit)
  2133. exitFns.push(onExit);
  2134. }
  2135. }
  2136. return exitFns;
  2137. }
  2138. };
  2139. }
  2140. /* -*- Mode: js; js-indent-level: 2; -*- */
  2141. /*
  2142. * Copyright 2011 Mozilla Foundation and contributors
  2143. * Licensed under the New BSD license. See LICENSE or:
  2144. * http://opensource.org/licenses/BSD-3-Clause
  2145. */
  2146. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  2147. /**
  2148. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  2149. */
  2150. var encode = function (number) {
  2151. if (0 <= number && number < intToCharMap.length) {
  2152. return intToCharMap[number];
  2153. }
  2154. throw new TypeError("Must be between 0 and 63: " + number);
  2155. };
  2156. /**
  2157. * Decode a single base 64 character code digit to an integer. Returns -1 on
  2158. * failure.
  2159. */
  2160. var decode = function (charCode) {
  2161. var bigA = 65; // 'A'
  2162. var bigZ = 90; // 'Z'
  2163. var littleA = 97; // 'a'
  2164. var littleZ = 122; // 'z'
  2165. var zero = 48; // '0'
  2166. var nine = 57; // '9'
  2167. var plus = 43; // '+'
  2168. var slash = 47; // '/'
  2169. var littleOffset = 26;
  2170. var numberOffset = 52;
  2171. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  2172. if (bigA <= charCode && charCode <= bigZ) {
  2173. return (charCode - bigA);
  2174. }
  2175. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  2176. if (littleA <= charCode && charCode <= littleZ) {
  2177. return (charCode - littleA + littleOffset);
  2178. }
  2179. // 52 - 61: 0123456789
  2180. if (zero <= charCode && charCode <= nine) {
  2181. return (charCode - zero + numberOffset);
  2182. }
  2183. // 62: +
  2184. if (charCode == plus) {
  2185. return 62;
  2186. }
  2187. // 63: /
  2188. if (charCode == slash) {
  2189. return 63;
  2190. }
  2191. // Invalid base64 digit.
  2192. return -1;
  2193. };
  2194. var base64 = {
  2195. encode: encode,
  2196. decode: decode
  2197. };
  2198. /* -*- Mode: js; js-indent-level: 2; -*- */
  2199. /*
  2200. * Copyright 2011 Mozilla Foundation and contributors
  2201. * Licensed under the New BSD license. See LICENSE or:
  2202. * http://opensource.org/licenses/BSD-3-Clause
  2203. *
  2204. * Based on the Base 64 VLQ implementation in Closure Compiler:
  2205. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  2206. *
  2207. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  2208. * Redistribution and use in source and binary forms, with or without
  2209. * modification, are permitted provided that the following conditions are
  2210. * met:
  2211. *
  2212. * * Redistributions of source code must retain the above copyright
  2213. * notice, this list of conditions and the following disclaimer.
  2214. * * Redistributions in binary form must reproduce the above
  2215. * copyright notice, this list of conditions and the following
  2216. * disclaimer in the documentation and/or other materials provided
  2217. * with the distribution.
  2218. * * Neither the name of Google Inc. nor the names of its
  2219. * contributors may be used to endorse or promote products derived
  2220. * from this software without specific prior written permission.
  2221. *
  2222. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2223. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2224. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2225. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2226. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2227. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2228. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2229. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2230. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2231. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2232. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2233. */
  2234. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  2235. // length quantities we use in the source map spec, the first bit is the sign,
  2236. // the next four bits are the actual value, and the 6th bit is the
  2237. // continuation bit. The continuation bit tells us whether there are more
  2238. // digits in this value following this digit.
  2239. //
  2240. // Continuation
  2241. // | Sign
  2242. // | |
  2243. // V V
  2244. // 101011
  2245. var VLQ_BASE_SHIFT = 5;
  2246. // binary: 100000
  2247. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  2248. // binary: 011111
  2249. var VLQ_BASE_MASK = VLQ_BASE - 1;
  2250. // binary: 100000
  2251. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  2252. /**
  2253. * Converts from a two-complement value to a value where the sign bit is
  2254. * placed in the least significant bit. For example, as decimals:
  2255. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  2256. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  2257. */
  2258. function toVLQSigned(aValue) {
  2259. return aValue < 0
  2260. ? ((-aValue) << 1) + 1
  2261. : (aValue << 1) + 0;
  2262. }
  2263. /**
  2264. * Converts to a two-complement value from a value where the sign bit is
  2265. * placed in the least significant bit. For example, as decimals:
  2266. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  2267. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  2268. */
  2269. function fromVLQSigned(aValue) {
  2270. var isNegative = (aValue & 1) === 1;
  2271. var shifted = aValue >> 1;
  2272. return isNegative
  2273. ? -shifted
  2274. : shifted;
  2275. }
  2276. /**
  2277. * Returns the base 64 VLQ encoded value.
  2278. */
  2279. var encode$1 = function base64VLQ_encode(aValue) {
  2280. var encoded = "";
  2281. var digit;
  2282. var vlq = toVLQSigned(aValue);
  2283. do {
  2284. digit = vlq & VLQ_BASE_MASK;
  2285. vlq >>>= VLQ_BASE_SHIFT;
  2286. if (vlq > 0) {
  2287. // There are still more digits in this value, so we must make sure the
  2288. // continuation bit is marked.
  2289. digit |= VLQ_CONTINUATION_BIT;
  2290. }
  2291. encoded += base64.encode(digit);
  2292. } while (vlq > 0);
  2293. return encoded;
  2294. };
  2295. /**
  2296. * Decodes the next base 64 VLQ value from the given string and returns the
  2297. * value and the rest of the string via the out parameter.
  2298. */
  2299. var decode$1 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  2300. var strLen = aStr.length;
  2301. var result = 0;
  2302. var shift = 0;
  2303. var continuation, digit;
  2304. do {
  2305. if (aIndex >= strLen) {
  2306. throw new Error("Expected more digits in base 64 VLQ value.");
  2307. }
  2308. digit = base64.decode(aStr.charCodeAt(aIndex++));
  2309. if (digit === -1) {
  2310. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  2311. }
  2312. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  2313. digit &= VLQ_BASE_MASK;
  2314. result = result + (digit << shift);
  2315. shift += VLQ_BASE_SHIFT;
  2316. } while (continuation);
  2317. aOutParam.value = fromVLQSigned(result);
  2318. aOutParam.rest = aIndex;
  2319. };
  2320. var base64Vlq = {
  2321. encode: encode$1,
  2322. decode: decode$1
  2323. };
  2324. function getDefaultExportFromCjs (x) {
  2325. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  2326. }
  2327. function createCommonjsModule(fn) {
  2328. var module = { exports: {} };
  2329. return fn(module, module.exports), module.exports;
  2330. }
  2331. /* -*- Mode: js; js-indent-level: 2; -*- */
  2332. var util = createCommonjsModule(function (module, exports) {
  2333. /*
  2334. * Copyright 2011 Mozilla Foundation and contributors
  2335. * Licensed under the New BSD license. See LICENSE or:
  2336. * http://opensource.org/licenses/BSD-3-Clause
  2337. */
  2338. /**
  2339. * This is a helper function for getting values from parameter/options
  2340. * objects.
  2341. *
  2342. * @param args The object we are extracting values from
  2343. * @param name The name of the property we are getting.
  2344. * @param defaultValue An optional value to return if the property is missing
  2345. * from the object. If this is not specified and the property is missing, an
  2346. * error will be thrown.
  2347. */
  2348. function getArg(aArgs, aName, aDefaultValue) {
  2349. if (aName in aArgs) {
  2350. return aArgs[aName];
  2351. } else if (arguments.length === 3) {
  2352. return aDefaultValue;
  2353. } else {
  2354. throw new Error('"' + aName + '" is a required argument.');
  2355. }
  2356. }
  2357. exports.getArg = getArg;
  2358. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  2359. var dataUrlRegexp = /^data:.+\,.+$/;
  2360. function urlParse(aUrl) {
  2361. var match = aUrl.match(urlRegexp);
  2362. if (!match) {
  2363. return null;
  2364. }
  2365. return {
  2366. scheme: match[1],
  2367. auth: match[2],
  2368. host: match[3],
  2369. port: match[4],
  2370. path: match[5]
  2371. };
  2372. }
  2373. exports.urlParse = urlParse;
  2374. function urlGenerate(aParsedUrl) {
  2375. var url = '';
  2376. if (aParsedUrl.scheme) {
  2377. url += aParsedUrl.scheme + ':';
  2378. }
  2379. url += '//';
  2380. if (aParsedUrl.auth) {
  2381. url += aParsedUrl.auth + '@';
  2382. }
  2383. if (aParsedUrl.host) {
  2384. url += aParsedUrl.host;
  2385. }
  2386. if (aParsedUrl.port) {
  2387. url += ":" + aParsedUrl.port;
  2388. }
  2389. if (aParsedUrl.path) {
  2390. url += aParsedUrl.path;
  2391. }
  2392. return url;
  2393. }
  2394. exports.urlGenerate = urlGenerate;
  2395. /**
  2396. * Normalizes a path, or the path portion of a URL:
  2397. *
  2398. * - Replaces consecutive slashes with one slash.
  2399. * - Removes unnecessary '.' parts.
  2400. * - Removes unnecessary '<dir>/..' parts.
  2401. *
  2402. * Based on code in the Node.js 'path' core module.
  2403. *
  2404. * @param aPath The path or url to normalize.
  2405. */
  2406. function normalize(aPath) {
  2407. var path = aPath;
  2408. var url = urlParse(aPath);
  2409. if (url) {
  2410. if (!url.path) {
  2411. return aPath;
  2412. }
  2413. path = url.path;
  2414. }
  2415. var isAbsolute = exports.isAbsolute(path);
  2416. var parts = path.split(/\/+/);
  2417. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  2418. part = parts[i];
  2419. if (part === '.') {
  2420. parts.splice(i, 1);
  2421. } else if (part === '..') {
  2422. up++;
  2423. } else if (up > 0) {
  2424. if (part === '') {
  2425. // The first part is blank if the path is absolute. Trying to go
  2426. // above the root is a no-op. Therefore we can remove all '..' parts
  2427. // directly after the root.
  2428. parts.splice(i + 1, up);
  2429. up = 0;
  2430. } else {
  2431. parts.splice(i, 2);
  2432. up--;
  2433. }
  2434. }
  2435. }
  2436. path = parts.join('/');
  2437. if (path === '') {
  2438. path = isAbsolute ? '/' : '.';
  2439. }
  2440. if (url) {
  2441. url.path = path;
  2442. return urlGenerate(url);
  2443. }
  2444. return path;
  2445. }
  2446. exports.normalize = normalize;
  2447. /**
  2448. * Joins two paths/URLs.
  2449. *
  2450. * @param aRoot The root path or URL.
  2451. * @param aPath The path or URL to be joined with the root.
  2452. *
  2453. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  2454. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  2455. * first.
  2456. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  2457. * is updated with the result and aRoot is returned. Otherwise the result
  2458. * is returned.
  2459. * - If aPath is absolute, the result is aPath.
  2460. * - Otherwise the two paths are joined with a slash.
  2461. * - Joining for example 'http://' and 'www.example.com' is also supported.
  2462. */
  2463. function join(aRoot, aPath) {
  2464. if (aRoot === "") {
  2465. aRoot = ".";
  2466. }
  2467. if (aPath === "") {
  2468. aPath = ".";
  2469. }
  2470. var aPathUrl = urlParse(aPath);
  2471. var aRootUrl = urlParse(aRoot);
  2472. if (aRootUrl) {
  2473. aRoot = aRootUrl.path || '/';
  2474. }
  2475. // `join(foo, '//www.example.org')`
  2476. if (aPathUrl && !aPathUrl.scheme) {
  2477. if (aRootUrl) {
  2478. aPathUrl.scheme = aRootUrl.scheme;
  2479. }
  2480. return urlGenerate(aPathUrl);
  2481. }
  2482. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  2483. return aPath;
  2484. }
  2485. // `join('http://', 'www.example.com')`
  2486. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  2487. aRootUrl.host = aPath;
  2488. return urlGenerate(aRootUrl);
  2489. }
  2490. var joined = aPath.charAt(0) === '/'
  2491. ? aPath
  2492. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  2493. if (aRootUrl) {
  2494. aRootUrl.path = joined;
  2495. return urlGenerate(aRootUrl);
  2496. }
  2497. return joined;
  2498. }
  2499. exports.join = join;
  2500. exports.isAbsolute = function (aPath) {
  2501. return aPath.charAt(0) === '/' || urlRegexp.test(aPath);
  2502. };
  2503. /**
  2504. * Make a path relative to a URL or another path.
  2505. *
  2506. * @param aRoot The root path or URL.
  2507. * @param aPath The path or URL to be made relative to aRoot.
  2508. */
  2509. function relative(aRoot, aPath) {
  2510. if (aRoot === "") {
  2511. aRoot = ".";
  2512. }
  2513. aRoot = aRoot.replace(/\/$/, '');
  2514. // It is possible for the path to be above the root. In this case, simply
  2515. // checking whether the root is a prefix of the path won't work. Instead, we
  2516. // need to remove components from the root one by one, until either we find
  2517. // a prefix that fits, or we run out of components to remove.
  2518. var level = 0;
  2519. while (aPath.indexOf(aRoot + '/') !== 0) {
  2520. var index = aRoot.lastIndexOf("/");
  2521. if (index < 0) {
  2522. return aPath;
  2523. }
  2524. // If the only part of the root that is left is the scheme (i.e. http://,
  2525. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  2526. // have exhausted all components, so the path is not relative to the root.
  2527. aRoot = aRoot.slice(0, index);
  2528. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  2529. return aPath;
  2530. }
  2531. ++level;
  2532. }
  2533. // Make sure we add a "../" for each component we removed from the root.
  2534. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  2535. }
  2536. exports.relative = relative;
  2537. var supportsNullProto = (function () {
  2538. var obj = Object.create(null);
  2539. return !('__proto__' in obj);
  2540. }());
  2541. function identity (s) {
  2542. return s;
  2543. }
  2544. /**
  2545. * Because behavior goes wacky when you set `__proto__` on objects, we
  2546. * have to prefix all the strings in our set with an arbitrary character.
  2547. *
  2548. * See https://github.com/mozilla/source-map/pull/31 and
  2549. * https://github.com/mozilla/source-map/issues/30
  2550. *
  2551. * @param String aStr
  2552. */
  2553. function toSetString(aStr) {
  2554. if (isProtoString(aStr)) {
  2555. return '$' + aStr;
  2556. }
  2557. return aStr;
  2558. }
  2559. exports.toSetString = supportsNullProto ? identity : toSetString;
  2560. function fromSetString(aStr) {
  2561. if (isProtoString(aStr)) {
  2562. return aStr.slice(1);
  2563. }
  2564. return aStr;
  2565. }
  2566. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  2567. function isProtoString(s) {
  2568. if (!s) {
  2569. return false;
  2570. }
  2571. var length = s.length;
  2572. if (length < 9 /* "__proto__".length */) {
  2573. return false;
  2574. }
  2575. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  2576. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  2577. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  2578. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  2579. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  2580. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  2581. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  2582. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  2583. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  2584. return false;
  2585. }
  2586. for (var i = length - 10; i >= 0; i--) {
  2587. if (s.charCodeAt(i) !== 36 /* '$' */) {
  2588. return false;
  2589. }
  2590. }
  2591. return true;
  2592. }
  2593. /**
  2594. * Comparator between two mappings where the original positions are compared.
  2595. *
  2596. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  2597. * mappings with the same original source/line/column, but different generated
  2598. * line and column the same. Useful when searching for a mapping with a
  2599. * stubbed out mapping.
  2600. */
  2601. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  2602. var cmp = strcmp(mappingA.source, mappingB.source);
  2603. if (cmp !== 0) {
  2604. return cmp;
  2605. }
  2606. cmp = mappingA.originalLine - mappingB.originalLine;
  2607. if (cmp !== 0) {
  2608. return cmp;
  2609. }
  2610. cmp = mappingA.originalColumn - mappingB.originalColumn;
  2611. if (cmp !== 0 || onlyCompareOriginal) {
  2612. return cmp;
  2613. }
  2614. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  2615. if (cmp !== 0) {
  2616. return cmp;
  2617. }
  2618. cmp = mappingA.generatedLine - mappingB.generatedLine;
  2619. if (cmp !== 0) {
  2620. return cmp;
  2621. }
  2622. return strcmp(mappingA.name, mappingB.name);
  2623. }
  2624. exports.compareByOriginalPositions = compareByOriginalPositions;
  2625. /**
  2626. * Comparator between two mappings with deflated source and name indices where
  2627. * the generated positions are compared.
  2628. *
  2629. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  2630. * mappings with the same generated line and column, but different
  2631. * source/name/original line and column the same. Useful when searching for a
  2632. * mapping with a stubbed out mapping.
  2633. */
  2634. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  2635. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  2636. if (cmp !== 0) {
  2637. return cmp;
  2638. }
  2639. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  2640. if (cmp !== 0 || onlyCompareGenerated) {
  2641. return cmp;
  2642. }
  2643. cmp = strcmp(mappingA.source, mappingB.source);
  2644. if (cmp !== 0) {
  2645. return cmp;
  2646. }
  2647. cmp = mappingA.originalLine - mappingB.originalLine;
  2648. if (cmp !== 0) {
  2649. return cmp;
  2650. }
  2651. cmp = mappingA.originalColumn - mappingB.originalColumn;
  2652. if (cmp !== 0) {
  2653. return cmp;
  2654. }
  2655. return strcmp(mappingA.name, mappingB.name);
  2656. }
  2657. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  2658. function strcmp(aStr1, aStr2) {
  2659. if (aStr1 === aStr2) {
  2660. return 0;
  2661. }
  2662. if (aStr1 === null) {
  2663. return 1; // aStr2 !== null
  2664. }
  2665. if (aStr2 === null) {
  2666. return -1; // aStr1 !== null
  2667. }
  2668. if (aStr1 > aStr2) {
  2669. return 1;
  2670. }
  2671. return -1;
  2672. }
  2673. /**
  2674. * Comparator between two mappings with inflated source and name strings where
  2675. * the generated positions are compared.
  2676. */
  2677. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  2678. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  2679. if (cmp !== 0) {
  2680. return cmp;
  2681. }
  2682. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  2683. if (cmp !== 0) {
  2684. return cmp;
  2685. }
  2686. cmp = strcmp(mappingA.source, mappingB.source);
  2687. if (cmp !== 0) {
  2688. return cmp;
  2689. }
  2690. cmp = mappingA.originalLine - mappingB.originalLine;
  2691. if (cmp !== 0) {
  2692. return cmp;
  2693. }
  2694. cmp = mappingA.originalColumn - mappingB.originalColumn;
  2695. if (cmp !== 0) {
  2696. return cmp;
  2697. }
  2698. return strcmp(mappingA.name, mappingB.name);
  2699. }
  2700. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  2701. /**
  2702. * Strip any JSON XSSI avoidance prefix from the string (as documented
  2703. * in the source maps specification), and then parse the string as
  2704. * JSON.
  2705. */
  2706. function parseSourceMapInput(str) {
  2707. return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ''));
  2708. }
  2709. exports.parseSourceMapInput = parseSourceMapInput;
  2710. /**
  2711. * Compute the URL of a source given the the source root, the source's
  2712. * URL, and the source map's URL.
  2713. */
  2714. function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
  2715. sourceURL = sourceURL || '';
  2716. if (sourceRoot) {
  2717. // This follows what Chrome does.
  2718. if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') {
  2719. sourceRoot += '/';
  2720. }
  2721. // The spec says:
  2722. // Line 4: An optional source root, useful for relocating source
  2723. // files on a server or removing repeated values in the
  2724. // “sources” entry. This value is prepended to the individual
  2725. // entries in the “source” field.
  2726. sourceURL = sourceRoot + sourceURL;
  2727. }
  2728. // Historically, SourceMapConsumer did not take the sourceMapURL as
  2729. // a parameter. This mode is still somewhat supported, which is why
  2730. // this code block is conditional. However, it's preferable to pass
  2731. // the source map URL to SourceMapConsumer, so that this function
  2732. // can implement the source URL resolution algorithm as outlined in
  2733. // the spec. This block is basically the equivalent of:
  2734. // new URL(sourceURL, sourceMapURL).toString()
  2735. // ... except it avoids using URL, which wasn't available in the
  2736. // older releases of node still supported by this library.
  2737. //
  2738. // The spec says:
  2739. // If the sources are not absolute URLs after prepending of the
  2740. // “sourceRoot”, the sources are resolved relative to the
  2741. // SourceMap (like resolving script src in a html document).
  2742. if (sourceMapURL) {
  2743. var parsed = urlParse(sourceMapURL);
  2744. if (!parsed) {
  2745. throw new Error("sourceMapURL could not be parsed");
  2746. }
  2747. if (parsed.path) {
  2748. // Strip the last path component, but keep the "/".
  2749. var index = parsed.path.lastIndexOf('/');
  2750. if (index >= 0) {
  2751. parsed.path = parsed.path.substring(0, index + 1);
  2752. }
  2753. }
  2754. sourceURL = join(urlGenerate(parsed), sourceURL);
  2755. }
  2756. return normalize(sourceURL);
  2757. }
  2758. exports.computeSourceURL = computeSourceURL;
  2759. });
  2760. /* -*- Mode: js; js-indent-level: 2; -*- */
  2761. /*
  2762. * Copyright 2011 Mozilla Foundation and contributors
  2763. * Licensed under the New BSD license. See LICENSE or:
  2764. * http://opensource.org/licenses/BSD-3-Clause
  2765. */
  2766. var has = Object.prototype.hasOwnProperty;
  2767. var hasNativeMap = typeof Map !== "undefined";
  2768. /**
  2769. * A data structure which is a combination of an array and a set. Adding a new
  2770. * member is O(1), testing for membership is O(1), and finding the index of an
  2771. * element is O(1). Removing elements from the set is not supported. Only
  2772. * strings are supported for membership.
  2773. */
  2774. function ArraySet() {
  2775. this._array = [];
  2776. this._set = hasNativeMap ? new Map() : Object.create(null);
  2777. }
  2778. /**
  2779. * Static method for creating ArraySet instances from an existing array.
  2780. */
  2781. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  2782. var set = new ArraySet();
  2783. for (var i = 0, len = aArray.length; i < len; i++) {
  2784. set.add(aArray[i], aAllowDuplicates);
  2785. }
  2786. return set;
  2787. };
  2788. /**
  2789. * Return how many unique items are in this ArraySet. If duplicates have been
  2790. * added, than those do not count towards the size.
  2791. *
  2792. * @returns Number
  2793. */
  2794. ArraySet.prototype.size = function ArraySet_size() {
  2795. return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
  2796. };
  2797. /**
  2798. * Add the given string to this set.
  2799. *
  2800. * @param String aStr
  2801. */
  2802. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  2803. var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
  2804. var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  2805. var idx = this._array.length;
  2806. if (!isDuplicate || aAllowDuplicates) {
  2807. this._array.push(aStr);
  2808. }
  2809. if (!isDuplicate) {
  2810. if (hasNativeMap) {
  2811. this._set.set(aStr, idx);
  2812. } else {
  2813. this._set[sStr] = idx;
  2814. }
  2815. }
  2816. };
  2817. /**
  2818. * Is the given string a member of this set?
  2819. *
  2820. * @param String aStr
  2821. */
  2822. ArraySet.prototype.has = function ArraySet_has(aStr) {
  2823. if (hasNativeMap) {
  2824. return this._set.has(aStr);
  2825. } else {
  2826. var sStr = util.toSetString(aStr);
  2827. return has.call(this._set, sStr);
  2828. }
  2829. };
  2830. /**
  2831. * What is the index of the given string in the array?
  2832. *
  2833. * @param String aStr
  2834. */
  2835. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  2836. if (hasNativeMap) {
  2837. var idx = this._set.get(aStr);
  2838. if (idx >= 0) {
  2839. return idx;
  2840. }
  2841. } else {
  2842. var sStr = util.toSetString(aStr);
  2843. if (has.call(this._set, sStr)) {
  2844. return this._set[sStr];
  2845. }
  2846. }
  2847. throw new Error('"' + aStr + '" is not in the set.');
  2848. };
  2849. /**
  2850. * What is the element at the given index?
  2851. *
  2852. * @param Number aIdx
  2853. */
  2854. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  2855. if (aIdx >= 0 && aIdx < this._array.length) {
  2856. return this._array[aIdx];
  2857. }
  2858. throw new Error('No element indexed by ' + aIdx);
  2859. };
  2860. /**
  2861. * Returns the array representation of this set (which has the proper indices
  2862. * indicated by indexOf). Note that this is a copy of the internal array used
  2863. * for storing the members so that no one can mess with internal state.
  2864. */
  2865. ArraySet.prototype.toArray = function ArraySet_toArray() {
  2866. return this._array.slice();
  2867. };
  2868. var ArraySet_1 = ArraySet;
  2869. var arraySet = {
  2870. ArraySet: ArraySet_1
  2871. };
  2872. /* -*- Mode: js; js-indent-level: 2; -*- */
  2873. /*
  2874. * Copyright 2014 Mozilla Foundation and contributors
  2875. * Licensed under the New BSD license. See LICENSE or:
  2876. * http://opensource.org/licenses/BSD-3-Clause
  2877. */
  2878. /**
  2879. * Determine whether mappingB is after mappingA with respect to generated
  2880. * position.
  2881. */
  2882. function generatedPositionAfter(mappingA, mappingB) {
  2883. // Optimized for most common case
  2884. var lineA = mappingA.generatedLine;
  2885. var lineB = mappingB.generatedLine;
  2886. var columnA = mappingA.generatedColumn;
  2887. var columnB = mappingB.generatedColumn;
  2888. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  2889. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  2890. }
  2891. /**
  2892. * A data structure to provide a sorted view of accumulated mappings in a
  2893. * performance conscious manner. It trades a neglibable overhead in general
  2894. * case for a large speedup in case of mappings being added in order.
  2895. */
  2896. function MappingList() {
  2897. this._array = [];
  2898. this._sorted = true;
  2899. // Serves as infimum
  2900. this._last = {generatedLine: -1, generatedColumn: 0};
  2901. }
  2902. /**
  2903. * Iterate through internal items. This method takes the same arguments that
  2904. * `Array.prototype.forEach` takes.
  2905. *
  2906. * NOTE: The order of the mappings is NOT guaranteed.
  2907. */
  2908. MappingList.prototype.unsortedForEach =
  2909. function MappingList_forEach(aCallback, aThisArg) {
  2910. this._array.forEach(aCallback, aThisArg);
  2911. };
  2912. /**
  2913. * Add the given source mapping.
  2914. *
  2915. * @param Object aMapping
  2916. */
  2917. MappingList.prototype.add = function MappingList_add(aMapping) {
  2918. if (generatedPositionAfter(this._last, aMapping)) {
  2919. this._last = aMapping;
  2920. this._array.push(aMapping);
  2921. } else {
  2922. this._sorted = false;
  2923. this._array.push(aMapping);
  2924. }
  2925. };
  2926. /**
  2927. * Returns the flat, sorted array of mappings. The mappings are sorted by
  2928. * generated position.
  2929. *
  2930. * WARNING: This method returns internal data without copying, for
  2931. * performance. The return value must NOT be mutated, and should be treated as
  2932. * an immutable borrow. If you want to take ownership, you must make your own
  2933. * copy.
  2934. */
  2935. MappingList.prototype.toArray = function MappingList_toArray() {
  2936. if (!this._sorted) {
  2937. this._array.sort(util.compareByGeneratedPositionsInflated);
  2938. this._sorted = true;
  2939. }
  2940. return this._array;
  2941. };
  2942. var MappingList_1 = MappingList;
  2943. var mappingList = {
  2944. MappingList: MappingList_1
  2945. };
  2946. /* -*- Mode: js; js-indent-level: 2; -*- */
  2947. /*
  2948. * Copyright 2011 Mozilla Foundation and contributors
  2949. * Licensed under the New BSD license. See LICENSE or:
  2950. * http://opensource.org/licenses/BSD-3-Clause
  2951. */
  2952. var ArraySet$1 = arraySet.ArraySet;
  2953. var MappingList$1 = mappingList.MappingList;
  2954. /**
  2955. * An instance of the SourceMapGenerator represents a source map which is
  2956. * being built incrementally. You may pass an object with the following
  2957. * properties:
  2958. *
  2959. * - file: The filename of the generated source.
  2960. * - sourceRoot: A root for all relative URLs in this source map.
  2961. */
  2962. function SourceMapGenerator(aArgs) {
  2963. if (!aArgs) {
  2964. aArgs = {};
  2965. }
  2966. this._file = util.getArg(aArgs, 'file', null);
  2967. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  2968. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  2969. this._sources = new ArraySet$1();
  2970. this._names = new ArraySet$1();
  2971. this._mappings = new MappingList$1();
  2972. this._sourcesContents = null;
  2973. }
  2974. SourceMapGenerator.prototype._version = 3;
  2975. /**
  2976. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  2977. *
  2978. * @param aSourceMapConsumer The SourceMap.
  2979. */
  2980. SourceMapGenerator.fromSourceMap =
  2981. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  2982. var sourceRoot = aSourceMapConsumer.sourceRoot;
  2983. var generator = new SourceMapGenerator({
  2984. file: aSourceMapConsumer.file,
  2985. sourceRoot: sourceRoot
  2986. });
  2987. aSourceMapConsumer.eachMapping(function (mapping) {
  2988. var newMapping = {
  2989. generated: {
  2990. line: mapping.generatedLine,
  2991. column: mapping.generatedColumn
  2992. }
  2993. };
  2994. if (mapping.source != null) {
  2995. newMapping.source = mapping.source;
  2996. if (sourceRoot != null) {
  2997. newMapping.source = util.relative(sourceRoot, newMapping.source);
  2998. }
  2999. newMapping.original = {
  3000. line: mapping.originalLine,
  3001. column: mapping.originalColumn
  3002. };
  3003. if (mapping.name != null) {
  3004. newMapping.name = mapping.name;
  3005. }
  3006. }
  3007. generator.addMapping(newMapping);
  3008. });
  3009. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  3010. var sourceRelative = sourceFile;
  3011. if (sourceRoot !== null) {
  3012. sourceRelative = util.relative(sourceRoot, sourceFile);
  3013. }
  3014. if (!generator._sources.has(sourceRelative)) {
  3015. generator._sources.add(sourceRelative);
  3016. }
  3017. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  3018. if (content != null) {
  3019. generator.setSourceContent(sourceFile, content);
  3020. }
  3021. });
  3022. return generator;
  3023. };
  3024. /**
  3025. * Add a single mapping from original source line and column to the generated
  3026. * source's line and column for this source map being created. The mapping
  3027. * object should have the following properties:
  3028. *
  3029. * - generated: An object with the generated line and column positions.
  3030. * - original: An object with the original line and column positions.
  3031. * - source: The original source file (relative to the sourceRoot).
  3032. * - name: An optional original token name for this mapping.
  3033. */
  3034. SourceMapGenerator.prototype.addMapping =
  3035. function SourceMapGenerator_addMapping(aArgs) {
  3036. var generated = util.getArg(aArgs, 'generated');
  3037. var original = util.getArg(aArgs, 'original', null);
  3038. var source = util.getArg(aArgs, 'source', null);
  3039. var name = util.getArg(aArgs, 'name', null);
  3040. if (!this._skipValidation) {
  3041. this._validateMapping(generated, original, source, name);
  3042. }
  3043. if (source != null) {
  3044. source = String(source);
  3045. if (!this._sources.has(source)) {
  3046. this._sources.add(source);
  3047. }
  3048. }
  3049. if (name != null) {
  3050. name = String(name);
  3051. if (!this._names.has(name)) {
  3052. this._names.add(name);
  3053. }
  3054. }
  3055. this._mappings.add({
  3056. generatedLine: generated.line,
  3057. generatedColumn: generated.column,
  3058. originalLine: original != null && original.line,
  3059. originalColumn: original != null && original.column,
  3060. source: source,
  3061. name: name
  3062. });
  3063. };
  3064. /**
  3065. * Set the source content for a source file.
  3066. */
  3067. SourceMapGenerator.prototype.setSourceContent =
  3068. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  3069. var source = aSourceFile;
  3070. if (this._sourceRoot != null) {
  3071. source = util.relative(this._sourceRoot, source);
  3072. }
  3073. if (aSourceContent != null) {
  3074. // Add the source content to the _sourcesContents map.
  3075. // Create a new _sourcesContents map if the property is null.
  3076. if (!this._sourcesContents) {
  3077. this._sourcesContents = Object.create(null);
  3078. }
  3079. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  3080. } else if (this._sourcesContents) {
  3081. // Remove the source file from the _sourcesContents map.
  3082. // If the _sourcesContents map is empty, set the property to null.
  3083. delete this._sourcesContents[util.toSetString(source)];
  3084. if (Object.keys(this._sourcesContents).length === 0) {
  3085. this._sourcesContents = null;
  3086. }
  3087. }
  3088. };
  3089. /**
  3090. * Applies the mappings of a sub-source-map for a specific source file to the
  3091. * source map being generated. Each mapping to the supplied source file is
  3092. * rewritten using the supplied source map. Note: The resolution for the
  3093. * resulting mappings is the minimium of this map and the supplied map.
  3094. *
  3095. * @param aSourceMapConsumer The source map to be applied.
  3096. * @param aSourceFile Optional. The filename of the source file.
  3097. * If omitted, SourceMapConsumer's file property will be used.
  3098. * @param aSourceMapPath Optional. The dirname of the path to the source map
  3099. * to be applied. If relative, it is relative to the SourceMapConsumer.
  3100. * This parameter is needed when the two source maps aren't in the same
  3101. * directory, and the source map to be applied contains relative source
  3102. * paths. If so, those relative source paths need to be rewritten
  3103. * relative to the SourceMapGenerator.
  3104. */
  3105. SourceMapGenerator.prototype.applySourceMap =
  3106. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  3107. var sourceFile = aSourceFile;
  3108. // If aSourceFile is omitted, we will use the file property of the SourceMap
  3109. if (aSourceFile == null) {
  3110. if (aSourceMapConsumer.file == null) {
  3111. throw new Error(
  3112. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  3113. 'or the source map\'s "file" property. Both were omitted.'
  3114. );
  3115. }
  3116. sourceFile = aSourceMapConsumer.file;
  3117. }
  3118. var sourceRoot = this._sourceRoot;
  3119. // Make "sourceFile" relative if an absolute Url is passed.
  3120. if (sourceRoot != null) {
  3121. sourceFile = util.relative(sourceRoot, sourceFile);
  3122. }
  3123. // Applying the SourceMap can add and remove items from the sources and
  3124. // the names array.
  3125. var newSources = new ArraySet$1();
  3126. var newNames = new ArraySet$1();
  3127. // Find mappings for the "sourceFile"
  3128. this._mappings.unsortedForEach(function (mapping) {
  3129. if (mapping.source === sourceFile && mapping.originalLine != null) {
  3130. // Check if it can be mapped by the source map, then update the mapping.
  3131. var original = aSourceMapConsumer.originalPositionFor({
  3132. line: mapping.originalLine,
  3133. column: mapping.originalColumn
  3134. });
  3135. if (original.source != null) {
  3136. // Copy mapping
  3137. mapping.source = original.source;
  3138. if (aSourceMapPath != null) {
  3139. mapping.source = util.join(aSourceMapPath, mapping.source);
  3140. }
  3141. if (sourceRoot != null) {
  3142. mapping.source = util.relative(sourceRoot, mapping.source);
  3143. }
  3144. mapping.originalLine = original.line;
  3145. mapping.originalColumn = original.column;
  3146. if (original.name != null) {
  3147. mapping.name = original.name;
  3148. }
  3149. }
  3150. }
  3151. var source = mapping.source;
  3152. if (source != null && !newSources.has(source)) {
  3153. newSources.add(source);
  3154. }
  3155. var name = mapping.name;
  3156. if (name != null && !newNames.has(name)) {
  3157. newNames.add(name);
  3158. }
  3159. }, this);
  3160. this._sources = newSources;
  3161. this._names = newNames;
  3162. // Copy sourcesContents of applied map.
  3163. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  3164. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  3165. if (content != null) {
  3166. if (aSourceMapPath != null) {
  3167. sourceFile = util.join(aSourceMapPath, sourceFile);
  3168. }
  3169. if (sourceRoot != null) {
  3170. sourceFile = util.relative(sourceRoot, sourceFile);
  3171. }
  3172. this.setSourceContent(sourceFile, content);
  3173. }
  3174. }, this);
  3175. };
  3176. /**
  3177. * A mapping can have one of the three levels of data:
  3178. *
  3179. * 1. Just the generated position.
  3180. * 2. The Generated position, original position, and original source.
  3181. * 3. Generated and original position, original source, as well as a name
  3182. * token.
  3183. *
  3184. * To maintain consistency, we validate that any new mapping being added falls
  3185. * in to one of these categories.
  3186. */
  3187. SourceMapGenerator.prototype._validateMapping =
  3188. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  3189. aName) {
  3190. // When aOriginal is truthy but has empty values for .line and .column,
  3191. // it is most likely a programmer error. In this case we throw a very
  3192. // specific error message to try to guide them the right way.
  3193. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  3194. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  3195. throw new Error(
  3196. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  3197. 'the original mapping entirely and only map the generated position. If so, pass ' +
  3198. 'null for the original mapping instead of an object with empty or null values.'
  3199. );
  3200. }
  3201. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  3202. && aGenerated.line > 0 && aGenerated.column >= 0
  3203. && !aOriginal && !aSource && !aName) {
  3204. // Case 1.
  3205. return;
  3206. }
  3207. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  3208. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  3209. && aGenerated.line > 0 && aGenerated.column >= 0
  3210. && aOriginal.line > 0 && aOriginal.column >= 0
  3211. && aSource) {
  3212. // Cases 2 and 3.
  3213. return;
  3214. }
  3215. else {
  3216. throw new Error('Invalid mapping: ' + JSON.stringify({
  3217. generated: aGenerated,
  3218. source: aSource,
  3219. original: aOriginal,
  3220. name: aName
  3221. }));
  3222. }
  3223. };
  3224. /**
  3225. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  3226. * specified by the source map format.
  3227. */
  3228. SourceMapGenerator.prototype._serializeMappings =
  3229. function SourceMapGenerator_serializeMappings() {
  3230. var previousGeneratedColumn = 0;
  3231. var previousGeneratedLine = 1;
  3232. var previousOriginalColumn = 0;
  3233. var previousOriginalLine = 0;
  3234. var previousName = 0;
  3235. var previousSource = 0;
  3236. var result = '';
  3237. var next;
  3238. var mapping;
  3239. var nameIdx;
  3240. var sourceIdx;
  3241. var mappings = this._mappings.toArray();
  3242. for (var i = 0, len = mappings.length; i < len; i++) {
  3243. mapping = mappings[i];
  3244. next = '';
  3245. if (mapping.generatedLine !== previousGeneratedLine) {
  3246. previousGeneratedColumn = 0;
  3247. while (mapping.generatedLine !== previousGeneratedLine) {
  3248. next += ';';
  3249. previousGeneratedLine++;
  3250. }
  3251. }
  3252. else {
  3253. if (i > 0) {
  3254. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  3255. continue;
  3256. }
  3257. next += ',';
  3258. }
  3259. }
  3260. next += base64Vlq.encode(mapping.generatedColumn
  3261. - previousGeneratedColumn);
  3262. previousGeneratedColumn = mapping.generatedColumn;
  3263. if (mapping.source != null) {
  3264. sourceIdx = this._sources.indexOf(mapping.source);
  3265. next += base64Vlq.encode(sourceIdx - previousSource);
  3266. previousSource = sourceIdx;
  3267. // lines are stored 0-based in SourceMap spec version 3
  3268. next += base64Vlq.encode(mapping.originalLine - 1
  3269. - previousOriginalLine);
  3270. previousOriginalLine = mapping.originalLine - 1;
  3271. next += base64Vlq.encode(mapping.originalColumn
  3272. - previousOriginalColumn);
  3273. previousOriginalColumn = mapping.originalColumn;
  3274. if (mapping.name != null) {
  3275. nameIdx = this._names.indexOf(mapping.name);
  3276. next += base64Vlq.encode(nameIdx - previousName);
  3277. previousName = nameIdx;
  3278. }
  3279. }
  3280. result += next;
  3281. }
  3282. return result;
  3283. };
  3284. SourceMapGenerator.prototype._generateSourcesContent =
  3285. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  3286. return aSources.map(function (source) {
  3287. if (!this._sourcesContents) {
  3288. return null;
  3289. }
  3290. if (aSourceRoot != null) {
  3291. source = util.relative(aSourceRoot, source);
  3292. }
  3293. var key = util.toSetString(source);
  3294. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  3295. ? this._sourcesContents[key]
  3296. : null;
  3297. }, this);
  3298. };
  3299. /**
  3300. * Externalize the source map.
  3301. */
  3302. SourceMapGenerator.prototype.toJSON =
  3303. function SourceMapGenerator_toJSON() {
  3304. var map = {
  3305. version: this._version,
  3306. sources: this._sources.toArray(),
  3307. names: this._names.toArray(),
  3308. mappings: this._serializeMappings()
  3309. };
  3310. if (this._file != null) {
  3311. map.file = this._file;
  3312. }
  3313. if (this._sourceRoot != null) {
  3314. map.sourceRoot = this._sourceRoot;
  3315. }
  3316. if (this._sourcesContents) {
  3317. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  3318. }
  3319. return map;
  3320. };
  3321. /**
  3322. * Render the source map being generated to a string.
  3323. */
  3324. SourceMapGenerator.prototype.toString =
  3325. function SourceMapGenerator_toString() {
  3326. return JSON.stringify(this.toJSON());
  3327. };
  3328. var SourceMapGenerator_1 = SourceMapGenerator;
  3329. var sourceMapGenerator = {
  3330. SourceMapGenerator: SourceMapGenerator_1
  3331. };
  3332. /* -*- Mode: js; js-indent-level: 2; -*- */
  3333. var binarySearch = createCommonjsModule(function (module, exports) {
  3334. /*
  3335. * Copyright 2011 Mozilla Foundation and contributors
  3336. * Licensed under the New BSD license. See LICENSE or:
  3337. * http://opensource.org/licenses/BSD-3-Clause
  3338. */
  3339. exports.GREATEST_LOWER_BOUND = 1;
  3340. exports.LEAST_UPPER_BOUND = 2;
  3341. /**
  3342. * Recursive implementation of binary search.
  3343. *
  3344. * @param aLow Indices here and lower do not contain the needle.
  3345. * @param aHigh Indices here and higher do not contain the needle.
  3346. * @param aNeedle The element being searched for.
  3347. * @param aHaystack The non-empty array being searched.
  3348. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  3349. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  3350. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  3351. * closest element that is smaller than or greater than the one we are
  3352. * searching for, respectively, if the exact element cannot be found.
  3353. */
  3354. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  3355. // This function terminates when one of the following is true:
  3356. //
  3357. // 1. We find the exact element we are looking for.
  3358. //
  3359. // 2. We did not find the exact element, but we can return the index of
  3360. // the next-closest element.
  3361. //
  3362. // 3. We did not find the exact element, and there is no next-closest
  3363. // element than the one we are searching for, so we return -1.
  3364. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  3365. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  3366. if (cmp === 0) {
  3367. // Found the element we are looking for.
  3368. return mid;
  3369. }
  3370. else if (cmp > 0) {
  3371. // Our needle is greater than aHaystack[mid].
  3372. if (aHigh - mid > 1) {
  3373. // The element is in the upper half.
  3374. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  3375. }
  3376. // The exact needle element was not found in this haystack. Determine if
  3377. // we are in termination case (3) or (2) and return the appropriate thing.
  3378. if (aBias == exports.LEAST_UPPER_BOUND) {
  3379. return aHigh < aHaystack.length ? aHigh : -1;
  3380. } else {
  3381. return mid;
  3382. }
  3383. }
  3384. else {
  3385. // Our needle is less than aHaystack[mid].
  3386. if (mid - aLow > 1) {
  3387. // The element is in the lower half.
  3388. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  3389. }
  3390. // we are in termination case (3) or (2) and return the appropriate thing.
  3391. if (aBias == exports.LEAST_UPPER_BOUND) {
  3392. return mid;
  3393. } else {
  3394. return aLow < 0 ? -1 : aLow;
  3395. }
  3396. }
  3397. }
  3398. /**
  3399. * This is an implementation of binary search which will always try and return
  3400. * the index of the closest element if there is no exact hit. This is because
  3401. * mappings between original and generated line/col pairs are single points,
  3402. * and there is an implicit region between each of them, so a miss just means
  3403. * that you aren't on the very start of a region.
  3404. *
  3405. * @param aNeedle The element you are looking for.
  3406. * @param aHaystack The array that is being searched.
  3407. * @param aCompare A function which takes the needle and an element in the
  3408. * array and returns -1, 0, or 1 depending on whether the needle is less
  3409. * than, equal to, or greater than the element, respectively.
  3410. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  3411. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  3412. * closest element that is smaller than or greater than the one we are
  3413. * searching for, respectively, if the exact element cannot be found.
  3414. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  3415. */
  3416. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  3417. if (aHaystack.length === 0) {
  3418. return -1;
  3419. }
  3420. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  3421. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  3422. if (index < 0) {
  3423. return -1;
  3424. }
  3425. // We have found either the exact element, or the next-closest element than
  3426. // the one we are searching for. However, there may be more than one such
  3427. // element. Make sure we always return the smallest of these.
  3428. while (index - 1 >= 0) {
  3429. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  3430. break;
  3431. }
  3432. --index;
  3433. }
  3434. return index;
  3435. };
  3436. });
  3437. /* -*- Mode: js; js-indent-level: 2; -*- */
  3438. /*
  3439. * Copyright 2011 Mozilla Foundation and contributors
  3440. * Licensed under the New BSD license. See LICENSE or:
  3441. * http://opensource.org/licenses/BSD-3-Clause
  3442. */
  3443. // It turns out that some (most?) JavaScript engines don't self-host
  3444. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  3445. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  3446. // custom comparator function, calling back and forth between the VM's C++ and
  3447. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  3448. // worse generated code for the comparator function than would be optimal. In
  3449. // fact, when sorting with a comparator, these costs outweigh the benefits of
  3450. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  3451. // a ~3500ms mean speed-up in `bench/bench.html`.
  3452. /**
  3453. * Swap the elements indexed by `x` and `y` in the array `ary`.
  3454. *
  3455. * @param {Array} ary
  3456. * The array.
  3457. * @param {Number} x
  3458. * The index of the first item.
  3459. * @param {Number} y
  3460. * The index of the second item.
  3461. */
  3462. function swap(ary, x, y) {
  3463. var temp = ary[x];
  3464. ary[x] = ary[y];
  3465. ary[y] = temp;
  3466. }
  3467. /**
  3468. * Returns a random integer within the range `low .. high` inclusive.
  3469. *
  3470. * @param {Number} low
  3471. * The lower bound on the range.
  3472. * @param {Number} high
  3473. * The upper bound on the range.
  3474. */
  3475. function randomIntInRange(low, high) {
  3476. return Math.round(low + (Math.random() * (high - low)));
  3477. }
  3478. /**
  3479. * The Quick Sort algorithm.
  3480. *
  3481. * @param {Array} ary
  3482. * An array to sort.
  3483. * @param {function} comparator
  3484. * Function to use to compare two items.
  3485. * @param {Number} p
  3486. * Start index of the array
  3487. * @param {Number} r
  3488. * End index of the array
  3489. */
  3490. function doQuickSort(ary, comparator, p, r) {
  3491. // If our lower bound is less than our upper bound, we (1) partition the
  3492. // array into two pieces and (2) recurse on each half. If it is not, this is
  3493. // the empty array and our base case.
  3494. if (p < r) {
  3495. // (1) Partitioning.
  3496. //
  3497. // The partitioning chooses a pivot between `p` and `r` and moves all
  3498. // elements that are less than or equal to the pivot to the before it, and
  3499. // all the elements that are greater than it after it. The effect is that
  3500. // once partition is done, the pivot is in the exact place it will be when
  3501. // the array is put in sorted order, and it will not need to be moved
  3502. // again. This runs in O(n) time.
  3503. // Always choose a random pivot so that an input array which is reverse
  3504. // sorted does not cause O(n^2) running time.
  3505. var pivotIndex = randomIntInRange(p, r);
  3506. var i = p - 1;
  3507. swap(ary, pivotIndex, r);
  3508. var pivot = ary[r];
  3509. // Immediately after `j` is incremented in this loop, the following hold
  3510. // true:
  3511. //
  3512. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  3513. //
  3514. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  3515. for (var j = p; j < r; j++) {
  3516. if (comparator(ary[j], pivot) <= 0) {
  3517. i += 1;
  3518. swap(ary, i, j);
  3519. }
  3520. }
  3521. swap(ary, i + 1, j);
  3522. var q = i + 1;
  3523. // (2) Recurse on each half.
  3524. doQuickSort(ary, comparator, p, q - 1);
  3525. doQuickSort(ary, comparator, q + 1, r);
  3526. }
  3527. }
  3528. /**
  3529. * Sort the given array in-place with the given comparator function.
  3530. *
  3531. * @param {Array} ary
  3532. * An array to sort.
  3533. * @param {function} comparator
  3534. * Function to use to compare two items.
  3535. */
  3536. var quickSort_1 = function (ary, comparator) {
  3537. doQuickSort(ary, comparator, 0, ary.length - 1);
  3538. };
  3539. var quickSort = {
  3540. quickSort: quickSort_1
  3541. };
  3542. /* -*- Mode: js; js-indent-level: 2; -*- */
  3543. /*
  3544. * Copyright 2011 Mozilla Foundation and contributors
  3545. * Licensed under the New BSD license. See LICENSE or:
  3546. * http://opensource.org/licenses/BSD-3-Clause
  3547. */
  3548. var ArraySet$2 = arraySet.ArraySet;
  3549. var quickSort$1 = quickSort.quickSort;
  3550. function SourceMapConsumer(aSourceMap, aSourceMapURL) {
  3551. var sourceMap = aSourceMap;
  3552. if (typeof aSourceMap === 'string') {
  3553. sourceMap = util.parseSourceMapInput(aSourceMap);
  3554. }
  3555. return sourceMap.sections != null
  3556. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  3557. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
  3558. }
  3559. SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  3560. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
  3561. };
  3562. /**
  3563. * The version of the source mapping spec that we are consuming.
  3564. */
  3565. SourceMapConsumer.prototype._version = 3;
  3566. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  3567. // parsed mapping coordinates from the source map's "mappings" attribute. They
  3568. // are lazily instantiated, accessed via the `_generatedMappings` and
  3569. // `_originalMappings` getters respectively, and we only parse the mappings
  3570. // and create these arrays once queried for a source location. We jump through
  3571. // these hoops because there can be many thousands of mappings, and parsing
  3572. // them is expensive, so we only want to do it if we must.
  3573. //
  3574. // Each object in the arrays is of the form:
  3575. //
  3576. // {
  3577. // generatedLine: The line number in the generated code,
  3578. // generatedColumn: The column number in the generated code,
  3579. // source: The path to the original source file that generated this
  3580. // chunk of code,
  3581. // originalLine: The line number in the original source that
  3582. // corresponds to this chunk of generated code,
  3583. // originalColumn: The column number in the original source that
  3584. // corresponds to this chunk of generated code,
  3585. // name: The name of the original symbol which generated this chunk of
  3586. // code.
  3587. // }
  3588. //
  3589. // All properties except for `generatedLine` and `generatedColumn` can be
  3590. // `null`.
  3591. //
  3592. // `_generatedMappings` is ordered by the generated positions.
  3593. //
  3594. // `_originalMappings` is ordered by the original positions.
  3595. SourceMapConsumer.prototype.__generatedMappings = null;
  3596. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  3597. configurable: true,
  3598. enumerable: true,
  3599. get: function () {
  3600. if (!this.__generatedMappings) {
  3601. this._parseMappings(this._mappings, this.sourceRoot);
  3602. }
  3603. return this.__generatedMappings;
  3604. }
  3605. });
  3606. SourceMapConsumer.prototype.__originalMappings = null;
  3607. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  3608. configurable: true,
  3609. enumerable: true,
  3610. get: function () {
  3611. if (!this.__originalMappings) {
  3612. this._parseMappings(this._mappings, this.sourceRoot);
  3613. }
  3614. return this.__originalMappings;
  3615. }
  3616. });
  3617. SourceMapConsumer.prototype._charIsMappingSeparator =
  3618. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  3619. var c = aStr.charAt(index);
  3620. return c === ";" || c === ",";
  3621. };
  3622. /**
  3623. * Parse the mappings in a string in to a data structure which we can easily
  3624. * query (the ordered arrays in the `this.__generatedMappings` and
  3625. * `this.__originalMappings` properties).
  3626. */
  3627. SourceMapConsumer.prototype._parseMappings =
  3628. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  3629. throw new Error("Subclasses must implement _parseMappings");
  3630. };
  3631. SourceMapConsumer.GENERATED_ORDER = 1;
  3632. SourceMapConsumer.ORIGINAL_ORDER = 2;
  3633. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  3634. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  3635. /**
  3636. * Iterate over each mapping between an original source/line/column and a
  3637. * generated line/column in this source map.
  3638. *
  3639. * @param Function aCallback
  3640. * The function that is called with each mapping.
  3641. * @param Object aContext
  3642. * Optional. If specified, this object will be the value of `this` every
  3643. * time that `aCallback` is called.
  3644. * @param aOrder
  3645. * Either `SourceMapConsumer.GENERATED_ORDER` or
  3646. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  3647. * iterate over the mappings sorted by the generated file's line/column
  3648. * order or the original's source/line/column order, respectively. Defaults to
  3649. * `SourceMapConsumer.GENERATED_ORDER`.
  3650. */
  3651. SourceMapConsumer.prototype.eachMapping =
  3652. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  3653. var context = aContext || null;
  3654. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  3655. var mappings;
  3656. switch (order) {
  3657. case SourceMapConsumer.GENERATED_ORDER:
  3658. mappings = this._generatedMappings;
  3659. break;
  3660. case SourceMapConsumer.ORIGINAL_ORDER:
  3661. mappings = this._originalMappings;
  3662. break;
  3663. default:
  3664. throw new Error("Unknown order of iteration.");
  3665. }
  3666. var sourceRoot = this.sourceRoot;
  3667. mappings.map(function (mapping) {
  3668. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  3669. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL);
  3670. return {
  3671. source: source,
  3672. generatedLine: mapping.generatedLine,
  3673. generatedColumn: mapping.generatedColumn,
  3674. originalLine: mapping.originalLine,
  3675. originalColumn: mapping.originalColumn,
  3676. name: mapping.name === null ? null : this._names.at(mapping.name)
  3677. };
  3678. }, this).forEach(aCallback, context);
  3679. };
  3680. /**
  3681. * Returns all generated line and column information for the original source,
  3682. * line, and column provided. If no column is provided, returns all mappings
  3683. * corresponding to a either the line we are searching for or the next
  3684. * closest line that has any mappings. Otherwise, returns all mappings
  3685. * corresponding to the given line and either the column we are searching for
  3686. * or the next closest column that has any offsets.
  3687. *
  3688. * The only argument is an object with the following properties:
  3689. *
  3690. * - source: The filename of the original source.
  3691. * - line: The line number in the original source. The line number is 1-based.
  3692. * - column: Optional. the column number in the original source.
  3693. * The column number is 0-based.
  3694. *
  3695. * and an array of objects is returned, each with the following properties:
  3696. *
  3697. * - line: The line number in the generated source, or null. The
  3698. * line number is 1-based.
  3699. * - column: The column number in the generated source, or null.
  3700. * The column number is 0-based.
  3701. */
  3702. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  3703. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  3704. var line = util.getArg(aArgs, 'line');
  3705. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  3706. // returns the index of the closest mapping less than the needle. By
  3707. // setting needle.originalColumn to 0, we thus find the last mapping for
  3708. // the given line, provided such a mapping exists.
  3709. var needle = {
  3710. source: util.getArg(aArgs, 'source'),
  3711. originalLine: line,
  3712. originalColumn: util.getArg(aArgs, 'column', 0)
  3713. };
  3714. needle.source = this._findSourceIndex(needle.source);
  3715. if (needle.source < 0) {
  3716. return [];
  3717. }
  3718. var mappings = [];
  3719. var index = this._findMapping(needle,
  3720. this._originalMappings,
  3721. "originalLine",
  3722. "originalColumn",
  3723. util.compareByOriginalPositions,
  3724. binarySearch.LEAST_UPPER_BOUND);
  3725. if (index >= 0) {
  3726. var mapping = this._originalMappings[index];
  3727. if (aArgs.column === undefined) {
  3728. var originalLine = mapping.originalLine;
  3729. // Iterate until either we run out of mappings, or we run into
  3730. // a mapping for a different line than the one we found. Since
  3731. // mappings are sorted, this is guaranteed to find all mappings for
  3732. // the line we found.
  3733. while (mapping && mapping.originalLine === originalLine) {
  3734. mappings.push({
  3735. line: util.getArg(mapping, 'generatedLine', null),
  3736. column: util.getArg(mapping, 'generatedColumn', null),
  3737. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  3738. });
  3739. mapping = this._originalMappings[++index];
  3740. }
  3741. } else {
  3742. var originalColumn = mapping.originalColumn;
  3743. // Iterate until either we run out of mappings, or we run into
  3744. // a mapping for a different line than the one we were searching for.
  3745. // Since mappings are sorted, this is guaranteed to find all mappings for
  3746. // the line we are searching for.
  3747. while (mapping &&
  3748. mapping.originalLine === line &&
  3749. mapping.originalColumn == originalColumn) {
  3750. mappings.push({
  3751. line: util.getArg(mapping, 'generatedLine', null),
  3752. column: util.getArg(mapping, 'generatedColumn', null),
  3753. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  3754. });
  3755. mapping = this._originalMappings[++index];
  3756. }
  3757. }
  3758. }
  3759. return mappings;
  3760. };
  3761. var SourceMapConsumer_1 = SourceMapConsumer;
  3762. /**
  3763. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  3764. * query for information about the original file positions by giving it a file
  3765. * position in the generated source.
  3766. *
  3767. * The first parameter is the raw source map (either as a JSON string, or
  3768. * already parsed to an object). According to the spec, source maps have the
  3769. * following attributes:
  3770. *
  3771. * - version: Which version of the source map spec this map is following.
  3772. * - sources: An array of URLs to the original source files.
  3773. * - names: An array of identifiers which can be referrenced by individual mappings.
  3774. * - sourceRoot: Optional. The URL root from which all sources are relative.
  3775. * - sourcesContent: Optional. An array of contents of the original source files.
  3776. * - mappings: A string of base64 VLQs which contain the actual mappings.
  3777. * - file: Optional. The generated file this source map is associated with.
  3778. *
  3779. * Here is an example source map, taken from the source map spec[0]:
  3780. *
  3781. * {
  3782. * version : 3,
  3783. * file: "out.js",
  3784. * sourceRoot : "",
  3785. * sources: ["foo.js", "bar.js"],
  3786. * names: ["src", "maps", "are", "fun"],
  3787. * mappings: "AA,AB;;ABCDE;"
  3788. * }
  3789. *
  3790. * The second parameter, if given, is a string whose value is the URL
  3791. * at which the source map was found. This URL is used to compute the
  3792. * sources array.
  3793. *
  3794. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  3795. */
  3796. function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  3797. var sourceMap = aSourceMap;
  3798. if (typeof aSourceMap === 'string') {
  3799. sourceMap = util.parseSourceMapInput(aSourceMap);
  3800. }
  3801. var version = util.getArg(sourceMap, 'version');
  3802. var sources = util.getArg(sourceMap, 'sources');
  3803. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  3804. // requires the array) to play nice here.
  3805. var names = util.getArg(sourceMap, 'names', []);
  3806. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  3807. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  3808. var mappings = util.getArg(sourceMap, 'mappings');
  3809. var file = util.getArg(sourceMap, 'file', null);
  3810. // Once again, Sass deviates from the spec and supplies the version as a
  3811. // string rather than a number, so we use loose equality checking here.
  3812. if (version != this._version) {
  3813. throw new Error('Unsupported version: ' + version);
  3814. }
  3815. if (sourceRoot) {
  3816. sourceRoot = util.normalize(sourceRoot);
  3817. }
  3818. sources = sources
  3819. .map(String)
  3820. // Some source maps produce relative source paths like "./foo.js" instead of
  3821. // "foo.js". Normalize these first so that future comparisons will succeed.
  3822. // See bugzil.la/1090768.
  3823. .map(util.normalize)
  3824. // Always ensure that absolute sources are internally stored relative to
  3825. // the source root, if the source root is absolute. Not doing this would
  3826. // be particularly problematic when the source root is a prefix of the
  3827. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  3828. .map(function (source) {
  3829. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  3830. ? util.relative(sourceRoot, source)
  3831. : source;
  3832. });
  3833. // Pass `true` below to allow duplicate names and sources. While source maps
  3834. // are intended to be compressed and deduplicated, the TypeScript compiler
  3835. // sometimes generates source maps with duplicates in them. See Github issue
  3836. // #72 and bugzil.la/889492.
  3837. this._names = ArraySet$2.fromArray(names.map(String), true);
  3838. this._sources = ArraySet$2.fromArray(sources, true);
  3839. this._absoluteSources = this._sources.toArray().map(function (s) {
  3840. return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
  3841. });
  3842. this.sourceRoot = sourceRoot;
  3843. this.sourcesContent = sourcesContent;
  3844. this._mappings = mappings;
  3845. this._sourceMapURL = aSourceMapURL;
  3846. this.file = file;
  3847. }
  3848. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  3849. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  3850. /**
  3851. * Utility function to find the index of a source. Returns -1 if not
  3852. * found.
  3853. */
  3854. BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  3855. var relativeSource = aSource;
  3856. if (this.sourceRoot != null) {
  3857. relativeSource = util.relative(this.sourceRoot, relativeSource);
  3858. }
  3859. if (this._sources.has(relativeSource)) {
  3860. return this._sources.indexOf(relativeSource);
  3861. }
  3862. // Maybe aSource is an absolute URL as returned by |sources|. In
  3863. // this case we can't simply undo the transform.
  3864. var i;
  3865. for (i = 0; i < this._absoluteSources.length; ++i) {
  3866. if (this._absoluteSources[i] == aSource) {
  3867. return i;
  3868. }
  3869. }
  3870. return -1;
  3871. };
  3872. /**
  3873. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  3874. *
  3875. * @param SourceMapGenerator aSourceMap
  3876. * The source map that will be consumed.
  3877. * @param String aSourceMapURL
  3878. * The URL at which the source map can be found (optional)
  3879. * @returns BasicSourceMapConsumer
  3880. */
  3881. BasicSourceMapConsumer.fromSourceMap =
  3882. function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  3883. var smc = Object.create(BasicSourceMapConsumer.prototype);
  3884. var names = smc._names = ArraySet$2.fromArray(aSourceMap._names.toArray(), true);
  3885. var sources = smc._sources = ArraySet$2.fromArray(aSourceMap._sources.toArray(), true);
  3886. smc.sourceRoot = aSourceMap._sourceRoot;
  3887. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  3888. smc.sourceRoot);
  3889. smc.file = aSourceMap._file;
  3890. smc._sourceMapURL = aSourceMapURL;
  3891. smc._absoluteSources = smc._sources.toArray().map(function (s) {
  3892. return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  3893. });
  3894. // Because we are modifying the entries (by converting string sources and
  3895. // names to indices into the sources and names ArraySets), we have to make
  3896. // a copy of the entry or else bad things happen. Shared mutable state
  3897. // strikes again! See github issue #191.
  3898. var generatedMappings = aSourceMap._mappings.toArray().slice();
  3899. var destGeneratedMappings = smc.__generatedMappings = [];
  3900. var destOriginalMappings = smc.__originalMappings = [];
  3901. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  3902. var srcMapping = generatedMappings[i];
  3903. var destMapping = new Mapping;
  3904. destMapping.generatedLine = srcMapping.generatedLine;
  3905. destMapping.generatedColumn = srcMapping.generatedColumn;
  3906. if (srcMapping.source) {
  3907. destMapping.source = sources.indexOf(srcMapping.source);
  3908. destMapping.originalLine = srcMapping.originalLine;
  3909. destMapping.originalColumn = srcMapping.originalColumn;
  3910. if (srcMapping.name) {
  3911. destMapping.name = names.indexOf(srcMapping.name);
  3912. }
  3913. destOriginalMappings.push(destMapping);
  3914. }
  3915. destGeneratedMappings.push(destMapping);
  3916. }
  3917. quickSort$1(smc.__originalMappings, util.compareByOriginalPositions);
  3918. return smc;
  3919. };
  3920. /**
  3921. * The version of the source mapping spec that we are consuming.
  3922. */
  3923. BasicSourceMapConsumer.prototype._version = 3;
  3924. /**
  3925. * The list of original sources.
  3926. */
  3927. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  3928. get: function () {
  3929. return this._absoluteSources.slice();
  3930. }
  3931. });
  3932. /**
  3933. * Provide the JIT with a nice shape / hidden class.
  3934. */
  3935. function Mapping() {
  3936. this.generatedLine = 0;
  3937. this.generatedColumn = 0;
  3938. this.source = null;
  3939. this.originalLine = null;
  3940. this.originalColumn = null;
  3941. this.name = null;
  3942. }
  3943. /**
  3944. * Parse the mappings in a string in to a data structure which we can easily
  3945. * query (the ordered arrays in the `this.__generatedMappings` and
  3946. * `this.__originalMappings` properties).
  3947. */
  3948. BasicSourceMapConsumer.prototype._parseMappings =
  3949. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  3950. var generatedLine = 1;
  3951. var previousGeneratedColumn = 0;
  3952. var previousOriginalLine = 0;
  3953. var previousOriginalColumn = 0;
  3954. var previousSource = 0;
  3955. var previousName = 0;
  3956. var length = aStr.length;
  3957. var index = 0;
  3958. var cachedSegments = {};
  3959. var temp = {};
  3960. var originalMappings = [];
  3961. var generatedMappings = [];
  3962. var mapping, str, segment, end, value;
  3963. while (index < length) {
  3964. if (aStr.charAt(index) === ';') {
  3965. generatedLine++;
  3966. index++;
  3967. previousGeneratedColumn = 0;
  3968. }
  3969. else if (aStr.charAt(index) === ',') {
  3970. index++;
  3971. }
  3972. else {
  3973. mapping = new Mapping();
  3974. mapping.generatedLine = generatedLine;
  3975. // Because each offset is encoded relative to the previous one,
  3976. // many segments often have the same encoding. We can exploit this
  3977. // fact by caching the parsed variable length fields of each segment,
  3978. // allowing us to avoid a second parse if we encounter the same
  3979. // segment again.
  3980. for (end = index; end < length; end++) {
  3981. if (this._charIsMappingSeparator(aStr, end)) {
  3982. break;
  3983. }
  3984. }
  3985. str = aStr.slice(index, end);
  3986. segment = cachedSegments[str];
  3987. if (segment) {
  3988. index += str.length;
  3989. } else {
  3990. segment = [];
  3991. while (index < end) {
  3992. base64Vlq.decode(aStr, index, temp);
  3993. value = temp.value;
  3994. index = temp.rest;
  3995. segment.push(value);
  3996. }
  3997. if (segment.length === 2) {
  3998. throw new Error('Found a source, but no line and column');
  3999. }
  4000. if (segment.length === 3) {
  4001. throw new Error('Found a source and line, but no column');
  4002. }
  4003. cachedSegments[str] = segment;
  4004. }
  4005. // Generated column.
  4006. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  4007. previousGeneratedColumn = mapping.generatedColumn;
  4008. if (segment.length > 1) {
  4009. // Original source.
  4010. mapping.source = previousSource + segment[1];
  4011. previousSource += segment[1];
  4012. // Original line.
  4013. mapping.originalLine = previousOriginalLine + segment[2];
  4014. previousOriginalLine = mapping.originalLine;
  4015. // Lines are stored 0-based
  4016. mapping.originalLine += 1;
  4017. // Original column.
  4018. mapping.originalColumn = previousOriginalColumn + segment[3];
  4019. previousOriginalColumn = mapping.originalColumn;
  4020. if (segment.length > 4) {
  4021. // Original name.
  4022. mapping.name = previousName + segment[4];
  4023. previousName += segment[4];
  4024. }
  4025. }
  4026. generatedMappings.push(mapping);
  4027. if (typeof mapping.originalLine === 'number') {
  4028. originalMappings.push(mapping);
  4029. }
  4030. }
  4031. }
  4032. quickSort$1(generatedMappings, util.compareByGeneratedPositionsDeflated);
  4033. this.__generatedMappings = generatedMappings;
  4034. quickSort$1(originalMappings, util.compareByOriginalPositions);
  4035. this.__originalMappings = originalMappings;
  4036. };
  4037. /**
  4038. * Find the mapping that best matches the hypothetical "needle" mapping that
  4039. * we are searching for in the given "haystack" of mappings.
  4040. */
  4041. BasicSourceMapConsumer.prototype._findMapping =
  4042. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  4043. aColumnName, aComparator, aBias) {
  4044. // To return the position we are searching for, we must first find the
  4045. // mapping for the given position and then return the opposite position it
  4046. // points to. Because the mappings are sorted, we can use binary search to
  4047. // find the best mapping.
  4048. if (aNeedle[aLineName] <= 0) {
  4049. throw new TypeError('Line must be greater than or equal to 1, got '
  4050. + aNeedle[aLineName]);
  4051. }
  4052. if (aNeedle[aColumnName] < 0) {
  4053. throw new TypeError('Column must be greater than or equal to 0, got '
  4054. + aNeedle[aColumnName]);
  4055. }
  4056. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  4057. };
  4058. /**
  4059. * Compute the last column for each generated mapping. The last column is
  4060. * inclusive.
  4061. */
  4062. BasicSourceMapConsumer.prototype.computeColumnSpans =
  4063. function SourceMapConsumer_computeColumnSpans() {
  4064. for (var index = 0; index < this._generatedMappings.length; ++index) {
  4065. var mapping = this._generatedMappings[index];
  4066. // Mappings do not contain a field for the last generated columnt. We
  4067. // can come up with an optimistic estimate, however, by assuming that
  4068. // mappings are contiguous (i.e. given two consecutive mappings, the
  4069. // first mapping ends where the second one starts).
  4070. if (index + 1 < this._generatedMappings.length) {
  4071. var nextMapping = this._generatedMappings[index + 1];
  4072. if (mapping.generatedLine === nextMapping.generatedLine) {
  4073. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  4074. continue;
  4075. }
  4076. }
  4077. // The last mapping for each line spans the entire line.
  4078. mapping.lastGeneratedColumn = Infinity;
  4079. }
  4080. };
  4081. /**
  4082. * Returns the original source, line, and column information for the generated
  4083. * source's line and column positions provided. The only argument is an object
  4084. * with the following properties:
  4085. *
  4086. * - line: The line number in the generated source. The line number
  4087. * is 1-based.
  4088. * - column: The column number in the generated source. The column
  4089. * number is 0-based.
  4090. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  4091. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  4092. * closest element that is smaller than or greater than the one we are
  4093. * searching for, respectively, if the exact element cannot be found.
  4094. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  4095. *
  4096. * and an object is returned with the following properties:
  4097. *
  4098. * - source: The original source file, or null.
  4099. * - line: The line number in the original source, or null. The
  4100. * line number is 1-based.
  4101. * - column: The column number in the original source, or null. The
  4102. * column number is 0-based.
  4103. * - name: The original identifier, or null.
  4104. */
  4105. BasicSourceMapConsumer.prototype.originalPositionFor =
  4106. function SourceMapConsumer_originalPositionFor(aArgs) {
  4107. var needle = {
  4108. generatedLine: util.getArg(aArgs, 'line'),
  4109. generatedColumn: util.getArg(aArgs, 'column')
  4110. };
  4111. var index = this._findMapping(
  4112. needle,
  4113. this._generatedMappings,
  4114. "generatedLine",
  4115. "generatedColumn",
  4116. util.compareByGeneratedPositionsDeflated,
  4117. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  4118. );
  4119. if (index >= 0) {
  4120. var mapping = this._generatedMappings[index];
  4121. if (mapping.generatedLine === needle.generatedLine) {
  4122. var source = util.getArg(mapping, 'source', null);
  4123. if (source !== null) {
  4124. source = this._sources.at(source);
  4125. source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
  4126. }
  4127. var name = util.getArg(mapping, 'name', null);
  4128. if (name !== null) {
  4129. name = this._names.at(name);
  4130. }
  4131. return {
  4132. source: source,
  4133. line: util.getArg(mapping, 'originalLine', null),
  4134. column: util.getArg(mapping, 'originalColumn', null),
  4135. name: name
  4136. };
  4137. }
  4138. }
  4139. return {
  4140. source: null,
  4141. line: null,
  4142. column: null,
  4143. name: null
  4144. };
  4145. };
  4146. /**
  4147. * Return true if we have the source content for every source in the source
  4148. * map, false otherwise.
  4149. */
  4150. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  4151. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  4152. if (!this.sourcesContent) {
  4153. return false;
  4154. }
  4155. return this.sourcesContent.length >= this._sources.size() &&
  4156. !this.sourcesContent.some(function (sc) { return sc == null; });
  4157. };
  4158. /**
  4159. * Returns the original source content. The only argument is the url of the
  4160. * original source file. Returns null if no original source content is
  4161. * available.
  4162. */
  4163. BasicSourceMapConsumer.prototype.sourceContentFor =
  4164. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  4165. if (!this.sourcesContent) {
  4166. return null;
  4167. }
  4168. var index = this._findSourceIndex(aSource);
  4169. if (index >= 0) {
  4170. return this.sourcesContent[index];
  4171. }
  4172. var relativeSource = aSource;
  4173. if (this.sourceRoot != null) {
  4174. relativeSource = util.relative(this.sourceRoot, relativeSource);
  4175. }
  4176. var url;
  4177. if (this.sourceRoot != null
  4178. && (url = util.urlParse(this.sourceRoot))) {
  4179. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  4180. // many users. We can help them out when they expect file:// URIs to
  4181. // behave like it would if they were running a local HTTP server. See
  4182. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  4183. var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
  4184. if (url.scheme == "file"
  4185. && this._sources.has(fileUriAbsPath)) {
  4186. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  4187. }
  4188. if ((!url.path || url.path == "/")
  4189. && this._sources.has("/" + relativeSource)) {
  4190. return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
  4191. }
  4192. }
  4193. // This function is used recursively from
  4194. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  4195. // don't want to throw if we can't find the source - we just want to
  4196. // return null, so we provide a flag to exit gracefully.
  4197. if (nullOnMissing) {
  4198. return null;
  4199. }
  4200. else {
  4201. throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  4202. }
  4203. };
  4204. /**
  4205. * Returns the generated line and column information for the original source,
  4206. * line, and column positions provided. The only argument is an object with
  4207. * the following properties:
  4208. *
  4209. * - source: The filename of the original source.
  4210. * - line: The line number in the original source. The line number
  4211. * is 1-based.
  4212. * - column: The column number in the original source. The column
  4213. * number is 0-based.
  4214. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  4215. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  4216. * closest element that is smaller than or greater than the one we are
  4217. * searching for, respectively, if the exact element cannot be found.
  4218. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  4219. *
  4220. * and an object is returned with the following properties:
  4221. *
  4222. * - line: The line number in the generated source, or null. The
  4223. * line number is 1-based.
  4224. * - column: The column number in the generated source, or null.
  4225. * The column number is 0-based.
  4226. */
  4227. BasicSourceMapConsumer.prototype.generatedPositionFor =
  4228. function SourceMapConsumer_generatedPositionFor(aArgs) {
  4229. var source = util.getArg(aArgs, 'source');
  4230. source = this._findSourceIndex(source);
  4231. if (source < 0) {
  4232. return {
  4233. line: null,
  4234. column: null,
  4235. lastColumn: null
  4236. };
  4237. }
  4238. var needle = {
  4239. source: source,
  4240. originalLine: util.getArg(aArgs, 'line'),
  4241. originalColumn: util.getArg(aArgs, 'column')
  4242. };
  4243. var index = this._findMapping(
  4244. needle,
  4245. this._originalMappings,
  4246. "originalLine",
  4247. "originalColumn",
  4248. util.compareByOriginalPositions,
  4249. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  4250. );
  4251. if (index >= 0) {
  4252. var mapping = this._originalMappings[index];
  4253. if (mapping.source === needle.source) {
  4254. return {
  4255. line: util.getArg(mapping, 'generatedLine', null),
  4256. column: util.getArg(mapping, 'generatedColumn', null),
  4257. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  4258. };
  4259. }
  4260. }
  4261. return {
  4262. line: null,
  4263. column: null,
  4264. lastColumn: null
  4265. };
  4266. };
  4267. var BasicSourceMapConsumer_1 = BasicSourceMapConsumer;
  4268. /**
  4269. * An IndexedSourceMapConsumer instance represents a parsed source map which
  4270. * we can query for information. It differs from BasicSourceMapConsumer in
  4271. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  4272. * input.
  4273. *
  4274. * The first parameter is a raw source map (either as a JSON string, or already
  4275. * parsed to an object). According to the spec for indexed source maps, they
  4276. * have the following attributes:
  4277. *
  4278. * - version: Which version of the source map spec this map is following.
  4279. * - file: Optional. The generated file this source map is associated with.
  4280. * - sections: A list of section definitions.
  4281. *
  4282. * Each value under the "sections" field has two fields:
  4283. * - offset: The offset into the original specified at which this section
  4284. * begins to apply, defined as an object with a "line" and "column"
  4285. * field.
  4286. * - map: A source map definition. This source map could also be indexed,
  4287. * but doesn't have to be.
  4288. *
  4289. * Instead of the "map" field, it's also possible to have a "url" field
  4290. * specifying a URL to retrieve a source map from, but that's currently
  4291. * unsupported.
  4292. *
  4293. * Here's an example source map, taken from the source map spec[0], but
  4294. * modified to omit a section which uses the "url" field.
  4295. *
  4296. * {
  4297. * version : 3,
  4298. * file: "app.js",
  4299. * sections: [{
  4300. * offset: {line:100, column:10},
  4301. * map: {
  4302. * version : 3,
  4303. * file: "section.js",
  4304. * sources: ["foo.js", "bar.js"],
  4305. * names: ["src", "maps", "are", "fun"],
  4306. * mappings: "AAAA,E;;ABCDE;"
  4307. * }
  4308. * }],
  4309. * }
  4310. *
  4311. * The second parameter, if given, is a string whose value is the URL
  4312. * at which the source map was found. This URL is used to compute the
  4313. * sources array.
  4314. *
  4315. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  4316. */
  4317. function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  4318. var sourceMap = aSourceMap;
  4319. if (typeof aSourceMap === 'string') {
  4320. sourceMap = util.parseSourceMapInput(aSourceMap);
  4321. }
  4322. var version = util.getArg(sourceMap, 'version');
  4323. var sections = util.getArg(sourceMap, 'sections');
  4324. if (version != this._version) {
  4325. throw new Error('Unsupported version: ' + version);
  4326. }
  4327. this._sources = new ArraySet$2();
  4328. this._names = new ArraySet$2();
  4329. var lastOffset = {
  4330. line: -1,
  4331. column: 0
  4332. };
  4333. this._sections = sections.map(function (s) {
  4334. if (s.url) {
  4335. // The url field will require support for asynchronicity.
  4336. // See https://github.com/mozilla/source-map/issues/16
  4337. throw new Error('Support for url field in sections not implemented.');
  4338. }
  4339. var offset = util.getArg(s, 'offset');
  4340. var offsetLine = util.getArg(offset, 'line');
  4341. var offsetColumn = util.getArg(offset, 'column');
  4342. if (offsetLine < lastOffset.line ||
  4343. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  4344. throw new Error('Section offsets must be ordered and non-overlapping.');
  4345. }
  4346. lastOffset = offset;
  4347. return {
  4348. generatedOffset: {
  4349. // The offset fields are 0-based, but we use 1-based indices when
  4350. // encoding/decoding from VLQ.
  4351. generatedLine: offsetLine + 1,
  4352. generatedColumn: offsetColumn + 1
  4353. },
  4354. consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
  4355. }
  4356. });
  4357. }
  4358. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  4359. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  4360. /**
  4361. * The version of the source mapping spec that we are consuming.
  4362. */
  4363. IndexedSourceMapConsumer.prototype._version = 3;
  4364. /**
  4365. * The list of original sources.
  4366. */
  4367. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  4368. get: function () {
  4369. var sources = [];
  4370. for (var i = 0; i < this._sections.length; i++) {
  4371. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  4372. sources.push(this._sections[i].consumer.sources[j]);
  4373. }
  4374. }
  4375. return sources;
  4376. }
  4377. });
  4378. /**
  4379. * Returns the original source, line, and column information for the generated
  4380. * source's line and column positions provided. The only argument is an object
  4381. * with the following properties:
  4382. *
  4383. * - line: The line number in the generated source. The line number
  4384. * is 1-based.
  4385. * - column: The column number in the generated source. The column
  4386. * number is 0-based.
  4387. *
  4388. * and an object is returned with the following properties:
  4389. *
  4390. * - source: The original source file, or null.
  4391. * - line: The line number in the original source, or null. The
  4392. * line number is 1-based.
  4393. * - column: The column number in the original source, or null. The
  4394. * column number is 0-based.
  4395. * - name: The original identifier, or null.
  4396. */
  4397. IndexedSourceMapConsumer.prototype.originalPositionFor =
  4398. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  4399. var needle = {
  4400. generatedLine: util.getArg(aArgs, 'line'),
  4401. generatedColumn: util.getArg(aArgs, 'column')
  4402. };
  4403. // Find the section containing the generated position we're trying to map
  4404. // to an original position.
  4405. var sectionIndex = binarySearch.search(needle, this._sections,
  4406. function(needle, section) {
  4407. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  4408. if (cmp) {
  4409. return cmp;
  4410. }
  4411. return (needle.generatedColumn -
  4412. section.generatedOffset.generatedColumn);
  4413. });
  4414. var section = this._sections[sectionIndex];
  4415. if (!section) {
  4416. return {
  4417. source: null,
  4418. line: null,
  4419. column: null,
  4420. name: null
  4421. };
  4422. }
  4423. return section.consumer.originalPositionFor({
  4424. line: needle.generatedLine -
  4425. (section.generatedOffset.generatedLine - 1),
  4426. column: needle.generatedColumn -
  4427. (section.generatedOffset.generatedLine === needle.generatedLine
  4428. ? section.generatedOffset.generatedColumn - 1
  4429. : 0),
  4430. bias: aArgs.bias
  4431. });
  4432. };
  4433. /**
  4434. * Return true if we have the source content for every source in the source
  4435. * map, false otherwise.
  4436. */
  4437. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  4438. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  4439. return this._sections.every(function (s) {
  4440. return s.consumer.hasContentsOfAllSources();
  4441. });
  4442. };
  4443. /**
  4444. * Returns the original source content. The only argument is the url of the
  4445. * original source file. Returns null if no original source content is
  4446. * available.
  4447. */
  4448. IndexedSourceMapConsumer.prototype.sourceContentFor =
  4449. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  4450. for (var i = 0; i < this._sections.length; i++) {
  4451. var section = this._sections[i];
  4452. var content = section.consumer.sourceContentFor(aSource, true);
  4453. if (content) {
  4454. return content;
  4455. }
  4456. }
  4457. if (nullOnMissing) {
  4458. return null;
  4459. }
  4460. else {
  4461. throw new Error('"' + aSource + '" is not in the SourceMap.');
  4462. }
  4463. };
  4464. /**
  4465. * Returns the generated line and column information for the original source,
  4466. * line, and column positions provided. The only argument is an object with
  4467. * the following properties:
  4468. *
  4469. * - source: The filename of the original source.
  4470. * - line: The line number in the original source. The line number
  4471. * is 1-based.
  4472. * - column: The column number in the original source. The column
  4473. * number is 0-based.
  4474. *
  4475. * and an object is returned with the following properties:
  4476. *
  4477. * - line: The line number in the generated source, or null. The
  4478. * line number is 1-based.
  4479. * - column: The column number in the generated source, or null.
  4480. * The column number is 0-based.
  4481. */
  4482. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  4483. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  4484. for (var i = 0; i < this._sections.length; i++) {
  4485. var section = this._sections[i];
  4486. // Only consider this section if the requested source is in the list of
  4487. // sources of the consumer.
  4488. if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) {
  4489. continue;
  4490. }
  4491. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  4492. if (generatedPosition) {
  4493. var ret = {
  4494. line: generatedPosition.line +
  4495. (section.generatedOffset.generatedLine - 1),
  4496. column: generatedPosition.column +
  4497. (section.generatedOffset.generatedLine === generatedPosition.line
  4498. ? section.generatedOffset.generatedColumn - 1
  4499. : 0)
  4500. };
  4501. return ret;
  4502. }
  4503. }
  4504. return {
  4505. line: null,
  4506. column: null
  4507. };
  4508. };
  4509. /**
  4510. * Parse the mappings in a string in to a data structure which we can easily
  4511. * query (the ordered arrays in the `this.__generatedMappings` and
  4512. * `this.__originalMappings` properties).
  4513. */
  4514. IndexedSourceMapConsumer.prototype._parseMappings =
  4515. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  4516. this.__generatedMappings = [];
  4517. this.__originalMappings = [];
  4518. for (var i = 0; i < this._sections.length; i++) {
  4519. var section = this._sections[i];
  4520. var sectionMappings = section.consumer._generatedMappings;
  4521. for (var j = 0; j < sectionMappings.length; j++) {
  4522. var mapping = sectionMappings[j];
  4523. var source = section.consumer._sources.at(mapping.source);
  4524. source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
  4525. this._sources.add(source);
  4526. source = this._sources.indexOf(source);
  4527. var name = null;
  4528. if (mapping.name) {
  4529. name = section.consumer._names.at(mapping.name);
  4530. this._names.add(name);
  4531. name = this._names.indexOf(name);
  4532. }
  4533. // The mappings coming from the consumer for the section have
  4534. // generated positions relative to the start of the section, so we
  4535. // need to offset them to be relative to the start of the concatenated
  4536. // generated file.
  4537. var adjustedMapping = {
  4538. source: source,
  4539. generatedLine: mapping.generatedLine +
  4540. (section.generatedOffset.generatedLine - 1),
  4541. generatedColumn: mapping.generatedColumn +
  4542. (section.generatedOffset.generatedLine === mapping.generatedLine
  4543. ? section.generatedOffset.generatedColumn - 1
  4544. : 0),
  4545. originalLine: mapping.originalLine,
  4546. originalColumn: mapping.originalColumn,
  4547. name: name
  4548. };
  4549. this.__generatedMappings.push(adjustedMapping);
  4550. if (typeof adjustedMapping.originalLine === 'number') {
  4551. this.__originalMappings.push(adjustedMapping);
  4552. }
  4553. }
  4554. }
  4555. quickSort$1(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  4556. quickSort$1(this.__originalMappings, util.compareByOriginalPositions);
  4557. };
  4558. var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer;
  4559. var sourceMapConsumer = {
  4560. SourceMapConsumer: SourceMapConsumer_1,
  4561. BasicSourceMapConsumer: BasicSourceMapConsumer_1,
  4562. IndexedSourceMapConsumer: IndexedSourceMapConsumer_1
  4563. };
  4564. /* -*- Mode: js; js-indent-level: 2; -*- */
  4565. /*
  4566. * Copyright 2011 Mozilla Foundation and contributors
  4567. * Licensed under the New BSD license. See LICENSE or:
  4568. * http://opensource.org/licenses/BSD-3-Clause
  4569. */
  4570. var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
  4571. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  4572. // operating systems these days (capturing the result).
  4573. var REGEX_NEWLINE = /(\r?\n)/;
  4574. // Newline character code for charCodeAt() comparisons
  4575. var NEWLINE_CODE = 10;
  4576. // Private symbol for identifying `SourceNode`s when multiple versions of
  4577. // the source-map library are loaded. This MUST NOT CHANGE across
  4578. // versions!
  4579. var isSourceNode = "$$$isSourceNode$$$";
  4580. /**
  4581. * SourceNodes provide a way to abstract over interpolating/concatenating
  4582. * snippets of generated JavaScript source code while maintaining the line and
  4583. * column information associated with the original source code.
  4584. *
  4585. * @param aLine The original line number.
  4586. * @param aColumn The original column number.
  4587. * @param aSource The original source's filename.
  4588. * @param aChunks Optional. An array of strings which are snippets of
  4589. * generated JS, or other SourceNodes.
  4590. * @param aName The original identifier.
  4591. */
  4592. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  4593. this.children = [];
  4594. this.sourceContents = {};
  4595. this.line = aLine == null ? null : aLine;
  4596. this.column = aColumn == null ? null : aColumn;
  4597. this.source = aSource == null ? null : aSource;
  4598. this.name = aName == null ? null : aName;
  4599. this[isSourceNode] = true;
  4600. if (aChunks != null) this.add(aChunks);
  4601. }
  4602. /**
  4603. * Creates a SourceNode from generated code and a SourceMapConsumer.
  4604. *
  4605. * @param aGeneratedCode The generated code
  4606. * @param aSourceMapConsumer The SourceMap for the generated code
  4607. * @param aRelativePath Optional. The path that relative sources in the
  4608. * SourceMapConsumer should be relative to.
  4609. */
  4610. SourceNode.fromStringWithSourceMap =
  4611. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  4612. // The SourceNode we want to fill with the generated code
  4613. // and the SourceMap
  4614. var node = new SourceNode();
  4615. // All even indices of this array are one line of the generated code,
  4616. // while all odd indices are the newlines between two adjacent lines
  4617. // (since `REGEX_NEWLINE` captures its match).
  4618. // Processed fragments are accessed by calling `shiftNextLine`.
  4619. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  4620. var remainingLinesIndex = 0;
  4621. var shiftNextLine = function() {
  4622. var lineContents = getNextLine();
  4623. // The last line of a file might not have a newline.
  4624. var newLine = getNextLine() || "";
  4625. return lineContents + newLine;
  4626. function getNextLine() {
  4627. return remainingLinesIndex < remainingLines.length ?
  4628. remainingLines[remainingLinesIndex++] : undefined;
  4629. }
  4630. };
  4631. // We need to remember the position of "remainingLines"
  4632. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  4633. // The generate SourceNodes we need a code range.
  4634. // To extract it current and last mapping is used.
  4635. // Here we store the last mapping.
  4636. var lastMapping = null;
  4637. aSourceMapConsumer.eachMapping(function (mapping) {
  4638. if (lastMapping !== null) {
  4639. // We add the code from "lastMapping" to "mapping":
  4640. // First check if there is a new line in between.
  4641. if (lastGeneratedLine < mapping.generatedLine) {
  4642. // Associate first line with "lastMapping"
  4643. addMappingWithCode(lastMapping, shiftNextLine());
  4644. lastGeneratedLine++;
  4645. lastGeneratedColumn = 0;
  4646. // The remaining code is added without mapping
  4647. } else {
  4648. // There is no new line in between.
  4649. // Associate the code between "lastGeneratedColumn" and
  4650. // "mapping.generatedColumn" with "lastMapping"
  4651. var nextLine = remainingLines[remainingLinesIndex] || '';
  4652. var code = nextLine.substr(0, mapping.generatedColumn -
  4653. lastGeneratedColumn);
  4654. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
  4655. lastGeneratedColumn);
  4656. lastGeneratedColumn = mapping.generatedColumn;
  4657. addMappingWithCode(lastMapping, code);
  4658. // No more remaining code, continue
  4659. lastMapping = mapping;
  4660. return;
  4661. }
  4662. }
  4663. // We add the generated code until the first mapping
  4664. // to the SourceNode without any mapping.
  4665. // Each line is added as separate string.
  4666. while (lastGeneratedLine < mapping.generatedLine) {
  4667. node.add(shiftNextLine());
  4668. lastGeneratedLine++;
  4669. }
  4670. if (lastGeneratedColumn < mapping.generatedColumn) {
  4671. var nextLine = remainingLines[remainingLinesIndex] || '';
  4672. node.add(nextLine.substr(0, mapping.generatedColumn));
  4673. remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
  4674. lastGeneratedColumn = mapping.generatedColumn;
  4675. }
  4676. lastMapping = mapping;
  4677. }, this);
  4678. // We have processed all mappings.
  4679. if (remainingLinesIndex < remainingLines.length) {
  4680. if (lastMapping) {
  4681. // Associate the remaining code in the current line with "lastMapping"
  4682. addMappingWithCode(lastMapping, shiftNextLine());
  4683. }
  4684. // and add the remaining lines without any mapping
  4685. node.add(remainingLines.splice(remainingLinesIndex).join(""));
  4686. }
  4687. // Copy sourcesContent into SourceNode
  4688. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  4689. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  4690. if (content != null) {
  4691. if (aRelativePath != null) {
  4692. sourceFile = util.join(aRelativePath, sourceFile);
  4693. }
  4694. node.setSourceContent(sourceFile, content);
  4695. }
  4696. });
  4697. return node;
  4698. function addMappingWithCode(mapping, code) {
  4699. if (mapping === null || mapping.source === undefined) {
  4700. node.add(code);
  4701. } else {
  4702. var source = aRelativePath
  4703. ? util.join(aRelativePath, mapping.source)
  4704. : mapping.source;
  4705. node.add(new SourceNode(mapping.originalLine,
  4706. mapping.originalColumn,
  4707. source,
  4708. code,
  4709. mapping.name));
  4710. }
  4711. }
  4712. };
  4713. /**
  4714. * Add a chunk of generated JS to this source node.
  4715. *
  4716. * @param aChunk A string snippet of generated JS code, another instance of
  4717. * SourceNode, or an array where each member is one of those things.
  4718. */
  4719. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  4720. if (Array.isArray(aChunk)) {
  4721. aChunk.forEach(function (chunk) {
  4722. this.add(chunk);
  4723. }, this);
  4724. }
  4725. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  4726. if (aChunk) {
  4727. this.children.push(aChunk);
  4728. }
  4729. }
  4730. else {
  4731. throw new TypeError(
  4732. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  4733. );
  4734. }
  4735. return this;
  4736. };
  4737. /**
  4738. * Add a chunk of generated JS to the beginning of this source node.
  4739. *
  4740. * @param aChunk A string snippet of generated JS code, another instance of
  4741. * SourceNode, or an array where each member is one of those things.
  4742. */
  4743. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  4744. if (Array.isArray(aChunk)) {
  4745. for (var i = aChunk.length-1; i >= 0; i--) {
  4746. this.prepend(aChunk[i]);
  4747. }
  4748. }
  4749. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  4750. this.children.unshift(aChunk);
  4751. }
  4752. else {
  4753. throw new TypeError(
  4754. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  4755. );
  4756. }
  4757. return this;
  4758. };
  4759. /**
  4760. * Walk over the tree of JS snippets in this node and its children. The
  4761. * walking function is called once for each snippet of JS and is passed that
  4762. * snippet and the its original associated source's line/column location.
  4763. *
  4764. * @param aFn The traversal function.
  4765. */
  4766. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  4767. var chunk;
  4768. for (var i = 0, len = this.children.length; i < len; i++) {
  4769. chunk = this.children[i];
  4770. if (chunk[isSourceNode]) {
  4771. chunk.walk(aFn);
  4772. }
  4773. else {
  4774. if (chunk !== '') {
  4775. aFn(chunk, { source: this.source,
  4776. line: this.line,
  4777. column: this.column,
  4778. name: this.name });
  4779. }
  4780. }
  4781. }
  4782. };
  4783. /**
  4784. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  4785. * each of `this.children`.
  4786. *
  4787. * @param aSep The separator.
  4788. */
  4789. SourceNode.prototype.join = function SourceNode_join(aSep) {
  4790. var newChildren;
  4791. var i;
  4792. var len = this.children.length;
  4793. if (len > 0) {
  4794. newChildren = [];
  4795. for (i = 0; i < len-1; i++) {
  4796. newChildren.push(this.children[i]);
  4797. newChildren.push(aSep);
  4798. }
  4799. newChildren.push(this.children[i]);
  4800. this.children = newChildren;
  4801. }
  4802. return this;
  4803. };
  4804. /**
  4805. * Call String.prototype.replace on the very right-most source snippet. Useful
  4806. * for trimming whitespace from the end of a source node, etc.
  4807. *
  4808. * @param aPattern The pattern to replace.
  4809. * @param aReplacement The thing to replace the pattern with.
  4810. */
  4811. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  4812. var lastChild = this.children[this.children.length - 1];
  4813. if (lastChild[isSourceNode]) {
  4814. lastChild.replaceRight(aPattern, aReplacement);
  4815. }
  4816. else if (typeof lastChild === 'string') {
  4817. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  4818. }
  4819. else {
  4820. this.children.push(''.replace(aPattern, aReplacement));
  4821. }
  4822. return this;
  4823. };
  4824. /**
  4825. * Set the source content for a source file. This will be added to the SourceMapGenerator
  4826. * in the sourcesContent field.
  4827. *
  4828. * @param aSourceFile The filename of the source file
  4829. * @param aSourceContent The content of the source file
  4830. */
  4831. SourceNode.prototype.setSourceContent =
  4832. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  4833. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  4834. };
  4835. /**
  4836. * Walk over the tree of SourceNodes. The walking function is called for each
  4837. * source file content and is passed the filename and source content.
  4838. *
  4839. * @param aFn The traversal function.
  4840. */
  4841. SourceNode.prototype.walkSourceContents =
  4842. function SourceNode_walkSourceContents(aFn) {
  4843. for (var i = 0, len = this.children.length; i < len; i++) {
  4844. if (this.children[i][isSourceNode]) {
  4845. this.children[i].walkSourceContents(aFn);
  4846. }
  4847. }
  4848. var sources = Object.keys(this.sourceContents);
  4849. for (var i = 0, len = sources.length; i < len; i++) {
  4850. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  4851. }
  4852. };
  4853. /**
  4854. * Return the string representation of this source node. Walks over the tree
  4855. * and concatenates all the various snippets together to one string.
  4856. */
  4857. SourceNode.prototype.toString = function SourceNode_toString() {
  4858. var str = "";
  4859. this.walk(function (chunk) {
  4860. str += chunk;
  4861. });
  4862. return str;
  4863. };
  4864. /**
  4865. * Returns the string representation of this source node along with a source
  4866. * map.
  4867. */
  4868. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  4869. var generated = {
  4870. code: "",
  4871. line: 1,
  4872. column: 0
  4873. };
  4874. var map = new SourceMapGenerator$1(aArgs);
  4875. var sourceMappingActive = false;
  4876. var lastOriginalSource = null;
  4877. var lastOriginalLine = null;
  4878. var lastOriginalColumn = null;
  4879. var lastOriginalName = null;
  4880. this.walk(function (chunk, original) {
  4881. generated.code += chunk;
  4882. if (original.source !== null
  4883. && original.line !== null
  4884. && original.column !== null) {
  4885. if(lastOriginalSource !== original.source
  4886. || lastOriginalLine !== original.line
  4887. || lastOriginalColumn !== original.column
  4888. || lastOriginalName !== original.name) {
  4889. map.addMapping({
  4890. source: original.source,
  4891. original: {
  4892. line: original.line,
  4893. column: original.column
  4894. },
  4895. generated: {
  4896. line: generated.line,
  4897. column: generated.column
  4898. },
  4899. name: original.name
  4900. });
  4901. }
  4902. lastOriginalSource = original.source;
  4903. lastOriginalLine = original.line;
  4904. lastOriginalColumn = original.column;
  4905. lastOriginalName = original.name;
  4906. sourceMappingActive = true;
  4907. } else if (sourceMappingActive) {
  4908. map.addMapping({
  4909. generated: {
  4910. line: generated.line,
  4911. column: generated.column
  4912. }
  4913. });
  4914. lastOriginalSource = null;
  4915. sourceMappingActive = false;
  4916. }
  4917. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  4918. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  4919. generated.line++;
  4920. generated.column = 0;
  4921. // Mappings end at eol
  4922. if (idx + 1 === length) {
  4923. lastOriginalSource = null;
  4924. sourceMappingActive = false;
  4925. } else if (sourceMappingActive) {
  4926. map.addMapping({
  4927. source: original.source,
  4928. original: {
  4929. line: original.line,
  4930. column: original.column
  4931. },
  4932. generated: {
  4933. line: generated.line,
  4934. column: generated.column
  4935. },
  4936. name: original.name
  4937. });
  4938. }
  4939. } else {
  4940. generated.column++;
  4941. }
  4942. }
  4943. });
  4944. this.walkSourceContents(function (sourceFile, sourceContent) {
  4945. map.setSourceContent(sourceFile, sourceContent);
  4946. });
  4947. return { code: generated.code, map: map };
  4948. };
  4949. var SourceNode_1 = SourceNode;
  4950. var sourceNode = {
  4951. SourceNode: SourceNode_1
  4952. };
  4953. /*
  4954. * Copyright 2009-2011 Mozilla Foundation and contributors
  4955. * Licensed under the New BSD license. See LICENSE.txt or:
  4956. * http://opensource.org/licenses/BSD-3-Clause
  4957. */
  4958. var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator;
  4959. var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer;
  4960. var SourceNode$1 = sourceNode.SourceNode;
  4961. var sourceMap = {
  4962. SourceMapGenerator: SourceMapGenerator$2,
  4963. SourceMapConsumer: SourceMapConsumer$1,
  4964. SourceNode: SourceNode$1
  4965. };
  4966. const PURE_ANNOTATION = `/*#__PURE__*/`;
  4967. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
  4968. const context = {
  4969. mode,
  4970. prefixIdentifiers,
  4971. sourceMap,
  4972. filename,
  4973. scopeId,
  4974. optimizeImports,
  4975. runtimeGlobalName,
  4976. runtimeModuleName,
  4977. ssr,
  4978. source: ast.loc.source,
  4979. code: ``,
  4980. column: 1,
  4981. line: 1,
  4982. offset: 0,
  4983. indentLevel: 0,
  4984. pure: false,
  4985. map: undefined,
  4986. helper(key) {
  4987. return `_${helperNameMap[key]}`;
  4988. },
  4989. push(code, node) {
  4990. context.code += code;
  4991. if ( context.map) {
  4992. if (node) {
  4993. let name;
  4994. if (node.type === 4 /* SIMPLE_EXPRESSION */ && !node.isStatic) {
  4995. const content = node.content.replace(/^_ctx\./, '');
  4996. if (content !== node.content && isSimpleIdentifier(content)) {
  4997. name = content;
  4998. }
  4999. }
  5000. addMapping(node.loc.start, name);
  5001. }
  5002. advancePositionWithMutation(context, code);
  5003. if (node && node.loc !== locStub) {
  5004. addMapping(node.loc.end);
  5005. }
  5006. }
  5007. },
  5008. indent() {
  5009. newline(++context.indentLevel);
  5010. },
  5011. deindent(withoutNewLine = false) {
  5012. if (withoutNewLine) {
  5013. --context.indentLevel;
  5014. }
  5015. else {
  5016. newline(--context.indentLevel);
  5017. }
  5018. },
  5019. newline() {
  5020. newline(context.indentLevel);
  5021. }
  5022. };
  5023. function newline(n) {
  5024. context.push('\n' + ` `.repeat(n));
  5025. }
  5026. function addMapping(loc, name) {
  5027. context.map.addMapping({
  5028. name,
  5029. source: context.filename,
  5030. original: {
  5031. line: loc.line,
  5032. column: loc.column - 1 // source-map column is 0 based
  5033. },
  5034. generated: {
  5035. line: context.line,
  5036. column: context.column - 1
  5037. }
  5038. });
  5039. }
  5040. if ( sourceMap) {
  5041. // lazy require source-map implementation, only in non-browser builds
  5042. context.map = new SourceMapGenerator$2();
  5043. context.map.setSourceContent(filename, context.source);
  5044. }
  5045. return context;
  5046. }
  5047. function generate(ast, options = {}) {
  5048. const context = createCodegenContext(ast, options);
  5049. if (options.onContextCreated)
  5050. options.onContextCreated(context);
  5051. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  5052. const hasHelpers = ast.helpers.length > 0;
  5053. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  5054. const genScopeId = scopeId != null && mode === 'module';
  5055. const isSetupInlined = !!options.inline;
  5056. // preambles
  5057. // in setup() inline mode, the preamble is generated in a sub context
  5058. // and returned separately.
  5059. const preambleContext = isSetupInlined
  5060. ? createCodegenContext(ast, options)
  5061. : context;
  5062. if ( mode === 'module') {
  5063. genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  5064. }
  5065. else {
  5066. genFunctionPreamble(ast, preambleContext);
  5067. }
  5068. // enter render function
  5069. const functionName = ssr ? `ssrRender` : `render`;
  5070. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  5071. if ( options.bindingMetadata && !options.inline) {
  5072. // binding optimization args
  5073. args.push('$props', '$setup', '$data', '$options');
  5074. }
  5075. const signature = options.isTS
  5076. ? args.map(arg => `${arg}: any`).join(',')
  5077. : args.join(', ');
  5078. if (genScopeId) {
  5079. if (isSetupInlined) {
  5080. push(`${PURE_ANNOTATION}_withId(`);
  5081. }
  5082. else {
  5083. push(`const ${functionName} = ${PURE_ANNOTATION}_withId(`);
  5084. }
  5085. }
  5086. if (isSetupInlined || genScopeId) {
  5087. push(`(${signature}) => {`);
  5088. }
  5089. else {
  5090. push(`function ${functionName}(${signature}) {`);
  5091. }
  5092. indent();
  5093. if (useWithBlock) {
  5094. push(`with (_ctx) {`);
  5095. indent();
  5096. // function mode const declarations should be inside with block
  5097. // also they should be renamed to avoid collision with user properties
  5098. if (hasHelpers) {
  5099. push(`const { ${ast.helpers
  5100. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  5101. .join(', ')} } = _Vue`);
  5102. push(`\n`);
  5103. newline();
  5104. }
  5105. }
  5106. // generate asset resolution statements
  5107. if (ast.components.length) {
  5108. genAssets(ast.components, 'component', context);
  5109. if (ast.directives.length || ast.temps > 0) {
  5110. newline();
  5111. }
  5112. }
  5113. if (ast.directives.length) {
  5114. genAssets(ast.directives, 'directive', context);
  5115. if (ast.temps > 0) {
  5116. newline();
  5117. }
  5118. }
  5119. if (ast.temps > 0) {
  5120. push(`let `);
  5121. for (let i = 0; i < ast.temps; i++) {
  5122. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  5123. }
  5124. }
  5125. if (ast.components.length || ast.directives.length || ast.temps) {
  5126. push(`\n`);
  5127. newline();
  5128. }
  5129. // generate the VNode tree expression
  5130. if (!ssr) {
  5131. push(`return `);
  5132. }
  5133. if (ast.codegenNode) {
  5134. genNode(ast.codegenNode, context);
  5135. }
  5136. else {
  5137. push(`null`);
  5138. }
  5139. if (useWithBlock) {
  5140. deindent();
  5141. push(`}`);
  5142. }
  5143. deindent();
  5144. push(`}`);
  5145. if (genScopeId) {
  5146. push(`)`);
  5147. }
  5148. return {
  5149. ast,
  5150. code: context.code,
  5151. preamble: isSetupInlined ? preambleContext.code : ``,
  5152. // SourceMapGenerator does have toJSON() method but it's not in the types
  5153. map: context.map ? context.map.toJSON() : undefined
  5154. };
  5155. }
  5156. function genFunctionPreamble(ast, context) {
  5157. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
  5158. const VueBinding = ssr
  5159. ? `require(${JSON.stringify(runtimeModuleName)})`
  5160. : runtimeGlobalName;
  5161. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  5162. // Generate const declaration for helpers
  5163. // In prefix mode, we place the const declaration at top so it's done
  5164. // only once; But if we not prefixing, we place the declaration inside the
  5165. // with block so it doesn't incur the `in` check cost for every helper access.
  5166. if (ast.helpers.length > 0) {
  5167. if ( prefixIdentifiers) {
  5168. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n`);
  5169. }
  5170. else {
  5171. // "with" mode.
  5172. // save Vue in a separate variable to avoid collision
  5173. push(`const _Vue = ${VueBinding}\n`);
  5174. // in "with" mode, helpers are declared inside the with block to avoid
  5175. // has check cost, but hoists are lifted out of the function - we need
  5176. // to provide the helper here.
  5177. if (ast.hoists.length) {
  5178. const staticHelpers = [
  5179. CREATE_VNODE,
  5180. CREATE_COMMENT,
  5181. CREATE_TEXT,
  5182. CREATE_STATIC
  5183. ]
  5184. .filter(helper => ast.helpers.includes(helper))
  5185. .map(aliasHelper)
  5186. .join(', ');
  5187. push(`const { ${staticHelpers} } = _Vue\n`);
  5188. }
  5189. }
  5190. }
  5191. // generate variables for ssr helpers
  5192. if ( ast.ssrHelpers && ast.ssrHelpers.length) {
  5193. // ssr guarantees prefixIdentifier: true
  5194. push(`const { ${ast.ssrHelpers
  5195. .map(aliasHelper)
  5196. .join(', ')} } = require("@vue/server-renderer")\n`);
  5197. }
  5198. genHoists(ast.hoists, context);
  5199. newline();
  5200. push(`return `);
  5201. }
  5202. function genModulePreamble(ast, context, genScopeId, inline) {
  5203. const { push, helper, newline, scopeId, optimizeImports, runtimeModuleName } = context;
  5204. if (genScopeId) {
  5205. ast.helpers.push(WITH_SCOPE_ID);
  5206. if (ast.hoists.length) {
  5207. ast.helpers.push(PUSH_SCOPE_ID, POP_SCOPE_ID);
  5208. }
  5209. }
  5210. // generate import statements for helpers
  5211. if (ast.helpers.length) {
  5212. if (optimizeImports) {
  5213. // when bundled with webpack with code-split, calling an import binding
  5214. // as a function leads to it being wrapped with `Object(a.b)` or `(0,a.b)`,
  5215. // incurring both payload size increase and potential perf overhead.
  5216. // therefore we assign the imports to variables (which is a constant ~50b
  5217. // cost per-component instead of scaling with template size)
  5218. push(`import { ${ast.helpers
  5219. .map(s => helperNameMap[s])
  5220. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  5221. push(`\n// Binding optimization for webpack code-split\nconst ${ast.helpers
  5222. .map(s => `_${helperNameMap[s]} = ${helperNameMap[s]}`)
  5223. .join(', ')}\n`);
  5224. }
  5225. else {
  5226. push(`import { ${ast.helpers
  5227. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  5228. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  5229. }
  5230. }
  5231. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  5232. push(`import { ${ast.ssrHelpers
  5233. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  5234. .join(', ')} } from "@vue/server-renderer"\n`);
  5235. }
  5236. if (ast.imports.length) {
  5237. genImports(ast.imports, context);
  5238. newline();
  5239. }
  5240. if (genScopeId) {
  5241. push(`const _withId = ${PURE_ANNOTATION}${helper(WITH_SCOPE_ID)}("${scopeId}")`);
  5242. newline();
  5243. }
  5244. genHoists(ast.hoists, context);
  5245. newline();
  5246. if (!inline) {
  5247. push(`export `);
  5248. }
  5249. }
  5250. function genAssets(assets, type, { helper, push, newline }) {
  5251. const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
  5252. for (let i = 0; i < assets.length; i++) {
  5253. const id = assets[i];
  5254. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})`);
  5255. if (i < assets.length - 1) {
  5256. newline();
  5257. }
  5258. }
  5259. }
  5260. function genHoists(hoists, context) {
  5261. if (!hoists.length) {
  5262. return;
  5263. }
  5264. context.pure = true;
  5265. const { push, newline, helper, scopeId, mode } = context;
  5266. const genScopeId = scopeId != null && mode !== 'function';
  5267. newline();
  5268. // push scope Id before initializing hoisted vnodes so that these vnodes
  5269. // get the proper scopeId as well.
  5270. if (genScopeId) {
  5271. push(`${helper(PUSH_SCOPE_ID)}("${scopeId}")`);
  5272. newline();
  5273. }
  5274. hoists.forEach((exp, i) => {
  5275. if (exp) {
  5276. push(`const _hoisted_${i + 1} = `);
  5277. genNode(exp, context);
  5278. newline();
  5279. }
  5280. });
  5281. if (genScopeId) {
  5282. push(`${helper(POP_SCOPE_ID)}()`);
  5283. newline();
  5284. }
  5285. context.pure = false;
  5286. }
  5287. function genImports(importsOptions, context) {
  5288. if (!importsOptions.length) {
  5289. return;
  5290. }
  5291. importsOptions.forEach(imports => {
  5292. context.push(`import `);
  5293. genNode(imports.exp, context);
  5294. context.push(` from '${imports.path}'`);
  5295. context.newline();
  5296. });
  5297. }
  5298. function isText$1(n) {
  5299. return (isString(n) ||
  5300. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  5301. n.type === 2 /* TEXT */ ||
  5302. n.type === 5 /* INTERPOLATION */ ||
  5303. n.type === 8 /* COMPOUND_EXPRESSION */);
  5304. }
  5305. function genNodeListAsArray(nodes, context) {
  5306. const multilines = nodes.length > 3 ||
  5307. ( nodes.some(n => isArray(n) || !isText$1(n)));
  5308. context.push(`[`);
  5309. multilines && context.indent();
  5310. genNodeList(nodes, context, multilines);
  5311. multilines && context.deindent();
  5312. context.push(`]`);
  5313. }
  5314. function genNodeList(nodes, context, multilines = false, comma = true) {
  5315. const { push, newline } = context;
  5316. for (let i = 0; i < nodes.length; i++) {
  5317. const node = nodes[i];
  5318. if (isString(node)) {
  5319. push(node);
  5320. }
  5321. else if (isArray(node)) {
  5322. genNodeListAsArray(node, context);
  5323. }
  5324. else {
  5325. genNode(node, context);
  5326. }
  5327. if (i < nodes.length - 1) {
  5328. if (multilines) {
  5329. comma && push(',');
  5330. newline();
  5331. }
  5332. else {
  5333. comma && push(', ');
  5334. }
  5335. }
  5336. }
  5337. }
  5338. function genNode(node, context) {
  5339. if (isString(node)) {
  5340. context.push(node);
  5341. return;
  5342. }
  5343. if (isSymbol(node)) {
  5344. context.push(context.helper(node));
  5345. return;
  5346. }
  5347. switch (node.type) {
  5348. case 1 /* ELEMENT */:
  5349. case 9 /* IF */:
  5350. case 11 /* FOR */:
  5351. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  5352. `Apply appropriate transforms first.`);
  5353. genNode(node.codegenNode, context);
  5354. break;
  5355. case 2 /* TEXT */:
  5356. genText(node, context);
  5357. break;
  5358. case 4 /* SIMPLE_EXPRESSION */:
  5359. genExpression(node, context);
  5360. break;
  5361. case 5 /* INTERPOLATION */:
  5362. genInterpolation(node, context);
  5363. break;
  5364. case 12 /* TEXT_CALL */:
  5365. genNode(node.codegenNode, context);
  5366. break;
  5367. case 8 /* COMPOUND_EXPRESSION */:
  5368. genCompoundExpression(node, context);
  5369. break;
  5370. case 3 /* COMMENT */:
  5371. genComment(node, context);
  5372. break;
  5373. case 13 /* VNODE_CALL */:
  5374. genVNodeCall(node, context);
  5375. break;
  5376. case 14 /* JS_CALL_EXPRESSION */:
  5377. genCallExpression(node, context);
  5378. break;
  5379. case 15 /* JS_OBJECT_EXPRESSION */:
  5380. genObjectExpression(node, context);
  5381. break;
  5382. case 17 /* JS_ARRAY_EXPRESSION */:
  5383. genArrayExpression(node, context);
  5384. break;
  5385. case 18 /* JS_FUNCTION_EXPRESSION */:
  5386. genFunctionExpression(node, context);
  5387. break;
  5388. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  5389. genConditionalExpression(node, context);
  5390. break;
  5391. case 20 /* JS_CACHE_EXPRESSION */:
  5392. genCacheExpression(node, context);
  5393. break;
  5394. // SSR only types
  5395. case 21 /* JS_BLOCK_STATEMENT */:
  5396. genNodeList(node.body, context, true, false);
  5397. break;
  5398. case 22 /* JS_TEMPLATE_LITERAL */:
  5399. genTemplateLiteral(node, context);
  5400. break;
  5401. case 23 /* JS_IF_STATEMENT */:
  5402. genIfStatement(node, context);
  5403. break;
  5404. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  5405. genAssignmentExpression(node, context);
  5406. break;
  5407. case 25 /* JS_SEQUENCE_EXPRESSION */:
  5408. genSequenceExpression(node, context);
  5409. break;
  5410. case 26 /* JS_RETURN_STATEMENT */:
  5411. genReturnStatement(node, context);
  5412. break;
  5413. /* istanbul ignore next */
  5414. case 10 /* IF_BRANCH */:
  5415. // noop
  5416. break;
  5417. default:
  5418. {
  5419. assert(false, `unhandled codegen node type: ${node.type}`);
  5420. // make sure we exhaust all possible types
  5421. const exhaustiveCheck = node;
  5422. return exhaustiveCheck;
  5423. }
  5424. }
  5425. }
  5426. function genText(node, context) {
  5427. context.push(JSON.stringify(node.content), node);
  5428. }
  5429. function genExpression(node, context) {
  5430. const { content, isStatic } = node;
  5431. context.push(isStatic ? JSON.stringify(content) : content, node);
  5432. }
  5433. function genInterpolation(node, context) {
  5434. const { push, helper, pure } = context;
  5435. if (pure)
  5436. push(PURE_ANNOTATION);
  5437. push(`${helper(TO_DISPLAY_STRING)}(`);
  5438. genNode(node.content, context);
  5439. push(`)`);
  5440. }
  5441. function genCompoundExpression(node, context) {
  5442. for (let i = 0; i < node.children.length; i++) {
  5443. const child = node.children[i];
  5444. if (isString(child)) {
  5445. context.push(child);
  5446. }
  5447. else {
  5448. genNode(child, context);
  5449. }
  5450. }
  5451. }
  5452. function genExpressionAsPropertyKey(node, context) {
  5453. const { push } = context;
  5454. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  5455. push(`[`);
  5456. genCompoundExpression(node, context);
  5457. push(`]`);
  5458. }
  5459. else if (node.isStatic) {
  5460. // only quote keys if necessary
  5461. const text = isSimpleIdentifier(node.content)
  5462. ? node.content
  5463. : JSON.stringify(node.content);
  5464. push(text, node);
  5465. }
  5466. else {
  5467. push(`[${node.content}]`, node);
  5468. }
  5469. }
  5470. function genComment(node, context) {
  5471. {
  5472. const { push, helper, pure } = context;
  5473. if (pure) {
  5474. push(PURE_ANNOTATION);
  5475. }
  5476. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  5477. }
  5478. }
  5479. function genVNodeCall(node, context) {
  5480. const { push, helper, pure } = context;
  5481. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
  5482. if (directives) {
  5483. push(helper(WITH_DIRECTIVES) + `(`);
  5484. }
  5485. if (isBlock) {
  5486. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  5487. }
  5488. if (pure) {
  5489. push(PURE_ANNOTATION);
  5490. }
  5491. push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
  5492. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  5493. push(`)`);
  5494. if (isBlock) {
  5495. push(`)`);
  5496. }
  5497. if (directives) {
  5498. push(`, `);
  5499. genNode(directives, context);
  5500. push(`)`);
  5501. }
  5502. }
  5503. function genNullableArgs(args) {
  5504. let i = args.length;
  5505. while (i--) {
  5506. if (args[i] != null)
  5507. break;
  5508. }
  5509. return args.slice(0, i + 1).map(arg => arg || `null`);
  5510. }
  5511. // JavaScript
  5512. function genCallExpression(node, context) {
  5513. const { push, helper, pure } = context;
  5514. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  5515. if (pure) {
  5516. push(PURE_ANNOTATION);
  5517. }
  5518. push(callee + `(`, node);
  5519. genNodeList(node.arguments, context);
  5520. push(`)`);
  5521. }
  5522. function genObjectExpression(node, context) {
  5523. const { push, indent, deindent, newline } = context;
  5524. const { properties } = node;
  5525. if (!properties.length) {
  5526. push(`{}`, node);
  5527. return;
  5528. }
  5529. const multilines = properties.length > 1 ||
  5530. (
  5531. properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  5532. push(multilines ? `{` : `{ `);
  5533. multilines && indent();
  5534. for (let i = 0; i < properties.length; i++) {
  5535. const { key, value } = properties[i];
  5536. // key
  5537. genExpressionAsPropertyKey(key, context);
  5538. push(`: `);
  5539. // value
  5540. genNode(value, context);
  5541. if (i < properties.length - 1) {
  5542. // will only reach this if it's multilines
  5543. push(`,`);
  5544. newline();
  5545. }
  5546. }
  5547. multilines && deindent();
  5548. push(multilines ? `}` : ` }`);
  5549. }
  5550. function genArrayExpression(node, context) {
  5551. genNodeListAsArray(node.elements, context);
  5552. }
  5553. function genFunctionExpression(node, context) {
  5554. const { push, indent, deindent, scopeId, mode } = context;
  5555. const { params, returns, body, newline, isSlot } = node;
  5556. // slot functions also need to push scopeId before rendering its content
  5557. const genScopeId = isSlot && scopeId != null && mode !== 'function';
  5558. if (genScopeId) {
  5559. push(`_withId(`);
  5560. }
  5561. else if (isSlot) {
  5562. push(`_${helperNameMap[WITH_CTX]}(`);
  5563. }
  5564. push(`(`, node);
  5565. if (isArray(params)) {
  5566. genNodeList(params, context);
  5567. }
  5568. else if (params) {
  5569. genNode(params, context);
  5570. }
  5571. push(`) => `);
  5572. if (newline || body) {
  5573. push(`{`);
  5574. indent();
  5575. }
  5576. if (returns) {
  5577. if (newline) {
  5578. push(`return `);
  5579. }
  5580. if (isArray(returns)) {
  5581. genNodeListAsArray(returns, context);
  5582. }
  5583. else {
  5584. genNode(returns, context);
  5585. }
  5586. }
  5587. else if (body) {
  5588. genNode(body, context);
  5589. }
  5590. if (newline || body) {
  5591. deindent();
  5592. push(`}`);
  5593. }
  5594. if (genScopeId || isSlot) {
  5595. push(`)`);
  5596. }
  5597. }
  5598. function genConditionalExpression(node, context) {
  5599. const { test, consequent, alternate, newline: needNewline } = node;
  5600. const { push, indent, deindent, newline } = context;
  5601. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  5602. const needsParens = !isSimpleIdentifier(test.content);
  5603. needsParens && push(`(`);
  5604. genExpression(test, context);
  5605. needsParens && push(`)`);
  5606. }
  5607. else {
  5608. push(`(`);
  5609. genNode(test, context);
  5610. push(`)`);
  5611. }
  5612. needNewline && indent();
  5613. context.indentLevel++;
  5614. needNewline || push(` `);
  5615. push(`? `);
  5616. genNode(consequent, context);
  5617. context.indentLevel--;
  5618. needNewline && newline();
  5619. needNewline || push(` `);
  5620. push(`: `);
  5621. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  5622. if (!isNested) {
  5623. context.indentLevel++;
  5624. }
  5625. genNode(alternate, context);
  5626. if (!isNested) {
  5627. context.indentLevel--;
  5628. }
  5629. needNewline && deindent(true /* without newline */);
  5630. }
  5631. function genCacheExpression(node, context) {
  5632. const { push, helper, indent, deindent, newline } = context;
  5633. push(`_cache[${node.index}] || (`);
  5634. if (node.isVNode) {
  5635. indent();
  5636. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  5637. newline();
  5638. }
  5639. push(`_cache[${node.index}] = `);
  5640. genNode(node.value, context);
  5641. if (node.isVNode) {
  5642. push(`,`);
  5643. newline();
  5644. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  5645. newline();
  5646. push(`_cache[${node.index}]`);
  5647. deindent();
  5648. }
  5649. push(`)`);
  5650. }
  5651. function genTemplateLiteral(node, context) {
  5652. const { push, indent, deindent } = context;
  5653. push('`');
  5654. const l = node.elements.length;
  5655. const multilines = l > 3;
  5656. for (let i = 0; i < l; i++) {
  5657. const e = node.elements[i];
  5658. if (isString(e)) {
  5659. push(e.replace(/(`|\$|\\)/g, '\\$1'));
  5660. }
  5661. else {
  5662. push('${');
  5663. if (multilines)
  5664. indent();
  5665. genNode(e, context);
  5666. if (multilines)
  5667. deindent();
  5668. push('}');
  5669. }
  5670. }
  5671. push('`');
  5672. }
  5673. function genIfStatement(node, context) {
  5674. const { push, indent, deindent } = context;
  5675. const { test, consequent, alternate } = node;
  5676. push(`if (`);
  5677. genNode(test, context);
  5678. push(`) {`);
  5679. indent();
  5680. genNode(consequent, context);
  5681. deindent();
  5682. push(`}`);
  5683. if (alternate) {
  5684. push(` else `);
  5685. if (alternate.type === 23 /* JS_IF_STATEMENT */) {
  5686. genIfStatement(alternate, context);
  5687. }
  5688. else {
  5689. push(`{`);
  5690. indent();
  5691. genNode(alternate, context);
  5692. deindent();
  5693. push(`}`);
  5694. }
  5695. }
  5696. }
  5697. function genAssignmentExpression(node, context) {
  5698. genNode(node.left, context);
  5699. context.push(` = `);
  5700. genNode(node.right, context);
  5701. }
  5702. function genSequenceExpression(node, context) {
  5703. context.push(`(`);
  5704. genNodeList(node.expressions, context);
  5705. context.push(`)`);
  5706. }
  5707. function genReturnStatement({ returns }, context) {
  5708. context.push(`return `);
  5709. if (isArray(returns)) {
  5710. genNodeListAsArray(returns, context);
  5711. }
  5712. else {
  5713. genNode(returns, context);
  5714. }
  5715. }
  5716. const beforeExpr = true;
  5717. const startsExpr = true;
  5718. const isLoop = true;
  5719. const isAssign = true;
  5720. const prefix = true;
  5721. const postfix = true;
  5722. class TokenType {
  5723. constructor(label, conf = {}) {
  5724. this.label = void 0;
  5725. this.keyword = void 0;
  5726. this.beforeExpr = void 0;
  5727. this.startsExpr = void 0;
  5728. this.rightAssociative = void 0;
  5729. this.isLoop = void 0;
  5730. this.isAssign = void 0;
  5731. this.prefix = void 0;
  5732. this.postfix = void 0;
  5733. this.binop = void 0;
  5734. this.updateContext = void 0;
  5735. this.label = label;
  5736. this.keyword = conf.keyword;
  5737. this.beforeExpr = !!conf.beforeExpr;
  5738. this.startsExpr = !!conf.startsExpr;
  5739. this.rightAssociative = !!conf.rightAssociative;
  5740. this.isLoop = !!conf.isLoop;
  5741. this.isAssign = !!conf.isAssign;
  5742. this.prefix = !!conf.prefix;
  5743. this.postfix = !!conf.postfix;
  5744. this.binop = conf.binop != null ? conf.binop : null;
  5745. this.updateContext = null;
  5746. }
  5747. }
  5748. const keywords = new Map();
  5749. function createKeyword(name, options = {}) {
  5750. options.keyword = name;
  5751. const token = new TokenType(name, options);
  5752. keywords.set(name, token);
  5753. return token;
  5754. }
  5755. function createBinop(name, binop) {
  5756. return new TokenType(name, {
  5757. beforeExpr,
  5758. binop
  5759. });
  5760. }
  5761. const types = {
  5762. num: new TokenType("num", {
  5763. startsExpr
  5764. }),
  5765. bigint: new TokenType("bigint", {
  5766. startsExpr
  5767. }),
  5768. decimal: new TokenType("decimal", {
  5769. startsExpr
  5770. }),
  5771. regexp: new TokenType("regexp", {
  5772. startsExpr
  5773. }),
  5774. string: new TokenType("string", {
  5775. startsExpr
  5776. }),
  5777. name: new TokenType("name", {
  5778. startsExpr
  5779. }),
  5780. eof: new TokenType("eof"),
  5781. bracketL: new TokenType("[", {
  5782. beforeExpr,
  5783. startsExpr
  5784. }),
  5785. bracketHashL: new TokenType("#[", {
  5786. beforeExpr,
  5787. startsExpr
  5788. }),
  5789. bracketBarL: new TokenType("[|", {
  5790. beforeExpr,
  5791. startsExpr
  5792. }),
  5793. bracketR: new TokenType("]"),
  5794. bracketBarR: new TokenType("|]"),
  5795. braceL: new TokenType("{", {
  5796. beforeExpr,
  5797. startsExpr
  5798. }),
  5799. braceBarL: new TokenType("{|", {
  5800. beforeExpr,
  5801. startsExpr
  5802. }),
  5803. braceHashL: new TokenType("#{", {
  5804. beforeExpr,
  5805. startsExpr
  5806. }),
  5807. braceR: new TokenType("}"),
  5808. braceBarR: new TokenType("|}"),
  5809. parenL: new TokenType("(", {
  5810. beforeExpr,
  5811. startsExpr
  5812. }),
  5813. parenR: new TokenType(")"),
  5814. comma: new TokenType(",", {
  5815. beforeExpr
  5816. }),
  5817. semi: new TokenType(";", {
  5818. beforeExpr
  5819. }),
  5820. colon: new TokenType(":", {
  5821. beforeExpr
  5822. }),
  5823. doubleColon: new TokenType("::", {
  5824. beforeExpr
  5825. }),
  5826. dot: new TokenType("."),
  5827. question: new TokenType("?", {
  5828. beforeExpr
  5829. }),
  5830. questionDot: new TokenType("?."),
  5831. arrow: new TokenType("=>", {
  5832. beforeExpr
  5833. }),
  5834. template: new TokenType("template"),
  5835. ellipsis: new TokenType("...", {
  5836. beforeExpr
  5837. }),
  5838. backQuote: new TokenType("`", {
  5839. startsExpr
  5840. }),
  5841. dollarBraceL: new TokenType("${", {
  5842. beforeExpr,
  5843. startsExpr
  5844. }),
  5845. at: new TokenType("@"),
  5846. hash: new TokenType("#", {
  5847. startsExpr
  5848. }),
  5849. interpreterDirective: new TokenType("#!..."),
  5850. eq: new TokenType("=", {
  5851. beforeExpr,
  5852. isAssign
  5853. }),
  5854. assign: new TokenType("_=", {
  5855. beforeExpr,
  5856. isAssign
  5857. }),
  5858. incDec: new TokenType("++/--", {
  5859. prefix,
  5860. postfix,
  5861. startsExpr
  5862. }),
  5863. bang: new TokenType("!", {
  5864. beforeExpr,
  5865. prefix,
  5866. startsExpr
  5867. }),
  5868. tilde: new TokenType("~", {
  5869. beforeExpr,
  5870. prefix,
  5871. startsExpr
  5872. }),
  5873. pipeline: createBinop("|>", 0),
  5874. nullishCoalescing: createBinop("??", 1),
  5875. logicalOR: createBinop("||", 1),
  5876. logicalAND: createBinop("&&", 2),
  5877. bitwiseOR: createBinop("|", 3),
  5878. bitwiseXOR: createBinop("^", 4),
  5879. bitwiseAND: createBinop("&", 5),
  5880. equality: createBinop("==/!=/===/!==", 6),
  5881. relational: createBinop("</>/<=/>=", 7),
  5882. bitShift: createBinop("<</>>/>>>", 8),
  5883. plusMin: new TokenType("+/-", {
  5884. beforeExpr,
  5885. binop: 9,
  5886. prefix,
  5887. startsExpr
  5888. }),
  5889. modulo: new TokenType("%", {
  5890. beforeExpr,
  5891. binop: 10,
  5892. startsExpr
  5893. }),
  5894. star: new TokenType("*", {
  5895. binop: 10
  5896. }),
  5897. slash: createBinop("/", 10),
  5898. exponent: new TokenType("**", {
  5899. beforeExpr,
  5900. binop: 11,
  5901. rightAssociative: true
  5902. }),
  5903. _break: createKeyword("break"),
  5904. _case: createKeyword("case", {
  5905. beforeExpr
  5906. }),
  5907. _catch: createKeyword("catch"),
  5908. _continue: createKeyword("continue"),
  5909. _debugger: createKeyword("debugger"),
  5910. _default: createKeyword("default", {
  5911. beforeExpr
  5912. }),
  5913. _do: createKeyword("do", {
  5914. isLoop,
  5915. beforeExpr
  5916. }),
  5917. _else: createKeyword("else", {
  5918. beforeExpr
  5919. }),
  5920. _finally: createKeyword("finally"),
  5921. _for: createKeyword("for", {
  5922. isLoop
  5923. }),
  5924. _function: createKeyword("function", {
  5925. startsExpr
  5926. }),
  5927. _if: createKeyword("if"),
  5928. _return: createKeyword("return", {
  5929. beforeExpr
  5930. }),
  5931. _switch: createKeyword("switch"),
  5932. _throw: createKeyword("throw", {
  5933. beforeExpr,
  5934. prefix,
  5935. startsExpr
  5936. }),
  5937. _try: createKeyword("try"),
  5938. _var: createKeyword("var"),
  5939. _const: createKeyword("const"),
  5940. _while: createKeyword("while", {
  5941. isLoop
  5942. }),
  5943. _with: createKeyword("with"),
  5944. _new: createKeyword("new", {
  5945. beforeExpr,
  5946. startsExpr
  5947. }),
  5948. _this: createKeyword("this", {
  5949. startsExpr
  5950. }),
  5951. _super: createKeyword("super", {
  5952. startsExpr
  5953. }),
  5954. _class: createKeyword("class", {
  5955. startsExpr
  5956. }),
  5957. _extends: createKeyword("extends", {
  5958. beforeExpr
  5959. }),
  5960. _export: createKeyword("export"),
  5961. _import: createKeyword("import", {
  5962. startsExpr
  5963. }),
  5964. _null: createKeyword("null", {
  5965. startsExpr
  5966. }),
  5967. _true: createKeyword("true", {
  5968. startsExpr
  5969. }),
  5970. _false: createKeyword("false", {
  5971. startsExpr
  5972. }),
  5973. _in: createKeyword("in", {
  5974. beforeExpr,
  5975. binop: 7
  5976. }),
  5977. _instanceof: createKeyword("instanceof", {
  5978. beforeExpr,
  5979. binop: 7
  5980. }),
  5981. _typeof: createKeyword("typeof", {
  5982. beforeExpr,
  5983. prefix,
  5984. startsExpr
  5985. }),
  5986. _void: createKeyword("void", {
  5987. beforeExpr,
  5988. prefix,
  5989. startsExpr
  5990. }),
  5991. _delete: createKeyword("delete", {
  5992. beforeExpr,
  5993. prefix,
  5994. startsExpr
  5995. })
  5996. };
  5997. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  5998. const lineBreakG = new RegExp(lineBreak.source, "g");
  5999. function isNewLine(code) {
  6000. switch (code) {
  6001. case 10:
  6002. case 13:
  6003. case 8232:
  6004. case 8233:
  6005. return true;
  6006. default:
  6007. return false;
  6008. }
  6009. }
  6010. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  6011. function isWhitespace(code) {
  6012. switch (code) {
  6013. case 0x0009:
  6014. case 0x000b:
  6015. case 0x000c:
  6016. case 32:
  6017. case 160:
  6018. case 5760:
  6019. case 0x2000:
  6020. case 0x2001:
  6021. case 0x2002:
  6022. case 0x2003:
  6023. case 0x2004:
  6024. case 0x2005:
  6025. case 0x2006:
  6026. case 0x2007:
  6027. case 0x2008:
  6028. case 0x2009:
  6029. case 0x200a:
  6030. case 0x202f:
  6031. case 0x205f:
  6032. case 0x3000:
  6033. case 0xfeff:
  6034. return true;
  6035. default:
  6036. return false;
  6037. }
  6038. }
  6039. class Position {
  6040. constructor(line, col) {
  6041. this.line = void 0;
  6042. this.column = void 0;
  6043. this.line = line;
  6044. this.column = col;
  6045. }
  6046. }
  6047. class SourceLocation {
  6048. constructor(start, end) {
  6049. this.start = void 0;
  6050. this.end = void 0;
  6051. this.filename = void 0;
  6052. this.identifierName = void 0;
  6053. this.start = start;
  6054. this.end = end;
  6055. }
  6056. }
  6057. function getLineInfo(input, offset) {
  6058. let line = 1;
  6059. let lineStart = 0;
  6060. let match;
  6061. lineBreakG.lastIndex = 0;
  6062. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  6063. line++;
  6064. lineStart = lineBreakG.lastIndex;
  6065. }
  6066. return new Position(line, offset - lineStart);
  6067. }
  6068. class BaseParser {
  6069. constructor() {
  6070. this.sawUnambiguousESM = false;
  6071. this.ambiguousScriptDifferentAst = false;
  6072. }
  6073. hasPlugin(name) {
  6074. return this.plugins.has(name);
  6075. }
  6076. getPluginOption(plugin, name) {
  6077. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  6078. }
  6079. }
  6080. function last$1(stack) {
  6081. return stack[stack.length - 1];
  6082. }
  6083. class CommentsParser extends BaseParser {
  6084. addComment(comment) {
  6085. if (this.filename) comment.loc.filename = this.filename;
  6086. this.state.trailingComments.push(comment);
  6087. this.state.leadingComments.push(comment);
  6088. }
  6089. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  6090. if (this.state.leadingComments.length === 0) {
  6091. return;
  6092. }
  6093. let lastElement = null;
  6094. let i = elements.length;
  6095. while (lastElement === null && i > 0) {
  6096. lastElement = elements[--i];
  6097. }
  6098. if (lastElement === null) {
  6099. return;
  6100. }
  6101. for (let j = 0; j < this.state.leadingComments.length; j++) {
  6102. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  6103. this.state.leadingComments.splice(j, 1);
  6104. j--;
  6105. }
  6106. }
  6107. const newTrailingComments = [];
  6108. for (let i = 0; i < this.state.leadingComments.length; i++) {
  6109. const leadingComment = this.state.leadingComments[i];
  6110. if (leadingComment.end < node.end) {
  6111. newTrailingComments.push(leadingComment);
  6112. if (!takeAllComments) {
  6113. this.state.leadingComments.splice(i, 1);
  6114. i--;
  6115. }
  6116. } else {
  6117. if (node.trailingComments === undefined) {
  6118. node.trailingComments = [];
  6119. }
  6120. node.trailingComments.push(leadingComment);
  6121. }
  6122. }
  6123. if (takeAllComments) this.state.leadingComments = [];
  6124. if (newTrailingComments.length > 0) {
  6125. lastElement.trailingComments = newTrailingComments;
  6126. } else if (lastElement.trailingComments !== undefined) {
  6127. lastElement.trailingComments = [];
  6128. }
  6129. }
  6130. processComment(node) {
  6131. if (node.type === "Program" && node.body.length > 0) return;
  6132. const stack = this.state.commentStack;
  6133. let firstChild, lastChild, trailingComments, i, j;
  6134. if (this.state.trailingComments.length > 0) {
  6135. if (this.state.trailingComments[0].start >= node.end) {
  6136. trailingComments = this.state.trailingComments;
  6137. this.state.trailingComments = [];
  6138. } else {
  6139. this.state.trailingComments.length = 0;
  6140. }
  6141. } else if (stack.length > 0) {
  6142. const lastInStack = last$1(stack);
  6143. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  6144. trailingComments = lastInStack.trailingComments;
  6145. delete lastInStack.trailingComments;
  6146. }
  6147. }
  6148. if (stack.length > 0 && last$1(stack).start >= node.start) {
  6149. firstChild = stack.pop();
  6150. }
  6151. while (stack.length > 0 && last$1(stack).start >= node.start) {
  6152. lastChild = stack.pop();
  6153. }
  6154. if (!lastChild && firstChild) lastChild = firstChild;
  6155. if (firstChild) {
  6156. switch (node.type) {
  6157. case "ObjectExpression":
  6158. this.adjustCommentsAfterTrailingComma(node, node.properties);
  6159. break;
  6160. case "ObjectPattern":
  6161. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  6162. break;
  6163. case "CallExpression":
  6164. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  6165. break;
  6166. case "ArrayExpression":
  6167. this.adjustCommentsAfterTrailingComma(node, node.elements);
  6168. break;
  6169. case "ArrayPattern":
  6170. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  6171. break;
  6172. }
  6173. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  6174. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
  6175. }
  6176. if (lastChild) {
  6177. if (lastChild.leadingComments) {
  6178. if (lastChild !== node && lastChild.leadingComments.length > 0 && last$1(lastChild.leadingComments).end <= node.start) {
  6179. node.leadingComments = lastChild.leadingComments;
  6180. delete lastChild.leadingComments;
  6181. } else {
  6182. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  6183. if (lastChild.leadingComments[i].end <= node.start) {
  6184. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  6185. break;
  6186. }
  6187. }
  6188. }
  6189. }
  6190. } else if (this.state.leadingComments.length > 0) {
  6191. if (last$1(this.state.leadingComments).end <= node.start) {
  6192. if (this.state.commentPreviousNode) {
  6193. for (j = 0; j < this.state.leadingComments.length; j++) {
  6194. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  6195. this.state.leadingComments.splice(j, 1);
  6196. j--;
  6197. }
  6198. }
  6199. }
  6200. if (this.state.leadingComments.length > 0) {
  6201. node.leadingComments = this.state.leadingComments;
  6202. this.state.leadingComments = [];
  6203. }
  6204. } else {
  6205. for (i = 0; i < this.state.leadingComments.length; i++) {
  6206. if (this.state.leadingComments[i].end > node.start) {
  6207. break;
  6208. }
  6209. }
  6210. const leadingComments = this.state.leadingComments.slice(0, i);
  6211. if (leadingComments.length) {
  6212. node.leadingComments = leadingComments;
  6213. }
  6214. trailingComments = this.state.leadingComments.slice(i);
  6215. if (trailingComments.length === 0) {
  6216. trailingComments = null;
  6217. }
  6218. }
  6219. }
  6220. this.state.commentPreviousNode = node;
  6221. if (trailingComments) {
  6222. if (trailingComments.length && trailingComments[0].start >= node.start && last$1(trailingComments).end <= node.end) {
  6223. node.innerComments = trailingComments;
  6224. } else {
  6225. const firstTrailingCommentIndex = trailingComments.findIndex(comment => comment.end >= node.end);
  6226. if (firstTrailingCommentIndex > 0) {
  6227. node.innerComments = trailingComments.slice(0, firstTrailingCommentIndex);
  6228. node.trailingComments = trailingComments.slice(firstTrailingCommentIndex);
  6229. } else {
  6230. node.trailingComments = trailingComments;
  6231. }
  6232. }
  6233. }
  6234. stack.push(node);
  6235. }
  6236. }
  6237. const ErrorMessages = Object.freeze({
  6238. AccessorIsGenerator: "A %0ter cannot be a generator",
  6239. ArgumentsInClass: "'arguments' is only allowed in functions and class methods",
  6240. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block",
  6241. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function",
  6242. AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
  6243. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules",
  6244. AwaitNotInAsyncFunction: "'await' is only allowed within async functions",
  6245. BadGetterArity: "getter must not have any formal parameters",
  6246. BadSetterArity: "setter must have exactly one formal parameter",
  6247. BadSetterRestParameter: "setter function argument must not be a rest parameter",
  6248. ConstructorClassField: "Classes may not have a field named 'constructor'",
  6249. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
  6250. ConstructorIsAccessor: "Class constructor may not be an accessor",
  6251. ConstructorIsAsync: "Constructor can't be an async function",
  6252. ConstructorIsGenerator: "Constructor can't be a generator",
  6253. DeclarationMissingInitializer: "%0 require an initialization value",
  6254. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
  6255. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  6256. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  6257. DecoratorSemicolon: "Decorators must not be followed by a semicolon",
  6258. DecoratorStaticBlock: "Decorators can't be used with a static block",
  6259. DeletePrivateField: "Deleting a private field is not allowed",
  6260. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  6261. DuplicateConstructor: "Duplicate constructor in the same class",
  6262. DuplicateDefaultExport: "Only one default export allowed per module.",
  6263. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  6264. DuplicateProto: "Redefinition of __proto__ property",
  6265. DuplicateRegExpFlags: "Duplicate regular expression flag",
  6266. DuplicateStaticBlock: "Duplicate static block in the same class",
  6267. ElementAfterRest: "Rest element must be last element",
  6268. EscapedCharNotAnIdentifier: "Invalid Unicode escape",
  6269. ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { %0 as '%1' } from 'some-module'`?",
  6270. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'",
  6271. ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
  6272. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block",
  6273. IllegalBreakContinue: "Unsyntactic %0",
  6274. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
  6275. IllegalReturn: "'return' outside of function",
  6276. ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
  6277. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments",
  6278. ImportCallArity: "import() requires exactly %0",
  6279. ImportCallNotNewExpression: "Cannot use new with import(...)",
  6280. ImportCallSpreadArgument: "... is not allowed in import()",
  6281. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  6282. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  6283. InvalidBigIntLiteral: "Invalid BigIntLiteral",
  6284. InvalidCodePoint: "Code point out of bounds",
  6285. InvalidDecimal: "Invalid decimal",
  6286. InvalidDigit: "Expected number in radix %0",
  6287. InvalidEscapeSequence: "Bad character escape sequence",
  6288. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template",
  6289. InvalidEscapedReservedWord: "Escape sequence in keyword %0",
  6290. InvalidIdentifier: "Invalid identifier %0",
  6291. InvalidLhs: "Invalid left-hand side in %0",
  6292. InvalidLhsBinding: "Binding invalid left-hand side in %0",
  6293. InvalidNumber: "Invalid number",
  6294. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'",
  6295. InvalidOrUnexpectedToken: "Unexpected character '%0'",
  6296. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern",
  6297. InvalidPrivateFieldResolution: "Private name #%0 is not defined",
  6298. InvalidPropertyBindingPattern: "Binding member expression",
  6299. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions",
  6300. InvalidRestAssignmentPattern: "Invalid rest operator's argument",
  6301. LabelRedeclaration: "Label '%0' is already declared",
  6302. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  6303. LineTerminatorBeforeArrow: "No line break is allowed before '=>'",
  6304. MalformedRegExpFlags: "Invalid regular expression flag",
  6305. MissingClassName: "A class name is required",
  6306. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  6307. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
  6308. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
  6309. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`",
  6310. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values",
  6311. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes',
  6312. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'",
  6313. ModuleExportUndefined: "Export '%0' is not defined",
  6314. MultipleDefaultsInSwitch: "Multiple default clauses",
  6315. NewlineAfterThrow: "Illegal newline after throw",
  6316. NoCatchOrFinally: "Missing catch or finally clause",
  6317. NumberIdentifier: "Identifier directly after number",
  6318. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
  6319. ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
  6320. OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
  6321. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
  6322. ParamDupe: "Argument name clash",
  6323. PatternHasAccessor: "Object pattern can't contain getter or setter",
  6324. PatternHasMethod: "Object pattern can't contain methods",
  6325. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
  6326. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
  6327. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
  6328. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
  6329. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
  6330. PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
  6331. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`)",
  6332. PrivateNameRedeclaration: "Duplicate private name #%0",
  6333. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  6334. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  6335. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  6336. RecordNoProto: "'__proto__' is not allowed in Record expressions",
  6337. RestTrailingComma: "Unexpected trailing comma after rest element",
  6338. 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",
  6339. StaticPrototype: "Classes may not have static property named prototype",
  6340. StrictDelete: "Deleting local variable in strict mode",
  6341. StrictEvalArguments: "Assigning to '%0' in strict mode",
  6342. StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
  6343. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
  6344. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'",
  6345. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
  6346. StrictWith: "'with' in strict mode",
  6347. 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?",
  6348. SuperPrivateField: "Private fields can't be accessed on super",
  6349. TrailingDecorator: "Decorators must be attached to a class element",
  6350. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  6351. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  6352. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  6353. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
  6354. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
  6355. UnexpectedDigitAfterHash: "Unexpected digit after hash token",
  6356. UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
  6357. UnexpectedKeyword: "Unexpected keyword '%0'",
  6358. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
  6359. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
  6360. UnexpectedNewTarget: "new.target can only be used in functions",
  6361. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
  6362. 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).",
  6363. UnexpectedReservedWord: "Unexpected reserved word '%0'",
  6364. UnexpectedSuper: "super is only allowed in object methods and classes",
  6365. UnexpectedToken: "Unexpected token '%0'",
  6366. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  6367. UnsupportedBind: "Binding should be performed on object property.",
  6368. UnsupportedDecoratorExport: "A decorated export must export a class declaration",
  6369. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  6370. UnsupportedImport: "import can only be used in import() or import.meta",
  6371. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
  6372. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
  6373. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
  6374. UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
  6375. UnterminatedComment: "Unterminated comment",
  6376. UnterminatedRegExp: "Unterminated regular expression",
  6377. UnterminatedString: "Unterminated string constant",
  6378. UnterminatedTemplate: "Unterminated template",
  6379. VarRedeclaration: "Identifier '%0' has already been declared",
  6380. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
  6381. YieldInParameter: "Yield expression is not allowed in formal parameters",
  6382. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
  6383. });
  6384. class ParserError extends CommentsParser {
  6385. getLocationForPosition(pos) {
  6386. let loc;
  6387. 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);
  6388. return loc;
  6389. }
  6390. raise(pos, errorTemplate, ...params) {
  6391. return this.raiseWithData(pos, undefined, errorTemplate, ...params);
  6392. }
  6393. raiseWithData(pos, data, errorTemplate, ...params) {
  6394. const loc = this.getLocationForPosition(pos);
  6395. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  6396. return this._raise(Object.assign({
  6397. loc,
  6398. pos
  6399. }, data), message);
  6400. }
  6401. _raise(errorContext, message) {
  6402. const err = new SyntaxError(message);
  6403. Object.assign(err, errorContext);
  6404. if (this.options.errorRecovery) {
  6405. if (!this.isLookahead) this.state.errors.push(err);
  6406. return err;
  6407. } else {
  6408. throw err;
  6409. }
  6410. }
  6411. }
  6412. function isSimpleProperty(node) {
  6413. return node != null && node.type === "Property" && node.kind === "init" && node.method === false;
  6414. }
  6415. var estree = (superClass => class extends superClass {
  6416. estreeParseRegExpLiteral({
  6417. pattern,
  6418. flags
  6419. }) {
  6420. let regex = null;
  6421. try {
  6422. regex = new RegExp(pattern, flags);
  6423. } catch (e) {}
  6424. const node = this.estreeParseLiteral(regex);
  6425. node.regex = {
  6426. pattern,
  6427. flags
  6428. };
  6429. return node;
  6430. }
  6431. estreeParseBigIntLiteral(value) {
  6432. const bigInt = typeof BigInt !== "undefined" ? BigInt(value) : null;
  6433. const node = this.estreeParseLiteral(bigInt);
  6434. node.bigint = String(node.value || value);
  6435. return node;
  6436. }
  6437. estreeParseDecimalLiteral(value) {
  6438. const decimal = null;
  6439. const node = this.estreeParseLiteral(decimal);
  6440. node.decimal = String(node.value || value);
  6441. return node;
  6442. }
  6443. estreeParseLiteral(value) {
  6444. return this.parseLiteral(value, "Literal");
  6445. }
  6446. directiveToStmt(directive) {
  6447. const directiveLiteral = directive.value;
  6448. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  6449. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  6450. expression.value = directiveLiteral.value;
  6451. expression.raw = directiveLiteral.extra.raw;
  6452. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  6453. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  6454. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  6455. }
  6456. initFunction(node, isAsync) {
  6457. super.initFunction(node, isAsync);
  6458. node.expression = false;
  6459. }
  6460. checkDeclaration(node) {
  6461. if (isSimpleProperty(node)) {
  6462. this.checkDeclaration(node.value);
  6463. } else {
  6464. super.checkDeclaration(node);
  6465. }
  6466. }
  6467. getObjectOrClassMethodParams(method) {
  6468. return method.value.params;
  6469. }
  6470. checkLVal(expr, contextDescription, ...args) {
  6471. switch (expr.type) {
  6472. case "ObjectPattern":
  6473. expr.properties.forEach(prop => {
  6474. this.checkLVal(prop.type === "Property" ? prop.value : prop, "object destructuring pattern", ...args);
  6475. });
  6476. break;
  6477. default:
  6478. super.checkLVal(expr, contextDescription, ...args);
  6479. }
  6480. }
  6481. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  6482. if (prop.method) {
  6483. return;
  6484. }
  6485. super.checkProto(prop, isRecord, protoRef, refExpressionErrors);
  6486. }
  6487. isValidDirective(stmt) {
  6488. var _stmt$expression$extr;
  6489. 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);
  6490. }
  6491. stmtToDirective(stmt) {
  6492. const directive = super.stmtToDirective(stmt);
  6493. const value = stmt.expression.value;
  6494. directive.value.value = value;
  6495. return directive;
  6496. }
  6497. parseBlockBody(node, allowDirectives, topLevel, end) {
  6498. super.parseBlockBody(node, allowDirectives, topLevel, end);
  6499. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  6500. node.body = directiveStatements.concat(node.body);
  6501. delete node.directives;
  6502. }
  6503. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  6504. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  6505. if (method.typeParameters) {
  6506. method.value.typeParameters = method.typeParameters;
  6507. delete method.typeParameters;
  6508. }
  6509. classBody.body.push(method);
  6510. }
  6511. parseExprAtom(refExpressionErrors) {
  6512. switch (this.state.type) {
  6513. case types.num:
  6514. case types.string:
  6515. return this.estreeParseLiteral(this.state.value);
  6516. case types.regexp:
  6517. return this.estreeParseRegExpLiteral(this.state.value);
  6518. case types.bigint:
  6519. return this.estreeParseBigIntLiteral(this.state.value);
  6520. case types.decimal:
  6521. return this.estreeParseDecimalLiteral(this.state.value);
  6522. case types._null:
  6523. return this.estreeParseLiteral(null);
  6524. case types._true:
  6525. return this.estreeParseLiteral(true);
  6526. case types._false:
  6527. return this.estreeParseLiteral(false);
  6528. default:
  6529. return super.parseExprAtom(refExpressionErrors);
  6530. }
  6531. }
  6532. parseLiteral(value, type, startPos, startLoc) {
  6533. const node = super.parseLiteral(value, type, startPos, startLoc);
  6534. node.raw = node.extra.raw;
  6535. delete node.extra;
  6536. return node;
  6537. }
  6538. parseFunctionBody(node, allowExpression, isMethod = false) {
  6539. super.parseFunctionBody(node, allowExpression, isMethod);
  6540. node.expression = node.body.type !== "BlockStatement";
  6541. }
  6542. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  6543. let funcNode = this.startNode();
  6544. funcNode.kind = node.kind;
  6545. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  6546. funcNode.type = "FunctionExpression";
  6547. delete funcNode.kind;
  6548. node.value = funcNode;
  6549. type = type === "ClassMethod" ? "MethodDefinition" : type;
  6550. return this.finishNode(node, type);
  6551. }
  6552. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  6553. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  6554. if (node) {
  6555. node.type = "Property";
  6556. if (node.kind === "method") node.kind = "init";
  6557. node.shorthand = false;
  6558. }
  6559. return node;
  6560. }
  6561. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  6562. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  6563. if (node) {
  6564. node.kind = "init";
  6565. node.type = "Property";
  6566. }
  6567. return node;
  6568. }
  6569. toAssignable(node, isLHS = false) {
  6570. if (isSimpleProperty(node)) {
  6571. this.toAssignable(node.value);
  6572. return node;
  6573. }
  6574. return super.toAssignable(node, isLHS);
  6575. }
  6576. toAssignableObjectExpressionProp(prop, ...args) {
  6577. if (prop.kind === "get" || prop.kind === "set") {
  6578. throw this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  6579. } else if (prop.method) {
  6580. throw this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  6581. } else {
  6582. super.toAssignableObjectExpressionProp(prop, ...args);
  6583. }
  6584. }
  6585. finishCallExpression(node, optional) {
  6586. super.finishCallExpression(node, optional);
  6587. if (node.callee.type === "Import") {
  6588. node.type = "ImportExpression";
  6589. node.source = node.arguments[0];
  6590. delete node.arguments;
  6591. delete node.callee;
  6592. }
  6593. return node;
  6594. }
  6595. toReferencedArguments(node) {
  6596. if (node.type === "ImportExpression") {
  6597. return;
  6598. }
  6599. super.toReferencedArguments(node);
  6600. }
  6601. parseExport(node) {
  6602. super.parseExport(node);
  6603. switch (node.type) {
  6604. case "ExportAllDeclaration":
  6605. node.exported = null;
  6606. break;
  6607. case "ExportNamedDeclaration":
  6608. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  6609. node.type = "ExportAllDeclaration";
  6610. node.exported = node.specifiers[0].exported;
  6611. delete node.specifiers;
  6612. }
  6613. break;
  6614. }
  6615. return node;
  6616. }
  6617. parseSubscript(base, startPos, startLoc, noCalls, state) {
  6618. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  6619. if (state.optionalChainMember) {
  6620. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  6621. node.type = node.type.substring(8);
  6622. }
  6623. if (state.stop) {
  6624. const chain = this.startNodeAtNode(node);
  6625. chain.expression = node;
  6626. return this.finishNode(chain, "ChainExpression");
  6627. }
  6628. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  6629. node.optional = false;
  6630. }
  6631. return node;
  6632. }
  6633. });
  6634. class TokContext {
  6635. constructor(token, isExpr, preserveSpace, override) {
  6636. this.token = void 0;
  6637. this.isExpr = void 0;
  6638. this.preserveSpace = void 0;
  6639. this.override = void 0;
  6640. this.token = token;
  6641. this.isExpr = !!isExpr;
  6642. this.preserveSpace = !!preserveSpace;
  6643. this.override = override;
  6644. }
  6645. }
  6646. const types$1 = {
  6647. braceStatement: new TokContext("{", false),
  6648. braceExpression: new TokContext("{", true),
  6649. recordExpression: new TokContext("#{", true),
  6650. templateQuasi: new TokContext("${", false),
  6651. parenStatement: new TokContext("(", false),
  6652. parenExpression: new TokContext("(", true),
  6653. template: new TokContext("`", true, true, p => p.readTmplToken()),
  6654. functionExpression: new TokContext("function", true),
  6655. functionStatement: new TokContext("function", false)
  6656. };
  6657. types.parenR.updateContext = types.braceR.updateContext = function () {
  6658. if (this.state.context.length === 1) {
  6659. this.state.exprAllowed = true;
  6660. return;
  6661. }
  6662. let out = this.state.context.pop();
  6663. if (out === types$1.braceStatement && this.curContext().token === "function") {
  6664. out = this.state.context.pop();
  6665. }
  6666. this.state.exprAllowed = !out.isExpr;
  6667. };
  6668. types.name.updateContext = function (prevType) {
  6669. let allowed = false;
  6670. if (prevType !== types.dot) {
  6671. if (this.state.value === "of" && !this.state.exprAllowed && prevType !== types._function && prevType !== types._class) {
  6672. allowed = true;
  6673. }
  6674. }
  6675. this.state.exprAllowed = allowed;
  6676. if (this.state.isIterator) {
  6677. this.state.isIterator = false;
  6678. }
  6679. };
  6680. types.braceL.updateContext = function (prevType) {
  6681. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  6682. this.state.exprAllowed = true;
  6683. };
  6684. types.dollarBraceL.updateContext = function () {
  6685. this.state.context.push(types$1.templateQuasi);
  6686. this.state.exprAllowed = true;
  6687. };
  6688. types.parenL.updateContext = function (prevType) {
  6689. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  6690. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  6691. this.state.exprAllowed = true;
  6692. };
  6693. types.incDec.updateContext = function () {};
  6694. types._function.updateContext = types._class.updateContext = function (prevType) {
  6695. 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)) {
  6696. this.state.context.push(types$1.functionExpression);
  6697. } else {
  6698. this.state.context.push(types$1.functionStatement);
  6699. }
  6700. this.state.exprAllowed = false;
  6701. };
  6702. types.backQuote.updateContext = function () {
  6703. if (this.curContext() === types$1.template) {
  6704. this.state.context.pop();
  6705. } else {
  6706. this.state.context.push(types$1.template);
  6707. }
  6708. this.state.exprAllowed = false;
  6709. };
  6710. types.braceHashL.updateContext = function () {
  6711. this.state.context.push(types$1.recordExpression);
  6712. this.state.exprAllowed = true;
  6713. };
  6714. 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";
  6715. 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";
  6716. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  6717. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  6718. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  6719. 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];
  6720. 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];
  6721. function isInAstralSet(code, set) {
  6722. let pos = 0x10000;
  6723. for (let i = 0, length = set.length; i < length; i += 2) {
  6724. pos += set[i];
  6725. if (pos > code) return false;
  6726. pos += set[i + 1];
  6727. if (pos >= code) return true;
  6728. }
  6729. return false;
  6730. }
  6731. function isIdentifierStart(code) {
  6732. if (code < 65) return code === 36;
  6733. if (code <= 90) return true;
  6734. if (code < 97) return code === 95;
  6735. if (code <= 122) return true;
  6736. if (code <= 0xffff) {
  6737. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  6738. }
  6739. return isInAstralSet(code, astralIdentifierStartCodes);
  6740. }
  6741. function isIdentifierChar(code) {
  6742. if (code < 48) return code === 36;
  6743. if (code < 58) return true;
  6744. if (code < 65) return false;
  6745. if (code <= 90) return true;
  6746. if (code < 97) return code === 95;
  6747. if (code <= 122) return true;
  6748. if (code <= 0xffff) {
  6749. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  6750. }
  6751. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  6752. }
  6753. const reservedWords = {
  6754. 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"],
  6755. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  6756. strictBind: ["eval", "arguments"]
  6757. };
  6758. const keywords$1 = new Set(reservedWords.keyword);
  6759. const reservedWordsStrictSet = new Set(reservedWords.strict);
  6760. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  6761. function isReservedWord(word, inModule) {
  6762. return inModule && word === "await" || word === "enum";
  6763. }
  6764. function isStrictReservedWord(word, inModule) {
  6765. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  6766. }
  6767. function isStrictBindOnlyReservedWord(word) {
  6768. return reservedWordsStrictBindSet.has(word);
  6769. }
  6770. function isStrictBindReservedWord(word, inModule) {
  6771. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  6772. }
  6773. function isKeyword(word) {
  6774. return keywords$1.has(word);
  6775. }
  6776. const keywordRelationalOperator = /^in(stanceof)?$/;
  6777. function isIteratorStart(current, next) {
  6778. return current === 64 && next === 64;
  6779. }
  6780. const SCOPE_OTHER = 0b00000000,
  6781. SCOPE_PROGRAM = 0b00000001,
  6782. SCOPE_FUNCTION = 0b00000010,
  6783. SCOPE_ARROW = 0b00000100,
  6784. SCOPE_SIMPLE_CATCH = 0b00001000,
  6785. SCOPE_SUPER = 0b00010000,
  6786. SCOPE_DIRECT_SUPER = 0b00100000,
  6787. SCOPE_CLASS = 0b01000000,
  6788. SCOPE_TS_MODULE = 0b10000000,
  6789. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  6790. const BIND_KIND_VALUE = 0b00000000001,
  6791. BIND_KIND_TYPE = 0b00000000010,
  6792. BIND_SCOPE_VAR = 0b00000000100,
  6793. BIND_SCOPE_LEXICAL = 0b00000001000,
  6794. BIND_SCOPE_FUNCTION = 0b00000010000,
  6795. BIND_FLAGS_NONE = 0b00001000000,
  6796. BIND_FLAGS_CLASS = 0b00010000000,
  6797. BIND_FLAGS_TS_ENUM = 0b00100000000,
  6798. BIND_FLAGS_TS_CONST_ENUM = 0b01000000000,
  6799. BIND_FLAGS_TS_EXPORT_ONLY = 0b10000000000;
  6800. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  6801. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  6802. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  6803. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  6804. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  6805. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  6806. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  6807. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  6808. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  6809. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  6810. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  6811. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY;
  6812. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  6813. CLASS_ELEMENT_KIND_GETTER = 0b010,
  6814. CLASS_ELEMENT_KIND_SETTER = 0b001,
  6815. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  6816. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  6817. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  6818. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  6819. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  6820. CLASS_ELEMENT_OTHER = 0;
  6821. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  6822. const FlowErrors = Object.freeze({
  6823. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  6824. 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",
  6825. AssignReservedType: "Cannot overwrite reserved type %0",
  6826. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  6827. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  6828. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  6829. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  6830. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  6831. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  6832. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  6833. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  6834. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  6835. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  6836. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  6837. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  6838. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  6839. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  6840. 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",
  6841. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  6842. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  6843. InexactVariance: "Explicit inexact syntax cannot have variance",
  6844. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  6845. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  6846. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  6847. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  6848. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  6849. SpreadVariance: "Spread properties cannot have variance",
  6850. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  6851. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  6852. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  6853. UnexpectedReservedType: "Unexpected reserved type %0",
  6854. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  6855. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  6856. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  6857. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  6858. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  6859. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
  6860. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  6861. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  6862. UnterminatedFlowComment: "Unterminated flow-comment"
  6863. });
  6864. function isEsModuleType(bodyElement) {
  6865. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  6866. }
  6867. function hasTypeImportKind(node) {
  6868. return node.importKind === "type" || node.importKind === "typeof";
  6869. }
  6870. function isMaybeDefaultImport(state) {
  6871. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  6872. }
  6873. const exportSuggestions = {
  6874. const: "declare export var",
  6875. let: "declare export var",
  6876. type: "export type",
  6877. interface: "export interface"
  6878. };
  6879. function partition(list, test) {
  6880. const list1 = [];
  6881. const list2 = [];
  6882. for (let i = 0; i < list.length; i++) {
  6883. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  6884. }
  6885. return [list1, list2];
  6886. }
  6887. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  6888. var flow = (superClass => {
  6889. var _temp;
  6890. return _temp = class extends superClass {
  6891. constructor(options, input) {
  6892. super(options, input);
  6893. this.flowPragma = void 0;
  6894. this.flowPragma = undefined;
  6895. }
  6896. shouldParseTypes() {
  6897. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  6898. }
  6899. shouldParseEnums() {
  6900. return !!this.getPluginOption("flow", "enums");
  6901. }
  6902. finishToken(type, val) {
  6903. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  6904. if (this.flowPragma === undefined) {
  6905. this.flowPragma = null;
  6906. }
  6907. }
  6908. return super.finishToken(type, val);
  6909. }
  6910. addComment(comment) {
  6911. if (this.flowPragma === undefined) {
  6912. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  6913. if (!matches) ; else if (matches[1] === "flow") {
  6914. this.flowPragma = "flow";
  6915. } else if (matches[1] === "noflow") {
  6916. this.flowPragma = "noflow";
  6917. } else {
  6918. throw new Error("Unexpected flow pragma");
  6919. }
  6920. }
  6921. return super.addComment(comment);
  6922. }
  6923. flowParseTypeInitialiser(tok) {
  6924. const oldInType = this.state.inType;
  6925. this.state.inType = true;
  6926. this.expect(tok || types.colon);
  6927. const type = this.flowParseType();
  6928. this.state.inType = oldInType;
  6929. return type;
  6930. }
  6931. flowParsePredicate() {
  6932. const node = this.startNode();
  6933. const moduloLoc = this.state.startLoc;
  6934. const moduloPos = this.state.start;
  6935. this.expect(types.modulo);
  6936. const checksLoc = this.state.startLoc;
  6937. this.expectContextual("checks");
  6938. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  6939. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  6940. }
  6941. if (this.eat(types.parenL)) {
  6942. node.value = this.parseExpression();
  6943. this.expect(types.parenR);
  6944. return this.finishNode(node, "DeclaredPredicate");
  6945. } else {
  6946. return this.finishNode(node, "InferredPredicate");
  6947. }
  6948. }
  6949. flowParseTypeAndPredicateInitialiser() {
  6950. const oldInType = this.state.inType;
  6951. this.state.inType = true;
  6952. this.expect(types.colon);
  6953. let type = null;
  6954. let predicate = null;
  6955. if (this.match(types.modulo)) {
  6956. this.state.inType = oldInType;
  6957. predicate = this.flowParsePredicate();
  6958. } else {
  6959. type = this.flowParseType();
  6960. this.state.inType = oldInType;
  6961. if (this.match(types.modulo)) {
  6962. predicate = this.flowParsePredicate();
  6963. }
  6964. }
  6965. return [type, predicate];
  6966. }
  6967. flowParseDeclareClass(node) {
  6968. this.next();
  6969. this.flowParseInterfaceish(node, true);
  6970. return this.finishNode(node, "DeclareClass");
  6971. }
  6972. flowParseDeclareFunction(node) {
  6973. this.next();
  6974. const id = node.id = this.parseIdentifier();
  6975. const typeNode = this.startNode();
  6976. const typeContainer = this.startNode();
  6977. if (this.isRelational("<")) {
  6978. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  6979. } else {
  6980. typeNode.typeParameters = null;
  6981. }
  6982. this.expect(types.parenL);
  6983. const tmp = this.flowParseFunctionTypeParams();
  6984. typeNode.params = tmp.params;
  6985. typeNode.rest = tmp.rest;
  6986. this.expect(types.parenR);
  6987. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  6988. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  6989. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  6990. this.resetEndLocation(id);
  6991. this.semicolon();
  6992. return this.finishNode(node, "DeclareFunction");
  6993. }
  6994. flowParseDeclare(node, insideModule) {
  6995. if (this.match(types._class)) {
  6996. return this.flowParseDeclareClass(node);
  6997. } else if (this.match(types._function)) {
  6998. return this.flowParseDeclareFunction(node);
  6999. } else if (this.match(types._var)) {
  7000. return this.flowParseDeclareVariable(node);
  7001. } else if (this.eatContextual("module")) {
  7002. if (this.match(types.dot)) {
  7003. return this.flowParseDeclareModuleExports(node);
  7004. } else {
  7005. if (insideModule) {
  7006. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  7007. }
  7008. return this.flowParseDeclareModule(node);
  7009. }
  7010. } else if (this.isContextual("type")) {
  7011. return this.flowParseDeclareTypeAlias(node);
  7012. } else if (this.isContextual("opaque")) {
  7013. return this.flowParseDeclareOpaqueType(node);
  7014. } else if (this.isContextual("interface")) {
  7015. return this.flowParseDeclareInterface(node);
  7016. } else if (this.match(types._export)) {
  7017. return this.flowParseDeclareExportDeclaration(node, insideModule);
  7018. } else {
  7019. throw this.unexpected();
  7020. }
  7021. }
  7022. flowParseDeclareVariable(node) {
  7023. this.next();
  7024. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  7025. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  7026. this.semicolon();
  7027. return this.finishNode(node, "DeclareVariable");
  7028. }
  7029. flowParseDeclareModule(node) {
  7030. this.scope.enter(SCOPE_OTHER);
  7031. if (this.match(types.string)) {
  7032. node.id = this.parseExprAtom();
  7033. } else {
  7034. node.id = this.parseIdentifier();
  7035. }
  7036. const bodyNode = node.body = this.startNode();
  7037. const body = bodyNode.body = [];
  7038. this.expect(types.braceL);
  7039. while (!this.match(types.braceR)) {
  7040. let bodyNode = this.startNode();
  7041. if (this.match(types._import)) {
  7042. this.next();
  7043. if (!this.isContextual("type") && !this.match(types._typeof)) {
  7044. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  7045. }
  7046. this.parseImport(bodyNode);
  7047. } else {
  7048. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  7049. bodyNode = this.flowParseDeclare(bodyNode, true);
  7050. }
  7051. body.push(bodyNode);
  7052. }
  7053. this.scope.exit();
  7054. this.expect(types.braceR);
  7055. this.finishNode(bodyNode, "BlockStatement");
  7056. let kind = null;
  7057. let hasModuleExport = false;
  7058. body.forEach(bodyElement => {
  7059. if (isEsModuleType(bodyElement)) {
  7060. if (kind === "CommonJS") {
  7061. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  7062. }
  7063. kind = "ES";
  7064. } else if (bodyElement.type === "DeclareModuleExports") {
  7065. if (hasModuleExport) {
  7066. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  7067. }
  7068. if (kind === "ES") {
  7069. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  7070. }
  7071. kind = "CommonJS";
  7072. hasModuleExport = true;
  7073. }
  7074. });
  7075. node.kind = kind || "CommonJS";
  7076. return this.finishNode(node, "DeclareModule");
  7077. }
  7078. flowParseDeclareExportDeclaration(node, insideModule) {
  7079. this.expect(types._export);
  7080. if (this.eat(types._default)) {
  7081. if (this.match(types._function) || this.match(types._class)) {
  7082. node.declaration = this.flowParseDeclare(this.startNode());
  7083. } else {
  7084. node.declaration = this.flowParseType();
  7085. this.semicolon();
  7086. }
  7087. node.default = true;
  7088. return this.finishNode(node, "DeclareExportDeclaration");
  7089. } else {
  7090. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  7091. const label = this.state.value;
  7092. const suggestion = exportSuggestions[label];
  7093. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  7094. }
  7095. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  7096. node.declaration = this.flowParseDeclare(this.startNode());
  7097. node.default = false;
  7098. return this.finishNode(node, "DeclareExportDeclaration");
  7099. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  7100. node = this.parseExport(node);
  7101. if (node.type === "ExportNamedDeclaration") {
  7102. node.type = "ExportDeclaration";
  7103. node.default = false;
  7104. delete node.exportKind;
  7105. }
  7106. node.type = "Declare" + node.type;
  7107. return node;
  7108. }
  7109. }
  7110. throw this.unexpected();
  7111. }
  7112. flowParseDeclareModuleExports(node) {
  7113. this.next();
  7114. this.expectContextual("exports");
  7115. node.typeAnnotation = this.flowParseTypeAnnotation();
  7116. this.semicolon();
  7117. return this.finishNode(node, "DeclareModuleExports");
  7118. }
  7119. flowParseDeclareTypeAlias(node) {
  7120. this.next();
  7121. this.flowParseTypeAlias(node);
  7122. node.type = "DeclareTypeAlias";
  7123. return node;
  7124. }
  7125. flowParseDeclareOpaqueType(node) {
  7126. this.next();
  7127. this.flowParseOpaqueType(node, true);
  7128. node.type = "DeclareOpaqueType";
  7129. return node;
  7130. }
  7131. flowParseDeclareInterface(node) {
  7132. this.next();
  7133. this.flowParseInterfaceish(node);
  7134. return this.finishNode(node, "DeclareInterface");
  7135. }
  7136. flowParseInterfaceish(node, isClass = false) {
  7137. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  7138. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  7139. if (this.isRelational("<")) {
  7140. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7141. } else {
  7142. node.typeParameters = null;
  7143. }
  7144. node.extends = [];
  7145. node.implements = [];
  7146. node.mixins = [];
  7147. if (this.eat(types._extends)) {
  7148. do {
  7149. node.extends.push(this.flowParseInterfaceExtends());
  7150. } while (!isClass && this.eat(types.comma));
  7151. }
  7152. if (this.isContextual("mixins")) {
  7153. this.next();
  7154. do {
  7155. node.mixins.push(this.flowParseInterfaceExtends());
  7156. } while (this.eat(types.comma));
  7157. }
  7158. if (this.isContextual("implements")) {
  7159. this.next();
  7160. do {
  7161. node.implements.push(this.flowParseInterfaceExtends());
  7162. } while (this.eat(types.comma));
  7163. }
  7164. node.body = this.flowParseObjectType({
  7165. allowStatic: isClass,
  7166. allowExact: false,
  7167. allowSpread: false,
  7168. allowProto: isClass,
  7169. allowInexact: false
  7170. });
  7171. }
  7172. flowParseInterfaceExtends() {
  7173. const node = this.startNode();
  7174. node.id = this.flowParseQualifiedTypeIdentifier();
  7175. if (this.isRelational("<")) {
  7176. node.typeParameters = this.flowParseTypeParameterInstantiation();
  7177. } else {
  7178. node.typeParameters = null;
  7179. }
  7180. return this.finishNode(node, "InterfaceExtends");
  7181. }
  7182. flowParseInterface(node) {
  7183. this.flowParseInterfaceish(node);
  7184. return this.finishNode(node, "InterfaceDeclaration");
  7185. }
  7186. checkNotUnderscore(word) {
  7187. if (word === "_") {
  7188. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  7189. }
  7190. }
  7191. checkReservedType(word, startLoc, declaration) {
  7192. if (!reservedTypes.has(word)) return;
  7193. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  7194. }
  7195. flowParseRestrictedIdentifier(liberal, declaration) {
  7196. this.checkReservedType(this.state.value, this.state.start, declaration);
  7197. return this.parseIdentifier(liberal);
  7198. }
  7199. flowParseTypeAlias(node) {
  7200. node.id = this.flowParseRestrictedIdentifier(false, true);
  7201. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  7202. if (this.isRelational("<")) {
  7203. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7204. } else {
  7205. node.typeParameters = null;
  7206. }
  7207. node.right = this.flowParseTypeInitialiser(types.eq);
  7208. this.semicolon();
  7209. return this.finishNode(node, "TypeAlias");
  7210. }
  7211. flowParseOpaqueType(node, declare) {
  7212. this.expectContextual("type");
  7213. node.id = this.flowParseRestrictedIdentifier(true, true);
  7214. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  7215. if (this.isRelational("<")) {
  7216. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7217. } else {
  7218. node.typeParameters = null;
  7219. }
  7220. node.supertype = null;
  7221. if (this.match(types.colon)) {
  7222. node.supertype = this.flowParseTypeInitialiser(types.colon);
  7223. }
  7224. node.impltype = null;
  7225. if (!declare) {
  7226. node.impltype = this.flowParseTypeInitialiser(types.eq);
  7227. }
  7228. this.semicolon();
  7229. return this.finishNode(node, "OpaqueType");
  7230. }
  7231. flowParseTypeParameter(requireDefault = false) {
  7232. const nodeStart = this.state.start;
  7233. const node = this.startNode();
  7234. const variance = this.flowParseVariance();
  7235. const ident = this.flowParseTypeAnnotatableIdentifier();
  7236. node.name = ident.name;
  7237. node.variance = variance;
  7238. node.bound = ident.typeAnnotation;
  7239. if (this.match(types.eq)) {
  7240. this.eat(types.eq);
  7241. node.default = this.flowParseType();
  7242. } else {
  7243. if (requireDefault) {
  7244. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  7245. }
  7246. }
  7247. return this.finishNode(node, "TypeParameter");
  7248. }
  7249. flowParseTypeParameterDeclaration() {
  7250. const oldInType = this.state.inType;
  7251. const node = this.startNode();
  7252. node.params = [];
  7253. this.state.inType = true;
  7254. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  7255. this.next();
  7256. } else {
  7257. this.unexpected();
  7258. }
  7259. let defaultRequired = false;
  7260. do {
  7261. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  7262. node.params.push(typeParameter);
  7263. if (typeParameter.default) {
  7264. defaultRequired = true;
  7265. }
  7266. if (!this.isRelational(">")) {
  7267. this.expect(types.comma);
  7268. }
  7269. } while (!this.isRelational(">"));
  7270. this.expectRelational(">");
  7271. this.state.inType = oldInType;
  7272. return this.finishNode(node, "TypeParameterDeclaration");
  7273. }
  7274. flowParseTypeParameterInstantiation() {
  7275. const node = this.startNode();
  7276. const oldInType = this.state.inType;
  7277. node.params = [];
  7278. this.state.inType = true;
  7279. this.expectRelational("<");
  7280. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  7281. this.state.noAnonFunctionType = false;
  7282. while (!this.isRelational(">")) {
  7283. node.params.push(this.flowParseType());
  7284. if (!this.isRelational(">")) {
  7285. this.expect(types.comma);
  7286. }
  7287. }
  7288. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7289. this.expectRelational(">");
  7290. this.state.inType = oldInType;
  7291. return this.finishNode(node, "TypeParameterInstantiation");
  7292. }
  7293. flowParseTypeParameterInstantiationCallOrNew() {
  7294. const node = this.startNode();
  7295. const oldInType = this.state.inType;
  7296. node.params = [];
  7297. this.state.inType = true;
  7298. this.expectRelational("<");
  7299. while (!this.isRelational(">")) {
  7300. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  7301. if (!this.isRelational(">")) {
  7302. this.expect(types.comma);
  7303. }
  7304. }
  7305. this.expectRelational(">");
  7306. this.state.inType = oldInType;
  7307. return this.finishNode(node, "TypeParameterInstantiation");
  7308. }
  7309. flowParseInterfaceType() {
  7310. const node = this.startNode();
  7311. this.expectContextual("interface");
  7312. node.extends = [];
  7313. if (this.eat(types._extends)) {
  7314. do {
  7315. node.extends.push(this.flowParseInterfaceExtends());
  7316. } while (this.eat(types.comma));
  7317. }
  7318. node.body = this.flowParseObjectType({
  7319. allowStatic: false,
  7320. allowExact: false,
  7321. allowSpread: false,
  7322. allowProto: false,
  7323. allowInexact: false
  7324. });
  7325. return this.finishNode(node, "InterfaceTypeAnnotation");
  7326. }
  7327. flowParseObjectPropertyKey() {
  7328. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  7329. }
  7330. flowParseObjectTypeIndexer(node, isStatic, variance) {
  7331. node.static = isStatic;
  7332. if (this.lookahead().type === types.colon) {
  7333. node.id = this.flowParseObjectPropertyKey();
  7334. node.key = this.flowParseTypeInitialiser();
  7335. } else {
  7336. node.id = null;
  7337. node.key = this.flowParseType();
  7338. }
  7339. this.expect(types.bracketR);
  7340. node.value = this.flowParseTypeInitialiser();
  7341. node.variance = variance;
  7342. return this.finishNode(node, "ObjectTypeIndexer");
  7343. }
  7344. flowParseObjectTypeInternalSlot(node, isStatic) {
  7345. node.static = isStatic;
  7346. node.id = this.flowParseObjectPropertyKey();
  7347. this.expect(types.bracketR);
  7348. this.expect(types.bracketR);
  7349. if (this.isRelational("<") || this.match(types.parenL)) {
  7350. node.method = true;
  7351. node.optional = false;
  7352. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  7353. } else {
  7354. node.method = false;
  7355. if (this.eat(types.question)) {
  7356. node.optional = true;
  7357. }
  7358. node.value = this.flowParseTypeInitialiser();
  7359. }
  7360. return this.finishNode(node, "ObjectTypeInternalSlot");
  7361. }
  7362. flowParseObjectTypeMethodish(node) {
  7363. node.params = [];
  7364. node.rest = null;
  7365. node.typeParameters = null;
  7366. if (this.isRelational("<")) {
  7367. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7368. }
  7369. this.expect(types.parenL);
  7370. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  7371. node.params.push(this.flowParseFunctionTypeParam());
  7372. if (!this.match(types.parenR)) {
  7373. this.expect(types.comma);
  7374. }
  7375. }
  7376. if (this.eat(types.ellipsis)) {
  7377. node.rest = this.flowParseFunctionTypeParam();
  7378. }
  7379. this.expect(types.parenR);
  7380. node.returnType = this.flowParseTypeInitialiser();
  7381. return this.finishNode(node, "FunctionTypeAnnotation");
  7382. }
  7383. flowParseObjectTypeCallProperty(node, isStatic) {
  7384. const valueNode = this.startNode();
  7385. node.static = isStatic;
  7386. node.value = this.flowParseObjectTypeMethodish(valueNode);
  7387. return this.finishNode(node, "ObjectTypeCallProperty");
  7388. }
  7389. flowParseObjectType({
  7390. allowStatic,
  7391. allowExact,
  7392. allowSpread,
  7393. allowProto,
  7394. allowInexact
  7395. }) {
  7396. const oldInType = this.state.inType;
  7397. this.state.inType = true;
  7398. const nodeStart = this.startNode();
  7399. nodeStart.callProperties = [];
  7400. nodeStart.properties = [];
  7401. nodeStart.indexers = [];
  7402. nodeStart.internalSlots = [];
  7403. let endDelim;
  7404. let exact;
  7405. let inexact = false;
  7406. if (allowExact && this.match(types.braceBarL)) {
  7407. this.expect(types.braceBarL);
  7408. endDelim = types.braceBarR;
  7409. exact = true;
  7410. } else {
  7411. this.expect(types.braceL);
  7412. endDelim = types.braceR;
  7413. exact = false;
  7414. }
  7415. nodeStart.exact = exact;
  7416. while (!this.match(endDelim)) {
  7417. let isStatic = false;
  7418. let protoStart = null;
  7419. let inexactStart = null;
  7420. const node = this.startNode();
  7421. if (allowProto && this.isContextual("proto")) {
  7422. const lookahead = this.lookahead();
  7423. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  7424. this.next();
  7425. protoStart = this.state.start;
  7426. allowStatic = false;
  7427. }
  7428. }
  7429. if (allowStatic && this.isContextual("static")) {
  7430. const lookahead = this.lookahead();
  7431. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  7432. this.next();
  7433. isStatic = true;
  7434. }
  7435. }
  7436. const variance = this.flowParseVariance();
  7437. if (this.eat(types.bracketL)) {
  7438. if (protoStart != null) {
  7439. this.unexpected(protoStart);
  7440. }
  7441. if (this.eat(types.bracketL)) {
  7442. if (variance) {
  7443. this.unexpected(variance.start);
  7444. }
  7445. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  7446. } else {
  7447. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  7448. }
  7449. } else if (this.match(types.parenL) || this.isRelational("<")) {
  7450. if (protoStart != null) {
  7451. this.unexpected(protoStart);
  7452. }
  7453. if (variance) {
  7454. this.unexpected(variance.start);
  7455. }
  7456. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  7457. } else {
  7458. let kind = "init";
  7459. if (this.isContextual("get") || this.isContextual("set")) {
  7460. const lookahead = this.lookahead();
  7461. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  7462. kind = this.state.value;
  7463. this.next();
  7464. }
  7465. }
  7466. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  7467. if (propOrInexact === null) {
  7468. inexact = true;
  7469. inexactStart = this.state.lastTokStart;
  7470. } else {
  7471. nodeStart.properties.push(propOrInexact);
  7472. }
  7473. }
  7474. this.flowObjectTypeSemicolon();
  7475. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  7476. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  7477. }
  7478. }
  7479. this.expect(endDelim);
  7480. if (allowSpread) {
  7481. nodeStart.inexact = inexact;
  7482. }
  7483. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  7484. this.state.inType = oldInType;
  7485. return out;
  7486. }
  7487. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  7488. if (this.eat(types.ellipsis)) {
  7489. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  7490. if (isInexactToken) {
  7491. if (!allowSpread) {
  7492. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  7493. } else if (!allowInexact) {
  7494. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  7495. }
  7496. if (variance) {
  7497. this.raise(variance.start, FlowErrors.InexactVariance);
  7498. }
  7499. return null;
  7500. }
  7501. if (!allowSpread) {
  7502. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  7503. }
  7504. if (protoStart != null) {
  7505. this.unexpected(protoStart);
  7506. }
  7507. if (variance) {
  7508. this.raise(variance.start, FlowErrors.SpreadVariance);
  7509. }
  7510. node.argument = this.flowParseType();
  7511. return this.finishNode(node, "ObjectTypeSpreadProperty");
  7512. } else {
  7513. node.key = this.flowParseObjectPropertyKey();
  7514. node.static = isStatic;
  7515. node.proto = protoStart != null;
  7516. node.kind = kind;
  7517. let optional = false;
  7518. if (this.isRelational("<") || this.match(types.parenL)) {
  7519. node.method = true;
  7520. if (protoStart != null) {
  7521. this.unexpected(protoStart);
  7522. }
  7523. if (variance) {
  7524. this.unexpected(variance.start);
  7525. }
  7526. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  7527. if (kind === "get" || kind === "set") {
  7528. this.flowCheckGetterSetterParams(node);
  7529. }
  7530. } else {
  7531. if (kind !== "init") this.unexpected();
  7532. node.method = false;
  7533. if (this.eat(types.question)) {
  7534. optional = true;
  7535. }
  7536. node.value = this.flowParseTypeInitialiser();
  7537. node.variance = variance;
  7538. }
  7539. node.optional = optional;
  7540. return this.finishNode(node, "ObjectTypeProperty");
  7541. }
  7542. }
  7543. flowCheckGetterSetterParams(property) {
  7544. const paramCount = property.kind === "get" ? 0 : 1;
  7545. const start = property.start;
  7546. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  7547. if (length !== paramCount) {
  7548. if (property.kind === "get") {
  7549. this.raise(start, ErrorMessages.BadGetterArity);
  7550. } else {
  7551. this.raise(start, ErrorMessages.BadSetterArity);
  7552. }
  7553. }
  7554. if (property.kind === "set" && property.value.rest) {
  7555. this.raise(start, ErrorMessages.BadSetterRestParameter);
  7556. }
  7557. }
  7558. flowObjectTypeSemicolon() {
  7559. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  7560. this.unexpected();
  7561. }
  7562. }
  7563. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  7564. startPos = startPos || this.state.start;
  7565. startLoc = startLoc || this.state.startLoc;
  7566. let node = id || this.flowParseRestrictedIdentifier(true);
  7567. while (this.eat(types.dot)) {
  7568. const node2 = this.startNodeAt(startPos, startLoc);
  7569. node2.qualification = node;
  7570. node2.id = this.flowParseRestrictedIdentifier(true);
  7571. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  7572. }
  7573. return node;
  7574. }
  7575. flowParseGenericType(startPos, startLoc, id) {
  7576. const node = this.startNodeAt(startPos, startLoc);
  7577. node.typeParameters = null;
  7578. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  7579. if (this.isRelational("<")) {
  7580. node.typeParameters = this.flowParseTypeParameterInstantiation();
  7581. }
  7582. return this.finishNode(node, "GenericTypeAnnotation");
  7583. }
  7584. flowParseTypeofType() {
  7585. const node = this.startNode();
  7586. this.expect(types._typeof);
  7587. node.argument = this.flowParsePrimaryType();
  7588. return this.finishNode(node, "TypeofTypeAnnotation");
  7589. }
  7590. flowParseTupleType() {
  7591. const node = this.startNode();
  7592. node.types = [];
  7593. this.expect(types.bracketL);
  7594. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  7595. node.types.push(this.flowParseType());
  7596. if (this.match(types.bracketR)) break;
  7597. this.expect(types.comma);
  7598. }
  7599. this.expect(types.bracketR);
  7600. return this.finishNode(node, "TupleTypeAnnotation");
  7601. }
  7602. flowParseFunctionTypeParam() {
  7603. let name = null;
  7604. let optional = false;
  7605. let typeAnnotation = null;
  7606. const node = this.startNode();
  7607. const lh = this.lookahead();
  7608. if (lh.type === types.colon || lh.type === types.question) {
  7609. name = this.parseIdentifier();
  7610. if (this.eat(types.question)) {
  7611. optional = true;
  7612. }
  7613. typeAnnotation = this.flowParseTypeInitialiser();
  7614. } else {
  7615. typeAnnotation = this.flowParseType();
  7616. }
  7617. node.name = name;
  7618. node.optional = optional;
  7619. node.typeAnnotation = typeAnnotation;
  7620. return this.finishNode(node, "FunctionTypeParam");
  7621. }
  7622. reinterpretTypeAsFunctionTypeParam(type) {
  7623. const node = this.startNodeAt(type.start, type.loc.start);
  7624. node.name = null;
  7625. node.optional = false;
  7626. node.typeAnnotation = type;
  7627. return this.finishNode(node, "FunctionTypeParam");
  7628. }
  7629. flowParseFunctionTypeParams(params = []) {
  7630. let rest = null;
  7631. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  7632. params.push(this.flowParseFunctionTypeParam());
  7633. if (!this.match(types.parenR)) {
  7634. this.expect(types.comma);
  7635. }
  7636. }
  7637. if (this.eat(types.ellipsis)) {
  7638. rest = this.flowParseFunctionTypeParam();
  7639. }
  7640. return {
  7641. params,
  7642. rest
  7643. };
  7644. }
  7645. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  7646. switch (id.name) {
  7647. case "any":
  7648. return this.finishNode(node, "AnyTypeAnnotation");
  7649. case "bool":
  7650. case "boolean":
  7651. return this.finishNode(node, "BooleanTypeAnnotation");
  7652. case "mixed":
  7653. return this.finishNode(node, "MixedTypeAnnotation");
  7654. case "empty":
  7655. return this.finishNode(node, "EmptyTypeAnnotation");
  7656. case "number":
  7657. return this.finishNode(node, "NumberTypeAnnotation");
  7658. case "string":
  7659. return this.finishNode(node, "StringTypeAnnotation");
  7660. case "symbol":
  7661. return this.finishNode(node, "SymbolTypeAnnotation");
  7662. default:
  7663. this.checkNotUnderscore(id.name);
  7664. return this.flowParseGenericType(startPos, startLoc, id);
  7665. }
  7666. }
  7667. flowParsePrimaryType() {
  7668. const startPos = this.state.start;
  7669. const startLoc = this.state.startLoc;
  7670. const node = this.startNode();
  7671. let tmp;
  7672. let type;
  7673. let isGroupedType = false;
  7674. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  7675. switch (this.state.type) {
  7676. case types.name:
  7677. if (this.isContextual("interface")) {
  7678. return this.flowParseInterfaceType();
  7679. }
  7680. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  7681. case types.braceL:
  7682. return this.flowParseObjectType({
  7683. allowStatic: false,
  7684. allowExact: false,
  7685. allowSpread: true,
  7686. allowProto: false,
  7687. allowInexact: true
  7688. });
  7689. case types.braceBarL:
  7690. return this.flowParseObjectType({
  7691. allowStatic: false,
  7692. allowExact: true,
  7693. allowSpread: true,
  7694. allowProto: false,
  7695. allowInexact: false
  7696. });
  7697. case types.bracketL:
  7698. this.state.noAnonFunctionType = false;
  7699. type = this.flowParseTupleType();
  7700. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7701. return type;
  7702. case types.relational:
  7703. if (this.state.value === "<") {
  7704. node.typeParameters = this.flowParseTypeParameterDeclaration();
  7705. this.expect(types.parenL);
  7706. tmp = this.flowParseFunctionTypeParams();
  7707. node.params = tmp.params;
  7708. node.rest = tmp.rest;
  7709. this.expect(types.parenR);
  7710. this.expect(types.arrow);
  7711. node.returnType = this.flowParseType();
  7712. return this.finishNode(node, "FunctionTypeAnnotation");
  7713. }
  7714. break;
  7715. case types.parenL:
  7716. this.next();
  7717. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  7718. if (this.match(types.name)) {
  7719. const token = this.lookahead().type;
  7720. isGroupedType = token !== types.question && token !== types.colon;
  7721. } else {
  7722. isGroupedType = true;
  7723. }
  7724. }
  7725. if (isGroupedType) {
  7726. this.state.noAnonFunctionType = false;
  7727. type = this.flowParseType();
  7728. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  7729. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  7730. this.expect(types.parenR);
  7731. return type;
  7732. } else {
  7733. this.eat(types.comma);
  7734. }
  7735. }
  7736. if (type) {
  7737. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  7738. } else {
  7739. tmp = this.flowParseFunctionTypeParams();
  7740. }
  7741. node.params = tmp.params;
  7742. node.rest = tmp.rest;
  7743. this.expect(types.parenR);
  7744. this.expect(types.arrow);
  7745. node.returnType = this.flowParseType();
  7746. node.typeParameters = null;
  7747. return this.finishNode(node, "FunctionTypeAnnotation");
  7748. case types.string:
  7749. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  7750. case types._true:
  7751. case types._false:
  7752. node.value = this.match(types._true);
  7753. this.next();
  7754. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  7755. case types.plusMin:
  7756. if (this.state.value === "-") {
  7757. this.next();
  7758. if (this.match(types.num)) {
  7759. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  7760. }
  7761. if (this.match(types.bigint)) {
  7762. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  7763. }
  7764. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  7765. }
  7766. throw this.unexpected();
  7767. case types.num:
  7768. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  7769. case types.bigint:
  7770. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  7771. case types._void:
  7772. this.next();
  7773. return this.finishNode(node, "VoidTypeAnnotation");
  7774. case types._null:
  7775. this.next();
  7776. return this.finishNode(node, "NullLiteralTypeAnnotation");
  7777. case types._this:
  7778. this.next();
  7779. return this.finishNode(node, "ThisTypeAnnotation");
  7780. case types.star:
  7781. this.next();
  7782. return this.finishNode(node, "ExistsTypeAnnotation");
  7783. default:
  7784. if (this.state.type.keyword === "typeof") {
  7785. return this.flowParseTypeofType();
  7786. } else if (this.state.type.keyword) {
  7787. const label = this.state.type.label;
  7788. this.next();
  7789. return super.createIdentifier(node, label);
  7790. }
  7791. }
  7792. throw this.unexpected();
  7793. }
  7794. flowParsePostfixType() {
  7795. const startPos = this.state.start,
  7796. startLoc = this.state.startLoc;
  7797. let type = this.flowParsePrimaryType();
  7798. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  7799. const node = this.startNodeAt(startPos, startLoc);
  7800. node.elementType = type;
  7801. this.expect(types.bracketL);
  7802. this.expect(types.bracketR);
  7803. type = this.finishNode(node, "ArrayTypeAnnotation");
  7804. }
  7805. return type;
  7806. }
  7807. flowParsePrefixType() {
  7808. const node = this.startNode();
  7809. if (this.eat(types.question)) {
  7810. node.typeAnnotation = this.flowParsePrefixType();
  7811. return this.finishNode(node, "NullableTypeAnnotation");
  7812. } else {
  7813. return this.flowParsePostfixType();
  7814. }
  7815. }
  7816. flowParseAnonFunctionWithoutParens() {
  7817. const param = this.flowParsePrefixType();
  7818. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  7819. const node = this.startNodeAt(param.start, param.loc.start);
  7820. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  7821. node.rest = null;
  7822. node.returnType = this.flowParseType();
  7823. node.typeParameters = null;
  7824. return this.finishNode(node, "FunctionTypeAnnotation");
  7825. }
  7826. return param;
  7827. }
  7828. flowParseIntersectionType() {
  7829. const node = this.startNode();
  7830. this.eat(types.bitwiseAND);
  7831. const type = this.flowParseAnonFunctionWithoutParens();
  7832. node.types = [type];
  7833. while (this.eat(types.bitwiseAND)) {
  7834. node.types.push(this.flowParseAnonFunctionWithoutParens());
  7835. }
  7836. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  7837. }
  7838. flowParseUnionType() {
  7839. const node = this.startNode();
  7840. this.eat(types.bitwiseOR);
  7841. const type = this.flowParseIntersectionType();
  7842. node.types = [type];
  7843. while (this.eat(types.bitwiseOR)) {
  7844. node.types.push(this.flowParseIntersectionType());
  7845. }
  7846. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  7847. }
  7848. flowParseType() {
  7849. const oldInType = this.state.inType;
  7850. this.state.inType = true;
  7851. const type = this.flowParseUnionType();
  7852. this.state.inType = oldInType;
  7853. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  7854. return type;
  7855. }
  7856. flowParseTypeOrImplicitInstantiation() {
  7857. if (this.state.type === types.name && this.state.value === "_") {
  7858. const startPos = this.state.start;
  7859. const startLoc = this.state.startLoc;
  7860. const node = this.parseIdentifier();
  7861. return this.flowParseGenericType(startPos, startLoc, node);
  7862. } else {
  7863. return this.flowParseType();
  7864. }
  7865. }
  7866. flowParseTypeAnnotation() {
  7867. const node = this.startNode();
  7868. node.typeAnnotation = this.flowParseTypeInitialiser();
  7869. return this.finishNode(node, "TypeAnnotation");
  7870. }
  7871. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  7872. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  7873. if (this.match(types.colon)) {
  7874. ident.typeAnnotation = this.flowParseTypeAnnotation();
  7875. this.resetEndLocation(ident);
  7876. }
  7877. return ident;
  7878. }
  7879. typeCastToParameter(node) {
  7880. node.expression.typeAnnotation = node.typeAnnotation;
  7881. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  7882. return node.expression;
  7883. }
  7884. flowParseVariance() {
  7885. let variance = null;
  7886. if (this.match(types.plusMin)) {
  7887. variance = this.startNode();
  7888. if (this.state.value === "+") {
  7889. variance.kind = "plus";
  7890. } else {
  7891. variance.kind = "minus";
  7892. }
  7893. this.next();
  7894. this.finishNode(variance, "Variance");
  7895. }
  7896. return variance;
  7897. }
  7898. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  7899. if (allowExpressionBody) {
  7900. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  7901. }
  7902. return super.parseFunctionBody(node, false, isMethod);
  7903. }
  7904. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  7905. if (this.match(types.colon)) {
  7906. const typeNode = this.startNode();
  7907. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  7908. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  7909. }
  7910. super.parseFunctionBodyAndFinish(node, type, isMethod);
  7911. }
  7912. parseStatement(context, topLevel) {
  7913. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  7914. const lookahead = this.lookahead();
  7915. if (lookahead.type === types.name || isKeyword(lookahead.value)) {
  7916. const node = this.startNode();
  7917. this.next();
  7918. return this.flowParseInterface(node);
  7919. }
  7920. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  7921. const node = this.startNode();
  7922. this.next();
  7923. return this.flowParseEnumDeclaration(node);
  7924. }
  7925. const stmt = super.parseStatement(context, topLevel);
  7926. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  7927. this.flowPragma = null;
  7928. }
  7929. return stmt;
  7930. }
  7931. parseExpressionStatement(node, expr) {
  7932. if (expr.type === "Identifier") {
  7933. if (expr.name === "declare") {
  7934. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  7935. return this.flowParseDeclare(node);
  7936. }
  7937. } else if (this.match(types.name)) {
  7938. if (expr.name === "interface") {
  7939. return this.flowParseInterface(node);
  7940. } else if (expr.name === "type") {
  7941. return this.flowParseTypeAlias(node);
  7942. } else if (expr.name === "opaque") {
  7943. return this.flowParseOpaqueType(node, false);
  7944. }
  7945. }
  7946. }
  7947. return super.parseExpressionStatement(node, expr);
  7948. }
  7949. shouldParseExportDeclaration() {
  7950. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  7951. }
  7952. isExportDefaultSpecifier() {
  7953. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  7954. return false;
  7955. }
  7956. return super.isExportDefaultSpecifier();
  7957. }
  7958. parseExportDefaultExpression() {
  7959. if (this.shouldParseEnums() && this.isContextual("enum")) {
  7960. const node = this.startNode();
  7961. this.next();
  7962. return this.flowParseEnumDeclaration(node);
  7963. }
  7964. return super.parseExportDefaultExpression();
  7965. }
  7966. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  7967. if (!this.match(types.question)) return expr;
  7968. if (refNeedsArrowPos) {
  7969. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  7970. if (!result.node) {
  7971. refNeedsArrowPos.start = result.error.pos || this.state.start;
  7972. return expr;
  7973. }
  7974. if (result.error) this.state = result.failState;
  7975. return result.node;
  7976. }
  7977. this.expect(types.question);
  7978. const state = this.state.clone();
  7979. const originalNoArrowAt = this.state.noArrowAt;
  7980. const node = this.startNodeAt(startPos, startLoc);
  7981. let {
  7982. consequent,
  7983. failed
  7984. } = this.tryParseConditionalConsequent();
  7985. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  7986. if (failed || invalid.length > 0) {
  7987. const noArrowAt = [...originalNoArrowAt];
  7988. if (invalid.length > 0) {
  7989. this.state = state;
  7990. this.state.noArrowAt = noArrowAt;
  7991. for (let i = 0; i < invalid.length; i++) {
  7992. noArrowAt.push(invalid[i].start);
  7993. }
  7994. ({
  7995. consequent,
  7996. failed
  7997. } = this.tryParseConditionalConsequent());
  7998. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  7999. }
  8000. if (failed && valid.length > 1) {
  8001. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  8002. }
  8003. if (failed && valid.length === 1) {
  8004. this.state = state;
  8005. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  8006. ({
  8007. consequent,
  8008. failed
  8009. } = this.tryParseConditionalConsequent());
  8010. }
  8011. }
  8012. this.getArrowLikeExpressions(consequent, true);
  8013. this.state.noArrowAt = originalNoArrowAt;
  8014. this.expect(types.colon);
  8015. node.test = expr;
  8016. node.consequent = consequent;
  8017. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined, undefined));
  8018. return this.finishNode(node, "ConditionalExpression");
  8019. }
  8020. tryParseConditionalConsequent() {
  8021. this.state.noArrowParamsConversionAt.push(this.state.start);
  8022. const consequent = this.parseMaybeAssignAllowIn();
  8023. const failed = !this.match(types.colon);
  8024. this.state.noArrowParamsConversionAt.pop();
  8025. return {
  8026. consequent,
  8027. failed
  8028. };
  8029. }
  8030. getArrowLikeExpressions(node, disallowInvalid) {
  8031. const stack = [node];
  8032. const arrows = [];
  8033. while (stack.length !== 0) {
  8034. const node = stack.pop();
  8035. if (node.type === "ArrowFunctionExpression") {
  8036. if (node.typeParameters || !node.returnType) {
  8037. this.finishArrowValidation(node);
  8038. } else {
  8039. arrows.push(node);
  8040. }
  8041. stack.push(node.body);
  8042. } else if (node.type === "ConditionalExpression") {
  8043. stack.push(node.consequent);
  8044. stack.push(node.alternate);
  8045. }
  8046. }
  8047. if (disallowInvalid) {
  8048. arrows.forEach(node => this.finishArrowValidation(node));
  8049. return [arrows, []];
  8050. }
  8051. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  8052. }
  8053. finishArrowValidation(node) {
  8054. var _node$extra;
  8055. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false);
  8056. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  8057. super.checkParams(node, false, true);
  8058. this.scope.exit();
  8059. }
  8060. forwardNoArrowParamsConversionAt(node, parse) {
  8061. let result;
  8062. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  8063. this.state.noArrowParamsConversionAt.push(this.state.start);
  8064. result = parse();
  8065. this.state.noArrowParamsConversionAt.pop();
  8066. } else {
  8067. result = parse();
  8068. }
  8069. return result;
  8070. }
  8071. parseParenItem(node, startPos, startLoc) {
  8072. node = super.parseParenItem(node, startPos, startLoc);
  8073. if (this.eat(types.question)) {
  8074. node.optional = true;
  8075. this.resetEndLocation(node);
  8076. }
  8077. if (this.match(types.colon)) {
  8078. const typeCastNode = this.startNodeAt(startPos, startLoc);
  8079. typeCastNode.expression = node;
  8080. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  8081. return this.finishNode(typeCastNode, "TypeCastExpression");
  8082. }
  8083. return node;
  8084. }
  8085. assertModuleNodeAllowed(node) {
  8086. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  8087. return;
  8088. }
  8089. super.assertModuleNodeAllowed(node);
  8090. }
  8091. parseExport(node) {
  8092. const decl = super.parseExport(node);
  8093. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  8094. decl.exportKind = decl.exportKind || "value";
  8095. }
  8096. return decl;
  8097. }
  8098. parseExportDeclaration(node) {
  8099. if (this.isContextual("type")) {
  8100. node.exportKind = "type";
  8101. const declarationNode = this.startNode();
  8102. this.next();
  8103. if (this.match(types.braceL)) {
  8104. node.specifiers = this.parseExportSpecifiers();
  8105. this.parseExportFrom(node);
  8106. return null;
  8107. } else {
  8108. return this.flowParseTypeAlias(declarationNode);
  8109. }
  8110. } else if (this.isContextual("opaque")) {
  8111. node.exportKind = "type";
  8112. const declarationNode = this.startNode();
  8113. this.next();
  8114. return this.flowParseOpaqueType(declarationNode, false);
  8115. } else if (this.isContextual("interface")) {
  8116. node.exportKind = "type";
  8117. const declarationNode = this.startNode();
  8118. this.next();
  8119. return this.flowParseInterface(declarationNode);
  8120. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  8121. node.exportKind = "value";
  8122. const declarationNode = this.startNode();
  8123. this.next();
  8124. return this.flowParseEnumDeclaration(declarationNode);
  8125. } else {
  8126. return super.parseExportDeclaration(node);
  8127. }
  8128. }
  8129. eatExportStar(node) {
  8130. if (super.eatExportStar(...arguments)) return true;
  8131. if (this.isContextual("type") && this.lookahead().type === types.star) {
  8132. node.exportKind = "type";
  8133. this.next();
  8134. this.next();
  8135. return true;
  8136. }
  8137. return false;
  8138. }
  8139. maybeParseExportNamespaceSpecifier(node) {
  8140. const pos = this.state.start;
  8141. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  8142. if (hasNamespace && node.exportKind === "type") {
  8143. this.unexpected(pos);
  8144. }
  8145. return hasNamespace;
  8146. }
  8147. parseClassId(node, isStatement, optionalId) {
  8148. super.parseClassId(node, isStatement, optionalId);
  8149. if (this.isRelational("<")) {
  8150. node.typeParameters = this.flowParseTypeParameterDeclaration();
  8151. }
  8152. }
  8153. parseClassMember(classBody, member, state) {
  8154. const pos = this.state.start;
  8155. if (this.isContextual("declare")) {
  8156. if (this.parseClassMemberFromModifier(classBody, member)) {
  8157. return;
  8158. }
  8159. member.declare = true;
  8160. }
  8161. super.parseClassMember(classBody, member, state);
  8162. if (member.declare) {
  8163. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty") {
  8164. this.raise(pos, FlowErrors.DeclareClassElement);
  8165. } else if (member.value) {
  8166. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  8167. }
  8168. }
  8169. }
  8170. getTokenFromCode(code) {
  8171. const next = this.input.charCodeAt(this.state.pos + 1);
  8172. if (code === 123 && next === 124) {
  8173. return this.finishOp(types.braceBarL, 2);
  8174. } else if (this.state.inType && (code === 62 || code === 60)) {
  8175. return this.finishOp(types.relational, 1);
  8176. } else if (this.state.inType && code === 63) {
  8177. return this.finishOp(types.question, 1);
  8178. } else if (isIteratorStart(code, next)) {
  8179. this.state.isIterator = true;
  8180. return super.readWord();
  8181. } else {
  8182. return super.getTokenFromCode(code);
  8183. }
  8184. }
  8185. isAssignable(node, isBinding) {
  8186. switch (node.type) {
  8187. case "Identifier":
  8188. case "ObjectPattern":
  8189. case "ArrayPattern":
  8190. case "AssignmentPattern":
  8191. return true;
  8192. case "ObjectExpression":
  8193. {
  8194. const last = node.properties.length - 1;
  8195. return node.properties.every((prop, i) => {
  8196. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  8197. });
  8198. }
  8199. case "ObjectProperty":
  8200. return this.isAssignable(node.value);
  8201. case "SpreadElement":
  8202. return this.isAssignable(node.argument);
  8203. case "ArrayExpression":
  8204. return node.elements.every(element => this.isAssignable(element));
  8205. case "AssignmentExpression":
  8206. return node.operator === "=";
  8207. case "ParenthesizedExpression":
  8208. case "TypeCastExpression":
  8209. return this.isAssignable(node.expression);
  8210. case "MemberExpression":
  8211. case "OptionalMemberExpression":
  8212. return !isBinding;
  8213. default:
  8214. return false;
  8215. }
  8216. }
  8217. toAssignable(node, isLHS = false) {
  8218. if (node.type === "TypeCastExpression") {
  8219. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  8220. } else {
  8221. return super.toAssignable(node, isLHS);
  8222. }
  8223. }
  8224. toAssignableList(exprList, trailingCommaPos, isLHS) {
  8225. for (let i = 0; i < exprList.length; i++) {
  8226. const expr = exprList[i];
  8227. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  8228. exprList[i] = this.typeCastToParameter(expr);
  8229. }
  8230. }
  8231. return super.toAssignableList(exprList, trailingCommaPos, isLHS);
  8232. }
  8233. toReferencedList(exprList, isParenthesizedExpr) {
  8234. for (let i = 0; i < exprList.length; i++) {
  8235. var _expr$extra;
  8236. const expr = exprList[i];
  8237. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) == null ? void 0 : _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  8238. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  8239. }
  8240. }
  8241. return exprList;
  8242. }
  8243. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  8244. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  8245. if (canBePattern && !this.state.maybeInArrowParameters) {
  8246. this.toReferencedList(node.elements);
  8247. }
  8248. return node;
  8249. }
  8250. checkLVal(expr, ...args) {
  8251. if (expr.type !== "TypeCastExpression") {
  8252. return super.checkLVal(expr, ...args);
  8253. }
  8254. }
  8255. parseClassProperty(node) {
  8256. if (this.match(types.colon)) {
  8257. node.typeAnnotation = this.flowParseTypeAnnotation();
  8258. }
  8259. return super.parseClassProperty(node);
  8260. }
  8261. parseClassPrivateProperty(node) {
  8262. if (this.match(types.colon)) {
  8263. node.typeAnnotation = this.flowParseTypeAnnotation();
  8264. }
  8265. return super.parseClassPrivateProperty(node);
  8266. }
  8267. isClassMethod() {
  8268. return this.isRelational("<") || super.isClassMethod();
  8269. }
  8270. isClassProperty() {
  8271. return this.match(types.colon) || super.isClassProperty();
  8272. }
  8273. isNonstaticConstructor(method) {
  8274. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  8275. }
  8276. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  8277. if (method.variance) {
  8278. this.unexpected(method.variance.start);
  8279. }
  8280. delete method.variance;
  8281. if (this.isRelational("<")) {
  8282. method.typeParameters = this.flowParseTypeParameterDeclaration();
  8283. }
  8284. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  8285. }
  8286. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  8287. if (method.variance) {
  8288. this.unexpected(method.variance.start);
  8289. }
  8290. delete method.variance;
  8291. if (this.isRelational("<")) {
  8292. method.typeParameters = this.flowParseTypeParameterDeclaration();
  8293. }
  8294. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  8295. }
  8296. parseClassSuper(node) {
  8297. super.parseClassSuper(node);
  8298. if (node.superClass && this.isRelational("<")) {
  8299. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  8300. }
  8301. if (this.isContextual("implements")) {
  8302. this.next();
  8303. const implemented = node.implements = [];
  8304. do {
  8305. const node = this.startNode();
  8306. node.id = this.flowParseRestrictedIdentifier(true);
  8307. if (this.isRelational("<")) {
  8308. node.typeParameters = this.flowParseTypeParameterInstantiation();
  8309. } else {
  8310. node.typeParameters = null;
  8311. }
  8312. implemented.push(this.finishNode(node, "ClassImplements"));
  8313. } while (this.eat(types.comma));
  8314. }
  8315. }
  8316. parsePropertyName(node, isPrivateNameAllowed) {
  8317. const variance = this.flowParseVariance();
  8318. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  8319. node.variance = variance;
  8320. return key;
  8321. }
  8322. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  8323. if (prop.variance) {
  8324. this.unexpected(prop.variance.start);
  8325. }
  8326. delete prop.variance;
  8327. let typeParameters;
  8328. if (this.isRelational("<") && !isAccessor) {
  8329. typeParameters = this.flowParseTypeParameterDeclaration();
  8330. if (!this.match(types.parenL)) this.unexpected();
  8331. }
  8332. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  8333. if (typeParameters) {
  8334. (prop.value || prop).typeParameters = typeParameters;
  8335. }
  8336. }
  8337. parseAssignableListItemTypes(param) {
  8338. if (this.eat(types.question)) {
  8339. if (param.type !== "Identifier") {
  8340. this.raise(param.start, FlowErrors.OptionalBindingPattern);
  8341. }
  8342. param.optional = true;
  8343. }
  8344. if (this.match(types.colon)) {
  8345. param.typeAnnotation = this.flowParseTypeAnnotation();
  8346. }
  8347. this.resetEndLocation(param);
  8348. return param;
  8349. }
  8350. parseMaybeDefault(startPos, startLoc, left) {
  8351. const node = super.parseMaybeDefault(startPos, startLoc, left);
  8352. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  8353. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  8354. }
  8355. return node;
  8356. }
  8357. shouldParseDefaultImport(node) {
  8358. if (!hasTypeImportKind(node)) {
  8359. return super.shouldParseDefaultImport(node);
  8360. }
  8361. return isMaybeDefaultImport(this.state);
  8362. }
  8363. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  8364. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  8365. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  8366. node.specifiers.push(this.finishNode(specifier, type));
  8367. }
  8368. maybeParseDefaultImportSpecifier(node) {
  8369. node.importKind = "value";
  8370. let kind = null;
  8371. if (this.match(types._typeof)) {
  8372. kind = "typeof";
  8373. } else if (this.isContextual("type")) {
  8374. kind = "type";
  8375. }
  8376. if (kind) {
  8377. const lh = this.lookahead();
  8378. if (kind === "type" && lh.type === types.star) {
  8379. this.unexpected(lh.start);
  8380. }
  8381. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  8382. this.next();
  8383. node.importKind = kind;
  8384. }
  8385. }
  8386. return super.maybeParseDefaultImportSpecifier(node);
  8387. }
  8388. parseImportSpecifier(node) {
  8389. const specifier = this.startNode();
  8390. const firstIdentLoc = this.state.start;
  8391. const firstIdent = this.parseModuleExportName();
  8392. let specifierTypeKind = null;
  8393. if (firstIdent.type === "Identifier") {
  8394. if (firstIdent.name === "type") {
  8395. specifierTypeKind = "type";
  8396. } else if (firstIdent.name === "typeof") {
  8397. specifierTypeKind = "typeof";
  8398. }
  8399. }
  8400. let isBinding = false;
  8401. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  8402. const as_ident = this.parseIdentifier(true);
  8403. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  8404. specifier.imported = as_ident;
  8405. specifier.importKind = specifierTypeKind;
  8406. specifier.local = as_ident.__clone();
  8407. } else {
  8408. specifier.imported = firstIdent;
  8409. specifier.importKind = null;
  8410. specifier.local = this.parseIdentifier();
  8411. }
  8412. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  8413. specifier.imported = this.parseIdentifier(true);
  8414. specifier.importKind = specifierTypeKind;
  8415. if (this.eatContextual("as")) {
  8416. specifier.local = this.parseIdentifier();
  8417. } else {
  8418. isBinding = true;
  8419. specifier.local = specifier.imported.__clone();
  8420. }
  8421. } else {
  8422. if (firstIdent.type === "StringLiteral") {
  8423. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
  8424. }
  8425. isBinding = true;
  8426. specifier.imported = firstIdent;
  8427. specifier.importKind = null;
  8428. specifier.local = specifier.imported.__clone();
  8429. }
  8430. const nodeIsTypeImport = hasTypeImportKind(node);
  8431. const specifierIsTypeImport = hasTypeImportKind(specifier);
  8432. if (nodeIsTypeImport && specifierIsTypeImport) {
  8433. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  8434. }
  8435. if (nodeIsTypeImport || specifierIsTypeImport) {
  8436. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  8437. }
  8438. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  8439. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  8440. }
  8441. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  8442. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  8443. }
  8444. parseFunctionParams(node, allowModifiers) {
  8445. const kind = node.kind;
  8446. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  8447. node.typeParameters = this.flowParseTypeParameterDeclaration();
  8448. }
  8449. super.parseFunctionParams(node, allowModifiers);
  8450. }
  8451. parseVarId(decl, kind) {
  8452. super.parseVarId(decl, kind);
  8453. if (this.match(types.colon)) {
  8454. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  8455. this.resetEndLocation(decl.id);
  8456. }
  8457. }
  8458. parseAsyncArrowFromCallExpression(node, call) {
  8459. if (this.match(types.colon)) {
  8460. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  8461. this.state.noAnonFunctionType = true;
  8462. node.returnType = this.flowParseTypeAnnotation();
  8463. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  8464. }
  8465. return super.parseAsyncArrowFromCallExpression(node, call);
  8466. }
  8467. shouldParseAsyncArrow() {
  8468. return this.match(types.colon) || super.shouldParseAsyncArrow();
  8469. }
  8470. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8471. var _jsx;
  8472. let state = null;
  8473. let jsx;
  8474. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  8475. state = this.state.clone();
  8476. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  8477. if (!jsx.error) return jsx.node;
  8478. const {
  8479. context
  8480. } = this.state;
  8481. if (context[context.length - 1] === types$1.j_oTag) {
  8482. context.length -= 2;
  8483. } else if (context[context.length - 1] === types$1.j_expr) {
  8484. context.length -= 1;
  8485. }
  8486. }
  8487. if (((_jsx = jsx) == null ? void 0 : _jsx.error) || this.isRelational("<")) {
  8488. var _jsx2, _jsx3;
  8489. state = state || this.state.clone();
  8490. let typeParameters;
  8491. const arrow = this.tryParse(abort => {
  8492. var _arrowExpression$extr;
  8493. typeParameters = this.flowParseTypeParameterDeclaration();
  8494. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  8495. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  8496. this.resetStartLocationFromNode(result, typeParameters);
  8497. return result;
  8498. });
  8499. if (arrowExpression.type !== "ArrowFunctionExpression" && ((_arrowExpression$extr = arrowExpression.extra) == null ? void 0 : _arrowExpression$extr.parenthesized)) {
  8500. abort();
  8501. }
  8502. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  8503. expr.typeParameters = typeParameters;
  8504. this.resetStartLocationFromNode(expr, typeParameters);
  8505. return arrowExpression;
  8506. }, state);
  8507. let arrowExpression = null;
  8508. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  8509. if (!arrow.error && !arrow.aborted) {
  8510. if (arrow.node.async) {
  8511. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  8512. }
  8513. return arrow.node;
  8514. }
  8515. arrowExpression = arrow.node;
  8516. }
  8517. if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
  8518. this.state = jsx.failState;
  8519. return jsx.node;
  8520. }
  8521. if (arrowExpression) {
  8522. this.state = arrow.failState;
  8523. return arrowExpression;
  8524. }
  8525. if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
  8526. if (arrow.thrown) throw arrow.error;
  8527. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  8528. }
  8529. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  8530. }
  8531. parseArrow(node) {
  8532. if (this.match(types.colon)) {
  8533. const result = this.tryParse(() => {
  8534. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  8535. this.state.noAnonFunctionType = true;
  8536. const typeNode = this.startNode();
  8537. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  8538. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  8539. if (this.canInsertSemicolon()) this.unexpected();
  8540. if (!this.match(types.arrow)) this.unexpected();
  8541. return typeNode;
  8542. });
  8543. if (result.thrown) return null;
  8544. if (result.error) this.state = result.failState;
  8545. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  8546. }
  8547. return super.parseArrow(node);
  8548. }
  8549. shouldParseArrow() {
  8550. return this.match(types.colon) || super.shouldParseArrow();
  8551. }
  8552. setArrowFunctionParameters(node, params) {
  8553. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  8554. node.params = params;
  8555. } else {
  8556. super.setArrowFunctionParameters(node, params);
  8557. }
  8558. }
  8559. checkParams(node, allowDuplicates, isArrowFunction) {
  8560. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  8561. return;
  8562. }
  8563. return super.checkParams(...arguments);
  8564. }
  8565. parseParenAndDistinguishExpression(canBeArrow) {
  8566. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  8567. }
  8568. parseSubscripts(base, startPos, startLoc, noCalls) {
  8569. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  8570. this.next();
  8571. const node = this.startNodeAt(startPos, startLoc);
  8572. node.callee = base;
  8573. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8574. base = this.finishNode(node, "CallExpression");
  8575. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  8576. const state = this.state.clone();
  8577. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  8578. if (!arrow.error && !arrow.aborted) return arrow.node;
  8579. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  8580. if (result.node && !result.error) return result.node;
  8581. if (arrow.node) {
  8582. this.state = arrow.failState;
  8583. return arrow.node;
  8584. }
  8585. if (result.node) {
  8586. this.state = result.failState;
  8587. return result.node;
  8588. }
  8589. throw arrow.error || result.error;
  8590. }
  8591. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  8592. }
  8593. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  8594. if (this.match(types.questionDot) && this.isLookaheadToken_lt()) {
  8595. subscriptState.optionalChainMember = true;
  8596. if (noCalls) {
  8597. subscriptState.stop = true;
  8598. return base;
  8599. }
  8600. this.next();
  8601. const node = this.startNodeAt(startPos, startLoc);
  8602. node.callee = base;
  8603. node.typeArguments = this.flowParseTypeParameterInstantiation();
  8604. this.expect(types.parenL);
  8605. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8606. node.optional = true;
  8607. return this.finishCallExpression(node, true);
  8608. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  8609. const node = this.startNodeAt(startPos, startLoc);
  8610. node.callee = base;
  8611. const result = this.tryParse(() => {
  8612. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  8613. this.expect(types.parenL);
  8614. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8615. if (subscriptState.optionalChainMember) node.optional = false;
  8616. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  8617. });
  8618. if (result.node) {
  8619. if (result.error) this.state = result.failState;
  8620. return result.node;
  8621. }
  8622. }
  8623. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  8624. }
  8625. parseNewArguments(node) {
  8626. let targs = null;
  8627. if (this.shouldParseTypes() && this.isRelational("<")) {
  8628. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  8629. }
  8630. node.typeArguments = targs;
  8631. super.parseNewArguments(node);
  8632. }
  8633. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  8634. const node = this.startNodeAt(startPos, startLoc);
  8635. this.parseFunctionParams(node);
  8636. if (!this.parseArrow(node)) return;
  8637. return this.parseArrowExpression(node, undefined, true);
  8638. }
  8639. readToken_mult_modulo(code) {
  8640. const next = this.input.charCodeAt(this.state.pos + 1);
  8641. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  8642. this.state.hasFlowComment = false;
  8643. this.state.pos += 2;
  8644. this.nextToken();
  8645. return;
  8646. }
  8647. super.readToken_mult_modulo(code);
  8648. }
  8649. readToken_pipe_amp(code) {
  8650. const next = this.input.charCodeAt(this.state.pos + 1);
  8651. if (code === 124 && next === 125) {
  8652. this.finishOp(types.braceBarR, 2);
  8653. return;
  8654. }
  8655. super.readToken_pipe_amp(code);
  8656. }
  8657. parseTopLevel(file, program) {
  8658. const fileNode = super.parseTopLevel(file, program);
  8659. if (this.state.hasFlowComment) {
  8660. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  8661. }
  8662. return fileNode;
  8663. }
  8664. skipBlockComment() {
  8665. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  8666. if (this.state.hasFlowComment) {
  8667. this.unexpected(null, FlowErrors.NestedFlowComment);
  8668. }
  8669. this.hasFlowCommentCompletion();
  8670. this.state.pos += this.skipFlowComment();
  8671. this.state.hasFlowComment = true;
  8672. return;
  8673. }
  8674. if (this.state.hasFlowComment) {
  8675. const end = this.input.indexOf("*-/", this.state.pos += 2);
  8676. if (end === -1) {
  8677. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  8678. }
  8679. this.state.pos = end + 3;
  8680. return;
  8681. }
  8682. super.skipBlockComment();
  8683. }
  8684. skipFlowComment() {
  8685. const {
  8686. pos
  8687. } = this.state;
  8688. let shiftToFirstNonWhiteSpace = 2;
  8689. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  8690. shiftToFirstNonWhiteSpace++;
  8691. }
  8692. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  8693. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  8694. if (ch2 === 58 && ch3 === 58) {
  8695. return shiftToFirstNonWhiteSpace + 2;
  8696. }
  8697. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  8698. return shiftToFirstNonWhiteSpace + 12;
  8699. }
  8700. if (ch2 === 58 && ch3 !== 58) {
  8701. return shiftToFirstNonWhiteSpace;
  8702. }
  8703. return false;
  8704. }
  8705. hasFlowCommentCompletion() {
  8706. const end = this.input.indexOf("*/", this.state.pos);
  8707. if (end === -1) {
  8708. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  8709. }
  8710. }
  8711. flowEnumErrorBooleanMemberNotInitialized(pos, {
  8712. enumName,
  8713. memberName
  8714. }) {
  8715. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  8716. }
  8717. flowEnumErrorInvalidMemberName(pos, {
  8718. enumName,
  8719. memberName
  8720. }) {
  8721. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  8722. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  8723. }
  8724. flowEnumErrorDuplicateMemberName(pos, {
  8725. enumName,
  8726. memberName
  8727. }) {
  8728. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  8729. }
  8730. flowEnumErrorInconsistentMemberValues(pos, {
  8731. enumName
  8732. }) {
  8733. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  8734. }
  8735. flowEnumErrorInvalidExplicitType(pos, {
  8736. enumName,
  8737. suppliedType
  8738. }) {
  8739. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  8740. }
  8741. flowEnumErrorInvalidMemberInitializer(pos, {
  8742. enumName,
  8743. explicitType,
  8744. memberName
  8745. }) {
  8746. let message = null;
  8747. switch (explicitType) {
  8748. case "boolean":
  8749. case "number":
  8750. case "string":
  8751. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  8752. break;
  8753. case "symbol":
  8754. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  8755. break;
  8756. default:
  8757. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  8758. }
  8759. return this.raise(pos, message, enumName, memberName, explicitType);
  8760. }
  8761. flowEnumErrorNumberMemberNotInitialized(pos, {
  8762. enumName,
  8763. memberName
  8764. }) {
  8765. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  8766. }
  8767. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  8768. enumName
  8769. }) {
  8770. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  8771. }
  8772. flowEnumMemberInit() {
  8773. const startPos = this.state.start;
  8774. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  8775. switch (this.state.type) {
  8776. case types.num:
  8777. {
  8778. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  8779. if (endOfInit()) {
  8780. return {
  8781. type: "number",
  8782. pos: literal.start,
  8783. value: literal
  8784. };
  8785. }
  8786. return {
  8787. type: "invalid",
  8788. pos: startPos
  8789. };
  8790. }
  8791. case types.string:
  8792. {
  8793. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  8794. if (endOfInit()) {
  8795. return {
  8796. type: "string",
  8797. pos: literal.start,
  8798. value: literal
  8799. };
  8800. }
  8801. return {
  8802. type: "invalid",
  8803. pos: startPos
  8804. };
  8805. }
  8806. case types._true:
  8807. case types._false:
  8808. {
  8809. const literal = this.parseBooleanLiteral();
  8810. if (endOfInit()) {
  8811. return {
  8812. type: "boolean",
  8813. pos: literal.start,
  8814. value: literal
  8815. };
  8816. }
  8817. return {
  8818. type: "invalid",
  8819. pos: startPos
  8820. };
  8821. }
  8822. default:
  8823. return {
  8824. type: "invalid",
  8825. pos: startPos
  8826. };
  8827. }
  8828. }
  8829. flowEnumMemberRaw() {
  8830. const pos = this.state.start;
  8831. const id = this.parseIdentifier(true);
  8832. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  8833. type: "none",
  8834. pos
  8835. };
  8836. return {
  8837. id,
  8838. init
  8839. };
  8840. }
  8841. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  8842. const {
  8843. explicitType
  8844. } = context;
  8845. if (explicitType === null) {
  8846. return;
  8847. }
  8848. if (explicitType !== expectedType) {
  8849. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  8850. }
  8851. }
  8852. flowEnumMembers({
  8853. enumName,
  8854. explicitType
  8855. }) {
  8856. const seenNames = new Set();
  8857. const members = {
  8858. booleanMembers: [],
  8859. numberMembers: [],
  8860. stringMembers: [],
  8861. defaultedMembers: []
  8862. };
  8863. while (!this.match(types.braceR)) {
  8864. const memberNode = this.startNode();
  8865. const {
  8866. id,
  8867. init
  8868. } = this.flowEnumMemberRaw();
  8869. const memberName = id.name;
  8870. if (memberName === "") {
  8871. continue;
  8872. }
  8873. if (/^[a-z]/.test(memberName)) {
  8874. this.flowEnumErrorInvalidMemberName(id.start, {
  8875. enumName,
  8876. memberName
  8877. });
  8878. }
  8879. if (seenNames.has(memberName)) {
  8880. this.flowEnumErrorDuplicateMemberName(id.start, {
  8881. enumName,
  8882. memberName
  8883. });
  8884. }
  8885. seenNames.add(memberName);
  8886. const context = {
  8887. enumName,
  8888. explicitType,
  8889. memberName
  8890. };
  8891. memberNode.id = id;
  8892. switch (init.type) {
  8893. case "boolean":
  8894. {
  8895. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  8896. memberNode.init = init.value;
  8897. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  8898. break;
  8899. }
  8900. case "number":
  8901. {
  8902. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  8903. memberNode.init = init.value;
  8904. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  8905. break;
  8906. }
  8907. case "string":
  8908. {
  8909. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  8910. memberNode.init = init.value;
  8911. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  8912. break;
  8913. }
  8914. case "invalid":
  8915. {
  8916. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  8917. }
  8918. case "none":
  8919. {
  8920. switch (explicitType) {
  8921. case "boolean":
  8922. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  8923. break;
  8924. case "number":
  8925. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  8926. break;
  8927. default:
  8928. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  8929. }
  8930. }
  8931. }
  8932. if (!this.match(types.braceR)) {
  8933. this.expect(types.comma);
  8934. }
  8935. }
  8936. return members;
  8937. }
  8938. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  8939. enumName
  8940. }) {
  8941. if (initializedMembers.length === 0) {
  8942. return defaultedMembers;
  8943. } else if (defaultedMembers.length === 0) {
  8944. return initializedMembers;
  8945. } else if (defaultedMembers.length > initializedMembers.length) {
  8946. for (let _i = 0; _i < initializedMembers.length; _i++) {
  8947. const member = initializedMembers[_i];
  8948. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  8949. enumName
  8950. });
  8951. }
  8952. return defaultedMembers;
  8953. } else {
  8954. for (let _i2 = 0; _i2 < defaultedMembers.length; _i2++) {
  8955. const member = defaultedMembers[_i2];
  8956. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  8957. enumName
  8958. });
  8959. }
  8960. return initializedMembers;
  8961. }
  8962. }
  8963. flowEnumParseExplicitType({
  8964. enumName
  8965. }) {
  8966. if (this.eatContextual("of")) {
  8967. if (!this.match(types.name)) {
  8968. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  8969. enumName,
  8970. suppliedType: null
  8971. });
  8972. }
  8973. const {
  8974. value
  8975. } = this.state;
  8976. this.next();
  8977. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  8978. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  8979. enumName,
  8980. suppliedType: value
  8981. });
  8982. }
  8983. return value;
  8984. }
  8985. return null;
  8986. }
  8987. flowEnumBody(node, {
  8988. enumName,
  8989. nameLoc
  8990. }) {
  8991. const explicitType = this.flowEnumParseExplicitType({
  8992. enumName
  8993. });
  8994. this.expect(types.braceL);
  8995. const members = this.flowEnumMembers({
  8996. enumName,
  8997. explicitType
  8998. });
  8999. switch (explicitType) {
  9000. case "boolean":
  9001. node.explicitType = true;
  9002. node.members = members.booleanMembers;
  9003. this.expect(types.braceR);
  9004. return this.finishNode(node, "EnumBooleanBody");
  9005. case "number":
  9006. node.explicitType = true;
  9007. node.members = members.numberMembers;
  9008. this.expect(types.braceR);
  9009. return this.finishNode(node, "EnumNumberBody");
  9010. case "string":
  9011. node.explicitType = true;
  9012. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  9013. enumName
  9014. });
  9015. this.expect(types.braceR);
  9016. return this.finishNode(node, "EnumStringBody");
  9017. case "symbol":
  9018. node.members = members.defaultedMembers;
  9019. this.expect(types.braceR);
  9020. return this.finishNode(node, "EnumSymbolBody");
  9021. default:
  9022. {
  9023. const empty = () => {
  9024. node.members = [];
  9025. this.expect(types.braceR);
  9026. return this.finishNode(node, "EnumStringBody");
  9027. };
  9028. node.explicitType = false;
  9029. const boolsLen = members.booleanMembers.length;
  9030. const numsLen = members.numberMembers.length;
  9031. const strsLen = members.stringMembers.length;
  9032. const defaultedLen = members.defaultedMembers.length;
  9033. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  9034. return empty();
  9035. } else if (!boolsLen && !numsLen) {
  9036. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  9037. enumName
  9038. });
  9039. this.expect(types.braceR);
  9040. return this.finishNode(node, "EnumStringBody");
  9041. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  9042. for (let _i3 = 0, _members$defaultedMem = members.defaultedMembers; _i3 < _members$defaultedMem.length; _i3++) {
  9043. const member = _members$defaultedMem[_i3];
  9044. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  9045. enumName,
  9046. memberName: member.id.name
  9047. });
  9048. }
  9049. node.members = members.booleanMembers;
  9050. this.expect(types.braceR);
  9051. return this.finishNode(node, "EnumBooleanBody");
  9052. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  9053. for (let _i4 = 0, _members$defaultedMem2 = members.defaultedMembers; _i4 < _members$defaultedMem2.length; _i4++) {
  9054. const member = _members$defaultedMem2[_i4];
  9055. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  9056. enumName,
  9057. memberName: member.id.name
  9058. });
  9059. }
  9060. node.members = members.numberMembers;
  9061. this.expect(types.braceR);
  9062. return this.finishNode(node, "EnumNumberBody");
  9063. } else {
  9064. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  9065. enumName
  9066. });
  9067. return empty();
  9068. }
  9069. }
  9070. }
  9071. }
  9072. flowParseEnumDeclaration(node) {
  9073. const id = this.parseIdentifier();
  9074. node.id = id;
  9075. node.body = this.flowEnumBody(this.startNode(), {
  9076. enumName: id.name,
  9077. nameLoc: id.start
  9078. });
  9079. return this.finishNode(node, "EnumDeclaration");
  9080. }
  9081. updateContext(prevType) {
  9082. if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
  9083. this.state.exprAllowed = false;
  9084. } else {
  9085. super.updateContext(prevType);
  9086. }
  9087. }
  9088. isLookaheadToken_lt() {
  9089. const next = this.nextTokenStart();
  9090. if (this.input.charCodeAt(next) === 60) {
  9091. const afterNext = this.input.charCodeAt(next + 1);
  9092. return afterNext !== 60 && afterNext !== 61;
  9093. }
  9094. return false;
  9095. }
  9096. maybeUnwrapTypeCastExpression(node) {
  9097. return node.type === "TypeCastExpression" ? node.expression : node;
  9098. }
  9099. }, _temp;
  9100. });
  9101. const entities = {
  9102. quot: "\u0022",
  9103. amp: "&",
  9104. apos: "\u0027",
  9105. lt: "<",
  9106. gt: ">",
  9107. nbsp: "\u00A0",
  9108. iexcl: "\u00A1",
  9109. cent: "\u00A2",
  9110. pound: "\u00A3",
  9111. curren: "\u00A4",
  9112. yen: "\u00A5",
  9113. brvbar: "\u00A6",
  9114. sect: "\u00A7",
  9115. uml: "\u00A8",
  9116. copy: "\u00A9",
  9117. ordf: "\u00AA",
  9118. laquo: "\u00AB",
  9119. not: "\u00AC",
  9120. shy: "\u00AD",
  9121. reg: "\u00AE",
  9122. macr: "\u00AF",
  9123. deg: "\u00B0",
  9124. plusmn: "\u00B1",
  9125. sup2: "\u00B2",
  9126. sup3: "\u00B3",
  9127. acute: "\u00B4",
  9128. micro: "\u00B5",
  9129. para: "\u00B6",
  9130. middot: "\u00B7",
  9131. cedil: "\u00B8",
  9132. sup1: "\u00B9",
  9133. ordm: "\u00BA",
  9134. raquo: "\u00BB",
  9135. frac14: "\u00BC",
  9136. frac12: "\u00BD",
  9137. frac34: "\u00BE",
  9138. iquest: "\u00BF",
  9139. Agrave: "\u00C0",
  9140. Aacute: "\u00C1",
  9141. Acirc: "\u00C2",
  9142. Atilde: "\u00C3",
  9143. Auml: "\u00C4",
  9144. Aring: "\u00C5",
  9145. AElig: "\u00C6",
  9146. Ccedil: "\u00C7",
  9147. Egrave: "\u00C8",
  9148. Eacute: "\u00C9",
  9149. Ecirc: "\u00CA",
  9150. Euml: "\u00CB",
  9151. Igrave: "\u00CC",
  9152. Iacute: "\u00CD",
  9153. Icirc: "\u00CE",
  9154. Iuml: "\u00CF",
  9155. ETH: "\u00D0",
  9156. Ntilde: "\u00D1",
  9157. Ograve: "\u00D2",
  9158. Oacute: "\u00D3",
  9159. Ocirc: "\u00D4",
  9160. Otilde: "\u00D5",
  9161. Ouml: "\u00D6",
  9162. times: "\u00D7",
  9163. Oslash: "\u00D8",
  9164. Ugrave: "\u00D9",
  9165. Uacute: "\u00DA",
  9166. Ucirc: "\u00DB",
  9167. Uuml: "\u00DC",
  9168. Yacute: "\u00DD",
  9169. THORN: "\u00DE",
  9170. szlig: "\u00DF",
  9171. agrave: "\u00E0",
  9172. aacute: "\u00E1",
  9173. acirc: "\u00E2",
  9174. atilde: "\u00E3",
  9175. auml: "\u00E4",
  9176. aring: "\u00E5",
  9177. aelig: "\u00E6",
  9178. ccedil: "\u00E7",
  9179. egrave: "\u00E8",
  9180. eacute: "\u00E9",
  9181. ecirc: "\u00EA",
  9182. euml: "\u00EB",
  9183. igrave: "\u00EC",
  9184. iacute: "\u00ED",
  9185. icirc: "\u00EE",
  9186. iuml: "\u00EF",
  9187. eth: "\u00F0",
  9188. ntilde: "\u00F1",
  9189. ograve: "\u00F2",
  9190. oacute: "\u00F3",
  9191. ocirc: "\u00F4",
  9192. otilde: "\u00F5",
  9193. ouml: "\u00F6",
  9194. divide: "\u00F7",
  9195. oslash: "\u00F8",
  9196. ugrave: "\u00F9",
  9197. uacute: "\u00FA",
  9198. ucirc: "\u00FB",
  9199. uuml: "\u00FC",
  9200. yacute: "\u00FD",
  9201. thorn: "\u00FE",
  9202. yuml: "\u00FF",
  9203. OElig: "\u0152",
  9204. oelig: "\u0153",
  9205. Scaron: "\u0160",
  9206. scaron: "\u0161",
  9207. Yuml: "\u0178",
  9208. fnof: "\u0192",
  9209. circ: "\u02C6",
  9210. tilde: "\u02DC",
  9211. Alpha: "\u0391",
  9212. Beta: "\u0392",
  9213. Gamma: "\u0393",
  9214. Delta: "\u0394",
  9215. Epsilon: "\u0395",
  9216. Zeta: "\u0396",
  9217. Eta: "\u0397",
  9218. Theta: "\u0398",
  9219. Iota: "\u0399",
  9220. Kappa: "\u039A",
  9221. Lambda: "\u039B",
  9222. Mu: "\u039C",
  9223. Nu: "\u039D",
  9224. Xi: "\u039E",
  9225. Omicron: "\u039F",
  9226. Pi: "\u03A0",
  9227. Rho: "\u03A1",
  9228. Sigma: "\u03A3",
  9229. Tau: "\u03A4",
  9230. Upsilon: "\u03A5",
  9231. Phi: "\u03A6",
  9232. Chi: "\u03A7",
  9233. Psi: "\u03A8",
  9234. Omega: "\u03A9",
  9235. alpha: "\u03B1",
  9236. beta: "\u03B2",
  9237. gamma: "\u03B3",
  9238. delta: "\u03B4",
  9239. epsilon: "\u03B5",
  9240. zeta: "\u03B6",
  9241. eta: "\u03B7",
  9242. theta: "\u03B8",
  9243. iota: "\u03B9",
  9244. kappa: "\u03BA",
  9245. lambda: "\u03BB",
  9246. mu: "\u03BC",
  9247. nu: "\u03BD",
  9248. xi: "\u03BE",
  9249. omicron: "\u03BF",
  9250. pi: "\u03C0",
  9251. rho: "\u03C1",
  9252. sigmaf: "\u03C2",
  9253. sigma: "\u03C3",
  9254. tau: "\u03C4",
  9255. upsilon: "\u03C5",
  9256. phi: "\u03C6",
  9257. chi: "\u03C7",
  9258. psi: "\u03C8",
  9259. omega: "\u03C9",
  9260. thetasym: "\u03D1",
  9261. upsih: "\u03D2",
  9262. piv: "\u03D6",
  9263. ensp: "\u2002",
  9264. emsp: "\u2003",
  9265. thinsp: "\u2009",
  9266. zwnj: "\u200C",
  9267. zwj: "\u200D",
  9268. lrm: "\u200E",
  9269. rlm: "\u200F",
  9270. ndash: "\u2013",
  9271. mdash: "\u2014",
  9272. lsquo: "\u2018",
  9273. rsquo: "\u2019",
  9274. sbquo: "\u201A",
  9275. ldquo: "\u201C",
  9276. rdquo: "\u201D",
  9277. bdquo: "\u201E",
  9278. dagger: "\u2020",
  9279. Dagger: "\u2021",
  9280. bull: "\u2022",
  9281. hellip: "\u2026",
  9282. permil: "\u2030",
  9283. prime: "\u2032",
  9284. Prime: "\u2033",
  9285. lsaquo: "\u2039",
  9286. rsaquo: "\u203A",
  9287. oline: "\u203E",
  9288. frasl: "\u2044",
  9289. euro: "\u20AC",
  9290. image: "\u2111",
  9291. weierp: "\u2118",
  9292. real: "\u211C",
  9293. trade: "\u2122",
  9294. alefsym: "\u2135",
  9295. larr: "\u2190",
  9296. uarr: "\u2191",
  9297. rarr: "\u2192",
  9298. darr: "\u2193",
  9299. harr: "\u2194",
  9300. crarr: "\u21B5",
  9301. lArr: "\u21D0",
  9302. uArr: "\u21D1",
  9303. rArr: "\u21D2",
  9304. dArr: "\u21D3",
  9305. hArr: "\u21D4",
  9306. forall: "\u2200",
  9307. part: "\u2202",
  9308. exist: "\u2203",
  9309. empty: "\u2205",
  9310. nabla: "\u2207",
  9311. isin: "\u2208",
  9312. notin: "\u2209",
  9313. ni: "\u220B",
  9314. prod: "\u220F",
  9315. sum: "\u2211",
  9316. minus: "\u2212",
  9317. lowast: "\u2217",
  9318. radic: "\u221A",
  9319. prop: "\u221D",
  9320. infin: "\u221E",
  9321. ang: "\u2220",
  9322. and: "\u2227",
  9323. or: "\u2228",
  9324. cap: "\u2229",
  9325. cup: "\u222A",
  9326. int: "\u222B",
  9327. there4: "\u2234",
  9328. sim: "\u223C",
  9329. cong: "\u2245",
  9330. asymp: "\u2248",
  9331. ne: "\u2260",
  9332. equiv: "\u2261",
  9333. le: "\u2264",
  9334. ge: "\u2265",
  9335. sub: "\u2282",
  9336. sup: "\u2283",
  9337. nsub: "\u2284",
  9338. sube: "\u2286",
  9339. supe: "\u2287",
  9340. oplus: "\u2295",
  9341. otimes: "\u2297",
  9342. perp: "\u22A5",
  9343. sdot: "\u22C5",
  9344. lceil: "\u2308",
  9345. rceil: "\u2309",
  9346. lfloor: "\u230A",
  9347. rfloor: "\u230B",
  9348. lang: "\u2329",
  9349. rang: "\u232A",
  9350. loz: "\u25CA",
  9351. spades: "\u2660",
  9352. clubs: "\u2663",
  9353. hearts: "\u2665",
  9354. diams: "\u2666"
  9355. };
  9356. const HEX_NUMBER = /^[\da-fA-F]+$/;
  9357. const DECIMAL_NUMBER = /^\d+$/;
  9358. const JsxErrors = Object.freeze({
  9359. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
  9360. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
  9361. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
  9362. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
  9363. UnterminatedJsxContent: "Unterminated JSX contents",
  9364. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  9365. });
  9366. types$1.j_oTag = new TokContext("<tag", false);
  9367. types$1.j_cTag = new TokContext("</tag", false);
  9368. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  9369. types.jsxName = new TokenType("jsxName");
  9370. types.jsxText = new TokenType("jsxText", {
  9371. beforeExpr: true
  9372. });
  9373. types.jsxTagStart = new TokenType("jsxTagStart", {
  9374. startsExpr: true
  9375. });
  9376. types.jsxTagEnd = new TokenType("jsxTagEnd");
  9377. types.jsxTagStart.updateContext = function () {
  9378. this.state.context.push(types$1.j_expr);
  9379. this.state.context.push(types$1.j_oTag);
  9380. this.state.exprAllowed = false;
  9381. };
  9382. types.jsxTagEnd.updateContext = function (prevType) {
  9383. const out = this.state.context.pop();
  9384. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  9385. this.state.context.pop();
  9386. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  9387. } else {
  9388. this.state.exprAllowed = true;
  9389. }
  9390. };
  9391. function isFragment(object) {
  9392. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  9393. }
  9394. function getQualifiedJSXName(object) {
  9395. if (object.type === "JSXIdentifier") {
  9396. return object.name;
  9397. }
  9398. if (object.type === "JSXNamespacedName") {
  9399. return object.namespace.name + ":" + object.name.name;
  9400. }
  9401. if (object.type === "JSXMemberExpression") {
  9402. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  9403. }
  9404. throw new Error("Node had unexpected type: " + object.type);
  9405. }
  9406. var jsx = (superClass => class extends superClass {
  9407. jsxReadToken() {
  9408. let out = "";
  9409. let chunkStart = this.state.pos;
  9410. for (;;) {
  9411. if (this.state.pos >= this.length) {
  9412. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  9413. }
  9414. const ch = this.input.charCodeAt(this.state.pos);
  9415. switch (ch) {
  9416. case 60:
  9417. case 123:
  9418. if (this.state.pos === this.state.start) {
  9419. if (ch === 60 && this.state.exprAllowed) {
  9420. ++this.state.pos;
  9421. return this.finishToken(types.jsxTagStart);
  9422. }
  9423. return super.getTokenFromCode(ch);
  9424. }
  9425. out += this.input.slice(chunkStart, this.state.pos);
  9426. return this.finishToken(types.jsxText, out);
  9427. case 38:
  9428. out += this.input.slice(chunkStart, this.state.pos);
  9429. out += this.jsxReadEntity();
  9430. chunkStart = this.state.pos;
  9431. break;
  9432. default:
  9433. if (isNewLine(ch)) {
  9434. out += this.input.slice(chunkStart, this.state.pos);
  9435. out += this.jsxReadNewLine(true);
  9436. chunkStart = this.state.pos;
  9437. } else {
  9438. ++this.state.pos;
  9439. }
  9440. }
  9441. }
  9442. }
  9443. jsxReadNewLine(normalizeCRLF) {
  9444. const ch = this.input.charCodeAt(this.state.pos);
  9445. let out;
  9446. ++this.state.pos;
  9447. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  9448. ++this.state.pos;
  9449. out = normalizeCRLF ? "\n" : "\r\n";
  9450. } else {
  9451. out = String.fromCharCode(ch);
  9452. }
  9453. ++this.state.curLine;
  9454. this.state.lineStart = this.state.pos;
  9455. return out;
  9456. }
  9457. jsxReadString(quote) {
  9458. let out = "";
  9459. let chunkStart = ++this.state.pos;
  9460. for (;;) {
  9461. if (this.state.pos >= this.length) {
  9462. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  9463. }
  9464. const ch = this.input.charCodeAt(this.state.pos);
  9465. if (ch === quote) break;
  9466. if (ch === 38) {
  9467. out += this.input.slice(chunkStart, this.state.pos);
  9468. out += this.jsxReadEntity();
  9469. chunkStart = this.state.pos;
  9470. } else if (isNewLine(ch)) {
  9471. out += this.input.slice(chunkStart, this.state.pos);
  9472. out += this.jsxReadNewLine(false);
  9473. chunkStart = this.state.pos;
  9474. } else {
  9475. ++this.state.pos;
  9476. }
  9477. }
  9478. out += this.input.slice(chunkStart, this.state.pos++);
  9479. return this.finishToken(types.string, out);
  9480. }
  9481. jsxReadEntity() {
  9482. let str = "";
  9483. let count = 0;
  9484. let entity;
  9485. let ch = this.input[this.state.pos];
  9486. const startPos = ++this.state.pos;
  9487. while (this.state.pos < this.length && count++ < 10) {
  9488. ch = this.input[this.state.pos++];
  9489. if (ch === ";") {
  9490. if (str[0] === "#") {
  9491. if (str[1] === "x") {
  9492. str = str.substr(2);
  9493. if (HEX_NUMBER.test(str)) {
  9494. entity = String.fromCodePoint(parseInt(str, 16));
  9495. }
  9496. } else {
  9497. str = str.substr(1);
  9498. if (DECIMAL_NUMBER.test(str)) {
  9499. entity = String.fromCodePoint(parseInt(str, 10));
  9500. }
  9501. }
  9502. } else {
  9503. entity = entities[str];
  9504. }
  9505. break;
  9506. }
  9507. str += ch;
  9508. }
  9509. if (!entity) {
  9510. this.state.pos = startPos;
  9511. return "&";
  9512. }
  9513. return entity;
  9514. }
  9515. jsxReadWord() {
  9516. let ch;
  9517. const start = this.state.pos;
  9518. do {
  9519. ch = this.input.charCodeAt(++this.state.pos);
  9520. } while (isIdentifierChar(ch) || ch === 45);
  9521. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  9522. }
  9523. jsxParseIdentifier() {
  9524. const node = this.startNode();
  9525. if (this.match(types.jsxName)) {
  9526. node.name = this.state.value;
  9527. } else if (this.state.type.keyword) {
  9528. node.name = this.state.type.keyword;
  9529. } else {
  9530. this.unexpected();
  9531. }
  9532. this.next();
  9533. return this.finishNode(node, "JSXIdentifier");
  9534. }
  9535. jsxParseNamespacedName() {
  9536. const startPos = this.state.start;
  9537. const startLoc = this.state.startLoc;
  9538. const name = this.jsxParseIdentifier();
  9539. if (!this.eat(types.colon)) return name;
  9540. const node = this.startNodeAt(startPos, startLoc);
  9541. node.namespace = name;
  9542. node.name = this.jsxParseIdentifier();
  9543. return this.finishNode(node, "JSXNamespacedName");
  9544. }
  9545. jsxParseElementName() {
  9546. const startPos = this.state.start;
  9547. const startLoc = this.state.startLoc;
  9548. let node = this.jsxParseNamespacedName();
  9549. if (node.type === "JSXNamespacedName") {
  9550. return node;
  9551. }
  9552. while (this.eat(types.dot)) {
  9553. const newNode = this.startNodeAt(startPos, startLoc);
  9554. newNode.object = node;
  9555. newNode.property = this.jsxParseIdentifier();
  9556. node = this.finishNode(newNode, "JSXMemberExpression");
  9557. }
  9558. return node;
  9559. }
  9560. jsxParseAttributeValue() {
  9561. let node;
  9562. switch (this.state.type) {
  9563. case types.braceL:
  9564. node = this.startNode();
  9565. this.next();
  9566. node = this.jsxParseExpressionContainer(node);
  9567. if (node.expression.type === "JSXEmptyExpression") {
  9568. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  9569. }
  9570. return node;
  9571. case types.jsxTagStart:
  9572. case types.string:
  9573. return this.parseExprAtom();
  9574. default:
  9575. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  9576. }
  9577. }
  9578. jsxParseEmptyExpression() {
  9579. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  9580. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  9581. }
  9582. jsxParseSpreadChild(node) {
  9583. this.next();
  9584. node.expression = this.parseExpression();
  9585. this.expect(types.braceR);
  9586. return this.finishNode(node, "JSXSpreadChild");
  9587. }
  9588. jsxParseExpressionContainer(node) {
  9589. if (this.match(types.braceR)) {
  9590. node.expression = this.jsxParseEmptyExpression();
  9591. } else {
  9592. node.expression = this.parseExpression();
  9593. }
  9594. this.expect(types.braceR);
  9595. return this.finishNode(node, "JSXExpressionContainer");
  9596. }
  9597. jsxParseAttribute() {
  9598. const node = this.startNode();
  9599. if (this.eat(types.braceL)) {
  9600. this.expect(types.ellipsis);
  9601. node.argument = this.parseMaybeAssignAllowIn();
  9602. this.expect(types.braceR);
  9603. return this.finishNode(node, "JSXSpreadAttribute");
  9604. }
  9605. node.name = this.jsxParseNamespacedName();
  9606. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  9607. return this.finishNode(node, "JSXAttribute");
  9608. }
  9609. jsxParseOpeningElementAt(startPos, startLoc) {
  9610. const node = this.startNodeAt(startPos, startLoc);
  9611. if (this.match(types.jsxTagEnd)) {
  9612. this.expect(types.jsxTagEnd);
  9613. return this.finishNode(node, "JSXOpeningFragment");
  9614. }
  9615. node.name = this.jsxParseElementName();
  9616. return this.jsxParseOpeningElementAfterName(node);
  9617. }
  9618. jsxParseOpeningElementAfterName(node) {
  9619. const attributes = [];
  9620. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  9621. attributes.push(this.jsxParseAttribute());
  9622. }
  9623. node.attributes = attributes;
  9624. node.selfClosing = this.eat(types.slash);
  9625. this.expect(types.jsxTagEnd);
  9626. return this.finishNode(node, "JSXOpeningElement");
  9627. }
  9628. jsxParseClosingElementAt(startPos, startLoc) {
  9629. const node = this.startNodeAt(startPos, startLoc);
  9630. if (this.match(types.jsxTagEnd)) {
  9631. this.expect(types.jsxTagEnd);
  9632. return this.finishNode(node, "JSXClosingFragment");
  9633. }
  9634. node.name = this.jsxParseElementName();
  9635. this.expect(types.jsxTagEnd);
  9636. return this.finishNode(node, "JSXClosingElement");
  9637. }
  9638. jsxParseElementAt(startPos, startLoc) {
  9639. const node = this.startNodeAt(startPos, startLoc);
  9640. const children = [];
  9641. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  9642. let closingElement = null;
  9643. if (!openingElement.selfClosing) {
  9644. contents: for (;;) {
  9645. switch (this.state.type) {
  9646. case types.jsxTagStart:
  9647. startPos = this.state.start;
  9648. startLoc = this.state.startLoc;
  9649. this.next();
  9650. if (this.eat(types.slash)) {
  9651. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  9652. break contents;
  9653. }
  9654. children.push(this.jsxParseElementAt(startPos, startLoc));
  9655. break;
  9656. case types.jsxText:
  9657. children.push(this.parseExprAtom());
  9658. break;
  9659. case types.braceL:
  9660. {
  9661. const node = this.startNode();
  9662. this.next();
  9663. if (this.match(types.ellipsis)) {
  9664. children.push(this.jsxParseSpreadChild(node));
  9665. } else {
  9666. children.push(this.jsxParseExpressionContainer(node));
  9667. }
  9668. break;
  9669. }
  9670. default:
  9671. throw this.unexpected();
  9672. }
  9673. }
  9674. if (isFragment(openingElement) && !isFragment(closingElement)) {
  9675. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  9676. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  9677. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  9678. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  9679. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  9680. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  9681. }
  9682. }
  9683. }
  9684. if (isFragment(openingElement)) {
  9685. node.openingFragment = openingElement;
  9686. node.closingFragment = closingElement;
  9687. } else {
  9688. node.openingElement = openingElement;
  9689. node.closingElement = closingElement;
  9690. }
  9691. node.children = children;
  9692. if (this.isRelational("<")) {
  9693. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  9694. }
  9695. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  9696. }
  9697. jsxParseElement() {
  9698. const startPos = this.state.start;
  9699. const startLoc = this.state.startLoc;
  9700. this.next();
  9701. return this.jsxParseElementAt(startPos, startLoc);
  9702. }
  9703. parseExprAtom(refExpressionErrors) {
  9704. if (this.match(types.jsxText)) {
  9705. return this.parseLiteral(this.state.value, "JSXText");
  9706. } else if (this.match(types.jsxTagStart)) {
  9707. return this.jsxParseElement();
  9708. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  9709. this.finishToken(types.jsxTagStart);
  9710. return this.jsxParseElement();
  9711. } else {
  9712. return super.parseExprAtom(refExpressionErrors);
  9713. }
  9714. }
  9715. getTokenFromCode(code) {
  9716. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  9717. const context = this.curContext();
  9718. if (context === types$1.j_expr) {
  9719. return this.jsxReadToken();
  9720. }
  9721. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  9722. if (isIdentifierStart(code)) {
  9723. return this.jsxReadWord();
  9724. }
  9725. if (code === 62) {
  9726. ++this.state.pos;
  9727. return this.finishToken(types.jsxTagEnd);
  9728. }
  9729. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  9730. return this.jsxReadString(code);
  9731. }
  9732. }
  9733. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  9734. ++this.state.pos;
  9735. return this.finishToken(types.jsxTagStart);
  9736. }
  9737. return super.getTokenFromCode(code);
  9738. }
  9739. updateContext(prevType) {
  9740. if (this.match(types.braceL)) {
  9741. const curContext = this.curContext();
  9742. if (curContext === types$1.j_oTag) {
  9743. this.state.context.push(types$1.braceExpression);
  9744. } else if (curContext === types$1.j_expr) {
  9745. this.state.context.push(types$1.templateQuasi);
  9746. } else {
  9747. super.updateContext(prevType);
  9748. }
  9749. this.state.exprAllowed = true;
  9750. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  9751. this.state.context.length -= 2;
  9752. this.state.context.push(types$1.j_cTag);
  9753. this.state.exprAllowed = false;
  9754. } else {
  9755. return super.updateContext(prevType);
  9756. }
  9757. }
  9758. });
  9759. class Scope {
  9760. constructor(flags) {
  9761. this.flags = void 0;
  9762. this.var = [];
  9763. this.lexical = [];
  9764. this.functions = [];
  9765. this.flags = flags;
  9766. }
  9767. }
  9768. class ScopeHandler {
  9769. constructor(raise, inModule) {
  9770. this.scopeStack = [];
  9771. this.undefinedExports = new Map();
  9772. this.undefinedPrivateNames = new Map();
  9773. this.raise = raise;
  9774. this.inModule = inModule;
  9775. }
  9776. get inFunction() {
  9777. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  9778. }
  9779. get allowSuper() {
  9780. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  9781. }
  9782. get allowDirectSuper() {
  9783. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  9784. }
  9785. get inClass() {
  9786. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  9787. }
  9788. get inNonArrowFunction() {
  9789. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  9790. }
  9791. get treatFunctionsAsVar() {
  9792. return this.treatFunctionsAsVarInScope(this.currentScope());
  9793. }
  9794. createScope(flags) {
  9795. return new Scope(flags);
  9796. }
  9797. enter(flags) {
  9798. this.scopeStack.push(this.createScope(flags));
  9799. }
  9800. exit() {
  9801. this.scopeStack.pop();
  9802. }
  9803. treatFunctionsAsVarInScope(scope) {
  9804. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  9805. }
  9806. declareName(name, bindingType, pos) {
  9807. let scope = this.currentScope();
  9808. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  9809. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  9810. if (bindingType & BIND_SCOPE_FUNCTION) {
  9811. scope.functions.push(name);
  9812. } else {
  9813. scope.lexical.push(name);
  9814. }
  9815. if (bindingType & BIND_SCOPE_LEXICAL) {
  9816. this.maybeExportDefined(scope, name);
  9817. }
  9818. } else if (bindingType & BIND_SCOPE_VAR) {
  9819. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  9820. scope = this.scopeStack[i];
  9821. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  9822. scope.var.push(name);
  9823. this.maybeExportDefined(scope, name);
  9824. if (scope.flags & SCOPE_VAR) break;
  9825. }
  9826. }
  9827. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  9828. this.undefinedExports.delete(name);
  9829. }
  9830. }
  9831. maybeExportDefined(scope, name) {
  9832. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  9833. this.undefinedExports.delete(name);
  9834. }
  9835. }
  9836. checkRedeclarationInScope(scope, name, bindingType, pos) {
  9837. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  9838. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  9839. }
  9840. }
  9841. isRedeclaredInScope(scope, name, bindingType) {
  9842. if (!(bindingType & BIND_KIND_VALUE)) return false;
  9843. if (bindingType & BIND_SCOPE_LEXICAL) {
  9844. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  9845. }
  9846. if (bindingType & BIND_SCOPE_FUNCTION) {
  9847. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  9848. }
  9849. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  9850. }
  9851. checkLocalExport(id) {
  9852. 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) {
  9853. this.undefinedExports.set(id.name, id.start);
  9854. }
  9855. }
  9856. currentScope() {
  9857. return this.scopeStack[this.scopeStack.length - 1];
  9858. }
  9859. currentVarScope() {
  9860. for (let i = this.scopeStack.length - 1;; i--) {
  9861. const scope = this.scopeStack[i];
  9862. if (scope.flags & SCOPE_VAR) {
  9863. return scope;
  9864. }
  9865. }
  9866. }
  9867. currentThisScope() {
  9868. for (let i = this.scopeStack.length - 1;; i--) {
  9869. const scope = this.scopeStack[i];
  9870. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  9871. return scope;
  9872. }
  9873. }
  9874. }
  9875. }
  9876. class TypeScriptScope extends Scope {
  9877. constructor(...args) {
  9878. super(...args);
  9879. this.types = [];
  9880. this.enums = [];
  9881. this.constEnums = [];
  9882. this.classes = [];
  9883. this.exportOnlyBindings = [];
  9884. }
  9885. }
  9886. class TypeScriptScopeHandler extends ScopeHandler {
  9887. createScope(flags) {
  9888. return new TypeScriptScope(flags);
  9889. }
  9890. declareName(name, bindingType, pos) {
  9891. const scope = this.currentScope();
  9892. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  9893. this.maybeExportDefined(scope, name);
  9894. scope.exportOnlyBindings.push(name);
  9895. return;
  9896. }
  9897. super.declareName(...arguments);
  9898. if (bindingType & BIND_KIND_TYPE) {
  9899. if (!(bindingType & BIND_KIND_VALUE)) {
  9900. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  9901. this.maybeExportDefined(scope, name);
  9902. }
  9903. scope.types.push(name);
  9904. }
  9905. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  9906. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  9907. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  9908. }
  9909. isRedeclaredInScope(scope, name, bindingType) {
  9910. if (scope.enums.indexOf(name) > -1) {
  9911. if (bindingType & BIND_FLAGS_TS_ENUM) {
  9912. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  9913. const wasConst = scope.constEnums.indexOf(name) > -1;
  9914. return isConst !== wasConst;
  9915. }
  9916. return true;
  9917. }
  9918. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  9919. if (scope.lexical.indexOf(name) > -1) {
  9920. return !!(bindingType & BIND_KIND_VALUE);
  9921. } else {
  9922. return false;
  9923. }
  9924. }
  9925. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  9926. return true;
  9927. }
  9928. return super.isRedeclaredInScope(...arguments);
  9929. }
  9930. checkLocalExport(id) {
  9931. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  9932. super.checkLocalExport(id);
  9933. }
  9934. }
  9935. }
  9936. const PARAM = 0b0000,
  9937. PARAM_YIELD = 0b0001,
  9938. PARAM_AWAIT = 0b0010,
  9939. PARAM_RETURN = 0b0100,
  9940. PARAM_IN = 0b1000;
  9941. class ProductionParameterHandler {
  9942. constructor() {
  9943. this.stacks = [];
  9944. }
  9945. enter(flags) {
  9946. this.stacks.push(flags);
  9947. }
  9948. exit() {
  9949. this.stacks.pop();
  9950. }
  9951. currentFlags() {
  9952. return this.stacks[this.stacks.length - 1];
  9953. }
  9954. get hasAwait() {
  9955. return (this.currentFlags() & PARAM_AWAIT) > 0;
  9956. }
  9957. get hasYield() {
  9958. return (this.currentFlags() & PARAM_YIELD) > 0;
  9959. }
  9960. get hasReturn() {
  9961. return (this.currentFlags() & PARAM_RETURN) > 0;
  9962. }
  9963. get hasIn() {
  9964. return (this.currentFlags() & PARAM_IN) > 0;
  9965. }
  9966. }
  9967. function functionFlags(isAsync, isGenerator) {
  9968. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  9969. }
  9970. function nonNull(x) {
  9971. if (x == null) {
  9972. throw new Error(`Unexpected ${x} value.`);
  9973. }
  9974. return x;
  9975. }
  9976. function assert$1(x) {
  9977. if (!x) {
  9978. throw new Error("Assert fail");
  9979. }
  9980. }
  9981. const TSErrors = Object.freeze({
  9982. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
  9983. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
  9984. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  9985. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  9986. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  9987. DuplicateModifier: "Duplicate modifier: '%0'",
  9988. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  9989. EmptyTypeArguments: "Type argument list cannot be empty.",
  9990. EmptyTypeParameters: "Type parameter list cannot be empty.",
  9991. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
  9992. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
  9993. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
  9994. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier",
  9995. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  9996. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  9997. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  9998. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  9999. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  10000. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
  10001. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  10002. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  10003. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  10004. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  10005. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  10006. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
  10007. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  10008. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
  10009. });
  10010. function keywordTypeFromName(value) {
  10011. switch (value) {
  10012. case "any":
  10013. return "TSAnyKeyword";
  10014. case "boolean":
  10015. return "TSBooleanKeyword";
  10016. case "bigint":
  10017. return "TSBigIntKeyword";
  10018. case "never":
  10019. return "TSNeverKeyword";
  10020. case "number":
  10021. return "TSNumberKeyword";
  10022. case "object":
  10023. return "TSObjectKeyword";
  10024. case "string":
  10025. return "TSStringKeyword";
  10026. case "symbol":
  10027. return "TSSymbolKeyword";
  10028. case "undefined":
  10029. return "TSUndefinedKeyword";
  10030. case "unknown":
  10031. return "TSUnknownKeyword";
  10032. default:
  10033. return undefined;
  10034. }
  10035. }
  10036. var typescript = (superClass => class extends superClass {
  10037. getScopeHandler() {
  10038. return TypeScriptScopeHandler;
  10039. }
  10040. tsIsIdentifier() {
  10041. return this.match(types.name);
  10042. }
  10043. tsNextTokenCanFollowModifier() {
  10044. this.next();
  10045. 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();
  10046. }
  10047. tsParseModifier(allowedModifiers) {
  10048. if (!this.match(types.name)) {
  10049. return undefined;
  10050. }
  10051. const modifier = this.state.value;
  10052. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  10053. return modifier;
  10054. }
  10055. return undefined;
  10056. }
  10057. tsParseModifiers(modified, allowedModifiers) {
  10058. for (;;) {
  10059. const startPos = this.state.start;
  10060. const modifier = this.tsParseModifier(allowedModifiers);
  10061. if (!modifier) break;
  10062. if (Object.hasOwnProperty.call(modified, modifier)) {
  10063. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  10064. }
  10065. modified[modifier] = true;
  10066. }
  10067. }
  10068. tsIsListTerminator(kind) {
  10069. switch (kind) {
  10070. case "EnumMembers":
  10071. case "TypeMembers":
  10072. return this.match(types.braceR);
  10073. case "HeritageClauseElement":
  10074. return this.match(types.braceL);
  10075. case "TupleElementTypes":
  10076. return this.match(types.bracketR);
  10077. case "TypeParametersOrArguments":
  10078. return this.isRelational(">");
  10079. }
  10080. throw new Error("Unreachable");
  10081. }
  10082. tsParseList(kind, parseElement) {
  10083. const result = [];
  10084. while (!this.tsIsListTerminator(kind)) {
  10085. result.push(parseElement());
  10086. }
  10087. return result;
  10088. }
  10089. tsParseDelimitedList(kind, parseElement) {
  10090. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  10091. }
  10092. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  10093. const result = [];
  10094. for (;;) {
  10095. if (this.tsIsListTerminator(kind)) {
  10096. break;
  10097. }
  10098. const element = parseElement();
  10099. if (element == null) {
  10100. return undefined;
  10101. }
  10102. result.push(element);
  10103. if (this.eat(types.comma)) {
  10104. continue;
  10105. }
  10106. if (this.tsIsListTerminator(kind)) {
  10107. break;
  10108. }
  10109. if (expectSuccess) {
  10110. this.expect(types.comma);
  10111. }
  10112. return undefined;
  10113. }
  10114. return result;
  10115. }
  10116. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  10117. if (!skipFirstToken) {
  10118. if (bracket) {
  10119. this.expect(types.bracketL);
  10120. } else {
  10121. this.expectRelational("<");
  10122. }
  10123. }
  10124. const result = this.tsParseDelimitedList(kind, parseElement);
  10125. if (bracket) {
  10126. this.expect(types.bracketR);
  10127. } else {
  10128. this.expectRelational(">");
  10129. }
  10130. return result;
  10131. }
  10132. tsParseImportType() {
  10133. const node = this.startNode();
  10134. this.expect(types._import);
  10135. this.expect(types.parenL);
  10136. if (!this.match(types.string)) {
  10137. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  10138. }
  10139. node.argument = this.parseExprAtom();
  10140. this.expect(types.parenR);
  10141. if (this.eat(types.dot)) {
  10142. node.qualifier = this.tsParseEntityName(true);
  10143. }
  10144. if (this.isRelational("<")) {
  10145. node.typeParameters = this.tsParseTypeArguments();
  10146. }
  10147. return this.finishNode(node, "TSImportType");
  10148. }
  10149. tsParseEntityName(allowReservedWords) {
  10150. let entity = this.parseIdentifier();
  10151. while (this.eat(types.dot)) {
  10152. const node = this.startNodeAtNode(entity);
  10153. node.left = entity;
  10154. node.right = this.parseIdentifier(allowReservedWords);
  10155. entity = this.finishNode(node, "TSQualifiedName");
  10156. }
  10157. return entity;
  10158. }
  10159. tsParseTypeReference() {
  10160. const node = this.startNode();
  10161. node.typeName = this.tsParseEntityName(false);
  10162. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  10163. node.typeParameters = this.tsParseTypeArguments();
  10164. }
  10165. return this.finishNode(node, "TSTypeReference");
  10166. }
  10167. tsParseThisTypePredicate(lhs) {
  10168. this.next();
  10169. const node = this.startNodeAtNode(lhs);
  10170. node.parameterName = lhs;
  10171. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  10172. node.asserts = false;
  10173. return this.finishNode(node, "TSTypePredicate");
  10174. }
  10175. tsParseThisTypeNode() {
  10176. const node = this.startNode();
  10177. this.next();
  10178. return this.finishNode(node, "TSThisType");
  10179. }
  10180. tsParseTypeQuery() {
  10181. const node = this.startNode();
  10182. this.expect(types._typeof);
  10183. if (this.match(types._import)) {
  10184. node.exprName = this.tsParseImportType();
  10185. } else {
  10186. node.exprName = this.tsParseEntityName(true);
  10187. }
  10188. return this.finishNode(node, "TSTypeQuery");
  10189. }
  10190. tsParseTypeParameter() {
  10191. const node = this.startNode();
  10192. node.name = this.parseIdentifierName(node.start);
  10193. node.constraint = this.tsEatThenParseType(types._extends);
  10194. node.default = this.tsEatThenParseType(types.eq);
  10195. return this.finishNode(node, "TSTypeParameter");
  10196. }
  10197. tsTryParseTypeParameters() {
  10198. if (this.isRelational("<")) {
  10199. return this.tsParseTypeParameters();
  10200. }
  10201. }
  10202. tsParseTypeParameters() {
  10203. const node = this.startNode();
  10204. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  10205. this.next();
  10206. } else {
  10207. this.unexpected();
  10208. }
  10209. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  10210. if (node.params.length === 0) {
  10211. this.raise(node.start, TSErrors.EmptyTypeParameters);
  10212. }
  10213. return this.finishNode(node, "TSTypeParameterDeclaration");
  10214. }
  10215. tsTryNextParseConstantContext() {
  10216. if (this.lookahead().type === types._const) {
  10217. this.next();
  10218. return this.tsParseTypeReference();
  10219. }
  10220. return null;
  10221. }
  10222. tsFillSignature(returnToken, signature) {
  10223. const returnTokenRequired = returnToken === types.arrow;
  10224. signature.typeParameters = this.tsTryParseTypeParameters();
  10225. this.expect(types.parenL);
  10226. signature.parameters = this.tsParseBindingListForSignature();
  10227. if (returnTokenRequired) {
  10228. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  10229. } else if (this.match(returnToken)) {
  10230. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  10231. }
  10232. }
  10233. tsParseBindingListForSignature() {
  10234. return this.parseBindingList(types.parenR, 41).map(pattern => {
  10235. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  10236. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  10237. }
  10238. return pattern;
  10239. });
  10240. }
  10241. tsParseTypeMemberSemicolon() {
  10242. if (!this.eat(types.comma)) {
  10243. this.semicolon();
  10244. }
  10245. }
  10246. tsParseSignatureMember(kind, node) {
  10247. this.tsFillSignature(types.colon, node);
  10248. this.tsParseTypeMemberSemicolon();
  10249. return this.finishNode(node, kind);
  10250. }
  10251. tsIsUnambiguouslyIndexSignature() {
  10252. this.next();
  10253. return this.eat(types.name) && this.match(types.colon);
  10254. }
  10255. tsTryParseIndexSignature(node) {
  10256. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  10257. return undefined;
  10258. }
  10259. this.expect(types.bracketL);
  10260. const id = this.parseIdentifier();
  10261. id.typeAnnotation = this.tsParseTypeAnnotation();
  10262. this.resetEndLocation(id);
  10263. this.expect(types.bracketR);
  10264. node.parameters = [id];
  10265. const type = this.tsTryParseTypeAnnotation();
  10266. if (type) node.typeAnnotation = type;
  10267. this.tsParseTypeMemberSemicolon();
  10268. return this.finishNode(node, "TSIndexSignature");
  10269. }
  10270. tsParsePropertyOrMethodSignature(node, readonly) {
  10271. if (this.eat(types.question)) node.optional = true;
  10272. const nodeAny = node;
  10273. if (!readonly && (this.match(types.parenL) || this.isRelational("<"))) {
  10274. const method = nodeAny;
  10275. this.tsFillSignature(types.colon, method);
  10276. this.tsParseTypeMemberSemicolon();
  10277. return this.finishNode(method, "TSMethodSignature");
  10278. } else {
  10279. const property = nodeAny;
  10280. if (readonly) property.readonly = true;
  10281. const type = this.tsTryParseTypeAnnotation();
  10282. if (type) property.typeAnnotation = type;
  10283. this.tsParseTypeMemberSemicolon();
  10284. return this.finishNode(property, "TSPropertySignature");
  10285. }
  10286. }
  10287. tsParseTypeMember() {
  10288. const node = this.startNode();
  10289. if (this.match(types.parenL) || this.isRelational("<")) {
  10290. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  10291. }
  10292. if (this.match(types._new)) {
  10293. const id = this.startNode();
  10294. this.next();
  10295. if (this.match(types.parenL) || this.isRelational("<")) {
  10296. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  10297. } else {
  10298. node.key = this.createIdentifier(id, "new");
  10299. return this.tsParsePropertyOrMethodSignature(node, false);
  10300. }
  10301. }
  10302. const readonly = !!this.tsParseModifier(["readonly"]);
  10303. const idx = this.tsTryParseIndexSignature(node);
  10304. if (idx) {
  10305. if (readonly) node.readonly = true;
  10306. return idx;
  10307. }
  10308. this.parsePropertyName(node, false);
  10309. return this.tsParsePropertyOrMethodSignature(node, readonly);
  10310. }
  10311. tsParseTypeLiteral() {
  10312. const node = this.startNode();
  10313. node.members = this.tsParseObjectTypeMembers();
  10314. return this.finishNode(node, "TSTypeLiteral");
  10315. }
  10316. tsParseObjectTypeMembers() {
  10317. this.expect(types.braceL);
  10318. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  10319. this.expect(types.braceR);
  10320. return members;
  10321. }
  10322. tsIsStartOfMappedType() {
  10323. this.next();
  10324. if (this.eat(types.plusMin)) {
  10325. return this.isContextual("readonly");
  10326. }
  10327. if (this.isContextual("readonly")) {
  10328. this.next();
  10329. }
  10330. if (!this.match(types.bracketL)) {
  10331. return false;
  10332. }
  10333. this.next();
  10334. if (!this.tsIsIdentifier()) {
  10335. return false;
  10336. }
  10337. this.next();
  10338. return this.match(types._in);
  10339. }
  10340. tsParseMappedTypeParameter() {
  10341. const node = this.startNode();
  10342. node.name = this.parseIdentifierName(node.start);
  10343. node.constraint = this.tsExpectThenParseType(types._in);
  10344. return this.finishNode(node, "TSTypeParameter");
  10345. }
  10346. tsParseMappedType() {
  10347. const node = this.startNode();
  10348. this.expect(types.braceL);
  10349. if (this.match(types.plusMin)) {
  10350. node.readonly = this.state.value;
  10351. this.next();
  10352. this.expectContextual("readonly");
  10353. } else if (this.eatContextual("readonly")) {
  10354. node.readonly = true;
  10355. }
  10356. this.expect(types.bracketL);
  10357. node.typeParameter = this.tsParseMappedTypeParameter();
  10358. node.nameType = this.eatContextual("as") ? this.tsParseType() : null;
  10359. this.expect(types.bracketR);
  10360. if (this.match(types.plusMin)) {
  10361. node.optional = this.state.value;
  10362. this.next();
  10363. this.expect(types.question);
  10364. } else if (this.eat(types.question)) {
  10365. node.optional = true;
  10366. }
  10367. node.typeAnnotation = this.tsTryParseType();
  10368. this.semicolon();
  10369. this.expect(types.braceR);
  10370. return this.finishNode(node, "TSMappedType");
  10371. }
  10372. tsParseTupleType() {
  10373. const node = this.startNode();
  10374. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  10375. let seenOptionalElement = false;
  10376. let labeledElements = null;
  10377. node.elementTypes.forEach(elementNode => {
  10378. var _labeledElements;
  10379. let {
  10380. type
  10381. } = elementNode;
  10382. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  10383. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  10384. }
  10385. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  10386. if (type === "TSRestType") {
  10387. elementNode = elementNode.typeAnnotation;
  10388. type = elementNode.type;
  10389. }
  10390. const isLabeled = type === "TSNamedTupleMember";
  10391. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  10392. if (labeledElements !== isLabeled) {
  10393. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  10394. }
  10395. });
  10396. return this.finishNode(node, "TSTupleType");
  10397. }
  10398. tsParseTupleElementType() {
  10399. const {
  10400. start: startPos,
  10401. startLoc
  10402. } = this.state;
  10403. const rest = this.eat(types.ellipsis);
  10404. let type = this.tsParseType();
  10405. const optional = this.eat(types.question);
  10406. const labeled = this.eat(types.colon);
  10407. if (labeled) {
  10408. const labeledNode = this.startNodeAtNode(type);
  10409. labeledNode.optional = optional;
  10410. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  10411. labeledNode.label = type.typeName;
  10412. } else {
  10413. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  10414. labeledNode.label = type;
  10415. }
  10416. labeledNode.elementType = this.tsParseType();
  10417. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  10418. } else if (optional) {
  10419. const optionalTypeNode = this.startNodeAtNode(type);
  10420. optionalTypeNode.typeAnnotation = type;
  10421. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  10422. }
  10423. if (rest) {
  10424. const restNode = this.startNodeAt(startPos, startLoc);
  10425. restNode.typeAnnotation = type;
  10426. type = this.finishNode(restNode, "TSRestType");
  10427. }
  10428. return type;
  10429. }
  10430. tsParseParenthesizedType() {
  10431. const node = this.startNode();
  10432. this.expect(types.parenL);
  10433. node.typeAnnotation = this.tsParseType();
  10434. this.expect(types.parenR);
  10435. return this.finishNode(node, "TSParenthesizedType");
  10436. }
  10437. tsParseFunctionOrConstructorType(type) {
  10438. const node = this.startNode();
  10439. if (type === "TSConstructorType") {
  10440. this.expect(types._new);
  10441. }
  10442. this.tsFillSignature(types.arrow, node);
  10443. return this.finishNode(node, type);
  10444. }
  10445. tsParseLiteralTypeNode() {
  10446. const node = this.startNode();
  10447. node.literal = (() => {
  10448. switch (this.state.type) {
  10449. case types.num:
  10450. case types.bigint:
  10451. case types.string:
  10452. case types._true:
  10453. case types._false:
  10454. return this.parseExprAtom();
  10455. default:
  10456. throw this.unexpected();
  10457. }
  10458. })();
  10459. return this.finishNode(node, "TSLiteralType");
  10460. }
  10461. tsParseTemplateLiteralType() {
  10462. const node = this.startNode();
  10463. node.literal = this.parseTemplate(false);
  10464. return this.finishNode(node, "TSLiteralType");
  10465. }
  10466. parseTemplateSubstitution() {
  10467. if (this.state.inType) return this.tsParseType();
  10468. return super.parseTemplateSubstitution();
  10469. }
  10470. tsParseThisTypeOrThisTypePredicate() {
  10471. const thisKeyword = this.tsParseThisTypeNode();
  10472. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  10473. return this.tsParseThisTypePredicate(thisKeyword);
  10474. } else {
  10475. return thisKeyword;
  10476. }
  10477. }
  10478. tsParseNonArrayType() {
  10479. switch (this.state.type) {
  10480. case types.name:
  10481. case types._void:
  10482. case types._null:
  10483. {
  10484. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  10485. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  10486. const node = this.startNode();
  10487. this.next();
  10488. return this.finishNode(node, type);
  10489. }
  10490. return this.tsParseTypeReference();
  10491. }
  10492. case types.string:
  10493. case types.num:
  10494. case types.bigint:
  10495. case types._true:
  10496. case types._false:
  10497. return this.tsParseLiteralTypeNode();
  10498. case types.plusMin:
  10499. if (this.state.value === "-") {
  10500. const node = this.startNode();
  10501. const nextToken = this.lookahead();
  10502. if (nextToken.type !== types.num && nextToken.type !== types.bigint) {
  10503. throw this.unexpected();
  10504. }
  10505. node.literal = this.parseMaybeUnary();
  10506. return this.finishNode(node, "TSLiteralType");
  10507. }
  10508. break;
  10509. case types._this:
  10510. return this.tsParseThisTypeOrThisTypePredicate();
  10511. case types._typeof:
  10512. return this.tsParseTypeQuery();
  10513. case types._import:
  10514. return this.tsParseImportType();
  10515. case types.braceL:
  10516. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  10517. case types.bracketL:
  10518. return this.tsParseTupleType();
  10519. case types.parenL:
  10520. return this.tsParseParenthesizedType();
  10521. case types.backQuote:
  10522. return this.tsParseTemplateLiteralType();
  10523. }
  10524. throw this.unexpected();
  10525. }
  10526. tsParseArrayTypeOrHigher() {
  10527. let type = this.tsParseNonArrayType();
  10528. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  10529. if (this.match(types.bracketR)) {
  10530. const node = this.startNodeAtNode(type);
  10531. node.elementType = type;
  10532. this.expect(types.bracketR);
  10533. type = this.finishNode(node, "TSArrayType");
  10534. } else {
  10535. const node = this.startNodeAtNode(type);
  10536. node.objectType = type;
  10537. node.indexType = this.tsParseType();
  10538. this.expect(types.bracketR);
  10539. type = this.finishNode(node, "TSIndexedAccessType");
  10540. }
  10541. }
  10542. return type;
  10543. }
  10544. tsParseTypeOperator(operator) {
  10545. const node = this.startNode();
  10546. this.expectContextual(operator);
  10547. node.operator = operator;
  10548. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  10549. if (operator === "readonly") {
  10550. this.tsCheckTypeAnnotationForReadOnly(node);
  10551. }
  10552. return this.finishNode(node, "TSTypeOperator");
  10553. }
  10554. tsCheckTypeAnnotationForReadOnly(node) {
  10555. switch (node.typeAnnotation.type) {
  10556. case "TSTupleType":
  10557. case "TSArrayType":
  10558. return;
  10559. default:
  10560. this.raise(node.start, TSErrors.UnexpectedReadonly);
  10561. }
  10562. }
  10563. tsParseInferType() {
  10564. const node = this.startNode();
  10565. this.expectContextual("infer");
  10566. const typeParameter = this.startNode();
  10567. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  10568. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  10569. return this.finishNode(node, "TSInferType");
  10570. }
  10571. tsParseTypeOperatorOrHigher() {
  10572. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  10573. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  10574. }
  10575. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  10576. this.eat(operator);
  10577. let type = parseConstituentType();
  10578. if (this.match(operator)) {
  10579. const types = [type];
  10580. while (this.eat(operator)) {
  10581. types.push(parseConstituentType());
  10582. }
  10583. const node = this.startNodeAtNode(type);
  10584. node.types = types;
  10585. type = this.finishNode(node, kind);
  10586. }
  10587. return type;
  10588. }
  10589. tsParseIntersectionTypeOrHigher() {
  10590. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  10591. }
  10592. tsParseUnionTypeOrHigher() {
  10593. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  10594. }
  10595. tsIsStartOfFunctionType() {
  10596. if (this.isRelational("<")) {
  10597. return true;
  10598. }
  10599. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  10600. }
  10601. tsSkipParameterStart() {
  10602. if (this.match(types.name) || this.match(types._this)) {
  10603. this.next();
  10604. return true;
  10605. }
  10606. if (this.match(types.braceL)) {
  10607. let braceStackCounter = 1;
  10608. this.next();
  10609. while (braceStackCounter > 0) {
  10610. if (this.match(types.braceL)) {
  10611. ++braceStackCounter;
  10612. } else if (this.match(types.braceR)) {
  10613. --braceStackCounter;
  10614. }
  10615. this.next();
  10616. }
  10617. return true;
  10618. }
  10619. if (this.match(types.bracketL)) {
  10620. let braceStackCounter = 1;
  10621. this.next();
  10622. while (braceStackCounter > 0) {
  10623. if (this.match(types.bracketL)) {
  10624. ++braceStackCounter;
  10625. } else if (this.match(types.bracketR)) {
  10626. --braceStackCounter;
  10627. }
  10628. this.next();
  10629. }
  10630. return true;
  10631. }
  10632. return false;
  10633. }
  10634. tsIsUnambiguouslyStartOfFunctionType() {
  10635. this.next();
  10636. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  10637. return true;
  10638. }
  10639. if (this.tsSkipParameterStart()) {
  10640. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  10641. return true;
  10642. }
  10643. if (this.match(types.parenR)) {
  10644. this.next();
  10645. if (this.match(types.arrow)) {
  10646. return true;
  10647. }
  10648. }
  10649. }
  10650. return false;
  10651. }
  10652. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  10653. return this.tsInType(() => {
  10654. const t = this.startNode();
  10655. this.expect(returnToken);
  10656. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  10657. if (asserts && this.match(types._this)) {
  10658. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  10659. if (thisTypePredicate.type === "TSThisType") {
  10660. const node = this.startNodeAtNode(t);
  10661. node.parameterName = thisTypePredicate;
  10662. node.asserts = true;
  10663. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  10664. } else {
  10665. thisTypePredicate.asserts = true;
  10666. }
  10667. t.typeAnnotation = thisTypePredicate;
  10668. return this.finishNode(t, "TSTypeAnnotation");
  10669. }
  10670. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  10671. if (!typePredicateVariable) {
  10672. if (!asserts) {
  10673. return this.tsParseTypeAnnotation(false, t);
  10674. }
  10675. const node = this.startNodeAtNode(t);
  10676. node.parameterName = this.parseIdentifier();
  10677. node.asserts = asserts;
  10678. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  10679. return this.finishNode(t, "TSTypeAnnotation");
  10680. }
  10681. const type = this.tsParseTypeAnnotation(false);
  10682. const node = this.startNodeAtNode(t);
  10683. node.parameterName = typePredicateVariable;
  10684. node.typeAnnotation = type;
  10685. node.asserts = asserts;
  10686. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  10687. return this.finishNode(t, "TSTypeAnnotation");
  10688. });
  10689. }
  10690. tsTryParseTypeOrTypePredicateAnnotation() {
  10691. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  10692. }
  10693. tsTryParseTypeAnnotation() {
  10694. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  10695. }
  10696. tsTryParseType() {
  10697. return this.tsEatThenParseType(types.colon);
  10698. }
  10699. tsParseTypePredicatePrefix() {
  10700. const id = this.parseIdentifier();
  10701. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  10702. this.next();
  10703. return id;
  10704. }
  10705. }
  10706. tsParseTypePredicateAsserts() {
  10707. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  10708. return false;
  10709. }
  10710. const containsEsc = this.state.containsEsc;
  10711. this.next();
  10712. if (!this.match(types.name) && !this.match(types._this)) {
  10713. return false;
  10714. }
  10715. if (containsEsc) {
  10716. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  10717. }
  10718. return true;
  10719. }
  10720. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  10721. this.tsInType(() => {
  10722. if (eatColon) this.expect(types.colon);
  10723. t.typeAnnotation = this.tsParseType();
  10724. });
  10725. return this.finishNode(t, "TSTypeAnnotation");
  10726. }
  10727. tsParseType() {
  10728. assert$1(this.state.inType);
  10729. const type = this.tsParseNonConditionalType();
  10730. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  10731. return type;
  10732. }
  10733. const node = this.startNodeAtNode(type);
  10734. node.checkType = type;
  10735. node.extendsType = this.tsParseNonConditionalType();
  10736. this.expect(types.question);
  10737. node.trueType = this.tsParseType();
  10738. this.expect(types.colon);
  10739. node.falseType = this.tsParseType();
  10740. return this.finishNode(node, "TSConditionalType");
  10741. }
  10742. tsParseNonConditionalType() {
  10743. if (this.tsIsStartOfFunctionType()) {
  10744. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  10745. }
  10746. if (this.match(types._new)) {
  10747. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  10748. }
  10749. return this.tsParseUnionTypeOrHigher();
  10750. }
  10751. tsParseTypeAssertion() {
  10752. const node = this.startNode();
  10753. const _const = this.tsTryNextParseConstantContext();
  10754. node.typeAnnotation = _const || this.tsNextThenParseType();
  10755. this.expectRelational(">");
  10756. node.expression = this.parseMaybeUnary();
  10757. return this.finishNode(node, "TSTypeAssertion");
  10758. }
  10759. tsParseHeritageClause(descriptor) {
  10760. const originalStart = this.state.start;
  10761. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  10762. if (!delimitedList.length) {
  10763. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  10764. }
  10765. return delimitedList;
  10766. }
  10767. tsParseExpressionWithTypeArguments() {
  10768. const node = this.startNode();
  10769. node.expression = this.tsParseEntityName(false);
  10770. if (this.isRelational("<")) {
  10771. node.typeParameters = this.tsParseTypeArguments();
  10772. }
  10773. return this.finishNode(node, "TSExpressionWithTypeArguments");
  10774. }
  10775. tsParseInterfaceDeclaration(node) {
  10776. node.id = this.parseIdentifier();
  10777. this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
  10778. node.typeParameters = this.tsTryParseTypeParameters();
  10779. if (this.eat(types._extends)) {
  10780. node.extends = this.tsParseHeritageClause("extends");
  10781. }
  10782. const body = this.startNode();
  10783. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  10784. node.body = this.finishNode(body, "TSInterfaceBody");
  10785. return this.finishNode(node, "TSInterfaceDeclaration");
  10786. }
  10787. tsParseTypeAliasDeclaration(node) {
  10788. node.id = this.parseIdentifier();
  10789. this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE);
  10790. node.typeParameters = this.tsTryParseTypeParameters();
  10791. node.typeAnnotation = this.tsInType(() => {
  10792. this.expect(types.eq);
  10793. if (this.isContextual("intrinsic") && this.lookahead().type !== types.dot) {
  10794. const node = this.startNode();
  10795. this.next();
  10796. return this.finishNode(node, "TSIntrinsicKeyword");
  10797. }
  10798. return this.tsParseType();
  10799. });
  10800. this.semicolon();
  10801. return this.finishNode(node, "TSTypeAliasDeclaration");
  10802. }
  10803. tsInNoContext(cb) {
  10804. const oldContext = this.state.context;
  10805. this.state.context = [oldContext[0]];
  10806. try {
  10807. return cb();
  10808. } finally {
  10809. this.state.context = oldContext;
  10810. }
  10811. }
  10812. tsInType(cb) {
  10813. const oldInType = this.state.inType;
  10814. this.state.inType = true;
  10815. try {
  10816. return cb();
  10817. } finally {
  10818. this.state.inType = oldInType;
  10819. }
  10820. }
  10821. tsEatThenParseType(token) {
  10822. return !this.match(token) ? undefined : this.tsNextThenParseType();
  10823. }
  10824. tsExpectThenParseType(token) {
  10825. return this.tsDoThenParseType(() => this.expect(token));
  10826. }
  10827. tsNextThenParseType() {
  10828. return this.tsDoThenParseType(() => this.next());
  10829. }
  10830. tsDoThenParseType(cb) {
  10831. return this.tsInType(() => {
  10832. cb();
  10833. return this.tsParseType();
  10834. });
  10835. }
  10836. tsParseEnumMember() {
  10837. const node = this.startNode();
  10838. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  10839. if (this.eat(types.eq)) {
  10840. node.initializer = this.parseMaybeAssignAllowIn();
  10841. }
  10842. return this.finishNode(node, "TSEnumMember");
  10843. }
  10844. tsParseEnumDeclaration(node, isConst) {
  10845. if (isConst) node.const = true;
  10846. node.id = this.parseIdentifier();
  10847. this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
  10848. this.expect(types.braceL);
  10849. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  10850. this.expect(types.braceR);
  10851. return this.finishNode(node, "TSEnumDeclaration");
  10852. }
  10853. tsParseModuleBlock() {
  10854. const node = this.startNode();
  10855. this.scope.enter(SCOPE_OTHER);
  10856. this.expect(types.braceL);
  10857. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  10858. this.scope.exit();
  10859. return this.finishNode(node, "TSModuleBlock");
  10860. }
  10861. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  10862. node.id = this.parseIdentifier();
  10863. if (!nested) {
  10864. this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE);
  10865. }
  10866. if (this.eat(types.dot)) {
  10867. const inner = this.startNode();
  10868. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  10869. node.body = inner;
  10870. } else {
  10871. this.scope.enter(SCOPE_TS_MODULE);
  10872. this.prodParam.enter(PARAM);
  10873. node.body = this.tsParseModuleBlock();
  10874. this.prodParam.exit();
  10875. this.scope.exit();
  10876. }
  10877. return this.finishNode(node, "TSModuleDeclaration");
  10878. }
  10879. tsParseAmbientExternalModuleDeclaration(node) {
  10880. if (this.isContextual("global")) {
  10881. node.global = true;
  10882. node.id = this.parseIdentifier();
  10883. } else if (this.match(types.string)) {
  10884. node.id = this.parseExprAtom();
  10885. } else {
  10886. this.unexpected();
  10887. }
  10888. if (this.match(types.braceL)) {
  10889. this.scope.enter(SCOPE_TS_MODULE);
  10890. this.prodParam.enter(PARAM);
  10891. node.body = this.tsParseModuleBlock();
  10892. this.prodParam.exit();
  10893. this.scope.exit();
  10894. } else {
  10895. this.semicolon();
  10896. }
  10897. return this.finishNode(node, "TSModuleDeclaration");
  10898. }
  10899. tsParseImportEqualsDeclaration(node, isExport) {
  10900. node.isExport = isExport || false;
  10901. node.id = this.parseIdentifier();
  10902. this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL);
  10903. this.expect(types.eq);
  10904. node.moduleReference = this.tsParseModuleReference();
  10905. this.semicolon();
  10906. return this.finishNode(node, "TSImportEqualsDeclaration");
  10907. }
  10908. tsIsExternalModuleReference() {
  10909. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  10910. }
  10911. tsParseModuleReference() {
  10912. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  10913. }
  10914. tsParseExternalModuleReference() {
  10915. const node = this.startNode();
  10916. this.expectContextual("require");
  10917. this.expect(types.parenL);
  10918. if (!this.match(types.string)) {
  10919. throw this.unexpected();
  10920. }
  10921. node.expression = this.parseExprAtom();
  10922. this.expect(types.parenR);
  10923. return this.finishNode(node, "TSExternalModuleReference");
  10924. }
  10925. tsLookAhead(f) {
  10926. const state = this.state.clone();
  10927. const res = f();
  10928. this.state = state;
  10929. return res;
  10930. }
  10931. tsTryParseAndCatch(f) {
  10932. const result = this.tryParse(abort => f() || abort());
  10933. if (result.aborted || !result.node) return undefined;
  10934. if (result.error) this.state = result.failState;
  10935. return result.node;
  10936. }
  10937. tsTryParse(f) {
  10938. const state = this.state.clone();
  10939. const result = f();
  10940. if (result !== undefined && result !== false) {
  10941. return result;
  10942. } else {
  10943. this.state = state;
  10944. return undefined;
  10945. }
  10946. }
  10947. tsTryParseDeclare(nany) {
  10948. if (this.isLineTerminator()) {
  10949. return;
  10950. }
  10951. let starttype = this.state.type;
  10952. let kind;
  10953. if (this.isContextual("let")) {
  10954. starttype = types._var;
  10955. kind = "let";
  10956. }
  10957. return this.tsInDeclareContext(() => {
  10958. switch (starttype) {
  10959. case types._function:
  10960. nany.declare = true;
  10961. return this.parseFunctionStatement(nany, false, true);
  10962. case types._class:
  10963. nany.declare = true;
  10964. return this.parseClass(nany, true, false);
  10965. case types._const:
  10966. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  10967. this.expect(types._const);
  10968. this.expectContextual("enum");
  10969. return this.tsParseEnumDeclaration(nany, true);
  10970. }
  10971. case types._var:
  10972. kind = kind || this.state.value;
  10973. return this.parseVarStatement(nany, kind);
  10974. case types.name:
  10975. {
  10976. const value = this.state.value;
  10977. if (value === "global") {
  10978. return this.tsParseAmbientExternalModuleDeclaration(nany);
  10979. } else {
  10980. return this.tsParseDeclaration(nany, value, true);
  10981. }
  10982. }
  10983. }
  10984. });
  10985. }
  10986. tsTryParseExportDeclaration() {
  10987. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  10988. }
  10989. tsParseExpressionStatement(node, expr) {
  10990. switch (expr.name) {
  10991. case "declare":
  10992. {
  10993. const declaration = this.tsTryParseDeclare(node);
  10994. if (declaration) {
  10995. declaration.declare = true;
  10996. return declaration;
  10997. }
  10998. break;
  10999. }
  11000. case "global":
  11001. if (this.match(types.braceL)) {
  11002. this.scope.enter(SCOPE_TS_MODULE);
  11003. this.prodParam.enter(PARAM);
  11004. const mod = node;
  11005. mod.global = true;
  11006. mod.id = expr;
  11007. mod.body = this.tsParseModuleBlock();
  11008. this.scope.exit();
  11009. this.prodParam.exit();
  11010. return this.finishNode(mod, "TSModuleDeclaration");
  11011. }
  11012. break;
  11013. default:
  11014. return this.tsParseDeclaration(node, expr.name, false);
  11015. }
  11016. }
  11017. tsParseDeclaration(node, value, next) {
  11018. switch (value) {
  11019. case "abstract":
  11020. if (this.tsCheckLineTerminatorAndMatch(types._class, next)) {
  11021. const cls = node;
  11022. cls.abstract = true;
  11023. if (next) {
  11024. this.next();
  11025. if (!this.match(types._class)) {
  11026. this.unexpected(null, types._class);
  11027. }
  11028. }
  11029. return this.parseClass(cls, true, false);
  11030. }
  11031. break;
  11032. case "enum":
  11033. if (next || this.match(types.name)) {
  11034. if (next) this.next();
  11035. return this.tsParseEnumDeclaration(node, false);
  11036. }
  11037. break;
  11038. case "interface":
  11039. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  11040. if (next) this.next();
  11041. return this.tsParseInterfaceDeclaration(node);
  11042. }
  11043. break;
  11044. case "module":
  11045. if (next) this.next();
  11046. if (this.match(types.string)) {
  11047. return this.tsParseAmbientExternalModuleDeclaration(node);
  11048. } else if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  11049. return this.tsParseModuleOrNamespaceDeclaration(node);
  11050. }
  11051. break;
  11052. case "namespace":
  11053. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  11054. if (next) this.next();
  11055. return this.tsParseModuleOrNamespaceDeclaration(node);
  11056. }
  11057. break;
  11058. case "type":
  11059. if (this.tsCheckLineTerminatorAndMatch(types.name, next)) {
  11060. if (next) this.next();
  11061. return this.tsParseTypeAliasDeclaration(node);
  11062. }
  11063. break;
  11064. }
  11065. }
  11066. tsCheckLineTerminatorAndMatch(tokenType, next) {
  11067. return (next || this.match(tokenType)) && !this.isLineTerminator();
  11068. }
  11069. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  11070. if (!this.isRelational("<")) {
  11071. return undefined;
  11072. }
  11073. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  11074. this.state.maybeInArrowParameters = true;
  11075. const res = this.tsTryParseAndCatch(() => {
  11076. const node = this.startNodeAt(startPos, startLoc);
  11077. node.typeParameters = this.tsParseTypeParameters();
  11078. super.parseFunctionParams(node);
  11079. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  11080. this.expect(types.arrow);
  11081. return node;
  11082. });
  11083. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  11084. if (!res) {
  11085. return undefined;
  11086. }
  11087. return this.parseArrowExpression(res, null, true);
  11088. }
  11089. tsParseTypeArguments() {
  11090. const node = this.startNode();
  11091. node.params = this.tsInType(() => this.tsInNoContext(() => {
  11092. this.expectRelational("<");
  11093. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  11094. }));
  11095. if (node.params.length === 0) {
  11096. this.raise(node.start, TSErrors.EmptyTypeArguments);
  11097. }
  11098. this.state.exprAllowed = false;
  11099. this.expectRelational(">");
  11100. return this.finishNode(node, "TSTypeParameterInstantiation");
  11101. }
  11102. tsIsDeclarationStart() {
  11103. if (this.match(types.name)) {
  11104. switch (this.state.value) {
  11105. case "abstract":
  11106. case "declare":
  11107. case "enum":
  11108. case "interface":
  11109. case "module":
  11110. case "namespace":
  11111. case "type":
  11112. return true;
  11113. }
  11114. }
  11115. return false;
  11116. }
  11117. isExportDefaultSpecifier() {
  11118. if (this.tsIsDeclarationStart()) return false;
  11119. return super.isExportDefaultSpecifier();
  11120. }
  11121. parseAssignableListItem(allowModifiers, decorators) {
  11122. const startPos = this.state.start;
  11123. const startLoc = this.state.startLoc;
  11124. let accessibility;
  11125. let readonly = false;
  11126. if (allowModifiers !== undefined) {
  11127. accessibility = this.parseAccessModifier();
  11128. readonly = !!this.tsParseModifier(["readonly"]);
  11129. if (allowModifiers === false && (accessibility || readonly)) {
  11130. this.raise(startPos, TSErrors.UnexpectedParameterModifier);
  11131. }
  11132. }
  11133. const left = this.parseMaybeDefault();
  11134. this.parseAssignableListItemTypes(left);
  11135. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  11136. if (accessibility || readonly) {
  11137. const pp = this.startNodeAt(startPos, startLoc);
  11138. if (decorators.length) {
  11139. pp.decorators = decorators;
  11140. }
  11141. if (accessibility) pp.accessibility = accessibility;
  11142. if (readonly) pp.readonly = readonly;
  11143. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  11144. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  11145. }
  11146. pp.parameter = elt;
  11147. return this.finishNode(pp, "TSParameterProperty");
  11148. }
  11149. if (decorators.length) {
  11150. left.decorators = decorators;
  11151. }
  11152. return elt;
  11153. }
  11154. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  11155. if (this.match(types.colon)) {
  11156. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  11157. }
  11158. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  11159. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  11160. this.finishNode(node, bodilessType);
  11161. return;
  11162. }
  11163. if (bodilessType === "TSDeclareFunction" && this.state.isDeclareContext) {
  11164. this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
  11165. if (node.declare) {
  11166. super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  11167. return;
  11168. }
  11169. }
  11170. super.parseFunctionBodyAndFinish(node, type, isMethod);
  11171. }
  11172. registerFunctionStatementId(node) {
  11173. if (!node.body && node.id) {
  11174. this.checkLVal(node.id, "function name", BIND_TS_AMBIENT);
  11175. } else {
  11176. super.registerFunctionStatementId(...arguments);
  11177. }
  11178. }
  11179. tsCheckForInvalidTypeCasts(items) {
  11180. items.forEach(node => {
  11181. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  11182. this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
  11183. }
  11184. });
  11185. }
  11186. toReferencedList(exprList, isInParens) {
  11187. this.tsCheckForInvalidTypeCasts(exprList);
  11188. return exprList;
  11189. }
  11190. parseArrayLike(...args) {
  11191. const node = super.parseArrayLike(...args);
  11192. if (node.type === "ArrayExpression") {
  11193. this.tsCheckForInvalidTypeCasts(node.elements);
  11194. }
  11195. return node;
  11196. }
  11197. parseSubscript(base, startPos, startLoc, noCalls, state) {
  11198. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  11199. this.state.exprAllowed = false;
  11200. this.next();
  11201. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  11202. nonNullExpression.expression = base;
  11203. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  11204. }
  11205. if (this.isRelational("<")) {
  11206. const result = this.tsTryParseAndCatch(() => {
  11207. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  11208. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  11209. if (asyncArrowFn) {
  11210. return asyncArrowFn;
  11211. }
  11212. }
  11213. const node = this.startNodeAt(startPos, startLoc);
  11214. node.callee = base;
  11215. const typeArguments = this.tsParseTypeArguments();
  11216. if (typeArguments) {
  11217. if (!noCalls && this.eat(types.parenL)) {
  11218. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  11219. this.tsCheckForInvalidTypeCasts(node.arguments);
  11220. node.typeParameters = typeArguments;
  11221. return this.finishCallExpression(node, state.optionalChainMember);
  11222. } else if (this.match(types.backQuote)) {
  11223. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  11224. result.typeParameters = typeArguments;
  11225. return result;
  11226. }
  11227. }
  11228. this.unexpected();
  11229. });
  11230. if (result) return result;
  11231. }
  11232. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  11233. }
  11234. parseNewArguments(node) {
  11235. if (this.isRelational("<")) {
  11236. const typeParameters = this.tsTryParseAndCatch(() => {
  11237. const args = this.tsParseTypeArguments();
  11238. if (!this.match(types.parenL)) this.unexpected();
  11239. return args;
  11240. });
  11241. if (typeParameters) {
  11242. node.typeParameters = typeParameters;
  11243. }
  11244. }
  11245. super.parseNewArguments(node);
  11246. }
  11247. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  11248. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  11249. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  11250. node.expression = left;
  11251. const _const = this.tsTryNextParseConstantContext();
  11252. if (_const) {
  11253. node.typeAnnotation = _const;
  11254. } else {
  11255. node.typeAnnotation = this.tsNextThenParseType();
  11256. }
  11257. this.finishNode(node, "TSAsExpression");
  11258. this.reScan_lt_gt();
  11259. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  11260. }
  11261. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  11262. }
  11263. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  11264. checkDuplicateExports() {}
  11265. parseImport(node) {
  11266. if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
  11267. const ahead = this.lookahead();
  11268. if (this.match(types.name) && ahead.type === types.eq) {
  11269. return this.tsParseImportEqualsDeclaration(node);
  11270. }
  11271. if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from")) {
  11272. node.importKind = "type";
  11273. this.next();
  11274. }
  11275. }
  11276. if (!node.importKind) {
  11277. node.importKind = "value";
  11278. }
  11279. const importNode = super.parseImport(node);
  11280. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  11281. this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
  11282. }
  11283. return importNode;
  11284. }
  11285. parseExport(node) {
  11286. if (this.match(types._import)) {
  11287. this.expect(types._import);
  11288. return this.tsParseImportEqualsDeclaration(node, true);
  11289. } else if (this.eat(types.eq)) {
  11290. const assign = node;
  11291. assign.expression = this.parseExpression();
  11292. this.semicolon();
  11293. return this.finishNode(assign, "TSExportAssignment");
  11294. } else if (this.eatContextual("as")) {
  11295. const decl = node;
  11296. this.expectContextual("namespace");
  11297. decl.id = this.parseIdentifier();
  11298. this.semicolon();
  11299. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  11300. } else {
  11301. if (this.isContextual("type") && this.lookahead().type === types.braceL) {
  11302. this.next();
  11303. node.exportKind = "type";
  11304. } else {
  11305. node.exportKind = "value";
  11306. }
  11307. return super.parseExport(node);
  11308. }
  11309. }
  11310. isAbstractClass() {
  11311. return this.isContextual("abstract") && this.lookahead().type === types._class;
  11312. }
  11313. parseExportDefaultExpression() {
  11314. if (this.isAbstractClass()) {
  11315. const cls = this.startNode();
  11316. this.next();
  11317. this.parseClass(cls, true, true);
  11318. cls.abstract = true;
  11319. return cls;
  11320. }
  11321. if (this.state.value === "interface") {
  11322. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  11323. if (result) return result;
  11324. }
  11325. return super.parseExportDefaultExpression();
  11326. }
  11327. parseStatementContent(context, topLevel) {
  11328. if (this.state.type === types._const) {
  11329. const ahead = this.lookahead();
  11330. if (ahead.type === types.name && ahead.value === "enum") {
  11331. const node = this.startNode();
  11332. this.expect(types._const);
  11333. this.expectContextual("enum");
  11334. return this.tsParseEnumDeclaration(node, true);
  11335. }
  11336. }
  11337. return super.parseStatementContent(context, topLevel);
  11338. }
  11339. parseAccessModifier() {
  11340. return this.tsParseModifier(["public", "protected", "private"]);
  11341. }
  11342. parseClassMember(classBody, member, state) {
  11343. this.tsParseModifiers(member, ["declare"]);
  11344. const accessibility = this.parseAccessModifier();
  11345. if (accessibility) member.accessibility = accessibility;
  11346. this.tsParseModifiers(member, ["declare"]);
  11347. const callParseClassMember = () => {
  11348. super.parseClassMember(classBody, member, state);
  11349. };
  11350. if (member.declare) {
  11351. this.tsInDeclareContext(callParseClassMember);
  11352. } else {
  11353. callParseClassMember();
  11354. }
  11355. }
  11356. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  11357. this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
  11358. const idx = this.tsTryParseIndexSignature(member);
  11359. if (idx) {
  11360. classBody.body.push(idx);
  11361. if (member.abstract) {
  11362. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  11363. }
  11364. if (isStatic) {
  11365. this.raise(member.start, TSErrors.IndexSignatureHasStatic);
  11366. }
  11367. if (member.accessibility) {
  11368. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  11369. }
  11370. if (member.declare) {
  11371. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  11372. }
  11373. return;
  11374. }
  11375. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  11376. }
  11377. parsePostMemberNameModifiers(methodOrProp) {
  11378. const optional = this.eat(types.question);
  11379. if (optional) methodOrProp.optional = true;
  11380. if (methodOrProp.readonly && this.match(types.parenL)) {
  11381. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  11382. }
  11383. if (methodOrProp.declare && this.match(types.parenL)) {
  11384. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  11385. }
  11386. }
  11387. parseExpressionStatement(node, expr) {
  11388. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  11389. return decl || super.parseExpressionStatement(node, expr);
  11390. }
  11391. shouldParseExportDeclaration() {
  11392. if (this.tsIsDeclarationStart()) return true;
  11393. return super.shouldParseExportDeclaration();
  11394. }
  11395. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  11396. if (!refNeedsArrowPos || !this.match(types.question)) {
  11397. return super.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  11398. }
  11399. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  11400. if (!result.node) {
  11401. refNeedsArrowPos.start = result.error.pos || this.state.start;
  11402. return expr;
  11403. }
  11404. if (result.error) this.state = result.failState;
  11405. return result.node;
  11406. }
  11407. parseParenItem(node, startPos, startLoc) {
  11408. node = super.parseParenItem(node, startPos, startLoc);
  11409. if (this.eat(types.question)) {
  11410. node.optional = true;
  11411. this.resetEndLocation(node);
  11412. }
  11413. if (this.match(types.colon)) {
  11414. const typeCastNode = this.startNodeAt(startPos, startLoc);
  11415. typeCastNode.expression = node;
  11416. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  11417. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  11418. }
  11419. return node;
  11420. }
  11421. parseExportDeclaration(node) {
  11422. const startPos = this.state.start;
  11423. const startLoc = this.state.startLoc;
  11424. const isDeclare = this.eatContextual("declare");
  11425. let declaration;
  11426. if (this.match(types.name)) {
  11427. declaration = this.tsTryParseExportDeclaration();
  11428. }
  11429. if (!declaration) {
  11430. declaration = super.parseExportDeclaration(node);
  11431. }
  11432. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  11433. node.exportKind = "type";
  11434. }
  11435. if (declaration && isDeclare) {
  11436. this.resetStartLocation(declaration, startPos, startLoc);
  11437. declaration.declare = true;
  11438. }
  11439. return declaration;
  11440. }
  11441. parseClassId(node, isStatement, optionalId) {
  11442. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  11443. return;
  11444. }
  11445. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  11446. const typeParameters = this.tsTryParseTypeParameters();
  11447. if (typeParameters) node.typeParameters = typeParameters;
  11448. }
  11449. parseClassPropertyAnnotation(node) {
  11450. if (!node.optional && this.eat(types.bang)) {
  11451. node.definite = true;
  11452. }
  11453. const type = this.tsTryParseTypeAnnotation();
  11454. if (type) node.typeAnnotation = type;
  11455. }
  11456. parseClassProperty(node) {
  11457. this.parseClassPropertyAnnotation(node);
  11458. if (this.state.isDeclareContext && this.match(types.eq)) {
  11459. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  11460. }
  11461. return super.parseClassProperty(node);
  11462. }
  11463. parseClassPrivateProperty(node) {
  11464. if (node.abstract) {
  11465. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  11466. }
  11467. if (node.accessibility) {
  11468. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  11469. }
  11470. this.parseClassPropertyAnnotation(node);
  11471. return super.parseClassPrivateProperty(node);
  11472. }
  11473. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  11474. const typeParameters = this.tsTryParseTypeParameters();
  11475. if (typeParameters && isConstructor) {
  11476. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  11477. }
  11478. if (typeParameters) method.typeParameters = typeParameters;
  11479. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  11480. }
  11481. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  11482. const typeParameters = this.tsTryParseTypeParameters();
  11483. if (typeParameters) method.typeParameters = typeParameters;
  11484. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  11485. }
  11486. parseClassSuper(node) {
  11487. super.parseClassSuper(node);
  11488. if (node.superClass && this.isRelational("<")) {
  11489. node.superTypeParameters = this.tsParseTypeArguments();
  11490. }
  11491. if (this.eatContextual("implements")) {
  11492. node.implements = this.tsParseHeritageClause("implements");
  11493. }
  11494. }
  11495. parseObjPropValue(prop, ...args) {
  11496. const typeParameters = this.tsTryParseTypeParameters();
  11497. if (typeParameters) prop.typeParameters = typeParameters;
  11498. super.parseObjPropValue(prop, ...args);
  11499. }
  11500. parseFunctionParams(node, allowModifiers) {
  11501. const typeParameters = this.tsTryParseTypeParameters();
  11502. if (typeParameters) node.typeParameters = typeParameters;
  11503. super.parseFunctionParams(node, allowModifiers);
  11504. }
  11505. parseVarId(decl, kind) {
  11506. super.parseVarId(decl, kind);
  11507. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  11508. decl.definite = true;
  11509. }
  11510. const type = this.tsTryParseTypeAnnotation();
  11511. if (type) {
  11512. decl.id.typeAnnotation = type;
  11513. this.resetEndLocation(decl.id);
  11514. }
  11515. }
  11516. parseAsyncArrowFromCallExpression(node, call) {
  11517. if (this.match(types.colon)) {
  11518. node.returnType = this.tsParseTypeAnnotation();
  11519. }
  11520. return super.parseAsyncArrowFromCallExpression(node, call);
  11521. }
  11522. parseMaybeAssign(...args) {
  11523. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  11524. let state;
  11525. let jsx;
  11526. let typeCast;
  11527. if (this.match(types.jsxTagStart)) {
  11528. state = this.state.clone();
  11529. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  11530. if (!jsx.error) return jsx.node;
  11531. const {
  11532. context
  11533. } = this.state;
  11534. if (context[context.length - 1] === types$1.j_oTag) {
  11535. context.length -= 2;
  11536. } else if (context[context.length - 1] === types$1.j_expr) {
  11537. context.length -= 1;
  11538. }
  11539. }
  11540. if (!((_jsx = jsx) == null ? void 0 : _jsx.error) && !this.isRelational("<")) {
  11541. return super.parseMaybeAssign(...args);
  11542. }
  11543. let typeParameters;
  11544. state = state || this.state.clone();
  11545. const arrow = this.tryParse(abort => {
  11546. var _typeParameters;
  11547. typeParameters = this.tsParseTypeParameters();
  11548. const expr = super.parseMaybeAssign(...args);
  11549. if (expr.type !== "ArrowFunctionExpression" || expr.extra && expr.extra.parenthesized) {
  11550. abort();
  11551. }
  11552. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  11553. this.resetStartLocationFromNode(expr, typeParameters);
  11554. }
  11555. expr.typeParameters = typeParameters;
  11556. return expr;
  11557. }, state);
  11558. if (!arrow.error && !arrow.aborted) return arrow.node;
  11559. if (!jsx) {
  11560. assert$1(!this.hasPlugin("jsx"));
  11561. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  11562. if (!typeCast.error) return typeCast.node;
  11563. }
  11564. if ((_jsx2 = jsx) == null ? void 0 : _jsx2.node) {
  11565. this.state = jsx.failState;
  11566. return jsx.node;
  11567. }
  11568. if (arrow.node) {
  11569. this.state = arrow.failState;
  11570. return arrow.node;
  11571. }
  11572. if ((_typeCast = typeCast) == null ? void 0 : _typeCast.node) {
  11573. this.state = typeCast.failState;
  11574. return typeCast.node;
  11575. }
  11576. if ((_jsx3 = jsx) == null ? void 0 : _jsx3.thrown) throw jsx.error;
  11577. if (arrow.thrown) throw arrow.error;
  11578. if ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.thrown) throw typeCast.error;
  11579. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  11580. }
  11581. parseMaybeUnary(refExpressionErrors) {
  11582. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  11583. return this.tsParseTypeAssertion();
  11584. } else {
  11585. return super.parseMaybeUnary(refExpressionErrors);
  11586. }
  11587. }
  11588. parseArrow(node) {
  11589. if (this.match(types.colon)) {
  11590. const result = this.tryParse(abort => {
  11591. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  11592. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  11593. return returnType;
  11594. });
  11595. if (result.aborted) return;
  11596. if (!result.thrown) {
  11597. if (result.error) this.state = result.failState;
  11598. node.returnType = result.node;
  11599. }
  11600. }
  11601. return super.parseArrow(node);
  11602. }
  11603. parseAssignableListItemTypes(param) {
  11604. if (this.eat(types.question)) {
  11605. if (param.type !== "Identifier" && !this.state.isDeclareContext && !this.state.inType) {
  11606. this.raise(param.start, TSErrors.PatternIsOptional);
  11607. }
  11608. param.optional = true;
  11609. }
  11610. const type = this.tsTryParseTypeAnnotation();
  11611. if (type) param.typeAnnotation = type;
  11612. this.resetEndLocation(param);
  11613. return param;
  11614. }
  11615. toAssignable(node, isLHS = false) {
  11616. switch (node.type) {
  11617. case "TSTypeCastExpression":
  11618. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  11619. case "TSParameterProperty":
  11620. return super.toAssignable(node, isLHS);
  11621. case "TSAsExpression":
  11622. case "TSNonNullExpression":
  11623. case "TSTypeAssertion":
  11624. node.expression = this.toAssignable(node.expression, isLHS);
  11625. return node;
  11626. default:
  11627. return super.toAssignable(node, isLHS);
  11628. }
  11629. }
  11630. checkLVal(expr, contextDescription, ...args) {
  11631. switch (expr.type) {
  11632. case "TSTypeCastExpression":
  11633. return;
  11634. case "TSParameterProperty":
  11635. this.checkLVal(expr.parameter, "parameter property", ...args);
  11636. return;
  11637. case "TSAsExpression":
  11638. case "TSNonNullExpression":
  11639. case "TSTypeAssertion":
  11640. this.checkLVal(expr.expression, contextDescription, ...args);
  11641. return;
  11642. default:
  11643. super.checkLVal(expr, contextDescription, ...args);
  11644. return;
  11645. }
  11646. }
  11647. parseBindingAtom() {
  11648. switch (this.state.type) {
  11649. case types._this:
  11650. return this.parseIdentifier(true);
  11651. default:
  11652. return super.parseBindingAtom();
  11653. }
  11654. }
  11655. parseMaybeDecoratorArguments(expr) {
  11656. if (this.isRelational("<")) {
  11657. const typeArguments = this.tsParseTypeArguments();
  11658. if (this.match(types.parenL)) {
  11659. const call = super.parseMaybeDecoratorArguments(expr);
  11660. call.typeParameters = typeArguments;
  11661. return call;
  11662. }
  11663. this.unexpected(this.state.start, types.parenL);
  11664. }
  11665. return super.parseMaybeDecoratorArguments(expr);
  11666. }
  11667. isClassMethod() {
  11668. return this.isRelational("<") || super.isClassMethod();
  11669. }
  11670. isClassProperty() {
  11671. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  11672. }
  11673. parseMaybeDefault(...args) {
  11674. const node = super.parseMaybeDefault(...args);
  11675. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  11676. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  11677. }
  11678. return node;
  11679. }
  11680. getTokenFromCode(code) {
  11681. if (this.state.inType && (code === 62 || code === 60)) {
  11682. return this.finishOp(types.relational, 1);
  11683. } else {
  11684. return super.getTokenFromCode(code);
  11685. }
  11686. }
  11687. reScan_lt_gt() {
  11688. if (this.match(types.relational)) {
  11689. const code = this.input.charCodeAt(this.state.start);
  11690. if (code === 60 || code === 62) {
  11691. this.state.pos -= 1;
  11692. this.readToken_lt_gt(code);
  11693. }
  11694. }
  11695. }
  11696. toAssignableList(exprList) {
  11697. for (let i = 0; i < exprList.length; i++) {
  11698. const expr = exprList[i];
  11699. if (!expr) continue;
  11700. switch (expr.type) {
  11701. case "TSTypeCastExpression":
  11702. exprList[i] = this.typeCastToParameter(expr);
  11703. break;
  11704. case "TSAsExpression":
  11705. case "TSTypeAssertion":
  11706. if (!this.state.maybeInArrowParameters) {
  11707. exprList[i] = this.typeCastToParameter(expr);
  11708. } else {
  11709. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  11710. }
  11711. break;
  11712. }
  11713. }
  11714. return super.toAssignableList(...arguments);
  11715. }
  11716. typeCastToParameter(node) {
  11717. node.expression.typeAnnotation = node.typeAnnotation;
  11718. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  11719. return node.expression;
  11720. }
  11721. shouldParseArrow() {
  11722. return this.match(types.colon) || super.shouldParseArrow();
  11723. }
  11724. shouldParseAsyncArrow() {
  11725. return this.match(types.colon) || super.shouldParseAsyncArrow();
  11726. }
  11727. canHaveLeadingDecorator() {
  11728. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  11729. }
  11730. jsxParseOpeningElementAfterName(node) {
  11731. if (this.isRelational("<")) {
  11732. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  11733. if (typeArguments) node.typeParameters = typeArguments;
  11734. }
  11735. return super.jsxParseOpeningElementAfterName(node);
  11736. }
  11737. getGetterSetterExpectedParamCount(method) {
  11738. const baseCount = super.getGetterSetterExpectedParamCount(method);
  11739. const params = this.getObjectOrClassMethodParams(method);
  11740. const firstParam = params[0];
  11741. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  11742. return hasContextParam ? baseCount + 1 : baseCount;
  11743. }
  11744. parseCatchClauseParam() {
  11745. const param = super.parseCatchClauseParam();
  11746. const type = this.tsTryParseTypeAnnotation();
  11747. if (type) {
  11748. param.typeAnnotation = type;
  11749. this.resetEndLocation(param);
  11750. }
  11751. return param;
  11752. }
  11753. tsInDeclareContext(cb) {
  11754. const oldIsDeclareContext = this.state.isDeclareContext;
  11755. this.state.isDeclareContext = true;
  11756. try {
  11757. return cb();
  11758. } finally {
  11759. this.state.isDeclareContext = oldIsDeclareContext;
  11760. }
  11761. }
  11762. });
  11763. types.placeholder = new TokenType("%%", {
  11764. startsExpr: true
  11765. });
  11766. var placeholders = (superClass => class extends superClass {
  11767. parsePlaceholder(expectedNode) {
  11768. if (this.match(types.placeholder)) {
  11769. const node = this.startNode();
  11770. this.next();
  11771. this.assertNoSpace("Unexpected space in placeholder.");
  11772. node.name = super.parseIdentifier(true);
  11773. this.assertNoSpace("Unexpected space in placeholder.");
  11774. this.expect(types.placeholder);
  11775. return this.finishPlaceholder(node, expectedNode);
  11776. }
  11777. }
  11778. finishPlaceholder(node, expectedNode) {
  11779. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  11780. node.expectedNode = expectedNode;
  11781. return isFinished ? node : this.finishNode(node, "Placeholder");
  11782. }
  11783. getTokenFromCode(code) {
  11784. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  11785. return this.finishOp(types.placeholder, 2);
  11786. }
  11787. return super.getTokenFromCode(...arguments);
  11788. }
  11789. parseExprAtom() {
  11790. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  11791. }
  11792. parseIdentifier() {
  11793. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  11794. }
  11795. checkReservedWord(word) {
  11796. if (word !== undefined) super.checkReservedWord(...arguments);
  11797. }
  11798. parseBindingAtom() {
  11799. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  11800. }
  11801. checkLVal(expr) {
  11802. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  11803. }
  11804. toAssignable(node) {
  11805. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  11806. node.expectedNode = "Pattern";
  11807. return node;
  11808. }
  11809. return super.toAssignable(...arguments);
  11810. }
  11811. verifyBreakContinue(node) {
  11812. if (node.label && node.label.type === "Placeholder") return;
  11813. super.verifyBreakContinue(...arguments);
  11814. }
  11815. parseExpressionStatement(node, expr) {
  11816. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  11817. return super.parseExpressionStatement(...arguments);
  11818. }
  11819. if (this.match(types.colon)) {
  11820. const stmt = node;
  11821. stmt.label = this.finishPlaceholder(expr, "Identifier");
  11822. this.next();
  11823. stmt.body = this.parseStatement("label");
  11824. return this.finishNode(stmt, "LabeledStatement");
  11825. }
  11826. this.semicolon();
  11827. node.name = expr.name;
  11828. return this.finishPlaceholder(node, "Statement");
  11829. }
  11830. parseBlock() {
  11831. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  11832. }
  11833. parseFunctionId() {
  11834. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  11835. }
  11836. parseClass(node, isStatement, optionalId) {
  11837. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  11838. this.next();
  11839. this.takeDecorators(node);
  11840. const oldStrict = this.state.strict;
  11841. const placeholder = this.parsePlaceholder("Identifier");
  11842. if (placeholder) {
  11843. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  11844. node.id = placeholder;
  11845. } else if (optionalId || !isStatement) {
  11846. node.id = null;
  11847. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  11848. return this.finishNode(node, type);
  11849. } else {
  11850. this.unexpected(null, "A class name is required");
  11851. }
  11852. } else {
  11853. this.parseClassId(node, isStatement, optionalId);
  11854. }
  11855. this.parseClassSuper(node);
  11856. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  11857. return this.finishNode(node, type);
  11858. }
  11859. parseExport(node) {
  11860. const placeholder = this.parsePlaceholder("Identifier");
  11861. if (!placeholder) return super.parseExport(...arguments);
  11862. if (!this.isContextual("from") && !this.match(types.comma)) {
  11863. node.specifiers = [];
  11864. node.source = null;
  11865. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  11866. return this.finishNode(node, "ExportNamedDeclaration");
  11867. }
  11868. this.expectPlugin("exportDefaultFrom");
  11869. const specifier = this.startNode();
  11870. specifier.exported = placeholder;
  11871. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  11872. return super.parseExport(node);
  11873. }
  11874. isExportDefaultSpecifier() {
  11875. if (this.match(types._default)) {
  11876. const next = this.nextTokenStart();
  11877. if (this.isUnparsedContextual(next, "from")) {
  11878. if (this.input.startsWith(types.placeholder.label, this.nextTokenStartSince(next + 4))) {
  11879. return true;
  11880. }
  11881. }
  11882. }
  11883. return super.isExportDefaultSpecifier();
  11884. }
  11885. maybeParseExportDefaultSpecifier(node) {
  11886. if (node.specifiers && node.specifiers.length > 0) {
  11887. return true;
  11888. }
  11889. return super.maybeParseExportDefaultSpecifier(...arguments);
  11890. }
  11891. checkExport(node) {
  11892. const {
  11893. specifiers
  11894. } = node;
  11895. if (specifiers == null ? void 0 : specifiers.length) {
  11896. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  11897. }
  11898. super.checkExport(node);
  11899. node.specifiers = specifiers;
  11900. }
  11901. parseImport(node) {
  11902. const placeholder = this.parsePlaceholder("Identifier");
  11903. if (!placeholder) return super.parseImport(...arguments);
  11904. node.specifiers = [];
  11905. if (!this.isContextual("from") && !this.match(types.comma)) {
  11906. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  11907. this.semicolon();
  11908. return this.finishNode(node, "ImportDeclaration");
  11909. }
  11910. const specifier = this.startNodeAtNode(placeholder);
  11911. specifier.local = placeholder;
  11912. this.finishNode(specifier, "ImportDefaultSpecifier");
  11913. node.specifiers.push(specifier);
  11914. if (this.eat(types.comma)) {
  11915. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  11916. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  11917. }
  11918. this.expectContextual("from");
  11919. node.source = this.parseImportSource();
  11920. this.semicolon();
  11921. return this.finishNode(node, "ImportDeclaration");
  11922. }
  11923. parseImportSource() {
  11924. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  11925. }
  11926. });
  11927. var v8intrinsic = (superClass => class extends superClass {
  11928. parseV8Intrinsic() {
  11929. if (this.match(types.modulo)) {
  11930. const v8IntrinsicStart = this.state.start;
  11931. const node = this.startNode();
  11932. this.eat(types.modulo);
  11933. if (this.match(types.name)) {
  11934. const name = this.parseIdentifierName(this.state.start);
  11935. const identifier = this.createIdentifier(node, name);
  11936. identifier.type = "V8IntrinsicIdentifier";
  11937. if (this.match(types.parenL)) {
  11938. return identifier;
  11939. }
  11940. }
  11941. this.unexpected(v8IntrinsicStart);
  11942. }
  11943. }
  11944. parseExprAtom() {
  11945. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  11946. }
  11947. });
  11948. function hasPlugin(plugins, name) {
  11949. return plugins.some(plugin => {
  11950. if (Array.isArray(plugin)) {
  11951. return plugin[0] === name;
  11952. } else {
  11953. return plugin === name;
  11954. }
  11955. });
  11956. }
  11957. function getPluginOption(plugins, name, option) {
  11958. const plugin = plugins.find(plugin => {
  11959. if (Array.isArray(plugin)) {
  11960. return plugin[0] === name;
  11961. } else {
  11962. return plugin === name;
  11963. }
  11964. });
  11965. if (plugin && Array.isArray(plugin)) {
  11966. return plugin[1][option];
  11967. }
  11968. return null;
  11969. }
  11970. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  11971. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  11972. function validatePlugins(plugins) {
  11973. if (hasPlugin(plugins, "decorators")) {
  11974. if (hasPlugin(plugins, "decorators-legacy")) {
  11975. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  11976. }
  11977. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  11978. if (decoratorsBeforeExport == null) {
  11979. 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'.");
  11980. } else if (typeof decoratorsBeforeExport !== "boolean") {
  11981. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  11982. }
  11983. }
  11984. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  11985. throw new Error("Cannot combine flow and typescript plugins.");
  11986. }
  11987. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  11988. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  11989. }
  11990. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  11991. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  11992. }
  11993. if (hasPlugin(plugins, "moduleAttributes")) {
  11994. if (hasPlugin(plugins, "importAssertions")) {
  11995. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  11996. }
  11997. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  11998. if (moduleAttributesVerionPluginOption !== "may-2020") {
  11999. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  12000. }
  12001. }
  12002. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  12003. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  12004. }
  12005. }
  12006. const mixinPlugins = {
  12007. estree,
  12008. jsx,
  12009. flow,
  12010. typescript,
  12011. v8intrinsic,
  12012. placeholders
  12013. };
  12014. const mixinPluginNames = Object.keys(mixinPlugins);
  12015. const defaultOptions = {
  12016. sourceType: "script",
  12017. sourceFilename: undefined,
  12018. startLine: 1,
  12019. allowAwaitOutsideFunction: false,
  12020. allowReturnOutsideFunction: false,
  12021. allowImportExportEverywhere: false,
  12022. allowSuperOutsideMethod: false,
  12023. allowUndeclaredExports: false,
  12024. plugins: [],
  12025. strictMode: null,
  12026. ranges: false,
  12027. tokens: false,
  12028. createParenthesizedExpressions: false,
  12029. errorRecovery: false
  12030. };
  12031. function getOptions(opts) {
  12032. const options = {};
  12033. for (let _i = 0, _Object$keys = Object.keys(defaultOptions); _i < _Object$keys.length; _i++) {
  12034. const key = _Object$keys[_i];
  12035. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  12036. }
  12037. return options;
  12038. }
  12039. class State {
  12040. constructor() {
  12041. this.strict = void 0;
  12042. this.curLine = void 0;
  12043. this.startLoc = void 0;
  12044. this.endLoc = void 0;
  12045. this.errors = [];
  12046. this.potentialArrowAt = -1;
  12047. this.noArrowAt = [];
  12048. this.noArrowParamsConversionAt = [];
  12049. this.maybeInArrowParameters = false;
  12050. this.inPipeline = false;
  12051. this.inType = false;
  12052. this.noAnonFunctionType = false;
  12053. this.inPropertyName = false;
  12054. this.hasFlowComment = false;
  12055. this.isIterator = false;
  12056. this.isDeclareContext = false;
  12057. this.topicContext = {
  12058. maxNumOfResolvableTopics: 0,
  12059. maxTopicIndex: null
  12060. };
  12061. this.soloAwait = false;
  12062. this.inFSharpPipelineDirectBody = false;
  12063. this.labels = [];
  12064. this.decoratorStack = [[]];
  12065. this.comments = [];
  12066. this.trailingComments = [];
  12067. this.leadingComments = [];
  12068. this.commentStack = [];
  12069. this.commentPreviousNode = null;
  12070. this.pos = 0;
  12071. this.lineStart = 0;
  12072. this.type = types.eof;
  12073. this.value = null;
  12074. this.start = 0;
  12075. this.end = 0;
  12076. this.lastTokEndLoc = null;
  12077. this.lastTokStartLoc = null;
  12078. this.lastTokStart = 0;
  12079. this.lastTokEnd = 0;
  12080. this.context = [types$1.braceStatement];
  12081. this.exprAllowed = true;
  12082. this.containsEsc = false;
  12083. this.octalPositions = [];
  12084. this.exportedIdentifiers = [];
  12085. this.tokensLength = 0;
  12086. }
  12087. init(options) {
  12088. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  12089. this.curLine = options.startLine;
  12090. this.startLoc = this.endLoc = this.curPosition();
  12091. }
  12092. curPosition() {
  12093. return new Position(this.curLine, this.pos - this.lineStart);
  12094. }
  12095. clone(skipArrays) {
  12096. const state = new State();
  12097. const keys = Object.keys(this);
  12098. for (let i = 0, length = keys.length; i < length; i++) {
  12099. const key = keys[i];
  12100. let val = this[key];
  12101. if (!skipArrays && Array.isArray(val)) {
  12102. val = val.slice();
  12103. }
  12104. state[key] = val;
  12105. }
  12106. return state;
  12107. }
  12108. }
  12109. var _isDigit = function isDigit(code) {
  12110. return code >= 48 && code <= 57;
  12111. };
  12112. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  12113. const forbiddenNumericSeparatorSiblings = {
  12114. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  12115. hex: [46, 88, 95, 120]
  12116. };
  12117. const allowedNumericSeparatorSiblings = {};
  12118. allowedNumericSeparatorSiblings.bin = [48, 49];
  12119. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  12120. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  12121. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  12122. class Token {
  12123. constructor(state) {
  12124. this.type = state.type;
  12125. this.value = state.value;
  12126. this.start = state.start;
  12127. this.end = state.end;
  12128. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  12129. }
  12130. }
  12131. class Tokenizer extends ParserError {
  12132. constructor(options, input) {
  12133. super();
  12134. this.isLookahead = void 0;
  12135. this.tokens = [];
  12136. this.state = new State();
  12137. this.state.init(options);
  12138. this.input = input;
  12139. this.length = input.length;
  12140. this.isLookahead = false;
  12141. }
  12142. pushToken(token) {
  12143. this.tokens.length = this.state.tokensLength;
  12144. this.tokens.push(token);
  12145. ++this.state.tokensLength;
  12146. }
  12147. next() {
  12148. if (!this.isLookahead) {
  12149. this.checkKeywordEscapes();
  12150. if (this.options.tokens) {
  12151. this.pushToken(new Token(this.state));
  12152. }
  12153. }
  12154. this.state.lastTokEnd = this.state.end;
  12155. this.state.lastTokStart = this.state.start;
  12156. this.state.lastTokEndLoc = this.state.endLoc;
  12157. this.state.lastTokStartLoc = this.state.startLoc;
  12158. this.nextToken();
  12159. }
  12160. eat(type) {
  12161. if (this.match(type)) {
  12162. this.next();
  12163. return true;
  12164. } else {
  12165. return false;
  12166. }
  12167. }
  12168. match(type) {
  12169. return this.state.type === type;
  12170. }
  12171. lookahead() {
  12172. const old = this.state;
  12173. this.state = old.clone(true);
  12174. this.isLookahead = true;
  12175. this.next();
  12176. this.isLookahead = false;
  12177. const curr = this.state;
  12178. this.state = old;
  12179. return curr;
  12180. }
  12181. nextTokenStart() {
  12182. return this.nextTokenStartSince(this.state.pos);
  12183. }
  12184. nextTokenStartSince(pos) {
  12185. skipWhiteSpace.lastIndex = pos;
  12186. const skip = skipWhiteSpace.exec(this.input);
  12187. return pos + skip[0].length;
  12188. }
  12189. lookaheadCharCode() {
  12190. return this.input.charCodeAt(this.nextTokenStart());
  12191. }
  12192. setStrict(strict) {
  12193. this.state.strict = strict;
  12194. if (!this.match(types.num) && !this.match(types.string)) return;
  12195. this.state.pos = this.state.start;
  12196. while (this.state.pos < this.state.lineStart) {
  12197. this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1;
  12198. --this.state.curLine;
  12199. }
  12200. this.nextToken();
  12201. }
  12202. curContext() {
  12203. return this.state.context[this.state.context.length - 1];
  12204. }
  12205. nextToken() {
  12206. const curContext = this.curContext();
  12207. if (!(curContext == null ? void 0 : curContext.preserveSpace)) this.skipSpace();
  12208. this.state.octalPositions = [];
  12209. this.state.start = this.state.pos;
  12210. this.state.startLoc = this.state.curPosition();
  12211. if (this.state.pos >= this.length) {
  12212. this.finishToken(types.eof);
  12213. return;
  12214. }
  12215. const override = curContext == null ? void 0 : curContext.override;
  12216. if (override) {
  12217. override(this);
  12218. } else {
  12219. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  12220. }
  12221. }
  12222. pushComment(block, text, start, end, startLoc, endLoc) {
  12223. const comment = {
  12224. type: block ? "CommentBlock" : "CommentLine",
  12225. value: text,
  12226. start: start,
  12227. end: end,
  12228. loc: new SourceLocation(startLoc, endLoc)
  12229. };
  12230. if (this.options.tokens) this.pushToken(comment);
  12231. this.state.comments.push(comment);
  12232. this.addComment(comment);
  12233. }
  12234. skipBlockComment() {
  12235. const startLoc = this.state.curPosition();
  12236. const start = this.state.pos;
  12237. const end = this.input.indexOf("*/", this.state.pos + 2);
  12238. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  12239. this.state.pos = end + 2;
  12240. lineBreakG.lastIndex = start;
  12241. let match;
  12242. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  12243. ++this.state.curLine;
  12244. this.state.lineStart = match.index + match[0].length;
  12245. }
  12246. if (this.isLookahead) return;
  12247. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  12248. }
  12249. skipLineComment(startSkip) {
  12250. const start = this.state.pos;
  12251. const startLoc = this.state.curPosition();
  12252. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  12253. if (this.state.pos < this.length) {
  12254. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  12255. ch = this.input.charCodeAt(this.state.pos);
  12256. }
  12257. }
  12258. if (this.isLookahead) return;
  12259. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  12260. }
  12261. skipSpace() {
  12262. loop: while (this.state.pos < this.length) {
  12263. const ch = this.input.charCodeAt(this.state.pos);
  12264. switch (ch) {
  12265. case 32:
  12266. case 160:
  12267. case 9:
  12268. ++this.state.pos;
  12269. break;
  12270. case 13:
  12271. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  12272. ++this.state.pos;
  12273. }
  12274. case 10:
  12275. case 8232:
  12276. case 8233:
  12277. ++this.state.pos;
  12278. ++this.state.curLine;
  12279. this.state.lineStart = this.state.pos;
  12280. break;
  12281. case 47:
  12282. switch (this.input.charCodeAt(this.state.pos + 1)) {
  12283. case 42:
  12284. this.skipBlockComment();
  12285. break;
  12286. case 47:
  12287. this.skipLineComment(2);
  12288. break;
  12289. default:
  12290. break loop;
  12291. }
  12292. break;
  12293. default:
  12294. if (isWhitespace(ch)) {
  12295. ++this.state.pos;
  12296. } else {
  12297. break loop;
  12298. }
  12299. }
  12300. }
  12301. }
  12302. finishToken(type, val) {
  12303. this.state.end = this.state.pos;
  12304. this.state.endLoc = this.state.curPosition();
  12305. const prevType = this.state.type;
  12306. this.state.type = type;
  12307. this.state.value = val;
  12308. if (!this.isLookahead) this.updateContext(prevType);
  12309. }
  12310. readToken_numberSign() {
  12311. if (this.state.pos === 0 && this.readToken_interpreter()) {
  12312. return;
  12313. }
  12314. const nextPos = this.state.pos + 1;
  12315. const next = this.input.charCodeAt(nextPos);
  12316. if (next >= 48 && next <= 57) {
  12317. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  12318. }
  12319. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  12320. this.expectPlugin("recordAndTuple");
  12321. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  12322. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  12323. }
  12324. if (next === 123) {
  12325. this.finishToken(types.braceHashL);
  12326. } else {
  12327. this.finishToken(types.bracketHashL);
  12328. }
  12329. this.state.pos += 2;
  12330. } else {
  12331. this.finishOp(types.hash, 1);
  12332. }
  12333. }
  12334. readToken_dot() {
  12335. const next = this.input.charCodeAt(this.state.pos + 1);
  12336. if (next >= 48 && next <= 57) {
  12337. this.readNumber(true);
  12338. return;
  12339. }
  12340. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  12341. this.state.pos += 3;
  12342. this.finishToken(types.ellipsis);
  12343. } else {
  12344. ++this.state.pos;
  12345. this.finishToken(types.dot);
  12346. }
  12347. }
  12348. readToken_slash() {
  12349. if (this.state.exprAllowed && !this.state.inType) {
  12350. ++this.state.pos;
  12351. this.readRegexp();
  12352. return;
  12353. }
  12354. const next = this.input.charCodeAt(this.state.pos + 1);
  12355. if (next === 61) {
  12356. this.finishOp(types.assign, 2);
  12357. } else {
  12358. this.finishOp(types.slash, 1);
  12359. }
  12360. }
  12361. readToken_interpreter() {
  12362. if (this.state.pos !== 0 || this.length < 2) return false;
  12363. let ch = this.input.charCodeAt(this.state.pos + 1);
  12364. if (ch !== 33) return false;
  12365. const start = this.state.pos;
  12366. this.state.pos += 1;
  12367. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  12368. ch = this.input.charCodeAt(this.state.pos);
  12369. }
  12370. const value = this.input.slice(start + 2, this.state.pos);
  12371. this.finishToken(types.interpreterDirective, value);
  12372. return true;
  12373. }
  12374. readToken_mult_modulo(code) {
  12375. let type = code === 42 ? types.star : types.modulo;
  12376. let width = 1;
  12377. let next = this.input.charCodeAt(this.state.pos + 1);
  12378. const exprAllowed = this.state.exprAllowed;
  12379. if (code === 42 && next === 42) {
  12380. width++;
  12381. next = this.input.charCodeAt(this.state.pos + 2);
  12382. type = types.exponent;
  12383. }
  12384. if (next === 61 && !exprAllowed) {
  12385. width++;
  12386. type = types.assign;
  12387. }
  12388. this.finishOp(type, width);
  12389. }
  12390. readToken_pipe_amp(code) {
  12391. const next = this.input.charCodeAt(this.state.pos + 1);
  12392. if (next === code) {
  12393. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  12394. this.finishOp(types.assign, 3);
  12395. } else {
  12396. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  12397. }
  12398. return;
  12399. }
  12400. if (code === 124) {
  12401. if (next === 62) {
  12402. this.finishOp(types.pipeline, 2);
  12403. return;
  12404. }
  12405. if (this.hasPlugin("recordAndTuple") && next === 125) {
  12406. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  12407. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  12408. }
  12409. this.finishOp(types.braceBarR, 2);
  12410. return;
  12411. }
  12412. if (this.hasPlugin("recordAndTuple") && next === 93) {
  12413. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  12414. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  12415. }
  12416. this.finishOp(types.bracketBarR, 2);
  12417. return;
  12418. }
  12419. }
  12420. if (next === 61) {
  12421. this.finishOp(types.assign, 2);
  12422. return;
  12423. }
  12424. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  12425. }
  12426. readToken_caret() {
  12427. const next = this.input.charCodeAt(this.state.pos + 1);
  12428. if (next === 61) {
  12429. this.finishOp(types.assign, 2);
  12430. } else {
  12431. this.finishOp(types.bitwiseXOR, 1);
  12432. }
  12433. }
  12434. readToken_plus_min(code) {
  12435. const next = this.input.charCodeAt(this.state.pos + 1);
  12436. if (next === code) {
  12437. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || this.hasPrecedingLineBreak())) {
  12438. this.skipLineComment(3);
  12439. this.skipSpace();
  12440. this.nextToken();
  12441. return;
  12442. }
  12443. this.finishOp(types.incDec, 2);
  12444. return;
  12445. }
  12446. if (next === 61) {
  12447. this.finishOp(types.assign, 2);
  12448. } else {
  12449. this.finishOp(types.plusMin, 1);
  12450. }
  12451. }
  12452. readToken_lt_gt(code) {
  12453. const next = this.input.charCodeAt(this.state.pos + 1);
  12454. let size = 1;
  12455. if (next === code) {
  12456. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  12457. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  12458. this.finishOp(types.assign, size + 1);
  12459. return;
  12460. }
  12461. this.finishOp(types.bitShift, size);
  12462. return;
  12463. }
  12464. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  12465. this.skipLineComment(4);
  12466. this.skipSpace();
  12467. this.nextToken();
  12468. return;
  12469. }
  12470. if (next === 61) {
  12471. size = 2;
  12472. }
  12473. this.finishOp(types.relational, size);
  12474. }
  12475. readToken_eq_excl(code) {
  12476. const next = this.input.charCodeAt(this.state.pos + 1);
  12477. if (next === 61) {
  12478. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  12479. return;
  12480. }
  12481. if (code === 61 && next === 62) {
  12482. this.state.pos += 2;
  12483. this.finishToken(types.arrow);
  12484. return;
  12485. }
  12486. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  12487. }
  12488. readToken_question() {
  12489. const next = this.input.charCodeAt(this.state.pos + 1);
  12490. const next2 = this.input.charCodeAt(this.state.pos + 2);
  12491. if (next === 63) {
  12492. if (next2 === 61) {
  12493. this.finishOp(types.assign, 3);
  12494. } else {
  12495. this.finishOp(types.nullishCoalescing, 2);
  12496. }
  12497. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  12498. this.state.pos += 2;
  12499. this.finishToken(types.questionDot);
  12500. } else {
  12501. ++this.state.pos;
  12502. this.finishToken(types.question);
  12503. }
  12504. }
  12505. getTokenFromCode(code) {
  12506. switch (code) {
  12507. case 46:
  12508. this.readToken_dot();
  12509. return;
  12510. case 40:
  12511. ++this.state.pos;
  12512. this.finishToken(types.parenL);
  12513. return;
  12514. case 41:
  12515. ++this.state.pos;
  12516. this.finishToken(types.parenR);
  12517. return;
  12518. case 59:
  12519. ++this.state.pos;
  12520. this.finishToken(types.semi);
  12521. return;
  12522. case 44:
  12523. ++this.state.pos;
  12524. this.finishToken(types.comma);
  12525. return;
  12526. case 91:
  12527. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  12528. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  12529. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  12530. }
  12531. this.finishToken(types.bracketBarL);
  12532. this.state.pos += 2;
  12533. } else {
  12534. ++this.state.pos;
  12535. this.finishToken(types.bracketL);
  12536. }
  12537. return;
  12538. case 93:
  12539. ++this.state.pos;
  12540. this.finishToken(types.bracketR);
  12541. return;
  12542. case 123:
  12543. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  12544. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  12545. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  12546. }
  12547. this.finishToken(types.braceBarL);
  12548. this.state.pos += 2;
  12549. } else {
  12550. ++this.state.pos;
  12551. this.finishToken(types.braceL);
  12552. }
  12553. return;
  12554. case 125:
  12555. ++this.state.pos;
  12556. this.finishToken(types.braceR);
  12557. return;
  12558. case 58:
  12559. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  12560. this.finishOp(types.doubleColon, 2);
  12561. } else {
  12562. ++this.state.pos;
  12563. this.finishToken(types.colon);
  12564. }
  12565. return;
  12566. case 63:
  12567. this.readToken_question();
  12568. return;
  12569. case 96:
  12570. ++this.state.pos;
  12571. this.finishToken(types.backQuote);
  12572. return;
  12573. case 48:
  12574. {
  12575. const next = this.input.charCodeAt(this.state.pos + 1);
  12576. if (next === 120 || next === 88) {
  12577. this.readRadixNumber(16);
  12578. return;
  12579. }
  12580. if (next === 111 || next === 79) {
  12581. this.readRadixNumber(8);
  12582. return;
  12583. }
  12584. if (next === 98 || next === 66) {
  12585. this.readRadixNumber(2);
  12586. return;
  12587. }
  12588. }
  12589. case 49:
  12590. case 50:
  12591. case 51:
  12592. case 52:
  12593. case 53:
  12594. case 54:
  12595. case 55:
  12596. case 56:
  12597. case 57:
  12598. this.readNumber(false);
  12599. return;
  12600. case 34:
  12601. case 39:
  12602. this.readString(code);
  12603. return;
  12604. case 47:
  12605. this.readToken_slash();
  12606. return;
  12607. case 37:
  12608. case 42:
  12609. this.readToken_mult_modulo(code);
  12610. return;
  12611. case 124:
  12612. case 38:
  12613. this.readToken_pipe_amp(code);
  12614. return;
  12615. case 94:
  12616. this.readToken_caret();
  12617. return;
  12618. case 43:
  12619. case 45:
  12620. this.readToken_plus_min(code);
  12621. return;
  12622. case 60:
  12623. case 62:
  12624. this.readToken_lt_gt(code);
  12625. return;
  12626. case 61:
  12627. case 33:
  12628. this.readToken_eq_excl(code);
  12629. return;
  12630. case 126:
  12631. this.finishOp(types.tilde, 1);
  12632. return;
  12633. case 64:
  12634. ++this.state.pos;
  12635. this.finishToken(types.at);
  12636. return;
  12637. case 35:
  12638. this.readToken_numberSign();
  12639. return;
  12640. case 92:
  12641. this.readWord();
  12642. return;
  12643. default:
  12644. if (isIdentifierStart(code)) {
  12645. this.readWord();
  12646. return;
  12647. }
  12648. }
  12649. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  12650. }
  12651. finishOp(type, size) {
  12652. const str = this.input.slice(this.state.pos, this.state.pos + size);
  12653. this.state.pos += size;
  12654. this.finishToken(type, str);
  12655. }
  12656. readRegexp() {
  12657. const start = this.state.pos;
  12658. let escaped, inClass;
  12659. for (;;) {
  12660. if (this.state.pos >= this.length) {
  12661. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  12662. }
  12663. const ch = this.input.charAt(this.state.pos);
  12664. if (lineBreak.test(ch)) {
  12665. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  12666. }
  12667. if (escaped) {
  12668. escaped = false;
  12669. } else {
  12670. if (ch === "[") {
  12671. inClass = true;
  12672. } else if (ch === "]" && inClass) {
  12673. inClass = false;
  12674. } else if (ch === "/" && !inClass) {
  12675. break;
  12676. }
  12677. escaped = ch === "\\";
  12678. }
  12679. ++this.state.pos;
  12680. }
  12681. const content = this.input.slice(start, this.state.pos);
  12682. ++this.state.pos;
  12683. let mods = "";
  12684. while (this.state.pos < this.length) {
  12685. const char = this.input[this.state.pos];
  12686. const charCode = this.input.codePointAt(this.state.pos);
  12687. if (VALID_REGEX_FLAGS.has(char)) {
  12688. if (mods.indexOf(char) > -1) {
  12689. this.raise(this.state.pos + 1, ErrorMessages.DuplicateRegExpFlags);
  12690. }
  12691. } else if (isIdentifierChar(charCode) || charCode === 92) {
  12692. this.raise(this.state.pos + 1, ErrorMessages.MalformedRegExpFlags);
  12693. } else {
  12694. break;
  12695. }
  12696. ++this.state.pos;
  12697. mods += char;
  12698. }
  12699. this.finishToken(types.regexp, {
  12700. pattern: content,
  12701. flags: mods
  12702. });
  12703. }
  12704. readInt(radix, len, forceLen, allowNumSeparator = true) {
  12705. const start = this.state.pos;
  12706. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  12707. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  12708. let invalid = false;
  12709. let total = 0;
  12710. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  12711. const code = this.input.charCodeAt(this.state.pos);
  12712. let val;
  12713. if (code === 95) {
  12714. const prev = this.input.charCodeAt(this.state.pos - 1);
  12715. const next = this.input.charCodeAt(this.state.pos + 1);
  12716. if (allowedSiblings.indexOf(next) === -1) {
  12717. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  12718. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  12719. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  12720. }
  12721. if (!allowNumSeparator) {
  12722. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  12723. }
  12724. ++this.state.pos;
  12725. continue;
  12726. }
  12727. if (code >= 97) {
  12728. val = code - 97 + 10;
  12729. } else if (code >= 65) {
  12730. val = code - 65 + 10;
  12731. } else if (_isDigit(code)) {
  12732. val = code - 48;
  12733. } else {
  12734. val = Infinity;
  12735. }
  12736. if (val >= radix) {
  12737. if (this.options.errorRecovery && val <= 9) {
  12738. val = 0;
  12739. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  12740. } else if (forceLen) {
  12741. val = 0;
  12742. invalid = true;
  12743. } else {
  12744. break;
  12745. }
  12746. }
  12747. ++this.state.pos;
  12748. total = total * radix + val;
  12749. }
  12750. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  12751. return null;
  12752. }
  12753. return total;
  12754. }
  12755. readRadixNumber(radix) {
  12756. const start = this.state.pos;
  12757. let isBigInt = false;
  12758. this.state.pos += 2;
  12759. const val = this.readInt(radix);
  12760. if (val == null) {
  12761. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  12762. }
  12763. const next = this.input.charCodeAt(this.state.pos);
  12764. if (next === 110) {
  12765. ++this.state.pos;
  12766. isBigInt = true;
  12767. } else if (next === 109) {
  12768. throw this.raise(start, ErrorMessages.InvalidDecimal);
  12769. }
  12770. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  12771. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  12772. }
  12773. if (isBigInt) {
  12774. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  12775. this.finishToken(types.bigint, str);
  12776. return;
  12777. }
  12778. this.finishToken(types.num, val);
  12779. }
  12780. readNumber(startsWithDot) {
  12781. const start = this.state.pos;
  12782. let isFloat = false;
  12783. let isBigInt = false;
  12784. let isDecimal = false;
  12785. let hasExponent = false;
  12786. let isOctal = false;
  12787. if (!startsWithDot && this.readInt(10) === null) {
  12788. this.raise(start, ErrorMessages.InvalidNumber);
  12789. }
  12790. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  12791. if (hasLeadingZero) {
  12792. const integer = this.input.slice(start, this.state.pos);
  12793. if (this.state.strict) {
  12794. this.raise(start, ErrorMessages.StrictOctalLiteral);
  12795. } else {
  12796. const underscorePos = integer.indexOf("_");
  12797. if (underscorePos > 0) {
  12798. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  12799. }
  12800. }
  12801. isOctal = hasLeadingZero && !/[89]/.test(integer);
  12802. }
  12803. let next = this.input.charCodeAt(this.state.pos);
  12804. if (next === 46 && !isOctal) {
  12805. ++this.state.pos;
  12806. this.readInt(10);
  12807. isFloat = true;
  12808. next = this.input.charCodeAt(this.state.pos);
  12809. }
  12810. if ((next === 69 || next === 101) && !isOctal) {
  12811. next = this.input.charCodeAt(++this.state.pos);
  12812. if (next === 43 || next === 45) {
  12813. ++this.state.pos;
  12814. }
  12815. if (this.readInt(10) === null) {
  12816. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  12817. }
  12818. isFloat = true;
  12819. hasExponent = true;
  12820. next = this.input.charCodeAt(this.state.pos);
  12821. }
  12822. if (next === 110) {
  12823. if (isFloat || hasLeadingZero) {
  12824. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  12825. }
  12826. ++this.state.pos;
  12827. isBigInt = true;
  12828. }
  12829. if (next === 109) {
  12830. this.expectPlugin("decimal", this.state.pos);
  12831. if (hasExponent || hasLeadingZero) {
  12832. this.raise(start, ErrorMessages.InvalidDecimal);
  12833. }
  12834. ++this.state.pos;
  12835. isDecimal = true;
  12836. }
  12837. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  12838. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  12839. }
  12840. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  12841. if (isBigInt) {
  12842. this.finishToken(types.bigint, str);
  12843. return;
  12844. }
  12845. if (isDecimal) {
  12846. this.finishToken(types.decimal, str);
  12847. return;
  12848. }
  12849. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  12850. this.finishToken(types.num, val);
  12851. }
  12852. readCodePoint(throwOnInvalid) {
  12853. const ch = this.input.charCodeAt(this.state.pos);
  12854. let code;
  12855. if (ch === 123) {
  12856. const codePos = ++this.state.pos;
  12857. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  12858. ++this.state.pos;
  12859. if (code !== null && code > 0x10ffff) {
  12860. if (throwOnInvalid) {
  12861. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  12862. } else {
  12863. return null;
  12864. }
  12865. }
  12866. } else {
  12867. code = this.readHexChar(4, false, throwOnInvalid);
  12868. }
  12869. return code;
  12870. }
  12871. readString(quote) {
  12872. let out = "",
  12873. chunkStart = ++this.state.pos;
  12874. for (;;) {
  12875. if (this.state.pos >= this.length) {
  12876. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  12877. }
  12878. const ch = this.input.charCodeAt(this.state.pos);
  12879. if (ch === quote) break;
  12880. if (ch === 92) {
  12881. out += this.input.slice(chunkStart, this.state.pos);
  12882. out += this.readEscapedChar(false);
  12883. chunkStart = this.state.pos;
  12884. } else if (ch === 8232 || ch === 8233) {
  12885. ++this.state.pos;
  12886. ++this.state.curLine;
  12887. this.state.lineStart = this.state.pos;
  12888. } else if (isNewLine(ch)) {
  12889. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  12890. } else {
  12891. ++this.state.pos;
  12892. }
  12893. }
  12894. out += this.input.slice(chunkStart, this.state.pos++);
  12895. this.finishToken(types.string, out);
  12896. }
  12897. readTmplToken() {
  12898. let out = "",
  12899. chunkStart = this.state.pos,
  12900. containsInvalid = false;
  12901. for (;;) {
  12902. if (this.state.pos >= this.length) {
  12903. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  12904. }
  12905. const ch = this.input.charCodeAt(this.state.pos);
  12906. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  12907. if (this.state.pos === this.state.start && this.match(types.template)) {
  12908. if (ch === 36) {
  12909. this.state.pos += 2;
  12910. this.finishToken(types.dollarBraceL);
  12911. return;
  12912. } else {
  12913. ++this.state.pos;
  12914. this.finishToken(types.backQuote);
  12915. return;
  12916. }
  12917. }
  12918. out += this.input.slice(chunkStart, this.state.pos);
  12919. this.finishToken(types.template, containsInvalid ? null : out);
  12920. return;
  12921. }
  12922. if (ch === 92) {
  12923. out += this.input.slice(chunkStart, this.state.pos);
  12924. const escaped = this.readEscapedChar(true);
  12925. if (escaped === null) {
  12926. containsInvalid = true;
  12927. } else {
  12928. out += escaped;
  12929. }
  12930. chunkStart = this.state.pos;
  12931. } else if (isNewLine(ch)) {
  12932. out += this.input.slice(chunkStart, this.state.pos);
  12933. ++this.state.pos;
  12934. switch (ch) {
  12935. case 13:
  12936. if (this.input.charCodeAt(this.state.pos) === 10) {
  12937. ++this.state.pos;
  12938. }
  12939. case 10:
  12940. out += "\n";
  12941. break;
  12942. default:
  12943. out += String.fromCharCode(ch);
  12944. break;
  12945. }
  12946. ++this.state.curLine;
  12947. this.state.lineStart = this.state.pos;
  12948. chunkStart = this.state.pos;
  12949. } else {
  12950. ++this.state.pos;
  12951. }
  12952. }
  12953. }
  12954. readEscapedChar(inTemplate) {
  12955. const throwOnInvalid = !inTemplate;
  12956. const ch = this.input.charCodeAt(++this.state.pos);
  12957. ++this.state.pos;
  12958. switch (ch) {
  12959. case 110:
  12960. return "\n";
  12961. case 114:
  12962. return "\r";
  12963. case 120:
  12964. {
  12965. const code = this.readHexChar(2, false, throwOnInvalid);
  12966. return code === null ? null : String.fromCharCode(code);
  12967. }
  12968. case 117:
  12969. {
  12970. const code = this.readCodePoint(throwOnInvalid);
  12971. return code === null ? null : String.fromCodePoint(code);
  12972. }
  12973. case 116:
  12974. return "\t";
  12975. case 98:
  12976. return "\b";
  12977. case 118:
  12978. return "\u000b";
  12979. case 102:
  12980. return "\f";
  12981. case 13:
  12982. if (this.input.charCodeAt(this.state.pos) === 10) {
  12983. ++this.state.pos;
  12984. }
  12985. case 10:
  12986. this.state.lineStart = this.state.pos;
  12987. ++this.state.curLine;
  12988. case 8232:
  12989. case 8233:
  12990. return "";
  12991. case 56:
  12992. case 57:
  12993. if (inTemplate) {
  12994. return null;
  12995. } else if (this.state.strict) {
  12996. this.raise(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  12997. }
  12998. default:
  12999. if (ch >= 48 && ch <= 55) {
  13000. const codePos = this.state.pos - 1;
  13001. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  13002. let octalStr = match[0];
  13003. let octal = parseInt(octalStr, 8);
  13004. if (octal > 255) {
  13005. octalStr = octalStr.slice(0, -1);
  13006. octal = parseInt(octalStr, 8);
  13007. }
  13008. this.state.pos += octalStr.length - 1;
  13009. const next = this.input.charCodeAt(this.state.pos);
  13010. if (octalStr !== "0" || next === 56 || next === 57) {
  13011. if (inTemplate) {
  13012. return null;
  13013. } else if (this.state.strict) {
  13014. this.raise(codePos, ErrorMessages.StrictNumericEscape);
  13015. } else {
  13016. this.state.octalPositions.push(codePos);
  13017. }
  13018. }
  13019. return String.fromCharCode(octal);
  13020. }
  13021. return String.fromCharCode(ch);
  13022. }
  13023. }
  13024. readHexChar(len, forceLen, throwOnInvalid) {
  13025. const codePos = this.state.pos;
  13026. const n = this.readInt(16, len, forceLen, false);
  13027. if (n === null) {
  13028. if (throwOnInvalid) {
  13029. this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
  13030. } else {
  13031. this.state.pos = codePos - 1;
  13032. }
  13033. }
  13034. return n;
  13035. }
  13036. readWord1() {
  13037. let word = "";
  13038. this.state.containsEsc = false;
  13039. const start = this.state.pos;
  13040. let chunkStart = this.state.pos;
  13041. while (this.state.pos < this.length) {
  13042. const ch = this.input.codePointAt(this.state.pos);
  13043. if (isIdentifierChar(ch)) {
  13044. this.state.pos += ch <= 0xffff ? 1 : 2;
  13045. } else if (this.state.isIterator && ch === 64) {
  13046. ++this.state.pos;
  13047. } else if (ch === 92) {
  13048. this.state.containsEsc = true;
  13049. word += this.input.slice(chunkStart, this.state.pos);
  13050. const escStart = this.state.pos;
  13051. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  13052. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  13053. this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
  13054. continue;
  13055. }
  13056. ++this.state.pos;
  13057. const esc = this.readCodePoint(true);
  13058. if (esc !== null) {
  13059. if (!identifierCheck(esc)) {
  13060. this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
  13061. }
  13062. word += String.fromCodePoint(esc);
  13063. }
  13064. chunkStart = this.state.pos;
  13065. } else {
  13066. break;
  13067. }
  13068. }
  13069. return word + this.input.slice(chunkStart, this.state.pos);
  13070. }
  13071. isIterator(word) {
  13072. return word === "@@iterator" || word === "@@asyncIterator";
  13073. }
  13074. readWord() {
  13075. const word = this.readWord1();
  13076. const type = keywords.get(word) || types.name;
  13077. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  13078. this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, word);
  13079. }
  13080. this.finishToken(type, word);
  13081. }
  13082. checkKeywordEscapes() {
  13083. const kw = this.state.type.keyword;
  13084. if (kw && this.state.containsEsc) {
  13085. this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, kw);
  13086. }
  13087. }
  13088. braceIsBlock(prevType) {
  13089. const parent = this.curContext();
  13090. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  13091. return true;
  13092. }
  13093. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  13094. return !parent.isExpr;
  13095. }
  13096. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  13097. return this.hasPrecedingLineBreak();
  13098. }
  13099. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  13100. return true;
  13101. }
  13102. if (prevType === types.braceL) {
  13103. return parent === types$1.braceStatement;
  13104. }
  13105. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  13106. return false;
  13107. }
  13108. if (prevType === types.relational) {
  13109. return true;
  13110. }
  13111. return !this.state.exprAllowed;
  13112. }
  13113. updateContext(prevType) {
  13114. const type = this.state.type;
  13115. let update;
  13116. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  13117. this.state.exprAllowed = false;
  13118. } else if (update = type.updateContext) {
  13119. update.call(this, prevType);
  13120. } else {
  13121. this.state.exprAllowed = type.beforeExpr;
  13122. }
  13123. }
  13124. }
  13125. class UtilParser extends Tokenizer {
  13126. addExtra(node, key, val) {
  13127. if (!node) return;
  13128. const extra = node.extra = node.extra || {};
  13129. extra[key] = val;
  13130. }
  13131. isRelational(op) {
  13132. return this.match(types.relational) && this.state.value === op;
  13133. }
  13134. expectRelational(op) {
  13135. if (this.isRelational(op)) {
  13136. this.next();
  13137. } else {
  13138. this.unexpected(null, types.relational);
  13139. }
  13140. }
  13141. isContextual(name) {
  13142. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  13143. }
  13144. isUnparsedContextual(nameStart, name) {
  13145. const nameEnd = nameStart + name.length;
  13146. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  13147. }
  13148. isLookaheadContextual(name) {
  13149. const next = this.nextTokenStart();
  13150. return this.isUnparsedContextual(next, name);
  13151. }
  13152. eatContextual(name) {
  13153. return this.isContextual(name) && this.eat(types.name);
  13154. }
  13155. expectContextual(name, message) {
  13156. if (!this.eatContextual(name)) this.unexpected(null, message);
  13157. }
  13158. canInsertSemicolon() {
  13159. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  13160. }
  13161. hasPrecedingLineBreak() {
  13162. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  13163. }
  13164. isLineTerminator() {
  13165. return this.eat(types.semi) || this.canInsertSemicolon();
  13166. }
  13167. semicolon() {
  13168. if (!this.isLineTerminator()) this.unexpected(null, types.semi);
  13169. }
  13170. expect(type, pos) {
  13171. this.eat(type) || this.unexpected(pos, type);
  13172. }
  13173. assertNoSpace(message = "Unexpected space.") {
  13174. if (this.state.start > this.state.lastTokEnd) {
  13175. this.raise(this.state.lastTokEnd, message);
  13176. }
  13177. }
  13178. unexpected(pos, messageOrType = "Unexpected token") {
  13179. if (typeof messageOrType !== "string") {
  13180. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  13181. }
  13182. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  13183. }
  13184. expectPlugin(name, pos) {
  13185. if (!this.hasPlugin(name)) {
  13186. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  13187. missingPlugin: [name]
  13188. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  13189. }
  13190. return true;
  13191. }
  13192. expectOnePlugin(names, pos) {
  13193. if (!names.some(n => this.hasPlugin(n))) {
  13194. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  13195. missingPlugin: names
  13196. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  13197. }
  13198. }
  13199. tryParse(fn, oldState = this.state.clone()) {
  13200. const abortSignal = {
  13201. node: null
  13202. };
  13203. try {
  13204. const node = fn((node = null) => {
  13205. abortSignal.node = node;
  13206. throw abortSignal;
  13207. });
  13208. if (this.state.errors.length > oldState.errors.length) {
  13209. const failState = this.state;
  13210. this.state = oldState;
  13211. return {
  13212. node,
  13213. error: failState.errors[oldState.errors.length],
  13214. thrown: false,
  13215. aborted: false,
  13216. failState
  13217. };
  13218. }
  13219. return {
  13220. node,
  13221. error: null,
  13222. thrown: false,
  13223. aborted: false,
  13224. failState: null
  13225. };
  13226. } catch (error) {
  13227. const failState = this.state;
  13228. this.state = oldState;
  13229. if (error instanceof SyntaxError) {
  13230. return {
  13231. node: null,
  13232. error,
  13233. thrown: true,
  13234. aborted: false,
  13235. failState
  13236. };
  13237. }
  13238. if (error === abortSignal) {
  13239. return {
  13240. node: abortSignal.node,
  13241. error: null,
  13242. thrown: false,
  13243. aborted: true,
  13244. failState
  13245. };
  13246. }
  13247. throw error;
  13248. }
  13249. }
  13250. checkExpressionErrors(refExpressionErrors, andThrow) {
  13251. if (!refExpressionErrors) return false;
  13252. const {
  13253. shorthandAssign,
  13254. doubleProto
  13255. } = refExpressionErrors;
  13256. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  13257. if (shorthandAssign >= 0) {
  13258. this.unexpected(shorthandAssign);
  13259. }
  13260. if (doubleProto >= 0) {
  13261. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  13262. }
  13263. }
  13264. isLiteralPropertyName() {
  13265. 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);
  13266. }
  13267. }
  13268. class ExpressionErrors {
  13269. constructor() {
  13270. this.shorthandAssign = -1;
  13271. this.doubleProto = -1;
  13272. }
  13273. }
  13274. class Node {
  13275. constructor(parser, pos, loc) {
  13276. this.type = void 0;
  13277. this.start = void 0;
  13278. this.end = void 0;
  13279. this.loc = void 0;
  13280. this.range = void 0;
  13281. this.leadingComments = void 0;
  13282. this.trailingComments = void 0;
  13283. this.innerComments = void 0;
  13284. this.extra = void 0;
  13285. this.type = "";
  13286. this.start = pos;
  13287. this.end = 0;
  13288. this.loc = new SourceLocation(loc);
  13289. if (parser == null ? void 0 : parser.options.ranges) this.range = [pos, 0];
  13290. if (parser == null ? void 0 : parser.filename) this.loc.filename = parser.filename;
  13291. }
  13292. __clone() {
  13293. const newNode = new Node();
  13294. const keys = Object.keys(this);
  13295. for (let i = 0, length = keys.length; i < length; i++) {
  13296. const key = keys[i];
  13297. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  13298. newNode[key] = this[key];
  13299. }
  13300. }
  13301. return newNode;
  13302. }
  13303. }
  13304. class NodeUtils extends UtilParser {
  13305. startNode() {
  13306. return new Node(this, this.state.start, this.state.startLoc);
  13307. }
  13308. startNodeAt(pos, loc) {
  13309. return new Node(this, pos, loc);
  13310. }
  13311. startNodeAtNode(type) {
  13312. return this.startNodeAt(type.start, type.loc.start);
  13313. }
  13314. finishNode(node, type) {
  13315. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  13316. }
  13317. finishNodeAt(node, type, pos, loc) {
  13318. node.type = type;
  13319. node.end = pos;
  13320. node.loc.end = loc;
  13321. if (this.options.ranges) node.range[1] = pos;
  13322. this.processComment(node);
  13323. return node;
  13324. }
  13325. resetStartLocation(node, start, startLoc) {
  13326. node.start = start;
  13327. node.loc.start = startLoc;
  13328. if (this.options.ranges) node.range[0] = start;
  13329. }
  13330. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  13331. node.end = end;
  13332. node.loc.end = endLoc;
  13333. if (this.options.ranges) node.range[1] = end;
  13334. }
  13335. resetStartLocationFromNode(node, locationNode) {
  13336. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  13337. }
  13338. }
  13339. const unwrapParenthesizedExpression = node => {
  13340. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  13341. };
  13342. class LValParser extends NodeUtils {
  13343. toAssignable(node, isLHS = false) {
  13344. var _node$extra, _node$extra3;
  13345. let parenthesized = undefined;
  13346. if (node.type === "ParenthesizedExpression" || ((_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized)) {
  13347. parenthesized = unwrapParenthesizedExpression(node);
  13348. if (isLHS) {
  13349. if (parenthesized.type === "Identifier") {
  13350. this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  13351. } else if (parenthesized.type !== "MemberExpression") {
  13352. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  13353. }
  13354. } else {
  13355. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  13356. }
  13357. }
  13358. switch (node.type) {
  13359. case "Identifier":
  13360. case "ObjectPattern":
  13361. case "ArrayPattern":
  13362. case "AssignmentPattern":
  13363. break;
  13364. case "ObjectExpression":
  13365. node.type = "ObjectPattern";
  13366. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  13367. var _node$extra2;
  13368. const prop = node.properties[i];
  13369. const isLast = i === last;
  13370. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  13371. if (isLast && prop.type === "RestElement" && ((_node$extra2 = node.extra) == null ? void 0 : _node$extra2.trailingComma)) {
  13372. this.raiseRestNotLast(node.extra.trailingComma);
  13373. }
  13374. }
  13375. break;
  13376. case "ObjectProperty":
  13377. this.toAssignable(node.value, isLHS);
  13378. break;
  13379. case "SpreadElement":
  13380. {
  13381. this.checkToRestConversion(node);
  13382. node.type = "RestElement";
  13383. const arg = node.argument;
  13384. this.toAssignable(arg, isLHS);
  13385. break;
  13386. }
  13387. case "ArrayExpression":
  13388. node.type = "ArrayPattern";
  13389. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS);
  13390. break;
  13391. case "AssignmentExpression":
  13392. if (node.operator !== "=") {
  13393. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  13394. }
  13395. node.type = "AssignmentPattern";
  13396. delete node.operator;
  13397. this.toAssignable(node.left, isLHS);
  13398. break;
  13399. case "ParenthesizedExpression":
  13400. this.toAssignable(parenthesized, isLHS);
  13401. break;
  13402. }
  13403. return node;
  13404. }
  13405. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  13406. if (prop.type === "ObjectMethod") {
  13407. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  13408. this.raise(prop.key.start, error);
  13409. } else if (prop.type === "SpreadElement" && !isLast) {
  13410. this.raiseRestNotLast(prop.start);
  13411. } else {
  13412. this.toAssignable(prop, isLHS);
  13413. }
  13414. }
  13415. toAssignableList(exprList, trailingCommaPos, isLHS) {
  13416. let end = exprList.length;
  13417. if (end) {
  13418. const last = exprList[end - 1];
  13419. if ((last == null ? void 0 : last.type) === "RestElement") {
  13420. --end;
  13421. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  13422. last.type = "RestElement";
  13423. let arg = last.argument;
  13424. this.toAssignable(arg, isLHS);
  13425. arg = unwrapParenthesizedExpression(arg);
  13426. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  13427. this.unexpected(arg.start);
  13428. }
  13429. if (trailingCommaPos) {
  13430. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  13431. }
  13432. --end;
  13433. }
  13434. }
  13435. for (let i = 0; i < end; i++) {
  13436. const elt = exprList[i];
  13437. if (elt) {
  13438. this.toAssignable(elt, isLHS);
  13439. if (elt.type === "RestElement") {
  13440. this.raiseRestNotLast(elt.start);
  13441. }
  13442. }
  13443. }
  13444. return exprList;
  13445. }
  13446. toReferencedList(exprList, isParenthesizedExpr) {
  13447. return exprList;
  13448. }
  13449. toReferencedListDeep(exprList, isParenthesizedExpr) {
  13450. this.toReferencedList(exprList, isParenthesizedExpr);
  13451. for (let _i = 0; _i < exprList.length; _i++) {
  13452. const expr = exprList[_i];
  13453. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  13454. this.toReferencedListDeep(expr.elements);
  13455. }
  13456. }
  13457. }
  13458. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  13459. const node = this.startNode();
  13460. this.next();
  13461. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  13462. return this.finishNode(node, "SpreadElement");
  13463. }
  13464. parseRestBinding() {
  13465. const node = this.startNode();
  13466. this.next();
  13467. node.argument = this.parseBindingAtom();
  13468. return this.finishNode(node, "RestElement");
  13469. }
  13470. parseBindingAtom() {
  13471. switch (this.state.type) {
  13472. case types.bracketL:
  13473. {
  13474. const node = this.startNode();
  13475. this.next();
  13476. node.elements = this.parseBindingList(types.bracketR, 93, true);
  13477. return this.finishNode(node, "ArrayPattern");
  13478. }
  13479. case types.braceL:
  13480. return this.parseObjectLike(types.braceR, true);
  13481. }
  13482. return this.parseIdentifier();
  13483. }
  13484. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  13485. const elts = [];
  13486. let first = true;
  13487. while (!this.eat(close)) {
  13488. if (first) {
  13489. first = false;
  13490. } else {
  13491. this.expect(types.comma);
  13492. }
  13493. if (allowEmpty && this.match(types.comma)) {
  13494. elts.push(null);
  13495. } else if (this.eat(close)) {
  13496. break;
  13497. } else if (this.match(types.ellipsis)) {
  13498. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  13499. this.checkCommaAfterRest(closeCharCode);
  13500. this.expect(close);
  13501. break;
  13502. } else {
  13503. const decorators = [];
  13504. if (this.match(types.at) && this.hasPlugin("decorators")) {
  13505. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  13506. }
  13507. while (this.match(types.at)) {
  13508. decorators.push(this.parseDecorator());
  13509. }
  13510. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  13511. }
  13512. }
  13513. return elts;
  13514. }
  13515. parseAssignableListItem(allowModifiers, decorators) {
  13516. const left = this.parseMaybeDefault();
  13517. this.parseAssignableListItemTypes(left);
  13518. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  13519. if (decorators.length) {
  13520. left.decorators = decorators;
  13521. }
  13522. return elt;
  13523. }
  13524. parseAssignableListItemTypes(param) {
  13525. return param;
  13526. }
  13527. parseMaybeDefault(startPos, startLoc, left) {
  13528. var _startLoc, _startPos, _left;
  13529. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  13530. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  13531. left = (_left = left) != null ? _left : this.parseBindingAtom();
  13532. if (!this.eat(types.eq)) return left;
  13533. const node = this.startNodeAt(startPos, startLoc);
  13534. node.left = left;
  13535. node.right = this.parseMaybeAssignAllowIn();
  13536. return this.finishNode(node, "AssignmentPattern");
  13537. }
  13538. checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) {
  13539. switch (expr.type) {
  13540. case "Identifier":
  13541. {
  13542. const {
  13543. name
  13544. } = expr;
  13545. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) {
  13546. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name);
  13547. }
  13548. if (checkClashes) {
  13549. if (checkClashes.has(name)) {
  13550. this.raise(expr.start, ErrorMessages.ParamDupe);
  13551. } else {
  13552. checkClashes.add(name);
  13553. }
  13554. }
  13555. if (disallowLetBinding && name === "let") {
  13556. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  13557. }
  13558. if (!(bindingType & BIND_NONE)) {
  13559. this.scope.declareName(name, bindingType, expr.start);
  13560. }
  13561. break;
  13562. }
  13563. case "MemberExpression":
  13564. if (bindingType !== BIND_NONE) {
  13565. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  13566. }
  13567. break;
  13568. case "ObjectPattern":
  13569. for (let _i2 = 0, _expr$properties = expr.properties; _i2 < _expr$properties.length; _i2++) {
  13570. let prop = _expr$properties[_i2];
  13571. if (prop.type === "ObjectProperty") prop = prop.value;else if (prop.type === "ObjectMethod") continue;
  13572. this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  13573. }
  13574. break;
  13575. case "ArrayPattern":
  13576. for (let _i3 = 0, _expr$elements = expr.elements; _i3 < _expr$elements.length; _i3++) {
  13577. const elem = _expr$elements[_i3];
  13578. if (elem) {
  13579. this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  13580. }
  13581. }
  13582. break;
  13583. case "AssignmentPattern":
  13584. this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes);
  13585. break;
  13586. case "RestElement":
  13587. this.checkLVal(expr.argument, "rest element", bindingType, checkClashes);
  13588. break;
  13589. case "ParenthesizedExpression":
  13590. this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes);
  13591. break;
  13592. default:
  13593. {
  13594. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  13595. }
  13596. }
  13597. }
  13598. checkToRestConversion(node) {
  13599. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  13600. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  13601. }
  13602. }
  13603. checkCommaAfterRest(close) {
  13604. if (this.match(types.comma)) {
  13605. if (this.lookaheadCharCode() === close) {
  13606. this.raiseTrailingCommaAfterRest(this.state.start);
  13607. } else {
  13608. this.raiseRestNotLast(this.state.start);
  13609. }
  13610. }
  13611. }
  13612. raiseRestNotLast(pos) {
  13613. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  13614. }
  13615. raiseTrailingCommaAfterRest(pos) {
  13616. this.raise(pos, ErrorMessages.RestTrailingComma);
  13617. }
  13618. }
  13619. const kExpression = 0,
  13620. kMaybeArrowParameterDeclaration = 1,
  13621. kMaybeAsyncArrowParameterDeclaration = 2,
  13622. kParameterDeclaration = 3;
  13623. class ExpressionScope {
  13624. constructor(type = kExpression) {
  13625. this.type = void 0;
  13626. this.type = type;
  13627. }
  13628. canBeArrowParameterDeclaration() {
  13629. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  13630. }
  13631. isCertainlyParameterDeclaration() {
  13632. return this.type === kParameterDeclaration;
  13633. }
  13634. }
  13635. class ArrowHeadParsingScope extends ExpressionScope {
  13636. constructor(type) {
  13637. super(type);
  13638. this.errors = new Map();
  13639. }
  13640. recordDeclarationError(pos, message) {
  13641. this.errors.set(pos, message);
  13642. }
  13643. clearDeclarationError(pos) {
  13644. this.errors.delete(pos);
  13645. }
  13646. iterateErrors(iterator) {
  13647. this.errors.forEach(iterator);
  13648. }
  13649. }
  13650. class ExpressionScopeHandler {
  13651. constructor(raise) {
  13652. this.stack = [new ExpressionScope()];
  13653. this.raise = raise;
  13654. }
  13655. enter(scope) {
  13656. this.stack.push(scope);
  13657. }
  13658. exit() {
  13659. this.stack.pop();
  13660. }
  13661. recordParameterInitializerError(pos, message) {
  13662. const {
  13663. stack
  13664. } = this;
  13665. let i = stack.length - 1;
  13666. let scope = stack[i];
  13667. while (!scope.isCertainlyParameterDeclaration()) {
  13668. if (scope.canBeArrowParameterDeclaration()) {
  13669. scope.recordDeclarationError(pos, message);
  13670. } else {
  13671. return;
  13672. }
  13673. scope = stack[--i];
  13674. }
  13675. this.raise(pos, message);
  13676. }
  13677. recordParenthesizedIdentifierError(pos, message) {
  13678. const {
  13679. stack
  13680. } = this;
  13681. const scope = stack[stack.length - 1];
  13682. if (scope.isCertainlyParameterDeclaration()) {
  13683. this.raise(pos, message);
  13684. } else if (scope.canBeArrowParameterDeclaration()) {
  13685. scope.recordDeclarationError(pos, message);
  13686. } else {
  13687. return;
  13688. }
  13689. }
  13690. recordAsyncArrowParametersError(pos, message) {
  13691. const {
  13692. stack
  13693. } = this;
  13694. let i = stack.length - 1;
  13695. let scope = stack[i];
  13696. while (scope.canBeArrowParameterDeclaration()) {
  13697. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  13698. scope.recordDeclarationError(pos, message);
  13699. }
  13700. scope = stack[--i];
  13701. }
  13702. }
  13703. validateAsPattern() {
  13704. const {
  13705. stack
  13706. } = this;
  13707. const currentScope = stack[stack.length - 1];
  13708. if (!currentScope.canBeArrowParameterDeclaration()) return;
  13709. currentScope.iterateErrors((message, pos) => {
  13710. this.raise(pos, message);
  13711. let i = stack.length - 2;
  13712. let scope = stack[i];
  13713. while (scope.canBeArrowParameterDeclaration()) {
  13714. scope.clearDeclarationError(pos);
  13715. scope = stack[--i];
  13716. }
  13717. });
  13718. }
  13719. }
  13720. function newParameterDeclarationScope() {
  13721. return new ExpressionScope(kParameterDeclaration);
  13722. }
  13723. function newArrowHeadScope() {
  13724. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  13725. }
  13726. function newAsyncArrowScope() {
  13727. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  13728. }
  13729. function newExpressionScope() {
  13730. return new ExpressionScope();
  13731. }
  13732. class ExpressionParser extends LValParser {
  13733. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  13734. if (prop.type === "SpreadElement" || prop.type === "ObjectMethod" || prop.computed || prop.shorthand) {
  13735. return;
  13736. }
  13737. const key = prop.key;
  13738. const name = key.type === "Identifier" ? key.name : key.value;
  13739. if (name === "__proto__") {
  13740. if (isRecord) {
  13741. this.raise(key.start, ErrorMessages.RecordNoProto);
  13742. return;
  13743. }
  13744. if (protoRef.used) {
  13745. if (refExpressionErrors) {
  13746. if (refExpressionErrors.doubleProto === -1) {
  13747. refExpressionErrors.doubleProto = key.start;
  13748. }
  13749. } else {
  13750. this.raise(key.start, ErrorMessages.DuplicateProto);
  13751. }
  13752. }
  13753. protoRef.used = true;
  13754. }
  13755. }
  13756. shouldExitDescending(expr, potentialArrowAt) {
  13757. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  13758. }
  13759. getExpression() {
  13760. let paramFlags = PARAM;
  13761. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  13762. paramFlags |= PARAM_AWAIT;
  13763. }
  13764. this.scope.enter(SCOPE_PROGRAM);
  13765. this.prodParam.enter(paramFlags);
  13766. this.nextToken();
  13767. const expr = this.parseExpression();
  13768. if (!this.match(types.eof)) {
  13769. this.unexpected();
  13770. }
  13771. expr.comments = this.state.comments;
  13772. expr.errors = this.state.errors;
  13773. return expr;
  13774. }
  13775. parseExpression(disallowIn, refExpressionErrors) {
  13776. if (disallowIn) {
  13777. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  13778. }
  13779. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  13780. }
  13781. parseExpressionBase(refExpressionErrors) {
  13782. const startPos = this.state.start;
  13783. const startLoc = this.state.startLoc;
  13784. const expr = this.parseMaybeAssign(refExpressionErrors);
  13785. if (this.match(types.comma)) {
  13786. const node = this.startNodeAt(startPos, startLoc);
  13787. node.expressions = [expr];
  13788. while (this.eat(types.comma)) {
  13789. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  13790. }
  13791. this.toReferencedList(node.expressions);
  13792. return this.finishNode(node, "SequenceExpression");
  13793. }
  13794. return expr;
  13795. }
  13796. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  13797. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  13798. }
  13799. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  13800. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  13801. }
  13802. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  13803. const startPos = this.state.start;
  13804. const startLoc = this.state.startLoc;
  13805. if (this.isContextual("yield")) {
  13806. if (this.prodParam.hasYield) {
  13807. this.state.exprAllowed = true;
  13808. let left = this.parseYield();
  13809. if (afterLeftParse) {
  13810. left = afterLeftParse.call(this, left, startPos, startLoc);
  13811. }
  13812. return left;
  13813. }
  13814. }
  13815. let ownExpressionErrors;
  13816. if (refExpressionErrors) {
  13817. ownExpressionErrors = false;
  13818. } else {
  13819. refExpressionErrors = new ExpressionErrors();
  13820. ownExpressionErrors = true;
  13821. }
  13822. if (this.match(types.parenL) || this.match(types.name)) {
  13823. this.state.potentialArrowAt = this.state.start;
  13824. }
  13825. let left = this.parseMaybeConditional(refExpressionErrors, refNeedsArrowPos);
  13826. if (afterLeftParse) {
  13827. left = afterLeftParse.call(this, left, startPos, startLoc);
  13828. }
  13829. if (this.state.type.isAssign) {
  13830. const node = this.startNodeAt(startPos, startLoc);
  13831. const operator = this.state.value;
  13832. node.operator = operator;
  13833. if (this.match(types.eq)) {
  13834. node.left = this.toAssignable(left, true);
  13835. refExpressionErrors.doubleProto = -1;
  13836. } else {
  13837. node.left = left;
  13838. }
  13839. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  13840. refExpressionErrors.shorthandAssign = -1;
  13841. }
  13842. this.checkLVal(left, "assignment expression");
  13843. this.next();
  13844. node.right = this.parseMaybeAssign();
  13845. return this.finishNode(node, "AssignmentExpression");
  13846. } else if (ownExpressionErrors) {
  13847. this.checkExpressionErrors(refExpressionErrors, true);
  13848. }
  13849. return left;
  13850. }
  13851. parseMaybeConditional(refExpressionErrors, refNeedsArrowPos) {
  13852. const startPos = this.state.start;
  13853. const startLoc = this.state.startLoc;
  13854. const potentialArrowAt = this.state.potentialArrowAt;
  13855. const expr = this.parseExprOps(refExpressionErrors);
  13856. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  13857. return expr;
  13858. }
  13859. return this.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  13860. }
  13861. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  13862. if (this.eat(types.question)) {
  13863. const node = this.startNodeAt(startPos, startLoc);
  13864. node.test = expr;
  13865. node.consequent = this.parseMaybeAssignAllowIn();
  13866. this.expect(types.colon);
  13867. node.alternate = this.parseMaybeAssign();
  13868. return this.finishNode(node, "ConditionalExpression");
  13869. }
  13870. return expr;
  13871. }
  13872. parseExprOps(refExpressionErrors) {
  13873. const startPos = this.state.start;
  13874. const startLoc = this.state.startLoc;
  13875. const potentialArrowAt = this.state.potentialArrowAt;
  13876. const expr = this.parseMaybeUnary(refExpressionErrors);
  13877. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  13878. return expr;
  13879. }
  13880. return this.parseExprOp(expr, startPos, startLoc, -1);
  13881. }
  13882. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  13883. let prec = this.state.type.binop;
  13884. if (prec != null && (this.prodParam.hasIn || !this.match(types._in))) {
  13885. if (prec > minPrec) {
  13886. const op = this.state.type;
  13887. if (op === types.pipeline) {
  13888. this.expectPlugin("pipelineOperator");
  13889. if (this.state.inFSharpPipelineDirectBody) {
  13890. return left;
  13891. }
  13892. this.state.inPipeline = true;
  13893. this.checkPipelineAtInfixOperator(left, leftStartPos);
  13894. }
  13895. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  13896. node.left = left;
  13897. node.operator = this.state.value;
  13898. if (op === types.exponent && left.type === "UnaryExpression" && (this.options.createParenthesizedExpressions || !(left.extra && left.extra.parenthesized))) {
  13899. this.raise(left.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  13900. }
  13901. const logical = op === types.logicalOR || op === types.logicalAND;
  13902. const coalesce = op === types.nullishCoalescing;
  13903. if (coalesce) {
  13904. prec = types.logicalAND.binop;
  13905. }
  13906. this.next();
  13907. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  13908. if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
  13909. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  13910. }
  13911. }
  13912. node.right = this.parseExprOpRightExpr(op, prec);
  13913. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  13914. const nextOp = this.state.type;
  13915. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  13916. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  13917. }
  13918. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  13919. }
  13920. }
  13921. return left;
  13922. }
  13923. parseExprOpRightExpr(op, prec) {
  13924. const startPos = this.state.start;
  13925. const startLoc = this.state.startLoc;
  13926. switch (op) {
  13927. case types.pipeline:
  13928. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  13929. case "smart":
  13930. return this.withTopicPermittingContext(() => {
  13931. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  13932. });
  13933. case "fsharp":
  13934. return this.withSoloAwaitPermittingContext(() => {
  13935. return this.parseFSharpPipelineBody(prec);
  13936. });
  13937. }
  13938. default:
  13939. return this.parseExprOpBaseRightExpr(op, prec);
  13940. }
  13941. }
  13942. parseExprOpBaseRightExpr(op, prec) {
  13943. const startPos = this.state.start;
  13944. const startLoc = this.state.startLoc;
  13945. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec);
  13946. }
  13947. parseMaybeUnary(refExpressionErrors) {
  13948. if (this.isContextual("await") && this.isAwaitAllowed()) {
  13949. return this.parseAwait();
  13950. }
  13951. const update = this.match(types.incDec);
  13952. const node = this.startNode();
  13953. if (this.state.type.prefix) {
  13954. node.operator = this.state.value;
  13955. node.prefix = true;
  13956. if (this.match(types._throw)) {
  13957. this.expectPlugin("throwExpressions");
  13958. }
  13959. const isDelete = this.match(types._delete);
  13960. this.next();
  13961. node.argument = this.parseMaybeUnary();
  13962. this.checkExpressionErrors(refExpressionErrors, true);
  13963. if (this.state.strict && isDelete) {
  13964. const arg = node.argument;
  13965. if (arg.type === "Identifier") {
  13966. this.raise(node.start, ErrorMessages.StrictDelete);
  13967. } else if ((arg.type === "MemberExpression" || arg.type === "OptionalMemberExpression") && arg.property.type === "PrivateName") {
  13968. this.raise(node.start, ErrorMessages.DeletePrivateField);
  13969. }
  13970. }
  13971. if (!update) {
  13972. return this.finishNode(node, "UnaryExpression");
  13973. }
  13974. }
  13975. return this.parseUpdate(node, update, refExpressionErrors);
  13976. }
  13977. parseUpdate(node, update, refExpressionErrors) {
  13978. if (update) {
  13979. this.checkLVal(node.argument, "prefix operation");
  13980. return this.finishNode(node, "UpdateExpression");
  13981. }
  13982. const startPos = this.state.start;
  13983. const startLoc = this.state.startLoc;
  13984. let expr = this.parseExprSubscripts(refExpressionErrors);
  13985. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  13986. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  13987. const node = this.startNodeAt(startPos, startLoc);
  13988. node.operator = this.state.value;
  13989. node.prefix = false;
  13990. node.argument = expr;
  13991. this.checkLVal(expr, "postfix operation");
  13992. this.next();
  13993. expr = this.finishNode(node, "UpdateExpression");
  13994. }
  13995. return expr;
  13996. }
  13997. parseExprSubscripts(refExpressionErrors) {
  13998. const startPos = this.state.start;
  13999. const startLoc = this.state.startLoc;
  14000. const potentialArrowAt = this.state.potentialArrowAt;
  14001. const expr = this.parseExprAtom(refExpressionErrors);
  14002. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  14003. return expr;
  14004. }
  14005. return this.parseSubscripts(expr, startPos, startLoc);
  14006. }
  14007. parseSubscripts(base, startPos, startLoc, noCalls) {
  14008. const state = {
  14009. optionalChainMember: false,
  14010. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  14011. stop: false
  14012. };
  14013. do {
  14014. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  14015. state.maybeAsyncArrow = false;
  14016. } while (!state.stop);
  14017. return base;
  14018. }
  14019. parseSubscript(base, startPos, startLoc, noCalls, state) {
  14020. if (!noCalls && this.eat(types.doubleColon)) {
  14021. return this.parseBind(base, startPos, startLoc, noCalls, state);
  14022. } else if (this.match(types.backQuote)) {
  14023. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  14024. }
  14025. let optional = false;
  14026. if (this.match(types.questionDot)) {
  14027. state.optionalChainMember = optional = true;
  14028. if (noCalls && this.lookaheadCharCode() === 40) {
  14029. state.stop = true;
  14030. return base;
  14031. }
  14032. this.next();
  14033. }
  14034. if (!noCalls && this.match(types.parenL)) {
  14035. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  14036. } else if (optional || this.match(types.bracketL) || this.eat(types.dot)) {
  14037. return this.parseMember(base, startPos, startLoc, state, optional);
  14038. } else {
  14039. state.stop = true;
  14040. return base;
  14041. }
  14042. }
  14043. parseMember(base, startPos, startLoc, state, optional) {
  14044. const node = this.startNodeAt(startPos, startLoc);
  14045. const computed = this.eat(types.bracketL);
  14046. node.object = base;
  14047. node.computed = computed;
  14048. const property = computed ? this.parseExpression() : this.parseMaybePrivateName(true);
  14049. if (property.type === "PrivateName") {
  14050. if (node.object.type === "Super") {
  14051. this.raise(startPos, ErrorMessages.SuperPrivateField);
  14052. }
  14053. this.classScope.usePrivateName(property.id.name, property.start);
  14054. }
  14055. node.property = property;
  14056. if (computed) {
  14057. this.expect(types.bracketR);
  14058. }
  14059. if (state.optionalChainMember) {
  14060. node.optional = optional;
  14061. return this.finishNode(node, "OptionalMemberExpression");
  14062. } else {
  14063. return this.finishNode(node, "MemberExpression");
  14064. }
  14065. }
  14066. parseBind(base, startPos, startLoc, noCalls, state) {
  14067. const node = this.startNodeAt(startPos, startLoc);
  14068. node.object = base;
  14069. node.callee = this.parseNoCallExpr();
  14070. state.stop = true;
  14071. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  14072. }
  14073. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  14074. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  14075. this.state.maybeInArrowParameters = true;
  14076. this.next();
  14077. let node = this.startNodeAt(startPos, startLoc);
  14078. node.callee = base;
  14079. if (state.maybeAsyncArrow) {
  14080. this.expressionScope.enter(newAsyncArrowScope());
  14081. }
  14082. if (state.optionalChainMember) {
  14083. node.optional = optional;
  14084. }
  14085. if (optional) {
  14086. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  14087. } else {
  14088. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  14089. }
  14090. this.finishCallExpression(node, state.optionalChainMember);
  14091. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  14092. state.stop = true;
  14093. this.expressionScope.validateAsPattern();
  14094. this.expressionScope.exit();
  14095. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  14096. } else {
  14097. if (state.maybeAsyncArrow) {
  14098. this.expressionScope.exit();
  14099. }
  14100. this.toReferencedArguments(node);
  14101. }
  14102. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  14103. return node;
  14104. }
  14105. toReferencedArguments(node, isParenthesizedExpr) {
  14106. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  14107. }
  14108. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  14109. const node = this.startNodeAt(startPos, startLoc);
  14110. node.tag = base;
  14111. node.quasi = this.parseTemplate(true);
  14112. if (state.optionalChainMember) {
  14113. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  14114. }
  14115. return this.finishNode(node, "TaggedTemplateExpression");
  14116. }
  14117. atPossibleAsyncArrow(base) {
  14118. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  14119. }
  14120. finishCallExpression(node, optional) {
  14121. if (node.callee.type === "Import") {
  14122. if (node.arguments.length === 2) {
  14123. if (!this.hasPlugin("moduleAttributes")) {
  14124. this.expectPlugin("importAssertions");
  14125. }
  14126. }
  14127. if (node.arguments.length === 0 || node.arguments.length > 2) {
  14128. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  14129. } else {
  14130. for (let _i = 0, _node$arguments = node.arguments; _i < _node$arguments.length; _i++) {
  14131. const arg = _node$arguments[_i];
  14132. if (arg.type === "SpreadElement") {
  14133. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  14134. }
  14135. }
  14136. }
  14137. }
  14138. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  14139. }
  14140. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  14141. const elts = [];
  14142. let first = true;
  14143. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  14144. this.state.inFSharpPipelineDirectBody = false;
  14145. while (!this.eat(close)) {
  14146. if (first) {
  14147. first = false;
  14148. } else {
  14149. this.expect(types.comma);
  14150. if (this.match(close)) {
  14151. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  14152. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  14153. }
  14154. if (nodeForExtra) {
  14155. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  14156. }
  14157. this.next();
  14158. break;
  14159. }
  14160. }
  14161. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  14162. start: 0
  14163. } : undefined, allowPlaceholder));
  14164. }
  14165. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  14166. return elts;
  14167. }
  14168. shouldParseAsyncArrow() {
  14169. return this.match(types.arrow) && !this.canInsertSemicolon();
  14170. }
  14171. parseAsyncArrowFromCallExpression(node, call) {
  14172. var _call$extra;
  14173. this.expect(types.arrow);
  14174. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  14175. return node;
  14176. }
  14177. parseNoCallExpr() {
  14178. const startPos = this.state.start;
  14179. const startLoc = this.state.startLoc;
  14180. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  14181. }
  14182. parseExprAtom(refExpressionErrors) {
  14183. if (this.state.type === types.slash) this.readRegexp();
  14184. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  14185. let node;
  14186. switch (this.state.type) {
  14187. case types._super:
  14188. return this.parseSuper();
  14189. case types._import:
  14190. node = this.startNode();
  14191. this.next();
  14192. if (this.match(types.dot)) {
  14193. return this.parseImportMetaProperty(node);
  14194. }
  14195. if (!this.match(types.parenL)) {
  14196. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  14197. }
  14198. return this.finishNode(node, "Import");
  14199. case types._this:
  14200. node = this.startNode();
  14201. this.next();
  14202. return this.finishNode(node, "ThisExpression");
  14203. case types.name:
  14204. {
  14205. const containsEsc = this.state.containsEsc;
  14206. const id = this.parseIdentifier();
  14207. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  14208. if (this.match(types._function)) {
  14209. const last = this.state.context.length - 1;
  14210. if (this.state.context[last] !== types$1.functionStatement) {
  14211. throw new Error("Internal error");
  14212. }
  14213. this.state.context[last] = types$1.functionExpression;
  14214. this.next();
  14215. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  14216. } else if (this.match(types.name)) {
  14217. return this.parseAsyncArrowUnaryFunction(id);
  14218. }
  14219. }
  14220. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  14221. this.next();
  14222. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  14223. }
  14224. return id;
  14225. }
  14226. case types._do:
  14227. {
  14228. return this.parseDo();
  14229. }
  14230. case types.regexp:
  14231. {
  14232. const value = this.state.value;
  14233. node = this.parseLiteral(value.value, "RegExpLiteral");
  14234. node.pattern = value.pattern;
  14235. node.flags = value.flags;
  14236. return node;
  14237. }
  14238. case types.num:
  14239. return this.parseLiteral(this.state.value, "NumericLiteral");
  14240. case types.bigint:
  14241. return this.parseLiteral(this.state.value, "BigIntLiteral");
  14242. case types.decimal:
  14243. return this.parseLiteral(this.state.value, "DecimalLiteral");
  14244. case types.string:
  14245. return this.parseLiteral(this.state.value, "StringLiteral");
  14246. case types._null:
  14247. node = this.startNode();
  14248. this.next();
  14249. return this.finishNode(node, "NullLiteral");
  14250. case types._true:
  14251. case types._false:
  14252. return this.parseBooleanLiteral();
  14253. case types.parenL:
  14254. return this.parseParenAndDistinguishExpression(canBeArrow);
  14255. case types.bracketBarL:
  14256. case types.bracketHashL:
  14257. {
  14258. return this.parseArrayLike(this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR, false, true, refExpressionErrors);
  14259. }
  14260. case types.bracketL:
  14261. {
  14262. return this.parseArrayLike(types.bracketR, true, false, refExpressionErrors);
  14263. }
  14264. case types.braceBarL:
  14265. case types.braceHashL:
  14266. {
  14267. return this.parseObjectLike(this.state.type === types.braceBarL ? types.braceBarR : types.braceR, false, true, refExpressionErrors);
  14268. }
  14269. case types.braceL:
  14270. {
  14271. return this.parseObjectLike(types.braceR, false, false, refExpressionErrors);
  14272. }
  14273. case types._function:
  14274. return this.parseFunctionOrFunctionSent();
  14275. case types.at:
  14276. this.parseDecorators();
  14277. case types._class:
  14278. node = this.startNode();
  14279. this.takeDecorators(node);
  14280. return this.parseClass(node, false);
  14281. case types._new:
  14282. return this.parseNewOrNewTarget();
  14283. case types.backQuote:
  14284. return this.parseTemplate(false);
  14285. case types.doubleColon:
  14286. {
  14287. node = this.startNode();
  14288. this.next();
  14289. node.object = null;
  14290. const callee = node.callee = this.parseNoCallExpr();
  14291. if (callee.type === "MemberExpression") {
  14292. return this.finishNode(node, "BindExpression");
  14293. } else {
  14294. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  14295. }
  14296. }
  14297. case types.hash:
  14298. {
  14299. if (this.state.inPipeline) {
  14300. node = this.startNode();
  14301. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  14302. this.raise(node.start, ErrorMessages.PrimaryTopicRequiresSmartPipeline);
  14303. }
  14304. this.next();
  14305. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  14306. this.raise(node.start, ErrorMessages.PrimaryTopicNotAllowed);
  14307. }
  14308. this.registerTopicReference();
  14309. return this.finishNode(node, "PipelinePrimaryTopicReference");
  14310. }
  14311. const nextCh = this.input.codePointAt(this.state.end);
  14312. if (isIdentifierStart(nextCh) || nextCh === 92) {
  14313. const start = this.state.start;
  14314. node = this.parseMaybePrivateName(true);
  14315. if (this.match(types._in)) {
  14316. this.expectPlugin("privateIn");
  14317. this.classScope.usePrivateName(node.id.name, node.start);
  14318. } else if (this.hasPlugin("privateIn")) {
  14319. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, node.id.name);
  14320. } else {
  14321. throw this.unexpected(start);
  14322. }
  14323. return node;
  14324. }
  14325. }
  14326. case types.relational:
  14327. {
  14328. if (this.state.value === "<") {
  14329. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  14330. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  14331. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  14332. }
  14333. }
  14334. }
  14335. default:
  14336. throw this.unexpected();
  14337. }
  14338. }
  14339. parseAsyncArrowUnaryFunction(id) {
  14340. const node = this.startNodeAtNode(id);
  14341. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  14342. const params = [this.parseIdentifier()];
  14343. this.prodParam.exit();
  14344. if (this.hasPrecedingLineBreak()) {
  14345. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  14346. }
  14347. this.expect(types.arrow);
  14348. this.parseArrowExpression(node, params, true);
  14349. return node;
  14350. }
  14351. parseDo() {
  14352. this.expectPlugin("doExpressions");
  14353. const node = this.startNode();
  14354. this.next();
  14355. const oldLabels = this.state.labels;
  14356. this.state.labels = [];
  14357. node.body = this.parseBlock();
  14358. this.state.labels = oldLabels;
  14359. return this.finishNode(node, "DoExpression");
  14360. }
  14361. parseSuper() {
  14362. const node = this.startNode();
  14363. this.next();
  14364. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  14365. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  14366. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  14367. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  14368. }
  14369. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  14370. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  14371. }
  14372. return this.finishNode(node, "Super");
  14373. }
  14374. parseBooleanLiteral() {
  14375. const node = this.startNode();
  14376. node.value = this.match(types._true);
  14377. this.next();
  14378. return this.finishNode(node, "BooleanLiteral");
  14379. }
  14380. parseMaybePrivateName(isPrivateNameAllowed) {
  14381. const isPrivate = this.match(types.hash);
  14382. if (isPrivate) {
  14383. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  14384. if (!isPrivateNameAllowed) {
  14385. this.raise(this.state.pos, ErrorMessages.UnexpectedPrivateField);
  14386. }
  14387. const node = this.startNode();
  14388. this.next();
  14389. this.assertNoSpace("Unexpected space between # and identifier");
  14390. node.id = this.parseIdentifier(true);
  14391. return this.finishNode(node, "PrivateName");
  14392. } else {
  14393. return this.parseIdentifier(true);
  14394. }
  14395. }
  14396. parseFunctionOrFunctionSent() {
  14397. const node = this.startNode();
  14398. this.next();
  14399. if (this.prodParam.hasYield && this.match(types.dot)) {
  14400. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  14401. this.next();
  14402. return this.parseMetaProperty(node, meta, "sent");
  14403. }
  14404. return this.parseFunction(node);
  14405. }
  14406. parseMetaProperty(node, meta, propertyName) {
  14407. node.meta = meta;
  14408. if (meta.name === "function" && propertyName === "sent") {
  14409. if (this.isContextual(propertyName)) {
  14410. this.expectPlugin("functionSent");
  14411. } else if (!this.hasPlugin("functionSent")) {
  14412. this.unexpected();
  14413. }
  14414. }
  14415. const containsEsc = this.state.containsEsc;
  14416. node.property = this.parseIdentifier(true);
  14417. if (node.property.name !== propertyName || containsEsc) {
  14418. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  14419. }
  14420. return this.finishNode(node, "MetaProperty");
  14421. }
  14422. parseImportMetaProperty(node) {
  14423. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  14424. this.next();
  14425. if (this.isContextual("meta")) {
  14426. if (!this.inModule) {
  14427. this.raiseWithData(id.start, {
  14428. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  14429. }, ErrorMessages.ImportMetaOutsideModule);
  14430. }
  14431. this.sawUnambiguousESM = true;
  14432. }
  14433. return this.parseMetaProperty(node, id, "meta");
  14434. }
  14435. parseLiteral(value, type, startPos, startLoc) {
  14436. startPos = startPos || this.state.start;
  14437. startLoc = startLoc || this.state.startLoc;
  14438. const node = this.startNodeAt(startPos, startLoc);
  14439. this.addExtra(node, "rawValue", value);
  14440. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  14441. node.value = value;
  14442. this.next();
  14443. return this.finishNode(node, type);
  14444. }
  14445. parseParenAndDistinguishExpression(canBeArrow) {
  14446. const startPos = this.state.start;
  14447. const startLoc = this.state.startLoc;
  14448. let val;
  14449. this.next();
  14450. this.expressionScope.enter(newArrowHeadScope());
  14451. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  14452. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  14453. this.state.maybeInArrowParameters = true;
  14454. this.state.inFSharpPipelineDirectBody = false;
  14455. const innerStartPos = this.state.start;
  14456. const innerStartLoc = this.state.startLoc;
  14457. const exprList = [];
  14458. const refExpressionErrors = new ExpressionErrors();
  14459. const refNeedsArrowPos = {
  14460. start: 0
  14461. };
  14462. let first = true;
  14463. let spreadStart;
  14464. let optionalCommaStart;
  14465. while (!this.match(types.parenR)) {
  14466. if (first) {
  14467. first = false;
  14468. } else {
  14469. this.expect(types.comma, refNeedsArrowPos.start || null);
  14470. if (this.match(types.parenR)) {
  14471. optionalCommaStart = this.state.start;
  14472. break;
  14473. }
  14474. }
  14475. if (this.match(types.ellipsis)) {
  14476. const spreadNodeStartPos = this.state.start;
  14477. const spreadNodeStartLoc = this.state.startLoc;
  14478. spreadStart = this.state.start;
  14479. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  14480. this.checkCommaAfterRest(41);
  14481. break;
  14482. } else {
  14483. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  14484. }
  14485. }
  14486. const innerEndPos = this.state.lastTokEnd;
  14487. const innerEndLoc = this.state.lastTokEndLoc;
  14488. this.expect(types.parenR);
  14489. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  14490. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  14491. let arrowNode = this.startNodeAt(startPos, startLoc);
  14492. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  14493. this.expressionScope.validateAsPattern();
  14494. this.expressionScope.exit();
  14495. this.parseArrowExpression(arrowNode, exprList, false);
  14496. return arrowNode;
  14497. }
  14498. this.expressionScope.exit();
  14499. if (!exprList.length) {
  14500. this.unexpected(this.state.lastTokStart);
  14501. }
  14502. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  14503. if (spreadStart) this.unexpected(spreadStart);
  14504. this.checkExpressionErrors(refExpressionErrors, true);
  14505. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  14506. this.toReferencedListDeep(exprList, true);
  14507. if (exprList.length > 1) {
  14508. val = this.startNodeAt(innerStartPos, innerStartLoc);
  14509. val.expressions = exprList;
  14510. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  14511. } else {
  14512. val = exprList[0];
  14513. }
  14514. if (!this.options.createParenthesizedExpressions) {
  14515. this.addExtra(val, "parenthesized", true);
  14516. this.addExtra(val, "parenStart", startPos);
  14517. return val;
  14518. }
  14519. const parenExpression = this.startNodeAt(startPos, startLoc);
  14520. parenExpression.expression = val;
  14521. this.finishNode(parenExpression, "ParenthesizedExpression");
  14522. return parenExpression;
  14523. }
  14524. shouldParseArrow() {
  14525. return !this.canInsertSemicolon();
  14526. }
  14527. parseArrow(node) {
  14528. if (this.eat(types.arrow)) {
  14529. return node;
  14530. }
  14531. }
  14532. parseParenItem(node, startPos, startLoc) {
  14533. return node;
  14534. }
  14535. parseNewOrNewTarget() {
  14536. const node = this.startNode();
  14537. this.next();
  14538. if (this.match(types.dot)) {
  14539. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  14540. this.next();
  14541. const metaProp = this.parseMetaProperty(node, meta, "target");
  14542. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  14543. let error = ErrorMessages.UnexpectedNewTarget;
  14544. if (this.hasPlugin("classProperties")) {
  14545. error += " or class properties";
  14546. }
  14547. this.raise(metaProp.start, error);
  14548. }
  14549. return metaProp;
  14550. }
  14551. return this.parseNew(node);
  14552. }
  14553. parseNew(node) {
  14554. node.callee = this.parseNoCallExpr();
  14555. if (node.callee.type === "Import") {
  14556. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  14557. } else if (node.callee.type === "OptionalMemberExpression" || node.callee.type === "OptionalCallExpression") {
  14558. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  14559. } else if (this.eat(types.questionDot)) {
  14560. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  14561. }
  14562. this.parseNewArguments(node);
  14563. return this.finishNode(node, "NewExpression");
  14564. }
  14565. parseNewArguments(node) {
  14566. if (this.eat(types.parenL)) {
  14567. const args = this.parseExprList(types.parenR);
  14568. this.toReferencedList(args);
  14569. node.arguments = args;
  14570. } else {
  14571. node.arguments = [];
  14572. }
  14573. }
  14574. parseTemplateElement(isTagged) {
  14575. const elem = this.startNode();
  14576. if (this.state.value === null) {
  14577. if (!isTagged) {
  14578. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  14579. }
  14580. }
  14581. elem.value = {
  14582. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  14583. cooked: this.state.value
  14584. };
  14585. this.next();
  14586. elem.tail = this.match(types.backQuote);
  14587. return this.finishNode(elem, "TemplateElement");
  14588. }
  14589. parseTemplate(isTagged) {
  14590. const node = this.startNode();
  14591. this.next();
  14592. node.expressions = [];
  14593. let curElt = this.parseTemplateElement(isTagged);
  14594. node.quasis = [curElt];
  14595. while (!curElt.tail) {
  14596. this.expect(types.dollarBraceL);
  14597. node.expressions.push(this.parseTemplateSubstitution());
  14598. this.expect(types.braceR);
  14599. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  14600. }
  14601. this.next();
  14602. return this.finishNode(node, "TemplateLiteral");
  14603. }
  14604. parseTemplateSubstitution() {
  14605. return this.parseExpression();
  14606. }
  14607. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  14608. if (isRecord) {
  14609. this.expectPlugin("recordAndTuple");
  14610. }
  14611. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  14612. this.state.inFSharpPipelineDirectBody = false;
  14613. const propHash = Object.create(null);
  14614. let first = true;
  14615. const node = this.startNode();
  14616. node.properties = [];
  14617. this.next();
  14618. while (!this.match(close)) {
  14619. if (first) {
  14620. first = false;
  14621. } else {
  14622. this.expect(types.comma);
  14623. if (this.match(close)) {
  14624. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  14625. break;
  14626. }
  14627. }
  14628. const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
  14629. if (!isPattern) {
  14630. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  14631. }
  14632. if (isRecord && prop.type !== "ObjectProperty" && prop.type !== "SpreadElement") {
  14633. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  14634. }
  14635. if (prop.shorthand) {
  14636. this.addExtra(prop, "shorthand", true);
  14637. }
  14638. node.properties.push(prop);
  14639. }
  14640. this.state.exprAllowed = false;
  14641. this.next();
  14642. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  14643. let type = "ObjectExpression";
  14644. if (isPattern) {
  14645. type = "ObjectPattern";
  14646. } else if (isRecord) {
  14647. type = "RecordExpression";
  14648. }
  14649. return this.finishNode(node, type);
  14650. }
  14651. maybeAsyncOrAccessorProp(prop) {
  14652. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(types.bracketL) || this.match(types.star));
  14653. }
  14654. parsePropertyDefinition(isPattern, refExpressionErrors) {
  14655. let decorators = [];
  14656. if (this.match(types.at)) {
  14657. if (this.hasPlugin("decorators")) {
  14658. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  14659. }
  14660. while (this.match(types.at)) {
  14661. decorators.push(this.parseDecorator());
  14662. }
  14663. }
  14664. const prop = this.startNode();
  14665. let isGenerator = false;
  14666. let isAsync = false;
  14667. let isAccessor = false;
  14668. let startPos;
  14669. let startLoc;
  14670. if (this.match(types.ellipsis)) {
  14671. if (decorators.length) this.unexpected();
  14672. if (isPattern) {
  14673. this.next();
  14674. prop.argument = this.parseIdentifier();
  14675. this.checkCommaAfterRest(125);
  14676. return this.finishNode(prop, "RestElement");
  14677. }
  14678. return this.parseSpread();
  14679. }
  14680. if (decorators.length) {
  14681. prop.decorators = decorators;
  14682. decorators = [];
  14683. }
  14684. prop.method = false;
  14685. if (isPattern || refExpressionErrors) {
  14686. startPos = this.state.start;
  14687. startLoc = this.state.startLoc;
  14688. }
  14689. if (!isPattern) {
  14690. isGenerator = this.eat(types.star);
  14691. }
  14692. const containsEsc = this.state.containsEsc;
  14693. const key = this.parsePropertyName(prop, false);
  14694. if (!isPattern && !isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  14695. const keyName = key.name;
  14696. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  14697. isAsync = true;
  14698. isGenerator = this.eat(types.star);
  14699. this.parsePropertyName(prop, false);
  14700. }
  14701. if (keyName === "get" || keyName === "set") {
  14702. isAccessor = true;
  14703. prop.kind = keyName;
  14704. if (this.match(types.star)) {
  14705. isGenerator = true;
  14706. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  14707. this.next();
  14708. }
  14709. this.parsePropertyName(prop, false);
  14710. }
  14711. }
  14712. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  14713. return prop;
  14714. }
  14715. getGetterSetterExpectedParamCount(method) {
  14716. return method.kind === "get" ? 0 : 1;
  14717. }
  14718. getObjectOrClassMethodParams(method) {
  14719. return method.params;
  14720. }
  14721. checkGetterSetterParams(method) {
  14722. var _params;
  14723. const paramCount = this.getGetterSetterExpectedParamCount(method);
  14724. const params = this.getObjectOrClassMethodParams(method);
  14725. const start = method.start;
  14726. if (params.length !== paramCount) {
  14727. if (method.kind === "get") {
  14728. this.raise(start, ErrorMessages.BadGetterArity);
  14729. } else {
  14730. this.raise(start, ErrorMessages.BadSetterArity);
  14731. }
  14732. }
  14733. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  14734. this.raise(start, ErrorMessages.BadSetterRestParameter);
  14735. }
  14736. }
  14737. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  14738. if (isAccessor) {
  14739. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  14740. this.checkGetterSetterParams(prop);
  14741. return prop;
  14742. }
  14743. if (isAsync || isGenerator || this.match(types.parenL)) {
  14744. if (isPattern) this.unexpected();
  14745. prop.kind = "method";
  14746. prop.method = true;
  14747. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  14748. }
  14749. }
  14750. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  14751. prop.shorthand = false;
  14752. if (this.eat(types.colon)) {
  14753. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  14754. return this.finishNode(prop, "ObjectProperty");
  14755. }
  14756. if (!prop.computed && prop.key.type === "Identifier") {
  14757. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  14758. if (isPattern) {
  14759. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  14760. } else if (this.match(types.eq) && refExpressionErrors) {
  14761. if (refExpressionErrors.shorthandAssign === -1) {
  14762. refExpressionErrors.shorthandAssign = this.state.start;
  14763. }
  14764. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  14765. } else {
  14766. prop.value = prop.key.__clone();
  14767. }
  14768. prop.shorthand = true;
  14769. return this.finishNode(prop, "ObjectProperty");
  14770. }
  14771. }
  14772. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  14773. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  14774. if (!node) this.unexpected();
  14775. return node;
  14776. }
  14777. parsePropertyName(prop, isPrivateNameAllowed) {
  14778. if (this.eat(types.bracketL)) {
  14779. prop.computed = true;
  14780. prop.key = this.parseMaybeAssignAllowIn();
  14781. this.expect(types.bracketR);
  14782. } else {
  14783. const oldInPropertyName = this.state.inPropertyName;
  14784. this.state.inPropertyName = true;
  14785. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) || this.match(types.decimal) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  14786. if (prop.key.type !== "PrivateName") {
  14787. prop.computed = false;
  14788. }
  14789. this.state.inPropertyName = oldInPropertyName;
  14790. }
  14791. return prop.key;
  14792. }
  14793. initFunction(node, isAsync) {
  14794. node.id = null;
  14795. node.generator = false;
  14796. node.async = !!isAsync;
  14797. }
  14798. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  14799. this.initFunction(node, isAsync);
  14800. node.generator = !!isGenerator;
  14801. const allowModifiers = isConstructor;
  14802. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  14803. this.prodParam.enter(functionFlags(isAsync, node.generator));
  14804. this.parseFunctionParams(node, allowModifiers);
  14805. this.parseFunctionBodyAndFinish(node, type, true);
  14806. this.prodParam.exit();
  14807. this.scope.exit();
  14808. return node;
  14809. }
  14810. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  14811. if (isTuple) {
  14812. this.expectPlugin("recordAndTuple");
  14813. }
  14814. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  14815. this.state.inFSharpPipelineDirectBody = false;
  14816. const node = this.startNode();
  14817. this.next();
  14818. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  14819. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  14820. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  14821. }
  14822. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  14823. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  14824. let flags = functionFlags(isAsync, false);
  14825. if (!this.match(types.bracketL) && this.prodParam.hasIn) {
  14826. flags |= PARAM_IN;
  14827. }
  14828. this.prodParam.enter(flags);
  14829. this.initFunction(node, isAsync);
  14830. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  14831. if (params) {
  14832. this.state.maybeInArrowParameters = true;
  14833. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  14834. }
  14835. this.state.maybeInArrowParameters = false;
  14836. this.parseFunctionBody(node, true);
  14837. this.prodParam.exit();
  14838. this.scope.exit();
  14839. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  14840. return this.finishNode(node, "ArrowFunctionExpression");
  14841. }
  14842. setArrowFunctionParameters(node, params, trailingCommaPos) {
  14843. node.params = this.toAssignableList(params, trailingCommaPos, false);
  14844. }
  14845. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  14846. this.parseFunctionBody(node, false, isMethod);
  14847. this.finishNode(node, type);
  14848. }
  14849. parseFunctionBody(node, allowExpression, isMethod = false) {
  14850. const isExpression = allowExpression && !this.match(types.braceL);
  14851. this.expressionScope.enter(newExpressionScope());
  14852. if (isExpression) {
  14853. node.body = this.parseMaybeAssign();
  14854. this.checkParams(node, false, allowExpression, false);
  14855. } else {
  14856. const oldStrict = this.state.strict;
  14857. const oldLabels = this.state.labels;
  14858. this.state.labels = [];
  14859. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  14860. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  14861. const nonSimple = !this.isSimpleParamList(node.params);
  14862. if (hasStrictModeDirective && nonSimple) {
  14863. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  14864. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  14865. }
  14866. const strictModeChanged = !oldStrict && this.state.strict;
  14867. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  14868. if (this.state.strict && node.id) {
  14869. this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged);
  14870. }
  14871. });
  14872. this.prodParam.exit();
  14873. this.expressionScope.exit();
  14874. this.state.labels = oldLabels;
  14875. }
  14876. }
  14877. isSimpleParamList(params) {
  14878. for (let i = 0, len = params.length; i < len; i++) {
  14879. if (params[i].type !== "Identifier") return false;
  14880. }
  14881. return true;
  14882. }
  14883. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  14884. const checkClashes = new Set();
  14885. for (let _i2 = 0, _node$params = node.params; _i2 < _node$params.length; _i2++) {
  14886. const param = _node$params[_i2];
  14887. this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged);
  14888. }
  14889. }
  14890. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  14891. const elts = [];
  14892. let first = true;
  14893. while (!this.eat(close)) {
  14894. if (first) {
  14895. first = false;
  14896. } else {
  14897. this.expect(types.comma);
  14898. if (this.match(close)) {
  14899. if (nodeForExtra) {
  14900. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  14901. }
  14902. this.next();
  14903. break;
  14904. }
  14905. }
  14906. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  14907. }
  14908. return elts;
  14909. }
  14910. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  14911. let elt;
  14912. if (this.match(types.comma)) {
  14913. if (!allowEmpty) {
  14914. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  14915. }
  14916. elt = null;
  14917. } else if (this.match(types.ellipsis)) {
  14918. const spreadNodeStartPos = this.state.start;
  14919. const spreadNodeStartLoc = this.state.startLoc;
  14920. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  14921. } else if (this.match(types.question)) {
  14922. this.expectPlugin("partialApplication");
  14923. if (!allowPlaceholder) {
  14924. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  14925. }
  14926. const node = this.startNode();
  14927. this.next();
  14928. elt = this.finishNode(node, "ArgumentPlaceholder");
  14929. } else {
  14930. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  14931. }
  14932. return elt;
  14933. }
  14934. parseIdentifier(liberal) {
  14935. const node = this.startNode();
  14936. const name = this.parseIdentifierName(node.start, liberal);
  14937. return this.createIdentifier(node, name);
  14938. }
  14939. createIdentifier(node, name) {
  14940. node.name = name;
  14941. node.loc.identifierName = name;
  14942. return this.finishNode(node, "Identifier");
  14943. }
  14944. parseIdentifierName(pos, liberal) {
  14945. let name;
  14946. const {
  14947. start,
  14948. type
  14949. } = this.state;
  14950. if (type === types.name) {
  14951. name = this.state.value;
  14952. } else if (type.keyword) {
  14953. name = type.keyword;
  14954. const curContext = this.curContext();
  14955. if ((type === types._class || type === types._function) && (curContext === types$1.functionStatement || curContext === types$1.functionExpression)) {
  14956. this.state.context.pop();
  14957. }
  14958. } else {
  14959. throw this.unexpected();
  14960. }
  14961. if (liberal) {
  14962. this.state.type = types.name;
  14963. } else {
  14964. this.checkReservedWord(name, start, !!type.keyword, false);
  14965. }
  14966. this.next();
  14967. return name;
  14968. }
  14969. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  14970. if (this.prodParam.hasYield && word === "yield") {
  14971. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  14972. return;
  14973. }
  14974. if (word === "await") {
  14975. if (this.prodParam.hasAwait) {
  14976. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  14977. return;
  14978. } else {
  14979. this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
  14980. }
  14981. }
  14982. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  14983. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  14984. return;
  14985. }
  14986. if (checkKeywords && isKeyword(word)) {
  14987. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  14988. return;
  14989. }
  14990. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  14991. if (reservedTest(word, this.inModule)) {
  14992. if (!this.prodParam.hasAwait && word === "await") {
  14993. this.raise(startLoc, this.hasPlugin("topLevelAwait") ? ErrorMessages.AwaitNotInAsyncContext : ErrorMessages.AwaitNotInAsyncFunction);
  14994. } else {
  14995. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  14996. }
  14997. }
  14998. }
  14999. isAwaitAllowed() {
  15000. if (this.scope.inFunction) return this.prodParam.hasAwait;
  15001. if (this.options.allowAwaitOutsideFunction) return true;
  15002. if (this.hasPlugin("topLevelAwait")) {
  15003. return this.inModule && this.prodParam.hasAwait;
  15004. }
  15005. return false;
  15006. }
  15007. parseAwait() {
  15008. const node = this.startNode();
  15009. this.next();
  15010. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  15011. if (this.eat(types.star)) {
  15012. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  15013. }
  15014. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  15015. 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)) {
  15016. this.ambiguousScriptDifferentAst = true;
  15017. } else {
  15018. this.sawUnambiguousESM = true;
  15019. }
  15020. }
  15021. if (!this.state.soloAwait) {
  15022. node.argument = this.parseMaybeUnary();
  15023. }
  15024. return this.finishNode(node, "AwaitExpression");
  15025. }
  15026. parseYield() {
  15027. const node = this.startNode();
  15028. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
  15029. this.next();
  15030. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  15031. node.delegate = false;
  15032. node.argument = null;
  15033. } else {
  15034. node.delegate = this.eat(types.star);
  15035. node.argument = this.parseMaybeAssign();
  15036. }
  15037. return this.finishNode(node, "YieldExpression");
  15038. }
  15039. checkPipelineAtInfixOperator(left, leftStartPos) {
  15040. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  15041. if (left.type === "SequenceExpression") {
  15042. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  15043. }
  15044. }
  15045. }
  15046. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  15047. this.checkSmartPipelineBodyEarlyErrors(childExpression, startPos);
  15048. return this.parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc);
  15049. }
  15050. checkSmartPipelineBodyEarlyErrors(childExpression, startPos) {
  15051. if (this.match(types.arrow)) {
  15052. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  15053. } else if (childExpression.type === "SequenceExpression") {
  15054. this.raise(startPos, ErrorMessages.PipelineBodySequenceExpression);
  15055. }
  15056. }
  15057. parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc) {
  15058. const bodyNode = this.startNodeAt(startPos, startLoc);
  15059. const isSimpleReference = this.isSimpleReference(childExpression);
  15060. if (isSimpleReference) {
  15061. bodyNode.callee = childExpression;
  15062. } else {
  15063. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  15064. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  15065. }
  15066. bodyNode.expression = childExpression;
  15067. }
  15068. return this.finishNode(bodyNode, isSimpleReference ? "PipelineBareFunction" : "PipelineTopicExpression");
  15069. }
  15070. isSimpleReference(expression) {
  15071. switch (expression.type) {
  15072. case "MemberExpression":
  15073. return !expression.computed && this.isSimpleReference(expression.object);
  15074. case "Identifier":
  15075. return true;
  15076. default:
  15077. return false;
  15078. }
  15079. }
  15080. withTopicPermittingContext(callback) {
  15081. const outerContextTopicState = this.state.topicContext;
  15082. this.state.topicContext = {
  15083. maxNumOfResolvableTopics: 1,
  15084. maxTopicIndex: null
  15085. };
  15086. try {
  15087. return callback();
  15088. } finally {
  15089. this.state.topicContext = outerContextTopicState;
  15090. }
  15091. }
  15092. withTopicForbiddingContext(callback) {
  15093. const outerContextTopicState = this.state.topicContext;
  15094. this.state.topicContext = {
  15095. maxNumOfResolvableTopics: 0,
  15096. maxTopicIndex: null
  15097. };
  15098. try {
  15099. return callback();
  15100. } finally {
  15101. this.state.topicContext = outerContextTopicState;
  15102. }
  15103. }
  15104. withSoloAwaitPermittingContext(callback) {
  15105. const outerContextSoloAwaitState = this.state.soloAwait;
  15106. this.state.soloAwait = true;
  15107. try {
  15108. return callback();
  15109. } finally {
  15110. this.state.soloAwait = outerContextSoloAwaitState;
  15111. }
  15112. }
  15113. allowInAnd(callback) {
  15114. const flags = this.prodParam.currentFlags();
  15115. const prodParamToSet = PARAM_IN & ~flags;
  15116. if (prodParamToSet) {
  15117. this.prodParam.enter(flags | PARAM_IN);
  15118. try {
  15119. return callback();
  15120. } finally {
  15121. this.prodParam.exit();
  15122. }
  15123. }
  15124. return callback();
  15125. }
  15126. disallowInAnd(callback) {
  15127. const flags = this.prodParam.currentFlags();
  15128. const prodParamToClear = PARAM_IN & flags;
  15129. if (prodParamToClear) {
  15130. this.prodParam.enter(flags & ~PARAM_IN);
  15131. try {
  15132. return callback();
  15133. } finally {
  15134. this.prodParam.exit();
  15135. }
  15136. }
  15137. return callback();
  15138. }
  15139. registerTopicReference() {
  15140. this.state.topicContext.maxTopicIndex = 0;
  15141. }
  15142. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  15143. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  15144. }
  15145. topicReferenceWasUsedInCurrentTopicContext() {
  15146. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  15147. }
  15148. parseFSharpPipelineBody(prec) {
  15149. const startPos = this.state.start;
  15150. const startLoc = this.state.startLoc;
  15151. this.state.potentialArrowAt = this.state.start;
  15152. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  15153. this.state.inFSharpPipelineDirectBody = true;
  15154. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec);
  15155. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  15156. return ret;
  15157. }
  15158. }
  15159. const loopLabel = {
  15160. kind: "loop"
  15161. },
  15162. switchLabel = {
  15163. kind: "switch"
  15164. };
  15165. const FUNC_NO_FLAGS = 0b000,
  15166. FUNC_STATEMENT = 0b001,
  15167. FUNC_HANGING_STATEMENT = 0b010,
  15168. FUNC_NULLABLE_ID = 0b100;
  15169. const loneSurrogate = /[\uD800-\uDFFF]/u;
  15170. class StatementParser extends ExpressionParser {
  15171. parseTopLevel(file, program) {
  15172. program.sourceType = this.options.sourceType;
  15173. program.interpreter = this.parseInterpreterDirective();
  15174. this.parseBlockBody(program, true, true, types.eof);
  15175. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  15176. for (let _i = 0, _Array$from = Array.from(this.scope.undefinedExports); _i < _Array$from.length; _i++) {
  15177. const [name] = _Array$from[_i];
  15178. const pos = this.scope.undefinedExports.get(name);
  15179. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  15180. }
  15181. }
  15182. file.program = this.finishNode(program, "Program");
  15183. file.comments = this.state.comments;
  15184. if (this.options.tokens) file.tokens = this.tokens;
  15185. return this.finishNode(file, "File");
  15186. }
  15187. stmtToDirective(stmt) {
  15188. const expr = stmt.expression;
  15189. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  15190. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  15191. const raw = this.input.slice(expr.start, expr.end);
  15192. const val = directiveLiteral.value = raw.slice(1, -1);
  15193. this.addExtra(directiveLiteral, "raw", raw);
  15194. this.addExtra(directiveLiteral, "rawValue", val);
  15195. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  15196. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  15197. }
  15198. parseInterpreterDirective() {
  15199. if (!this.match(types.interpreterDirective)) {
  15200. return null;
  15201. }
  15202. const node = this.startNode();
  15203. node.value = this.state.value;
  15204. this.next();
  15205. return this.finishNode(node, "InterpreterDirective");
  15206. }
  15207. isLet(context) {
  15208. if (!this.isContextual("let")) {
  15209. return false;
  15210. }
  15211. const next = this.nextTokenStart();
  15212. const nextCh = this.input.charCodeAt(next);
  15213. if (nextCh === 91) return true;
  15214. if (context) return false;
  15215. if (nextCh === 123) return true;
  15216. if (isIdentifierStart(nextCh)) {
  15217. let pos = next + 1;
  15218. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  15219. ++pos;
  15220. }
  15221. const ident = this.input.slice(next, pos);
  15222. if (!keywordRelationalOperator.test(ident)) return true;
  15223. }
  15224. return false;
  15225. }
  15226. parseStatement(context, topLevel) {
  15227. if (this.match(types.at)) {
  15228. this.parseDecorators(true);
  15229. }
  15230. return this.parseStatementContent(context, topLevel);
  15231. }
  15232. parseStatementContent(context, topLevel) {
  15233. let starttype = this.state.type;
  15234. const node = this.startNode();
  15235. let kind;
  15236. if (this.isLet(context)) {
  15237. starttype = types._var;
  15238. kind = "let";
  15239. }
  15240. switch (starttype) {
  15241. case types._break:
  15242. case types._continue:
  15243. return this.parseBreakContinueStatement(node, starttype.keyword);
  15244. case types._debugger:
  15245. return this.parseDebuggerStatement(node);
  15246. case types._do:
  15247. return this.parseDoStatement(node);
  15248. case types._for:
  15249. return this.parseForStatement(node);
  15250. case types._function:
  15251. if (this.lookaheadCharCode() === 46) break;
  15252. if (context) {
  15253. if (this.state.strict) {
  15254. this.raise(this.state.start, ErrorMessages.StrictFunction);
  15255. } else if (context !== "if" && context !== "label") {
  15256. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  15257. }
  15258. }
  15259. return this.parseFunctionStatement(node, false, !context);
  15260. case types._class:
  15261. if (context) this.unexpected();
  15262. return this.parseClass(node, true);
  15263. case types._if:
  15264. return this.parseIfStatement(node);
  15265. case types._return:
  15266. return this.parseReturnStatement(node);
  15267. case types._switch:
  15268. return this.parseSwitchStatement(node);
  15269. case types._throw:
  15270. return this.parseThrowStatement(node);
  15271. case types._try:
  15272. return this.parseTryStatement(node);
  15273. case types._const:
  15274. case types._var:
  15275. kind = kind || this.state.value;
  15276. if (context && kind !== "var") {
  15277. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  15278. }
  15279. return this.parseVarStatement(node, kind);
  15280. case types._while:
  15281. return this.parseWhileStatement(node);
  15282. case types._with:
  15283. return this.parseWithStatement(node);
  15284. case types.braceL:
  15285. return this.parseBlock();
  15286. case types.semi:
  15287. return this.parseEmptyStatement(node);
  15288. case types._import:
  15289. {
  15290. const nextTokenCharCode = this.lookaheadCharCode();
  15291. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  15292. break;
  15293. }
  15294. }
  15295. case types._export:
  15296. {
  15297. if (!this.options.allowImportExportEverywhere && !topLevel) {
  15298. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  15299. }
  15300. this.next();
  15301. let result;
  15302. if (starttype === types._import) {
  15303. result = this.parseImport(node);
  15304. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  15305. this.sawUnambiguousESM = true;
  15306. }
  15307. } else {
  15308. result = this.parseExport(node);
  15309. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  15310. this.sawUnambiguousESM = true;
  15311. }
  15312. }
  15313. this.assertModuleNodeAllowed(node);
  15314. return result;
  15315. }
  15316. default:
  15317. {
  15318. if (this.isAsyncFunction()) {
  15319. if (context) {
  15320. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  15321. }
  15322. this.next();
  15323. return this.parseFunctionStatement(node, true, !context);
  15324. }
  15325. }
  15326. }
  15327. const maybeName = this.state.value;
  15328. const expr = this.parseExpression();
  15329. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  15330. return this.parseLabeledStatement(node, maybeName, expr, context);
  15331. } else {
  15332. return this.parseExpressionStatement(node, expr);
  15333. }
  15334. }
  15335. assertModuleNodeAllowed(node) {
  15336. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  15337. this.raiseWithData(node.start, {
  15338. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  15339. }, ErrorMessages.ImportOutsideModule);
  15340. }
  15341. }
  15342. takeDecorators(node) {
  15343. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  15344. if (decorators.length) {
  15345. node.decorators = decorators;
  15346. this.resetStartLocationFromNode(node, decorators[0]);
  15347. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  15348. }
  15349. }
  15350. canHaveLeadingDecorator() {
  15351. return this.match(types._class);
  15352. }
  15353. parseDecorators(allowExport) {
  15354. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  15355. while (this.match(types.at)) {
  15356. const decorator = this.parseDecorator();
  15357. currentContextDecorators.push(decorator);
  15358. }
  15359. if (this.match(types._export)) {
  15360. if (!allowExport) {
  15361. this.unexpected();
  15362. }
  15363. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  15364. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  15365. }
  15366. } else if (!this.canHaveLeadingDecorator()) {
  15367. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  15368. }
  15369. }
  15370. parseDecorator() {
  15371. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  15372. const node = this.startNode();
  15373. this.next();
  15374. if (this.hasPlugin("decorators")) {
  15375. this.state.decoratorStack.push([]);
  15376. const startPos = this.state.start;
  15377. const startLoc = this.state.startLoc;
  15378. let expr;
  15379. if (this.eat(types.parenL)) {
  15380. expr = this.parseExpression();
  15381. this.expect(types.parenR);
  15382. } else {
  15383. expr = this.parseIdentifier(false);
  15384. while (this.eat(types.dot)) {
  15385. const node = this.startNodeAt(startPos, startLoc);
  15386. node.object = expr;
  15387. node.property = this.parseIdentifier(true);
  15388. node.computed = false;
  15389. expr = this.finishNode(node, "MemberExpression");
  15390. }
  15391. }
  15392. node.expression = this.parseMaybeDecoratorArguments(expr);
  15393. this.state.decoratorStack.pop();
  15394. } else {
  15395. node.expression = this.parseExprSubscripts();
  15396. }
  15397. return this.finishNode(node, "Decorator");
  15398. }
  15399. parseMaybeDecoratorArguments(expr) {
  15400. if (this.eat(types.parenL)) {
  15401. const node = this.startNodeAtNode(expr);
  15402. node.callee = expr;
  15403. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  15404. this.toReferencedList(node.arguments);
  15405. return this.finishNode(node, "CallExpression");
  15406. }
  15407. return expr;
  15408. }
  15409. parseBreakContinueStatement(node, keyword) {
  15410. const isBreak = keyword === "break";
  15411. this.next();
  15412. if (this.isLineTerminator()) {
  15413. node.label = null;
  15414. } else {
  15415. node.label = this.parseIdentifier();
  15416. this.semicolon();
  15417. }
  15418. this.verifyBreakContinue(node, keyword);
  15419. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  15420. }
  15421. verifyBreakContinue(node, keyword) {
  15422. const isBreak = keyword === "break";
  15423. let i;
  15424. for (i = 0; i < this.state.labels.length; ++i) {
  15425. const lab = this.state.labels[i];
  15426. if (node.label == null || lab.name === node.label.name) {
  15427. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  15428. if (node.label && isBreak) break;
  15429. }
  15430. }
  15431. if (i === this.state.labels.length) {
  15432. this.raise(node.start, ErrorMessages.IllegalBreakContinue, keyword);
  15433. }
  15434. }
  15435. parseDebuggerStatement(node) {
  15436. this.next();
  15437. this.semicolon();
  15438. return this.finishNode(node, "DebuggerStatement");
  15439. }
  15440. parseHeaderExpression() {
  15441. this.expect(types.parenL);
  15442. const val = this.parseExpression();
  15443. this.expect(types.parenR);
  15444. return val;
  15445. }
  15446. parseDoStatement(node) {
  15447. this.next();
  15448. this.state.labels.push(loopLabel);
  15449. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  15450. this.state.labels.pop();
  15451. this.expect(types._while);
  15452. node.test = this.parseHeaderExpression();
  15453. this.eat(types.semi);
  15454. return this.finishNode(node, "DoWhileStatement");
  15455. }
  15456. parseForStatement(node) {
  15457. this.next();
  15458. this.state.labels.push(loopLabel);
  15459. let awaitAt = -1;
  15460. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  15461. awaitAt = this.state.lastTokStart;
  15462. }
  15463. this.scope.enter(SCOPE_OTHER);
  15464. this.expect(types.parenL);
  15465. if (this.match(types.semi)) {
  15466. if (awaitAt > -1) {
  15467. this.unexpected(awaitAt);
  15468. }
  15469. return this.parseFor(node, null);
  15470. }
  15471. const isLet = this.isLet();
  15472. if (this.match(types._var) || this.match(types._const) || isLet) {
  15473. const init = this.startNode();
  15474. const kind = isLet ? "let" : this.state.value;
  15475. this.next();
  15476. this.parseVar(init, true, kind);
  15477. this.finishNode(init, "VariableDeclaration");
  15478. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  15479. return this.parseForIn(node, init, awaitAt);
  15480. }
  15481. if (awaitAt > -1) {
  15482. this.unexpected(awaitAt);
  15483. }
  15484. return this.parseFor(node, init);
  15485. }
  15486. const refExpressionErrors = new ExpressionErrors();
  15487. const init = this.parseExpression(true, refExpressionErrors);
  15488. if (this.match(types._in) || this.isContextual("of")) {
  15489. this.toAssignable(init, true);
  15490. const description = this.isContextual("of") ? "for-of statement" : "for-in statement";
  15491. this.checkLVal(init, description);
  15492. return this.parseForIn(node, init, awaitAt);
  15493. } else {
  15494. this.checkExpressionErrors(refExpressionErrors, true);
  15495. }
  15496. if (awaitAt > -1) {
  15497. this.unexpected(awaitAt);
  15498. }
  15499. return this.parseFor(node, init);
  15500. }
  15501. parseFunctionStatement(node, isAsync, declarationPosition) {
  15502. this.next();
  15503. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  15504. }
  15505. parseIfStatement(node) {
  15506. this.next();
  15507. node.test = this.parseHeaderExpression();
  15508. node.consequent = this.parseStatement("if");
  15509. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  15510. return this.finishNode(node, "IfStatement");
  15511. }
  15512. parseReturnStatement(node) {
  15513. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  15514. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  15515. }
  15516. this.next();
  15517. if (this.isLineTerminator()) {
  15518. node.argument = null;
  15519. } else {
  15520. node.argument = this.parseExpression();
  15521. this.semicolon();
  15522. }
  15523. return this.finishNode(node, "ReturnStatement");
  15524. }
  15525. parseSwitchStatement(node) {
  15526. this.next();
  15527. node.discriminant = this.parseHeaderExpression();
  15528. const cases = node.cases = [];
  15529. this.expect(types.braceL);
  15530. this.state.labels.push(switchLabel);
  15531. this.scope.enter(SCOPE_OTHER);
  15532. let cur;
  15533. for (let sawDefault; !this.match(types.braceR);) {
  15534. if (this.match(types._case) || this.match(types._default)) {
  15535. const isCase = this.match(types._case);
  15536. if (cur) this.finishNode(cur, "SwitchCase");
  15537. cases.push(cur = this.startNode());
  15538. cur.consequent = [];
  15539. this.next();
  15540. if (isCase) {
  15541. cur.test = this.parseExpression();
  15542. } else {
  15543. if (sawDefault) {
  15544. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  15545. }
  15546. sawDefault = true;
  15547. cur.test = null;
  15548. }
  15549. this.expect(types.colon);
  15550. } else {
  15551. if (cur) {
  15552. cur.consequent.push(this.parseStatement(null));
  15553. } else {
  15554. this.unexpected();
  15555. }
  15556. }
  15557. }
  15558. this.scope.exit();
  15559. if (cur) this.finishNode(cur, "SwitchCase");
  15560. this.next();
  15561. this.state.labels.pop();
  15562. return this.finishNode(node, "SwitchStatement");
  15563. }
  15564. parseThrowStatement(node) {
  15565. this.next();
  15566. if (this.hasPrecedingLineBreak()) {
  15567. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  15568. }
  15569. node.argument = this.parseExpression();
  15570. this.semicolon();
  15571. return this.finishNode(node, "ThrowStatement");
  15572. }
  15573. parseCatchClauseParam() {
  15574. const param = this.parseBindingAtom();
  15575. const simple = param.type === "Identifier";
  15576. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  15577. this.checkLVal(param, "catch clause", BIND_LEXICAL);
  15578. return param;
  15579. }
  15580. parseTryStatement(node) {
  15581. this.next();
  15582. node.block = this.parseBlock();
  15583. node.handler = null;
  15584. if (this.match(types._catch)) {
  15585. const clause = this.startNode();
  15586. this.next();
  15587. if (this.match(types.parenL)) {
  15588. this.expect(types.parenL);
  15589. clause.param = this.parseCatchClauseParam();
  15590. this.expect(types.parenR);
  15591. } else {
  15592. clause.param = null;
  15593. this.scope.enter(SCOPE_OTHER);
  15594. }
  15595. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  15596. this.scope.exit();
  15597. node.handler = this.finishNode(clause, "CatchClause");
  15598. }
  15599. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  15600. if (!node.handler && !node.finalizer) {
  15601. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  15602. }
  15603. return this.finishNode(node, "TryStatement");
  15604. }
  15605. parseVarStatement(node, kind) {
  15606. this.next();
  15607. this.parseVar(node, false, kind);
  15608. this.semicolon();
  15609. return this.finishNode(node, "VariableDeclaration");
  15610. }
  15611. parseWhileStatement(node) {
  15612. this.next();
  15613. node.test = this.parseHeaderExpression();
  15614. this.state.labels.push(loopLabel);
  15615. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  15616. this.state.labels.pop();
  15617. return this.finishNode(node, "WhileStatement");
  15618. }
  15619. parseWithStatement(node) {
  15620. if (this.state.strict) {
  15621. this.raise(this.state.start, ErrorMessages.StrictWith);
  15622. }
  15623. this.next();
  15624. node.object = this.parseHeaderExpression();
  15625. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  15626. return this.finishNode(node, "WithStatement");
  15627. }
  15628. parseEmptyStatement(node) {
  15629. this.next();
  15630. return this.finishNode(node, "EmptyStatement");
  15631. }
  15632. parseLabeledStatement(node, maybeName, expr, context) {
  15633. for (let _i2 = 0, _this$state$labels = this.state.labels; _i2 < _this$state$labels.length; _i2++) {
  15634. const label = _this$state$labels[_i2];
  15635. if (label.name === maybeName) {
  15636. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  15637. }
  15638. }
  15639. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  15640. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  15641. const label = this.state.labels[i];
  15642. if (label.statementStart === node.start) {
  15643. label.statementStart = this.state.start;
  15644. label.kind = kind;
  15645. } else {
  15646. break;
  15647. }
  15648. }
  15649. this.state.labels.push({
  15650. name: maybeName,
  15651. kind: kind,
  15652. statementStart: this.state.start
  15653. });
  15654. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  15655. this.state.labels.pop();
  15656. node.label = expr;
  15657. return this.finishNode(node, "LabeledStatement");
  15658. }
  15659. parseExpressionStatement(node, expr) {
  15660. node.expression = expr;
  15661. this.semicolon();
  15662. return this.finishNode(node, "ExpressionStatement");
  15663. }
  15664. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  15665. const node = this.startNode();
  15666. this.expect(types.braceL);
  15667. if (createNewLexicalScope) {
  15668. this.scope.enter(SCOPE_OTHER);
  15669. }
  15670. this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
  15671. if (createNewLexicalScope) {
  15672. this.scope.exit();
  15673. }
  15674. return this.finishNode(node, "BlockStatement");
  15675. }
  15676. isValidDirective(stmt) {
  15677. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  15678. }
  15679. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  15680. const body = node.body = [];
  15681. const directives = node.directives = [];
  15682. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  15683. }
  15684. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  15685. const octalPositions = [];
  15686. const oldStrict = this.state.strict;
  15687. let hasStrictModeDirective = false;
  15688. let parsedNonDirective = false;
  15689. while (!this.match(end)) {
  15690. if (!parsedNonDirective && this.state.octalPositions.length) {
  15691. octalPositions.push(...this.state.octalPositions);
  15692. }
  15693. const stmt = this.parseStatement(null, topLevel);
  15694. if (directives && !parsedNonDirective && this.isValidDirective(stmt)) {
  15695. const directive = this.stmtToDirective(stmt);
  15696. directives.push(directive);
  15697. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  15698. hasStrictModeDirective = true;
  15699. this.setStrict(true);
  15700. }
  15701. continue;
  15702. }
  15703. parsedNonDirective = true;
  15704. body.push(stmt);
  15705. }
  15706. if (this.state.strict && octalPositions.length) {
  15707. for (let _i3 = 0; _i3 < octalPositions.length; _i3++) {
  15708. const pos = octalPositions[_i3];
  15709. this.raise(pos, ErrorMessages.StrictOctalLiteral);
  15710. }
  15711. }
  15712. if (afterBlockParse) {
  15713. afterBlockParse.call(this, hasStrictModeDirective);
  15714. }
  15715. if (!oldStrict) {
  15716. this.setStrict(false);
  15717. }
  15718. this.next();
  15719. }
  15720. parseFor(node, init) {
  15721. node.init = init;
  15722. this.expect(types.semi);
  15723. node.test = this.match(types.semi) ? null : this.parseExpression();
  15724. this.expect(types.semi);
  15725. node.update = this.match(types.parenR) ? null : this.parseExpression();
  15726. this.expect(types.parenR);
  15727. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  15728. this.scope.exit();
  15729. this.state.labels.pop();
  15730. return this.finishNode(node, "ForStatement");
  15731. }
  15732. parseForIn(node, init, awaitAt) {
  15733. const isForIn = this.match(types._in);
  15734. this.next();
  15735. if (isForIn) {
  15736. if (awaitAt > -1) this.unexpected(awaitAt);
  15737. } else {
  15738. node.await = awaitAt > -1;
  15739. }
  15740. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  15741. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  15742. } else if (init.type === "AssignmentPattern") {
  15743. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  15744. }
  15745. node.left = init;
  15746. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  15747. this.expect(types.parenR);
  15748. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  15749. this.scope.exit();
  15750. this.state.labels.pop();
  15751. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  15752. }
  15753. parseVar(node, isFor, kind) {
  15754. const declarations = node.declarations = [];
  15755. const isTypescript = this.hasPlugin("typescript");
  15756. node.kind = kind;
  15757. for (;;) {
  15758. const decl = this.startNode();
  15759. this.parseVarId(decl, kind);
  15760. if (this.eat(types.eq)) {
  15761. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  15762. } else {
  15763. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  15764. if (!isTypescript) {
  15765. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  15766. }
  15767. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  15768. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  15769. }
  15770. decl.init = null;
  15771. }
  15772. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  15773. if (!this.eat(types.comma)) break;
  15774. }
  15775. return node;
  15776. }
  15777. parseVarId(decl, kind) {
  15778. decl.id = this.parseBindingAtom();
  15779. this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var");
  15780. }
  15781. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  15782. const isStatement = statement & FUNC_STATEMENT;
  15783. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  15784. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  15785. this.initFunction(node, isAsync);
  15786. if (this.match(types.star) && isHangingStatement) {
  15787. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  15788. }
  15789. node.generator = this.eat(types.star);
  15790. if (isStatement) {
  15791. node.id = this.parseFunctionId(requireId);
  15792. }
  15793. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  15794. this.state.maybeInArrowParameters = false;
  15795. this.scope.enter(SCOPE_FUNCTION);
  15796. this.prodParam.enter(functionFlags(isAsync, node.generator));
  15797. if (!isStatement) {
  15798. node.id = this.parseFunctionId();
  15799. }
  15800. this.parseFunctionParams(node, false);
  15801. this.withTopicForbiddingContext(() => {
  15802. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  15803. });
  15804. this.prodParam.exit();
  15805. this.scope.exit();
  15806. if (isStatement && !isHangingStatement) {
  15807. this.registerFunctionStatementId(node);
  15808. }
  15809. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  15810. return node;
  15811. }
  15812. parseFunctionId(requireId) {
  15813. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  15814. }
  15815. parseFunctionParams(node, allowModifiers) {
  15816. this.expect(types.parenL);
  15817. this.expressionScope.enter(newParameterDeclarationScope());
  15818. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  15819. this.expressionScope.exit();
  15820. }
  15821. registerFunctionStatementId(node) {
  15822. if (!node.id) return;
  15823. 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);
  15824. }
  15825. parseClass(node, isStatement, optionalId) {
  15826. this.next();
  15827. this.takeDecorators(node);
  15828. const oldStrict = this.state.strict;
  15829. this.state.strict = true;
  15830. this.parseClassId(node, isStatement, optionalId);
  15831. this.parseClassSuper(node);
  15832. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  15833. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  15834. }
  15835. isClassProperty() {
  15836. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  15837. }
  15838. isClassMethod() {
  15839. return this.match(types.parenL);
  15840. }
  15841. isNonstaticConstructor(method) {
  15842. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  15843. }
  15844. parseClassBody(constructorAllowsSuper, oldStrict) {
  15845. this.classScope.enter();
  15846. const state = {
  15847. constructorAllowsSuper,
  15848. hadConstructor: false,
  15849. hadStaticBlock: false
  15850. };
  15851. let decorators = [];
  15852. const classBody = this.startNode();
  15853. classBody.body = [];
  15854. this.expect(types.braceL);
  15855. this.withTopicForbiddingContext(() => {
  15856. while (!this.match(types.braceR)) {
  15857. if (this.eat(types.semi)) {
  15858. if (decorators.length > 0) {
  15859. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  15860. }
  15861. continue;
  15862. }
  15863. if (this.match(types.at)) {
  15864. decorators.push(this.parseDecorator());
  15865. continue;
  15866. }
  15867. const member = this.startNode();
  15868. if (decorators.length) {
  15869. member.decorators = decorators;
  15870. this.resetStartLocationFromNode(member, decorators[0]);
  15871. decorators = [];
  15872. }
  15873. this.parseClassMember(classBody, member, state);
  15874. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  15875. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  15876. }
  15877. }
  15878. });
  15879. this.state.strict = oldStrict;
  15880. this.next();
  15881. if (decorators.length) {
  15882. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  15883. }
  15884. this.classScope.exit();
  15885. return this.finishNode(classBody, "ClassBody");
  15886. }
  15887. parseClassMemberFromModifier(classBody, member) {
  15888. const key = this.parseIdentifier(true);
  15889. if (this.isClassMethod()) {
  15890. const method = member;
  15891. method.kind = "method";
  15892. method.computed = false;
  15893. method.key = key;
  15894. method.static = false;
  15895. this.pushClassMethod(classBody, method, false, false, false, false);
  15896. return true;
  15897. } else if (this.isClassProperty()) {
  15898. const prop = member;
  15899. prop.computed = false;
  15900. prop.key = key;
  15901. prop.static = false;
  15902. classBody.body.push(this.parseClassProperty(prop));
  15903. return true;
  15904. }
  15905. return false;
  15906. }
  15907. parseClassMember(classBody, member, state) {
  15908. const isStatic = this.isContextual("static");
  15909. if (isStatic) {
  15910. if (this.parseClassMemberFromModifier(classBody, member)) {
  15911. return;
  15912. }
  15913. if (this.eat(types.braceL)) {
  15914. this.parseClassStaticBlock(classBody, member, state);
  15915. return;
  15916. }
  15917. }
  15918. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  15919. }
  15920. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  15921. const publicMethod = member;
  15922. const privateMethod = member;
  15923. const publicProp = member;
  15924. const privateProp = member;
  15925. const method = publicMethod;
  15926. const publicMember = publicMethod;
  15927. member.static = isStatic;
  15928. if (this.eat(types.star)) {
  15929. method.kind = "method";
  15930. this.parseClassElementName(method);
  15931. if (method.key.type === "PrivateName") {
  15932. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  15933. return;
  15934. }
  15935. if (this.isNonstaticConstructor(publicMethod)) {
  15936. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  15937. }
  15938. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  15939. return;
  15940. }
  15941. const containsEsc = this.state.containsEsc;
  15942. const key = this.parseClassElementName(member);
  15943. const isPrivate = key.type === "PrivateName";
  15944. const isSimple = key.type === "Identifier";
  15945. const maybeQuestionTokenStart = this.state.start;
  15946. this.parsePostMemberNameModifiers(publicMember);
  15947. if (this.isClassMethod()) {
  15948. method.kind = "method";
  15949. if (isPrivate) {
  15950. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  15951. return;
  15952. }
  15953. const isConstructor = this.isNonstaticConstructor(publicMethod);
  15954. let allowsDirectSuper = false;
  15955. if (isConstructor) {
  15956. publicMethod.kind = "constructor";
  15957. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  15958. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  15959. }
  15960. state.hadConstructor = true;
  15961. allowsDirectSuper = state.constructorAllowsSuper;
  15962. }
  15963. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  15964. } else if (this.isClassProperty()) {
  15965. if (isPrivate) {
  15966. this.pushClassPrivateProperty(classBody, privateProp);
  15967. } else {
  15968. this.pushClassProperty(classBody, publicProp);
  15969. }
  15970. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  15971. const isGenerator = this.eat(types.star);
  15972. if (publicMember.optional) {
  15973. this.unexpected(maybeQuestionTokenStart);
  15974. }
  15975. method.kind = "method";
  15976. this.parseClassElementName(method);
  15977. this.parsePostMemberNameModifiers(publicMember);
  15978. if (method.key.type === "PrivateName") {
  15979. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  15980. } else {
  15981. if (this.isNonstaticConstructor(publicMethod)) {
  15982. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  15983. }
  15984. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  15985. }
  15986. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  15987. method.kind = key.name;
  15988. this.parseClassElementName(publicMethod);
  15989. if (method.key.type === "PrivateName") {
  15990. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  15991. } else {
  15992. if (this.isNonstaticConstructor(publicMethod)) {
  15993. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  15994. }
  15995. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  15996. }
  15997. this.checkGetterSetterParams(publicMethod);
  15998. } else if (this.isLineTerminator()) {
  15999. if (isPrivate) {
  16000. this.pushClassPrivateProperty(classBody, privateProp);
  16001. } else {
  16002. this.pushClassProperty(classBody, publicProp);
  16003. }
  16004. } else {
  16005. this.unexpected();
  16006. }
  16007. }
  16008. parseClassElementName(member) {
  16009. const key = this.parsePropertyName(member, true);
  16010. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  16011. this.raise(key.start, ErrorMessages.StaticPrototype);
  16012. }
  16013. if (key.type === "PrivateName" && key.id.name === "constructor") {
  16014. this.raise(key.start, ErrorMessages.ConstructorClassPrivateField);
  16015. }
  16016. return key;
  16017. }
  16018. parseClassStaticBlock(classBody, member, state) {
  16019. var _member$decorators;
  16020. this.expectPlugin("classStaticBlock", member.start);
  16021. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  16022. this.expressionScope.enter(newExpressionScope());
  16023. const oldLabels = this.state.labels;
  16024. this.state.labels = [];
  16025. this.prodParam.enter(PARAM);
  16026. const body = member.body = [];
  16027. this.parseBlockOrModuleBlockBody(body, undefined, false, types.braceR);
  16028. this.prodParam.exit();
  16029. this.expressionScope.exit();
  16030. this.scope.exit();
  16031. this.state.labels = oldLabels;
  16032. classBody.body.push(this.finishNode(member, "StaticBlock"));
  16033. if (state.hadStaticBlock) {
  16034. this.raise(member.start, ErrorMessages.DuplicateStaticBlock);
  16035. }
  16036. if ((_member$decorators = member.decorators) == null ? void 0 : _member$decorators.length) {
  16037. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  16038. }
  16039. state.hadStaticBlock = true;
  16040. }
  16041. pushClassProperty(classBody, prop) {
  16042. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  16043. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  16044. }
  16045. classBody.body.push(this.parseClassProperty(prop));
  16046. }
  16047. pushClassPrivateProperty(classBody, prop) {
  16048. this.expectPlugin("classPrivateProperties", prop.key.start);
  16049. const node = this.parseClassPrivateProperty(prop);
  16050. classBody.body.push(node);
  16051. this.classScope.declarePrivateName(node.key.id.name, CLASS_ELEMENT_OTHER, node.key.start);
  16052. }
  16053. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  16054. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  16055. }
  16056. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  16057. this.expectPlugin("classPrivateMethods", method.key.start);
  16058. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  16059. classBody.body.push(node);
  16060. 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;
  16061. this.classScope.declarePrivateName(node.key.id.name, kind, node.key.start);
  16062. }
  16063. parsePostMemberNameModifiers(methodOrProp) {}
  16064. parseClassPrivateProperty(node) {
  16065. this.parseInitializer(node);
  16066. this.semicolon();
  16067. return this.finishNode(node, "ClassPrivateProperty");
  16068. }
  16069. parseClassProperty(node) {
  16070. if (!node.typeAnnotation || this.match(types.eq)) {
  16071. this.expectPlugin("classProperties");
  16072. }
  16073. this.parseInitializer(node);
  16074. this.semicolon();
  16075. return this.finishNode(node, "ClassProperty");
  16076. }
  16077. parseInitializer(node) {
  16078. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  16079. this.expressionScope.enter(newExpressionScope());
  16080. this.prodParam.enter(PARAM);
  16081. node.value = this.eat(types.eq) ? this.parseMaybeAssignAllowIn() : null;
  16082. this.expressionScope.exit();
  16083. this.prodParam.exit();
  16084. this.scope.exit();
  16085. }
  16086. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  16087. if (this.match(types.name)) {
  16088. node.id = this.parseIdentifier();
  16089. if (isStatement) {
  16090. this.checkLVal(node.id, "class name", bindingType);
  16091. }
  16092. } else {
  16093. if (optionalId || !isStatement) {
  16094. node.id = null;
  16095. } else {
  16096. this.unexpected(null, ErrorMessages.MissingClassName);
  16097. }
  16098. }
  16099. }
  16100. parseClassSuper(node) {
  16101. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  16102. }
  16103. parseExport(node) {
  16104. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  16105. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  16106. const hasStar = parseAfterDefault && this.eatExportStar(node);
  16107. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  16108. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  16109. const isFromRequired = hasDefault || hasStar;
  16110. if (hasStar && !hasNamespace) {
  16111. if (hasDefault) this.unexpected();
  16112. this.parseExportFrom(node, true);
  16113. return this.finishNode(node, "ExportAllDeclaration");
  16114. }
  16115. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  16116. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  16117. throw this.unexpected(null, types.braceL);
  16118. }
  16119. let hasDeclaration;
  16120. if (isFromRequired || hasSpecifiers) {
  16121. hasDeclaration = false;
  16122. this.parseExportFrom(node, isFromRequired);
  16123. } else {
  16124. hasDeclaration = this.maybeParseExportDeclaration(node);
  16125. }
  16126. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  16127. this.checkExport(node, true, false, !!node.source);
  16128. return this.finishNode(node, "ExportNamedDeclaration");
  16129. }
  16130. if (this.eat(types._default)) {
  16131. node.declaration = this.parseExportDefaultExpression();
  16132. this.checkExport(node, true, true);
  16133. return this.finishNode(node, "ExportDefaultDeclaration");
  16134. }
  16135. throw this.unexpected(null, types.braceL);
  16136. }
  16137. eatExportStar(node) {
  16138. return this.eat(types.star);
  16139. }
  16140. maybeParseExportDefaultSpecifier(node) {
  16141. if (this.isExportDefaultSpecifier()) {
  16142. this.expectPlugin("exportDefaultFrom");
  16143. const specifier = this.startNode();
  16144. specifier.exported = this.parseIdentifier(true);
  16145. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  16146. return true;
  16147. }
  16148. return false;
  16149. }
  16150. maybeParseExportNamespaceSpecifier(node) {
  16151. if (this.isContextual("as")) {
  16152. if (!node.specifiers) node.specifiers = [];
  16153. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  16154. this.next();
  16155. specifier.exported = this.parseModuleExportName();
  16156. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  16157. return true;
  16158. }
  16159. return false;
  16160. }
  16161. maybeParseExportNamedSpecifiers(node) {
  16162. if (this.match(types.braceL)) {
  16163. if (!node.specifiers) node.specifiers = [];
  16164. node.specifiers.push(...this.parseExportSpecifiers());
  16165. node.source = null;
  16166. node.declaration = null;
  16167. return true;
  16168. }
  16169. return false;
  16170. }
  16171. maybeParseExportDeclaration(node) {
  16172. if (this.shouldParseExportDeclaration()) {
  16173. node.specifiers = [];
  16174. node.source = null;
  16175. node.declaration = this.parseExportDeclaration(node);
  16176. return true;
  16177. }
  16178. return false;
  16179. }
  16180. isAsyncFunction() {
  16181. if (!this.isContextual("async")) return false;
  16182. const next = this.nextTokenStart();
  16183. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  16184. }
  16185. parseExportDefaultExpression() {
  16186. const expr = this.startNode();
  16187. const isAsync = this.isAsyncFunction();
  16188. if (this.match(types._function) || isAsync) {
  16189. this.next();
  16190. if (isAsync) {
  16191. this.next();
  16192. }
  16193. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  16194. } else if (this.match(types._class)) {
  16195. return this.parseClass(expr, true, true);
  16196. } else if (this.match(types.at)) {
  16197. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  16198. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  16199. }
  16200. this.parseDecorators(false);
  16201. return this.parseClass(expr, true, true);
  16202. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  16203. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  16204. } else {
  16205. const res = this.parseMaybeAssignAllowIn();
  16206. this.semicolon();
  16207. return res;
  16208. }
  16209. }
  16210. parseExportDeclaration(node) {
  16211. return this.parseStatement(null);
  16212. }
  16213. isExportDefaultSpecifier() {
  16214. if (this.match(types.name)) {
  16215. const value = this.state.value;
  16216. if (value === "async" && !this.state.containsEsc || value === "let") {
  16217. return false;
  16218. }
  16219. if ((value === "type" || value === "interface") && !this.state.containsEsc) {
  16220. const l = this.lookahead();
  16221. if (l.type === types.name && l.value !== "from" || l.type === types.braceL) {
  16222. this.expectOnePlugin(["flow", "typescript"]);
  16223. return false;
  16224. }
  16225. }
  16226. } else if (!this.match(types._default)) {
  16227. return false;
  16228. }
  16229. const next = this.nextTokenStart();
  16230. const hasFrom = this.isUnparsedContextual(next, "from");
  16231. if (this.input.charCodeAt(next) === 44 || this.match(types.name) && hasFrom) {
  16232. return true;
  16233. }
  16234. if (this.match(types._default) && hasFrom) {
  16235. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  16236. return nextAfterFrom === 34 || nextAfterFrom === 39;
  16237. }
  16238. return false;
  16239. }
  16240. parseExportFrom(node, expect) {
  16241. if (this.eatContextual("from")) {
  16242. node.source = this.parseImportSource();
  16243. this.checkExport(node);
  16244. const assertions = this.maybeParseImportAssertions();
  16245. if (assertions) {
  16246. node.assertions = assertions;
  16247. }
  16248. } else {
  16249. if (expect) {
  16250. this.unexpected();
  16251. } else {
  16252. node.source = null;
  16253. }
  16254. }
  16255. this.semicolon();
  16256. }
  16257. shouldParseExportDeclaration() {
  16258. if (this.match(types.at)) {
  16259. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  16260. if (this.hasPlugin("decorators")) {
  16261. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  16262. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  16263. } else {
  16264. return true;
  16265. }
  16266. }
  16267. }
  16268. 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();
  16269. }
  16270. checkExport(node, checkNames, isDefault, isFrom) {
  16271. if (checkNames) {
  16272. if (isDefault) {
  16273. this.checkDuplicateExports(node, "default");
  16274. if (this.hasPlugin("exportDefaultFrom")) {
  16275. var _declaration$extra;
  16276. const declaration = node.declaration;
  16277. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) == null ? void 0 : _declaration$extra.parenthesized)) {
  16278. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  16279. }
  16280. }
  16281. } else if (node.specifiers && node.specifiers.length) {
  16282. for (let _i4 = 0, _node$specifiers = node.specifiers; _i4 < _node$specifiers.length; _i4++) {
  16283. const specifier = _node$specifiers[_i4];
  16284. const {
  16285. exported
  16286. } = specifier;
  16287. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  16288. this.checkDuplicateExports(specifier, exportedName);
  16289. if (!isFrom && specifier.local) {
  16290. const {
  16291. local
  16292. } = specifier;
  16293. if (local.type === "StringLiteral") {
  16294. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.extra.raw, exportedName);
  16295. } else {
  16296. this.checkReservedWord(local.name, local.start, true, false);
  16297. this.scope.checkLocalExport(local);
  16298. }
  16299. }
  16300. }
  16301. } else if (node.declaration) {
  16302. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  16303. const id = node.declaration.id;
  16304. if (!id) throw new Error("Assertion failure");
  16305. this.checkDuplicateExports(node, id.name);
  16306. } else if (node.declaration.type === "VariableDeclaration") {
  16307. for (let _i5 = 0, _node$declaration$dec = node.declaration.declarations; _i5 < _node$declaration$dec.length; _i5++) {
  16308. const declaration = _node$declaration$dec[_i5];
  16309. this.checkDeclaration(declaration.id);
  16310. }
  16311. }
  16312. }
  16313. }
  16314. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  16315. if (currentContextDecorators.length) {
  16316. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  16317. }
  16318. }
  16319. checkDeclaration(node) {
  16320. if (node.type === "Identifier") {
  16321. this.checkDuplicateExports(node, node.name);
  16322. } else if (node.type === "ObjectPattern") {
  16323. for (let _i6 = 0, _node$properties = node.properties; _i6 < _node$properties.length; _i6++) {
  16324. const prop = _node$properties[_i6];
  16325. this.checkDeclaration(prop);
  16326. }
  16327. } else if (node.type === "ArrayPattern") {
  16328. for (let _i7 = 0, _node$elements = node.elements; _i7 < _node$elements.length; _i7++) {
  16329. const elem = _node$elements[_i7];
  16330. if (elem) {
  16331. this.checkDeclaration(elem);
  16332. }
  16333. }
  16334. } else if (node.type === "ObjectProperty") {
  16335. this.checkDeclaration(node.value);
  16336. } else if (node.type === "RestElement") {
  16337. this.checkDeclaration(node.argument);
  16338. } else if (node.type === "AssignmentPattern") {
  16339. this.checkDeclaration(node.left);
  16340. }
  16341. }
  16342. checkDuplicateExports(node, name) {
  16343. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  16344. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  16345. }
  16346. this.state.exportedIdentifiers.push(name);
  16347. }
  16348. parseExportSpecifiers() {
  16349. const nodes = [];
  16350. let first = true;
  16351. this.expect(types.braceL);
  16352. while (!this.eat(types.braceR)) {
  16353. if (first) {
  16354. first = false;
  16355. } else {
  16356. this.expect(types.comma);
  16357. if (this.eat(types.braceR)) break;
  16358. }
  16359. const node = this.startNode();
  16360. node.local = this.parseModuleExportName();
  16361. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local.__clone();
  16362. nodes.push(this.finishNode(node, "ExportSpecifier"));
  16363. }
  16364. return nodes;
  16365. }
  16366. parseModuleExportName() {
  16367. if (this.match(types.string)) {
  16368. this.expectPlugin("moduleStringNames");
  16369. const result = this.parseLiteral(this.state.value, "StringLiteral");
  16370. const surrogate = result.value.match(loneSurrogate);
  16371. if (surrogate) {
  16372. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  16373. }
  16374. return result;
  16375. }
  16376. return this.parseIdentifier(true);
  16377. }
  16378. parseImport(node) {
  16379. node.specifiers = [];
  16380. if (!this.match(types.string)) {
  16381. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  16382. const parseNext = !hasDefault || this.eat(types.comma);
  16383. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  16384. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  16385. this.expectContextual("from");
  16386. }
  16387. node.source = this.parseImportSource();
  16388. const assertions = this.maybeParseImportAssertions();
  16389. if (assertions) {
  16390. node.assertions = assertions;
  16391. } else {
  16392. const attributes = this.maybeParseModuleAttributes();
  16393. if (attributes) {
  16394. node.attributes = attributes;
  16395. }
  16396. }
  16397. this.semicolon();
  16398. return this.finishNode(node, "ImportDeclaration");
  16399. }
  16400. parseImportSource() {
  16401. if (!this.match(types.string)) this.unexpected();
  16402. return this.parseExprAtom();
  16403. }
  16404. shouldParseDefaultImport(node) {
  16405. return this.match(types.name);
  16406. }
  16407. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  16408. specifier.local = this.parseIdentifier();
  16409. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  16410. node.specifiers.push(this.finishNode(specifier, type));
  16411. }
  16412. parseAssertEntries() {
  16413. const attrs = [];
  16414. const attrNames = new Set();
  16415. do {
  16416. if (this.match(types.braceR)) {
  16417. break;
  16418. }
  16419. const node = this.startNode();
  16420. const keyName = this.state.value;
  16421. if (this.match(types.string)) {
  16422. node.key = this.parseLiteral(keyName, "StringLiteral");
  16423. } else {
  16424. node.key = this.parseIdentifier(true);
  16425. }
  16426. this.expect(types.colon);
  16427. if (keyName !== "type") {
  16428. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, keyName);
  16429. }
  16430. if (attrNames.has(keyName)) {
  16431. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
  16432. }
  16433. attrNames.add(keyName);
  16434. if (!this.match(types.string)) {
  16435. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  16436. }
  16437. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  16438. this.finishNode(node, "ImportAttribute");
  16439. attrs.push(node);
  16440. } while (this.eat(types.comma));
  16441. return attrs;
  16442. }
  16443. maybeParseModuleAttributes() {
  16444. if (this.match(types._with) && !this.hasPrecedingLineBreak()) {
  16445. this.expectPlugin("moduleAttributes");
  16446. this.next();
  16447. } else {
  16448. if (this.hasPlugin("moduleAttributes")) return [];
  16449. return null;
  16450. }
  16451. const attrs = [];
  16452. const attributes = new Set();
  16453. do {
  16454. const node = this.startNode();
  16455. node.key = this.parseIdentifier(true);
  16456. if (node.key.name !== "type") {
  16457. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  16458. }
  16459. if (attributes.has(node.key.name)) {
  16460. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  16461. }
  16462. attributes.add(node.key.name);
  16463. this.expect(types.colon);
  16464. if (!this.match(types.string)) {
  16465. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  16466. }
  16467. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  16468. this.finishNode(node, "ImportAttribute");
  16469. attrs.push(node);
  16470. } while (this.eat(types.comma));
  16471. return attrs;
  16472. }
  16473. maybeParseImportAssertions() {
  16474. if (this.isContextual("assert") && !this.hasPrecedingLineBreak()) {
  16475. this.expectPlugin("importAssertions");
  16476. this.next();
  16477. } else {
  16478. if (this.hasPlugin("importAssertions")) return [];
  16479. return null;
  16480. }
  16481. this.eat(types.braceL);
  16482. const attrs = this.parseAssertEntries();
  16483. this.eat(types.braceR);
  16484. return attrs;
  16485. }
  16486. maybeParseDefaultImportSpecifier(node) {
  16487. if (this.shouldParseDefaultImport(node)) {
  16488. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  16489. return true;
  16490. }
  16491. return false;
  16492. }
  16493. maybeParseStarImportSpecifier(node) {
  16494. if (this.match(types.star)) {
  16495. const specifier = this.startNode();
  16496. this.next();
  16497. this.expectContextual("as");
  16498. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  16499. return true;
  16500. }
  16501. return false;
  16502. }
  16503. parseNamedImportSpecifiers(node) {
  16504. let first = true;
  16505. this.expect(types.braceL);
  16506. while (!this.eat(types.braceR)) {
  16507. if (first) {
  16508. first = false;
  16509. } else {
  16510. if (this.eat(types.colon)) {
  16511. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  16512. }
  16513. this.expect(types.comma);
  16514. if (this.eat(types.braceR)) break;
  16515. }
  16516. this.parseImportSpecifier(node);
  16517. }
  16518. }
  16519. parseImportSpecifier(node) {
  16520. const specifier = this.startNode();
  16521. specifier.imported = this.parseModuleExportName();
  16522. if (this.eatContextual("as")) {
  16523. specifier.local = this.parseIdentifier();
  16524. } else {
  16525. const {
  16526. imported
  16527. } = specifier;
  16528. if (imported.type === "StringLiteral") {
  16529. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  16530. }
  16531. this.checkReservedWord(imported.name, specifier.start, true, true);
  16532. specifier.local = imported.__clone();
  16533. }
  16534. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  16535. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  16536. }
  16537. }
  16538. class ClassScope {
  16539. constructor() {
  16540. this.privateNames = new Set();
  16541. this.loneAccessors = new Map();
  16542. this.undefinedPrivateNames = new Map();
  16543. }
  16544. }
  16545. class ClassScopeHandler {
  16546. constructor(raise) {
  16547. this.stack = [];
  16548. this.undefinedPrivateNames = new Map();
  16549. this.raise = raise;
  16550. }
  16551. current() {
  16552. return this.stack[this.stack.length - 1];
  16553. }
  16554. enter() {
  16555. this.stack.push(new ClassScope());
  16556. }
  16557. exit() {
  16558. const oldClassScope = this.stack.pop();
  16559. const current = this.current();
  16560. for (let _i = 0, _Array$from = Array.from(oldClassScope.undefinedPrivateNames); _i < _Array$from.length; _i++) {
  16561. const [name, pos] = _Array$from[_i];
  16562. if (current) {
  16563. if (!current.undefinedPrivateNames.has(name)) {
  16564. current.undefinedPrivateNames.set(name, pos);
  16565. }
  16566. } else {
  16567. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  16568. }
  16569. }
  16570. }
  16571. declarePrivateName(name, elementType, pos) {
  16572. const classScope = this.current();
  16573. let redefined = classScope.privateNames.has(name);
  16574. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  16575. const accessor = redefined && classScope.loneAccessors.get(name);
  16576. if (accessor) {
  16577. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  16578. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  16579. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  16580. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  16581. redefined = oldKind === newKind || oldStatic !== newStatic;
  16582. if (!redefined) classScope.loneAccessors.delete(name);
  16583. } else if (!redefined) {
  16584. classScope.loneAccessors.set(name, elementType);
  16585. }
  16586. }
  16587. if (redefined) {
  16588. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  16589. }
  16590. classScope.privateNames.add(name);
  16591. classScope.undefinedPrivateNames.delete(name);
  16592. }
  16593. usePrivateName(name, pos) {
  16594. let classScope;
  16595. for (let _i2 = 0, _this$stack = this.stack; _i2 < _this$stack.length; _i2++) {
  16596. classScope = _this$stack[_i2];
  16597. if (classScope.privateNames.has(name)) return;
  16598. }
  16599. if (classScope) {
  16600. classScope.undefinedPrivateNames.set(name, pos);
  16601. } else {
  16602. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  16603. }
  16604. }
  16605. }
  16606. class Parser extends StatementParser {
  16607. constructor(options, input) {
  16608. options = getOptions(options);
  16609. super(options, input);
  16610. const ScopeHandler = this.getScopeHandler();
  16611. this.options = options;
  16612. this.inModule = this.options.sourceType === "module";
  16613. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  16614. this.prodParam = new ProductionParameterHandler();
  16615. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  16616. this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
  16617. this.plugins = pluginsMap(this.options.plugins);
  16618. this.filename = options.sourceFilename;
  16619. }
  16620. getScopeHandler() {
  16621. return ScopeHandler;
  16622. }
  16623. parse() {
  16624. let paramFlags = PARAM;
  16625. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  16626. paramFlags |= PARAM_AWAIT;
  16627. }
  16628. this.scope.enter(SCOPE_PROGRAM);
  16629. this.prodParam.enter(paramFlags);
  16630. const file = this.startNode();
  16631. const program = this.startNode();
  16632. this.nextToken();
  16633. file.errors = null;
  16634. this.parseTopLevel(file, program);
  16635. file.errors = this.state.errors;
  16636. return file;
  16637. }
  16638. }
  16639. function pluginsMap(plugins) {
  16640. const pluginMap = new Map();
  16641. for (let _i = 0; _i < plugins.length; _i++) {
  16642. const plugin = plugins[_i];
  16643. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  16644. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  16645. }
  16646. return pluginMap;
  16647. }
  16648. function parse(input, options) {
  16649. var _options;
  16650. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  16651. options = Object.assign({}, options);
  16652. try {
  16653. options.sourceType = "module";
  16654. const parser = getParser(options, input);
  16655. const ast = parser.parse();
  16656. if (parser.sawUnambiguousESM) {
  16657. return ast;
  16658. }
  16659. if (parser.ambiguousScriptDifferentAst) {
  16660. try {
  16661. options.sourceType = "script";
  16662. return getParser(options, input).parse();
  16663. } catch (_unused) {}
  16664. } else {
  16665. ast.program.sourceType = "script";
  16666. }
  16667. return ast;
  16668. } catch (moduleError) {
  16669. try {
  16670. options.sourceType = "script";
  16671. return getParser(options, input).parse();
  16672. } catch (_unused2) {}
  16673. throw moduleError;
  16674. }
  16675. } else {
  16676. return getParser(options, input).parse();
  16677. }
  16678. }
  16679. function getParser(options, input) {
  16680. let cls = Parser;
  16681. if (options == null ? void 0 : options.plugins) {
  16682. validatePlugins(options.plugins);
  16683. cls = getParserClass(options.plugins);
  16684. }
  16685. return new cls(options, input);
  16686. }
  16687. const parserClassCache = {};
  16688. function getParserClass(pluginsFromOptions) {
  16689. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  16690. const key = pluginList.join("/");
  16691. let cls = parserClassCache[key];
  16692. if (!cls) {
  16693. cls = Parser;
  16694. for (let _i = 0; _i < pluginList.length; _i++) {
  16695. const plugin = pluginList[_i];
  16696. cls = mixinPlugins[plugin](cls);
  16697. }
  16698. parserClassCache[key] = cls;
  16699. }
  16700. return cls;
  16701. }
  16702. var parse_1 = parse;
  16703. class WalkerBase {constructor() { WalkerBase.prototype.__init.call(this);WalkerBase.prototype.__init2.call(this);WalkerBase.prototype.__init3.call(this);WalkerBase.prototype.__init4.call(this); }
  16704. __init() {this.should_skip = false;}
  16705. __init2() {this.should_remove = false;}
  16706. __init3() {this.replacement = null;}
  16707. __init4() {this.context = {
  16708. skip: () => (this.should_skip = true),
  16709. remove: () => (this.should_remove = true),
  16710. replace: (node) => (this.replacement = node)
  16711. };}
  16712. replace(parent, prop, index, node) {
  16713. if (parent) {
  16714. if (index !== null) {
  16715. parent[prop][index] = node;
  16716. } else {
  16717. parent[prop] = node;
  16718. }
  16719. }
  16720. }
  16721. remove(parent, prop, index) {
  16722. if (parent) {
  16723. if (index !== null) {
  16724. parent[prop].splice(index, 1);
  16725. } else {
  16726. delete parent[prop];
  16727. }
  16728. }
  16729. }
  16730. }
  16731. class SyncWalkerClass extends WalkerBase {
  16732. constructor(walker) {
  16733. super();
  16734. this.enter = walker.enter;
  16735. this.leave = walker.leave;
  16736. }
  16737. visit(
  16738. node,
  16739. parent,
  16740. enter,
  16741. leave,
  16742. prop,
  16743. index
  16744. ) {
  16745. if (node) {
  16746. if (enter) {
  16747. const _should_skip = this.should_skip;
  16748. const _should_remove = this.should_remove;
  16749. const _replacement = this.replacement;
  16750. this.should_skip = false;
  16751. this.should_remove = false;
  16752. this.replacement = null;
  16753. enter.call(this.context, node, parent, prop, index);
  16754. if (this.replacement) {
  16755. node = this.replacement;
  16756. this.replace(parent, prop, index, node);
  16757. }
  16758. if (this.should_remove) {
  16759. this.remove(parent, prop, index);
  16760. }
  16761. const skipped = this.should_skip;
  16762. const removed = this.should_remove;
  16763. this.should_skip = _should_skip;
  16764. this.should_remove = _should_remove;
  16765. this.replacement = _replacement;
  16766. if (skipped) return node;
  16767. if (removed) return null;
  16768. }
  16769. for (const key in node) {
  16770. const value = (node )[key];
  16771. if (typeof value !== "object") {
  16772. continue;
  16773. } else if (Array.isArray(value)) {
  16774. for (let i = 0; i < value.length; i += 1) {
  16775. if (value[i] !== null && typeof value[i].type === 'string') {
  16776. if (!this.visit(value[i], node, enter, leave, key, i)) {
  16777. // removed
  16778. i--;
  16779. }
  16780. }
  16781. }
  16782. } else if (value !== null && typeof value.type === "string") {
  16783. this.visit(value, node, enter, leave, key, null);
  16784. }
  16785. }
  16786. if (leave) {
  16787. const _replacement = this.replacement;
  16788. const _should_remove = this.should_remove;
  16789. this.replacement = null;
  16790. this.should_remove = false;
  16791. leave.call(this.context, node, parent, prop, index);
  16792. if (this.replacement) {
  16793. node = this.replacement;
  16794. this.replace(parent, prop, index, node);
  16795. }
  16796. if (this.should_remove) {
  16797. this.remove(parent, prop, index);
  16798. }
  16799. const removed = this.should_remove;
  16800. this.replacement = _replacement;
  16801. this.should_remove = _should_remove;
  16802. if (removed) return null;
  16803. }
  16804. }
  16805. return node;
  16806. }
  16807. }
  16808. function walk$1(ast, walker) {
  16809. const instance = new SyncWalkerClass(walker);
  16810. return instance.visit(ast, null, walker.enter, walker.leave);
  16811. }
  16812. const isLiteralWhitelisted = /*#__PURE__*/ makeMap('true,false,null,this');
  16813. const transformExpression = (node, context) => {
  16814. if (node.type === 5 /* INTERPOLATION */) {
  16815. node.content = processExpression(node.content, context);
  16816. }
  16817. else if (node.type === 1 /* ELEMENT */) {
  16818. // handle directives on element
  16819. for (let i = 0; i < node.props.length; i++) {
  16820. const dir = node.props[i];
  16821. // do not process for v-on & v-for since they are special handled
  16822. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  16823. const exp = dir.exp;
  16824. const arg = dir.arg;
  16825. // do not process exp if this is v-on:arg - we need special handling
  16826. // for wrapping inline statements.
  16827. if (exp &&
  16828. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  16829. !(dir.name === 'on' && arg)) {
  16830. dir.exp = processExpression(exp, context,
  16831. // slot args must be processed as function params
  16832. dir.name === 'slot');
  16833. }
  16834. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  16835. dir.arg = processExpression(arg, context);
  16836. }
  16837. }
  16838. }
  16839. }
  16840. };
  16841. // Important: since this function uses Node.js only dependencies, it should
  16842. // always be used with a leading !false check so that it can be
  16843. // tree-shaken from the browser build.
  16844. function processExpression(node, context,
  16845. // some expressions like v-slot props & v-for aliases should be parsed as
  16846. // function params
  16847. asParams = false,
  16848. // v-on handler values may contain multiple statements
  16849. asRawStatements = false) {
  16850. if (!context.prefixIdentifiers || !node.content.trim()) {
  16851. return node;
  16852. }
  16853. const { inline, bindingMetadata } = context;
  16854. const rewriteIdentifier = (raw, parent, id) => {
  16855. const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
  16856. if (inline) {
  16857. // x = y
  16858. const isAssignmentLVal = parent && parent.type === 'AssignmentExpression' && parent.left === id;
  16859. // x++
  16860. const isUpdateArg = parent && parent.type === 'UpdateExpression' && parent.argument === id;
  16861. // ({ x } = y)
  16862. const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
  16863. if (type === "setup-const" /* SETUP_CONST */) {
  16864. return raw;
  16865. }
  16866. else if (type === "setup-ref" /* SETUP_REF */) {
  16867. return `${raw}.value`;
  16868. }
  16869. else if (type === "setup-maybe-ref" /* SETUP_MAYBE_REF */) {
  16870. // const binding that may or may not be ref
  16871. // if it's not a ref, then assignments don't make sense -
  16872. // so we ignore the non-ref assignment case and generate code
  16873. // that assumes the value to be a ref for more efficiency
  16874. return isAssignmentLVal || isUpdateArg || isDestructureAssignment
  16875. ? `${raw}.value`
  16876. : `${context.helperString(UNREF)}(${raw})`;
  16877. }
  16878. else if (type === "setup-let" /* SETUP_LET */) {
  16879. if (isAssignmentLVal) {
  16880. // let binding.
  16881. // this is a bit more tricky as we need to cover the case where
  16882. // let is a local non-ref value, and we need to replicate the
  16883. // right hand side value.
  16884. // x = y --> isRef(x) ? x.value = y : x = y
  16885. const rVal = parent.right;
  16886. const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
  16887. const rExpString = stringifyExpression(processExpression(createSimpleExpression(rExp, false), context));
  16888. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${raw}.value = ${rExpString} : ${raw}`;
  16889. }
  16890. else if (isUpdateArg) {
  16891. // make id replace parent in the code range so the raw update operator
  16892. // is removed
  16893. id.start = parent.start;
  16894. id.end = parent.end;
  16895. const { prefix: isPrefix, operator } = parent;
  16896. const prefix = isPrefix ? operator : ``;
  16897. const postfix = isPrefix ? `` : operator;
  16898. // let binding.
  16899. // x++ --> isRef(a) ? a.value++ : a++
  16900. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
  16901. }
  16902. else if (isDestructureAssignment) {
  16903. // TODO
  16904. // let binding in a destructure assignment - it's very tricky to
  16905. // handle both possible cases here without altering the original
  16906. // structure of the code, so we just assume it's not a ref here
  16907. // for now
  16908. return raw;
  16909. }
  16910. else {
  16911. return `${context.helperString(UNREF)}(${raw})`;
  16912. }
  16913. }
  16914. else if (type === "props" /* PROPS */) {
  16915. // use __props which is generated by compileScript so in ts mode
  16916. // it gets correct type
  16917. return `__props.${raw}`;
  16918. }
  16919. }
  16920. else {
  16921. if (type && type.startsWith('setup')) {
  16922. // setup bindings in non-inline mode
  16923. return `$setup.${raw}`;
  16924. }
  16925. else if (type) {
  16926. return `$${type}.${raw}`;
  16927. }
  16928. }
  16929. // fallback to ctx
  16930. return `_ctx.${raw}`;
  16931. };
  16932. // fast path if expression is a simple identifier.
  16933. const rawExp = node.content;
  16934. // bail constant on parens (function invocation) and dot (member access)
  16935. const bailConstant = rawExp.indexOf(`(`) > -1 || rawExp.indexOf('.') > 0;
  16936. if (isSimpleIdentifier(rawExp)) {
  16937. const isScopeVarReference = context.identifiers[rawExp];
  16938. const isAllowedGlobal = isGloballyWhitelisted(rawExp);
  16939. const isLiteral = isLiteralWhitelisted(rawExp);
  16940. if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
  16941. // const bindings exposed from setup can be skipped for patching but
  16942. // cannot be hoisted to module scope
  16943. if (bindingMetadata[node.content] === "setup-const" /* SETUP_CONST */) {
  16944. node.constType = 1 /* CAN_SKIP_PATCH */;
  16945. }
  16946. node.content = rewriteIdentifier(rawExp);
  16947. }
  16948. else if (!isScopeVarReference) {
  16949. if (isLiteral) {
  16950. node.constType = 3 /* CAN_STRINGIFY */;
  16951. }
  16952. else {
  16953. node.constType = 2 /* CAN_HOIST */;
  16954. }
  16955. }
  16956. return node;
  16957. }
  16958. let ast;
  16959. // exp needs to be parsed differently:
  16960. // 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
  16961. // exp, but make sure to pad with spaces for consistent ranges
  16962. // 2. Expressions: wrap with parens (for e.g. object expressions)
  16963. // 3. Function arguments (v-for, v-slot): place in a function argument position
  16964. const source = asRawStatements
  16965. ? ` ${rawExp} `
  16966. : `(${rawExp})${asParams ? `=>{}` : ``}`;
  16967. try {
  16968. ast = parse_1(source, {
  16969. plugins: [...context.expressionPlugins, ...babelParserDefaultPlugins]
  16970. }).program;
  16971. }
  16972. catch (e) {
  16973. context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
  16974. return node;
  16975. }
  16976. const ids = [];
  16977. const knownIds = Object.create(context.identifiers);
  16978. const isDuplicate = (node) => ids.some(id => id.start === node.start);
  16979. const parentStack = [];
  16980. walk$1(ast, {
  16981. enter(node, parent) {
  16982. parent && parentStack.push(parent);
  16983. if (node.type === 'Identifier') {
  16984. if (!isDuplicate(node)) {
  16985. const needPrefix = shouldPrefix(node, parent, parentStack);
  16986. if (!knownIds[node.name] && needPrefix) {
  16987. if (isStaticProperty(parent) && parent.shorthand) {
  16988. // property shorthand like { foo }, we need to add the key since
  16989. // we rewrite the value
  16990. node.prefix = `${node.name}: `;
  16991. }
  16992. node.name = rewriteIdentifier(node.name, parent, node);
  16993. ids.push(node);
  16994. }
  16995. else if (!isStaticPropertyKey(node, parent)) {
  16996. // The identifier is considered constant unless it's pointing to a
  16997. // scope variable (a v-for alias, or a v-slot prop)
  16998. if (!(needPrefix && knownIds[node.name]) && !bailConstant) {
  16999. node.isConstant = true;
  17000. }
  17001. // also generate sub-expressions for other identifiers for better
  17002. // source map support. (except for property keys which are static)
  17003. ids.push(node);
  17004. }
  17005. }
  17006. }
  17007. else if (isFunction$1(node)) {
  17008. // walk function expressions and add its arguments to known identifiers
  17009. // so that we don't prefix them
  17010. node.params.forEach(p => walk$1(p, {
  17011. enter(child, parent) {
  17012. if (child.type === 'Identifier' &&
  17013. // do not record as scope variable if is a destructured key
  17014. !isStaticPropertyKey(child, parent) &&
  17015. // do not record if this is a default value
  17016. // assignment of a destructured variable
  17017. !(parent &&
  17018. parent.type === 'AssignmentPattern' &&
  17019. parent.right === child)) {
  17020. const { name } = child;
  17021. if (node.scopeIds && node.scopeIds.has(name)) {
  17022. return;
  17023. }
  17024. if (name in knownIds) {
  17025. knownIds[name]++;
  17026. }
  17027. else {
  17028. knownIds[name] = 1;
  17029. }
  17030. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  17031. }
  17032. }
  17033. }));
  17034. }
  17035. },
  17036. leave(node, parent) {
  17037. parent && parentStack.pop();
  17038. if (node !== ast.body[0].expression && node.scopeIds) {
  17039. node.scopeIds.forEach((id) => {
  17040. knownIds[id]--;
  17041. if (knownIds[id] === 0) {
  17042. delete knownIds[id];
  17043. }
  17044. });
  17045. }
  17046. }
  17047. });
  17048. // We break up the compound expression into an array of strings and sub
  17049. // expressions (for identifiers that have been prefixed). In codegen, if
  17050. // an ExpressionNode has the `.children` property, it will be used instead of
  17051. // `.content`.
  17052. const children = [];
  17053. ids.sort((a, b) => a.start - b.start);
  17054. ids.forEach((id, i) => {
  17055. // range is offset by -1 due to the wrapping parens when parsed
  17056. const start = id.start - 1;
  17057. const end = id.end - 1;
  17058. const last = ids[i - 1];
  17059. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  17060. if (leadingText.length || id.prefix) {
  17061. children.push(leadingText + (id.prefix || ``));
  17062. }
  17063. const source = rawExp.slice(start, end);
  17064. children.push(createSimpleExpression(id.name, false, {
  17065. source,
  17066. start: advancePositionWithClone(node.loc.start, source, start),
  17067. end: advancePositionWithClone(node.loc.start, source, end)
  17068. }, id.isConstant ? 3 /* CAN_STRINGIFY */ : 0 /* NOT_CONSTANT */));
  17069. if (i === ids.length - 1 && end < rawExp.length) {
  17070. children.push(rawExp.slice(end));
  17071. }
  17072. });
  17073. let ret;
  17074. if (children.length) {
  17075. ret = createCompoundExpression(children, node.loc);
  17076. }
  17077. else {
  17078. ret = node;
  17079. ret.constType = bailConstant
  17080. ? 0 /* NOT_CONSTANT */
  17081. : 3 /* CAN_STRINGIFY */;
  17082. }
  17083. ret.identifiers = Object.keys(knownIds);
  17084. return ret;
  17085. }
  17086. const isFunction$1 = (node) => {
  17087. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  17088. };
  17089. const isStaticProperty = (node) => node &&
  17090. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  17091. !node.computed;
  17092. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  17093. function shouldPrefix(id, parent, parentStack) {
  17094. // declaration id
  17095. if ((parent.type === 'VariableDeclarator' ||
  17096. parent.type === 'ClassDeclaration') &&
  17097. parent.id === id) {
  17098. return false;
  17099. }
  17100. if (isFunction$1(parent)) {
  17101. // function decalration/expression id
  17102. if (parent.id === id) {
  17103. return false;
  17104. }
  17105. // params list
  17106. if (parent.params.includes(id)) {
  17107. return false;
  17108. }
  17109. }
  17110. // property key
  17111. // this also covers object destructure pattern
  17112. if (isStaticPropertyKey(id, parent)) {
  17113. return false;
  17114. }
  17115. // non-assignment array destructure pattern
  17116. if (parent.type === 'ArrayPattern' &&
  17117. !isInDestructureAssignment(parent, parentStack)) {
  17118. return false;
  17119. }
  17120. // member expression property
  17121. if ((parent.type === 'MemberExpression' ||
  17122. parent.type === 'OptionalMemberExpression') &&
  17123. parent.property === id &&
  17124. !parent.computed) {
  17125. return false;
  17126. }
  17127. // is a special keyword but parsed as identifier
  17128. if (id.name === 'arguments') {
  17129. return false;
  17130. }
  17131. // skip whitelisted globals
  17132. if (isGloballyWhitelisted(id.name)) {
  17133. return false;
  17134. }
  17135. // special case for webpack compilation
  17136. if (id.name === 'require') {
  17137. return false;
  17138. }
  17139. return true;
  17140. }
  17141. function isInDestructureAssignment(parent, parentStack) {
  17142. if (parent &&
  17143. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  17144. let i = parentStack.length;
  17145. while (i--) {
  17146. const p = parentStack[i];
  17147. if (p.type === 'AssignmentExpression') {
  17148. return true;
  17149. }
  17150. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  17151. break;
  17152. }
  17153. }
  17154. }
  17155. return false;
  17156. }
  17157. function stringifyExpression(exp) {
  17158. if (isString(exp)) {
  17159. return exp;
  17160. }
  17161. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  17162. return exp.content;
  17163. }
  17164. else {
  17165. return exp.children
  17166. .map(stringifyExpression)
  17167. .join('');
  17168. }
  17169. }
  17170. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  17171. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  17172. // #1587: We need to dynamically increment the key based on the current
  17173. // node's sibling nodes, since chained v-if/else branches are
  17174. // rendered at the same depth
  17175. const siblings = context.parent.children;
  17176. let i = siblings.indexOf(ifNode);
  17177. let key = 0;
  17178. while (i-- >= 0) {
  17179. const sibling = siblings[i];
  17180. if (sibling && sibling.type === 9 /* IF */) {
  17181. key += sibling.branches.length;
  17182. }
  17183. }
  17184. // Exit callback. Complete the codegenNode when all children have been
  17185. // transformed.
  17186. return () => {
  17187. if (isRoot) {
  17188. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  17189. }
  17190. else {
  17191. // attach this branch's codegen node to the v-if root.
  17192. const parentCondition = getParentCondition(ifNode.codegenNode);
  17193. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  17194. }
  17195. };
  17196. });
  17197. });
  17198. // target-agnostic transform used for both Client and SSR
  17199. function processIf(node, dir, context, processCodegen) {
  17200. if (dir.name !== 'else' &&
  17201. (!dir.exp || !dir.exp.content.trim())) {
  17202. const loc = dir.exp ? dir.exp.loc : node.loc;
  17203. context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  17204. dir.exp = createSimpleExpression(`true`, false, loc);
  17205. }
  17206. if ( context.prefixIdentifiers && dir.exp) {
  17207. // dir.exp can only be simple expression because vIf transform is applied
  17208. // before expression transform.
  17209. dir.exp = processExpression(dir.exp, context);
  17210. }
  17211. if (dir.name === 'if') {
  17212. const branch = createIfBranch(node, dir);
  17213. const ifNode = {
  17214. type: 9 /* IF */,
  17215. loc: node.loc,
  17216. branches: [branch]
  17217. };
  17218. context.replaceNode(ifNode);
  17219. if (processCodegen) {
  17220. return processCodegen(ifNode, branch, true);
  17221. }
  17222. }
  17223. else {
  17224. // locate the adjacent v-if
  17225. const siblings = context.parent.children;
  17226. const comments = [];
  17227. let i = siblings.indexOf(node);
  17228. while (i-- >= -1) {
  17229. const sibling = siblings[i];
  17230. if ( sibling && sibling.type === 3 /* COMMENT */) {
  17231. context.removeNode(sibling);
  17232. comments.unshift(sibling);
  17233. continue;
  17234. }
  17235. if (sibling &&
  17236. sibling.type === 2 /* TEXT */ &&
  17237. !sibling.content.trim().length) {
  17238. context.removeNode(sibling);
  17239. continue;
  17240. }
  17241. if (sibling && sibling.type === 9 /* IF */) {
  17242. // move the node to the if node's branches
  17243. context.removeNode();
  17244. const branch = createIfBranch(node, dir);
  17245. if ( comments.length) {
  17246. branch.children = [...comments, ...branch.children];
  17247. }
  17248. // check if user is forcing same key on different branches
  17249. {
  17250. const key = branch.userKey;
  17251. if (key) {
  17252. sibling.branches.forEach(({ userKey }) => {
  17253. if (isSameKey(userKey, key)) {
  17254. context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  17255. }
  17256. });
  17257. }
  17258. }
  17259. sibling.branches.push(branch);
  17260. const onExit = processCodegen && processCodegen(sibling, branch, false);
  17261. // since the branch was removed, it will not be traversed.
  17262. // make sure to traverse here.
  17263. traverseNode(branch, context);
  17264. // call on exit
  17265. if (onExit)
  17266. onExit();
  17267. // make sure to reset currentNode after traversal to indicate this
  17268. // node has been removed.
  17269. context.currentNode = null;
  17270. }
  17271. else {
  17272. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  17273. }
  17274. break;
  17275. }
  17276. }
  17277. }
  17278. function createIfBranch(node, dir) {
  17279. return {
  17280. type: 10 /* IF_BRANCH */,
  17281. loc: node.loc,
  17282. condition: dir.name === 'else' ? undefined : dir.exp,
  17283. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  17284. ? node.children
  17285. : [node],
  17286. userKey: findProp(node, `key`)
  17287. };
  17288. }
  17289. function createCodegenNodeForBranch(branch, keyIndex, context) {
  17290. if (branch.condition) {
  17291. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  17292. // make sure to pass in asBlock: true so that the comment node call
  17293. // closes the current block.
  17294. createCallExpression(context.helper(CREATE_COMMENT), [
  17295. '"v-if"' ,
  17296. 'true'
  17297. ]));
  17298. }
  17299. else {
  17300. return createChildrenCodegenNode(branch, keyIndex, context);
  17301. }
  17302. }
  17303. function createChildrenCodegenNode(branch, keyIndex, context) {
  17304. const { helper } = context;
  17305. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
  17306. const { children } = branch;
  17307. const firstChild = children[0];
  17308. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  17309. if (needFragmentWrapper) {
  17310. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  17311. // optimize away nested fragments when child is a ForNode
  17312. const vnodeCall = firstChild.codegenNode;
  17313. injectProp(vnodeCall, keyProperty, context);
  17314. return vnodeCall;
  17315. }
  17316. else {
  17317. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, 64 /* STABLE_FRAGMENT */ +
  17318. ( ` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  17319. ), undefined, undefined, true, false, branch.loc);
  17320. }
  17321. }
  17322. else {
  17323. const vnodeCall = firstChild
  17324. .codegenNode;
  17325. // Change createVNode to createBlock.
  17326. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  17327. vnodeCall.isBlock = true;
  17328. helper(OPEN_BLOCK);
  17329. helper(CREATE_BLOCK);
  17330. }
  17331. // inject branch key
  17332. injectProp(vnodeCall, keyProperty, context);
  17333. return vnodeCall;
  17334. }
  17335. }
  17336. function isSameKey(a, b) {
  17337. if (!a || a.type !== b.type) {
  17338. return false;
  17339. }
  17340. if (a.type === 6 /* ATTRIBUTE */) {
  17341. if (a.value.content !== b.value.content) {
  17342. return false;
  17343. }
  17344. }
  17345. else {
  17346. // directive
  17347. const exp = a.exp;
  17348. const branchExp = b.exp;
  17349. if (exp.type !== branchExp.type) {
  17350. return false;
  17351. }
  17352. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  17353. (exp.isStatic !== branchExp.isStatic ||
  17354. exp.content !== branchExp.content)) {
  17355. return false;
  17356. }
  17357. }
  17358. return true;
  17359. }
  17360. function getParentCondition(node) {
  17361. while (true) {
  17362. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  17363. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  17364. node = node.alternate;
  17365. }
  17366. else {
  17367. return node;
  17368. }
  17369. }
  17370. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  17371. node = node.value;
  17372. }
  17373. }
  17374. }
  17375. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  17376. const { helper } = context;
  17377. return processFor(node, dir, context, forNode => {
  17378. // create the loop render function expression now, and add the
  17379. // iterator on exit after all children have been traversed
  17380. const renderExp = createCallExpression(helper(RENDER_LIST), [
  17381. forNode.source
  17382. ]);
  17383. const keyProp = findProp(node, `key`);
  17384. const keyProperty = keyProp
  17385. ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
  17386. ? createSimpleExpression(keyProp.value.content, true)
  17387. : keyProp.exp)
  17388. : null;
  17389. if ( context.prefixIdentifiers && keyProperty) {
  17390. // #2085 process :key expression needs to be processed in order for it
  17391. // to behave consistently for <template v-for> and <div v-for>.
  17392. // In the case of `<template v-for>`, the node is discarded and never
  17393. // traversed so its key expression won't be processed by the normal
  17394. // transforms.
  17395. keyProperty.value = processExpression(keyProperty.value, context);
  17396. }
  17397. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  17398. forNode.source.constType > 0;
  17399. const fragmentFlag = isStableFragment
  17400. ? 64 /* STABLE_FRAGMENT */
  17401. : keyProp
  17402. ? 128 /* KEYED_FRAGMENT */
  17403. : 256 /* UNKEYED_FRAGMENT */;
  17404. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  17405. ( ` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
  17406. return () => {
  17407. // finish the codegen now that all children have been traversed
  17408. let childBlock;
  17409. const isTemplate = isTemplateNode(node);
  17410. const { children } = forNode;
  17411. // check <template v-for> key placement
  17412. if ( isTemplate) {
  17413. node.children.some(c => {
  17414. if (c.type === 1 /* ELEMENT */) {
  17415. const key = findProp(c, 'key');
  17416. if (key) {
  17417. context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  17418. return true;
  17419. }
  17420. }
  17421. });
  17422. }
  17423. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  17424. const slotOutlet = isSlotOutlet(node)
  17425. ? node
  17426. : isTemplate &&
  17427. node.children.length === 1 &&
  17428. isSlotOutlet(node.children[0])
  17429. ? node.children[0] // api-extractor somehow fails to infer this
  17430. : null;
  17431. if (slotOutlet) {
  17432. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  17433. childBlock = slotOutlet.codegenNode;
  17434. if (isTemplate && keyProperty) {
  17435. // <template v-for="..." :key="..."><slot/></template>
  17436. // we need to inject the key to the renderSlot() call.
  17437. // the props for renderSlot is passed as the 3rd argument.
  17438. injectProp(childBlock, keyProperty, context);
  17439. }
  17440. }
  17441. else if (needFragmentWrapper) {
  17442. // <template v-for="..."> with text or multi-elements
  17443. // should generate a fragment block for each loop
  17444. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
  17445. ( ` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  17446. ), undefined, undefined, true);
  17447. }
  17448. else {
  17449. // Normal element v-for. Directly use the child's codegenNode
  17450. // but mark it as a block.
  17451. childBlock = children[0]
  17452. .codegenNode;
  17453. if (isTemplate && keyProperty) {
  17454. injectProp(childBlock, keyProperty, context);
  17455. }
  17456. childBlock.isBlock = !isStableFragment;
  17457. if (childBlock.isBlock) {
  17458. helper(OPEN_BLOCK);
  17459. helper(CREATE_BLOCK);
  17460. }
  17461. else {
  17462. helper(CREATE_VNODE);
  17463. }
  17464. }
  17465. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  17466. };
  17467. });
  17468. });
  17469. // target-agnostic transform used for both Client and SSR
  17470. function processFor(node, dir, context, processCodegen) {
  17471. if (!dir.exp) {
  17472. context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  17473. return;
  17474. }
  17475. const parseResult = parseForExpression(
  17476. // can only be simple expression because vFor transform is applied
  17477. // before expression transform.
  17478. dir.exp, context);
  17479. if (!parseResult) {
  17480. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  17481. return;
  17482. }
  17483. const { addIdentifiers, removeIdentifiers, scopes } = context;
  17484. const { source, value, key, index } = parseResult;
  17485. const forNode = {
  17486. type: 11 /* FOR */,
  17487. loc: dir.loc,
  17488. source,
  17489. valueAlias: value,
  17490. keyAlias: key,
  17491. objectIndexAlias: index,
  17492. parseResult,
  17493. children: isTemplateNode(node) ? node.children : [node]
  17494. };
  17495. context.replaceNode(forNode);
  17496. // bookkeeping
  17497. scopes.vFor++;
  17498. if ( context.prefixIdentifiers) {
  17499. // scope management
  17500. // inject identifiers to context
  17501. value && addIdentifiers(value);
  17502. key && addIdentifiers(key);
  17503. index && addIdentifiers(index);
  17504. }
  17505. const onExit = processCodegen && processCodegen(forNode);
  17506. return () => {
  17507. scopes.vFor--;
  17508. if ( context.prefixIdentifiers) {
  17509. value && removeIdentifiers(value);
  17510. key && removeIdentifiers(key);
  17511. index && removeIdentifiers(index);
  17512. }
  17513. if (onExit)
  17514. onExit();
  17515. };
  17516. }
  17517. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  17518. // This regex doesn't cover the case if key or index aliases have destructuring,
  17519. // but those do not make sense in the first place, so this works in practice.
  17520. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  17521. const stripParensRE = /^\(|\)$/g;
  17522. function parseForExpression(input, context) {
  17523. const loc = input.loc;
  17524. const exp = input.content;
  17525. const inMatch = exp.match(forAliasRE);
  17526. if (!inMatch)
  17527. return;
  17528. const [, LHS, RHS] = inMatch;
  17529. const result = {
  17530. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  17531. value: undefined,
  17532. key: undefined,
  17533. index: undefined
  17534. };
  17535. if ( context.prefixIdentifiers) {
  17536. result.source = processExpression(result.source, context);
  17537. }
  17538. let valueContent = LHS.trim()
  17539. .replace(stripParensRE, '')
  17540. .trim();
  17541. const trimmedOffset = LHS.indexOf(valueContent);
  17542. const iteratorMatch = valueContent.match(forIteratorRE);
  17543. if (iteratorMatch) {
  17544. valueContent = valueContent.replace(forIteratorRE, '').trim();
  17545. const keyContent = iteratorMatch[1].trim();
  17546. let keyOffset;
  17547. if (keyContent) {
  17548. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  17549. result.key = createAliasExpression(loc, keyContent, keyOffset);
  17550. if ( context.prefixIdentifiers) {
  17551. result.key = processExpression(result.key, context, true);
  17552. }
  17553. }
  17554. if (iteratorMatch[2]) {
  17555. const indexContent = iteratorMatch[2].trim();
  17556. if (indexContent) {
  17557. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  17558. ? keyOffset + keyContent.length
  17559. : trimmedOffset + valueContent.length));
  17560. if ( context.prefixIdentifiers) {
  17561. result.index = processExpression(result.index, context, true);
  17562. }
  17563. }
  17564. }
  17565. }
  17566. if (valueContent) {
  17567. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  17568. if ( context.prefixIdentifiers) {
  17569. result.value = processExpression(result.value, context, true);
  17570. }
  17571. }
  17572. return result;
  17573. }
  17574. function createAliasExpression(range, content, offset) {
  17575. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  17576. }
  17577. function createForLoopParams({ value, key, index }) {
  17578. const params = [];
  17579. if (value) {
  17580. params.push(value);
  17581. }
  17582. if (key) {
  17583. if (!value) {
  17584. params.push(createSimpleExpression(`_`, false));
  17585. }
  17586. params.push(key);
  17587. }
  17588. if (index) {
  17589. if (!key) {
  17590. if (!value) {
  17591. params.push(createSimpleExpression(`_`, false));
  17592. }
  17593. params.push(createSimpleExpression(`__`, false));
  17594. }
  17595. params.push(index);
  17596. }
  17597. return params;
  17598. }
  17599. const defaultFallback = createSimpleExpression(`undefined`, false);
  17600. // A NodeTransform that:
  17601. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  17602. // by transformExpression. This is only applied in non-browser builds with
  17603. // { prefixIdentifiers: true }.
  17604. // 2. Track v-slot depths so that we know a slot is inside another slot.
  17605. // Note the exit callback is executed before buildSlots() on the same node,
  17606. // so only nested slots see positive numbers.
  17607. const trackSlotScopes = (node, context) => {
  17608. if (node.type === 1 /* ELEMENT */ &&
  17609. (node.tagType === 1 /* COMPONENT */ ||
  17610. node.tagType === 3 /* TEMPLATE */)) {
  17611. // We are only checking non-empty v-slot here
  17612. // since we only care about slots that introduce scope variables.
  17613. const vSlot = findDir(node, 'slot');
  17614. if (vSlot) {
  17615. const slotProps = vSlot.exp;
  17616. if ( context.prefixIdentifiers) {
  17617. slotProps && context.addIdentifiers(slotProps);
  17618. }
  17619. context.scopes.vSlot++;
  17620. return () => {
  17621. if ( context.prefixIdentifiers) {
  17622. slotProps && context.removeIdentifiers(slotProps);
  17623. }
  17624. context.scopes.vSlot--;
  17625. };
  17626. }
  17627. }
  17628. };
  17629. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  17630. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  17631. const trackVForSlotScopes = (node, context) => {
  17632. let vFor;
  17633. if (isTemplateNode(node) &&
  17634. node.props.some(isVSlot) &&
  17635. (vFor = findDir(node, 'for'))) {
  17636. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  17637. if (result) {
  17638. const { value, key, index } = result;
  17639. const { addIdentifiers, removeIdentifiers } = context;
  17640. value && addIdentifiers(value);
  17641. key && addIdentifiers(key);
  17642. index && addIdentifiers(index);
  17643. return () => {
  17644. value && removeIdentifiers(value);
  17645. key && removeIdentifiers(key);
  17646. index && removeIdentifiers(index);
  17647. };
  17648. }
  17649. }
  17650. };
  17651. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  17652. // Instead of being a DirectiveTransform, v-slot processing is called during
  17653. // transformElement to build the slots object for a component.
  17654. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  17655. context.helper(WITH_CTX);
  17656. const { children, loc } = node;
  17657. const slotsProperties = [];
  17658. const dynamicSlots = [];
  17659. const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
  17660. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  17661. // since it likely uses a scope variable.
  17662. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  17663. // with `prefixIdentifiers: true`, this can be further optimized to make
  17664. // it dynamic only when the slot actually uses the scope variables.
  17665. if ( !context.ssr && context.prefixIdentifiers) {
  17666. hasDynamicSlots = hasScopeRef(node, context.identifiers);
  17667. }
  17668. // 1. Check for slot with slotProps on component itself.
  17669. // <Comp v-slot="{ prop }"/>
  17670. const onComponentSlot = findDir(node, 'slot', true);
  17671. if (onComponentSlot) {
  17672. const { arg, exp } = onComponentSlot;
  17673. if (arg && !isStaticExp(arg)) {
  17674. hasDynamicSlots = true;
  17675. }
  17676. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  17677. }
  17678. // 2. Iterate through children and check for template slots
  17679. // <template v-slot:foo="{ prop }">
  17680. let hasTemplateSlots = false;
  17681. let hasNamedDefaultSlot = false;
  17682. const implicitDefaultChildren = [];
  17683. const seenSlotNames = new Set();
  17684. for (let i = 0; i < children.length; i++) {
  17685. const slotElement = children[i];
  17686. let slotDir;
  17687. if (!isTemplateNode(slotElement) ||
  17688. !(slotDir = findDir(slotElement, 'slot', true))) {
  17689. // not a <template v-slot>, skip.
  17690. if (slotElement.type !== 3 /* COMMENT */) {
  17691. implicitDefaultChildren.push(slotElement);
  17692. }
  17693. continue;
  17694. }
  17695. if (onComponentSlot) {
  17696. // already has on-component slot - this is incorrect usage.
  17697. context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  17698. break;
  17699. }
  17700. hasTemplateSlots = true;
  17701. const { children: slotChildren, loc: slotLoc } = slotElement;
  17702. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  17703. // check if name is dynamic.
  17704. let staticSlotName;
  17705. if (isStaticExp(slotName)) {
  17706. staticSlotName = slotName ? slotName.content : `default`;
  17707. }
  17708. else {
  17709. hasDynamicSlots = true;
  17710. }
  17711. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  17712. // check if this slot is conditional (v-if/v-for)
  17713. let vIf;
  17714. let vElse;
  17715. let vFor;
  17716. if ((vIf = findDir(slotElement, 'if'))) {
  17717. hasDynamicSlots = true;
  17718. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  17719. }
  17720. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  17721. // find adjacent v-if
  17722. let j = i;
  17723. let prev;
  17724. while (j--) {
  17725. prev = children[j];
  17726. if (prev.type !== 3 /* COMMENT */) {
  17727. break;
  17728. }
  17729. }
  17730. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  17731. // remove node
  17732. children.splice(i, 1);
  17733. i--;
  17734. // attach this slot to previous conditional
  17735. let conditional = dynamicSlots[dynamicSlots.length - 1];
  17736. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  17737. conditional = conditional.alternate;
  17738. }
  17739. conditional.alternate = vElse.exp
  17740. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  17741. : buildDynamicSlot(slotName, slotFunction);
  17742. }
  17743. else {
  17744. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  17745. }
  17746. }
  17747. else if ((vFor = findDir(slotElement, 'for'))) {
  17748. hasDynamicSlots = true;
  17749. const parseResult = vFor.parseResult ||
  17750. parseForExpression(vFor.exp, context);
  17751. if (parseResult) {
  17752. // Render the dynamic slots as an array and add it to the createSlot()
  17753. // args. The runtime knows how to handle it appropriately.
  17754. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  17755. parseResult.source,
  17756. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  17757. ]));
  17758. }
  17759. else {
  17760. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  17761. }
  17762. }
  17763. else {
  17764. // check duplicate static names
  17765. if (staticSlotName) {
  17766. if (seenSlotNames.has(staticSlotName)) {
  17767. context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  17768. continue;
  17769. }
  17770. seenSlotNames.add(staticSlotName);
  17771. if (staticSlotName === 'default') {
  17772. hasNamedDefaultSlot = true;
  17773. }
  17774. }
  17775. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  17776. }
  17777. }
  17778. if (!onComponentSlot) {
  17779. if (!hasTemplateSlots) {
  17780. // implicit default slot (on component)
  17781. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  17782. }
  17783. else if (implicitDefaultChildren.length) {
  17784. // implicit default slot (mixed with named slots)
  17785. if (hasNamedDefaultSlot) {
  17786. context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  17787. }
  17788. else {
  17789. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  17790. }
  17791. }
  17792. }
  17793. const slotFlag = hasDynamicSlots
  17794. ? 2 /* DYNAMIC */
  17795. : hasForwardedSlots(node.children)
  17796. ? 3 /* FORWARDED */
  17797. : 1 /* STABLE */;
  17798. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  17799. // 2 = compiled but dynamic = can skip normalization, but must run diff
  17800. // 1 = compiled and static = can skip normalization AND diff as optimized
  17801. createSimpleExpression(slotFlag + ( ` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  17802. if (dynamicSlots.length) {
  17803. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  17804. slots,
  17805. createArrayExpression(dynamicSlots)
  17806. ]);
  17807. }
  17808. return {
  17809. slots,
  17810. hasDynamicSlots
  17811. };
  17812. }
  17813. function buildDynamicSlot(name, fn) {
  17814. return createObjectExpression([
  17815. createObjectProperty(`name`, name),
  17816. createObjectProperty(`fn`, fn)
  17817. ]);
  17818. }
  17819. function hasForwardedSlots(children) {
  17820. for (let i = 0; i < children.length; i++) {
  17821. const child = children[i];
  17822. if (child.type === 1 /* ELEMENT */) {
  17823. if (child.tagType === 2 /* SLOT */ ||
  17824. (child.tagType === 0 /* ELEMENT */ &&
  17825. hasForwardedSlots(child.children))) {
  17826. return true;
  17827. }
  17828. }
  17829. }
  17830. return false;
  17831. }
  17832. // some directive transforms (e.g. v-model) may return a symbol for runtime
  17833. // import, which should be used instead of a resolveDirective call.
  17834. const directiveImportMap = new WeakMap();
  17835. // generate a JavaScript AST for this element's codegen
  17836. const transformElement = (node, context) => {
  17837. if (!(node.type === 1 /* ELEMENT */ &&
  17838. (node.tagType === 0 /* ELEMENT */ ||
  17839. node.tagType === 1 /* COMPONENT */))) {
  17840. return;
  17841. }
  17842. // perform the work on exit, after all child expressions have been
  17843. // processed and merged.
  17844. return function postTransformElement() {
  17845. const { tag, props } = node;
  17846. const isComponent = node.tagType === 1 /* COMPONENT */;
  17847. // The goal of the transform is to create a codegenNode implementing the
  17848. // VNodeCall interface.
  17849. const vnodeTag = isComponent
  17850. ? resolveComponentType(node, context)
  17851. : `"${tag}"`;
  17852. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  17853. let vnodeProps;
  17854. let vnodeChildren;
  17855. let vnodePatchFlag;
  17856. let patchFlag = 0;
  17857. let vnodeDynamicProps;
  17858. let dynamicPropNames;
  17859. let vnodeDirectives;
  17860. let shouldUseBlock =
  17861. // dynamic component may resolve to plain elements
  17862. isDynamicComponent ||
  17863. vnodeTag === TELEPORT ||
  17864. vnodeTag === SUSPENSE ||
  17865. (!isComponent &&
  17866. // <svg> and <foreignObject> must be forced into blocks so that block
  17867. // updates inside get proper isSVG flag at runtime. (#639, #643)
  17868. // This is technically web-specific, but splitting the logic out of core
  17869. // leads to too much unnecessary complexity.
  17870. (tag === 'svg' ||
  17871. tag === 'foreignObject' ||
  17872. // #938: elements with dynamic keys should be forced into blocks
  17873. findProp(node, 'key', true)));
  17874. // props
  17875. if (props.length > 0) {
  17876. const propsBuildResult = buildProps(node, context);
  17877. vnodeProps = propsBuildResult.props;
  17878. patchFlag = propsBuildResult.patchFlag;
  17879. dynamicPropNames = propsBuildResult.dynamicPropNames;
  17880. const directives = propsBuildResult.directives;
  17881. vnodeDirectives =
  17882. directives && directives.length
  17883. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  17884. : undefined;
  17885. }
  17886. // children
  17887. if (node.children.length > 0) {
  17888. if (vnodeTag === KEEP_ALIVE) {
  17889. // Although a built-in component, we compile KeepAlive with raw children
  17890. // instead of slot functions so that it can be used inside Transition
  17891. // or other Transition-wrapping HOCs.
  17892. // To ensure correct updates with block optimizations, we need to:
  17893. // 1. Force keep-alive into a block. This avoids its children being
  17894. // collected by a parent block.
  17895. shouldUseBlock = true;
  17896. // 2. Force keep-alive to always be updated, since it uses raw children.
  17897. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  17898. if ( node.children.length > 1) {
  17899. context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  17900. start: node.children[0].loc.start,
  17901. end: node.children[node.children.length - 1].loc.end,
  17902. source: ''
  17903. }));
  17904. }
  17905. }
  17906. const shouldBuildAsSlots = isComponent &&
  17907. // Teleport is not a real component and has dedicated runtime handling
  17908. vnodeTag !== TELEPORT &&
  17909. // explained above.
  17910. vnodeTag !== KEEP_ALIVE;
  17911. if (shouldBuildAsSlots) {
  17912. const { slots, hasDynamicSlots } = buildSlots(node, context);
  17913. vnodeChildren = slots;
  17914. if (hasDynamicSlots) {
  17915. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  17916. }
  17917. }
  17918. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  17919. const child = node.children[0];
  17920. const type = child.type;
  17921. // check for dynamic text children
  17922. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  17923. type === 8 /* COMPOUND_EXPRESSION */;
  17924. if (hasDynamicTextChild &&
  17925. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  17926. patchFlag |= 1 /* TEXT */;
  17927. }
  17928. // pass directly if the only child is a text node
  17929. // (plain / interpolation / expression)
  17930. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  17931. vnodeChildren = child;
  17932. }
  17933. else {
  17934. vnodeChildren = node.children;
  17935. }
  17936. }
  17937. else {
  17938. vnodeChildren = node.children;
  17939. }
  17940. }
  17941. // patchFlag & dynamicPropNames
  17942. if (patchFlag !== 0) {
  17943. {
  17944. if (patchFlag < 0) {
  17945. // special flags (negative and mutually exclusive)
  17946. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  17947. }
  17948. else {
  17949. // bitwise flags
  17950. const flagNames = Object.keys(PatchFlagNames)
  17951. .map(Number)
  17952. .filter(n => n > 0 && patchFlag & n)
  17953. .map(n => PatchFlagNames[n])
  17954. .join(`, `);
  17955. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  17956. }
  17957. }
  17958. if (dynamicPropNames && dynamicPropNames.length) {
  17959. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  17960. }
  17961. }
  17962. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
  17963. };
  17964. };
  17965. function resolveComponentType(node, context, ssr = false) {
  17966. const { tag } = node;
  17967. // 1. dynamic component
  17968. const isProp = node.tag === 'component' ? findProp(node, 'is') : findDir(node, 'is');
  17969. if (isProp) {
  17970. const exp = isProp.type === 6 /* ATTRIBUTE */
  17971. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  17972. : isProp.exp;
  17973. if (exp) {
  17974. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  17975. exp
  17976. ]);
  17977. }
  17978. }
  17979. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  17980. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  17981. if (builtIn) {
  17982. // built-ins are simply fallthroughs / have special handling during ssr
  17983. // so we don't need to import their runtime equivalents
  17984. if (!ssr)
  17985. context.helper(builtIn);
  17986. return builtIn;
  17987. }
  17988. // 3. user component (from setup bindings)
  17989. // this is skipped in browser build since browser builds do not perform
  17990. // binding analysis.
  17991. {
  17992. const fromSetup = resolveSetupReference(tag, context);
  17993. if (fromSetup) {
  17994. return fromSetup;
  17995. }
  17996. }
  17997. // 4. Self referencing component (inferred from filename)
  17998. if ( context.selfName) {
  17999. if (capitalize(camelize(tag)) === context.selfName) {
  18000. context.helper(RESOLVE_COMPONENT);
  18001. context.components.add(`_self`);
  18002. return toValidAssetId(`_self`, `component`);
  18003. }
  18004. }
  18005. // 5. user component (resolve)
  18006. context.helper(RESOLVE_COMPONENT);
  18007. context.components.add(tag);
  18008. return toValidAssetId(tag, `component`);
  18009. }
  18010. function resolveSetupReference(name, context) {
  18011. const bindings = context.bindingMetadata;
  18012. if (!bindings) {
  18013. return;
  18014. }
  18015. const camelName = camelize(name);
  18016. const PascalName = capitalize(camelName);
  18017. const checkType = (type) => {
  18018. if (bindings[name] === type) {
  18019. return name;
  18020. }
  18021. if (bindings[camelName] === type) {
  18022. return camelName;
  18023. }
  18024. if (bindings[PascalName] === type) {
  18025. return PascalName;
  18026. }
  18027. };
  18028. const fromConst = checkType("setup-const" /* SETUP_CONST */);
  18029. if (fromConst) {
  18030. return context.inline
  18031. ? // in inline mode, const setup bindings (e.g. imports) can be used as-is
  18032. fromConst
  18033. : `$setup[${JSON.stringify(fromConst)}]`;
  18034. }
  18035. const fromMaybeRef = checkType("setup-let" /* SETUP_LET */) ||
  18036. checkType("setup-ref" /* SETUP_REF */) ||
  18037. checkType("setup-maybe-ref" /* SETUP_MAYBE_REF */);
  18038. if (fromMaybeRef) {
  18039. return context.inline
  18040. ? // setup scope bindings that may be refs need to be unrefed
  18041. `${context.helperString(UNREF)}(${fromMaybeRef})`
  18042. : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  18043. }
  18044. }
  18045. function buildProps(node, context, props = node.props, ssr = false) {
  18046. const { tag, loc: elementLoc } = node;
  18047. const isComponent = node.tagType === 1 /* COMPONENT */;
  18048. let properties = [];
  18049. const mergeArgs = [];
  18050. const runtimeDirectives = [];
  18051. // patchFlag analysis
  18052. let patchFlag = 0;
  18053. let hasRef = false;
  18054. let hasClassBinding = false;
  18055. let hasStyleBinding = false;
  18056. let hasHydrationEventBinding = false;
  18057. let hasDynamicKeys = false;
  18058. let hasVnodeHook = false;
  18059. const dynamicPropNames = [];
  18060. const analyzePatchFlag = ({ key, value }) => {
  18061. if (isStaticExp(key)) {
  18062. const name = key.content;
  18063. const isEventHandler = isOn(name);
  18064. if (!isComponent &&
  18065. isEventHandler &&
  18066. // omit the flag for click handlers because hydration gives click
  18067. // dedicated fast path.
  18068. name.toLowerCase() !== 'onclick' &&
  18069. // omit v-model handlers
  18070. name !== 'onUpdate:modelValue' &&
  18071. // omit onVnodeXXX hooks
  18072. !isReservedProp(name)) {
  18073. hasHydrationEventBinding = true;
  18074. }
  18075. if (isEventHandler && isReservedProp(name)) {
  18076. hasVnodeHook = true;
  18077. }
  18078. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  18079. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  18080. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  18081. getConstantType(value, context) > 0)) {
  18082. // skip if the prop is a cached handler or has constant value
  18083. return;
  18084. }
  18085. if (name === 'ref') {
  18086. hasRef = true;
  18087. }
  18088. else if (name === 'class' && !isComponent) {
  18089. hasClassBinding = true;
  18090. }
  18091. else if (name === 'style' && !isComponent) {
  18092. hasStyleBinding = true;
  18093. }
  18094. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  18095. dynamicPropNames.push(name);
  18096. }
  18097. }
  18098. else {
  18099. hasDynamicKeys = true;
  18100. }
  18101. };
  18102. for (let i = 0; i < props.length; i++) {
  18103. // static attribute
  18104. const prop = props[i];
  18105. if (prop.type === 6 /* ATTRIBUTE */) {
  18106. const { loc, name, value } = prop;
  18107. let isStatic = true;
  18108. if (name === 'ref') {
  18109. hasRef = true;
  18110. // in inline mode there is no setupState object, so we can't use string
  18111. // keys to set the ref. Instead, we need to transform it to pass the
  18112. // acrtual ref instead.
  18113. if ( context.inline) {
  18114. isStatic = false;
  18115. }
  18116. }
  18117. // skip :is on <component>
  18118. if (name === 'is' && tag === 'component') {
  18119. continue;
  18120. }
  18121. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  18122. }
  18123. else {
  18124. // directives
  18125. const { name, arg, exp, loc } = prop;
  18126. const isBind = name === 'bind';
  18127. const isOn = name === 'on';
  18128. // skip v-slot - it is handled by its dedicated transform.
  18129. if (name === 'slot') {
  18130. if (!isComponent) {
  18131. context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
  18132. }
  18133. continue;
  18134. }
  18135. // skip v-once - it is handled by its dedicated transform.
  18136. if (name === 'once') {
  18137. continue;
  18138. }
  18139. // skip v-is and :is on <component>
  18140. if (name === 'is' ||
  18141. (isBind && tag === 'component' && isBindKey(arg, 'is'))) {
  18142. continue;
  18143. }
  18144. // skip v-on in SSR compilation
  18145. if (isOn && ssr) {
  18146. continue;
  18147. }
  18148. // special case for v-bind and v-on with no argument
  18149. if (!arg && (isBind || isOn)) {
  18150. hasDynamicKeys = true;
  18151. if (exp) {
  18152. if (properties.length) {
  18153. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  18154. properties = [];
  18155. }
  18156. if (isBind) {
  18157. mergeArgs.push(exp);
  18158. }
  18159. else {
  18160. // v-on="obj" -> toHandlers(obj)
  18161. mergeArgs.push({
  18162. type: 14 /* JS_CALL_EXPRESSION */,
  18163. loc,
  18164. callee: context.helper(TO_HANDLERS),
  18165. arguments: [exp]
  18166. });
  18167. }
  18168. }
  18169. else {
  18170. context.onError(createCompilerError(isBind
  18171. ? 33 /* X_V_BIND_NO_EXPRESSION */
  18172. : 34 /* X_V_ON_NO_EXPRESSION */, loc));
  18173. }
  18174. continue;
  18175. }
  18176. const directiveTransform = context.directiveTransforms[name];
  18177. if (directiveTransform) {
  18178. // has built-in directive transform.
  18179. const { props, needRuntime } = directiveTransform(prop, node, context);
  18180. !ssr && props.forEach(analyzePatchFlag);
  18181. properties.push(...props);
  18182. if (needRuntime) {
  18183. runtimeDirectives.push(prop);
  18184. if (isSymbol(needRuntime)) {
  18185. directiveImportMap.set(prop, needRuntime);
  18186. }
  18187. }
  18188. }
  18189. else {
  18190. // no built-in transform, this is a user custom directive.
  18191. runtimeDirectives.push(prop);
  18192. }
  18193. }
  18194. }
  18195. let propsExpression = undefined;
  18196. // has v-bind="object" or v-on="object", wrap with mergeProps
  18197. if (mergeArgs.length) {
  18198. if (properties.length) {
  18199. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  18200. }
  18201. if (mergeArgs.length > 1) {
  18202. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  18203. }
  18204. else {
  18205. // single v-bind with nothing else - no need for a mergeProps call
  18206. propsExpression = mergeArgs[0];
  18207. }
  18208. }
  18209. else if (properties.length) {
  18210. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  18211. }
  18212. // patchFlag analysis
  18213. if (hasDynamicKeys) {
  18214. patchFlag |= 16 /* FULL_PROPS */;
  18215. }
  18216. else {
  18217. if (hasClassBinding) {
  18218. patchFlag |= 2 /* CLASS */;
  18219. }
  18220. if (hasStyleBinding) {
  18221. patchFlag |= 4 /* STYLE */;
  18222. }
  18223. if (dynamicPropNames.length) {
  18224. patchFlag |= 8 /* PROPS */;
  18225. }
  18226. if (hasHydrationEventBinding) {
  18227. patchFlag |= 32 /* HYDRATE_EVENTS */;
  18228. }
  18229. }
  18230. if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  18231. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  18232. patchFlag |= 512 /* NEED_PATCH */;
  18233. }
  18234. return {
  18235. props: propsExpression,
  18236. directives: runtimeDirectives,
  18237. patchFlag,
  18238. dynamicPropNames
  18239. };
  18240. }
  18241. // Dedupe props in an object literal.
  18242. // Literal duplicated attributes would have been warned during the parse phase,
  18243. // however, it's possible to encounter duplicated `onXXX` handlers with different
  18244. // modifiers. We also need to merge static and dynamic class / style attributes.
  18245. // - onXXX handlers / style: merge into array
  18246. // - class: merge into single expression with concatenation
  18247. function dedupeProperties(properties) {
  18248. const knownProps = new Map();
  18249. const deduped = [];
  18250. for (let i = 0; i < properties.length; i++) {
  18251. const prop = properties[i];
  18252. // dynamic keys are always allowed
  18253. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  18254. deduped.push(prop);
  18255. continue;
  18256. }
  18257. const name = prop.key.content;
  18258. const existing = knownProps.get(name);
  18259. if (existing) {
  18260. if (name === 'style' || name === 'class' || name.startsWith('on')) {
  18261. mergeAsArray(existing, prop);
  18262. }
  18263. // unexpected duplicate, should have emitted error during parse
  18264. }
  18265. else {
  18266. knownProps.set(name, prop);
  18267. deduped.push(prop);
  18268. }
  18269. }
  18270. return deduped;
  18271. }
  18272. function mergeAsArray(existing, incoming) {
  18273. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  18274. existing.value.elements.push(incoming.value);
  18275. }
  18276. else {
  18277. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  18278. }
  18279. }
  18280. function buildDirectiveArgs(dir, context) {
  18281. const dirArgs = [];
  18282. const runtime = directiveImportMap.get(dir);
  18283. if (runtime) {
  18284. // built-in directive with runtime
  18285. dirArgs.push(context.helperString(runtime));
  18286. }
  18287. else {
  18288. // user directive.
  18289. // see if we have directives exposed via <script setup>
  18290. const fromSetup = resolveSetupReference(dir.name, context);
  18291. if (fromSetup) {
  18292. dirArgs.push(fromSetup);
  18293. }
  18294. else {
  18295. // inject statement for resolving directive
  18296. context.helper(RESOLVE_DIRECTIVE);
  18297. context.directives.add(dir.name);
  18298. dirArgs.push(toValidAssetId(dir.name, `directive`));
  18299. }
  18300. }
  18301. const { loc } = dir;
  18302. if (dir.exp)
  18303. dirArgs.push(dir.exp);
  18304. if (dir.arg) {
  18305. if (!dir.exp) {
  18306. dirArgs.push(`void 0`);
  18307. }
  18308. dirArgs.push(dir.arg);
  18309. }
  18310. if (Object.keys(dir.modifiers).length) {
  18311. if (!dir.arg) {
  18312. if (!dir.exp) {
  18313. dirArgs.push(`void 0`);
  18314. }
  18315. dirArgs.push(`void 0`);
  18316. }
  18317. const trueExpression = createSimpleExpression(`true`, false, loc);
  18318. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  18319. }
  18320. return createArrayExpression(dirArgs, dir.loc);
  18321. }
  18322. function stringifyDynamicPropNames(props) {
  18323. let propsNamesString = `[`;
  18324. for (let i = 0, l = props.length; i < l; i++) {
  18325. propsNamesString += JSON.stringify(props[i]);
  18326. if (i < l - 1)
  18327. propsNamesString += ', ';
  18328. }
  18329. return propsNamesString + `]`;
  18330. }
  18331. const transformSlotOutlet = (node, context) => {
  18332. if (isSlotOutlet(node)) {
  18333. const { children, loc } = node;
  18334. const { slotName, slotProps } = processSlotOutlet(node, context);
  18335. const slotArgs = [
  18336. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  18337. slotName
  18338. ];
  18339. if (slotProps) {
  18340. slotArgs.push(slotProps);
  18341. }
  18342. if (children.length) {
  18343. if (!slotProps) {
  18344. slotArgs.push(`{}`);
  18345. }
  18346. slotArgs.push(createFunctionExpression([], children, false, false, loc));
  18347. }
  18348. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  18349. }
  18350. };
  18351. function processSlotOutlet(node, context) {
  18352. let slotName = `"default"`;
  18353. let slotProps = undefined;
  18354. const nonNameProps = [];
  18355. for (let i = 0; i < node.props.length; i++) {
  18356. const p = node.props[i];
  18357. if (p.type === 6 /* ATTRIBUTE */) {
  18358. if (p.value) {
  18359. if (p.name === 'name') {
  18360. slotName = JSON.stringify(p.value.content);
  18361. }
  18362. else {
  18363. p.name = camelize(p.name);
  18364. nonNameProps.push(p);
  18365. }
  18366. }
  18367. }
  18368. else {
  18369. if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
  18370. if (p.exp)
  18371. slotName = p.exp;
  18372. }
  18373. else {
  18374. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  18375. p.arg.content = camelize(p.arg.content);
  18376. }
  18377. nonNameProps.push(p);
  18378. }
  18379. }
  18380. }
  18381. if (nonNameProps.length > 0) {
  18382. const { props, directives } = buildProps(node, context, nonNameProps);
  18383. slotProps = props;
  18384. if (directives.length) {
  18385. context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  18386. }
  18387. }
  18388. return {
  18389. slotName,
  18390. slotProps
  18391. };
  18392. }
  18393. const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
  18394. const transformOn = (dir, node, context, augmentor) => {
  18395. const { loc, modifiers, arg } = dir;
  18396. if (!dir.exp && !modifiers.length) {
  18397. context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
  18398. }
  18399. let eventName;
  18400. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  18401. if (arg.isStatic) {
  18402. const rawName = arg.content;
  18403. // for all event listeners, auto convert it to camelCase. See issue #2249
  18404. eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
  18405. }
  18406. else {
  18407. // #2388
  18408. eventName = createCompoundExpression([
  18409. `${context.helperString(TO_HANDLER_KEY)}(`,
  18410. arg,
  18411. `)`
  18412. ]);
  18413. }
  18414. }
  18415. else {
  18416. // already a compound expression.
  18417. eventName = arg;
  18418. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  18419. eventName.children.push(`)`);
  18420. }
  18421. // handler processing
  18422. let exp = dir.exp;
  18423. if (exp && !exp.content.trim()) {
  18424. exp = undefined;
  18425. }
  18426. let shouldCache = context.cacheHandlers && !exp;
  18427. if (exp) {
  18428. const isMemberExp = isMemberExpression(exp.content);
  18429. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  18430. const hasMultipleStatements = exp.content.includes(`;`);
  18431. // process the expression since it's been skipped
  18432. if ( context.prefixIdentifiers) {
  18433. isInlineStatement && context.addIdentifiers(`$event`);
  18434. exp = dir.exp = processExpression(exp, context, false, hasMultipleStatements);
  18435. isInlineStatement && context.removeIdentifiers(`$event`);
  18436. // with scope analysis, the function is hoistable if it has no reference
  18437. // to scope variables.
  18438. shouldCache =
  18439. context.cacheHandlers &&
  18440. // runtime constants don't need to be cached
  18441. // (this is analyzed by compileScript in SFC <script setup>)
  18442. !(exp.type === 4 /* SIMPLE_EXPRESSION */ && exp.constType > 0) &&
  18443. // #1541 bail if this is a member exp handler passed to a component -
  18444. // we need to use the original function to preserve arity,
  18445. // e.g. <transition> relies on checking cb.length to determine
  18446. // transition end handling. Inline function is ok since its arity
  18447. // is preserved even when cached.
  18448. !(isMemberExp && node.tagType === 1 /* COMPONENT */) &&
  18449. // bail if the function references closure variables (v-for, v-slot)
  18450. // it must be passed fresh to avoid stale values.
  18451. !hasScopeRef(exp, context.identifiers);
  18452. // If the expression is optimizable and is a member expression pointing
  18453. // to a function, turn it into invocation (and wrap in an arrow function
  18454. // below) so that it always accesses the latest value when called - thus
  18455. // avoiding the need to be patched.
  18456. if (shouldCache && isMemberExp) {
  18457. if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  18458. exp.content = `${exp.content} && ${exp.content}(...args)`;
  18459. }
  18460. else {
  18461. exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
  18462. }
  18463. }
  18464. }
  18465. if (isInlineStatement || (shouldCache && isMemberExp)) {
  18466. // wrap inline statement in a function expression
  18467. exp = createCompoundExpression([
  18468. `${isInlineStatement
  18469. ? context.isTS
  18470. ? `($event: any)`
  18471. : `$event`
  18472. : `${ context.isTS ? `\n//@ts-ignore\n` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  18473. exp,
  18474. hasMultipleStatements ? `}` : `)`
  18475. ]);
  18476. }
  18477. }
  18478. let ret = {
  18479. props: [
  18480. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  18481. ]
  18482. };
  18483. // apply extended compiler augmentor
  18484. if (augmentor) {
  18485. ret = augmentor(ret);
  18486. }
  18487. if (shouldCache) {
  18488. // cache handlers so that it's always the same handler being passed down.
  18489. // this avoids unnecessary re-renders when users use inline handlers on
  18490. // components.
  18491. ret.props[0].value = context.cache(ret.props[0].value);
  18492. }
  18493. return ret;
  18494. };
  18495. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  18496. // codegen for the entire props object. This transform here is only for v-bind
  18497. // *with* args.
  18498. const transformBind = (dir, node, context) => {
  18499. const { exp, modifiers, loc } = dir;
  18500. const arg = dir.arg;
  18501. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  18502. arg.children.unshift(`(`);
  18503. arg.children.push(`) || ""`);
  18504. }
  18505. else if (!arg.isStatic) {
  18506. arg.content = `${arg.content} || ""`;
  18507. }
  18508. // .prop is no longer necessary due to new patch behavior
  18509. // .sync is replaced by v-model:arg
  18510. if (modifiers.includes('camel')) {
  18511. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  18512. if (arg.isStatic) {
  18513. arg.content = camelize(arg.content);
  18514. }
  18515. else {
  18516. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  18517. }
  18518. }
  18519. else {
  18520. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  18521. arg.children.push(`)`);
  18522. }
  18523. }
  18524. if (!exp ||
  18525. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  18526. context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
  18527. return {
  18528. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  18529. };
  18530. }
  18531. return {
  18532. props: [createObjectProperty(arg, exp)]
  18533. };
  18534. };
  18535. // Merge adjacent text nodes and expressions into a single expression
  18536. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  18537. const transformText = (node, context) => {
  18538. if (node.type === 0 /* ROOT */ ||
  18539. node.type === 1 /* ELEMENT */ ||
  18540. node.type === 11 /* FOR */ ||
  18541. node.type === 10 /* IF_BRANCH */) {
  18542. // perform the transform on node exit so that all expressions have already
  18543. // been processed.
  18544. return () => {
  18545. const children = node.children;
  18546. let currentContainer = undefined;
  18547. let hasText = false;
  18548. for (let i = 0; i < children.length; i++) {
  18549. const child = children[i];
  18550. if (isText(child)) {
  18551. hasText = true;
  18552. for (let j = i + 1; j < children.length; j++) {
  18553. const next = children[j];
  18554. if (isText(next)) {
  18555. if (!currentContainer) {
  18556. currentContainer = children[i] = {
  18557. type: 8 /* COMPOUND_EXPRESSION */,
  18558. loc: child.loc,
  18559. children: [child]
  18560. };
  18561. }
  18562. // merge adjacent text node into current
  18563. currentContainer.children.push(` + `, next);
  18564. children.splice(j, 1);
  18565. j--;
  18566. }
  18567. else {
  18568. currentContainer = undefined;
  18569. break;
  18570. }
  18571. }
  18572. }
  18573. }
  18574. if (!hasText ||
  18575. // if this is a plain element with a single text child, leave it
  18576. // as-is since the runtime has dedicated fast path for this by directly
  18577. // setting textContent of the element.
  18578. // for component root it's always normalized anyway.
  18579. (children.length === 1 &&
  18580. (node.type === 0 /* ROOT */ ||
  18581. (node.type === 1 /* ELEMENT */ &&
  18582. node.tagType === 0 /* ELEMENT */)))) {
  18583. return;
  18584. }
  18585. // pre-convert text nodes into createTextVNode(text) calls to avoid
  18586. // runtime normalization.
  18587. for (let i = 0; i < children.length; i++) {
  18588. const child = children[i];
  18589. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  18590. const callArgs = [];
  18591. // createTextVNode defaults to single whitespace, so if it is a
  18592. // single space the code could be an empty call to save bytes.
  18593. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  18594. callArgs.push(child);
  18595. }
  18596. // mark dynamic text with flag so it gets patched inside a block
  18597. if (!context.ssr &&
  18598. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  18599. callArgs.push(1 /* TEXT */ +
  18600. ( ` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
  18601. }
  18602. children[i] = {
  18603. type: 12 /* TEXT_CALL */,
  18604. content: child,
  18605. loc: child.loc,
  18606. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  18607. };
  18608. }
  18609. }
  18610. };
  18611. }
  18612. };
  18613. const seen = new WeakSet();
  18614. const transformOnce = (node, context) => {
  18615. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  18616. if (seen.has(node)) {
  18617. return;
  18618. }
  18619. seen.add(node);
  18620. context.helper(SET_BLOCK_TRACKING);
  18621. return () => {
  18622. const cur = context.currentNode;
  18623. if (cur.codegenNode) {
  18624. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  18625. }
  18626. };
  18627. }
  18628. };
  18629. const transformModel = (dir, node, context) => {
  18630. const { exp, arg } = dir;
  18631. if (!exp) {
  18632. context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  18633. return createTransformProps();
  18634. }
  18635. const rawExp = exp.loc.source;
  18636. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  18637. // im SFC <script setup> inline mode, the exp may have been transformed into
  18638. // _unref(exp)
  18639. const bindingType = context.bindingMetadata[rawExp];
  18640. const maybeRef =
  18641. 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 (
  18649. context.prefixIdentifiers &&
  18650. isSimpleIdentifier(expString) &&
  18651. context.identifiers[expString]) {
  18652. context.onError(createCompilerError(42 /* X_V_MODEL_ON_SCOPE_VARIABLE */, exp.loc));
  18653. return createTransformProps();
  18654. }
  18655. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  18656. const eventName = arg
  18657. ? isStaticExp(arg)
  18658. ? `onUpdate:${arg.content}`
  18659. : createCompoundExpression(['"onUpdate:" + ', arg])
  18660. : `onUpdate:modelValue`;
  18661. let assignmentExp;
  18662. const eventArg = context.isTS ? `($event: any)` : `$event`;
  18663. if (maybeRef) {
  18664. if (bindingType === "setup-ref" /* SETUP_REF */) {
  18665. // v-model used on known ref.
  18666. assignmentExp = createCompoundExpression([
  18667. `${eventArg} => (`,
  18668. createSimpleExpression(rawExp, false, exp.loc),
  18669. `.value = $event)`
  18670. ]);
  18671. }
  18672. else {
  18673. // v-model used on a potentially ref binding in <script setup> inline mode.
  18674. // the assignment needs to check whether the binding is actually a ref.
  18675. const altAssignment = bindingType === "setup-let" /* SETUP_LET */ ? `${rawExp} = $event` : `null`;
  18676. assignmentExp = createCompoundExpression([
  18677. `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? `,
  18678. createSimpleExpression(rawExp, false, exp.loc),
  18679. `.value = $event : ${altAssignment})`
  18680. ]);
  18681. }
  18682. }
  18683. else {
  18684. assignmentExp = createCompoundExpression([
  18685. `${eventArg} => (`,
  18686. exp,
  18687. ` = $event)`
  18688. ]);
  18689. }
  18690. const props = [
  18691. // modelValue: foo
  18692. createObjectProperty(propName, dir.exp),
  18693. // "onUpdate:modelValue": $event => (foo = $event)
  18694. createObjectProperty(eventName, assignmentExp)
  18695. ];
  18696. // cache v-model handler if applicable (when it doesn't refer any scope vars)
  18697. if (
  18698. context.prefixIdentifiers &&
  18699. context.cacheHandlers &&
  18700. !hasScopeRef(exp, context.identifiers)) {
  18701. props[1].value = context.cache(props[1].value);
  18702. }
  18703. // modelModifiers: { foo: true, "bar-baz": true }
  18704. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  18705. const modifiers = dir.modifiers
  18706. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  18707. .join(`, `);
  18708. const modifiersKey = arg
  18709. ? isStaticExp(arg)
  18710. ? `${arg.content}Modifiers`
  18711. : createCompoundExpression([arg, ' + "Modifiers"'])
  18712. : `modelModifiers`;
  18713. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
  18714. }
  18715. return createTransformProps(props);
  18716. };
  18717. function createTransformProps(props = []) {
  18718. return { props };
  18719. }
  18720. function getBaseTransformPreset(prefixIdentifiers) {
  18721. return [
  18722. [
  18723. transformOnce,
  18724. transformIf,
  18725. transformFor,
  18726. ...( prefixIdentifiers
  18727. ? [
  18728. // order is important
  18729. trackVForSlotScopes,
  18730. transformExpression
  18731. ]
  18732. : []),
  18733. transformSlotOutlet,
  18734. transformElement,
  18735. trackSlotScopes,
  18736. transformText
  18737. ],
  18738. {
  18739. on: transformOn,
  18740. bind: transformBind,
  18741. model: transformModel
  18742. }
  18743. ];
  18744. }
  18745. // we name it `baseCompile` so that higher order compilers like
  18746. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  18747. function baseCompile(template, options = {}) {
  18748. const onError = options.onError || defaultOnError;
  18749. const isModuleMode = options.mode === 'module';
  18750. const prefixIdentifiers = (options.prefixIdentifiers === true || isModuleMode);
  18751. if (!prefixIdentifiers && options.cacheHandlers) {
  18752. onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  18753. }
  18754. if (options.scopeId && !isModuleMode) {
  18755. onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
  18756. }
  18757. const ast = isString(template) ? baseParse(template, options) : template;
  18758. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  18759. transform(ast, extend({}, options, {
  18760. prefixIdentifiers,
  18761. nodeTransforms: [
  18762. ...nodeTransforms,
  18763. ...(options.nodeTransforms || []) // user transforms
  18764. ],
  18765. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  18766. )
  18767. }));
  18768. return generate(ast, extend({}, options, {
  18769. prefixIdentifiers
  18770. }));
  18771. }
  18772. const noopDirectiveTransform = () => ({ props: [] });
  18773. const V_MODEL_RADIO = Symbol( `vModelRadio` );
  18774. const V_MODEL_CHECKBOX = Symbol( `vModelCheckbox` );
  18775. const V_MODEL_TEXT = Symbol( `vModelText` );
  18776. const V_MODEL_SELECT = Symbol( `vModelSelect` );
  18777. const V_MODEL_DYNAMIC = Symbol( `vModelDynamic` );
  18778. const V_ON_WITH_MODIFIERS = Symbol( `vOnModifiersGuard` );
  18779. const V_ON_WITH_KEYS = Symbol( `vOnKeysGuard` );
  18780. const V_SHOW = Symbol( `vShow` );
  18781. const TRANSITION = Symbol( `Transition` );
  18782. const TRANSITION_GROUP = Symbol( `TransitionGroup` );
  18783. registerRuntimeHelpers({
  18784. [V_MODEL_RADIO]: `vModelRadio`,
  18785. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  18786. [V_MODEL_TEXT]: `vModelText`,
  18787. [V_MODEL_SELECT]: `vModelSelect`,
  18788. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  18789. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  18790. [V_ON_WITH_KEYS]: `withKeys`,
  18791. [V_SHOW]: `vShow`,
  18792. [TRANSITION]: `Transition`,
  18793. [TRANSITION_GROUP]: `TransitionGroup`
  18794. });
  18795. var namedCharacterReferences = {
  18796. GT: ">",
  18797. gt: ">",
  18798. LT: "<",
  18799. lt: "<",
  18800. "ac;": "∾",
  18801. "af;": "⁡",
  18802. AMP: "&",
  18803. amp: "&",
  18804. "ap;": "≈",
  18805. "DD;": "ⅅ",
  18806. "dd;": "ⅆ",
  18807. deg: "°",
  18808. "ee;": "ⅇ",
  18809. "eg;": "⪚",
  18810. "el;": "⪙",
  18811. ETH: "Ð",
  18812. eth: "ð",
  18813. "gE;": "≧",
  18814. "ge;": "≥",
  18815. "Gg;": "⋙",
  18816. "gg;": "≫",
  18817. "gl;": "≷",
  18818. "GT;": ">",
  18819. "Gt;": "≫",
  18820. "gt;": ">",
  18821. "ic;": "⁣",
  18822. "ii;": "ⅈ",
  18823. "Im;": "ℑ",
  18824. "in;": "∈",
  18825. "it;": "⁢",
  18826. "lE;": "≦",
  18827. "le;": "≤",
  18828. "lg;": "≶",
  18829. "Ll;": "⋘",
  18830. "ll;": "≪",
  18831. "LT;": "<",
  18832. "Lt;": "≪",
  18833. "lt;": "<",
  18834. "mp;": "∓",
  18835. "Mu;": "Μ",
  18836. "mu;": "μ",
  18837. "ne;": "≠",
  18838. "ni;": "∋",
  18839. not: "¬",
  18840. "Nu;": "Ν",
  18841. "nu;": "ν",
  18842. "Or;": "⩔",
  18843. "or;": "∨",
  18844. "oS;": "Ⓢ",
  18845. "Pi;": "Π",
  18846. "pi;": "π",
  18847. "pm;": "±",
  18848. "Pr;": "⪻",
  18849. "pr;": "≺",
  18850. "Re;": "ℜ",
  18851. REG: "®",
  18852. reg: "®",
  18853. "rx;": "℞",
  18854. "Sc;": "⪼",
  18855. "sc;": "≻",
  18856. shy: "­",
  18857. uml: "¨",
  18858. "wp;": "℘",
  18859. "wr;": "≀",
  18860. "Xi;": "Ξ",
  18861. "xi;": "ξ",
  18862. yen: "¥",
  18863. "acd;": "∿",
  18864. "acE;": "∾̳",
  18865. "Acy;": "А",
  18866. "acy;": "а",
  18867. "Afr;": "𝔄",
  18868. "afr;": "𝔞",
  18869. "AMP;": "&",
  18870. "amp;": "&",
  18871. "And;": "⩓",
  18872. "and;": "∧",
  18873. "ang;": "∠",
  18874. "apE;": "⩰",
  18875. "ape;": "≊",
  18876. "ast;": "*",
  18877. Auml: "Ä",
  18878. auml: "ä",
  18879. "Bcy;": "Б",
  18880. "bcy;": "б",
  18881. "Bfr;": "𝔅",
  18882. "bfr;": "𝔟",
  18883. "bne;": "=⃥",
  18884. "bot;": "⊥",
  18885. "Cap;": "⋒",
  18886. "cap;": "∩",
  18887. cent: "¢",
  18888. "Cfr;": "ℭ",
  18889. "cfr;": "𝔠",
  18890. "Chi;": "Χ",
  18891. "chi;": "χ",
  18892. "cir;": "○",
  18893. COPY: "©",
  18894. copy: "©",
  18895. "Cup;": "⋓",
  18896. "cup;": "∪",
  18897. "Dcy;": "Д",
  18898. "dcy;": "д",
  18899. "deg;": "°",
  18900. "Del;": "∇",
  18901. "Dfr;": "𝔇",
  18902. "dfr;": "𝔡",
  18903. "die;": "¨",
  18904. "div;": "÷",
  18905. "Dot;": "¨",
  18906. "dot;": "˙",
  18907. "Ecy;": "Э",
  18908. "ecy;": "э",
  18909. "Efr;": "𝔈",
  18910. "efr;": "𝔢",
  18911. "egs;": "⪖",
  18912. "ell;": "ℓ",
  18913. "els;": "⪕",
  18914. "ENG;": "Ŋ",
  18915. "eng;": "ŋ",
  18916. "Eta;": "Η",
  18917. "eta;": "η",
  18918. "ETH;": "Ð",
  18919. "eth;": "ð",
  18920. Euml: "Ë",
  18921. euml: "ë",
  18922. "Fcy;": "Ф",
  18923. "fcy;": "ф",
  18924. "Ffr;": "𝔉",
  18925. "ffr;": "𝔣",
  18926. "gap;": "⪆",
  18927. "Gcy;": "Г",
  18928. "gcy;": "г",
  18929. "gEl;": "⪌",
  18930. "gel;": "⋛",
  18931. "geq;": "≥",
  18932. "ges;": "⩾",
  18933. "Gfr;": "𝔊",
  18934. "gfr;": "𝔤",
  18935. "ggg;": "⋙",
  18936. "gla;": "⪥",
  18937. "glE;": "⪒",
  18938. "glj;": "⪤",
  18939. "gnE;": "≩",
  18940. "gne;": "⪈",
  18941. "Hat;": "^",
  18942. "Hfr;": "ℌ",
  18943. "hfr;": "𝔥",
  18944. "Icy;": "И",
  18945. "icy;": "и",
  18946. "iff;": "⇔",
  18947. "Ifr;": "ℑ",
  18948. "ifr;": "𝔦",
  18949. "Int;": "∬",
  18950. "int;": "∫",
  18951. Iuml: "Ï",
  18952. iuml: "ï",
  18953. "Jcy;": "Й",
  18954. "jcy;": "й",
  18955. "Jfr;": "𝔍",
  18956. "jfr;": "𝔧",
  18957. "Kcy;": "К",
  18958. "kcy;": "к",
  18959. "Kfr;": "𝔎",
  18960. "kfr;": "𝔨",
  18961. "lap;": "⪅",
  18962. "lat;": "⪫",
  18963. "Lcy;": "Л",
  18964. "lcy;": "л",
  18965. "lEg;": "⪋",
  18966. "leg;": "⋚",
  18967. "leq;": "≤",
  18968. "les;": "⩽",
  18969. "Lfr;": "𝔏",
  18970. "lfr;": "𝔩",
  18971. "lgE;": "⪑",
  18972. "lnE;": "≨",
  18973. "lne;": "⪇",
  18974. "loz;": "◊",
  18975. "lrm;": "‎",
  18976. "Lsh;": "↰",
  18977. "lsh;": "↰",
  18978. macr: "¯",
  18979. "Map;": "⤅",
  18980. "map;": "↦",
  18981. "Mcy;": "М",
  18982. "mcy;": "м",
  18983. "Mfr;": "𝔐",
  18984. "mfr;": "𝔪",
  18985. "mho;": "℧",
  18986. "mid;": "∣",
  18987. "nap;": "≉",
  18988. nbsp: " ",
  18989. "Ncy;": "Н",
  18990. "ncy;": "н",
  18991. "Nfr;": "𝔑",
  18992. "nfr;": "𝔫",
  18993. "ngE;": "≧̸",
  18994. "nge;": "≱",
  18995. "nGg;": "⋙̸",
  18996. "nGt;": "≫⃒",
  18997. "ngt;": "≯",
  18998. "nis;": "⋼",
  18999. "niv;": "∋",
  19000. "nlE;": "≦̸",
  19001. "nle;": "≰",
  19002. "nLl;": "⋘̸",
  19003. "nLt;": "≪⃒",
  19004. "nlt;": "≮",
  19005. "Not;": "⫬",
  19006. "not;": "¬",
  19007. "npr;": "⊀",
  19008. "nsc;": "⊁",
  19009. "num;": "#",
  19010. "Ocy;": "О",
  19011. "ocy;": "о",
  19012. "Ofr;": "𝔒",
  19013. "ofr;": "𝔬",
  19014. "ogt;": "⧁",
  19015. "ohm;": "Ω",
  19016. "olt;": "⧀",
  19017. "ord;": "⩝",
  19018. ordf: "ª",
  19019. ordm: "º",
  19020. "orv;": "⩛",
  19021. Ouml: "Ö",
  19022. ouml: "ö",
  19023. "par;": "∥",
  19024. para: "¶",
  19025. "Pcy;": "П",
  19026. "pcy;": "п",
  19027. "Pfr;": "𝔓",
  19028. "pfr;": "𝔭",
  19029. "Phi;": "Φ",
  19030. "phi;": "φ",
  19031. "piv;": "ϖ",
  19032. "prE;": "⪳",
  19033. "pre;": "⪯",
  19034. "Psi;": "Ψ",
  19035. "psi;": "ψ",
  19036. "Qfr;": "𝔔",
  19037. "qfr;": "𝔮",
  19038. QUOT: "\"",
  19039. quot: "\"",
  19040. "Rcy;": "Р",
  19041. "rcy;": "р",
  19042. "REG;": "®",
  19043. "reg;": "®",
  19044. "Rfr;": "ℜ",
  19045. "rfr;": "𝔯",
  19046. "Rho;": "Ρ",
  19047. "rho;": "ρ",
  19048. "rlm;": "‏",
  19049. "Rsh;": "↱",
  19050. "rsh;": "↱",
  19051. "scE;": "⪴",
  19052. "sce;": "⪰",
  19053. "Scy;": "С",
  19054. "scy;": "с",
  19055. sect: "§",
  19056. "Sfr;": "𝔖",
  19057. "sfr;": "𝔰",
  19058. "shy;": "­",
  19059. "sim;": "∼",
  19060. "smt;": "⪪",
  19061. "sol;": "/",
  19062. "squ;": "□",
  19063. "Sub;": "⋐",
  19064. "sub;": "⊂",
  19065. "Sum;": "∑",
  19066. "sum;": "∑",
  19067. "Sup;": "⋑",
  19068. "sup;": "⊃",
  19069. sup1: "¹",
  19070. sup2: "²",
  19071. sup3: "³",
  19072. "Tab;": "\t",
  19073. "Tau;": "Τ",
  19074. "tau;": "τ",
  19075. "Tcy;": "Т",
  19076. "tcy;": "т",
  19077. "Tfr;": "𝔗",
  19078. "tfr;": "𝔱",
  19079. "top;": "⊤",
  19080. "Ucy;": "У",
  19081. "ucy;": "у",
  19082. "Ufr;": "𝔘",
  19083. "ufr;": "𝔲",
  19084. "uml;": "¨",
  19085. Uuml: "Ü",
  19086. uuml: "ü",
  19087. "Vcy;": "В",
  19088. "vcy;": "в",
  19089. "Vee;": "⋁",
  19090. "vee;": "∨",
  19091. "Vfr;": "𝔙",
  19092. "vfr;": "𝔳",
  19093. "Wfr;": "𝔚",
  19094. "wfr;": "𝔴",
  19095. "Xfr;": "𝔛",
  19096. "xfr;": "𝔵",
  19097. "Ycy;": "Ы",
  19098. "ycy;": "ы",
  19099. "yen;": "¥",
  19100. "Yfr;": "𝔜",
  19101. "yfr;": "𝔶",
  19102. yuml: "ÿ",
  19103. "Zcy;": "З",
  19104. "zcy;": "з",
  19105. "Zfr;": "ℨ",
  19106. "zfr;": "𝔷",
  19107. "zwj;": "‍",
  19108. Acirc: "Â",
  19109. acirc: "â",
  19110. acute: "´",
  19111. AElig: "Æ",
  19112. aelig: "æ",
  19113. "andd;": "⩜",
  19114. "andv;": "⩚",
  19115. "ange;": "⦤",
  19116. "Aopf;": "𝔸",
  19117. "aopf;": "𝕒",
  19118. "apid;": "≋",
  19119. "apos;": "'",
  19120. Aring: "Å",
  19121. aring: "å",
  19122. "Ascr;": "𝒜",
  19123. "ascr;": "𝒶",
  19124. "Auml;": "Ä",
  19125. "auml;": "ä",
  19126. "Barv;": "⫧",
  19127. "bbrk;": "⎵",
  19128. "Beta;": "Β",
  19129. "beta;": "β",
  19130. "beth;": "ℶ",
  19131. "bNot;": "⫭",
  19132. "bnot;": "⌐",
  19133. "Bopf;": "𝔹",
  19134. "bopf;": "𝕓",
  19135. "boxH;": "═",
  19136. "boxh;": "─",
  19137. "boxV;": "║",
  19138. "boxv;": "│",
  19139. "Bscr;": "ℬ",
  19140. "bscr;": "𝒷",
  19141. "bsim;": "∽",
  19142. "bsol;": "\\",
  19143. "bull;": "•",
  19144. "bump;": "≎",
  19145. "caps;": "∩︀",
  19146. "Cdot;": "Ċ",
  19147. "cdot;": "ċ",
  19148. cedil: "¸",
  19149. "cent;": "¢",
  19150. "CHcy;": "Ч",
  19151. "chcy;": "ч",
  19152. "circ;": "ˆ",
  19153. "cirE;": "⧃",
  19154. "cire;": "≗",
  19155. "comp;": "∁",
  19156. "cong;": "≅",
  19157. "Copf;": "ℂ",
  19158. "copf;": "𝕔",
  19159. "COPY;": "©",
  19160. "copy;": "©",
  19161. "Cscr;": "𝒞",
  19162. "cscr;": "𝒸",
  19163. "csub;": "⫏",
  19164. "csup;": "⫐",
  19165. "cups;": "∪︀",
  19166. "Darr;": "↡",
  19167. "dArr;": "⇓",
  19168. "darr;": "↓",
  19169. "dash;": "‐",
  19170. "dHar;": "⥥",
  19171. "diam;": "⋄",
  19172. "DJcy;": "Ђ",
  19173. "djcy;": "ђ",
  19174. "Dopf;": "𝔻",
  19175. "dopf;": "𝕕",
  19176. "Dscr;": "𝒟",
  19177. "dscr;": "𝒹",
  19178. "DScy;": "Ѕ",
  19179. "dscy;": "ѕ",
  19180. "dsol;": "⧶",
  19181. "dtri;": "▿",
  19182. "DZcy;": "Џ",
  19183. "dzcy;": "џ",
  19184. "ecir;": "≖",
  19185. Ecirc: "Ê",
  19186. ecirc: "ê",
  19187. "Edot;": "Ė",
  19188. "eDot;": "≑",
  19189. "edot;": "ė",
  19190. "emsp;": " ",
  19191. "ensp;": " ",
  19192. "Eopf;": "𝔼",
  19193. "eopf;": "𝕖",
  19194. "epar;": "⋕",
  19195. "epsi;": "ε",
  19196. "Escr;": "ℰ",
  19197. "escr;": "ℯ",
  19198. "Esim;": "⩳",
  19199. "esim;": "≂",
  19200. "Euml;": "Ë",
  19201. "euml;": "ë",
  19202. "euro;": "€",
  19203. "excl;": "!",
  19204. "flat;": "♭",
  19205. "fnof;": "ƒ",
  19206. "Fopf;": "𝔽",
  19207. "fopf;": "𝕗",
  19208. "fork;": "⋔",
  19209. "Fscr;": "ℱ",
  19210. "fscr;": "𝒻",
  19211. "Gdot;": "Ġ",
  19212. "gdot;": "ġ",
  19213. "geqq;": "≧",
  19214. "gesl;": "⋛︀",
  19215. "GJcy;": "Ѓ",
  19216. "gjcy;": "ѓ",
  19217. "gnap;": "⪊",
  19218. "gneq;": "⪈",
  19219. "Gopf;": "𝔾",
  19220. "gopf;": "𝕘",
  19221. "Gscr;": "𝒢",
  19222. "gscr;": "ℊ",
  19223. "gsim;": "≳",
  19224. "gtcc;": "⪧",
  19225. "gvnE;": "≩︀",
  19226. "half;": "½",
  19227. "hArr;": "⇔",
  19228. "harr;": "↔",
  19229. "hbar;": "ℏ",
  19230. "Hopf;": "ℍ",
  19231. "hopf;": "𝕙",
  19232. "Hscr;": "ℋ",
  19233. "hscr;": "𝒽",
  19234. Icirc: "Î",
  19235. icirc: "î",
  19236. "Idot;": "İ",
  19237. "IEcy;": "Е",
  19238. "iecy;": "е",
  19239. iexcl: "¡",
  19240. "imof;": "⊷",
  19241. "IOcy;": "Ё",
  19242. "iocy;": "ё",
  19243. "Iopf;": "𝕀",
  19244. "iopf;": "𝕚",
  19245. "Iota;": "Ι",
  19246. "iota;": "ι",
  19247. "Iscr;": "ℐ",
  19248. "iscr;": "𝒾",
  19249. "isin;": "∈",
  19250. "Iuml;": "Ï",
  19251. "iuml;": "ï",
  19252. "Jopf;": "𝕁",
  19253. "jopf;": "𝕛",
  19254. "Jscr;": "𝒥",
  19255. "jscr;": "𝒿",
  19256. "KHcy;": "Х",
  19257. "khcy;": "х",
  19258. "KJcy;": "Ќ",
  19259. "kjcy;": "ќ",
  19260. "Kopf;": "𝕂",
  19261. "kopf;": "𝕜",
  19262. "Kscr;": "𝒦",
  19263. "kscr;": "𝓀",
  19264. "Lang;": "⟪",
  19265. "lang;": "⟨",
  19266. laquo: "«",
  19267. "Larr;": "↞",
  19268. "lArr;": "⇐",
  19269. "larr;": "←",
  19270. "late;": "⪭",
  19271. "lcub;": "{",
  19272. "ldca;": "⤶",
  19273. "ldsh;": "↲",
  19274. "leqq;": "≦",
  19275. "lesg;": "⋚︀",
  19276. "lHar;": "⥢",
  19277. "LJcy;": "Љ",
  19278. "ljcy;": "љ",
  19279. "lnap;": "⪉",
  19280. "lneq;": "⪇",
  19281. "Lopf;": "𝕃",
  19282. "lopf;": "𝕝",
  19283. "lozf;": "⧫",
  19284. "lpar;": "(",
  19285. "Lscr;": "ℒ",
  19286. "lscr;": "𝓁",
  19287. "lsim;": "≲",
  19288. "lsqb;": "[",
  19289. "ltcc;": "⪦",
  19290. "ltri;": "◃",
  19291. "lvnE;": "≨︀",
  19292. "macr;": "¯",
  19293. "male;": "♂",
  19294. "malt;": "✠",
  19295. micro: "µ",
  19296. "mlcp;": "⫛",
  19297. "mldr;": "…",
  19298. "Mopf;": "𝕄",
  19299. "mopf;": "𝕞",
  19300. "Mscr;": "ℳ",
  19301. "mscr;": "𝓂",
  19302. "nang;": "∠⃒",
  19303. "napE;": "⩰̸",
  19304. "nbsp;": " ",
  19305. "ncap;": "⩃",
  19306. "ncup;": "⩂",
  19307. "ngeq;": "≱",
  19308. "nges;": "⩾̸",
  19309. "ngtr;": "≯",
  19310. "nGtv;": "≫̸",
  19311. "nisd;": "⋺",
  19312. "NJcy;": "Њ",
  19313. "njcy;": "њ",
  19314. "nldr;": "‥",
  19315. "nleq;": "≰",
  19316. "nles;": "⩽̸",
  19317. "nLtv;": "≪̸",
  19318. "nmid;": "∤",
  19319. "Nopf;": "ℕ",
  19320. "nopf;": "𝕟",
  19321. "npar;": "∦",
  19322. "npre;": "⪯̸",
  19323. "nsce;": "⪰̸",
  19324. "Nscr;": "𝒩",
  19325. "nscr;": "𝓃",
  19326. "nsim;": "≁",
  19327. "nsub;": "⊄",
  19328. "nsup;": "⊅",
  19329. "ntgl;": "≹",
  19330. "ntlg;": "≸",
  19331. "nvap;": "≍⃒",
  19332. "nvge;": "≥⃒",
  19333. "nvgt;": ">⃒",
  19334. "nvle;": "≤⃒",
  19335. "nvlt;": "<⃒",
  19336. "oast;": "⊛",
  19337. "ocir;": "⊚",
  19338. Ocirc: "Ô",
  19339. ocirc: "ô",
  19340. "odiv;": "⨸",
  19341. "odot;": "⊙",
  19342. "ogon;": "˛",
  19343. "oint;": "∮",
  19344. "omid;": "⦶",
  19345. "Oopf;": "𝕆",
  19346. "oopf;": "𝕠",
  19347. "opar;": "⦷",
  19348. "ordf;": "ª",
  19349. "ordm;": "º",
  19350. "oror;": "⩖",
  19351. "Oscr;": "𝒪",
  19352. "oscr;": "ℴ",
  19353. "osol;": "⊘",
  19354. "Ouml;": "Ö",
  19355. "ouml;": "ö",
  19356. "para;": "¶",
  19357. "part;": "∂",
  19358. "perp;": "⊥",
  19359. "phiv;": "ϕ",
  19360. "plus;": "+",
  19361. "Popf;": "ℙ",
  19362. "popf;": "𝕡",
  19363. pound: "£",
  19364. "prap;": "⪷",
  19365. "prec;": "≺",
  19366. "prnE;": "⪵",
  19367. "prod;": "∏",
  19368. "prop;": "∝",
  19369. "Pscr;": "𝒫",
  19370. "pscr;": "𝓅",
  19371. "qint;": "⨌",
  19372. "Qopf;": "ℚ",
  19373. "qopf;": "𝕢",
  19374. "Qscr;": "𝒬",
  19375. "qscr;": "𝓆",
  19376. "QUOT;": "\"",
  19377. "quot;": "\"",
  19378. "race;": "∽̱",
  19379. "Rang;": "⟫",
  19380. "rang;": "⟩",
  19381. raquo: "»",
  19382. "Rarr;": "↠",
  19383. "rArr;": "⇒",
  19384. "rarr;": "→",
  19385. "rcub;": "}",
  19386. "rdca;": "⤷",
  19387. "rdsh;": "↳",
  19388. "real;": "ℜ",
  19389. "rect;": "▭",
  19390. "rHar;": "⥤",
  19391. "rhov;": "ϱ",
  19392. "ring;": "˚",
  19393. "Ropf;": "ℝ",
  19394. "ropf;": "𝕣",
  19395. "rpar;": ")",
  19396. "Rscr;": "ℛ",
  19397. "rscr;": "𝓇",
  19398. "rsqb;": "]",
  19399. "rtri;": "▹",
  19400. "scap;": "⪸",
  19401. "scnE;": "⪶",
  19402. "sdot;": "⋅",
  19403. "sect;": "§",
  19404. "semi;": ";",
  19405. "sext;": "✶",
  19406. "SHcy;": "Ш",
  19407. "shcy;": "ш",
  19408. "sime;": "≃",
  19409. "simg;": "⪞",
  19410. "siml;": "⪝",
  19411. "smid;": "∣",
  19412. "smte;": "⪬",
  19413. "solb;": "⧄",
  19414. "Sopf;": "𝕊",
  19415. "sopf;": "𝕤",
  19416. "spar;": "∥",
  19417. "Sqrt;": "√",
  19418. "squf;": "▪",
  19419. "Sscr;": "𝒮",
  19420. "sscr;": "𝓈",
  19421. "Star;": "⋆",
  19422. "star;": "☆",
  19423. "subE;": "⫅",
  19424. "sube;": "⊆",
  19425. "succ;": "≻",
  19426. "sung;": "♪",
  19427. "sup1;": "¹",
  19428. "sup2;": "²",
  19429. "sup3;": "³",
  19430. "supE;": "⫆",
  19431. "supe;": "⊇",
  19432. szlig: "ß",
  19433. "tbrk;": "⎴",
  19434. "tdot;": "⃛",
  19435. THORN: "Þ",
  19436. thorn: "þ",
  19437. times: "×",
  19438. "tint;": "∭",
  19439. "toea;": "⤨",
  19440. "Topf;": "𝕋",
  19441. "topf;": "𝕥",
  19442. "tosa;": "⤩",
  19443. "trie;": "≜",
  19444. "Tscr;": "𝒯",
  19445. "tscr;": "𝓉",
  19446. "TScy;": "Ц",
  19447. "tscy;": "ц",
  19448. "Uarr;": "↟",
  19449. "uArr;": "⇑",
  19450. "uarr;": "↑",
  19451. Ucirc: "Û",
  19452. ucirc: "û",
  19453. "uHar;": "⥣",
  19454. "Uopf;": "𝕌",
  19455. "uopf;": "𝕦",
  19456. "Upsi;": "ϒ",
  19457. "upsi;": "υ",
  19458. "Uscr;": "𝒰",
  19459. "uscr;": "𝓊",
  19460. "utri;": "▵",
  19461. "Uuml;": "Ü",
  19462. "uuml;": "ü",
  19463. "vArr;": "⇕",
  19464. "varr;": "↕",
  19465. "Vbar;": "⫫",
  19466. "vBar;": "⫨",
  19467. "Vert;": "‖",
  19468. "vert;": "|",
  19469. "Vopf;": "𝕍",
  19470. "vopf;": "𝕧",
  19471. "Vscr;": "𝒱",
  19472. "vscr;": "𝓋",
  19473. "Wopf;": "𝕎",
  19474. "wopf;": "𝕨",
  19475. "Wscr;": "𝒲",
  19476. "wscr;": "𝓌",
  19477. "xcap;": "⋂",
  19478. "xcup;": "⋃",
  19479. "xmap;": "⟼",
  19480. "xnis;": "⋻",
  19481. "Xopf;": "𝕏",
  19482. "xopf;": "𝕩",
  19483. "Xscr;": "𝒳",
  19484. "xscr;": "𝓍",
  19485. "xvee;": "⋁",
  19486. "YAcy;": "Я",
  19487. "yacy;": "я",
  19488. "YIcy;": "Ї",
  19489. "yicy;": "ї",
  19490. "Yopf;": "𝕐",
  19491. "yopf;": "𝕪",
  19492. "Yscr;": "𝒴",
  19493. "yscr;": "𝓎",
  19494. "YUcy;": "Ю",
  19495. "yucy;": "ю",
  19496. "Yuml;": "Ÿ",
  19497. "yuml;": "ÿ",
  19498. "Zdot;": "Ż",
  19499. "zdot;": "ż",
  19500. "Zeta;": "Ζ",
  19501. "zeta;": "ζ",
  19502. "ZHcy;": "Ж",
  19503. "zhcy;": "ж",
  19504. "Zopf;": "ℤ",
  19505. "zopf;": "𝕫",
  19506. "Zscr;": "𝒵",
  19507. "zscr;": "𝓏",
  19508. "zwnj;": "‌",
  19509. Aacute: "Á",
  19510. aacute: "á",
  19511. "Acirc;": "Â",
  19512. "acirc;": "â",
  19513. "acute;": "´",
  19514. "AElig;": "Æ",
  19515. "aelig;": "æ",
  19516. Agrave: "À",
  19517. agrave: "à",
  19518. "aleph;": "ℵ",
  19519. "Alpha;": "Α",
  19520. "alpha;": "α",
  19521. "Amacr;": "Ā",
  19522. "amacr;": "ā",
  19523. "amalg;": "⨿",
  19524. "angle;": "∠",
  19525. "angrt;": "∟",
  19526. "angst;": "Å",
  19527. "Aogon;": "Ą",
  19528. "aogon;": "ą",
  19529. "Aring;": "Å",
  19530. "aring;": "å",
  19531. "asymp;": "≈",
  19532. Atilde: "Ã",
  19533. atilde: "ã",
  19534. "awint;": "⨑",
  19535. "bcong;": "≌",
  19536. "bdquo;": "„",
  19537. "bepsi;": "϶",
  19538. "blank;": "␣",
  19539. "blk12;": "▒",
  19540. "blk14;": "░",
  19541. "blk34;": "▓",
  19542. "block;": "█",
  19543. "boxDL;": "╗",
  19544. "boxDl;": "╖",
  19545. "boxdL;": "╕",
  19546. "boxdl;": "┐",
  19547. "boxDR;": "╔",
  19548. "boxDr;": "╓",
  19549. "boxdR;": "╒",
  19550. "boxdr;": "┌",
  19551. "boxHD;": "╦",
  19552. "boxHd;": "╤",
  19553. "boxhD;": "╥",
  19554. "boxhd;": "┬",
  19555. "boxHU;": "╩",
  19556. "boxHu;": "╧",
  19557. "boxhU;": "╨",
  19558. "boxhu;": "┴",
  19559. "boxUL;": "╝",
  19560. "boxUl;": "╜",
  19561. "boxuL;": "╛",
  19562. "boxul;": "┘",
  19563. "boxUR;": "╚",
  19564. "boxUr;": "╙",
  19565. "boxuR;": "╘",
  19566. "boxur;": "└",
  19567. "boxVH;": "╬",
  19568. "boxVh;": "╫",
  19569. "boxvH;": "╪",
  19570. "boxvh;": "┼",
  19571. "boxVL;": "╣",
  19572. "boxVl;": "╢",
  19573. "boxvL;": "╡",
  19574. "boxvl;": "┤",
  19575. "boxVR;": "╠",
  19576. "boxVr;": "╟",
  19577. "boxvR;": "╞",
  19578. "boxvr;": "├",
  19579. "Breve;": "˘",
  19580. "breve;": "˘",
  19581. brvbar: "¦",
  19582. "bsemi;": "⁏",
  19583. "bsime;": "⋍",
  19584. "bsolb;": "⧅",
  19585. "bumpE;": "⪮",
  19586. "bumpe;": "≏",
  19587. "caret;": "⁁",
  19588. "caron;": "ˇ",
  19589. "ccaps;": "⩍",
  19590. Ccedil: "Ç",
  19591. ccedil: "ç",
  19592. "Ccirc;": "Ĉ",
  19593. "ccirc;": "ĉ",
  19594. "ccups;": "⩌",
  19595. "cedil;": "¸",
  19596. "check;": "✓",
  19597. "clubs;": "♣",
  19598. "Colon;": "∷",
  19599. "colon;": ":",
  19600. "comma;": ",",
  19601. "crarr;": "↵",
  19602. "Cross;": "⨯",
  19603. "cross;": "✗",
  19604. "csube;": "⫑",
  19605. "csupe;": "⫒",
  19606. "ctdot;": "⋯",
  19607. "cuepr;": "⋞",
  19608. "cuesc;": "⋟",
  19609. "cupor;": "⩅",
  19610. curren: "¤",
  19611. "cuvee;": "⋎",
  19612. "cuwed;": "⋏",
  19613. "cwint;": "∱",
  19614. "Dashv;": "⫤",
  19615. "dashv;": "⊣",
  19616. "dblac;": "˝",
  19617. "ddarr;": "⇊",
  19618. "Delta;": "Δ",
  19619. "delta;": "δ",
  19620. "dharl;": "⇃",
  19621. "dharr;": "⇂",
  19622. "diams;": "♦",
  19623. "disin;": "⋲",
  19624. divide: "÷",
  19625. "doteq;": "≐",
  19626. "dtdot;": "⋱",
  19627. "dtrif;": "▾",
  19628. "duarr;": "⇵",
  19629. "duhar;": "⥯",
  19630. Eacute: "É",
  19631. eacute: "é",
  19632. "Ecirc;": "Ê",
  19633. "ecirc;": "ê",
  19634. "eDDot;": "⩷",
  19635. "efDot;": "≒",
  19636. Egrave: "È",
  19637. egrave: "è",
  19638. "Emacr;": "Ē",
  19639. "emacr;": "ē",
  19640. "empty;": "∅",
  19641. "Eogon;": "Ę",
  19642. "eogon;": "ę",
  19643. "eplus;": "⩱",
  19644. "epsiv;": "ϵ",
  19645. "eqsim;": "≂",
  19646. "Equal;": "⩵",
  19647. "equiv;": "≡",
  19648. "erarr;": "⥱",
  19649. "erDot;": "≓",
  19650. "esdot;": "≐",
  19651. "exist;": "∃",
  19652. "fflig;": "ff",
  19653. "filig;": "fi",
  19654. "fjlig;": "fj",
  19655. "fllig;": "fl",
  19656. "fltns;": "▱",
  19657. "forkv;": "⫙",
  19658. frac12: "½",
  19659. frac14: "¼",
  19660. frac34: "¾",
  19661. "frasl;": "⁄",
  19662. "frown;": "⌢",
  19663. "Gamma;": "Γ",
  19664. "gamma;": "γ",
  19665. "Gcirc;": "Ĝ",
  19666. "gcirc;": "ĝ",
  19667. "gescc;": "⪩",
  19668. "gimel;": "ℷ",
  19669. "gneqq;": "≩",
  19670. "gnsim;": "⋧",
  19671. "grave;": "`",
  19672. "gsime;": "⪎",
  19673. "gsiml;": "⪐",
  19674. "gtcir;": "⩺",
  19675. "gtdot;": "⋗",
  19676. "Hacek;": "ˇ",
  19677. "harrw;": "↭",
  19678. "Hcirc;": "Ĥ",
  19679. "hcirc;": "ĥ",
  19680. "hoarr;": "⇿",
  19681. Iacute: "Í",
  19682. iacute: "í",
  19683. "Icirc;": "Î",
  19684. "icirc;": "î",
  19685. "iexcl;": "¡",
  19686. Igrave: "Ì",
  19687. igrave: "ì",
  19688. "iiint;": "∭",
  19689. "iiota;": "℩",
  19690. "IJlig;": "IJ",
  19691. "ijlig;": "ij",
  19692. "Imacr;": "Ī",
  19693. "imacr;": "ī",
  19694. "image;": "ℑ",
  19695. "imath;": "ı",
  19696. "imped;": "Ƶ",
  19697. "infin;": "∞",
  19698. "Iogon;": "Į",
  19699. "iogon;": "į",
  19700. "iprod;": "⨼",
  19701. iquest: "¿",
  19702. "isinE;": "⋹",
  19703. "isins;": "⋴",
  19704. "isinv;": "∈",
  19705. "Iukcy;": "І",
  19706. "iukcy;": "і",
  19707. "Jcirc;": "Ĵ",
  19708. "jcirc;": "ĵ",
  19709. "jmath;": "ȷ",
  19710. "Jukcy;": "Є",
  19711. "jukcy;": "є",
  19712. "Kappa;": "Κ",
  19713. "kappa;": "κ",
  19714. "lAarr;": "⇚",
  19715. "langd;": "⦑",
  19716. "laquo;": "«",
  19717. "larrb;": "⇤",
  19718. "lates;": "⪭︀",
  19719. "lBarr;": "⤎",
  19720. "lbarr;": "⤌",
  19721. "lbbrk;": "❲",
  19722. "lbrke;": "⦋",
  19723. "lceil;": "⌈",
  19724. "ldquo;": "“",
  19725. "lescc;": "⪨",
  19726. "lhard;": "↽",
  19727. "lharu;": "↼",
  19728. "lhblk;": "▄",
  19729. "llarr;": "⇇",
  19730. "lltri;": "◺",
  19731. "lneqq;": "≨",
  19732. "lnsim;": "⋦",
  19733. "loang;": "⟬",
  19734. "loarr;": "⇽",
  19735. "lobrk;": "⟦",
  19736. "lopar;": "⦅",
  19737. "lrarr;": "⇆",
  19738. "lrhar;": "⇋",
  19739. "lrtri;": "⊿",
  19740. "lsime;": "⪍",
  19741. "lsimg;": "⪏",
  19742. "lsquo;": "‘",
  19743. "ltcir;": "⩹",
  19744. "ltdot;": "⋖",
  19745. "ltrie;": "⊴",
  19746. "ltrif;": "◂",
  19747. "mdash;": "—",
  19748. "mDDot;": "∺",
  19749. "micro;": "µ",
  19750. middot: "·",
  19751. "minus;": "−",
  19752. "mumap;": "⊸",
  19753. "nabla;": "∇",
  19754. "napid;": "≋̸",
  19755. "napos;": "ʼn",
  19756. "natur;": "♮",
  19757. "nbump;": "≎̸",
  19758. "ncong;": "≇",
  19759. "ndash;": "–",
  19760. "neArr;": "⇗",
  19761. "nearr;": "↗",
  19762. "nedot;": "≐̸",
  19763. "nesim;": "≂̸",
  19764. "ngeqq;": "≧̸",
  19765. "ngsim;": "≵",
  19766. "nhArr;": "⇎",
  19767. "nharr;": "↮",
  19768. "nhpar;": "⫲",
  19769. "nlArr;": "⇍",
  19770. "nlarr;": "↚",
  19771. "nleqq;": "≦̸",
  19772. "nless;": "≮",
  19773. "nlsim;": "≴",
  19774. "nltri;": "⋪",
  19775. "notin;": "∉",
  19776. "notni;": "∌",
  19777. "npart;": "∂̸",
  19778. "nprec;": "⊀",
  19779. "nrArr;": "⇏",
  19780. "nrarr;": "↛",
  19781. "nrtri;": "⋫",
  19782. "nsime;": "≄",
  19783. "nsmid;": "∤",
  19784. "nspar;": "∦",
  19785. "nsubE;": "⫅̸",
  19786. "nsube;": "⊈",
  19787. "nsucc;": "⊁",
  19788. "nsupE;": "⫆̸",
  19789. "nsupe;": "⊉",
  19790. Ntilde: "Ñ",
  19791. ntilde: "ñ",
  19792. "numsp;": " ",
  19793. "nvsim;": "∼⃒",
  19794. "nwArr;": "⇖",
  19795. "nwarr;": "↖",
  19796. Oacute: "Ó",
  19797. oacute: "ó",
  19798. "Ocirc;": "Ô",
  19799. "ocirc;": "ô",
  19800. "odash;": "⊝",
  19801. "OElig;": "Œ",
  19802. "oelig;": "œ",
  19803. "ofcir;": "⦿",
  19804. Ograve: "Ò",
  19805. ograve: "ò",
  19806. "ohbar;": "⦵",
  19807. "olarr;": "↺",
  19808. "olcir;": "⦾",
  19809. "oline;": "‾",
  19810. "Omacr;": "Ō",
  19811. "omacr;": "ō",
  19812. "Omega;": "Ω",
  19813. "omega;": "ω",
  19814. "operp;": "⦹",
  19815. "oplus;": "⊕",
  19816. "orarr;": "↻",
  19817. "order;": "ℴ",
  19818. Oslash: "Ø",
  19819. oslash: "ø",
  19820. Otilde: "Õ",
  19821. otilde: "õ",
  19822. "ovbar;": "⌽",
  19823. "parsl;": "⫽",
  19824. "phone;": "☎",
  19825. "plusb;": "⊞",
  19826. "pluse;": "⩲",
  19827. plusmn: "±",
  19828. "pound;": "£",
  19829. "prcue;": "≼",
  19830. "Prime;": "″",
  19831. "prime;": "′",
  19832. "prnap;": "⪹",
  19833. "prsim;": "≾",
  19834. "quest;": "?",
  19835. "rAarr;": "⇛",
  19836. "radic;": "√",
  19837. "rangd;": "⦒",
  19838. "range;": "⦥",
  19839. "raquo;": "»",
  19840. "rarrb;": "⇥",
  19841. "rarrc;": "⤳",
  19842. "rarrw;": "↝",
  19843. "ratio;": "∶",
  19844. "RBarr;": "⤐",
  19845. "rBarr;": "⤏",
  19846. "rbarr;": "⤍",
  19847. "rbbrk;": "❳",
  19848. "rbrke;": "⦌",
  19849. "rceil;": "⌉",
  19850. "rdquo;": "”",
  19851. "reals;": "ℝ",
  19852. "rhard;": "⇁",
  19853. "rharu;": "⇀",
  19854. "rlarr;": "⇄",
  19855. "rlhar;": "⇌",
  19856. "rnmid;": "⫮",
  19857. "roang;": "⟭",
  19858. "roarr;": "⇾",
  19859. "robrk;": "⟧",
  19860. "ropar;": "⦆",
  19861. "rrarr;": "⇉",
  19862. "rsquo;": "’",
  19863. "rtrie;": "⊵",
  19864. "rtrif;": "▸",
  19865. "sbquo;": "‚",
  19866. "sccue;": "≽",
  19867. "Scirc;": "Ŝ",
  19868. "scirc;": "ŝ",
  19869. "scnap;": "⪺",
  19870. "scsim;": "≿",
  19871. "sdotb;": "⊡",
  19872. "sdote;": "⩦",
  19873. "seArr;": "⇘",
  19874. "searr;": "↘",
  19875. "setmn;": "∖",
  19876. "sharp;": "♯",
  19877. "Sigma;": "Σ",
  19878. "sigma;": "σ",
  19879. "simeq;": "≃",
  19880. "simgE;": "⪠",
  19881. "simlE;": "⪟",
  19882. "simne;": "≆",
  19883. "slarr;": "←",
  19884. "smile;": "⌣",
  19885. "smtes;": "⪬︀",
  19886. "sqcap;": "⊓",
  19887. "sqcup;": "⊔",
  19888. "sqsub;": "⊏",
  19889. "sqsup;": "⊐",
  19890. "srarr;": "→",
  19891. "starf;": "★",
  19892. "strns;": "¯",
  19893. "subnE;": "⫋",
  19894. "subne;": "⊊",
  19895. "supnE;": "⫌",
  19896. "supne;": "⊋",
  19897. "swArr;": "⇙",
  19898. "swarr;": "↙",
  19899. "szlig;": "ß",
  19900. "Theta;": "Θ",
  19901. "theta;": "θ",
  19902. "thkap;": "≈",
  19903. "THORN;": "Þ",
  19904. "thorn;": "þ",
  19905. "Tilde;": "∼",
  19906. "tilde;": "˜",
  19907. "times;": "×",
  19908. "TRADE;": "™",
  19909. "trade;": "™",
  19910. "trisb;": "⧍",
  19911. "TSHcy;": "Ћ",
  19912. "tshcy;": "ћ",
  19913. "twixt;": "≬",
  19914. Uacute: "Ú",
  19915. uacute: "ú",
  19916. "Ubrcy;": "Ў",
  19917. "ubrcy;": "ў",
  19918. "Ucirc;": "Û",
  19919. "ucirc;": "û",
  19920. "udarr;": "⇅",
  19921. "udhar;": "⥮",
  19922. Ugrave: "Ù",
  19923. ugrave: "ù",
  19924. "uharl;": "↿",
  19925. "uharr;": "↾",
  19926. "uhblk;": "▀",
  19927. "ultri;": "◸",
  19928. "Umacr;": "Ū",
  19929. "umacr;": "ū",
  19930. "Union;": "⋃",
  19931. "Uogon;": "Ų",
  19932. "uogon;": "ų",
  19933. "uplus;": "⊎",
  19934. "upsih;": "ϒ",
  19935. "UpTee;": "⊥",
  19936. "Uring;": "Ů",
  19937. "uring;": "ů",
  19938. "urtri;": "◹",
  19939. "utdot;": "⋰",
  19940. "utrif;": "▴",
  19941. "uuarr;": "⇈",
  19942. "varpi;": "ϖ",
  19943. "vBarv;": "⫩",
  19944. "VDash;": "⊫",
  19945. "Vdash;": "⊩",
  19946. "vDash;": "⊨",
  19947. "vdash;": "⊢",
  19948. "veeeq;": "≚",
  19949. "vltri;": "⊲",
  19950. "vnsub;": "⊂⃒",
  19951. "vnsup;": "⊃⃒",
  19952. "vprop;": "∝",
  19953. "vrtri;": "⊳",
  19954. "Wcirc;": "Ŵ",
  19955. "wcirc;": "ŵ",
  19956. "Wedge;": "⋀",
  19957. "wedge;": "∧",
  19958. "xcirc;": "◯",
  19959. "xdtri;": "▽",
  19960. "xhArr;": "⟺",
  19961. "xharr;": "⟷",
  19962. "xlArr;": "⟸",
  19963. "xlarr;": "⟵",
  19964. "xodot;": "⨀",
  19965. "xrArr;": "⟹",
  19966. "xrarr;": "⟶",
  19967. "xutri;": "△",
  19968. Yacute: "Ý",
  19969. yacute: "ý",
  19970. "Ycirc;": "Ŷ",
  19971. "ycirc;": "ŷ",
  19972. "Aacute;": "Á",
  19973. "aacute;": "á",
  19974. "Abreve;": "Ă",
  19975. "abreve;": "ă",
  19976. "Agrave;": "À",
  19977. "agrave;": "à",
  19978. "andand;": "⩕",
  19979. "angmsd;": "∡",
  19980. "angsph;": "∢",
  19981. "apacir;": "⩯",
  19982. "approx;": "≈",
  19983. "Assign;": "≔",
  19984. "Atilde;": "Ã",
  19985. "atilde;": "ã",
  19986. "barvee;": "⊽",
  19987. "Barwed;": "⌆",
  19988. "barwed;": "⌅",
  19989. "becaus;": "∵",
  19990. "bernou;": "ℬ",
  19991. "bigcap;": "⋂",
  19992. "bigcup;": "⋃",
  19993. "bigvee;": "⋁",
  19994. "bkarow;": "⤍",
  19995. "bottom;": "⊥",
  19996. "bowtie;": "⋈",
  19997. "boxbox;": "⧉",
  19998. "bprime;": "‵",
  19999. "brvbar;": "¦",
  20000. "bullet;": "•",
  20001. "Bumpeq;": "≎",
  20002. "bumpeq;": "≏",
  20003. "Cacute;": "Ć",
  20004. "cacute;": "ć",
  20005. "capand;": "⩄",
  20006. "capcap;": "⩋",
  20007. "capcup;": "⩇",
  20008. "capdot;": "⩀",
  20009. "Ccaron;": "Č",
  20010. "ccaron;": "č",
  20011. "Ccedil;": "Ç",
  20012. "ccedil;": "ç",
  20013. "circeq;": "≗",
  20014. "cirmid;": "⫯",
  20015. "Colone;": "⩴",
  20016. "colone;": "≔",
  20017. "commat;": "@",
  20018. "compfn;": "∘",
  20019. "Conint;": "∯",
  20020. "conint;": "∮",
  20021. "coprod;": "∐",
  20022. "copysr;": "℗",
  20023. "cularr;": "↶",
  20024. "CupCap;": "≍",
  20025. "cupcap;": "⩆",
  20026. "cupcup;": "⩊",
  20027. "cupdot;": "⊍",
  20028. "curarr;": "↷",
  20029. "curren;": "¤",
  20030. "cylcty;": "⌭",
  20031. "Dagger;": "‡",
  20032. "dagger;": "†",
  20033. "daleth;": "ℸ",
  20034. "Dcaron;": "Ď",
  20035. "dcaron;": "ď",
  20036. "dfisht;": "⥿",
  20037. "divide;": "÷",
  20038. "divonx;": "⋇",
  20039. "dlcorn;": "⌞",
  20040. "dlcrop;": "⌍",
  20041. "dollar;": "$",
  20042. "DotDot;": "⃜",
  20043. "drcorn;": "⌟",
  20044. "drcrop;": "⌌",
  20045. "Dstrok;": "Đ",
  20046. "dstrok;": "đ",
  20047. "Eacute;": "É",
  20048. "eacute;": "é",
  20049. "easter;": "⩮",
  20050. "Ecaron;": "Ě",
  20051. "ecaron;": "ě",
  20052. "ecolon;": "≕",
  20053. "Egrave;": "È",
  20054. "egrave;": "è",
  20055. "egsdot;": "⪘",
  20056. "elsdot;": "⪗",
  20057. "emptyv;": "∅",
  20058. "emsp13;": " ",
  20059. "emsp14;": " ",
  20060. "eparsl;": "⧣",
  20061. "eqcirc;": "≖",
  20062. "equals;": "=",
  20063. "equest;": "≟",
  20064. "Exists;": "∃",
  20065. "female;": "♀",
  20066. "ffilig;": "ffi",
  20067. "ffllig;": "ffl",
  20068. "ForAll;": "∀",
  20069. "forall;": "∀",
  20070. "frac12;": "½",
  20071. "frac13;": "⅓",
  20072. "frac14;": "¼",
  20073. "frac15;": "⅕",
  20074. "frac16;": "⅙",
  20075. "frac18;": "⅛",
  20076. "frac23;": "⅔",
  20077. "frac25;": "⅖",
  20078. "frac34;": "¾",
  20079. "frac35;": "⅗",
  20080. "frac38;": "⅜",
  20081. "frac45;": "⅘",
  20082. "frac56;": "⅚",
  20083. "frac58;": "⅝",
  20084. "frac78;": "⅞",
  20085. "gacute;": "ǵ",
  20086. "Gammad;": "Ϝ",
  20087. "gammad;": "ϝ",
  20088. "Gbreve;": "Ğ",
  20089. "gbreve;": "ğ",
  20090. "Gcedil;": "Ģ",
  20091. "gesdot;": "⪀",
  20092. "gesles;": "⪔",
  20093. "gtlPar;": "⦕",
  20094. "gtrarr;": "⥸",
  20095. "gtrdot;": "⋗",
  20096. "gtrsim;": "≳",
  20097. "hairsp;": " ",
  20098. "hamilt;": "ℋ",
  20099. "HARDcy;": "Ъ",
  20100. "hardcy;": "ъ",
  20101. "hearts;": "♥",
  20102. "hellip;": "…",
  20103. "hercon;": "⊹",
  20104. "homtht;": "∻",
  20105. "horbar;": "―",
  20106. "hslash;": "ℏ",
  20107. "Hstrok;": "Ħ",
  20108. "hstrok;": "ħ",
  20109. "hybull;": "⁃",
  20110. "hyphen;": "‐",
  20111. "Iacute;": "Í",
  20112. "iacute;": "í",
  20113. "Igrave;": "Ì",
  20114. "igrave;": "ì",
  20115. "iiiint;": "⨌",
  20116. "iinfin;": "⧜",
  20117. "incare;": "℅",
  20118. "inodot;": "ı",
  20119. "intcal;": "⊺",
  20120. "iquest;": "¿",
  20121. "isinsv;": "⋳",
  20122. "Itilde;": "Ĩ",
  20123. "itilde;": "ĩ",
  20124. "Jsercy;": "Ј",
  20125. "jsercy;": "ј",
  20126. "kappav;": "ϰ",
  20127. "Kcedil;": "Ķ",
  20128. "kcedil;": "ķ",
  20129. "kgreen;": "ĸ",
  20130. "Lacute;": "Ĺ",
  20131. "lacute;": "ĺ",
  20132. "lagran;": "ℒ",
  20133. "Lambda;": "Λ",
  20134. "lambda;": "λ",
  20135. "langle;": "⟨",
  20136. "larrfs;": "⤝",
  20137. "larrhk;": "↩",
  20138. "larrlp;": "↫",
  20139. "larrpl;": "⤹",
  20140. "larrtl;": "↢",
  20141. "lAtail;": "⤛",
  20142. "latail;": "⤙",
  20143. "lbrace;": "{",
  20144. "lbrack;": "[",
  20145. "Lcaron;": "Ľ",
  20146. "lcaron;": "ľ",
  20147. "Lcedil;": "Ļ",
  20148. "lcedil;": "ļ",
  20149. "ldquor;": "„",
  20150. "lesdot;": "⩿",
  20151. "lesges;": "⪓",
  20152. "lfisht;": "⥼",
  20153. "lfloor;": "⌊",
  20154. "lharul;": "⥪",
  20155. "llhard;": "⥫",
  20156. "Lmidot;": "Ŀ",
  20157. "lmidot;": "ŀ",
  20158. "lmoust;": "⎰",
  20159. "loplus;": "⨭",
  20160. "lowast;": "∗",
  20161. "lowbar;": "_",
  20162. "lparlt;": "⦓",
  20163. "lrhard;": "⥭",
  20164. "lsaquo;": "‹",
  20165. "lsquor;": "‚",
  20166. "Lstrok;": "Ł",
  20167. "lstrok;": "ł",
  20168. "lthree;": "⋋",
  20169. "ltimes;": "⋉",
  20170. "ltlarr;": "⥶",
  20171. "ltrPar;": "⦖",
  20172. "mapsto;": "↦",
  20173. "marker;": "▮",
  20174. "mcomma;": "⨩",
  20175. "midast;": "*",
  20176. "midcir;": "⫰",
  20177. "middot;": "·",
  20178. "minusb;": "⊟",
  20179. "minusd;": "∸",
  20180. "mnplus;": "∓",
  20181. "models;": "⊧",
  20182. "mstpos;": "∾",
  20183. "Nacute;": "Ń",
  20184. "nacute;": "ń",
  20185. "nbumpe;": "≏̸",
  20186. "Ncaron;": "Ň",
  20187. "ncaron;": "ň",
  20188. "Ncedil;": "Ņ",
  20189. "ncedil;": "ņ",
  20190. "nearhk;": "⤤",
  20191. "nequiv;": "≢",
  20192. "nesear;": "⤨",
  20193. "nexist;": "∄",
  20194. "nltrie;": "⋬",
  20195. "notinE;": "⋹̸",
  20196. "nparsl;": "⫽⃥",
  20197. "nprcue;": "⋠",
  20198. "nrarrc;": "⤳̸",
  20199. "nrarrw;": "↝̸",
  20200. "nrtrie;": "⋭",
  20201. "nsccue;": "⋡",
  20202. "nsimeq;": "≄",
  20203. "Ntilde;": "Ñ",
  20204. "ntilde;": "ñ",
  20205. "numero;": "№",
  20206. "nVDash;": "⊯",
  20207. "nVdash;": "⊮",
  20208. "nvDash;": "⊭",
  20209. "nvdash;": "⊬",
  20210. "nvHarr;": "⤄",
  20211. "nvlArr;": "⤂",
  20212. "nvrArr;": "⤃",
  20213. "nwarhk;": "⤣",
  20214. "nwnear;": "⤧",
  20215. "Oacute;": "Ó",
  20216. "oacute;": "ó",
  20217. "Odblac;": "Ő",
  20218. "odblac;": "ő",
  20219. "odsold;": "⦼",
  20220. "Ograve;": "Ò",
  20221. "ograve;": "ò",
  20222. "ominus;": "⊖",
  20223. "origof;": "⊶",
  20224. "Oslash;": "Ø",
  20225. "oslash;": "ø",
  20226. "Otilde;": "Õ",
  20227. "otilde;": "õ",
  20228. "Otimes;": "⨷",
  20229. "otimes;": "⊗",
  20230. "parsim;": "⫳",
  20231. "percnt;": "%",
  20232. "period;": ".",
  20233. "permil;": "‰",
  20234. "phmmat;": "ℳ",
  20235. "planck;": "ℏ",
  20236. "plankv;": "ℏ",
  20237. "plusdo;": "∔",
  20238. "plusdu;": "⨥",
  20239. "plusmn;": "±",
  20240. "preceq;": "⪯",
  20241. "primes;": "ℙ",
  20242. "prnsim;": "⋨",
  20243. "propto;": "∝",
  20244. "prurel;": "⊰",
  20245. "puncsp;": " ",
  20246. "qprime;": "⁗",
  20247. "Racute;": "Ŕ",
  20248. "racute;": "ŕ",
  20249. "rangle;": "⟩",
  20250. "rarrap;": "⥵",
  20251. "rarrfs;": "⤞",
  20252. "rarrhk;": "↪",
  20253. "rarrlp;": "↬",
  20254. "rarrpl;": "⥅",
  20255. "Rarrtl;": "⤖",
  20256. "rarrtl;": "↣",
  20257. "rAtail;": "⤜",
  20258. "ratail;": "⤚",
  20259. "rbrace;": "}",
  20260. "rbrack;": "]",
  20261. "Rcaron;": "Ř",
  20262. "rcaron;": "ř",
  20263. "Rcedil;": "Ŗ",
  20264. "rcedil;": "ŗ",
  20265. "rdquor;": "”",
  20266. "rfisht;": "⥽",
  20267. "rfloor;": "⌋",
  20268. "rharul;": "⥬",
  20269. "rmoust;": "⎱",
  20270. "roplus;": "⨮",
  20271. "rpargt;": "⦔",
  20272. "rsaquo;": "›",
  20273. "rsquor;": "’",
  20274. "rthree;": "⋌",
  20275. "rtimes;": "⋊",
  20276. "Sacute;": "Ś",
  20277. "sacute;": "ś",
  20278. "Scaron;": "Š",
  20279. "scaron;": "š",
  20280. "Scedil;": "Ş",
  20281. "scedil;": "ş",
  20282. "scnsim;": "⋩",
  20283. "searhk;": "⤥",
  20284. "seswar;": "⤩",
  20285. "sfrown;": "⌢",
  20286. "SHCHcy;": "Щ",
  20287. "shchcy;": "щ",
  20288. "sigmaf;": "ς",
  20289. "sigmav;": "ς",
  20290. "simdot;": "⩪",
  20291. "smashp;": "⨳",
  20292. "SOFTcy;": "Ь",
  20293. "softcy;": "ь",
  20294. "solbar;": "⌿",
  20295. "spades;": "♠",
  20296. "sqcaps;": "⊓︀",
  20297. "sqcups;": "⊔︀",
  20298. "sqsube;": "⊑",
  20299. "sqsupe;": "⊒",
  20300. "Square;": "□",
  20301. "square;": "□",
  20302. "squarf;": "▪",
  20303. "ssetmn;": "∖",
  20304. "ssmile;": "⌣",
  20305. "sstarf;": "⋆",
  20306. "subdot;": "⪽",
  20307. "Subset;": "⋐",
  20308. "subset;": "⊂",
  20309. "subsim;": "⫇",
  20310. "subsub;": "⫕",
  20311. "subsup;": "⫓",
  20312. "succeq;": "⪰",
  20313. "supdot;": "⪾",
  20314. "Supset;": "⋑",
  20315. "supset;": "⊃",
  20316. "supsim;": "⫈",
  20317. "supsub;": "⫔",
  20318. "supsup;": "⫖",
  20319. "swarhk;": "⤦",
  20320. "swnwar;": "⤪",
  20321. "target;": "⌖",
  20322. "Tcaron;": "Ť",
  20323. "tcaron;": "ť",
  20324. "Tcedil;": "Ţ",
  20325. "tcedil;": "ţ",
  20326. "telrec;": "⌕",
  20327. "there4;": "∴",
  20328. "thetav;": "ϑ",
  20329. "thinsp;": " ",
  20330. "thksim;": "∼",
  20331. "timesb;": "⊠",
  20332. "timesd;": "⨰",
  20333. "topbot;": "⌶",
  20334. "topcir;": "⫱",
  20335. "tprime;": "‴",
  20336. "tridot;": "◬",
  20337. "Tstrok;": "Ŧ",
  20338. "tstrok;": "ŧ",
  20339. "Uacute;": "Ú",
  20340. "uacute;": "ú",
  20341. "Ubreve;": "Ŭ",
  20342. "ubreve;": "ŭ",
  20343. "Udblac;": "Ű",
  20344. "udblac;": "ű",
  20345. "ufisht;": "⥾",
  20346. "Ugrave;": "Ù",
  20347. "ugrave;": "ù",
  20348. "ulcorn;": "⌜",
  20349. "ulcrop;": "⌏",
  20350. "urcorn;": "⌝",
  20351. "urcrop;": "⌎",
  20352. "Utilde;": "Ũ",
  20353. "utilde;": "ũ",
  20354. "vangrt;": "⦜",
  20355. "varphi;": "ϕ",
  20356. "varrho;": "ϱ",
  20357. "Vdashl;": "⫦",
  20358. "veebar;": "⊻",
  20359. "vellip;": "⋮",
  20360. "Verbar;": "‖",
  20361. "verbar;": "|",
  20362. "vsubnE;": "⫋︀",
  20363. "vsubne;": "⊊︀",
  20364. "vsupnE;": "⫌︀",
  20365. "vsupne;": "⊋︀",
  20366. "Vvdash;": "⊪",
  20367. "wedbar;": "⩟",
  20368. "wedgeq;": "≙",
  20369. "weierp;": "℘",
  20370. "wreath;": "≀",
  20371. "xoplus;": "⨁",
  20372. "xotime;": "⨂",
  20373. "xsqcup;": "⨆",
  20374. "xuplus;": "⨄",
  20375. "xwedge;": "⋀",
  20376. "Yacute;": "Ý",
  20377. "yacute;": "ý",
  20378. "Zacute;": "Ź",
  20379. "zacute;": "ź",
  20380. "Zcaron;": "Ž",
  20381. "zcaron;": "ž",
  20382. "zeetrf;": "ℨ",
  20383. "alefsym;": "ℵ",
  20384. "angrtvb;": "⊾",
  20385. "angzarr;": "⍼",
  20386. "asympeq;": "≍",
  20387. "backsim;": "∽",
  20388. "Because;": "∵",
  20389. "because;": "∵",
  20390. "bemptyv;": "⦰",
  20391. "between;": "≬",
  20392. "bigcirc;": "◯",
  20393. "bigodot;": "⨀",
  20394. "bigstar;": "★",
  20395. "bnequiv;": "≡⃥",
  20396. "boxplus;": "⊞",
  20397. "Cayleys;": "ℭ",
  20398. "Cconint;": "∰",
  20399. "ccupssm;": "⩐",
  20400. "Cedilla;": "¸",
  20401. "cemptyv;": "⦲",
  20402. "cirscir;": "⧂",
  20403. "coloneq;": "≔",
  20404. "congdot;": "⩭",
  20405. "cudarrl;": "⤸",
  20406. "cudarrr;": "⤵",
  20407. "cularrp;": "⤽",
  20408. "curarrm;": "⤼",
  20409. "dbkarow;": "⤏",
  20410. "ddagger;": "‡",
  20411. "ddotseq;": "⩷",
  20412. "demptyv;": "⦱",
  20413. "Diamond;": "⋄",
  20414. "diamond;": "⋄",
  20415. "digamma;": "ϝ",
  20416. "dotplus;": "∔",
  20417. "DownTee;": "⊤",
  20418. "dwangle;": "⦦",
  20419. "Element;": "∈",
  20420. "Epsilon;": "Ε",
  20421. "epsilon;": "ε",
  20422. "eqcolon;": "≕",
  20423. "equivDD;": "⩸",
  20424. "gesdoto;": "⪂",
  20425. "gtquest;": "⩼",
  20426. "gtrless;": "≷",
  20427. "harrcir;": "⥈",
  20428. "Implies;": "⇒",
  20429. "intprod;": "⨼",
  20430. "isindot;": "⋵",
  20431. "larrbfs;": "⤟",
  20432. "larrsim;": "⥳",
  20433. "lbrksld;": "⦏",
  20434. "lbrkslu;": "⦍",
  20435. "ldrdhar;": "⥧",
  20436. "LeftTee;": "⊣",
  20437. "lesdoto;": "⪁",
  20438. "lessdot;": "⋖",
  20439. "lessgtr;": "≶",
  20440. "lesssim;": "≲",
  20441. "lotimes;": "⨴",
  20442. "lozenge;": "◊",
  20443. "ltquest;": "⩻",
  20444. "luruhar;": "⥦",
  20445. "maltese;": "✠",
  20446. "minusdu;": "⨪",
  20447. "napprox;": "≉",
  20448. "natural;": "♮",
  20449. "nearrow;": "↗",
  20450. "NewLine;": "\n",
  20451. "nexists;": "∄",
  20452. "NoBreak;": "⁠",
  20453. "notinva;": "∉",
  20454. "notinvb;": "⋷",
  20455. "notinvc;": "⋶",
  20456. "NotLess;": "≮",
  20457. "notniva;": "∌",
  20458. "notnivb;": "⋾",
  20459. "notnivc;": "⋽",
  20460. "npolint;": "⨔",
  20461. "npreceq;": "⪯̸",
  20462. "nsqsube;": "⋢",
  20463. "nsqsupe;": "⋣",
  20464. "nsubset;": "⊂⃒",
  20465. "nsucceq;": "⪰̸",
  20466. "nsupset;": "⊃⃒",
  20467. "nvinfin;": "⧞",
  20468. "nvltrie;": "⊴⃒",
  20469. "nvrtrie;": "⊵⃒",
  20470. "nwarrow;": "↖",
  20471. "olcross;": "⦻",
  20472. "Omicron;": "Ο",
  20473. "omicron;": "ο",
  20474. "orderof;": "ℴ",
  20475. "orslope;": "⩗",
  20476. "OverBar;": "‾",
  20477. "pertenk;": "‱",
  20478. "planckh;": "ℎ",
  20479. "pluscir;": "⨢",
  20480. "plussim;": "⨦",
  20481. "plustwo;": "⨧",
  20482. "precsim;": "≾",
  20483. "Product;": "∏",
  20484. "quatint;": "⨖",
  20485. "questeq;": "≟",
  20486. "rarrbfs;": "⤠",
  20487. "rarrsim;": "⥴",
  20488. "rbrksld;": "⦎",
  20489. "rbrkslu;": "⦐",
  20490. "rdldhar;": "⥩",
  20491. "realine;": "ℛ",
  20492. "rotimes;": "⨵",
  20493. "ruluhar;": "⥨",
  20494. "searrow;": "↘",
  20495. "simplus;": "⨤",
  20496. "simrarr;": "⥲",
  20497. "subedot;": "⫃",
  20498. "submult;": "⫁",
  20499. "subplus;": "⪿",
  20500. "subrarr;": "⥹",
  20501. "succsim;": "≿",
  20502. "supdsub;": "⫘",
  20503. "supedot;": "⫄",
  20504. "suphsol;": "⟉",
  20505. "suphsub;": "⫗",
  20506. "suplarr;": "⥻",
  20507. "supmult;": "⫂",
  20508. "supplus;": "⫀",
  20509. "swarrow;": "↙",
  20510. "topfork;": "⫚",
  20511. "triplus;": "⨹",
  20512. "tritime;": "⨻",
  20513. "UpArrow;": "↑",
  20514. "Uparrow;": "⇑",
  20515. "uparrow;": "↑",
  20516. "Upsilon;": "Υ",
  20517. "upsilon;": "υ",
  20518. "uwangle;": "⦧",
  20519. "vzigzag;": "⦚",
  20520. "zigrarr;": "⇝",
  20521. "andslope;": "⩘",
  20522. "angmsdaa;": "⦨",
  20523. "angmsdab;": "⦩",
  20524. "angmsdac;": "⦪",
  20525. "angmsdad;": "⦫",
  20526. "angmsdae;": "⦬",
  20527. "angmsdaf;": "⦭",
  20528. "angmsdag;": "⦮",
  20529. "angmsdah;": "⦯",
  20530. "angrtvbd;": "⦝",
  20531. "approxeq;": "≊",
  20532. "awconint;": "∳",
  20533. "backcong;": "≌",
  20534. "barwedge;": "⌅",
  20535. "bbrktbrk;": "⎶",
  20536. "bigoplus;": "⨁",
  20537. "bigsqcup;": "⨆",
  20538. "biguplus;": "⨄",
  20539. "bigwedge;": "⋀",
  20540. "boxminus;": "⊟",
  20541. "boxtimes;": "⊠",
  20542. "bsolhsub;": "⟈",
  20543. "capbrcup;": "⩉",
  20544. "circledR;": "®",
  20545. "circledS;": "Ⓢ",
  20546. "cirfnint;": "⨐",
  20547. "clubsuit;": "♣",
  20548. "cupbrcap;": "⩈",
  20549. "curlyvee;": "⋎",
  20550. "cwconint;": "∲",
  20551. "DDotrahd;": "⤑",
  20552. "doteqdot;": "≑",
  20553. "DotEqual;": "≐",
  20554. "dotminus;": "∸",
  20555. "drbkarow;": "⤐",
  20556. "dzigrarr;": "⟿",
  20557. "elinters;": "⏧",
  20558. "emptyset;": "∅",
  20559. "eqvparsl;": "⧥",
  20560. "fpartint;": "⨍",
  20561. "geqslant;": "⩾",
  20562. "gesdotol;": "⪄",
  20563. "gnapprox;": "⪊",
  20564. "hksearow;": "⤥",
  20565. "hkswarow;": "⤦",
  20566. "imagline;": "ℐ",
  20567. "imagpart;": "ℑ",
  20568. "infintie;": "⧝",
  20569. "integers;": "ℤ",
  20570. "Integral;": "∫",
  20571. "intercal;": "⊺",
  20572. "intlarhk;": "⨗",
  20573. "laemptyv;": "⦴",
  20574. "ldrushar;": "⥋",
  20575. "leqslant;": "⩽",
  20576. "lesdotor;": "⪃",
  20577. "LessLess;": "⪡",
  20578. "llcorner;": "⌞",
  20579. "lnapprox;": "⪉",
  20580. "lrcorner;": "⌟",
  20581. "lurdshar;": "⥊",
  20582. "mapstoup;": "↥",
  20583. "multimap;": "⊸",
  20584. "naturals;": "ℕ",
  20585. "ncongdot;": "⩭̸",
  20586. "NotEqual;": "≠",
  20587. "notindot;": "⋵̸",
  20588. "NotTilde;": "≁",
  20589. "otimesas;": "⨶",
  20590. "parallel;": "∥",
  20591. "PartialD;": "∂",
  20592. "plusacir;": "⨣",
  20593. "pointint;": "⨕",
  20594. "Precedes;": "≺",
  20595. "precneqq;": "⪵",
  20596. "precnsim;": "⋨",
  20597. "profalar;": "⌮",
  20598. "profline;": "⌒",
  20599. "profsurf;": "⌓",
  20600. "raemptyv;": "⦳",
  20601. "realpart;": "ℜ",
  20602. "RightTee;": "⊢",
  20603. "rppolint;": "⨒",
  20604. "rtriltri;": "⧎",
  20605. "scpolint;": "⨓",
  20606. "setminus;": "∖",
  20607. "shortmid;": "∣",
  20608. "smeparsl;": "⧤",
  20609. "sqsubset;": "⊏",
  20610. "sqsupset;": "⊐",
  20611. "subseteq;": "⊆",
  20612. "Succeeds;": "≻",
  20613. "succneqq;": "⪶",
  20614. "succnsim;": "⋩",
  20615. "SuchThat;": "∋",
  20616. "Superset;": "⊃",
  20617. "supseteq;": "⊇",
  20618. "thetasym;": "ϑ",
  20619. "thicksim;": "∼",
  20620. "timesbar;": "⨱",
  20621. "triangle;": "▵",
  20622. "triminus;": "⨺",
  20623. "trpezium;": "⏢",
  20624. "Uarrocir;": "⥉",
  20625. "ulcorner;": "⌜",
  20626. "UnderBar;": "_",
  20627. "urcorner;": "⌝",
  20628. "varkappa;": "ϰ",
  20629. "varsigma;": "ς",
  20630. "vartheta;": "ϑ",
  20631. "backprime;": "‵",
  20632. "backsimeq;": "⋍",
  20633. "Backslash;": "∖",
  20634. "bigotimes;": "⨂",
  20635. "CenterDot;": "·",
  20636. "centerdot;": "·",
  20637. "checkmark;": "✓",
  20638. "CircleDot;": "⊙",
  20639. "complexes;": "ℂ",
  20640. "Congruent;": "≡",
  20641. "Coproduct;": "∐",
  20642. "dotsquare;": "⊡",
  20643. "DoubleDot;": "¨",
  20644. "DownArrow;": "↓",
  20645. "Downarrow;": "⇓",
  20646. "downarrow;": "↓",
  20647. "DownBreve;": "̑",
  20648. "gtrapprox;": "⪆",
  20649. "gtreqless;": "⋛",
  20650. "gvertneqq;": "≩︀",
  20651. "heartsuit;": "♥",
  20652. "HumpEqual;": "≏",
  20653. "LeftArrow;": "←",
  20654. "Leftarrow;": "⇐",
  20655. "leftarrow;": "←",
  20656. "LeftFloor;": "⌊",
  20657. "lesseqgtr;": "⋚",
  20658. "LessTilde;": "≲",
  20659. "lvertneqq;": "≨︀",
  20660. "Mellintrf;": "ℳ",
  20661. "MinusPlus;": "∓",
  20662. "ngeqslant;": "⩾̸",
  20663. "nleqslant;": "⩽̸",
  20664. "NotCupCap;": "≭",
  20665. "NotExists;": "∄",
  20666. "NotSubset;": "⊂⃒",
  20667. "nparallel;": "∦",
  20668. "nshortmid;": "∤",
  20669. "nsubseteq;": "⊈",
  20670. "nsupseteq;": "⊉",
  20671. "OverBrace;": "⏞",
  20672. "pitchfork;": "⋔",
  20673. "PlusMinus;": "±",
  20674. "rationals;": "ℚ",
  20675. "spadesuit;": "♠",
  20676. "subseteqq;": "⫅",
  20677. "subsetneq;": "⊊",
  20678. "supseteqq;": "⫆",
  20679. "supsetneq;": "⊋",
  20680. "Therefore;": "∴",
  20681. "therefore;": "∴",
  20682. "ThinSpace;": " ",
  20683. "triangleq;": "≜",
  20684. "TripleDot;": "⃛",
  20685. "UnionPlus;": "⊎",
  20686. "varpropto;": "∝",
  20687. "Bernoullis;": "ℬ",
  20688. "circledast;": "⊛",
  20689. "CirclePlus;": "⊕",
  20690. "complement;": "∁",
  20691. "curlywedge;": "⋏",
  20692. "eqslantgtr;": "⪖",
  20693. "EqualTilde;": "≂",
  20694. "Fouriertrf;": "ℱ",
  20695. "gtreqqless;": "⪌",
  20696. "ImaginaryI;": "ⅈ",
  20697. "Laplacetrf;": "ℒ",
  20698. "LeftVector;": "↼",
  20699. "lessapprox;": "⪅",
  20700. "lesseqqgtr;": "⪋",
  20701. "Lleftarrow;": "⇚",
  20702. "lmoustache;": "⎰",
  20703. "longmapsto;": "⟼",
  20704. "mapstodown;": "↧",
  20705. "mapstoleft;": "↤",
  20706. "nLeftarrow;": "⇍",
  20707. "nleftarrow;": "↚",
  20708. "NotElement;": "∉",
  20709. "NotGreater;": "≯",
  20710. "nsubseteqq;": "⫅̸",
  20711. "nsupseteqq;": "⫆̸",
  20712. "precapprox;": "⪷",
  20713. "Proportion;": "∷",
  20714. "RightArrow;": "→",
  20715. "Rightarrow;": "⇒",
  20716. "rightarrow;": "→",
  20717. "RightFloor;": "⌋",
  20718. "rmoustache;": "⎱",
  20719. "sqsubseteq;": "⊑",
  20720. "sqsupseteq;": "⊒",
  20721. "subsetneqq;": "⫋",
  20722. "succapprox;": "⪸",
  20723. "supsetneqq;": "⫌",
  20724. "ThickSpace;": "  ",
  20725. "TildeEqual;": "≃",
  20726. "TildeTilde;": "≈",
  20727. "UnderBrace;": "⏟",
  20728. "UpArrowBar;": "⤒",
  20729. "UpTeeArrow;": "↥",
  20730. "upuparrows;": "⇈",
  20731. "varepsilon;": "ϵ",
  20732. "varnothing;": "∅",
  20733. "backepsilon;": "϶",
  20734. "blacksquare;": "▪",
  20735. "circledcirc;": "⊚",
  20736. "circleddash;": "⊝",
  20737. "CircleMinus;": "⊖",
  20738. "CircleTimes;": "⊗",
  20739. "curlyeqprec;": "⋞",
  20740. "curlyeqsucc;": "⋟",
  20741. "diamondsuit;": "♦",
  20742. "eqslantless;": "⪕",
  20743. "Equilibrium;": "⇌",
  20744. "expectation;": "ℰ",
  20745. "GreaterLess;": "≷",
  20746. "LeftCeiling;": "⌈",
  20747. "LessGreater;": "≶",
  20748. "MediumSpace;": " ",
  20749. "NotLessLess;": "≪̸",
  20750. "NotPrecedes;": "⊀",
  20751. "NotSucceeds;": "⊁",
  20752. "NotSuperset;": "⊃⃒",
  20753. "nRightarrow;": "⇏",
  20754. "nrightarrow;": "↛",
  20755. "OverBracket;": "⎴",
  20756. "preccurlyeq;": "≼",
  20757. "precnapprox;": "⪹",
  20758. "quaternions;": "ℍ",
  20759. "RightVector;": "⇀",
  20760. "Rrightarrow;": "⇛",
  20761. "RuleDelayed;": "⧴",
  20762. "SmallCircle;": "∘",
  20763. "SquareUnion;": "⊔",
  20764. "straightphi;": "ϕ",
  20765. "SubsetEqual;": "⊆",
  20766. "succcurlyeq;": "≽",
  20767. "succnapprox;": "⪺",
  20768. "thickapprox;": "≈",
  20769. "UpDownArrow;": "↕",
  20770. "Updownarrow;": "⇕",
  20771. "updownarrow;": "↕",
  20772. "VerticalBar;": "∣",
  20773. "blacklozenge;": "⧫",
  20774. "DownArrowBar;": "⤓",
  20775. "DownTeeArrow;": "↧",
  20776. "ExponentialE;": "ⅇ",
  20777. "exponentiale;": "ⅇ",
  20778. "GreaterEqual;": "≥",
  20779. "GreaterTilde;": "≳",
  20780. "HilbertSpace;": "ℋ",
  20781. "HumpDownHump;": "≎",
  20782. "Intersection;": "⋂",
  20783. "LeftArrowBar;": "⇤",
  20784. "LeftTeeArrow;": "↤",
  20785. "LeftTriangle;": "⊲",
  20786. "LeftUpVector;": "↿",
  20787. "NotCongruent;": "≢",
  20788. "NotHumpEqual;": "≏̸",
  20789. "NotLessEqual;": "≰",
  20790. "NotLessTilde;": "≴",
  20791. "Proportional;": "∝",
  20792. "RightCeiling;": "⌉",
  20793. "risingdotseq;": "≓",
  20794. "RoundImplies;": "⥰",
  20795. "ShortUpArrow;": "↑",
  20796. "SquareSubset;": "⊏",
  20797. "triangledown;": "▿",
  20798. "triangleleft;": "◃",
  20799. "UnderBracket;": "⎵",
  20800. "varsubsetneq;": "⊊︀",
  20801. "varsupsetneq;": "⊋︀",
  20802. "VerticalLine;": "|",
  20803. "ApplyFunction;": "⁡",
  20804. "bigtriangleup;": "△",
  20805. "blacktriangle;": "▴",
  20806. "DifferentialD;": "ⅆ",
  20807. "divideontimes;": "⋇",
  20808. "DoubleLeftTee;": "⫤",
  20809. "DoubleUpArrow;": "⇑",
  20810. "fallingdotseq;": "≒",
  20811. "hookleftarrow;": "↩",
  20812. "leftarrowtail;": "↢",
  20813. "leftharpoonup;": "↼",
  20814. "LeftTeeVector;": "⥚",
  20815. "LeftVectorBar;": "⥒",
  20816. "LessFullEqual;": "≦",
  20817. "LongLeftArrow;": "⟵",
  20818. "Longleftarrow;": "⟸",
  20819. "longleftarrow;": "⟵",
  20820. "looparrowleft;": "↫",
  20821. "measuredangle;": "∡",
  20822. "NotEqualTilde;": "≂̸",
  20823. "NotTildeEqual;": "≄",
  20824. "NotTildeTilde;": "≉",
  20825. "ntriangleleft;": "⋪",
  20826. "Poincareplane;": "ℌ",
  20827. "PrecedesEqual;": "⪯",
  20828. "PrecedesTilde;": "≾",
  20829. "RightArrowBar;": "⇥",
  20830. "RightTeeArrow;": "↦",
  20831. "RightTriangle;": "⊳",
  20832. "RightUpVector;": "↾",
  20833. "shortparallel;": "∥",
  20834. "smallsetminus;": "∖",
  20835. "SucceedsEqual;": "⪰",
  20836. "SucceedsTilde;": "≿",
  20837. "SupersetEqual;": "⊇",
  20838. "triangleright;": "▹",
  20839. "UpEquilibrium;": "⥮",
  20840. "upharpoonleft;": "↿",
  20841. "varsubsetneqq;": "⫋︀",
  20842. "varsupsetneqq;": "⫌︀",
  20843. "VerticalTilde;": "≀",
  20844. "VeryThinSpace;": " ",
  20845. "curvearrowleft;": "↶",
  20846. "DiacriticalDot;": "˙",
  20847. "doublebarwedge;": "⌆",
  20848. "DoubleRightTee;": "⊨",
  20849. "downdownarrows;": "⇊",
  20850. "DownLeftVector;": "↽",
  20851. "GreaterGreater;": "⪢",
  20852. "hookrightarrow;": "↪",
  20853. "HorizontalLine;": "─",
  20854. "InvisibleComma;": "⁣",
  20855. "InvisibleTimes;": "⁢",
  20856. "LeftDownVector;": "⇃",
  20857. "leftleftarrows;": "⇇",
  20858. "LeftRightArrow;": "↔",
  20859. "Leftrightarrow;": "⇔",
  20860. "leftrightarrow;": "↔",
  20861. "leftthreetimes;": "⋋",
  20862. "LessSlantEqual;": "⩽",
  20863. "LongRightArrow;": "⟶",
  20864. "Longrightarrow;": "⟹",
  20865. "longrightarrow;": "⟶",
  20866. "looparrowright;": "↬",
  20867. "LowerLeftArrow;": "↙",
  20868. "NestedLessLess;": "≪",
  20869. "NotGreaterLess;": "≹",
  20870. "NotLessGreater;": "≸",
  20871. "NotSubsetEqual;": "⊈",
  20872. "NotVerticalBar;": "∤",
  20873. "nshortparallel;": "∦",
  20874. "ntriangleright;": "⋫",
  20875. "OpenCurlyQuote;": "‘",
  20876. "ReverseElement;": "∋",
  20877. "rightarrowtail;": "↣",
  20878. "rightharpoonup;": "⇀",
  20879. "RightTeeVector;": "⥛",
  20880. "RightVectorBar;": "⥓",
  20881. "ShortDownArrow;": "↓",
  20882. "ShortLeftArrow;": "←",
  20883. "SquareSuperset;": "⊐",
  20884. "TildeFullEqual;": "≅",
  20885. "trianglelefteq;": "⊴",
  20886. "upharpoonright;": "↾",
  20887. "UpperLeftArrow;": "↖",
  20888. "ZeroWidthSpace;": "​",
  20889. "bigtriangledown;": "▽",
  20890. "circlearrowleft;": "↺",
  20891. "CloseCurlyQuote;": "’",
  20892. "ContourIntegral;": "∮",
  20893. "curvearrowright;": "↷",
  20894. "DoubleDownArrow;": "⇓",
  20895. "DoubleLeftArrow;": "⇐",
  20896. "downharpoonleft;": "⇃",
  20897. "DownRightVector;": "⇁",
  20898. "leftharpoondown;": "↽",
  20899. "leftrightarrows;": "⇆",
  20900. "LeftRightVector;": "⥎",
  20901. "LeftTriangleBar;": "⧏",
  20902. "LeftUpTeeVector;": "⥠",
  20903. "LeftUpVectorBar;": "⥘",
  20904. "LowerRightArrow;": "↘",
  20905. "nLeftrightarrow;": "⇎",
  20906. "nleftrightarrow;": "↮",
  20907. "NotGreaterEqual;": "≱",
  20908. "NotGreaterTilde;": "≵",
  20909. "NotHumpDownHump;": "≎̸",
  20910. "NotLeftTriangle;": "⋪",
  20911. "NotSquareSubset;": "⊏̸",
  20912. "ntrianglelefteq;": "⋬",
  20913. "OverParenthesis;": "⏜",
  20914. "RightDownVector;": "⇂",
  20915. "rightleftarrows;": "⇄",
  20916. "rightsquigarrow;": "↝",
  20917. "rightthreetimes;": "⋌",
  20918. "ShortRightArrow;": "→",
  20919. "straightepsilon;": "ϵ",
  20920. "trianglerighteq;": "⊵",
  20921. "UpperRightArrow;": "↗",
  20922. "vartriangleleft;": "⊲",
  20923. "circlearrowright;": "↻",
  20924. "DiacriticalAcute;": "´",
  20925. "DiacriticalGrave;": "`",
  20926. "DiacriticalTilde;": "˜",
  20927. "DoubleRightArrow;": "⇒",
  20928. "DownArrowUpArrow;": "⇵",
  20929. "downharpoonright;": "⇂",
  20930. "EmptySmallSquare;": "◻",
  20931. "GreaterEqualLess;": "⋛",
  20932. "GreaterFullEqual;": "≧",
  20933. "LeftAngleBracket;": "⟨",
  20934. "LeftUpDownVector;": "⥑",
  20935. "LessEqualGreater;": "⋚",
  20936. "NonBreakingSpace;": " ",
  20937. "NotPrecedesEqual;": "⪯̸",
  20938. "NotRightTriangle;": "⋫",
  20939. "NotSucceedsEqual;": "⪰̸",
  20940. "NotSucceedsTilde;": "≿̸",
  20941. "NotSupersetEqual;": "⊉",
  20942. "ntrianglerighteq;": "⋭",
  20943. "rightharpoondown;": "⇁",
  20944. "rightrightarrows;": "⇉",
  20945. "RightTriangleBar;": "⧐",
  20946. "RightUpTeeVector;": "⥜",
  20947. "RightUpVectorBar;": "⥔",
  20948. "twoheadleftarrow;": "↞",
  20949. "UnderParenthesis;": "⏝",
  20950. "UpArrowDownArrow;": "⇅",
  20951. "vartriangleright;": "⊳",
  20952. "blacktriangledown;": "▾",
  20953. "blacktriangleleft;": "◂",
  20954. "DoubleUpDownArrow;": "⇕",
  20955. "DoubleVerticalBar;": "∥",
  20956. "DownLeftTeeVector;": "⥞",
  20957. "DownLeftVectorBar;": "⥖",
  20958. "FilledSmallSquare;": "◼",
  20959. "GreaterSlantEqual;": "⩾",
  20960. "LeftDoubleBracket;": "⟦",
  20961. "LeftDownTeeVector;": "⥡",
  20962. "LeftDownVectorBar;": "⥙",
  20963. "leftrightharpoons;": "⇋",
  20964. "LeftTriangleEqual;": "⊴",
  20965. "NegativeThinSpace;": "​",
  20966. "NotGreaterGreater;": "≫̸",
  20967. "NotLessSlantEqual;": "⩽̸",
  20968. "NotNestedLessLess;": "⪡̸",
  20969. "NotReverseElement;": "∌",
  20970. "NotSquareSuperset;": "⊐̸",
  20971. "NotTildeFullEqual;": "≇",
  20972. "RightAngleBracket;": "⟩",
  20973. "rightleftharpoons;": "⇌",
  20974. "RightUpDownVector;": "⥏",
  20975. "SquareSubsetEqual;": "⊑",
  20976. "twoheadrightarrow;": "↠",
  20977. "VerticalSeparator;": "❘",
  20978. "blacktriangleright;": "▸",
  20979. "DownRightTeeVector;": "⥟",
  20980. "DownRightVectorBar;": "⥗",
  20981. "LongLeftRightArrow;": "⟷",
  20982. "Longleftrightarrow;": "⟺",
  20983. "longleftrightarrow;": "⟷",
  20984. "NegativeThickSpace;": "​",
  20985. "NotLeftTriangleBar;": "⧏̸",
  20986. "PrecedesSlantEqual;": "≼",
  20987. "ReverseEquilibrium;": "⇋",
  20988. "RightDoubleBracket;": "⟧",
  20989. "RightDownTeeVector;": "⥝",
  20990. "RightDownVectorBar;": "⥕",
  20991. "RightTriangleEqual;": "⊵",
  20992. "SquareIntersection;": "⊓",
  20993. "SucceedsSlantEqual;": "≽",
  20994. "DoubleLongLeftArrow;": "⟸",
  20995. "DownLeftRightVector;": "⥐",
  20996. "LeftArrowRightArrow;": "⇆",
  20997. "leftrightsquigarrow;": "↭",
  20998. "NegativeMediumSpace;": "​",
  20999. "NotGreaterFullEqual;": "≧̸",
  21000. "NotRightTriangleBar;": "⧐̸",
  21001. "RightArrowLeftArrow;": "⇄",
  21002. "SquareSupersetEqual;": "⊒",
  21003. "CapitalDifferentialD;": "ⅅ",
  21004. "DoubleLeftRightArrow;": "⇔",
  21005. "DoubleLongRightArrow;": "⟹",
  21006. "EmptyVerySmallSquare;": "▫",
  21007. "NestedGreaterGreater;": "≫",
  21008. "NotDoubleVerticalBar;": "∦",
  21009. "NotGreaterSlantEqual;": "⩾̸",
  21010. "NotLeftTriangleEqual;": "⋬",
  21011. "NotSquareSubsetEqual;": "⋢",
  21012. "OpenCurlyDoubleQuote;": "“",
  21013. "ReverseUpEquilibrium;": "⥯",
  21014. "CloseCurlyDoubleQuote;": "”",
  21015. "DoubleContourIntegral;": "∯",
  21016. "FilledVerySmallSquare;": "▪",
  21017. "NegativeVeryThinSpace;": "​",
  21018. "NotPrecedesSlantEqual;": "⋠",
  21019. "NotRightTriangleEqual;": "⋭",
  21020. "NotSucceedsSlantEqual;": "⋡",
  21021. "DiacriticalDoubleAcute;": "˝",
  21022. "NotSquareSupersetEqual;": "⋣",
  21023. "NotNestedGreaterGreater;": "⪢̸",
  21024. "ClockwiseContourIntegral;": "∲",
  21025. "DoubleLongLeftRightArrow;": "⟺",
  21026. "CounterClockwiseContourIntegral;": "∳"
  21027. };
  21028. // lazy compute this to make this file tree-shakable for browser
  21029. let maxCRNameLength;
  21030. const decodeHtml = (rawText, asAttr) => {
  21031. let offset = 0;
  21032. const end = rawText.length;
  21033. let decodedText = '';
  21034. function advance(length) {
  21035. offset += length;
  21036. rawText = rawText.slice(length);
  21037. }
  21038. while (offset < end) {
  21039. const head = /&(?:#x?)?/i.exec(rawText);
  21040. if (!head || offset + head.index >= end) {
  21041. const remaining = end - offset;
  21042. decodedText += rawText.slice(0, remaining);
  21043. advance(remaining);
  21044. break;
  21045. }
  21046. // Advance to the "&".
  21047. decodedText += rawText.slice(0, head.index);
  21048. advance(head.index);
  21049. if (head[0] === '&') {
  21050. // Named character reference.
  21051. let name = '';
  21052. let value = undefined;
  21053. if (/[0-9a-z]/i.test(rawText[1])) {
  21054. if (!maxCRNameLength) {
  21055. maxCRNameLength = Object.keys(namedCharacterReferences).reduce((max, name) => Math.max(max, name.length), 0);
  21056. }
  21057. for (let length = maxCRNameLength; !value && length > 0; --length) {
  21058. name = rawText.substr(1, length);
  21059. value = namedCharacterReferences[name];
  21060. }
  21061. if (value) {
  21062. const semi = name.endsWith(';');
  21063. if (asAttr &&
  21064. !semi &&
  21065. /[=a-z0-9]/i.test(rawText[name.length + 1] || '')) {
  21066. decodedText += '&' + name;
  21067. advance(1 + name.length);
  21068. }
  21069. else {
  21070. decodedText += value;
  21071. advance(1 + name.length);
  21072. }
  21073. }
  21074. else {
  21075. decodedText += '&' + name;
  21076. advance(1 + name.length);
  21077. }
  21078. }
  21079. else {
  21080. decodedText += '&';
  21081. advance(1);
  21082. }
  21083. }
  21084. else {
  21085. // Numeric character reference.
  21086. const hex = head[0] === '&#x';
  21087. const pattern = hex ? /^&#x([0-9a-f]+);?/i : /^&#([0-9]+);?/;
  21088. const body = pattern.exec(rawText);
  21089. if (!body) {
  21090. decodedText += head[0];
  21091. advance(head[0].length);
  21092. }
  21093. else {
  21094. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  21095. let cp = Number.parseInt(body[1], hex ? 16 : 10);
  21096. if (cp === 0) {
  21097. cp = 0xfffd;
  21098. }
  21099. else if (cp > 0x10ffff) {
  21100. cp = 0xfffd;
  21101. }
  21102. else if (cp >= 0xd800 && cp <= 0xdfff) {
  21103. cp = 0xfffd;
  21104. }
  21105. else if ((cp >= 0xfdd0 && cp <= 0xfdef) || (cp & 0xfffe) === 0xfffe) ;
  21106. else if ((cp >= 0x01 && cp <= 0x08) ||
  21107. cp === 0x0b ||
  21108. (cp >= 0x0d && cp <= 0x1f) ||
  21109. (cp >= 0x7f && cp <= 0x9f)) {
  21110. cp = CCR_REPLACEMENTS[cp] || cp;
  21111. }
  21112. decodedText += String.fromCodePoint(cp);
  21113. advance(body[0].length);
  21114. }
  21115. }
  21116. }
  21117. return decodedText;
  21118. };
  21119. // https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
  21120. const CCR_REPLACEMENTS = {
  21121. 0x80: 0x20ac,
  21122. 0x82: 0x201a,
  21123. 0x83: 0x0192,
  21124. 0x84: 0x201e,
  21125. 0x85: 0x2026,
  21126. 0x86: 0x2020,
  21127. 0x87: 0x2021,
  21128. 0x88: 0x02c6,
  21129. 0x89: 0x2030,
  21130. 0x8a: 0x0160,
  21131. 0x8b: 0x2039,
  21132. 0x8c: 0x0152,
  21133. 0x8e: 0x017d,
  21134. 0x91: 0x2018,
  21135. 0x92: 0x2019,
  21136. 0x93: 0x201c,
  21137. 0x94: 0x201d,
  21138. 0x95: 0x2022,
  21139. 0x96: 0x2013,
  21140. 0x97: 0x2014,
  21141. 0x98: 0x02dc,
  21142. 0x99: 0x2122,
  21143. 0x9a: 0x0161,
  21144. 0x9b: 0x203a,
  21145. 0x9c: 0x0153,
  21146. 0x9e: 0x017e,
  21147. 0x9f: 0x0178
  21148. };
  21149. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  21150. const parserOptions = {
  21151. isVoidTag,
  21152. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  21153. isPreTag: tag => tag === 'pre',
  21154. decodeEntities: decodeHtml,
  21155. isBuiltInComponent: (tag) => {
  21156. if (isBuiltInType(tag, `Transition`)) {
  21157. return TRANSITION;
  21158. }
  21159. else if (isBuiltInType(tag, `TransitionGroup`)) {
  21160. return TRANSITION_GROUP;
  21161. }
  21162. },
  21163. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  21164. getNamespace(tag, parent) {
  21165. let ns = parent ? parent.ns : 0 /* HTML */;
  21166. if (parent && ns === 2 /* MATH_ML */) {
  21167. if (parent.tag === 'annotation-xml') {
  21168. if (tag === 'svg') {
  21169. return 1 /* SVG */;
  21170. }
  21171. if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
  21172. a.name === 'encoding' &&
  21173. a.value != null &&
  21174. (a.value.content === 'text/html' ||
  21175. a.value.content === 'application/xhtml+xml'))) {
  21176. ns = 0 /* HTML */;
  21177. }
  21178. }
  21179. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  21180. tag !== 'mglyph' &&
  21181. tag !== 'malignmark') {
  21182. ns = 0 /* HTML */;
  21183. }
  21184. }
  21185. else if (parent && ns === 1 /* SVG */) {
  21186. if (parent.tag === 'foreignObject' ||
  21187. parent.tag === 'desc' ||
  21188. parent.tag === 'title') {
  21189. ns = 0 /* HTML */;
  21190. }
  21191. }
  21192. if (ns === 0 /* HTML */) {
  21193. if (tag === 'svg') {
  21194. return 1 /* SVG */;
  21195. }
  21196. if (tag === 'math') {
  21197. return 2 /* MATH_ML */;
  21198. }
  21199. }
  21200. return ns;
  21201. },
  21202. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  21203. getTextMode({ tag, ns }) {
  21204. if (ns === 0 /* HTML */) {
  21205. if (tag === 'textarea' || tag === 'title') {
  21206. return 1 /* RCDATA */;
  21207. }
  21208. if (isRawTextContainer(tag)) {
  21209. return 2 /* RAWTEXT */;
  21210. }
  21211. }
  21212. return 0 /* DATA */;
  21213. }
  21214. };
  21215. // Parse inline CSS strings for static style attributes into an object.
  21216. // This is a NodeTransform since it works on the static `style` attribute and
  21217. // converts it into a dynamic equivalent:
  21218. // style="color: red" -> :style='{ "color": "red" }'
  21219. // It is then processed by `transformElement` and included in the generated
  21220. // props.
  21221. const transformStyle = node => {
  21222. if (node.type === 1 /* ELEMENT */) {
  21223. node.props.forEach((p, i) => {
  21224. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  21225. // replace p with an expression node
  21226. node.props[i] = {
  21227. type: 7 /* DIRECTIVE */,
  21228. name: `bind`,
  21229. arg: createSimpleExpression(`style`, true, p.loc),
  21230. exp: parseInlineCSS(p.value.content, p.loc),
  21231. modifiers: [],
  21232. loc: p.loc
  21233. };
  21234. }
  21235. });
  21236. }
  21237. };
  21238. const parseInlineCSS = (cssText, loc) => {
  21239. const normalized = parseStringStyle(cssText);
  21240. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
  21241. };
  21242. function createDOMCompilerError(code, loc) {
  21243. return createCompilerError(code, loc, DOMErrorMessages );
  21244. }
  21245. const DOMErrorMessages = {
  21246. [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  21247. [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  21248. [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  21249. [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  21250. [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  21251. [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  21252. [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.`,
  21253. [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  21254. [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  21255. [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  21256. [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  21257. };
  21258. const transformVHtml = (dir, node, context) => {
  21259. const { exp, loc } = dir;
  21260. if (!exp) {
  21261. context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
  21262. }
  21263. if (node.children.length) {
  21264. context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
  21265. node.children.length = 0;
  21266. }
  21267. return {
  21268. props: [
  21269. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  21270. ]
  21271. };
  21272. };
  21273. const transformVText = (dir, node, context) => {
  21274. const { exp, loc } = dir;
  21275. if (!exp) {
  21276. context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
  21277. }
  21278. if (node.children.length) {
  21279. context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
  21280. node.children.length = 0;
  21281. }
  21282. return {
  21283. props: [
  21284. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  21285. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  21286. : createSimpleExpression('', true))
  21287. ]
  21288. };
  21289. };
  21290. const transformModel$1 = (dir, node, context) => {
  21291. const baseResult = transformModel(dir, node, context);
  21292. // base transform has errors OR component v-model (only need props)
  21293. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  21294. return baseResult;
  21295. }
  21296. if (dir.arg) {
  21297. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  21298. }
  21299. function checkDuplicatedValue() {
  21300. const value = findProp(node, 'value');
  21301. if (value) {
  21302. context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  21303. }
  21304. }
  21305. const { tag } = node;
  21306. const isCustomElement = context.isCustomElement(tag);
  21307. if (tag === 'input' ||
  21308. tag === 'textarea' ||
  21309. tag === 'select' ||
  21310. isCustomElement) {
  21311. let directiveToUse = V_MODEL_TEXT;
  21312. let isInvalidType = false;
  21313. if (tag === 'input' || isCustomElement) {
  21314. const type = findProp(node, `type`);
  21315. if (type) {
  21316. if (type.type === 7 /* DIRECTIVE */) {
  21317. // :type="foo"
  21318. directiveToUse = V_MODEL_DYNAMIC;
  21319. }
  21320. else if (type.value) {
  21321. switch (type.value.content) {
  21322. case 'radio':
  21323. directiveToUse = V_MODEL_RADIO;
  21324. break;
  21325. case 'checkbox':
  21326. directiveToUse = V_MODEL_CHECKBOX;
  21327. break;
  21328. case 'file':
  21329. isInvalidType = true;
  21330. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  21331. break;
  21332. default:
  21333. // text type
  21334. checkDuplicatedValue();
  21335. break;
  21336. }
  21337. }
  21338. }
  21339. else if (hasDynamicKeyVBind(node)) {
  21340. // element has bindings with dynamic keys, which can possibly contain
  21341. // "type".
  21342. directiveToUse = V_MODEL_DYNAMIC;
  21343. }
  21344. else {
  21345. // text type
  21346. checkDuplicatedValue();
  21347. }
  21348. }
  21349. else if (tag === 'select') {
  21350. directiveToUse = V_MODEL_SELECT;
  21351. }
  21352. else {
  21353. // textarea
  21354. checkDuplicatedValue();
  21355. }
  21356. // inject runtime directive
  21357. // by returning the helper symbol via needRuntime
  21358. // the import will replaced a resolveDirective call.
  21359. if (!isInvalidType) {
  21360. baseResult.needRuntime = context.helper(directiveToUse);
  21361. }
  21362. }
  21363. else {
  21364. context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  21365. }
  21366. // native vmodel doesn't need the `modelValue` props since they are also
  21367. // passed to the runtime as `binding.value`. removing it reduces code size.
  21368. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  21369. p.key.content === 'modelValue'));
  21370. return baseResult;
  21371. };
  21372. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  21373. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  21374. // event propagation management
  21375. `stop,prevent,self,` +
  21376. // system modifiers + exact
  21377. `ctrl,shift,alt,meta,exact,` +
  21378. // mouse
  21379. `middle`);
  21380. // left & right could be mouse or key modifiers based on event type
  21381. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  21382. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  21383. const resolveModifiers = (key, modifiers) => {
  21384. const keyModifiers = [];
  21385. const nonKeyModifiers = [];
  21386. const eventOptionModifiers = [];
  21387. for (let i = 0; i < modifiers.length; i++) {
  21388. const modifier = modifiers[i];
  21389. if (isEventOptionModifier(modifier)) {
  21390. // eventOptionModifiers: modifiers for addEventListener() options,
  21391. // e.g. .passive & .capture
  21392. eventOptionModifiers.push(modifier);
  21393. }
  21394. else {
  21395. // runtimeModifiers: modifiers that needs runtime guards
  21396. if (maybeKeyModifier(modifier)) {
  21397. if (isStaticExp(key)) {
  21398. if (isKeyboardEvent(key.content)) {
  21399. keyModifiers.push(modifier);
  21400. }
  21401. else {
  21402. nonKeyModifiers.push(modifier);
  21403. }
  21404. }
  21405. else {
  21406. keyModifiers.push(modifier);
  21407. nonKeyModifiers.push(modifier);
  21408. }
  21409. }
  21410. else {
  21411. if (isNonKeyModifier(modifier)) {
  21412. nonKeyModifiers.push(modifier);
  21413. }
  21414. else {
  21415. keyModifiers.push(modifier);
  21416. }
  21417. }
  21418. }
  21419. }
  21420. return {
  21421. keyModifiers,
  21422. nonKeyModifiers,
  21423. eventOptionModifiers
  21424. };
  21425. };
  21426. const transformClick = (key, event) => {
  21427. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  21428. return isStaticClick
  21429. ? createSimpleExpression(event, true)
  21430. : key.type !== 4 /* SIMPLE_EXPRESSION */
  21431. ? createCompoundExpression([
  21432. `(`,
  21433. key,
  21434. `) === "onClick" ? "${event}" : (`,
  21435. key,
  21436. `)`
  21437. ])
  21438. : key;
  21439. };
  21440. const transformOn$1 = (dir, node, context) => {
  21441. return transformOn(dir, node, context, baseResult => {
  21442. const { modifiers } = dir;
  21443. if (!modifiers.length)
  21444. return baseResult;
  21445. let { key, value: handlerExp } = baseResult.props[0];
  21446. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
  21447. // normalize click.right and click.middle since they don't actually fire
  21448. if (nonKeyModifiers.includes('right')) {
  21449. key = transformClick(key, `onContextmenu`);
  21450. }
  21451. if (nonKeyModifiers.includes('middle')) {
  21452. key = transformClick(key, `onMouseup`);
  21453. }
  21454. if (nonKeyModifiers.length) {
  21455. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  21456. handlerExp,
  21457. JSON.stringify(nonKeyModifiers)
  21458. ]);
  21459. }
  21460. if (keyModifiers.length &&
  21461. // if event name is dynamic, always wrap with keys guard
  21462. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  21463. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  21464. handlerExp,
  21465. JSON.stringify(keyModifiers)
  21466. ]);
  21467. }
  21468. if (eventOptionModifiers.length) {
  21469. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  21470. key = isStaticExp(key)
  21471. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  21472. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  21473. }
  21474. return {
  21475. props: [createObjectProperty(key, handlerExp)]
  21476. };
  21477. });
  21478. };
  21479. const transformShow = (dir, node, context) => {
  21480. const { exp, loc } = dir;
  21481. if (!exp) {
  21482. context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
  21483. }
  21484. return {
  21485. props: [],
  21486. needRuntime: context.helper(V_SHOW)
  21487. };
  21488. };
  21489. const warnTransitionChildren = (node, context) => {
  21490. if (node.type === 1 /* ELEMENT */ &&
  21491. node.tagType === 1 /* COMPONENT */) {
  21492. const component = context.isBuiltInComponent(node.tag);
  21493. if (component === TRANSITION) {
  21494. return () => {
  21495. if (node.children.length && hasMultipleChildren(node)) {
  21496. context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
  21497. start: node.children[0].loc.start,
  21498. end: node.children[node.children.length - 1].loc.end,
  21499. source: ''
  21500. }));
  21501. }
  21502. };
  21503. }
  21504. }
  21505. };
  21506. function hasMultipleChildren(node) {
  21507. // #1352 filter out potential comment nodes.
  21508. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
  21509. const child = children[0];
  21510. return (children.length !== 1 ||
  21511. child.type === 11 /* FOR */ ||
  21512. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  21513. }
  21514. /**
  21515. * This module is Node-only.
  21516. */
  21517. /**
  21518. * Turn eligible hoisted static trees into stringified static nodes, e.g.
  21519. *
  21520. * ```js
  21521. * const _hoisted_1 = createStaticVNode(`<div class="foo">bar</div>`)
  21522. * ```
  21523. *
  21524. * A single static vnode can contain stringified content for **multiple**
  21525. * consecutive nodes (element and plain text), called a "chunk".
  21526. * `@vue/runtime-dom` will create the content via innerHTML in a hidden
  21527. * container element and insert all the nodes in place. The call must also
  21528. * provide the number of nodes contained in the chunk so that during hydration
  21529. * we can know how many nodes the static vnode should adopt.
  21530. *
  21531. * The optimization scans a children list that contains hoisted nodes, and
  21532. * tries to find the largest chunk of consecutive hoisted nodes before running
  21533. * into a non-hoisted node or the end of the list. A chunk is then converted
  21534. * into a single static vnode and replaces the hoisted expression of the first
  21535. * node in the chunk. Other nodes in the chunk are considered "merged" and
  21536. * therefore removed from both the hoist list and the children array.
  21537. *
  21538. * This optimization is only performed in Node.js.
  21539. */
  21540. const stringifyStatic = (children, context, parent) => {
  21541. if (parent.type === 1 /* ELEMENT */ &&
  21542. (parent.tagType === 1 /* COMPONENT */ ||
  21543. parent.tagType === 3 /* TEMPLATE */)) {
  21544. return;
  21545. }
  21546. let nc = 0; // current node count
  21547. let ec = 0; // current element with binding count
  21548. const currentChunk = [];
  21549. const stringifyCurrentChunk = (currentIndex) => {
  21550. if (nc >= 20 /* NODE_COUNT */ ||
  21551. ec >= 5 /* ELEMENT_WITH_BINDING_COUNT */) {
  21552. // combine all currently eligible nodes into a single static vnode call
  21553. const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
  21554. JSON.stringify(currentChunk.map(node => stringifyNode(node, context)).join('')),
  21555. // the 2nd argument indicates the number of DOM nodes this static vnode
  21556. // will insert / hydrate
  21557. String(currentChunk.length)
  21558. ]);
  21559. // replace the first node's hoisted expression with the static vnode call
  21560. replaceHoist(currentChunk[0], staticCall, context);
  21561. if (currentChunk.length > 1) {
  21562. for (let i = 1; i < currentChunk.length; i++) {
  21563. // for the merged nodes, set their hoisted expression to null
  21564. replaceHoist(currentChunk[i], null, context);
  21565. }
  21566. // also remove merged nodes from children
  21567. const deleteCount = currentChunk.length - 1;
  21568. children.splice(currentIndex - currentChunk.length + 1, deleteCount);
  21569. return deleteCount;
  21570. }
  21571. }
  21572. return 0;
  21573. };
  21574. let i = 0;
  21575. for (; i < children.length; i++) {
  21576. const child = children[i];
  21577. const hoisted = getHoistedNode(child);
  21578. if (hoisted) {
  21579. // presence of hoisted means child must be a stringifiable node
  21580. const node = child;
  21581. const result = analyzeNode(node);
  21582. if (result) {
  21583. // node is stringifiable, record state
  21584. nc += result[0];
  21585. ec += result[1];
  21586. currentChunk.push(node);
  21587. continue;
  21588. }
  21589. }
  21590. // we only reach here if we ran into a node that is not stringifiable
  21591. // check if currently analyzed nodes meet criteria for stringification.
  21592. // adjust iteration index
  21593. i -= stringifyCurrentChunk(i);
  21594. // reset state
  21595. nc = 0;
  21596. ec = 0;
  21597. currentChunk.length = 0;
  21598. }
  21599. // in case the last node was also stringifiable
  21600. stringifyCurrentChunk(i);
  21601. };
  21602. const getHoistedNode = (node) => ((node.type === 1 /* ELEMENT */ && node.tagType === 0 /* ELEMENT */) ||
  21603. node.type == 12 /* TEXT_CALL */) &&
  21604. node.codegenNode &&
  21605. node.codegenNode.type === 4 /* SIMPLE_EXPRESSION */ &&
  21606. node.codegenNode.hoisted;
  21607. const dataAriaRE = /^(data|aria)-/;
  21608. const isStringifiableAttr = (name) => {
  21609. return isKnownAttr(name) || dataAriaRE.test(name);
  21610. };
  21611. const replaceHoist = (node, replacement, context) => {
  21612. const hoistToReplace = node.codegenNode.hoisted;
  21613. context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement;
  21614. };
  21615. const isNonStringifiable = /*#__PURE__*/ makeMap(`caption,thead,tr,th,tbody,td,tfoot,colgroup,col`);
  21616. /**
  21617. * for a hoisted node, analyze it and return:
  21618. * - false: bailed (contains runtime constant)
  21619. * - [nc, ec] where
  21620. * - nc is the number of nodes inside
  21621. * - ec is the number of element with bindings inside
  21622. */
  21623. function analyzeNode(node) {
  21624. if (node.type === 1 /* ELEMENT */ && isNonStringifiable(node.tag)) {
  21625. return false;
  21626. }
  21627. if (node.type === 12 /* TEXT_CALL */) {
  21628. return [1, 0];
  21629. }
  21630. let nc = 1; // node count
  21631. let ec = node.props.length > 0 ? 1 : 0; // element w/ binding count
  21632. let bailed = false;
  21633. const bail = () => {
  21634. bailed = true;
  21635. return false;
  21636. };
  21637. // TODO: check for cases where using innerHTML will result in different
  21638. // output compared to imperative node insertions.
  21639. // probably only need to check for most common case
  21640. // i.e. non-phrasing-content tags inside `<p>`
  21641. function walk(node) {
  21642. for (let i = 0; i < node.props.length; i++) {
  21643. const p = node.props[i];
  21644. // bail on non-attr bindings
  21645. if (p.type === 6 /* ATTRIBUTE */ && !isStringifiableAttr(p.name)) {
  21646. return bail();
  21647. }
  21648. if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind') {
  21649. // bail on non-attr bindings
  21650. if (p.arg &&
  21651. (p.arg.type === 8 /* COMPOUND_EXPRESSION */ ||
  21652. (p.arg.isStatic && !isStringifiableAttr(p.arg.content)))) {
  21653. return bail();
  21654. }
  21655. }
  21656. }
  21657. for (let i = 0; i < node.children.length; i++) {
  21658. nc++;
  21659. const child = node.children[i];
  21660. if (child.type === 1 /* ELEMENT */) {
  21661. if (child.props.length > 0) {
  21662. ec++;
  21663. }
  21664. walk(child);
  21665. if (bailed) {
  21666. return false;
  21667. }
  21668. }
  21669. }
  21670. return true;
  21671. }
  21672. return walk(node) ? [nc, ec] : false;
  21673. }
  21674. function stringifyNode(node, context) {
  21675. if (isString(node)) {
  21676. return node;
  21677. }
  21678. if (isSymbol(node)) {
  21679. return ``;
  21680. }
  21681. switch (node.type) {
  21682. case 1 /* ELEMENT */:
  21683. return stringifyElement(node, context);
  21684. case 2 /* TEXT */:
  21685. return escapeHtml(node.content);
  21686. case 3 /* COMMENT */:
  21687. return `<!--${escapeHtml(node.content)}-->`;
  21688. case 5 /* INTERPOLATION */:
  21689. return escapeHtml(toDisplayString(evaluateConstant(node.content)));
  21690. case 8 /* COMPOUND_EXPRESSION */:
  21691. return escapeHtml(evaluateConstant(node));
  21692. case 12 /* TEXT_CALL */:
  21693. return stringifyNode(node.content, context);
  21694. default:
  21695. // static trees will not contain if/for nodes
  21696. return '';
  21697. }
  21698. }
  21699. function stringifyElement(node, context) {
  21700. let res = `<${node.tag}`;
  21701. for (let i = 0; i < node.props.length; i++) {
  21702. const p = node.props[i];
  21703. if (p.type === 6 /* ATTRIBUTE */) {
  21704. res += ` ${p.name}`;
  21705. if (p.value) {
  21706. res += `="${escapeHtml(p.value.content)}"`;
  21707. }
  21708. }
  21709. else if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind') {
  21710. // constant v-bind, e.g. :foo="1"
  21711. let evaluated = evaluateConstant(p.exp);
  21712. const arg = p.arg && p.arg.content;
  21713. if (arg === 'class') {
  21714. evaluated = normalizeClass(evaluated);
  21715. }
  21716. else if (arg === 'style') {
  21717. evaluated = stringifyStyle(normalizeStyle(evaluated));
  21718. }
  21719. res += ` ${p.arg.content}="${escapeHtml(evaluated)}"`;
  21720. }
  21721. }
  21722. if (context.scopeId) {
  21723. res += ` ${context.scopeId}`;
  21724. }
  21725. res += `>`;
  21726. for (let i = 0; i < node.children.length; i++) {
  21727. res += stringifyNode(node.children[i], context);
  21728. }
  21729. if (!isVoidTag(node.tag)) {
  21730. res += `</${node.tag}>`;
  21731. }
  21732. return res;
  21733. }
  21734. // __UNSAFE__
  21735. // Reason: eval.
  21736. // It's technically safe to eval because only constant expressions are possible
  21737. // here, e.g. `{{ 1 }}` or `{{ 'foo' }}`
  21738. // in addition, constant exps bail on presence of parens so you can't even
  21739. // run JSFuck in here. But we mark it unsafe for security review purposes.
  21740. // (see compiler-core/src/transformExpressions)
  21741. function evaluateConstant(exp) {
  21742. if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  21743. return new Function(`return ${exp.content}`)();
  21744. }
  21745. else {
  21746. // compound
  21747. let res = ``;
  21748. exp.children.forEach(c => {
  21749. if (isString(c) || isSymbol(c)) {
  21750. return;
  21751. }
  21752. if (c.type === 2 /* TEXT */) {
  21753. res += c.content;
  21754. }
  21755. else if (c.type === 5 /* INTERPOLATION */) {
  21756. res += toDisplayString(evaluateConstant(c.content));
  21757. }
  21758. else {
  21759. res += evaluateConstant(c);
  21760. }
  21761. });
  21762. return res;
  21763. }
  21764. }
  21765. const ignoreSideEffectTags = (node, context) => {
  21766. if (node.type === 1 /* ELEMENT */ &&
  21767. node.tagType === 0 /* ELEMENT */ &&
  21768. (node.tag === 'script' || node.tag === 'style')) {
  21769. context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  21770. context.removeNode();
  21771. }
  21772. };
  21773. const DOMNodeTransforms = [
  21774. transformStyle,
  21775. ...( [warnTransitionChildren] )
  21776. ];
  21777. const DOMDirectiveTransforms = {
  21778. cloak: noopDirectiveTransform,
  21779. html: transformVHtml,
  21780. text: transformVText,
  21781. model: transformModel$1,
  21782. on: transformOn$1,
  21783. show: transformShow
  21784. };
  21785. function compile(template, options = {}) {
  21786. return baseCompile(template, extend({}, parserOptions, options, {
  21787. nodeTransforms: [
  21788. // ignore <script> and <tag>
  21789. // this is not put inside DOMNodeTransforms because that list is used
  21790. // by compiler-ssr to generate vnode fallback branches
  21791. ignoreSideEffectTags,
  21792. ...DOMNodeTransforms,
  21793. ...(options.nodeTransforms || [])
  21794. ],
  21795. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  21796. transformHoist: stringifyStatic
  21797. }));
  21798. }
  21799. function parse$1(template, options = {}) {
  21800. return baseParse(template, extend({}, parserOptions, options));
  21801. }
  21802. var CompilerDOM = /*#__PURE__*/Object.freeze({
  21803. __proto__: null,
  21804. parserOptions: parserOptions,
  21805. DOMNodeTransforms: DOMNodeTransforms,
  21806. DOMDirectiveTransforms: DOMDirectiveTransforms,
  21807. compile: compile,
  21808. parse: parse$1,
  21809. transformStyle: transformStyle,
  21810. createDOMCompilerError: createDOMCompilerError,
  21811. V_MODEL_RADIO: V_MODEL_RADIO,
  21812. V_MODEL_CHECKBOX: V_MODEL_CHECKBOX,
  21813. V_MODEL_TEXT: V_MODEL_TEXT,
  21814. V_MODEL_SELECT: V_MODEL_SELECT,
  21815. V_MODEL_DYNAMIC: V_MODEL_DYNAMIC,
  21816. V_ON_WITH_MODIFIERS: V_ON_WITH_MODIFIERS,
  21817. V_ON_WITH_KEYS: V_ON_WITH_KEYS,
  21818. V_SHOW: V_SHOW,
  21819. TRANSITION: TRANSITION,
  21820. TRANSITION_GROUP: TRANSITION_GROUP,
  21821. baseCompile: baseCompile,
  21822. baseParse: baseParse,
  21823. transform: transform,
  21824. createTransformContext: createTransformContext,
  21825. traverseNode: traverseNode,
  21826. createStructuralDirectiveTransform: createStructuralDirectiveTransform,
  21827. generate: generate,
  21828. createCompilerError: createCompilerError,
  21829. getBaseTransformPreset: getBaseTransformPreset,
  21830. transformModel: transformModel,
  21831. transformOn: transformOn,
  21832. transformBind: transformBind,
  21833. noopDirectiveTransform: noopDirectiveTransform,
  21834. processIf: processIf,
  21835. processFor: processFor,
  21836. createForLoopParams: createForLoopParams,
  21837. transformExpression: transformExpression,
  21838. processExpression: processExpression,
  21839. buildSlots: buildSlots,
  21840. trackVForSlotScopes: trackVForSlotScopes,
  21841. trackSlotScopes: trackSlotScopes,
  21842. transformElement: transformElement,
  21843. resolveComponentType: resolveComponentType,
  21844. buildProps: buildProps,
  21845. processSlotOutlet: processSlotOutlet,
  21846. generateCodeFrame: generateCodeFrame,
  21847. locStub: locStub,
  21848. createRoot: createRoot,
  21849. createVNodeCall: createVNodeCall,
  21850. createArrayExpression: createArrayExpression,
  21851. createObjectExpression: createObjectExpression,
  21852. createObjectProperty: createObjectProperty,
  21853. createSimpleExpression: createSimpleExpression,
  21854. createInterpolation: createInterpolation,
  21855. createCompoundExpression: createCompoundExpression,
  21856. createCallExpression: createCallExpression,
  21857. createFunctionExpression: createFunctionExpression,
  21858. createConditionalExpression: createConditionalExpression,
  21859. createCacheExpression: createCacheExpression,
  21860. createBlockStatement: createBlockStatement,
  21861. createTemplateLiteral: createTemplateLiteral,
  21862. createIfStatement: createIfStatement,
  21863. createAssignmentExpression: createAssignmentExpression,
  21864. createSequenceExpression: createSequenceExpression,
  21865. createReturnStatement: createReturnStatement,
  21866. isStaticExp: isStaticExp,
  21867. isBuiltInType: isBuiltInType,
  21868. isCoreComponent: isCoreComponent,
  21869. isSimpleIdentifier: isSimpleIdentifier,
  21870. isMemberExpression: isMemberExpression,
  21871. getInnerRange: getInnerRange,
  21872. advancePositionWithClone: advancePositionWithClone,
  21873. advancePositionWithMutation: advancePositionWithMutation,
  21874. assert: assert,
  21875. findDir: findDir,
  21876. findProp: findProp,
  21877. isBindKey: isBindKey,
  21878. hasDynamicKeyVBind: hasDynamicKeyVBind,
  21879. isText: isText,
  21880. isVSlot: isVSlot,
  21881. isTemplateNode: isTemplateNode,
  21882. isSlotOutlet: isSlotOutlet,
  21883. injectProp: injectProp,
  21884. toValidAssetId: toValidAssetId,
  21885. hasScopeRef: hasScopeRef,
  21886. FRAGMENT: FRAGMENT,
  21887. TELEPORT: TELEPORT,
  21888. SUSPENSE: SUSPENSE,
  21889. KEEP_ALIVE: KEEP_ALIVE,
  21890. BASE_TRANSITION: BASE_TRANSITION,
  21891. OPEN_BLOCK: OPEN_BLOCK,
  21892. CREATE_BLOCK: CREATE_BLOCK,
  21893. CREATE_VNODE: CREATE_VNODE,
  21894. CREATE_COMMENT: CREATE_COMMENT,
  21895. CREATE_TEXT: CREATE_TEXT,
  21896. CREATE_STATIC: CREATE_STATIC,
  21897. RESOLVE_COMPONENT: RESOLVE_COMPONENT,
  21898. RESOLVE_DYNAMIC_COMPONENT: RESOLVE_DYNAMIC_COMPONENT,
  21899. RESOLVE_DIRECTIVE: RESOLVE_DIRECTIVE,
  21900. WITH_DIRECTIVES: WITH_DIRECTIVES,
  21901. RENDER_LIST: RENDER_LIST,
  21902. RENDER_SLOT: RENDER_SLOT,
  21903. CREATE_SLOTS: CREATE_SLOTS,
  21904. TO_DISPLAY_STRING: TO_DISPLAY_STRING,
  21905. MERGE_PROPS: MERGE_PROPS,
  21906. TO_HANDLERS: TO_HANDLERS,
  21907. CAMELIZE: CAMELIZE,
  21908. CAPITALIZE: CAPITALIZE,
  21909. TO_HANDLER_KEY: TO_HANDLER_KEY,
  21910. SET_BLOCK_TRACKING: SET_BLOCK_TRACKING,
  21911. PUSH_SCOPE_ID: PUSH_SCOPE_ID,
  21912. POP_SCOPE_ID: POP_SCOPE_ID,
  21913. WITH_SCOPE_ID: WITH_SCOPE_ID,
  21914. WITH_CTX: WITH_CTX,
  21915. UNREF: UNREF,
  21916. IS_REF: IS_REF,
  21917. helperNameMap: helperNameMap,
  21918. registerRuntimeHelpers: registerRuntimeHelpers
  21919. });
  21920. function pad (hash, len) {
  21921. while (hash.length < len) {
  21922. hash = '0' + hash;
  21923. }
  21924. return hash;
  21925. }
  21926. function fold (hash, text) {
  21927. var i;
  21928. var chr;
  21929. var len;
  21930. if (text.length === 0) {
  21931. return hash;
  21932. }
  21933. for (i = 0, len = text.length; i < len; i++) {
  21934. chr = text.charCodeAt(i);
  21935. hash = ((hash << 5) - hash) + chr;
  21936. hash |= 0;
  21937. }
  21938. return hash < 0 ? hash * -2 : hash;
  21939. }
  21940. function foldObject (hash, o, seen) {
  21941. return Object.keys(o).sort().reduce(foldKey, hash);
  21942. function foldKey (hash, key) {
  21943. return foldValue(hash, o[key], key, seen);
  21944. }
  21945. }
  21946. function foldValue (input, value, key, seen) {
  21947. var hash = fold(fold(fold(input, key), toString(value)), typeof value);
  21948. if (value === null) {
  21949. return fold(hash, 'null');
  21950. }
  21951. if (value === undefined) {
  21952. return fold(hash, 'undefined');
  21953. }
  21954. if (typeof value === 'object' || typeof value === 'function') {
  21955. if (seen.indexOf(value) !== -1) {
  21956. return fold(hash, '[Circular]' + key);
  21957. }
  21958. seen.push(value);
  21959. var objHash = foldObject(hash, value, seen);
  21960. if (!('valueOf' in value) || typeof value.valueOf !== 'function') {
  21961. return objHash;
  21962. }
  21963. try {
  21964. return fold(objHash, String(value.valueOf()))
  21965. } catch (err) {
  21966. return fold(objHash, '[valueOf exception]' + (err.stack || err.message))
  21967. }
  21968. }
  21969. return fold(hash, value.toString());
  21970. }
  21971. function toString (o) {
  21972. return Object.prototype.toString.call(o);
  21973. }
  21974. function sum (o) {
  21975. return pad(foldValue(0, o, '', []).toString(16), 8);
  21976. }
  21977. var hashSum = sum;
  21978. const CSS_VARS_HELPER = `useCssVars`;
  21979. const cssVarRE = /\bv-bind\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^)]*))\s*\)/g;
  21980. function genCssVarsFromList(vars, id, isProd) {
  21981. return `{\n ${vars
  21982. .map(key => `"${genVarName(id, key, isProd)}": (${key})`)
  21983. .join(',\n ')}\n}`;
  21984. }
  21985. function genVarName(id, raw, isProd) {
  21986. if (isProd) {
  21987. return hashSum(id + raw);
  21988. }
  21989. else {
  21990. return `${id}-${raw.replace(/([^\w-])/g, '_')}`;
  21991. }
  21992. }
  21993. function parseCssVars(sfc) {
  21994. const vars = [];
  21995. sfc.styles.forEach(style => {
  21996. let match;
  21997. while ((match = cssVarRE.exec(style.content))) {
  21998. vars.push(match[1] || match[2] || match[3]);
  21999. }
  22000. });
  22001. return vars;
  22002. }
  22003. const cssVarsPlugin = postcss__default.plugin('vue-scoped', opts => (root) => {
  22004. const { id, isProd } = opts;
  22005. root.walkDecls(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. function genCssVarsCode(vars, bindings, id, isProd) {
  22015. const varsExp = genCssVarsFromList(vars, id, isProd);
  22016. const exp = createSimpleExpression(varsExp, false);
  22017. const context = createTransformContext(createRoot([]), {
  22018. prefixIdentifiers: true,
  22019. inline: true,
  22020. bindingMetadata: bindings
  22021. });
  22022. const transformed = processExpression(exp, context);
  22023. const transformedString = transformed.type === 4 /* SIMPLE_EXPRESSION */
  22024. ? transformed.content
  22025. : transformed.children
  22026. .map(c => {
  22027. return typeof c === 'string'
  22028. ? c
  22029. : c.content;
  22030. })
  22031. .join('');
  22032. return `_${CSS_VARS_HELPER}(_ctx => (${transformedString}))`;
  22033. }
  22034. // <script setup> already gets the calls injected as part of the transform
  22035. // this is only for single normal <script>
  22036. function genNormalScriptCssVarsCode(cssVars, bindings, id, isProd) {
  22037. return (`\nimport { ${CSS_VARS_HELPER} as _${CSS_VARS_HELPER} } from 'vue'\n` +
  22038. `const __injectCSSVars__ = () => {\n${genCssVarsCode(cssVars, bindings, id, isProd)}}\n` +
  22039. `const __setup__ = __default__.setup\n` +
  22040. `__default__.setup = __setup__\n` +
  22041. ` ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) }\n` +
  22042. ` : __injectCSSVars__\n`);
  22043. }
  22044. const hasWarned = {};
  22045. function warnOnce(msg) {
  22046. const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
  22047. if (!isNodeProd && !false && !hasWarned[msg]) {
  22048. hasWarned[msg] = true;
  22049. warn(msg);
  22050. }
  22051. }
  22052. function warn(msg) {
  22053. console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  22054. }
  22055. function warnExperimental(feature, rfcId) {
  22056. warnOnce(`${feature} is still an experimental proposal.\n` +
  22057. `Follow its status at https://github.com/vuejs/rfcs/pull/${rfcId}.`);
  22058. warnOnce(`When using experimental features,\n` +
  22059. `it is recommended to pin your vue dependencies to exact versions to avoid breakage.`);
  22060. }
  22061. const sourceToSFC = new Map()
  22062. ;
  22063. function parse$2(source, { sourceMap = true, filename = 'anonymous.vue', sourceRoot = '', pad = false, compiler = CompilerDOM } = {}) {
  22064. const sourceKey = source + sourceMap + filename + sourceRoot + pad + compiler.parse;
  22065. const cache = sourceToSFC.get(sourceKey);
  22066. if (cache) {
  22067. return cache;
  22068. }
  22069. const descriptor = {
  22070. filename,
  22071. source,
  22072. template: null,
  22073. script: null,
  22074. scriptSetup: null,
  22075. styles: [],
  22076. customBlocks: [],
  22077. cssVars: []
  22078. };
  22079. const errors = [];
  22080. const ast = compiler.parse(source, {
  22081. // there are no components at SFC parsing level
  22082. isNativeTag: () => true,
  22083. // preserve all whitespaces
  22084. isPreTag: () => true,
  22085. getTextMode: ({ tag, props }, parent) => {
  22086. // all top level elements except <template> are parsed as raw text
  22087. // containers
  22088. if ((!parent && tag !== 'template') ||
  22089. // <template lang="xxx"> should also be treated as raw text
  22090. (tag === 'template' &&
  22091. props.some(p => p.type === 6 /* ATTRIBUTE */ &&
  22092. p.name === 'lang' &&
  22093. p.value &&
  22094. p.value.content !== 'html'))) {
  22095. return 2 /* RAWTEXT */;
  22096. }
  22097. else {
  22098. return 0 /* DATA */;
  22099. }
  22100. },
  22101. onError: e => {
  22102. errors.push(e);
  22103. }
  22104. });
  22105. ast.children.forEach(node => {
  22106. if (node.type !== 1 /* ELEMENT */) {
  22107. return;
  22108. }
  22109. if (!node.children.length && !hasSrc(node) && node.tag !== 'template') {
  22110. return;
  22111. }
  22112. switch (node.tag) {
  22113. case 'template':
  22114. if (!descriptor.template) {
  22115. const templateBlock = (descriptor.template = createBlock(node, source, false));
  22116. templateBlock.ast = node;
  22117. }
  22118. else {
  22119. errors.push(createDuplicateBlockError(node));
  22120. }
  22121. break;
  22122. case 'script':
  22123. const scriptBlock = createBlock(node, source, pad);
  22124. const isSetup = !!scriptBlock.attrs.setup;
  22125. if (isSetup && !descriptor.scriptSetup) {
  22126. descriptor.scriptSetup = scriptBlock;
  22127. break;
  22128. }
  22129. if (!isSetup && !descriptor.script) {
  22130. descriptor.script = scriptBlock;
  22131. break;
  22132. }
  22133. errors.push(createDuplicateBlockError(node, isSetup));
  22134. break;
  22135. case 'style':
  22136. const styleBlock = createBlock(node, source, pad);
  22137. if (styleBlock.attrs.vars) {
  22138. errors.push(new SyntaxError(`<style vars> has been replaced by a new proposal: ` +
  22139. `https://github.com/vuejs/rfcs/pull/231`));
  22140. }
  22141. descriptor.styles.push(styleBlock);
  22142. break;
  22143. default:
  22144. descriptor.customBlocks.push(createBlock(node, source, pad));
  22145. break;
  22146. }
  22147. });
  22148. if (descriptor.scriptSetup) {
  22149. if (descriptor.scriptSetup.src) {
  22150. errors.push(new SyntaxError(`<script setup> cannot use the "src" attribute because ` +
  22151. `its syntax will be ambiguous outside of the component.`));
  22152. descriptor.scriptSetup = null;
  22153. }
  22154. if (descriptor.script && descriptor.script.src) {
  22155. errors.push(new SyntaxError(`<script> cannot use the "src" attribute when <script setup> is ` +
  22156. `also present because they must be processed together.`));
  22157. descriptor.script = null;
  22158. }
  22159. }
  22160. if (sourceMap) {
  22161. const genMap = (block) => {
  22162. if (block && !block.src) {
  22163. block.map = generateSourceMap(filename, source, block.content, sourceRoot, !pad || block.type === 'template' ? block.loc.start.line - 1 : 0);
  22164. }
  22165. };
  22166. genMap(descriptor.template);
  22167. genMap(descriptor.script);
  22168. descriptor.styles.forEach(genMap);
  22169. descriptor.customBlocks.forEach(genMap);
  22170. }
  22171. // parse CSS vars
  22172. descriptor.cssVars = parseCssVars(descriptor);
  22173. if (descriptor.cssVars.length) {
  22174. warnExperimental(`v-bind() CSS variable injection`, 231);
  22175. }
  22176. const result = {
  22177. descriptor,
  22178. errors
  22179. };
  22180. sourceToSFC.set(sourceKey, result);
  22181. return result;
  22182. }
  22183. function createDuplicateBlockError(node, isScriptSetup = false) {
  22184. const err = new SyntaxError(`Single file component can contain only one <${node.tag}${isScriptSetup ? ` setup` : ``}> element`);
  22185. err.loc = node.loc;
  22186. return err;
  22187. }
  22188. function createBlock(node, source, pad) {
  22189. const type = node.tag;
  22190. let { start, end } = node.loc;
  22191. let content = '';
  22192. if (node.children.length) {
  22193. start = node.children[0].loc.start;
  22194. end = node.children[node.children.length - 1].loc.end;
  22195. content = source.slice(start.offset, end.offset);
  22196. }
  22197. const loc = {
  22198. source: content,
  22199. start,
  22200. end
  22201. };
  22202. const attrs = {};
  22203. const block = {
  22204. type,
  22205. content,
  22206. loc,
  22207. attrs
  22208. };
  22209. if (pad) {
  22210. block.content = padContent(source, block, pad) + block.content;
  22211. }
  22212. node.props.forEach(p => {
  22213. if (p.type === 6 /* ATTRIBUTE */) {
  22214. attrs[p.name] = p.value ? p.value.content || true : true;
  22215. if (p.name === 'lang') {
  22216. block.lang = p.value && p.value.content;
  22217. }
  22218. else if (p.name === 'src') {
  22219. block.src = p.value && p.value.content;
  22220. }
  22221. else if (type === 'style') {
  22222. if (p.name === 'scoped') {
  22223. block.scoped = true;
  22224. }
  22225. else if (p.name === 'module') {
  22226. block.module = attrs[p.name];
  22227. }
  22228. }
  22229. else if (type === 'script' && p.name === 'setup') {
  22230. block.setup = attrs.setup;
  22231. }
  22232. }
  22233. });
  22234. return block;
  22235. }
  22236. const splitRE = /\r?\n/g;
  22237. const emptyRE = /^(?:\/\/)?\s*$/;
  22238. const replaceRE = /./g;
  22239. function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
  22240. const map = new SourceMapGenerator$2({
  22241. file: filename.replace(/\\/g, '/'),
  22242. sourceRoot: sourceRoot.replace(/\\/g, '/')
  22243. });
  22244. map.setSourceContent(filename, source);
  22245. generated.split(splitRE).forEach((line, index) => {
  22246. if (!emptyRE.test(line)) {
  22247. const originalLine = index + 1 + lineOffset;
  22248. const generatedLine = index + 1;
  22249. for (let i = 0; i < line.length; i++) {
  22250. if (!/\s/.test(line[i])) {
  22251. map.addMapping({
  22252. source: filename,
  22253. original: {
  22254. line: originalLine,
  22255. column: i
  22256. },
  22257. generated: {
  22258. line: generatedLine,
  22259. column: i
  22260. }
  22261. });
  22262. }
  22263. }
  22264. }
  22265. });
  22266. return JSON.parse(map.toString());
  22267. }
  22268. function padContent(content, block, pad) {
  22269. content = content.slice(0, block.loc.start.offset);
  22270. if (pad === 'space') {
  22271. return content.replace(replaceRE, ' ');
  22272. }
  22273. else {
  22274. const offset = content.split(splitRE).length;
  22275. const padChar = block.type === 'script' && !block.lang ? '//\n' : '\n';
  22276. return Array(offset).join(padChar);
  22277. }
  22278. }
  22279. function hasSrc(node) {
  22280. return node.props.some(p => {
  22281. if (p.type !== 6 /* ATTRIBUTE */) {
  22282. return false;
  22283. }
  22284. return p.name === 'src';
  22285. });
  22286. }
  22287. function isRelativeUrl(url) {
  22288. const firstChar = url.charAt(0);
  22289. return firstChar === '.' || firstChar === '~' || firstChar === '@';
  22290. }
  22291. const externalRE = /^https?:\/\//;
  22292. function isExternalUrl(url) {
  22293. return externalRE.test(url);
  22294. }
  22295. const dataUrlRE = /^\s*data:/i;
  22296. function isDataUrl(url) {
  22297. return dataUrlRE.test(url);
  22298. }
  22299. /**
  22300. * Parses string url into URL object.
  22301. */
  22302. function parseUrl(url) {
  22303. const firstChar = url.charAt(0);
  22304. if (firstChar === '~') {
  22305. const secondChar = url.charAt(1);
  22306. url = url.slice(secondChar === '/' ? 2 : 1);
  22307. }
  22308. return parseUriParts(url);
  22309. }
  22310. /**
  22311. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  22312. * @param urlString an url as a string
  22313. */
  22314. function parseUriParts(urlString) {
  22315. // A TypeError is thrown if urlString is not a string
  22316. // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
  22317. return url.parse(isString(urlString) ? urlString : '', false, true);
  22318. }
  22319. const defaultAssetUrlOptions = {
  22320. base: null,
  22321. includeAbsolute: false,
  22322. tags: {
  22323. video: ['src', 'poster'],
  22324. source: ['src'],
  22325. img: ['src'],
  22326. image: ['xlink:href', 'href'],
  22327. use: ['xlink:href', 'href']
  22328. }
  22329. };
  22330. const normalizeOptions = (options) => {
  22331. if (Object.keys(options).some(key => isArray(options[key]))) {
  22332. // legacy option format which directly passes in tags config
  22333. return {
  22334. ...defaultAssetUrlOptions,
  22335. tags: options
  22336. };
  22337. }
  22338. return {
  22339. ...defaultAssetUrlOptions,
  22340. ...options
  22341. };
  22342. };
  22343. const createAssetUrlTransformWithOptions = (options) => {
  22344. return (node, context) => transformAssetUrl(node, context, options);
  22345. };
  22346. /**
  22347. * A `@vue/compiler-core` plugin that transforms relative asset urls into
  22348. * either imports or absolute urls.
  22349. *
  22350. * ``` js
  22351. * // Before
  22352. * createVNode('img', { src: './logo.png' })
  22353. *
  22354. * // After
  22355. * import _imports_0 from './logo.png'
  22356. * createVNode('img', { src: _imports_0 })
  22357. * ```
  22358. */
  22359. const transformAssetUrl = (node, context, options = defaultAssetUrlOptions) => {
  22360. if (node.type === 1 /* ELEMENT */) {
  22361. if (!node.props.length) {
  22362. return;
  22363. }
  22364. const tags = options.tags || defaultAssetUrlOptions.tags;
  22365. const attrs = tags[node.tag];
  22366. const wildCardAttrs = tags['*'];
  22367. if (!attrs && !wildCardAttrs) {
  22368. return;
  22369. }
  22370. const assetAttrs = (attrs || []).concat(wildCardAttrs || []);
  22371. node.props.forEach((attr, index) => {
  22372. if (attr.type !== 6 /* ATTRIBUTE */ ||
  22373. !assetAttrs.includes(attr.name) ||
  22374. !attr.value ||
  22375. isExternalUrl(attr.value.content) ||
  22376. isDataUrl(attr.value.content) ||
  22377. attr.value.content[0] === '#' ||
  22378. (!options.includeAbsolute && !isRelativeUrl(attr.value.content))) {
  22379. return;
  22380. }
  22381. const url = parseUrl(attr.value.content);
  22382. if (options.base) {
  22383. // explicit base - directly rewrite the url into absolute url
  22384. // does not apply to absolute urls or urls that start with `@`
  22385. // since they are aliases
  22386. if (attr.value.content[0] !== '@' &&
  22387. isRelativeUrl(attr.value.content)) {
  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. }
  22399. return;
  22400. }
  22401. // otherwise, transform the url into an import.
  22402. // this assumes a bundler will resolve the import into the correct
  22403. // absolute url (e.g. webpack file-loader)
  22404. const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context);
  22405. node.props[index] = {
  22406. type: 7 /* DIRECTIVE */,
  22407. name: 'bind',
  22408. arg: createSimpleExpression(attr.name, true, attr.loc),
  22409. exp,
  22410. modifiers: [],
  22411. loc: attr.loc
  22412. };
  22413. });
  22414. }
  22415. };
  22416. function getImportsExpressionExp(path, hash, loc, context) {
  22417. if (path) {
  22418. const importsArray = Array.from(context.imports);
  22419. const existing = importsArray.find(i => i.path === path);
  22420. if (existing) {
  22421. return existing.exp;
  22422. }
  22423. const name = `_imports_${importsArray.length}`;
  22424. const exp = createSimpleExpression(name, false, loc, 2 /* CAN_HOIST */);
  22425. context.imports.add({ exp, path });
  22426. if (hash && path) {
  22427. return context.hoist(createSimpleExpression(`${name} + '${hash}'`, false, loc, 2 /* CAN_HOIST */));
  22428. }
  22429. else {
  22430. return exp;
  22431. }
  22432. }
  22433. else {
  22434. return createSimpleExpression(`''`, false, loc, 2 /* CAN_HOIST */);
  22435. }
  22436. }
  22437. const srcsetTags = ['img', 'source'];
  22438. // http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
  22439. const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
  22440. const createSrcsetTransformWithOptions = (options) => {
  22441. return (node, context) => transformSrcset(node, context, options);
  22442. };
  22443. const transformSrcset = (node, context, options = defaultAssetUrlOptions) => {
  22444. if (node.type === 1 /* ELEMENT */) {
  22445. if (srcsetTags.includes(node.tag) && node.props.length) {
  22446. node.props.forEach((attr, index) => {
  22447. if (attr.name === 'srcset' && attr.type === 6 /* ATTRIBUTE */) {
  22448. if (!attr.value)
  22449. return;
  22450. const value = attr.value.content;
  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 importsArray = Array.from(context.imports);
  22497. const existingImportsIndex = importsArray.findIndex(i => i.path === path);
  22498. if (existingImportsIndex > -1) {
  22499. exp = createSimpleExpression(`_imports_${existingImportsIndex}`, false, attr.loc, 2 /* CAN_HOIST */);
  22500. }
  22501. else {
  22502. exp = createSimpleExpression(`_imports_${importsArray.length}`, false, attr.loc, 2 /* CAN_HOIST */);
  22503. context.imports.add({ exp, path });
  22504. }
  22505. compoundExpression.children.push(exp);
  22506. }
  22507. }
  22508. else {
  22509. const exp = createSimpleExpression(`"${url}"`, false, attr.loc, 2 /* CAN_HOIST */);
  22510. compoundExpression.children.push(exp);
  22511. }
  22512. const isNotLast = imageCandidates.length - 1 > index;
  22513. if (descriptor && isNotLast) {
  22514. compoundExpression.children.push(` + '${descriptor}, ' + `);
  22515. }
  22516. else if (descriptor) {
  22517. compoundExpression.children.push(` + '${descriptor}'`);
  22518. }
  22519. else if (isNotLast) {
  22520. compoundExpression.children.push(` + ', ' + `);
  22521. }
  22522. });
  22523. const hoisted = context.hoist(compoundExpression);
  22524. hoisted.constType = 2 /* CAN_HOIST */;
  22525. node.props[index] = {
  22526. type: 7 /* DIRECTIVE */,
  22527. name: 'bind',
  22528. arg: createSimpleExpression('srcset', true, attr.loc),
  22529. exp: hoisted,
  22530. modifiers: [],
  22531. loc: attr.loc
  22532. };
  22533. }
  22534. });
  22535. }
  22536. }
  22537. };
  22538. const SSR_INTERPOLATE = Symbol(`ssrInterpolate`);
  22539. const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`);
  22540. const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`);
  22541. const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`);
  22542. const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`);
  22543. const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`);
  22544. const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`);
  22545. const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`);
  22546. const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`);
  22547. const SSR_RENDER_LIST = Symbol(`ssrRenderList`);
  22548. const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`);
  22549. const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`);
  22550. const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`);
  22551. const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`);
  22552. const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`);
  22553. const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`);
  22554. const ssrHelpers = {
  22555. [SSR_INTERPOLATE]: `ssrInterpolate`,
  22556. [SSR_RENDER_VNODE]: `ssrRenderVNode`,
  22557. [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
  22558. [SSR_RENDER_SLOT]: `ssrRenderSlot`,
  22559. [SSR_RENDER_CLASS]: `ssrRenderClass`,
  22560. [SSR_RENDER_STYLE]: `ssrRenderStyle`,
  22561. [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
  22562. [SSR_RENDER_ATTR]: `ssrRenderAttr`,
  22563. [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
  22564. [SSR_RENDER_LIST]: `ssrRenderList`,
  22565. [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
  22566. [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
  22567. [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
  22568. [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
  22569. [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
  22570. [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`
  22571. };
  22572. // Note: these are helpers imported from @vue/server-renderer
  22573. // make sure the names match!
  22574. registerRuntimeHelpers(ssrHelpers);
  22575. // Plugin for the first transform pass, which simply constructs the AST node
  22576. const ssrTransformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, processIf);
  22577. // This is called during the 2nd transform pass to construct the SSR-specific
  22578. // codegen nodes.
  22579. function ssrProcessIf(node, context, disableNestedFragments = false) {
  22580. const [rootBranch] = node.branches;
  22581. const ifStatement = createIfStatement(rootBranch.condition, processIfBranch(rootBranch, context, disableNestedFragments));
  22582. context.pushStatement(ifStatement);
  22583. let currentIf = ifStatement;
  22584. for (let i = 1; i < node.branches.length; i++) {
  22585. const branch = node.branches[i];
  22586. const branchBlockStatement = processIfBranch(branch, context, disableNestedFragments);
  22587. if (branch.condition) {
  22588. // else-if
  22589. currentIf = currentIf.alternate = createIfStatement(branch.condition, branchBlockStatement);
  22590. }
  22591. else {
  22592. // else
  22593. currentIf.alternate = branchBlockStatement;
  22594. }
  22595. }
  22596. if (!currentIf.alternate) {
  22597. currentIf.alternate = createBlockStatement([
  22598. createCallExpression(`_push`, ['`<!---->`'])
  22599. ]);
  22600. }
  22601. }
  22602. function processIfBranch(branch, context, disableNestedFragments = false) {
  22603. const { children } = branch;
  22604. const needFragmentWrapper = !disableNestedFragments &&
  22605. (children.length !== 1 || children[0].type !== 1 /* ELEMENT */) &&
  22606. // optimize away nested fragments when the only child is a ForNode
  22607. !(children.length === 1 && children[0].type === 11 /* FOR */);
  22608. return processChildrenAsStatement(children, context, needFragmentWrapper);
  22609. }
  22610. // Plugin for the first transform pass, which simply constructs the AST node
  22611. const ssrTransformFor = createStructuralDirectiveTransform('for', processFor);
  22612. // This is called during the 2nd transform pass to construct the SSR-specific
  22613. // codegen nodes.
  22614. function ssrProcessFor(node, context, disableNestedFragments = false) {
  22615. const needFragmentWrapper = !disableNestedFragments &&
  22616. (node.children.length !== 1 || node.children[0].type !== 1 /* ELEMENT */);
  22617. const renderLoop = createFunctionExpression(createForLoopParams(node.parseResult));
  22618. renderLoop.body = processChildrenAsStatement(node.children, context, needFragmentWrapper);
  22619. // v-for always renders a fragment unless explicitly disabled
  22620. if (!disableNestedFragments) {
  22621. context.pushStringPart(`<!--[-->`);
  22622. }
  22623. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_LIST), [
  22624. node.source,
  22625. renderLoop
  22626. ]));
  22627. if (!disableNestedFragments) {
  22628. context.pushStringPart(`<!--]-->`);
  22629. }
  22630. }
  22631. const ssrTransformSlotOutlet = (node, context) => {
  22632. if (isSlotOutlet(node)) {
  22633. const { slotName, slotProps } = processSlotOutlet(node, context);
  22634. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_SLOT), [
  22635. `_ctx.$slots`,
  22636. slotName,
  22637. slotProps || `{}`,
  22638. `null`,
  22639. `_push`,
  22640. `_parent`
  22641. ]);
  22642. }
  22643. };
  22644. function ssrProcessSlotOutlet(node, context) {
  22645. const renderCall = node.ssrCodegenNode;
  22646. // has fallback content
  22647. if (node.children.length) {
  22648. const fallbackRenderFn = createFunctionExpression([]);
  22649. fallbackRenderFn.body = processChildrenAsStatement(node.children, context);
  22650. // _renderSlot(slots, name, props, fallback, ...)
  22651. renderCall.arguments[3] = fallbackRenderFn;
  22652. }
  22653. context.pushStatement(node.ssrCodegenNode);
  22654. }
  22655. function createSSRCompilerError(code, loc) {
  22656. return createCompilerError(code, loc, SSRErrorMessages);
  22657. }
  22658. const SSRErrorMessages = {
  22659. [60 /* X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM */]: `Custom directive is missing corresponding SSR transform and will be ignored.`,
  22660. [61 /* X_SSR_UNSAFE_ATTR_NAME */]: `Unsafe attribute name for SSR.`,
  22661. [62 /* X_SSR_NO_TELEPORT_TARGET */]: `Missing the 'to' prop on teleport element.`,
  22662. [63 /* X_SSR_INVALID_AST_NODE */]: `Invalid AST node during SSR transform.`
  22663. };
  22664. // Note: this is a 2nd-pass codegen transform.
  22665. function ssrProcessTeleport(node, context) {
  22666. const targetProp = findProp(node, 'to');
  22667. if (!targetProp) {
  22668. context.onError(createSSRCompilerError(62 /* X_SSR_NO_TELEPORT_TARGET */, node.loc));
  22669. return;
  22670. }
  22671. let target;
  22672. if (targetProp.type === 6 /* ATTRIBUTE */) {
  22673. target =
  22674. targetProp.value && createSimpleExpression(targetProp.value.content, true);
  22675. }
  22676. else {
  22677. target = targetProp.exp;
  22678. }
  22679. if (!target) {
  22680. context.onError(createSSRCompilerError(62 /* X_SSR_NO_TELEPORT_TARGET */, targetProp.loc));
  22681. return;
  22682. }
  22683. const disabledProp = findProp(node, 'disabled', false, true /* allow empty */);
  22684. const disabled = disabledProp
  22685. ? disabledProp.type === 6 /* ATTRIBUTE */
  22686. ? `true`
  22687. : disabledProp.exp || `false`
  22688. : `false`;
  22689. const contentRenderFn = createFunctionExpression([`_push`], undefined, // Body is added later
  22690. true, // newline
  22691. false, // isSlot
  22692. node.loc);
  22693. contentRenderFn.body = processChildrenAsStatement(node.children, context);
  22694. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_TELEPORT), [
  22695. `_push`,
  22696. contentRenderFn,
  22697. target,
  22698. disabled,
  22699. `_parent`
  22700. ]));
  22701. }
  22702. const wipMap = new WeakMap();
  22703. // phase 1
  22704. function ssrTransformSuspense(node, context) {
  22705. return () => {
  22706. if (node.children.length) {
  22707. const wipEntry = {
  22708. slotsExp: null,
  22709. wipSlots: []
  22710. };
  22711. wipMap.set(node, wipEntry);
  22712. wipEntry.slotsExp = buildSlots(node, context, (_props, children, loc) => {
  22713. const fn = createFunctionExpression([], undefined, // no return, assign body later
  22714. true, // newline
  22715. false, // suspense slots are not treated as normal slots
  22716. loc);
  22717. wipEntry.wipSlots.push({
  22718. fn,
  22719. children
  22720. });
  22721. return fn;
  22722. }).slots;
  22723. }
  22724. };
  22725. }
  22726. // phase 2
  22727. function ssrProcessSuspense(node, context) {
  22728. // complete wip slots with ssr code
  22729. const wipEntry = wipMap.get(node);
  22730. if (!wipEntry) {
  22731. return;
  22732. }
  22733. const { slotsExp, wipSlots } = wipEntry;
  22734. for (let i = 0; i < wipSlots.length; i++) {
  22735. const { fn, children } = wipSlots[i];
  22736. fn.body = processChildrenAsStatement(children, context);
  22737. }
  22738. // _push(ssrRenderSuspense(slots))
  22739. context.pushStatement(createCallExpression(context.helper(SSR_RENDER_SUSPENSE), [
  22740. `_push`,
  22741. slotsExp
  22742. ]));
  22743. }
  22744. function ssrProcessTransitionGroup(node, context) {
  22745. const tag = findProp(node, 'tag');
  22746. if (tag) {
  22747. if (tag.type === 7 /* DIRECTIVE */) {
  22748. // dynamic :tag
  22749. context.pushStringPart(`<`);
  22750. context.pushStringPart(tag.exp);
  22751. context.pushStringPart(`>`);
  22752. processChildren(node.children, context, false,
  22753. /**
  22754. * TransitionGroup has the special runtime behavior of flattening and
  22755. * concatenating all children into a single fragment (in order for them to
  22756. * be pathced using the same key map) so we need to account for that here
  22757. * by disabling nested fragment wrappers from being generated.
  22758. */
  22759. true);
  22760. context.pushStringPart(`</`);
  22761. context.pushStringPart(tag.exp);
  22762. context.pushStringPart(`>`);
  22763. }
  22764. else {
  22765. // static tag
  22766. context.pushStringPart(`<${tag.value.content}>`);
  22767. processChildren(node.children, context, false, true);
  22768. context.pushStringPart(`</${tag.value.content}>`);
  22769. }
  22770. }
  22771. else {
  22772. // fragment
  22773. processChildren(node.children, context, true, true);
  22774. }
  22775. }
  22776. // We need to construct the slot functions in the 1st pass to ensure proper
  22777. // scope tracking, but the children of each slot cannot be processed until
  22778. // the 2nd pass, so we store the WIP slot functions in a weakmap during the 1st
  22779. // pass and complete them in the 2nd pass.
  22780. const wipMap$1 = new WeakMap();
  22781. const componentTypeMap = new WeakMap();
  22782. // ssr component transform is done in two phases:
  22783. // In phase 1. we use `buildSlot` to analyze the children of the component into
  22784. // WIP slot functions (it must be done in phase 1 because `buildSlot` relies on
  22785. // the core transform context).
  22786. // In phase 2. we convert the WIP slots from phase 1 into ssr-specific codegen
  22787. // nodes.
  22788. const ssrTransformComponent = (node, context) => {
  22789. if (node.type !== 1 /* ELEMENT */ ||
  22790. node.tagType !== 1 /* COMPONENT */) {
  22791. return;
  22792. }
  22793. const component = resolveComponentType(node, context, true /* ssr */);
  22794. componentTypeMap.set(node, component);
  22795. if (isSymbol(component)) {
  22796. if (component === SUSPENSE) {
  22797. return ssrTransformSuspense(node, context);
  22798. }
  22799. return; // built-in component: fallthrough
  22800. }
  22801. // Build the fallback vnode-based branch for the component's slots.
  22802. // We need to clone the node into a fresh copy and use the buildSlots' logic
  22803. // to get access to the children of each slot. We then compile them with
  22804. // a child transform pipeline using vnode-based transforms (instead of ssr-
  22805. // based ones), and save the result branch (a ReturnStatement) in an array.
  22806. // The branch is retrieved when processing slots again in ssr mode.
  22807. const vnodeBranches = [];
  22808. const clonedNode = clone(node);
  22809. return function ssrPostTransformComponent() {
  22810. // Using the cloned node, build the normal VNode-based branches (for
  22811. // fallback in case the child is render-fn based). Store them in an array
  22812. // for later use.
  22813. if (clonedNode.children.length) {
  22814. buildSlots(clonedNode, context, (props, children) => {
  22815. vnodeBranches.push(createVNodeSlotBranch(props, children, context));
  22816. return createFunctionExpression(undefined);
  22817. });
  22818. }
  22819. const props = node.props.length > 0
  22820. ? // note we are not passing ssr: true here because for components, v-on
  22821. // handlers should still be passed
  22822. buildProps(node, context).props || `null`
  22823. : `null`;
  22824. const wipEntries = [];
  22825. wipMap$1.set(node, wipEntries);
  22826. const buildSSRSlotFn = (props, children, loc) => {
  22827. const fn = createFunctionExpression([props || `_`, `_push`, `_parent`, `_scopeId`], undefined, // no return, assign body later
  22828. true, // newline
  22829. true, // isSlot
  22830. loc);
  22831. wipEntries.push({
  22832. fn,
  22833. children,
  22834. // also collect the corresponding vnode branch built earlier
  22835. vnodeBranch: vnodeBranches[wipEntries.length]
  22836. });
  22837. return fn;
  22838. };
  22839. const slots = node.children.length
  22840. ? buildSlots(node, context, buildSSRSlotFn).slots
  22841. : `null`;
  22842. if (typeof component !== 'string') {
  22843. // dynamic component that resolved to a `resolveDynamicComponent` call
  22844. // expression - since the resolved result may be a plain element (string)
  22845. // or a VNode, handle it with `renderVNode`.
  22846. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_VNODE), [
  22847. `_push`,
  22848. createCallExpression(context.helper(CREATE_VNODE), [
  22849. component,
  22850. props,
  22851. slots
  22852. ]),
  22853. `_parent`
  22854. ]);
  22855. }
  22856. else {
  22857. node.ssrCodegenNode = createCallExpression(context.helper(SSR_RENDER_COMPONENT), [component, props, slots, `_parent`]);
  22858. }
  22859. };
  22860. };
  22861. function ssrProcessComponent(node, context) {
  22862. const component = componentTypeMap.get(node);
  22863. if (!node.ssrCodegenNode) {
  22864. // this is a built-in component that fell-through.
  22865. if (component === TELEPORT) {
  22866. return ssrProcessTeleport(node, context);
  22867. }
  22868. else if (component === SUSPENSE) {
  22869. return ssrProcessSuspense(node, context);
  22870. }
  22871. else if (component === TRANSITION_GROUP) {
  22872. return ssrProcessTransitionGroup(node, context);
  22873. }
  22874. else {
  22875. // real fall-through (e.g. KeepAlive): just render its children.
  22876. processChildren(node.children, context);
  22877. }
  22878. }
  22879. else {
  22880. // finish up slot function expressions from the 1st pass.
  22881. const wipEntries = wipMap$1.get(node) || [];
  22882. for (let i = 0; i < wipEntries.length; i++) {
  22883. const { fn, children, vnodeBranch } = wipEntries[i];
  22884. // For each slot, we generate two branches: one SSR-optimized branch and
  22885. // one normal vnode-based branch. The branches are taken based on the
  22886. // presence of the 2nd `_push` argument (which is only present if the slot
  22887. // is called by `_ssrRenderSlot`.
  22888. fn.body = createIfStatement(createSimpleExpression(`_push`, false), processChildrenAsStatement(children, context, false, true /* withSlotScopeId */), vnodeBranch);
  22889. }
  22890. if (typeof component === 'string') {
  22891. // static component
  22892. context.pushStatement(createCallExpression(`_push`, [node.ssrCodegenNode]));
  22893. }
  22894. else {
  22895. // dynamic component (`resolveDynamicComponent` call)
  22896. // the codegen node is a `renderVNode` call
  22897. context.pushStatement(node.ssrCodegenNode);
  22898. }
  22899. }
  22900. }
  22901. const rawOptionsMap = new WeakMap();
  22902. const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
  22903. const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms];
  22904. const vnodeDirectiveTransforms = {
  22905. ...baseDirectiveTransforms,
  22906. ...DOMDirectiveTransforms
  22907. };
  22908. function createVNodeSlotBranch(props, children, parentContext) {
  22909. // apply a sub-transform using vnode-based transforms.
  22910. const rawOptions = rawOptionsMap.get(parentContext.root);
  22911. const subOptions = {
  22912. ...rawOptions,
  22913. // overwrite with vnode-based transforms
  22914. nodeTransforms: [
  22915. ...vnodeNodeTransforms,
  22916. ...(rawOptions.nodeTransforms || [])
  22917. ],
  22918. directiveTransforms: {
  22919. ...vnodeDirectiveTransforms,
  22920. ...(rawOptions.directiveTransforms || {})
  22921. }
  22922. };
  22923. // wrap the children with a wrapper template for proper children treatment.
  22924. const wrapperNode = {
  22925. type: 1 /* ELEMENT */,
  22926. ns: 0 /* HTML */,
  22927. tag: 'template',
  22928. tagType: 3 /* TEMPLATE */,
  22929. isSelfClosing: false,
  22930. // important: provide v-slot="props" on the wrapper for proper
  22931. // scope analysis
  22932. props: [
  22933. {
  22934. type: 7 /* DIRECTIVE */,
  22935. name: 'slot',
  22936. exp: props,
  22937. arg: undefined,
  22938. modifiers: [],
  22939. loc: locStub
  22940. }
  22941. ],
  22942. children,
  22943. loc: locStub,
  22944. codegenNode: undefined
  22945. };
  22946. subTransform(wrapperNode, subOptions, parentContext);
  22947. return createReturnStatement(children);
  22948. }
  22949. function subTransform(node, options, parentContext) {
  22950. const childRoot = createRoot([node]);
  22951. const childContext = createTransformContext(childRoot, options);
  22952. // this sub transform is for vnode fallback branch so it should be handled
  22953. // like normal render functions
  22954. childContext.ssr = false;
  22955. // inherit parent scope analysis state
  22956. childContext.scopes = { ...parentContext.scopes };
  22957. childContext.identifiers = { ...parentContext.identifiers };
  22958. // traverse
  22959. traverseNode(childRoot, childContext);
  22960. ['helpers', 'components', 'directives', 'imports'].forEach(key => {
  22961. childContext[key].forEach((value) => {
  22962. parentContext[key].add(value);
  22963. });
  22964. });
  22965. }
  22966. function clone(v) {
  22967. if (isArray(v)) {
  22968. return v.map(clone);
  22969. }
  22970. else if (isObject(v)) {
  22971. const res = {};
  22972. for (const key in v) {
  22973. res[key] = clone(v[key]);
  22974. }
  22975. return res;
  22976. }
  22977. else {
  22978. return v;
  22979. }
  22980. }
  22981. // for directives with children overwrite (e.g. v-html & v-text), we need to
  22982. // store the raw children so that they can be added in the 2nd pass.
  22983. const rawChildrenMap = new WeakMap();
  22984. const ssrTransformElement = (node, context) => {
  22985. if (node.type !== 1 /* ELEMENT */ ||
  22986. node.tagType !== 0 /* ELEMENT */) {
  22987. return;
  22988. }
  22989. return function ssrPostTransformElement() {
  22990. // element
  22991. // generate the template literal representing the open tag.
  22992. const openTag = [`<${node.tag}`];
  22993. // some tags need to be passed to runtime for special checks
  22994. const needTagForRuntime = node.tag === 'textarea' || node.tag.indexOf('-') > 0;
  22995. // v-bind="obj" or v-bind:[key] can potentially overwrite other static
  22996. // attrs and can affect final rendering result, so when they are present
  22997. // we need to bail out to full `renderAttrs`
  22998. const hasDynamicVBind = hasDynamicKeyVBind(node);
  22999. if (hasDynamicVBind) {
  23000. const { props } = buildProps(node, context, node.props, true /* ssr */);
  23001. if (props) {
  23002. const propsExp = createCallExpression(context.helper(SSR_RENDER_ATTRS), [props]);
  23003. if (node.tag === 'textarea') {
  23004. const existingText = node.children[0];
  23005. // If interpolation, this is dynamic <textarea> content, potentially
  23006. // injected by v-model and takes higher priority than v-bind value
  23007. if (!existingText || existingText.type !== 5 /* INTERPOLATION */) {
  23008. // <textarea> with dynamic v-bind. We don't know if the final props
  23009. // will contain .value, so we will have to do something special:
  23010. // assign the merged props to a temp variable, and check whether
  23011. // it contains value (if yes, render is as children).
  23012. const tempId = `_temp${context.temps++}`;
  23013. propsExp.arguments = [
  23014. createAssignmentExpression(createSimpleExpression(tempId, false), props)
  23015. ];
  23016. rawChildrenMap.set(node, createCallExpression(context.helper(SSR_INTERPOLATE), [
  23017. createConditionalExpression(createSimpleExpression(`"value" in ${tempId}`, false), createSimpleExpression(`${tempId}.value`, false), createSimpleExpression(existingText ? existingText.content : ``, true), false)
  23018. ]));
  23019. }
  23020. }
  23021. else if (node.tag === 'input') {
  23022. // <input v-bind="obj" v-model>
  23023. // we need to determine the props to render for the dynamic v-model
  23024. // and merge it with the v-bind expression.
  23025. const vModel = findVModel(node);
  23026. if (vModel) {
  23027. // 1. save the props (san v-model) in a temp variable
  23028. const tempId = `_temp${context.temps++}`;
  23029. const tempExp = createSimpleExpression(tempId, false);
  23030. propsExp.arguments = [
  23031. createSequenceExpression([
  23032. createAssignmentExpression(tempExp, props),
  23033. createCallExpression(context.helper(MERGE_PROPS), [
  23034. tempExp,
  23035. createCallExpression(context.helper(SSR_GET_DYNAMIC_MODEL_PROPS), [
  23036. tempExp,
  23037. vModel.exp // model
  23038. ])
  23039. ])
  23040. ])
  23041. ];
  23042. }
  23043. }
  23044. if (needTagForRuntime) {
  23045. propsExp.arguments.push(`"${node.tag}"`);
  23046. }
  23047. openTag.push(propsExp);
  23048. }
  23049. }
  23050. // book keeping static/dynamic class merging.
  23051. let dynamicClassBinding = undefined;
  23052. let staticClassBinding = undefined;
  23053. // all style bindings are converted to dynamic by transformStyle.
  23054. // but we need to make sure to merge them.
  23055. let dynamicStyleBinding = undefined;
  23056. for (let i = 0; i < node.props.length; i++) {
  23057. const prop = node.props[i];
  23058. // ignore true-value/false-value on input
  23059. if (node.tag === 'input' && isTrueFalseValue(prop)) {
  23060. continue;
  23061. }
  23062. // special cases with children override
  23063. if (prop.type === 7 /* DIRECTIVE */) {
  23064. if (prop.name === 'html' && prop.exp) {
  23065. rawChildrenMap.set(node, prop.exp);
  23066. }
  23067. else if (prop.name === 'text' && prop.exp) {
  23068. node.children = [createInterpolation(prop.exp, prop.loc)];
  23069. }
  23070. else if (prop.name === 'slot') {
  23071. context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, prop.loc));
  23072. }
  23073. else if (isTextareaWithValue(node, prop) && prop.exp) {
  23074. if (!hasDynamicVBind) {
  23075. node.children = [createInterpolation(prop.exp, prop.loc)];
  23076. }
  23077. }
  23078. else {
  23079. // Directive transforms.
  23080. const directiveTransform = context.directiveTransforms[prop.name];
  23081. if (!directiveTransform) {
  23082. // no corresponding ssr directive transform found.
  23083. context.onError(createSSRCompilerError(60 /* X_SSR_CUSTOM_DIRECTIVE_NO_TRANSFORM */, prop.loc));
  23084. }
  23085. else if (!hasDynamicVBind) {
  23086. const { props, ssrTagParts } = directiveTransform(prop, node, context);
  23087. if (ssrTagParts) {
  23088. openTag.push(...ssrTagParts);
  23089. }
  23090. for (let j = 0; j < props.length; j++) {
  23091. const { key, value } = props[j];
  23092. if (isStaticExp(key)) {
  23093. let attrName = key.content;
  23094. // static key attr
  23095. if (attrName === 'key' || attrName === 'ref') {
  23096. continue;
  23097. }
  23098. if (attrName === 'class') {
  23099. openTag.push(` class="`, (dynamicClassBinding = createCallExpression(context.helper(SSR_RENDER_CLASS), [value])), `"`);
  23100. }
  23101. else if (attrName === 'style') {
  23102. if (dynamicStyleBinding) {
  23103. // already has style binding, merge into it.
  23104. mergeCall(dynamicStyleBinding, value);
  23105. }
  23106. else {
  23107. openTag.push(` style="`, (dynamicStyleBinding = createCallExpression(context.helper(SSR_RENDER_STYLE), [value])), `"`);
  23108. }
  23109. }
  23110. else {
  23111. attrName =
  23112. node.tag.indexOf('-') > 0
  23113. ? attrName // preserve raw name on custom elements
  23114. : propsToAttrMap[attrName] || attrName.toLowerCase();
  23115. if (isBooleanAttr(attrName)) {
  23116. openTag.push(createConditionalExpression(value, createSimpleExpression(' ' + attrName, true), createSimpleExpression('', true), false /* no newline */));
  23117. }
  23118. else if (isSSRSafeAttrName(attrName)) {
  23119. openTag.push(createCallExpression(context.helper(SSR_RENDER_ATTR), [
  23120. key,
  23121. value
  23122. ]));
  23123. }
  23124. else {
  23125. context.onError(createSSRCompilerError(61 /* X_SSR_UNSAFE_ATTR_NAME */, key.loc));
  23126. }
  23127. }
  23128. }
  23129. else {
  23130. // dynamic key attr
  23131. // this branch is only encountered for custom directive
  23132. // transforms that returns properties with dynamic keys
  23133. const args = [key, value];
  23134. if (needTagForRuntime) {
  23135. args.push(`"${node.tag}"`);
  23136. }
  23137. openTag.push(createCallExpression(context.helper(SSR_RENDER_DYNAMIC_ATTR), args));
  23138. }
  23139. }
  23140. }
  23141. }
  23142. }
  23143. else {
  23144. // special case: value on <textarea>
  23145. if (node.tag === 'textarea' && prop.name === 'value' && prop.value) {
  23146. rawChildrenMap.set(node, escapeHtml(prop.value.content));
  23147. }
  23148. else if (!hasDynamicVBind) {
  23149. if (prop.name === 'key' || prop.name === 'ref') {
  23150. continue;
  23151. }
  23152. // static prop
  23153. if (prop.name === 'class' && prop.value) {
  23154. staticClassBinding = JSON.stringify(prop.value.content);
  23155. }
  23156. openTag.push(` ${prop.name}` +
  23157. (prop.value ? `="${escapeHtml(prop.value.content)}"` : ``));
  23158. }
  23159. }
  23160. }
  23161. // handle co-existence of dynamic + static class bindings
  23162. if (dynamicClassBinding && staticClassBinding) {
  23163. mergeCall(dynamicClassBinding, staticClassBinding);
  23164. removeStaticBinding(openTag, 'class');
  23165. }
  23166. if (context.scopeId) {
  23167. openTag.push(` ${context.scopeId}`);
  23168. }
  23169. node.ssrCodegenNode = createTemplateLiteral(openTag);
  23170. };
  23171. };
  23172. function isTrueFalseValue(prop) {
  23173. if (prop.type === 7 /* DIRECTIVE */) {
  23174. return (prop.name === 'bind' &&
  23175. prop.arg &&
  23176. isStaticExp(prop.arg) &&
  23177. (prop.arg.content === 'true-value' || prop.arg.content === 'false-value'));
  23178. }
  23179. else {
  23180. return prop.name === 'true-value' || prop.name === 'false-value';
  23181. }
  23182. }
  23183. function isTextareaWithValue(node, prop) {
  23184. return !!(node.tag === 'textarea' &&
  23185. prop.name === 'bind' &&
  23186. isBindKey(prop.arg, 'value'));
  23187. }
  23188. function mergeCall(call, arg) {
  23189. const existing = call.arguments[0];
  23190. if (existing.type === 17 /* JS_ARRAY_EXPRESSION */) {
  23191. existing.elements.push(arg);
  23192. }
  23193. else {
  23194. call.arguments[0] = createArrayExpression([existing, arg]);
  23195. }
  23196. }
  23197. function removeStaticBinding(tag, binding) {
  23198. const regExp = new RegExp(`^ ${binding}=".+"$`);
  23199. const i = tag.findIndex(e => typeof e === 'string' && regExp.test(e));
  23200. if (i > -1) {
  23201. tag.splice(i, 1);
  23202. }
  23203. }
  23204. function findVModel(node) {
  23205. return node.props.find(p => p.type === 7 /* DIRECTIVE */ && p.name === 'model' && p.exp);
  23206. }
  23207. function ssrProcessElement(node, context) {
  23208. const isVoidTag = context.options.isVoidTag || NO;
  23209. const elementsToAdd = node.ssrCodegenNode.elements;
  23210. for (let j = 0; j < elementsToAdd.length; j++) {
  23211. context.pushStringPart(elementsToAdd[j]);
  23212. }
  23213. // Handle slot scopeId
  23214. if (context.withSlotScopeId) {
  23215. context.pushStringPart(createSimpleExpression(`_scopeId`, false));
  23216. }
  23217. // close open tag
  23218. context.pushStringPart(`>`);
  23219. const rawChildren = rawChildrenMap.get(node);
  23220. if (rawChildren) {
  23221. context.pushStringPart(rawChildren);
  23222. }
  23223. else if (node.children.length) {
  23224. processChildren(node.children, context);
  23225. }
  23226. if (!isVoidTag(node.tag)) {
  23227. // push closing tag
  23228. context.pushStringPart(`</${node.tag}>`);
  23229. }
  23230. }
  23231. // Because SSR codegen output is completely different from client-side output
  23232. // (e.g. multiple elements can be concatenated into a single template literal
  23233. // instead of each getting a corresponding call), we need to apply an extra
  23234. // transform pass to convert the template AST into a fresh JS AST before
  23235. // passing it to codegen.
  23236. function ssrCodegenTransform(ast, options) {
  23237. const context = createSSRTransformContext(ast, options);
  23238. // inject SFC <style> CSS variables
  23239. // we do this instead of inlining the expression to ensure the vars are
  23240. // only resolved once per render
  23241. if (options.ssrCssVars) {
  23242. const varsExp = processExpression(createSimpleExpression(options.ssrCssVars, false), createTransformContext(createRoot([]), options));
  23243. context.body.push(createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]));
  23244. }
  23245. const isFragment = ast.children.length > 1 && ast.children.some(c => !isText(c));
  23246. processChildren(ast.children, context, isFragment);
  23247. ast.codegenNode = createBlockStatement(context.body);
  23248. // Finalize helpers.
  23249. // We need to separate helpers imported from 'vue' vs. '@vue/server-renderer'
  23250. ast.ssrHelpers = [
  23251. ...ast.helpers.filter(h => h in ssrHelpers),
  23252. ...context.helpers
  23253. ];
  23254. ast.helpers = ast.helpers.filter(h => !(h in ssrHelpers));
  23255. }
  23256. function createSSRTransformContext(root, options, helpers = new Set(), withSlotScopeId = false) {
  23257. const body = [];
  23258. let currentString = null;
  23259. return {
  23260. root,
  23261. options,
  23262. body,
  23263. helpers,
  23264. withSlotScopeId,
  23265. onError: options.onError ||
  23266. (e => {
  23267. throw e;
  23268. }),
  23269. helper(name) {
  23270. helpers.add(name);
  23271. return name;
  23272. },
  23273. pushStringPart(part) {
  23274. if (!currentString) {
  23275. const currentCall = createCallExpression(`_push`);
  23276. body.push(currentCall);
  23277. currentString = createTemplateLiteral([]);
  23278. currentCall.arguments.push(currentString);
  23279. }
  23280. const bufferedElements = currentString.elements;
  23281. const lastItem = bufferedElements[bufferedElements.length - 1];
  23282. if (isString(part) && isString(lastItem)) {
  23283. bufferedElements[bufferedElements.length - 1] += part;
  23284. }
  23285. else {
  23286. bufferedElements.push(part);
  23287. }
  23288. },
  23289. pushStatement(statement) {
  23290. // close current string
  23291. currentString = null;
  23292. body.push(statement);
  23293. }
  23294. };
  23295. }
  23296. function createChildContext(parent, withSlotScopeId = parent.withSlotScopeId) {
  23297. // ensure child inherits parent helpers
  23298. return createSSRTransformContext(parent.root, parent.options, parent.helpers, withSlotScopeId);
  23299. }
  23300. function processChildren(children, context, asFragment = false, disableNestedFragments = false) {
  23301. if (asFragment) {
  23302. context.pushStringPart(`<!--[-->`);
  23303. }
  23304. for (let i = 0; i < children.length; i++) {
  23305. const child = children[i];
  23306. switch (child.type) {
  23307. case 1 /* ELEMENT */:
  23308. switch (child.tagType) {
  23309. case 0 /* ELEMENT */:
  23310. ssrProcessElement(child, context);
  23311. break;
  23312. case 1 /* COMPONENT */:
  23313. ssrProcessComponent(child, context);
  23314. break;
  23315. case 2 /* SLOT */:
  23316. ssrProcessSlotOutlet(child, context);
  23317. break;
  23318. case 3 /* TEMPLATE */:
  23319. // TODO
  23320. break;
  23321. default:
  23322. context.onError(createSSRCompilerError(63 /* X_SSR_INVALID_AST_NODE */, child.loc));
  23323. // make sure we exhaust all possible types
  23324. const exhaustiveCheck = child;
  23325. return exhaustiveCheck;
  23326. }
  23327. break;
  23328. case 2 /* TEXT */:
  23329. context.pushStringPart(escapeHtml(child.content));
  23330. break;
  23331. case 3 /* COMMENT */:
  23332. // no need to escape comment here because the AST can only
  23333. // contain valid comments.
  23334. context.pushStringPart(`<!--${child.content}-->`);
  23335. break;
  23336. case 5 /* INTERPOLATION */:
  23337. context.pushStringPart(createCallExpression(context.helper(SSR_INTERPOLATE), [child.content]));
  23338. break;
  23339. case 9 /* IF */:
  23340. ssrProcessIf(child, context, disableNestedFragments);
  23341. break;
  23342. case 11 /* FOR */:
  23343. ssrProcessFor(child, context, disableNestedFragments);
  23344. break;
  23345. case 10 /* IF_BRANCH */:
  23346. // no-op - handled by ssrProcessIf
  23347. break;
  23348. case 12 /* TEXT_CALL */:
  23349. case 8 /* COMPOUND_EXPRESSION */:
  23350. // no-op - these two types can never appear as template child node since
  23351. // `transformText` is not used during SSR compile.
  23352. break;
  23353. default:
  23354. context.onError(createSSRCompilerError(63 /* X_SSR_INVALID_AST_NODE */, child.loc));
  23355. // make sure we exhaust all possible types
  23356. const exhaustiveCheck = child;
  23357. return exhaustiveCheck;
  23358. }
  23359. }
  23360. if (asFragment) {
  23361. context.pushStringPart(`<!--]-->`);
  23362. }
  23363. }
  23364. function processChildrenAsStatement(children, parentContext, asFragment = false, withSlotScopeId = parentContext.withSlotScopeId) {
  23365. const childContext = createChildContext(parentContext, withSlotScopeId);
  23366. processChildren(children, childContext, asFragment);
  23367. return createBlockStatement(childContext.body);
  23368. }
  23369. const ssrTransformModel = (dir, node, context) => {
  23370. const model = dir.exp;
  23371. function checkDuplicatedValue() {
  23372. const value = findProp(node, 'value');
  23373. if (value) {
  23374. context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  23375. }
  23376. }
  23377. if (node.tagType === 0 /* ELEMENT */) {
  23378. const res = { props: [] };
  23379. const defaultProps = [
  23380. // default value binding for text type inputs
  23381. createObjectProperty(`value`, model)
  23382. ];
  23383. if (node.tag === 'input') {
  23384. const type = findProp(node, 'type');
  23385. if (type) {
  23386. const value = findValueBinding(node);
  23387. if (type.type === 7 /* DIRECTIVE */) {
  23388. // dynamic type
  23389. res.ssrTagParts = [
  23390. createCallExpression(context.helper(SSR_RENDER_DYNAMIC_MODEL), [
  23391. type.exp,
  23392. model,
  23393. value
  23394. ])
  23395. ];
  23396. }
  23397. else if (type.value) {
  23398. // static type
  23399. switch (type.value.content) {
  23400. case 'radio':
  23401. res.props = [
  23402. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  23403. model,
  23404. value
  23405. ]))
  23406. ];
  23407. break;
  23408. case 'checkbox':
  23409. const trueValueBinding = findProp(node, 'true-value');
  23410. if (trueValueBinding) {
  23411. const trueValue = trueValueBinding.type === 6 /* ATTRIBUTE */
  23412. ? JSON.stringify(trueValueBinding.value.content)
  23413. : trueValueBinding.exp;
  23414. res.props = [
  23415. createObjectProperty(`checked`, createCallExpression(context.helper(SSR_LOOSE_EQUAL), [
  23416. model,
  23417. trueValue
  23418. ]))
  23419. ];
  23420. }
  23421. else {
  23422. res.props = [
  23423. createObjectProperty(`checked`, createConditionalExpression(createCallExpression(`Array.isArray`, [model]), createCallExpression(context.helper(SSR_LOOSE_CONTAIN), [
  23424. model,
  23425. value
  23426. ]), model))
  23427. ];
  23428. }
  23429. break;
  23430. case 'file':
  23431. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  23432. break;
  23433. default:
  23434. checkDuplicatedValue();
  23435. res.props = defaultProps;
  23436. break;
  23437. }
  23438. }
  23439. }
  23440. else if (hasDynamicKeyVBind(node)) ;
  23441. else {
  23442. // text type
  23443. checkDuplicatedValue();
  23444. res.props = defaultProps;
  23445. }
  23446. }
  23447. else if (node.tag === 'textarea') {
  23448. checkDuplicatedValue();
  23449. node.children = [createInterpolation(model, model.loc)];
  23450. }
  23451. else if (node.tag === 'select') ;
  23452. else {
  23453. context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  23454. }
  23455. return res;
  23456. }
  23457. else {
  23458. // component v-model
  23459. return transformModel(dir, node, context);
  23460. }
  23461. };
  23462. function findValueBinding(node) {
  23463. const valueBinding = findProp(node, 'value');
  23464. return valueBinding
  23465. ? valueBinding.type === 7 /* DIRECTIVE */
  23466. ? valueBinding.exp
  23467. : createSimpleExpression(valueBinding.value.content, true)
  23468. : createSimpleExpression(`null`, false);
  23469. }
  23470. const ssrTransformShow = (dir, node, context) => {
  23471. if (!dir.exp) {
  23472. context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */));
  23473. }
  23474. return {
  23475. props: [
  23476. createObjectProperty(`style`, createConditionalExpression(dir.exp, createSimpleExpression(`null`, false), createObjectExpression([
  23477. createObjectProperty(`display`, createSimpleExpression(`none`, true))
  23478. ]), false /* no newline */))
  23479. ]
  23480. };
  23481. };
  23482. const hasSingleChild = (node) => node.children.filter(n => n.type !== 3 /* COMMENT */).length === 1;
  23483. const ssrInjectFallthroughAttrs = (node, context) => {
  23484. // _attrs is provided as a function argument.
  23485. // mark it as a known identifier so that it doesn't get prefixed by
  23486. // transformExpression.
  23487. if (node.type === 0 /* ROOT */) {
  23488. context.identifiers._attrs = 1;
  23489. }
  23490. const parent = context.parent;
  23491. if (!parent || parent.type !== 0 /* ROOT */) {
  23492. return;
  23493. }
  23494. if (node.type === 10 /* IF_BRANCH */ && hasSingleChild(node)) {
  23495. injectFallthroughAttrs(node.children[0]);
  23496. }
  23497. else if (hasSingleChild(parent)) {
  23498. injectFallthroughAttrs(node);
  23499. }
  23500. };
  23501. function injectFallthroughAttrs(node) {
  23502. if (node.type === 1 /* ELEMENT */ &&
  23503. (node.tagType === 0 /* ELEMENT */ ||
  23504. node.tagType === 1 /* COMPONENT */) &&
  23505. !findDir(node, 'for')) {
  23506. node.props.push({
  23507. type: 7 /* DIRECTIVE */,
  23508. name: 'bind',
  23509. arg: undefined,
  23510. exp: createSimpleExpression(`_attrs`, false),
  23511. modifiers: [],
  23512. loc: locStub
  23513. });
  23514. }
  23515. }
  23516. const ssrInjectCssVars = (node, context) => {
  23517. if (!context.ssrCssVars) {
  23518. return;
  23519. }
  23520. // _cssVars is initialized once per render function
  23521. // the code is injected in ssrCodegenTransform when creating the
  23522. // ssr transform context
  23523. if (node.type === 0 /* ROOT */) {
  23524. context.identifiers._cssVars = 1;
  23525. }
  23526. const parent = context.parent;
  23527. if (!parent || parent.type !== 0 /* ROOT */) {
  23528. return;
  23529. }
  23530. if (node.type === 10 /* IF_BRANCH */) {
  23531. for (const child of node.children) {
  23532. injectCssVars(child);
  23533. }
  23534. }
  23535. else {
  23536. injectCssVars(node);
  23537. }
  23538. };
  23539. function injectCssVars(node) {
  23540. if (node.type === 1 /* ELEMENT */ &&
  23541. (node.tagType === 0 /* ELEMENT */ ||
  23542. node.tagType === 1 /* COMPONENT */) &&
  23543. !findDir(node, 'for')) {
  23544. if (isBuiltInType(node.tag, 'Suspense')) {
  23545. for (const child of node.children) {
  23546. if (child.type === 1 /* ELEMENT */ &&
  23547. child.tagType === 3 /* TEMPLATE */) {
  23548. // suspense slot
  23549. child.children.forEach(injectCssVars);
  23550. }
  23551. else {
  23552. injectCssVars(child);
  23553. }
  23554. }
  23555. }
  23556. else {
  23557. node.props.push({
  23558. type: 7 /* DIRECTIVE */,
  23559. name: 'bind',
  23560. arg: undefined,
  23561. exp: createSimpleExpression(`_cssVars`, false),
  23562. modifiers: [],
  23563. loc: locStub
  23564. });
  23565. }
  23566. }
  23567. }
  23568. function compile$1(template, options = {}) {
  23569. options = {
  23570. ...options,
  23571. // apply DOM-specific parsing options
  23572. ...parserOptions,
  23573. ssr: true,
  23574. scopeId: options.mode === 'function' ? null : options.scopeId,
  23575. // always prefix since compiler-ssr doesn't have size concern
  23576. prefixIdentifiers: true,
  23577. // disable optimizations that are unnecessary for ssr
  23578. cacheHandlers: false,
  23579. hoistStatic: false
  23580. };
  23581. const ast = baseParse(template, options);
  23582. // Save raw options for AST. This is needed when performing sub-transforms
  23583. // on slot vnode branches.
  23584. rawOptionsMap.set(ast, options);
  23585. transform(ast, {
  23586. ...options,
  23587. nodeTransforms: [
  23588. ssrTransformIf,
  23589. ssrTransformFor,
  23590. trackVForSlotScopes,
  23591. transformExpression,
  23592. ssrTransformSlotOutlet,
  23593. ssrInjectFallthroughAttrs,
  23594. ssrInjectCssVars,
  23595. ssrTransformElement,
  23596. ssrTransformComponent,
  23597. trackSlotScopes,
  23598. transformStyle,
  23599. ...(options.nodeTransforms || []) // user transforms
  23600. ],
  23601. directiveTransforms: {
  23602. // reusing core v-bind
  23603. bind: transformBind,
  23604. // model and show has dedicated SSR handling
  23605. model: ssrTransformModel,
  23606. show: ssrTransformShow,
  23607. // the following are ignored during SSR
  23608. on: noopDirectiveTransform,
  23609. cloak: noopDirectiveTransform,
  23610. once: noopDirectiveTransform,
  23611. ...(options.directiveTransforms || {}) // user transforms
  23612. }
  23613. });
  23614. // traverse the template AST and convert into SSR codegen AST
  23615. // by replacing ast.codegenNode.
  23616. ssrCodegenTransform(ast, options);
  23617. return generate(ast, options);
  23618. }
  23619. var CompilerSSR = /*#__PURE__*/Object.freeze({
  23620. __proto__: null,
  23621. compile: compile$1
  23622. });
  23623. function preprocess({ source, filename, preprocessOptions }, preprocessor) {
  23624. // Consolidate exposes a callback based API, but the callback is in fact
  23625. // called synchronously for most templating engines. In our case, we have to
  23626. // expose a synchronous API so that it is usable in Jest transforms (which
  23627. // have to be sync because they are applied via Node.js require hooks)
  23628. let res = '';
  23629. let err = null;
  23630. preprocessor.render(source, { filename, ...preprocessOptions }, (_err, _res) => {
  23631. if (_err)
  23632. err = _err;
  23633. res = _res;
  23634. });
  23635. if (err)
  23636. throw err;
  23637. return res;
  23638. }
  23639. function compileTemplate(options) {
  23640. const { preprocessLang, preprocessCustomRequire } = options;
  23641. if (
  23642. preprocessLang &&
  23643. !preprocessCustomRequire) {
  23644. throw new Error(`[@vue/compiler-sfc] Template preprocessing in the browser build must ` +
  23645. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  23646. `version of the preprocessor in the shape of { render(): string }.`);
  23647. }
  23648. const preprocessor = preprocessLang
  23649. ? preprocessCustomRequire
  23650. ? preprocessCustomRequire(preprocessLang)
  23651. : require('consolidate')[preprocessLang]
  23652. : false;
  23653. if (preprocessor) {
  23654. try {
  23655. return doCompileTemplate({
  23656. ...options,
  23657. source: preprocess(options, preprocessor)
  23658. });
  23659. }
  23660. catch (e) {
  23661. return {
  23662. code: `export default function render() {}`,
  23663. source: options.source,
  23664. tips: [],
  23665. errors: [e]
  23666. };
  23667. }
  23668. }
  23669. else if (preprocessLang) {
  23670. return {
  23671. code: `export default function render() {}`,
  23672. source: options.source,
  23673. tips: [
  23674. `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
  23675. ],
  23676. errors: [
  23677. `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
  23678. ]
  23679. };
  23680. }
  23681. else {
  23682. return doCompileTemplate(options);
  23683. }
  23684. }
  23685. function doCompileTemplate({ filename, id, scoped, inMap, source, ssr = false, ssrCssVars, isProd = false, compiler = ssr ? CompilerSSR : CompilerDOM, compilerOptions = {}, transformAssetUrls }) {
  23686. const errors = [];
  23687. let nodeTransforms = [];
  23688. if (isObject(transformAssetUrls)) {
  23689. const assetOptions = normalizeOptions(transformAssetUrls);
  23690. nodeTransforms = [
  23691. createAssetUrlTransformWithOptions(assetOptions),
  23692. createSrcsetTransformWithOptions(assetOptions)
  23693. ];
  23694. }
  23695. else if (transformAssetUrls !== false) {
  23696. nodeTransforms = [transformAssetUrl, transformSrcset];
  23697. }
  23698. if (ssr && !ssrCssVars) {
  23699. warnOnce(`compileTemplate is called with \`ssr: true\` but no ` +
  23700. `corresponding \`cssVars\` option.\`.`);
  23701. }
  23702. if (!id) {
  23703. warnOnce(`compileTemplate now requires the \`id\` option.\`.`);
  23704. id = '';
  23705. }
  23706. const shortId = id.replace(/^data-v-/, '');
  23707. const longId = `data-v-${shortId}`;
  23708. let { code, ast, preamble, map } = compiler.compile(source, {
  23709. mode: 'module',
  23710. prefixIdentifiers: true,
  23711. hoistStatic: true,
  23712. cacheHandlers: true,
  23713. ssrCssVars: ssr && ssrCssVars && ssrCssVars.length
  23714. ? genCssVarsFromList(ssrCssVars, shortId, isProd)
  23715. : '',
  23716. scopeId: scoped ? longId : undefined,
  23717. ...compilerOptions,
  23718. nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),
  23719. filename,
  23720. sourceMap: true,
  23721. onError: e => errors.push(e)
  23722. });
  23723. // inMap should be the map produced by ./parse.ts which is a simple line-only
  23724. // mapping. If it is present, we need to adjust the final map and errors to
  23725. // reflect the original line numbers.
  23726. if (inMap) {
  23727. if (map) {
  23728. map = mapLines(inMap, map);
  23729. }
  23730. if (errors.length) {
  23731. patchErrors(errors, source, inMap);
  23732. }
  23733. }
  23734. return { code, ast, preamble, source, errors, tips: [], map };
  23735. }
  23736. function mapLines(oldMap, newMap) {
  23737. if (!oldMap)
  23738. return newMap;
  23739. if (!newMap)
  23740. return oldMap;
  23741. const oldMapConsumer = new SourceMapConsumer$1(oldMap);
  23742. const newMapConsumer = new SourceMapConsumer$1(newMap);
  23743. const mergedMapGenerator = new SourceMapGenerator$2();
  23744. newMapConsumer.eachMapping(m => {
  23745. if (m.originalLine == null) {
  23746. return;
  23747. }
  23748. const origPosInOldMap = oldMapConsumer.originalPositionFor({
  23749. line: m.originalLine,
  23750. column: m.originalColumn
  23751. });
  23752. if (origPosInOldMap.source == null) {
  23753. return;
  23754. }
  23755. mergedMapGenerator.addMapping({
  23756. generated: {
  23757. line: m.generatedLine,
  23758. column: m.generatedColumn
  23759. },
  23760. original: {
  23761. line: origPosInOldMap.line,
  23762. // use current column, since the oldMap produced by @vue/compiler-sfc
  23763. // does not
  23764. column: m.originalColumn
  23765. },
  23766. source: origPosInOldMap.source,
  23767. name: origPosInOldMap.name
  23768. });
  23769. });
  23770. // source-map's type definition is incomplete
  23771. const generator = mergedMapGenerator;
  23772. oldMapConsumer.sources.forEach((sourceFile) => {
  23773. generator._sources.add(sourceFile);
  23774. const sourceContent = oldMapConsumer.sourceContentFor(sourceFile);
  23775. if (sourceContent != null) {
  23776. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  23777. }
  23778. });
  23779. generator._sourceRoot = oldMap.sourceRoot;
  23780. generator._file = oldMap.file;
  23781. return generator.toJSON();
  23782. }
  23783. function patchErrors(errors, source, inMap) {
  23784. const originalSource = inMap.sourcesContent[0];
  23785. const offset = originalSource.indexOf(source);
  23786. const lineOffset = originalSource.slice(0, offset).split(/\r?\n/).length - 1;
  23787. errors.forEach(err => {
  23788. if (err.loc) {
  23789. err.loc.start.line += lineOffset;
  23790. err.loc.start.offset += offset;
  23791. if (err.loc.end !== err.loc.start) {
  23792. err.loc.end.line += lineOffset;
  23793. err.loc.end.offset += offset;
  23794. }
  23795. }
  23796. });
  23797. }
  23798. var trimPlugin = postcss__default.plugin('trim', () => (css) => {
  23799. css.walk(({ type, raws }) => {
  23800. if (type === 'rule' || type === 'atrule') {
  23801. if (raws.before)
  23802. raws.before = '\n';
  23803. if (raws.after)
  23804. raws.after = '\n';
  23805. }
  23806. });
  23807. });
  23808. var indexesOf = function (ary, item) {
  23809. var i = -1, indexes = [];
  23810. while((i = ary.indexOf(item, i + 1)) !== -1)
  23811. indexes.push(i);
  23812. return indexes
  23813. };
  23814. function unique_pred(list, compare) {
  23815. var ptr = 1
  23816. , len = list.length
  23817. , a=list[0], b=list[0];
  23818. for(var i=1; i<len; ++i) {
  23819. b = a;
  23820. a = list[i];
  23821. if(compare(a, b)) {
  23822. if(i === ptr) {
  23823. ptr++;
  23824. continue
  23825. }
  23826. list[ptr++] = a;
  23827. }
  23828. }
  23829. list.length = ptr;
  23830. return list
  23831. }
  23832. function unique_eq(list) {
  23833. var ptr = 1
  23834. , len = list.length
  23835. , a=list[0], b = list[0];
  23836. for(var i=1; i<len; ++i, b=a) {
  23837. b = a;
  23838. a = list[i];
  23839. if(a !== b) {
  23840. if(i === ptr) {
  23841. ptr++;
  23842. continue
  23843. }
  23844. list[ptr++] = a;
  23845. }
  23846. }
  23847. list.length = ptr;
  23848. return list
  23849. }
  23850. function unique(list, compare, sorted) {
  23851. if(list.length === 0) {
  23852. return list
  23853. }
  23854. if(compare) {
  23855. if(!sorted) {
  23856. list.sort(compare);
  23857. }
  23858. return unique_pred(list, compare)
  23859. }
  23860. if(!sorted) {
  23861. list.sort();
  23862. }
  23863. return unique_eq(list)
  23864. }
  23865. var uniq = unique;
  23866. var unesc_1 = createCommonjsModule(function (module, exports) {
  23867. exports.__esModule = true;
  23868. exports.default = unesc;
  23869. var whitespace = '[\\x20\\t\\r\\n\\f]';
  23870. var unescapeRegExp = new RegExp('\\\\([\\da-f]{1,6}' + whitespace + '?|(' + whitespace + ')|.)', 'ig');
  23871. function unesc(str) {
  23872. return str.replace(unescapeRegExp, function (_, escaped, escapedWhitespace) {
  23873. var high = '0x' + escaped - 0x10000; // NaN means non-codepoint
  23874. // Workaround erroneous numeric interpretation of +"0x"
  23875. // eslint-disable-next-line no-self-compare
  23876. return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint
  23877. String.fromCharCode(high + 0x10000) : // Supplemental Plane codepoint (surrogate pair)
  23878. String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
  23879. });
  23880. }
  23881. module.exports = exports.default;
  23882. });
  23883. var getProp_1 = createCommonjsModule(function (module, exports) {
  23884. exports.__esModule = true;
  23885. exports.default = getProp;
  23886. function getProp(obj) {
  23887. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  23888. props[_key - 1] = arguments[_key];
  23889. }
  23890. while (props.length > 0) {
  23891. var prop = props.shift();
  23892. if (!obj[prop]) {
  23893. return undefined;
  23894. }
  23895. obj = obj[prop];
  23896. }
  23897. return obj;
  23898. }
  23899. module.exports = exports.default;
  23900. });
  23901. var ensureObject_1 = createCommonjsModule(function (module, exports) {
  23902. exports.__esModule = true;
  23903. exports.default = ensureObject;
  23904. function ensureObject(obj) {
  23905. for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  23906. props[_key - 1] = arguments[_key];
  23907. }
  23908. while (props.length > 0) {
  23909. var prop = props.shift();
  23910. if (!obj[prop]) {
  23911. obj[prop] = {};
  23912. }
  23913. obj = obj[prop];
  23914. }
  23915. }
  23916. module.exports = exports.default;
  23917. });
  23918. var stripComments_1 = createCommonjsModule(function (module, exports) {
  23919. exports.__esModule = true;
  23920. exports.default = stripComments;
  23921. function stripComments(str) {
  23922. var s = "";
  23923. var commentStart = str.indexOf("/*");
  23924. var lastEnd = 0;
  23925. while (commentStart >= 0) {
  23926. s = s + str.slice(lastEnd, commentStart);
  23927. var commentEnd = str.indexOf("*/", commentStart + 2);
  23928. if (commentEnd < 0) {
  23929. return s;
  23930. }
  23931. lastEnd = commentEnd + 2;
  23932. commentStart = str.indexOf("/*", lastEnd);
  23933. }
  23934. s = s + str.slice(lastEnd);
  23935. return s;
  23936. }
  23937. module.exports = exports.default;
  23938. });
  23939. var util$1 = createCommonjsModule(function (module, exports) {
  23940. exports.__esModule = true;
  23941. exports.stripComments = exports.ensureObject = exports.getProp = exports.unesc = void 0;
  23942. var _unesc = _interopRequireDefault(unesc_1);
  23943. exports.unesc = _unesc.default;
  23944. var _getProp = _interopRequireDefault(getProp_1);
  23945. exports.getProp = _getProp.default;
  23946. var _ensureObject = _interopRequireDefault(ensureObject_1);
  23947. exports.ensureObject = _ensureObject.default;
  23948. var _stripComments = _interopRequireDefault(stripComments_1);
  23949. exports.stripComments = _stripComments.default;
  23950. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  23951. });
  23952. var node = createCommonjsModule(function (module, exports) {
  23953. exports.__esModule = true;
  23954. exports.default = void 0;
  23955. 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); } }
  23956. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  23957. var cloneNode = function cloneNode(obj, parent) {
  23958. if (typeof obj !== 'object' || obj === null) {
  23959. return obj;
  23960. }
  23961. var cloned = new obj.constructor();
  23962. for (var i in obj) {
  23963. if (!obj.hasOwnProperty(i)) {
  23964. continue;
  23965. }
  23966. var value = obj[i];
  23967. var type = typeof value;
  23968. if (i === 'parent' && type === 'object') {
  23969. if (parent) {
  23970. cloned[i] = parent;
  23971. }
  23972. } else if (value instanceof Array) {
  23973. cloned[i] = value.map(function (j) {
  23974. return cloneNode(j, cloned);
  23975. });
  23976. } else {
  23977. cloned[i] = cloneNode(value, cloned);
  23978. }
  23979. }
  23980. return cloned;
  23981. };
  23982. var Node =
  23983. /*#__PURE__*/
  23984. function () {
  23985. function Node(opts) {
  23986. if (opts === void 0) {
  23987. opts = {};
  23988. }
  23989. Object.assign(this, opts);
  23990. this.spaces = this.spaces || {};
  23991. this.spaces.before = this.spaces.before || '';
  23992. this.spaces.after = this.spaces.after || '';
  23993. }
  23994. var _proto = Node.prototype;
  23995. _proto.remove = function remove() {
  23996. if (this.parent) {
  23997. this.parent.removeChild(this);
  23998. }
  23999. this.parent = undefined;
  24000. return this;
  24001. };
  24002. _proto.replaceWith = function replaceWith() {
  24003. if (this.parent) {
  24004. for (var index in arguments) {
  24005. this.parent.insertBefore(this, arguments[index]);
  24006. }
  24007. this.remove();
  24008. }
  24009. return this;
  24010. };
  24011. _proto.next = function next() {
  24012. return this.parent.at(this.parent.index(this) + 1);
  24013. };
  24014. _proto.prev = function prev() {
  24015. return this.parent.at(this.parent.index(this) - 1);
  24016. };
  24017. _proto.clone = function clone(overrides) {
  24018. if (overrides === void 0) {
  24019. overrides = {};
  24020. }
  24021. var cloned = cloneNode(this);
  24022. for (var name in overrides) {
  24023. cloned[name] = overrides[name];
  24024. }
  24025. return cloned;
  24026. }
  24027. /**
  24028. * Some non-standard syntax doesn't follow normal escaping rules for css.
  24029. * This allows non standard syntax to be appended to an existing property
  24030. * by specifying the escaped value. By specifying the escaped value,
  24031. * illegal characters are allowed to be directly inserted into css output.
  24032. * @param {string} name the property to set
  24033. * @param {any} value the unescaped value of the property
  24034. * @param {string} valueEscaped optional. the escaped value of the property.
  24035. */
  24036. ;
  24037. _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
  24038. if (!this.raws) {
  24039. this.raws = {};
  24040. }
  24041. var originalValue = this[name];
  24042. var originalEscaped = this.raws[name];
  24043. this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
  24044. if (originalEscaped || valueEscaped !== value) {
  24045. this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
  24046. } else {
  24047. delete this.raws[name]; // delete any escaped value that was created by the setter.
  24048. }
  24049. }
  24050. /**
  24051. * Some non-standard syntax doesn't follow normal escaping rules for css.
  24052. * This allows the escaped value to be specified directly, allowing illegal
  24053. * characters to be directly inserted into css output.
  24054. * @param {string} name the property to set
  24055. * @param {any} value the unescaped value of the property
  24056. * @param {string} valueEscaped the escaped value of the property.
  24057. */
  24058. ;
  24059. _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
  24060. if (!this.raws) {
  24061. this.raws = {};
  24062. }
  24063. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  24064. this.raws[name] = valueEscaped;
  24065. }
  24066. /**
  24067. * When you want a value to passed through to CSS directly. This method
  24068. * deletes the corresponding raw value causing the stringifier to fallback
  24069. * to the unescaped value.
  24070. * @param {string} name the property to set.
  24071. * @param {any} value The value that is both escaped and unescaped.
  24072. */
  24073. ;
  24074. _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
  24075. this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
  24076. if (this.raws) {
  24077. delete this.raws[name];
  24078. }
  24079. }
  24080. /**
  24081. *
  24082. * @param {number} line The number (starting with 1)
  24083. * @param {number} column The column number (starting with 1)
  24084. */
  24085. ;
  24086. _proto.isAtPosition = function isAtPosition(line, column) {
  24087. if (this.source && this.source.start && this.source.end) {
  24088. if (this.source.start.line > line) {
  24089. return false;
  24090. }
  24091. if (this.source.end.line < line) {
  24092. return false;
  24093. }
  24094. if (this.source.start.line === line && this.source.start.column > column) {
  24095. return false;
  24096. }
  24097. if (this.source.end.line === line && this.source.end.column < column) {
  24098. return false;
  24099. }
  24100. return true;
  24101. }
  24102. return undefined;
  24103. };
  24104. _proto.stringifyProperty = function stringifyProperty(name) {
  24105. return this.raws && this.raws[name] || this[name];
  24106. };
  24107. _proto.valueToString = function valueToString() {
  24108. return String(this.stringifyProperty("value"));
  24109. };
  24110. _proto.toString = function toString() {
  24111. return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join('');
  24112. };
  24113. _createClass(Node, [{
  24114. key: "rawSpaceBefore",
  24115. get: function get() {
  24116. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
  24117. if (rawSpace === undefined) {
  24118. rawSpace = this.spaces && this.spaces.before;
  24119. }
  24120. return rawSpace || "";
  24121. },
  24122. set: function set(raw) {
  24123. (0, util$1.ensureObject)(this, "raws", "spaces");
  24124. this.raws.spaces.before = raw;
  24125. }
  24126. }, {
  24127. key: "rawSpaceAfter",
  24128. get: function get() {
  24129. var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
  24130. if (rawSpace === undefined) {
  24131. rawSpace = this.spaces.after;
  24132. }
  24133. return rawSpace || "";
  24134. },
  24135. set: function set(raw) {
  24136. (0, util$1.ensureObject)(this, "raws", "spaces");
  24137. this.raws.spaces.after = raw;
  24138. }
  24139. }]);
  24140. return Node;
  24141. }();
  24142. exports.default = Node;
  24143. module.exports = exports.default;
  24144. });
  24145. var types$2 = createCommonjsModule(function (module, exports) {
  24146. exports.__esModule = true;
  24147. 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;
  24148. var TAG = 'tag';
  24149. exports.TAG = TAG;
  24150. var STRING = 'string';
  24151. exports.STRING = STRING;
  24152. var SELECTOR = 'selector';
  24153. exports.SELECTOR = SELECTOR;
  24154. var ROOT = 'root';
  24155. exports.ROOT = ROOT;
  24156. var PSEUDO = 'pseudo';
  24157. exports.PSEUDO = PSEUDO;
  24158. var NESTING = 'nesting';
  24159. exports.NESTING = NESTING;
  24160. var ID = 'id';
  24161. exports.ID = ID;
  24162. var COMMENT = 'comment';
  24163. exports.COMMENT = COMMENT;
  24164. var COMBINATOR = 'combinator';
  24165. exports.COMBINATOR = COMBINATOR;
  24166. var CLASS = 'class';
  24167. exports.CLASS = CLASS;
  24168. var ATTRIBUTE = 'attribute';
  24169. exports.ATTRIBUTE = ATTRIBUTE;
  24170. var UNIVERSAL = 'universal';
  24171. exports.UNIVERSAL = UNIVERSAL;
  24172. });
  24173. var container = createCommonjsModule(function (module, exports) {
  24174. exports.__esModule = true;
  24175. exports.default = void 0;
  24176. var _node = _interopRequireDefault(node);
  24177. var types = _interopRequireWildcard(types$2);
  24178. 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; } }
  24179. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24180. 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); } }
  24181. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  24182. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24183. var Container =
  24184. /*#__PURE__*/
  24185. function (_Node) {
  24186. _inheritsLoose(Container, _Node);
  24187. function Container(opts) {
  24188. var _this;
  24189. _this = _Node.call(this, opts) || this;
  24190. if (!_this.nodes) {
  24191. _this.nodes = [];
  24192. }
  24193. return _this;
  24194. }
  24195. var _proto = Container.prototype;
  24196. _proto.append = function append(selector) {
  24197. selector.parent = this;
  24198. this.nodes.push(selector);
  24199. return this;
  24200. };
  24201. _proto.prepend = function prepend(selector) {
  24202. selector.parent = this;
  24203. this.nodes.unshift(selector);
  24204. return this;
  24205. };
  24206. _proto.at = function at(index) {
  24207. return this.nodes[index];
  24208. };
  24209. _proto.index = function index(child) {
  24210. if (typeof child === 'number') {
  24211. return child;
  24212. }
  24213. return this.nodes.indexOf(child);
  24214. };
  24215. _proto.removeChild = function removeChild(child) {
  24216. child = this.index(child);
  24217. this.at(child).parent = undefined;
  24218. this.nodes.splice(child, 1);
  24219. var index;
  24220. for (var id in this.indexes) {
  24221. index = this.indexes[id];
  24222. if (index >= child) {
  24223. this.indexes[id] = index - 1;
  24224. }
  24225. }
  24226. return this;
  24227. };
  24228. _proto.removeAll = function removeAll() {
  24229. for (var _iterator = this.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  24230. var _ref;
  24231. if (_isArray) {
  24232. if (_i >= _iterator.length) break;
  24233. _ref = _iterator[_i++];
  24234. } else {
  24235. _i = _iterator.next();
  24236. if (_i.done) break;
  24237. _ref = _i.value;
  24238. }
  24239. var node = _ref;
  24240. node.parent = undefined;
  24241. }
  24242. this.nodes = [];
  24243. return this;
  24244. };
  24245. _proto.empty = function empty() {
  24246. return this.removeAll();
  24247. };
  24248. _proto.insertAfter = function insertAfter(oldNode, newNode) {
  24249. newNode.parent = this;
  24250. var oldIndex = this.index(oldNode);
  24251. this.nodes.splice(oldIndex + 1, 0, newNode);
  24252. newNode.parent = this;
  24253. var index;
  24254. for (var id in this.indexes) {
  24255. index = this.indexes[id];
  24256. if (oldIndex <= index) {
  24257. this.indexes[id] = index + 1;
  24258. }
  24259. }
  24260. return this;
  24261. };
  24262. _proto.insertBefore = function insertBefore(oldNode, newNode) {
  24263. newNode.parent = this;
  24264. var oldIndex = this.index(oldNode);
  24265. this.nodes.splice(oldIndex, 0, newNode);
  24266. newNode.parent = this;
  24267. var index;
  24268. for (var id in this.indexes) {
  24269. index = this.indexes[id];
  24270. if (index <= oldIndex) {
  24271. this.indexes[id] = index + 1;
  24272. }
  24273. }
  24274. return this;
  24275. };
  24276. _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
  24277. var found = undefined;
  24278. this.each(function (node) {
  24279. if (node.atPosition) {
  24280. var foundChild = node.atPosition(line, col);
  24281. if (foundChild) {
  24282. found = foundChild;
  24283. return false;
  24284. }
  24285. } else if (node.isAtPosition(line, col)) {
  24286. found = node;
  24287. return false;
  24288. }
  24289. });
  24290. return found;
  24291. }
  24292. /**
  24293. * Return the most specific node at the line and column number given.
  24294. * The source location is based on the original parsed location, locations aren't
  24295. * updated as selector nodes are mutated.
  24296. *
  24297. * Note that this location is relative to the location of the first character
  24298. * of the selector, and not the location of the selector in the overall document
  24299. * when used in conjunction with postcss.
  24300. *
  24301. * If not found, returns undefined.
  24302. * @param {number} line The line number of the node to find. (1-based index)
  24303. * @param {number} col The column number of the node to find. (1-based index)
  24304. */
  24305. ;
  24306. _proto.atPosition = function atPosition(line, col) {
  24307. if (this.isAtPosition(line, col)) {
  24308. return this._findChildAtPosition(line, col) || this;
  24309. } else {
  24310. return undefined;
  24311. }
  24312. };
  24313. _proto._inferEndPosition = function _inferEndPosition() {
  24314. if (this.last && this.last.source && this.last.source.end) {
  24315. this.source = this.source || {};
  24316. this.source.end = this.source.end || {};
  24317. Object.assign(this.source.end, this.last.source.end);
  24318. }
  24319. };
  24320. _proto.each = function each(callback) {
  24321. if (!this.lastEach) {
  24322. this.lastEach = 0;
  24323. }
  24324. if (!this.indexes) {
  24325. this.indexes = {};
  24326. }
  24327. this.lastEach++;
  24328. var id = this.lastEach;
  24329. this.indexes[id] = 0;
  24330. if (!this.length) {
  24331. return undefined;
  24332. }
  24333. var index, result;
  24334. while (this.indexes[id] < this.length) {
  24335. index = this.indexes[id];
  24336. result = callback(this.at(index), index);
  24337. if (result === false) {
  24338. break;
  24339. }
  24340. this.indexes[id] += 1;
  24341. }
  24342. delete this.indexes[id];
  24343. if (result === false) {
  24344. return false;
  24345. }
  24346. };
  24347. _proto.walk = function walk(callback) {
  24348. return this.each(function (node, i) {
  24349. var result = callback(node, i);
  24350. if (result !== false && node.length) {
  24351. result = node.walk(callback);
  24352. }
  24353. if (result === false) {
  24354. return false;
  24355. }
  24356. });
  24357. };
  24358. _proto.walkAttributes = function walkAttributes(callback) {
  24359. var _this2 = this;
  24360. return this.walk(function (selector) {
  24361. if (selector.type === types.ATTRIBUTE) {
  24362. return callback.call(_this2, selector);
  24363. }
  24364. });
  24365. };
  24366. _proto.walkClasses = function walkClasses(callback) {
  24367. var _this3 = this;
  24368. return this.walk(function (selector) {
  24369. if (selector.type === types.CLASS) {
  24370. return callback.call(_this3, selector);
  24371. }
  24372. });
  24373. };
  24374. _proto.walkCombinators = function walkCombinators(callback) {
  24375. var _this4 = this;
  24376. return this.walk(function (selector) {
  24377. if (selector.type === types.COMBINATOR) {
  24378. return callback.call(_this4, selector);
  24379. }
  24380. });
  24381. };
  24382. _proto.walkComments = function walkComments(callback) {
  24383. var _this5 = this;
  24384. return this.walk(function (selector) {
  24385. if (selector.type === types.COMMENT) {
  24386. return callback.call(_this5, selector);
  24387. }
  24388. });
  24389. };
  24390. _proto.walkIds = function walkIds(callback) {
  24391. var _this6 = this;
  24392. return this.walk(function (selector) {
  24393. if (selector.type === types.ID) {
  24394. return callback.call(_this6, selector);
  24395. }
  24396. });
  24397. };
  24398. _proto.walkNesting = function walkNesting(callback) {
  24399. var _this7 = this;
  24400. return this.walk(function (selector) {
  24401. if (selector.type === types.NESTING) {
  24402. return callback.call(_this7, selector);
  24403. }
  24404. });
  24405. };
  24406. _proto.walkPseudos = function walkPseudos(callback) {
  24407. var _this8 = this;
  24408. return this.walk(function (selector) {
  24409. if (selector.type === types.PSEUDO) {
  24410. return callback.call(_this8, selector);
  24411. }
  24412. });
  24413. };
  24414. _proto.walkTags = function walkTags(callback) {
  24415. var _this9 = this;
  24416. return this.walk(function (selector) {
  24417. if (selector.type === types.TAG) {
  24418. return callback.call(_this9, selector);
  24419. }
  24420. });
  24421. };
  24422. _proto.walkUniversals = function walkUniversals(callback) {
  24423. var _this10 = this;
  24424. return this.walk(function (selector) {
  24425. if (selector.type === types.UNIVERSAL) {
  24426. return callback.call(_this10, selector);
  24427. }
  24428. });
  24429. };
  24430. _proto.split = function split(callback) {
  24431. var _this11 = this;
  24432. var current = [];
  24433. return this.reduce(function (memo, node, index) {
  24434. var split = callback.call(_this11, node);
  24435. current.push(node);
  24436. if (split) {
  24437. memo.push(current);
  24438. current = [];
  24439. } else if (index === _this11.length - 1) {
  24440. memo.push(current);
  24441. }
  24442. return memo;
  24443. }, []);
  24444. };
  24445. _proto.map = function map(callback) {
  24446. return this.nodes.map(callback);
  24447. };
  24448. _proto.reduce = function reduce(callback, memo) {
  24449. return this.nodes.reduce(callback, memo);
  24450. };
  24451. _proto.every = function every(callback) {
  24452. return this.nodes.every(callback);
  24453. };
  24454. _proto.some = function some(callback) {
  24455. return this.nodes.some(callback);
  24456. };
  24457. _proto.filter = function filter(callback) {
  24458. return this.nodes.filter(callback);
  24459. };
  24460. _proto.sort = function sort(callback) {
  24461. return this.nodes.sort(callback);
  24462. };
  24463. _proto.toString = function toString() {
  24464. return this.map(String).join('');
  24465. };
  24466. _createClass(Container, [{
  24467. key: "first",
  24468. get: function get() {
  24469. return this.at(0);
  24470. }
  24471. }, {
  24472. key: "last",
  24473. get: function get() {
  24474. return this.at(this.length - 1);
  24475. }
  24476. }, {
  24477. key: "length",
  24478. get: function get() {
  24479. return this.nodes.length;
  24480. }
  24481. }]);
  24482. return Container;
  24483. }(_node.default);
  24484. exports.default = Container;
  24485. module.exports = exports.default;
  24486. });
  24487. var root = createCommonjsModule(function (module, exports) {
  24488. exports.__esModule = true;
  24489. exports.default = void 0;
  24490. var _container = _interopRequireDefault(container);
  24491. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24492. 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); } }
  24493. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  24494. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24495. var Root =
  24496. /*#__PURE__*/
  24497. function (_Container) {
  24498. _inheritsLoose(Root, _Container);
  24499. function Root(opts) {
  24500. var _this;
  24501. _this = _Container.call(this, opts) || this;
  24502. _this.type = types$2.ROOT;
  24503. return _this;
  24504. }
  24505. var _proto = Root.prototype;
  24506. _proto.toString = function toString() {
  24507. var str = this.reduce(function (memo, selector) {
  24508. memo.push(String(selector));
  24509. return memo;
  24510. }, []).join(',');
  24511. return this.trailingComma ? str + ',' : str;
  24512. };
  24513. _proto.error = function error(message, options) {
  24514. if (this._error) {
  24515. return this._error(message, options);
  24516. } else {
  24517. return new Error(message);
  24518. }
  24519. };
  24520. _createClass(Root, [{
  24521. key: "errorGenerator",
  24522. set: function set(handler) {
  24523. this._error = handler;
  24524. }
  24525. }]);
  24526. return Root;
  24527. }(_container.default);
  24528. exports.default = Root;
  24529. module.exports = exports.default;
  24530. });
  24531. var selector = createCommonjsModule(function (module, exports) {
  24532. exports.__esModule = true;
  24533. exports.default = void 0;
  24534. var _container = _interopRequireDefault(container);
  24535. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24536. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24537. var Selector =
  24538. /*#__PURE__*/
  24539. function (_Container) {
  24540. _inheritsLoose(Selector, _Container);
  24541. function Selector(opts) {
  24542. var _this;
  24543. _this = _Container.call(this, opts) || this;
  24544. _this.type = types$2.SELECTOR;
  24545. return _this;
  24546. }
  24547. return Selector;
  24548. }(_container.default);
  24549. exports.default = Selector;
  24550. module.exports = exports.default;
  24551. });
  24552. /*! https://mths.be/cssesc v3.0.0 by @mathias */
  24553. var object = {};
  24554. var hasOwnProperty$1 = object.hasOwnProperty;
  24555. var merge = function merge(options, defaults) {
  24556. if (!options) {
  24557. return defaults;
  24558. }
  24559. var result = {};
  24560. for (var key in defaults) {
  24561. // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
  24562. // only recognized option names are used.
  24563. result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key];
  24564. }
  24565. return result;
  24566. };
  24567. var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
  24568. var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
  24569. var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
  24570. // https://mathiasbynens.be/notes/css-escapes#css
  24571. var cssesc = function cssesc(string, options) {
  24572. options = merge(options, cssesc.options);
  24573. if (options.quotes != 'single' && options.quotes != 'double') {
  24574. options.quotes = 'single';
  24575. }
  24576. var quote = options.quotes == 'double' ? '"' : '\'';
  24577. var isIdentifier = options.isIdentifier;
  24578. var firstChar = string.charAt(0);
  24579. var output = '';
  24580. var counter = 0;
  24581. var length = string.length;
  24582. while (counter < length) {
  24583. var character = string.charAt(counter++);
  24584. var codePoint = character.charCodeAt();
  24585. var value = void 0;
  24586. // If it’s not a printable ASCII character…
  24587. if (codePoint < 0x20 || codePoint > 0x7E) {
  24588. if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
  24589. // It’s a high surrogate, and there is a next character.
  24590. var extra = string.charCodeAt(counter++);
  24591. if ((extra & 0xFC00) == 0xDC00) {
  24592. // next character is low surrogate
  24593. codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
  24594. } else {
  24595. // It’s an unmatched surrogate; only append this code unit, in case
  24596. // the next code unit is the high surrogate of a surrogate pair.
  24597. counter--;
  24598. }
  24599. }
  24600. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  24601. } else {
  24602. if (options.escapeEverything) {
  24603. if (regexAnySingleEscape.test(character)) {
  24604. value = '\\' + character;
  24605. } else {
  24606. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  24607. }
  24608. } else if (/[\t\n\f\r\x0B]/.test(character)) {
  24609. value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
  24610. } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
  24611. value = '\\' + character;
  24612. } else {
  24613. value = character;
  24614. }
  24615. }
  24616. output += value;
  24617. }
  24618. if (isIdentifier) {
  24619. if (/^-[-\d]/.test(output)) {
  24620. output = '\\-' + output.slice(1);
  24621. } else if (/\d/.test(firstChar)) {
  24622. output = '\\3' + firstChar + ' ' + output.slice(1);
  24623. }
  24624. }
  24625. // Remove spaces after `\HEX` escapes that are not followed by a hex digit,
  24626. // since they’re redundant. Note that this is only possible if the escape
  24627. // sequence isn’t preceded by an odd number of backslashes.
  24628. output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
  24629. if ($1 && $1.length % 2) {
  24630. // It’s not safe to remove the space, so don’t.
  24631. return $0;
  24632. }
  24633. // Strip the space.
  24634. return ($1 || '') + $2;
  24635. });
  24636. if (!isIdentifier && options.wrap) {
  24637. return quote + output + quote;
  24638. }
  24639. return output;
  24640. };
  24641. // Expose default options (so they can be overridden globally).
  24642. cssesc.options = {
  24643. 'escapeEverything': false,
  24644. 'isIdentifier': false,
  24645. 'quotes': 'single',
  24646. 'wrap': false
  24647. };
  24648. cssesc.version = '3.0.0';
  24649. var cssesc_1 = cssesc;
  24650. var className = createCommonjsModule(function (module, exports) {
  24651. exports.__esModule = true;
  24652. exports.default = void 0;
  24653. var _cssesc = _interopRequireDefault(cssesc_1);
  24654. var _node = _interopRequireDefault(node);
  24655. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24656. 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); } }
  24657. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  24658. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24659. var ClassName =
  24660. /*#__PURE__*/
  24661. function (_Node) {
  24662. _inheritsLoose(ClassName, _Node);
  24663. function ClassName(opts) {
  24664. var _this;
  24665. _this = _Node.call(this, opts) || this;
  24666. _this.type = types$2.CLASS;
  24667. _this._constructed = true;
  24668. return _this;
  24669. }
  24670. var _proto = ClassName.prototype;
  24671. _proto.valueToString = function valueToString() {
  24672. return '.' + _Node.prototype.valueToString.call(this);
  24673. };
  24674. _createClass(ClassName, [{
  24675. key: "value",
  24676. set: function set(v) {
  24677. if (this._constructed) {
  24678. var escaped = (0, _cssesc.default)(v, {
  24679. isIdentifier: true
  24680. });
  24681. if (escaped !== v) {
  24682. (0, util$1.ensureObject)(this, "raws");
  24683. this.raws.value = escaped;
  24684. } else if (this.raws) {
  24685. delete this.raws.value;
  24686. }
  24687. }
  24688. this._value = v;
  24689. },
  24690. get: function get() {
  24691. return this._value;
  24692. }
  24693. }]);
  24694. return ClassName;
  24695. }(_node.default);
  24696. exports.default = ClassName;
  24697. module.exports = exports.default;
  24698. });
  24699. var comment = createCommonjsModule(function (module, exports) {
  24700. exports.__esModule = true;
  24701. exports.default = void 0;
  24702. var _node = _interopRequireDefault(node);
  24703. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24704. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24705. var Comment =
  24706. /*#__PURE__*/
  24707. function (_Node) {
  24708. _inheritsLoose(Comment, _Node);
  24709. function Comment(opts) {
  24710. var _this;
  24711. _this = _Node.call(this, opts) || this;
  24712. _this.type = types$2.COMMENT;
  24713. return _this;
  24714. }
  24715. return Comment;
  24716. }(_node.default);
  24717. exports.default = Comment;
  24718. module.exports = exports.default;
  24719. });
  24720. var id = createCommonjsModule(function (module, exports) {
  24721. exports.__esModule = true;
  24722. exports.default = void 0;
  24723. var _node = _interopRequireDefault(node);
  24724. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24725. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24726. var ID =
  24727. /*#__PURE__*/
  24728. function (_Node) {
  24729. _inheritsLoose(ID, _Node);
  24730. function ID(opts) {
  24731. var _this;
  24732. _this = _Node.call(this, opts) || this;
  24733. _this.type = types$2.ID;
  24734. return _this;
  24735. }
  24736. var _proto = ID.prototype;
  24737. _proto.valueToString = function valueToString() {
  24738. return '#' + _Node.prototype.valueToString.call(this);
  24739. };
  24740. return ID;
  24741. }(_node.default);
  24742. exports.default = ID;
  24743. module.exports = exports.default;
  24744. });
  24745. var namespace = createCommonjsModule(function (module, exports) {
  24746. exports.__esModule = true;
  24747. exports.default = void 0;
  24748. var _cssesc = _interopRequireDefault(cssesc_1);
  24749. var _node = _interopRequireDefault(node);
  24750. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24751. 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); } }
  24752. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  24753. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24754. var Namespace =
  24755. /*#__PURE__*/
  24756. function (_Node) {
  24757. _inheritsLoose(Namespace, _Node);
  24758. function Namespace() {
  24759. return _Node.apply(this, arguments) || this;
  24760. }
  24761. var _proto = Namespace.prototype;
  24762. _proto.qualifiedName = function qualifiedName(value) {
  24763. if (this.namespace) {
  24764. return this.namespaceString + "|" + value;
  24765. } else {
  24766. return value;
  24767. }
  24768. };
  24769. _proto.valueToString = function valueToString() {
  24770. return this.qualifiedName(_Node.prototype.valueToString.call(this));
  24771. };
  24772. _createClass(Namespace, [{
  24773. key: "namespace",
  24774. get: function get() {
  24775. return this._namespace;
  24776. },
  24777. set: function set(namespace) {
  24778. if (namespace === true || namespace === "*" || namespace === "&") {
  24779. this._namespace = namespace;
  24780. if (this.raws) {
  24781. delete this.raws.namespace;
  24782. }
  24783. return;
  24784. }
  24785. var escaped = (0, _cssesc.default)(namespace, {
  24786. isIdentifier: true
  24787. });
  24788. this._namespace = namespace;
  24789. if (escaped !== namespace) {
  24790. (0, util$1.ensureObject)(this, "raws");
  24791. this.raws.namespace = escaped;
  24792. } else if (this.raws) {
  24793. delete this.raws.namespace;
  24794. }
  24795. }
  24796. }, {
  24797. key: "ns",
  24798. get: function get() {
  24799. return this._namespace;
  24800. },
  24801. set: function set(namespace) {
  24802. this.namespace = namespace;
  24803. }
  24804. }, {
  24805. key: "namespaceString",
  24806. get: function get() {
  24807. if (this.namespace) {
  24808. var ns = this.stringifyProperty("namespace");
  24809. if (ns === true) {
  24810. return '';
  24811. } else {
  24812. return ns;
  24813. }
  24814. } else {
  24815. return '';
  24816. }
  24817. }
  24818. }]);
  24819. return Namespace;
  24820. }(_node.default);
  24821. exports.default = Namespace;
  24822. module.exports = exports.default;
  24823. });
  24824. var tag = createCommonjsModule(function (module, exports) {
  24825. exports.__esModule = true;
  24826. exports.default = void 0;
  24827. var _namespace = _interopRequireDefault(namespace);
  24828. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24829. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24830. var Tag =
  24831. /*#__PURE__*/
  24832. function (_Namespace) {
  24833. _inheritsLoose(Tag, _Namespace);
  24834. function Tag(opts) {
  24835. var _this;
  24836. _this = _Namespace.call(this, opts) || this;
  24837. _this.type = types$2.TAG;
  24838. return _this;
  24839. }
  24840. return Tag;
  24841. }(_namespace.default);
  24842. exports.default = Tag;
  24843. module.exports = exports.default;
  24844. });
  24845. var string = createCommonjsModule(function (module, exports) {
  24846. exports.__esModule = true;
  24847. exports.default = void 0;
  24848. var _node = _interopRequireDefault(node);
  24849. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24850. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24851. var String =
  24852. /*#__PURE__*/
  24853. function (_Node) {
  24854. _inheritsLoose(String, _Node);
  24855. function String(opts) {
  24856. var _this;
  24857. _this = _Node.call(this, opts) || this;
  24858. _this.type = types$2.STRING;
  24859. return _this;
  24860. }
  24861. return String;
  24862. }(_node.default);
  24863. exports.default = String;
  24864. module.exports = exports.default;
  24865. });
  24866. var pseudo = createCommonjsModule(function (module, exports) {
  24867. exports.__esModule = true;
  24868. exports.default = void 0;
  24869. var _container = _interopRequireDefault(container);
  24870. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24871. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24872. var Pseudo =
  24873. /*#__PURE__*/
  24874. function (_Container) {
  24875. _inheritsLoose(Pseudo, _Container);
  24876. function Pseudo(opts) {
  24877. var _this;
  24878. _this = _Container.call(this, opts) || this;
  24879. _this.type = types$2.PSEUDO;
  24880. return _this;
  24881. }
  24882. var _proto = Pseudo.prototype;
  24883. _proto.toString = function toString() {
  24884. var params = this.length ? '(' + this.map(String).join(',') + ')' : '';
  24885. return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join('');
  24886. };
  24887. return Pseudo;
  24888. }(_container.default);
  24889. exports.default = Pseudo;
  24890. module.exports = exports.default;
  24891. });
  24892. /**
  24893. * For Node.js, simply re-export the core `util.deprecate` function.
  24894. */
  24895. var node$1 = require$$0__default.deprecate;
  24896. var attribute = createCommonjsModule(function (module, exports) {
  24897. exports.__esModule = true;
  24898. exports.unescapeValue = unescapeValue;
  24899. exports.default = void 0;
  24900. var _cssesc = _interopRequireDefault(cssesc_1);
  24901. var _unesc = _interopRequireDefault(unesc_1);
  24902. var _namespace = _interopRequireDefault(namespace);
  24903. var _CSSESC_QUOTE_OPTIONS;
  24904. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24905. 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); } }
  24906. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  24907. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  24908. var WRAPPED_IN_QUOTES = /^('|")(.*)\1$/;
  24909. var warnOfDeprecatedValueAssignment = node$1(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
  24910. var warnOfDeprecatedQuotedAssignment = node$1(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  24911. var warnOfDeprecatedConstructor = node$1(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  24912. function unescapeValue(value) {
  24913. var deprecatedUsage = false;
  24914. var quoteMark = null;
  24915. var unescaped = value;
  24916. var m = unescaped.match(WRAPPED_IN_QUOTES);
  24917. if (m) {
  24918. quoteMark = m[1];
  24919. unescaped = m[2];
  24920. }
  24921. unescaped = (0, _unesc.default)(unescaped);
  24922. if (unescaped !== value) {
  24923. deprecatedUsage = true;
  24924. }
  24925. return {
  24926. deprecatedUsage: deprecatedUsage,
  24927. unescaped: unescaped,
  24928. quoteMark: quoteMark
  24929. };
  24930. }
  24931. function handleDeprecatedContructorOpts(opts) {
  24932. if (opts.quoteMark !== undefined) {
  24933. return opts;
  24934. }
  24935. if (opts.value === undefined) {
  24936. return opts;
  24937. }
  24938. warnOfDeprecatedConstructor();
  24939. var _unescapeValue = unescapeValue(opts.value),
  24940. quoteMark = _unescapeValue.quoteMark,
  24941. unescaped = _unescapeValue.unescaped;
  24942. if (!opts.raws) {
  24943. opts.raws = {};
  24944. }
  24945. if (opts.raws.value === undefined) {
  24946. opts.raws.value = opts.value;
  24947. }
  24948. opts.value = unescaped;
  24949. opts.quoteMark = quoteMark;
  24950. return opts;
  24951. }
  24952. var Attribute =
  24953. /*#__PURE__*/
  24954. function (_Namespace) {
  24955. _inheritsLoose(Attribute, _Namespace);
  24956. function Attribute(opts) {
  24957. var _this;
  24958. if (opts === void 0) {
  24959. opts = {};
  24960. }
  24961. _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
  24962. _this.type = types$2.ATTRIBUTE;
  24963. _this.raws = _this.raws || {};
  24964. Object.defineProperty(_this.raws, 'unquoted', {
  24965. get: node$1(function () {
  24966. return _this.value;
  24967. }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
  24968. set: node$1(function () {
  24969. return _this.value;
  24970. }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
  24971. });
  24972. _this._constructed = true;
  24973. return _this;
  24974. }
  24975. /**
  24976. * Returns the Attribute's value quoted such that it would be legal to use
  24977. * in the value of a css file. The original value's quotation setting
  24978. * used for stringification is left unchanged. See `setValue(value, options)`
  24979. * if you want to control the quote settings of a new value for the attribute.
  24980. *
  24981. * You can also change the quotation used for the current value by setting quoteMark.
  24982. *
  24983. * Options:
  24984. * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
  24985. * option is not set, the original value for quoteMark will be used. If
  24986. * indeterminate, a double quote is used. The legal values are:
  24987. * * `null` - the value will be unquoted and characters will be escaped as necessary.
  24988. * * `'` - the value will be quoted with a single quote and single quotes are escaped.
  24989. * * `"` - the value will be quoted with a double quote and double quotes are escaped.
  24990. * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
  24991. * over the quoteMark option value.
  24992. * * smart {boolean} - if true, will select a quote mark based on the value
  24993. * and the other options specified here. See the `smartQuoteMark()`
  24994. * method.
  24995. **/
  24996. var _proto = Attribute.prototype;
  24997. _proto.getQuotedValue = function getQuotedValue(options) {
  24998. if (options === void 0) {
  24999. options = {};
  25000. }
  25001. var quoteMark = this._determineQuoteMark(options);
  25002. var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
  25003. var escaped = (0, _cssesc.default)(this._value, cssescopts);
  25004. return escaped;
  25005. };
  25006. _proto._determineQuoteMark = function _determineQuoteMark(options) {
  25007. return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
  25008. }
  25009. /**
  25010. * Set the unescaped value with the specified quotation options. The value
  25011. * provided must not include any wrapping quote marks -- those quotes will
  25012. * be interpreted as part of the value and escaped accordingly.
  25013. */
  25014. ;
  25015. _proto.setValue = function setValue(value, options) {
  25016. if (options === void 0) {
  25017. options = {};
  25018. }
  25019. this._value = value;
  25020. this._quoteMark = this._determineQuoteMark(options);
  25021. this._syncRawValue();
  25022. }
  25023. /**
  25024. * Intelligently select a quoteMark value based on the value's contents. If
  25025. * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
  25026. * mark will be picked that minimizes the number of escapes.
  25027. *
  25028. * If there's no clear winner, the quote mark from these options is used,
  25029. * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
  25030. * true). If the quoteMark is unspecified, a double quote is used.
  25031. *
  25032. * @param options This takes the quoteMark and preferCurrentQuoteMark options
  25033. * from the quoteValue method.
  25034. */
  25035. ;
  25036. _proto.smartQuoteMark = function smartQuoteMark(options) {
  25037. var v = this.value;
  25038. var numSingleQuotes = v.replace(/[^']/g, '').length;
  25039. var numDoubleQuotes = v.replace(/[^"]/g, '').length;
  25040. if (numSingleQuotes + numDoubleQuotes === 0) {
  25041. var escaped = (0, _cssesc.default)(v, {
  25042. isIdentifier: true
  25043. });
  25044. if (escaped === v) {
  25045. return Attribute.NO_QUOTE;
  25046. } else {
  25047. var pref = this.preferredQuoteMark(options);
  25048. if (pref === Attribute.NO_QUOTE) {
  25049. // pick a quote mark that isn't none and see if it's smaller
  25050. var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
  25051. var opts = CSSESC_QUOTE_OPTIONS[quote];
  25052. var quoteValue = (0, _cssesc.default)(v, opts);
  25053. if (quoteValue.length < escaped.length) {
  25054. return quote;
  25055. }
  25056. }
  25057. return pref;
  25058. }
  25059. } else if (numDoubleQuotes === numSingleQuotes) {
  25060. return this.preferredQuoteMark(options);
  25061. } else if (numDoubleQuotes < numSingleQuotes) {
  25062. return Attribute.DOUBLE_QUOTE;
  25063. } else {
  25064. return Attribute.SINGLE_QUOTE;
  25065. }
  25066. }
  25067. /**
  25068. * Selects the preferred quote mark based on the options and the current quote mark value.
  25069. * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
  25070. * instead.
  25071. */
  25072. ;
  25073. _proto.preferredQuoteMark = function preferredQuoteMark(options) {
  25074. var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
  25075. if (quoteMark === undefined) {
  25076. quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
  25077. }
  25078. if (quoteMark === undefined) {
  25079. quoteMark = Attribute.DOUBLE_QUOTE;
  25080. }
  25081. return quoteMark;
  25082. };
  25083. _proto._syncRawValue = function _syncRawValue() {
  25084. var rawValue = (0, _cssesc.default)(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
  25085. if (rawValue === this._value) {
  25086. if (this.raws) {
  25087. delete this.raws.value;
  25088. }
  25089. } else {
  25090. this.raws.value = rawValue;
  25091. }
  25092. };
  25093. _proto._handleEscapes = function _handleEscapes(prop, value) {
  25094. if (this._constructed) {
  25095. var escaped = (0, _cssesc.default)(value, {
  25096. isIdentifier: true
  25097. });
  25098. if (escaped !== value) {
  25099. this.raws[prop] = escaped;
  25100. } else {
  25101. delete this.raws[prop];
  25102. }
  25103. }
  25104. };
  25105. _proto._spacesFor = function _spacesFor(name) {
  25106. var attrSpaces = {
  25107. before: '',
  25108. after: ''
  25109. };
  25110. var spaces = this.spaces[name] || {};
  25111. var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
  25112. return Object.assign(attrSpaces, spaces, rawSpaces);
  25113. };
  25114. _proto._stringFor = function _stringFor(name, spaceName, concat) {
  25115. if (spaceName === void 0) {
  25116. spaceName = name;
  25117. }
  25118. if (concat === void 0) {
  25119. concat = defaultAttrConcat;
  25120. }
  25121. var attrSpaces = this._spacesFor(spaceName);
  25122. return concat(this.stringifyProperty(name), attrSpaces);
  25123. }
  25124. /**
  25125. * returns the offset of the attribute part specified relative to the
  25126. * start of the node of the output string.
  25127. *
  25128. * * "ns" - alias for "namespace"
  25129. * * "namespace" - the namespace if it exists.
  25130. * * "attribute" - the attribute name
  25131. * * "attributeNS" - the start of the attribute or its namespace
  25132. * * "operator" - the match operator of the attribute
  25133. * * "value" - The value (string or identifier)
  25134. * * "insensitive" - the case insensitivity flag;
  25135. * @param part One of the possible values inside an attribute.
  25136. * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
  25137. */
  25138. ;
  25139. _proto.offsetOf = function offsetOf(name) {
  25140. var count = 1;
  25141. var attributeSpaces = this._spacesFor("attribute");
  25142. count += attributeSpaces.before.length;
  25143. if (name === "namespace" || name === "ns") {
  25144. return this.namespace ? count : -1;
  25145. }
  25146. if (name === "attributeNS") {
  25147. return count;
  25148. }
  25149. count += this.namespaceString.length;
  25150. if (this.namespace) {
  25151. count += 1;
  25152. }
  25153. if (name === "attribute") {
  25154. return count;
  25155. }
  25156. count += this.stringifyProperty("attribute").length;
  25157. count += attributeSpaces.after.length;
  25158. var operatorSpaces = this._spacesFor("operator");
  25159. count += operatorSpaces.before.length;
  25160. var operator = this.stringifyProperty("operator");
  25161. if (name === "operator") {
  25162. return operator ? count : -1;
  25163. }
  25164. count += operator.length;
  25165. count += operatorSpaces.after.length;
  25166. var valueSpaces = this._spacesFor("value");
  25167. count += valueSpaces.before.length;
  25168. var value = this.stringifyProperty("value");
  25169. if (name === "value") {
  25170. return value ? count : -1;
  25171. }
  25172. count += value.length;
  25173. count += valueSpaces.after.length;
  25174. var insensitiveSpaces = this._spacesFor("insensitive");
  25175. count += insensitiveSpaces.before.length;
  25176. if (name === "insensitive") {
  25177. return this.insensitive ? count : -1;
  25178. }
  25179. return -1;
  25180. };
  25181. _proto.toString = function toString() {
  25182. var _this2 = this;
  25183. var selector = [this.rawSpaceBefore, '['];
  25184. selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
  25185. if (this.operator && (this.value || this.value === '')) {
  25186. selector.push(this._stringFor('operator'));
  25187. selector.push(this._stringFor('value'));
  25188. selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
  25189. if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
  25190. attrSpaces.before = " ";
  25191. }
  25192. return defaultAttrConcat(attrValue, attrSpaces);
  25193. }));
  25194. }
  25195. selector.push(']');
  25196. selector.push(this.rawSpaceAfter);
  25197. return selector.join('');
  25198. };
  25199. _createClass(Attribute, [{
  25200. key: "quoted",
  25201. get: function get() {
  25202. var qm = this.quoteMark;
  25203. return qm === "'" || qm === '"';
  25204. },
  25205. set: function set(value) {
  25206. warnOfDeprecatedQuotedAssignment();
  25207. }
  25208. /**
  25209. * returns a single (`'`) or double (`"`) quote character if the value is quoted.
  25210. * returns `null` if the value is not quoted.
  25211. * returns `undefined` if the quotation state is unknown (this can happen when
  25212. * the attribute is constructed without specifying a quote mark.)
  25213. */
  25214. }, {
  25215. key: "quoteMark",
  25216. get: function get() {
  25217. return this._quoteMark;
  25218. }
  25219. /**
  25220. * Set the quote mark to be used by this attribute's value.
  25221. * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
  25222. * value is updated accordingly.
  25223. *
  25224. * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
  25225. */
  25226. ,
  25227. set: function set(quoteMark) {
  25228. if (!this._constructed) {
  25229. this._quoteMark = quoteMark;
  25230. return;
  25231. }
  25232. if (this._quoteMark !== quoteMark) {
  25233. this._quoteMark = quoteMark;
  25234. this._syncRawValue();
  25235. }
  25236. }
  25237. }, {
  25238. key: "qualifiedAttribute",
  25239. get: function get() {
  25240. return this.qualifiedName(this.raws.attribute || this.attribute);
  25241. }
  25242. }, {
  25243. key: "insensitiveFlag",
  25244. get: function get() {
  25245. return this.insensitive ? 'i' : '';
  25246. }
  25247. }, {
  25248. key: "value",
  25249. get: function get() {
  25250. return this._value;
  25251. }
  25252. /**
  25253. * Before 3.0, the value had to be set to an escaped value including any wrapped
  25254. * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
  25255. * is unescaped during parsing and any quote marks are removed.
  25256. *
  25257. * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
  25258. * a deprecation warning is raised when the new value contains any characters that would
  25259. * require escaping (including if it contains wrapped quotes).
  25260. *
  25261. * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
  25262. * how the new value is quoted.
  25263. */
  25264. ,
  25265. set: function set(v) {
  25266. if (this._constructed) {
  25267. var _unescapeValue2 = unescapeValue(v),
  25268. deprecatedUsage = _unescapeValue2.deprecatedUsage,
  25269. unescaped = _unescapeValue2.unescaped,
  25270. quoteMark = _unescapeValue2.quoteMark;
  25271. if (deprecatedUsage) {
  25272. warnOfDeprecatedValueAssignment();
  25273. }
  25274. if (unescaped === this._value && quoteMark === this._quoteMark) {
  25275. return;
  25276. }
  25277. this._value = unescaped;
  25278. this._quoteMark = quoteMark;
  25279. this._syncRawValue();
  25280. } else {
  25281. this._value = v;
  25282. }
  25283. }
  25284. }, {
  25285. key: "attribute",
  25286. get: function get() {
  25287. return this._attribute;
  25288. },
  25289. set: function set(name) {
  25290. this._handleEscapes("attribute", name);
  25291. this._attribute = name;
  25292. }
  25293. }]);
  25294. return Attribute;
  25295. }(_namespace.default);
  25296. exports.default = Attribute;
  25297. Attribute.NO_QUOTE = null;
  25298. Attribute.SINGLE_QUOTE = "'";
  25299. Attribute.DOUBLE_QUOTE = '"';
  25300. var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
  25301. "'": {
  25302. quotes: 'single',
  25303. wrap: true
  25304. },
  25305. '"': {
  25306. quotes: 'double',
  25307. wrap: true
  25308. }
  25309. }, _CSSESC_QUOTE_OPTIONS[null] = {
  25310. isIdentifier: true
  25311. }, _CSSESC_QUOTE_OPTIONS);
  25312. function defaultAttrConcat(attrValue, attrSpaces) {
  25313. return "" + attrSpaces.before + attrValue + attrSpaces.after;
  25314. }
  25315. });
  25316. var universal = createCommonjsModule(function (module, exports) {
  25317. exports.__esModule = true;
  25318. exports.default = void 0;
  25319. var _namespace = _interopRequireDefault(namespace);
  25320. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25321. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  25322. var Universal =
  25323. /*#__PURE__*/
  25324. function (_Namespace) {
  25325. _inheritsLoose(Universal, _Namespace);
  25326. function Universal(opts) {
  25327. var _this;
  25328. _this = _Namespace.call(this, opts) || this;
  25329. _this.type = types$2.UNIVERSAL;
  25330. _this.value = '*';
  25331. return _this;
  25332. }
  25333. return Universal;
  25334. }(_namespace.default);
  25335. exports.default = Universal;
  25336. module.exports = exports.default;
  25337. });
  25338. var combinator = createCommonjsModule(function (module, exports) {
  25339. exports.__esModule = true;
  25340. exports.default = void 0;
  25341. var _node = _interopRequireDefault(node);
  25342. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25343. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  25344. var Combinator =
  25345. /*#__PURE__*/
  25346. function (_Node) {
  25347. _inheritsLoose(Combinator, _Node);
  25348. function Combinator(opts) {
  25349. var _this;
  25350. _this = _Node.call(this, opts) || this;
  25351. _this.type = types$2.COMBINATOR;
  25352. return _this;
  25353. }
  25354. return Combinator;
  25355. }(_node.default);
  25356. exports.default = Combinator;
  25357. module.exports = exports.default;
  25358. });
  25359. var nesting = createCommonjsModule(function (module, exports) {
  25360. exports.__esModule = true;
  25361. exports.default = void 0;
  25362. var _node = _interopRequireDefault(node);
  25363. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25364. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  25365. var Nesting =
  25366. /*#__PURE__*/
  25367. function (_Node) {
  25368. _inheritsLoose(Nesting, _Node);
  25369. function Nesting(opts) {
  25370. var _this;
  25371. _this = _Node.call(this, opts) || this;
  25372. _this.type = types$2.NESTING;
  25373. _this.value = '&';
  25374. return _this;
  25375. }
  25376. return Nesting;
  25377. }(_node.default);
  25378. exports.default = Nesting;
  25379. module.exports = exports.default;
  25380. });
  25381. var sortAscending_1 = createCommonjsModule(function (module, exports) {
  25382. exports.__esModule = true;
  25383. exports.default = sortAscending;
  25384. function sortAscending(list) {
  25385. return list.sort(function (a, b) {
  25386. return a - b;
  25387. });
  25388. }
  25389. module.exports = exports.default;
  25390. });
  25391. var tokenTypes = createCommonjsModule(function (module, exports) {
  25392. exports.__esModule = true;
  25393. 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;
  25394. var ampersand = 38; // `&`.charCodeAt(0);
  25395. exports.ampersand = ampersand;
  25396. var asterisk = 42; // `*`.charCodeAt(0);
  25397. exports.asterisk = asterisk;
  25398. var at = 64; // `@`.charCodeAt(0);
  25399. exports.at = at;
  25400. var comma = 44; // `,`.charCodeAt(0);
  25401. exports.comma = comma;
  25402. var colon = 58; // `:`.charCodeAt(0);
  25403. exports.colon = colon;
  25404. var semicolon = 59; // `;`.charCodeAt(0);
  25405. exports.semicolon = semicolon;
  25406. var openParenthesis = 40; // `(`.charCodeAt(0);
  25407. exports.openParenthesis = openParenthesis;
  25408. var closeParenthesis = 41; // `)`.charCodeAt(0);
  25409. exports.closeParenthesis = closeParenthesis;
  25410. var openSquare = 91; // `[`.charCodeAt(0);
  25411. exports.openSquare = openSquare;
  25412. var closeSquare = 93; // `]`.charCodeAt(0);
  25413. exports.closeSquare = closeSquare;
  25414. var dollar = 36; // `$`.charCodeAt(0);
  25415. exports.dollar = dollar;
  25416. var tilde = 126; // `~`.charCodeAt(0);
  25417. exports.tilde = tilde;
  25418. var caret = 94; // `^`.charCodeAt(0);
  25419. exports.caret = caret;
  25420. var plus = 43; // `+`.charCodeAt(0);
  25421. exports.plus = plus;
  25422. var equals = 61; // `=`.charCodeAt(0);
  25423. exports.equals = equals;
  25424. var pipe = 124; // `|`.charCodeAt(0);
  25425. exports.pipe = pipe;
  25426. var greaterThan = 62; // `>`.charCodeAt(0);
  25427. exports.greaterThan = greaterThan;
  25428. var space = 32; // ` `.charCodeAt(0);
  25429. exports.space = space;
  25430. var singleQuote = 39; // `'`.charCodeAt(0);
  25431. exports.singleQuote = singleQuote;
  25432. var doubleQuote = 34; // `"`.charCodeAt(0);
  25433. exports.doubleQuote = doubleQuote;
  25434. var slash = 47; // `/`.charCodeAt(0);
  25435. exports.slash = slash;
  25436. var bang = 33; // `!`.charCodeAt(0);
  25437. exports.bang = bang;
  25438. var backslash = 92; // '\\'.charCodeAt(0);
  25439. exports.backslash = backslash;
  25440. var cr = 13; // '\r'.charCodeAt(0);
  25441. exports.cr = cr;
  25442. var feed = 12; // '\f'.charCodeAt(0);
  25443. exports.feed = feed;
  25444. var newline = 10; // '\n'.charCodeAt(0);
  25445. exports.newline = newline;
  25446. var tab = 9; // '\t'.charCodeAt(0);
  25447. // Expose aliases primarily for readability.
  25448. exports.tab = tab;
  25449. var str = singleQuote; // No good single character representation!
  25450. exports.str = str;
  25451. var comment = -1;
  25452. exports.comment = comment;
  25453. var word = -2;
  25454. exports.word = word;
  25455. var combinator = -3;
  25456. exports.combinator = combinator;
  25457. });
  25458. var tokenize_1 = createCommonjsModule(function (module, exports) {
  25459. exports.__esModule = true;
  25460. exports.default = tokenize;
  25461. exports.FIELDS = void 0;
  25462. var t = _interopRequireWildcard(tokenTypes);
  25463. var _unescapable, _wordDelimiters;
  25464. 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; } }
  25465. var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  25466. 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);
  25467. var hex = {};
  25468. var hexChars = "0123456789abcdefABCDEF";
  25469. for (var i = 0; i < hexChars.length; i++) {
  25470. hex[hexChars.charCodeAt(i)] = true;
  25471. }
  25472. /**
  25473. * Returns the last index of the bar css word
  25474. * @param {string} css The string in which the word begins
  25475. * @param {number} start The index into the string where word's first letter occurs
  25476. */
  25477. function consumeWord(css, start) {
  25478. var next = start;
  25479. var code;
  25480. do {
  25481. code = css.charCodeAt(next);
  25482. if (wordDelimiters[code]) {
  25483. return next - 1;
  25484. } else if (code === t.backslash) {
  25485. next = consumeEscape(css, next) + 1;
  25486. } else {
  25487. // All other characters are part of the word
  25488. next++;
  25489. }
  25490. } while (next < css.length);
  25491. return next - 1;
  25492. }
  25493. /**
  25494. * Returns the last index of the escape sequence
  25495. * @param {string} css The string in which the sequence begins
  25496. * @param {number} start The index into the string where escape character (`\`) occurs.
  25497. */
  25498. function consumeEscape(css, start) {
  25499. var next = start;
  25500. var code = css.charCodeAt(next + 1);
  25501. if (unescapable[code]) ; else if (hex[code]) {
  25502. var hexDigits = 0; // consume up to 6 hex chars
  25503. do {
  25504. next++;
  25505. hexDigits++;
  25506. code = css.charCodeAt(next + 1);
  25507. } while (hex[code] && hexDigits < 6); // if fewer than 6 hex chars, a trailing space ends the escape
  25508. if (hexDigits < 6 && code === t.space) {
  25509. next++;
  25510. }
  25511. } else {
  25512. // the next char is part of the current word
  25513. next++;
  25514. }
  25515. return next;
  25516. }
  25517. var FIELDS = {
  25518. TYPE: 0,
  25519. START_LINE: 1,
  25520. START_COL: 2,
  25521. END_LINE: 3,
  25522. END_COL: 4,
  25523. START_POS: 5,
  25524. END_POS: 6
  25525. };
  25526. exports.FIELDS = FIELDS;
  25527. function tokenize(input) {
  25528. var tokens = [];
  25529. var css = input.css.valueOf();
  25530. var _css = css,
  25531. length = _css.length;
  25532. var offset = -1;
  25533. var line = 1;
  25534. var start = 0;
  25535. var end = 0;
  25536. var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
  25537. function unclosed(what, fix) {
  25538. if (input.safe) {
  25539. // fyi: this is never set to true.
  25540. css += fix;
  25541. next = css.length - 1;
  25542. } else {
  25543. throw input.error('Unclosed ' + what, line, start - offset, start);
  25544. }
  25545. }
  25546. while (start < length) {
  25547. code = css.charCodeAt(start);
  25548. if (code === t.newline) {
  25549. offset = start;
  25550. line += 1;
  25551. }
  25552. switch (code) {
  25553. case t.space:
  25554. case t.tab:
  25555. case t.newline:
  25556. case t.cr:
  25557. case t.feed:
  25558. next = start;
  25559. do {
  25560. next += 1;
  25561. code = css.charCodeAt(next);
  25562. if (code === t.newline) {
  25563. offset = next;
  25564. line += 1;
  25565. }
  25566. } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
  25567. tokenType = t.space;
  25568. endLine = line;
  25569. endColumn = next - offset - 1;
  25570. end = next;
  25571. break;
  25572. case t.plus:
  25573. case t.greaterThan:
  25574. case t.tilde:
  25575. case t.pipe:
  25576. next = start;
  25577. do {
  25578. next += 1;
  25579. code = css.charCodeAt(next);
  25580. } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
  25581. tokenType = t.combinator;
  25582. endLine = line;
  25583. endColumn = start - offset;
  25584. end = next;
  25585. break;
  25586. // Consume these characters as single tokens.
  25587. case t.asterisk:
  25588. case t.ampersand:
  25589. case t.bang:
  25590. case t.comma:
  25591. case t.equals:
  25592. case t.dollar:
  25593. case t.caret:
  25594. case t.openSquare:
  25595. case t.closeSquare:
  25596. case t.colon:
  25597. case t.semicolon:
  25598. case t.openParenthesis:
  25599. case t.closeParenthesis:
  25600. next = start;
  25601. tokenType = code;
  25602. endLine = line;
  25603. endColumn = start - offset;
  25604. end = next + 1;
  25605. break;
  25606. case t.singleQuote:
  25607. case t.doubleQuote:
  25608. quote = code === t.singleQuote ? "'" : '"';
  25609. next = start;
  25610. do {
  25611. escaped = false;
  25612. next = css.indexOf(quote, next + 1);
  25613. if (next === -1) {
  25614. unclosed('quote', quote);
  25615. }
  25616. escapePos = next;
  25617. while (css.charCodeAt(escapePos - 1) === t.backslash) {
  25618. escapePos -= 1;
  25619. escaped = !escaped;
  25620. }
  25621. } while (escaped);
  25622. tokenType = t.str;
  25623. endLine = line;
  25624. endColumn = start - offset;
  25625. end = next + 1;
  25626. break;
  25627. default:
  25628. if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
  25629. next = css.indexOf('*/', start + 2) + 1;
  25630. if (next === 0) {
  25631. unclosed('comment', '*/');
  25632. }
  25633. content = css.slice(start, next + 1);
  25634. lines = content.split('\n');
  25635. last = lines.length - 1;
  25636. if (last > 0) {
  25637. nextLine = line + last;
  25638. nextOffset = next - lines[last].length;
  25639. } else {
  25640. nextLine = line;
  25641. nextOffset = offset;
  25642. }
  25643. tokenType = t.comment;
  25644. line = nextLine;
  25645. endLine = nextLine;
  25646. endColumn = next - nextOffset;
  25647. } else if (code === t.slash) {
  25648. next = start;
  25649. tokenType = code;
  25650. endLine = line;
  25651. endColumn = start - offset;
  25652. end = next + 1;
  25653. } else {
  25654. next = consumeWord(css, start);
  25655. tokenType = t.word;
  25656. endLine = line;
  25657. endColumn = next - offset;
  25658. }
  25659. end = next + 1;
  25660. break;
  25661. } // Ensure that the token structure remains consistent
  25662. tokens.push([tokenType, // [0] Token type
  25663. line, // [1] Starting line
  25664. start - offset, // [2] Starting column
  25665. endLine, // [3] Ending line
  25666. endColumn, // [4] Ending column
  25667. start, // [5] Start position / Source index
  25668. end]); // Reset offset for the next token
  25669. if (nextOffset) {
  25670. offset = nextOffset;
  25671. nextOffset = null;
  25672. }
  25673. start = end;
  25674. }
  25675. return tokens;
  25676. }
  25677. });
  25678. var parser = createCommonjsModule(function (module, exports) {
  25679. exports.__esModule = true;
  25680. exports.default = void 0;
  25681. var _indexesOf = _interopRequireDefault(indexesOf);
  25682. var _uniq = _interopRequireDefault(uniq);
  25683. var _root = _interopRequireDefault(root);
  25684. var _selector = _interopRequireDefault(selector);
  25685. var _className = _interopRequireDefault(className);
  25686. var _comment = _interopRequireDefault(comment);
  25687. var _id = _interopRequireDefault(id);
  25688. var _tag = _interopRequireDefault(tag);
  25689. var _string = _interopRequireDefault(string);
  25690. var _pseudo = _interopRequireDefault(pseudo);
  25691. var _attribute = _interopRequireWildcard(attribute);
  25692. var _universal = _interopRequireDefault(universal);
  25693. var _combinator = _interopRequireDefault(combinator);
  25694. var _nesting = _interopRequireDefault(nesting);
  25695. var _sortAscending = _interopRequireDefault(sortAscending_1);
  25696. var _tokenize = _interopRequireWildcard(tokenize_1);
  25697. var tokens = _interopRequireWildcard(tokenTypes);
  25698. var types = _interopRequireWildcard(types$2);
  25699. var _WHITESPACE_TOKENS, _Object$assign;
  25700. 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; } }
  25701. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25702. 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); } }
  25703. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  25704. 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);
  25705. var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  25706. function tokenStart(token) {
  25707. return {
  25708. line: token[_tokenize.FIELDS.START_LINE],
  25709. column: token[_tokenize.FIELDS.START_COL]
  25710. };
  25711. }
  25712. function tokenEnd(token) {
  25713. return {
  25714. line: token[_tokenize.FIELDS.END_LINE],
  25715. column: token[_tokenize.FIELDS.END_COL]
  25716. };
  25717. }
  25718. function getSource(startLine, startColumn, endLine, endColumn) {
  25719. return {
  25720. start: {
  25721. line: startLine,
  25722. column: startColumn
  25723. },
  25724. end: {
  25725. line: endLine,
  25726. column: endColumn
  25727. }
  25728. };
  25729. }
  25730. function getTokenSource(token) {
  25731. return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  25732. }
  25733. function getTokenSourceSpan(startToken, endToken) {
  25734. if (!startToken) {
  25735. return undefined;
  25736. }
  25737. return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  25738. }
  25739. function unescapeProp(node, prop) {
  25740. var value = node[prop];
  25741. if (typeof value !== "string") {
  25742. return;
  25743. }
  25744. if (value.indexOf("\\") !== -1) {
  25745. (0, util$1.ensureObject)(node, 'raws');
  25746. node[prop] = (0, util$1.unesc)(value);
  25747. if (node.raws[prop] === undefined) {
  25748. node.raws[prop] = value;
  25749. }
  25750. }
  25751. return node;
  25752. }
  25753. var Parser =
  25754. /*#__PURE__*/
  25755. function () {
  25756. function Parser(rule, options) {
  25757. if (options === void 0) {
  25758. options = {};
  25759. }
  25760. this.rule = rule;
  25761. this.options = Object.assign({
  25762. lossy: false,
  25763. safe: false
  25764. }, options);
  25765. this.position = 0;
  25766. this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector;
  25767. this.tokens = (0, _tokenize.default)({
  25768. css: this.css,
  25769. error: this._errorGenerator(),
  25770. safe: this.options.safe
  25771. });
  25772. var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
  25773. this.root = new _root.default({
  25774. source: rootSource
  25775. });
  25776. this.root.errorGenerator = this._errorGenerator();
  25777. var selector = new _selector.default({
  25778. source: {
  25779. start: {
  25780. line: 1,
  25781. column: 1
  25782. }
  25783. }
  25784. });
  25785. this.root.append(selector);
  25786. this.current = selector;
  25787. this.loop();
  25788. }
  25789. var _proto = Parser.prototype;
  25790. _proto._errorGenerator = function _errorGenerator() {
  25791. var _this = this;
  25792. return function (message, errorOptions) {
  25793. if (typeof _this.rule === 'string') {
  25794. return new Error(message);
  25795. }
  25796. return _this.rule.error(message, errorOptions);
  25797. };
  25798. };
  25799. _proto.attribute = function attribute() {
  25800. var attr = [];
  25801. var startingToken = this.currToken;
  25802. this.position++;
  25803. while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  25804. attr.push(this.currToken);
  25805. this.position++;
  25806. }
  25807. if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
  25808. return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  25809. }
  25810. var len = attr.length;
  25811. var node = {
  25812. source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
  25813. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  25814. };
  25815. if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
  25816. return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]);
  25817. }
  25818. var pos = 0;
  25819. var spaceBefore = '';
  25820. var commentBefore = '';
  25821. var lastAdded = null;
  25822. var spaceAfterMeaningfulToken = false;
  25823. while (pos < len) {
  25824. var token = attr[pos];
  25825. var content = this.content(token);
  25826. var next = attr[pos + 1];
  25827. switch (token[_tokenize.FIELDS.TYPE]) {
  25828. case tokens.space:
  25829. // if (
  25830. // len === 1 ||
  25831. // pos === 0 && this.content(next) === '|'
  25832. // ) {
  25833. // return this.expected('attribute', token[TOKEN.START_POS], content);
  25834. // }
  25835. spaceAfterMeaningfulToken = true;
  25836. if (this.options.lossy) {
  25837. break;
  25838. }
  25839. if (lastAdded) {
  25840. (0, util$1.ensureObject)(node, 'spaces', lastAdded);
  25841. var prevContent = node.spaces[lastAdded].after || '';
  25842. node.spaces[lastAdded].after = prevContent + content;
  25843. var existingComment = (0, util$1.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null;
  25844. if (existingComment) {
  25845. node.raws.spaces[lastAdded].after = existingComment + content;
  25846. }
  25847. } else {
  25848. spaceBefore = spaceBefore + content;
  25849. commentBefore = commentBefore + content;
  25850. }
  25851. break;
  25852. case tokens.asterisk:
  25853. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  25854. node.operator = content;
  25855. lastAdded = 'operator';
  25856. } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
  25857. if (spaceBefore) {
  25858. (0, util$1.ensureObject)(node, 'spaces', 'attribute');
  25859. node.spaces.attribute.before = spaceBefore;
  25860. spaceBefore = '';
  25861. }
  25862. if (commentBefore) {
  25863. (0, util$1.ensureObject)(node, 'raws', 'spaces', 'attribute');
  25864. node.raws.spaces.attribute.before = spaceBefore;
  25865. commentBefore = '';
  25866. }
  25867. node.namespace = (node.namespace || "") + content;
  25868. var rawValue = (0, util$1.getProp)(node, 'raws', 'namespace') || null;
  25869. if (rawValue) {
  25870. node.raws.namespace += content;
  25871. }
  25872. lastAdded = 'namespace';
  25873. }
  25874. spaceAfterMeaningfulToken = false;
  25875. break;
  25876. case tokens.dollar:
  25877. if (lastAdded === "value") {
  25878. var oldRawValue = (0, util$1.getProp)(node, 'raws', 'value');
  25879. node.value += "$";
  25880. if (oldRawValue) {
  25881. node.raws.value = oldRawValue + "$";
  25882. }
  25883. break;
  25884. }
  25885. // Falls through
  25886. case tokens.caret:
  25887. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  25888. node.operator = content;
  25889. lastAdded = 'operator';
  25890. }
  25891. spaceAfterMeaningfulToken = false;
  25892. break;
  25893. case tokens.combinator:
  25894. if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  25895. node.operator = content;
  25896. lastAdded = 'operator';
  25897. }
  25898. if (content !== '|') {
  25899. spaceAfterMeaningfulToken = false;
  25900. break;
  25901. }
  25902. if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
  25903. node.operator = content;
  25904. lastAdded = 'operator';
  25905. } else if (!node.namespace && !node.attribute) {
  25906. node.namespace = true;
  25907. }
  25908. spaceAfterMeaningfulToken = false;
  25909. break;
  25910. case tokens.word:
  25911. 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.
  25912. !node.operator && !node.namespace) {
  25913. node.namespace = content;
  25914. lastAdded = 'namespace';
  25915. } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
  25916. if (spaceBefore) {
  25917. (0, util$1.ensureObject)(node, 'spaces', 'attribute');
  25918. node.spaces.attribute.before = spaceBefore;
  25919. spaceBefore = '';
  25920. }
  25921. if (commentBefore) {
  25922. (0, util$1.ensureObject)(node, 'raws', 'spaces', 'attribute');
  25923. node.raws.spaces.attribute.before = commentBefore;
  25924. commentBefore = '';
  25925. }
  25926. node.attribute = (node.attribute || "") + content;
  25927. var _rawValue = (0, util$1.getProp)(node, 'raws', 'attribute') || null;
  25928. if (_rawValue) {
  25929. node.raws.attribute += content;
  25930. }
  25931. lastAdded = 'attribute';
  25932. } else if (!node.value && node.value !== "" || lastAdded === "value" && !spaceAfterMeaningfulToken) {
  25933. var _unescaped = (0, util$1.unesc)(content);
  25934. var _oldRawValue = (0, util$1.getProp)(node, 'raws', 'value') || '';
  25935. var oldValue = node.value || '';
  25936. node.value = oldValue + _unescaped;
  25937. node.quoteMark = null;
  25938. if (_unescaped !== content || _oldRawValue) {
  25939. (0, util$1.ensureObject)(node, 'raws');
  25940. node.raws.value = (_oldRawValue || oldValue) + content;
  25941. }
  25942. lastAdded = 'value';
  25943. } else {
  25944. var insensitive = content === 'i' || content === "I";
  25945. if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) {
  25946. node.insensitive = insensitive;
  25947. if (!insensitive || content === "I") {
  25948. (0, util$1.ensureObject)(node, 'raws');
  25949. node.raws.insensitiveFlag = content;
  25950. }
  25951. lastAdded = 'insensitive';
  25952. if (spaceBefore) {
  25953. (0, util$1.ensureObject)(node, 'spaces', 'insensitive');
  25954. node.spaces.insensitive.before = spaceBefore;
  25955. spaceBefore = '';
  25956. }
  25957. if (commentBefore) {
  25958. (0, util$1.ensureObject)(node, 'raws', 'spaces', 'insensitive');
  25959. node.raws.spaces.insensitive.before = commentBefore;
  25960. commentBefore = '';
  25961. }
  25962. } else if (node.value || node.value === '') {
  25963. lastAdded = 'value';
  25964. node.value += content;
  25965. if (node.raws.value) {
  25966. node.raws.value += content;
  25967. }
  25968. }
  25969. }
  25970. spaceAfterMeaningfulToken = false;
  25971. break;
  25972. case tokens.str:
  25973. if (!node.attribute || !node.operator) {
  25974. return this.error("Expected an attribute followed by an operator preceding the string.", {
  25975. index: token[_tokenize.FIELDS.START_POS]
  25976. });
  25977. }
  25978. var _unescapeValue = (0, _attribute.unescapeValue)(content),
  25979. unescaped = _unescapeValue.unescaped,
  25980. quoteMark = _unescapeValue.quoteMark;
  25981. node.value = unescaped;
  25982. node.quoteMark = quoteMark;
  25983. lastAdded = 'value';
  25984. (0, util$1.ensureObject)(node, 'raws');
  25985. node.raws.value = content;
  25986. spaceAfterMeaningfulToken = false;
  25987. break;
  25988. case tokens.equals:
  25989. if (!node.attribute) {
  25990. return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content);
  25991. }
  25992. if (node.value) {
  25993. return this.error('Unexpected "=" found; an operator was already defined.', {
  25994. index: token[_tokenize.FIELDS.START_POS]
  25995. });
  25996. }
  25997. node.operator = node.operator ? node.operator + content : content;
  25998. lastAdded = 'operator';
  25999. spaceAfterMeaningfulToken = false;
  26000. break;
  26001. case tokens.comment:
  26002. if (lastAdded) {
  26003. if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') {
  26004. var lastComment = (0, util$1.getProp)(node, 'spaces', lastAdded, 'after') || '';
  26005. var rawLastComment = (0, util$1.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment;
  26006. (0, util$1.ensureObject)(node, 'raws', 'spaces', lastAdded);
  26007. node.raws.spaces[lastAdded].after = rawLastComment + content;
  26008. } else {
  26009. var lastValue = node[lastAdded] || '';
  26010. var rawLastValue = (0, util$1.getProp)(node, 'raws', lastAdded) || lastValue;
  26011. (0, util$1.ensureObject)(node, 'raws');
  26012. node.raws[lastAdded] = rawLastValue + content;
  26013. }
  26014. } else {
  26015. commentBefore = commentBefore + content;
  26016. }
  26017. break;
  26018. default:
  26019. return this.error("Unexpected \"" + content + "\" found.", {
  26020. index: token[_tokenize.FIELDS.START_POS]
  26021. });
  26022. }
  26023. pos++;
  26024. }
  26025. unescapeProp(node, "attribute");
  26026. unescapeProp(node, "namespace");
  26027. this.newNode(new _attribute.default(node));
  26028. this.position++;
  26029. }
  26030. /**
  26031. * return a node containing meaningless garbage up to (but not including) the specified token position.
  26032. * if the token position is negative, all remaining tokens are consumed.
  26033. *
  26034. * This returns an array containing a single string node if all whitespace,
  26035. * otherwise an array of comment nodes with space before and after.
  26036. *
  26037. * These tokens are not added to the current selector, the caller can add them or use them to amend
  26038. * a previous node's space metadata.
  26039. *
  26040. * In lossy mode, this returns only comments.
  26041. */
  26042. ;
  26043. _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
  26044. if (stopPosition < 0) {
  26045. stopPosition = this.tokens.length;
  26046. }
  26047. var startPosition = this.position;
  26048. var nodes = [];
  26049. var space = "";
  26050. var lastComment = undefined;
  26051. do {
  26052. if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
  26053. if (!this.options.lossy) {
  26054. space += this.content();
  26055. }
  26056. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
  26057. var spaces = {};
  26058. if (space) {
  26059. spaces.before = space;
  26060. space = "";
  26061. }
  26062. lastComment = new _comment.default({
  26063. value: this.content(),
  26064. source: getTokenSource(this.currToken),
  26065. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  26066. spaces: spaces
  26067. });
  26068. nodes.push(lastComment);
  26069. }
  26070. } while (++this.position < stopPosition);
  26071. if (space) {
  26072. if (lastComment) {
  26073. lastComment.spaces.after = space;
  26074. } else if (!this.options.lossy) {
  26075. var firstToken = this.tokens[startPosition];
  26076. var lastToken = this.tokens[this.position - 1];
  26077. nodes.push(new _string.default({
  26078. value: '',
  26079. source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
  26080. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  26081. spaces: {
  26082. before: space,
  26083. after: ''
  26084. }
  26085. }));
  26086. }
  26087. }
  26088. return nodes;
  26089. }
  26090. /**
  26091. *
  26092. * @param {*} nodes
  26093. */
  26094. ;
  26095. _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
  26096. var _this2 = this;
  26097. if (requiredSpace === void 0) {
  26098. requiredSpace = false;
  26099. }
  26100. var space = "";
  26101. var rawSpace = "";
  26102. nodes.forEach(function (n) {
  26103. var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace);
  26104. var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace);
  26105. space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0);
  26106. rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
  26107. });
  26108. if (rawSpace === space) {
  26109. rawSpace = undefined;
  26110. }
  26111. var result = {
  26112. space: space,
  26113. rawSpace: rawSpace
  26114. };
  26115. return result;
  26116. };
  26117. _proto.isNamedCombinator = function isNamedCombinator(position) {
  26118. if (position === void 0) {
  26119. position = this.position;
  26120. }
  26121. 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;
  26122. };
  26123. _proto.namedCombinator = function namedCombinator() {
  26124. if (this.isNamedCombinator()) {
  26125. var nameRaw = this.content(this.tokens[this.position + 1]);
  26126. var name = (0, util$1.unesc)(nameRaw).toLowerCase();
  26127. var raws = {};
  26128. if (name !== nameRaw) {
  26129. raws.value = "/" + nameRaw + "/";
  26130. }
  26131. var node = new _combinator.default({
  26132. value: "/" + name + "/",
  26133. 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]),
  26134. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
  26135. raws: raws
  26136. });
  26137. this.position = this.position + 3;
  26138. return node;
  26139. } else {
  26140. this.unexpected();
  26141. }
  26142. };
  26143. _proto.combinator = function combinator() {
  26144. var _this3 = this;
  26145. if (this.content() === '|') {
  26146. return this.namespace();
  26147. } // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector.
  26148. var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
  26149. if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
  26150. var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  26151. if (nodes.length > 0) {
  26152. var last = this.current.last;
  26153. if (last) {
  26154. var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes),
  26155. space = _this$convertWhitespa.space,
  26156. rawSpace = _this$convertWhitespa.rawSpace;
  26157. if (rawSpace !== undefined) {
  26158. last.rawSpaceAfter += rawSpace;
  26159. }
  26160. last.spaces.after += space;
  26161. } else {
  26162. nodes.forEach(function (n) {
  26163. return _this3.newNode(n);
  26164. });
  26165. }
  26166. }
  26167. return;
  26168. }
  26169. var firstToken = this.currToken;
  26170. var spaceOrDescendantSelectorNodes = undefined;
  26171. if (nextSigTokenPos > this.position) {
  26172. spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
  26173. }
  26174. var node;
  26175. if (this.isNamedCombinator()) {
  26176. node = this.namedCombinator();
  26177. } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
  26178. node = new _combinator.default({
  26179. value: this.content(),
  26180. source: getTokenSource(this.currToken),
  26181. sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
  26182. });
  26183. this.position++;
  26184. } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) {
  26185. this.unexpected();
  26186. }
  26187. if (node) {
  26188. if (spaceOrDescendantSelectorNodes) {
  26189. var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes),
  26190. _space = _this$convertWhitespa2.space,
  26191. _rawSpace = _this$convertWhitespa2.rawSpace;
  26192. node.spaces.before = _space;
  26193. node.rawSpaceBefore = _rawSpace;
  26194. }
  26195. } else {
  26196. // descendant combinator
  26197. var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true),
  26198. _space2 = _this$convertWhitespa3.space,
  26199. _rawSpace2 = _this$convertWhitespa3.rawSpace;
  26200. if (!_rawSpace2) {
  26201. _rawSpace2 = _space2;
  26202. }
  26203. var spaces = {};
  26204. var raws = {
  26205. spaces: {}
  26206. };
  26207. if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) {
  26208. spaces.before = _space2.slice(0, _space2.length - 1);
  26209. raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
  26210. } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) {
  26211. spaces.after = _space2.slice(1);
  26212. raws.spaces.after = _rawSpace2.slice(1);
  26213. } else {
  26214. raws.value = _rawSpace2;
  26215. }
  26216. node = new _combinator.default({
  26217. value: ' ',
  26218. source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
  26219. sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
  26220. spaces: spaces,
  26221. raws: raws
  26222. });
  26223. }
  26224. if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
  26225. node.spaces.after = this.optionalSpace(this.content());
  26226. this.position++;
  26227. }
  26228. return this.newNode(node);
  26229. };
  26230. _proto.comma = function comma() {
  26231. if (this.position === this.tokens.length - 1) {
  26232. this.root.trailingComma = true;
  26233. this.position++;
  26234. return;
  26235. }
  26236. this.current._inferEndPosition();
  26237. var selector = new _selector.default({
  26238. source: {
  26239. start: tokenStart(this.tokens[this.position + 1])
  26240. }
  26241. });
  26242. this.current.parent.append(selector);
  26243. this.current = selector;
  26244. this.position++;
  26245. };
  26246. _proto.comment = function comment() {
  26247. var current = this.currToken;
  26248. this.newNode(new _comment.default({
  26249. value: this.content(),
  26250. source: getTokenSource(current),
  26251. sourceIndex: current[_tokenize.FIELDS.START_POS]
  26252. }));
  26253. this.position++;
  26254. };
  26255. _proto.error = function error(message, opts) {
  26256. throw this.root.error(message, opts);
  26257. };
  26258. _proto.missingBackslash = function missingBackslash() {
  26259. return this.error('Expected a backslash preceding the semicolon.', {
  26260. index: this.currToken[_tokenize.FIELDS.START_POS]
  26261. });
  26262. };
  26263. _proto.missingParenthesis = function missingParenthesis() {
  26264. return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  26265. };
  26266. _proto.missingSquareBracket = function missingSquareBracket() {
  26267. return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]);
  26268. };
  26269. _proto.unexpected = function unexpected() {
  26270. return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
  26271. };
  26272. _proto.namespace = function namespace() {
  26273. var before = this.prevToken && this.content(this.prevToken) || true;
  26274. if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  26275. this.position++;
  26276. return this.word(before);
  26277. } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
  26278. this.position++;
  26279. return this.universal(before);
  26280. }
  26281. };
  26282. _proto.nesting = function nesting() {
  26283. if (this.nextToken) {
  26284. var nextContent = this.content(this.nextToken);
  26285. if (nextContent === "|") {
  26286. this.position++;
  26287. return;
  26288. }
  26289. }
  26290. var current = this.currToken;
  26291. this.newNode(new _nesting.default({
  26292. value: this.content(),
  26293. source: getTokenSource(current),
  26294. sourceIndex: current[_tokenize.FIELDS.START_POS]
  26295. }));
  26296. this.position++;
  26297. };
  26298. _proto.parentheses = function parentheses() {
  26299. var last = this.current.last;
  26300. var unbalanced = 1;
  26301. this.position++;
  26302. if (last && last.type === types.PSEUDO) {
  26303. var selector = new _selector.default({
  26304. source: {
  26305. start: tokenStart(this.tokens[this.position - 1])
  26306. }
  26307. });
  26308. var cache = this.current;
  26309. last.append(selector);
  26310. this.current = selector;
  26311. while (this.position < this.tokens.length && unbalanced) {
  26312. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  26313. unbalanced++;
  26314. }
  26315. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  26316. unbalanced--;
  26317. }
  26318. if (unbalanced) {
  26319. this.parse();
  26320. } else {
  26321. this.current.source.end = tokenEnd(this.currToken);
  26322. this.current.parent.source.end = tokenEnd(this.currToken);
  26323. this.position++;
  26324. }
  26325. }
  26326. this.current = cache;
  26327. } else {
  26328. // I think this case should be an error. It's used to implement a basic parse of media queries
  26329. // but I don't think it's a good idea.
  26330. var parenStart = this.currToken;
  26331. var parenValue = "(";
  26332. var parenEnd;
  26333. while (this.position < this.tokens.length && unbalanced) {
  26334. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  26335. unbalanced++;
  26336. }
  26337. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  26338. unbalanced--;
  26339. }
  26340. parenEnd = this.currToken;
  26341. parenValue += this.parseParenthesisToken(this.currToken);
  26342. this.position++;
  26343. }
  26344. if (last) {
  26345. last.appendToPropertyAndEscape("value", parenValue, parenValue);
  26346. } else {
  26347. this.newNode(new _string.default({
  26348. value: parenValue,
  26349. source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
  26350. sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
  26351. }));
  26352. }
  26353. }
  26354. if (unbalanced) {
  26355. return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]);
  26356. }
  26357. };
  26358. _proto.pseudo = function pseudo() {
  26359. var _this4 = this;
  26360. var pseudoStr = '';
  26361. var startingToken = this.currToken;
  26362. while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
  26363. pseudoStr += this.content();
  26364. this.position++;
  26365. }
  26366. if (!this.currToken) {
  26367. return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1);
  26368. }
  26369. if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
  26370. this.splitWord(false, function (first, length) {
  26371. pseudoStr += first;
  26372. _this4.newNode(new _pseudo.default({
  26373. value: pseudoStr,
  26374. source: getTokenSourceSpan(startingToken, _this4.currToken),
  26375. sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
  26376. }));
  26377. if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
  26378. _this4.error('Misplaced parenthesis.', {
  26379. index: _this4.nextToken[_tokenize.FIELDS.START_POS]
  26380. });
  26381. }
  26382. });
  26383. } else {
  26384. return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]);
  26385. }
  26386. };
  26387. _proto.space = function space() {
  26388. var content = this.content(); // Handle space before and after the selector
  26389. if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) {
  26390. return node.type === 'comment';
  26391. })) {
  26392. this.spaces = this.optionalSpace(content);
  26393. this.position++;
  26394. } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
  26395. this.current.last.spaces.after = this.optionalSpace(content);
  26396. this.position++;
  26397. } else {
  26398. this.combinator();
  26399. }
  26400. };
  26401. _proto.string = function string() {
  26402. var current = this.currToken;
  26403. this.newNode(new _string.default({
  26404. value: this.content(),
  26405. source: getTokenSource(current),
  26406. sourceIndex: current[_tokenize.FIELDS.START_POS]
  26407. }));
  26408. this.position++;
  26409. };
  26410. _proto.universal = function universal(namespace) {
  26411. var nextToken = this.nextToken;
  26412. if (nextToken && this.content(nextToken) === '|') {
  26413. this.position++;
  26414. return this.namespace();
  26415. }
  26416. var current = this.currToken;
  26417. this.newNode(new _universal.default({
  26418. value: this.content(),
  26419. source: getTokenSource(current),
  26420. sourceIndex: current[_tokenize.FIELDS.START_POS]
  26421. }), namespace);
  26422. this.position++;
  26423. };
  26424. _proto.splitWord = function splitWord(namespace, firstCallback) {
  26425. var _this5 = this;
  26426. var nextToken = this.nextToken;
  26427. var word = this.content();
  26428. while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
  26429. this.position++;
  26430. var current = this.content();
  26431. word += current;
  26432. if (current.lastIndexOf('\\') === current.length - 1) {
  26433. var next = this.nextToken;
  26434. if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
  26435. word += this.requiredSpace(this.content(next));
  26436. this.position++;
  26437. }
  26438. }
  26439. nextToken = this.nextToken;
  26440. }
  26441. var hasClass = (0, _indexesOf.default)(word, '.').filter(function (i) {
  26442. return word[i - 1] !== '\\';
  26443. });
  26444. var hasId = (0, _indexesOf.default)(word, '#').filter(function (i) {
  26445. return word[i - 1] !== '\\';
  26446. }); // Eliminate Sass interpolations from the list of id indexes
  26447. var interpolations = (0, _indexesOf.default)(word, '#{');
  26448. if (interpolations.length) {
  26449. hasId = hasId.filter(function (hashIndex) {
  26450. return !~interpolations.indexOf(hashIndex);
  26451. });
  26452. }
  26453. var indices = (0, _sortAscending.default)((0, _uniq.default)([0].concat(hasClass, hasId)));
  26454. indices.forEach(function (ind, i) {
  26455. var index = indices[i + 1] || word.length;
  26456. var value = word.slice(ind, index);
  26457. if (i === 0 && firstCallback) {
  26458. return firstCallback.call(_this5, value, indices.length);
  26459. }
  26460. var node;
  26461. var current = _this5.currToken;
  26462. var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i];
  26463. var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1));
  26464. if (~hasClass.indexOf(ind)) {
  26465. var classNameOpts = {
  26466. value: value.slice(1),
  26467. source: source,
  26468. sourceIndex: sourceIndex
  26469. };
  26470. node = new _className.default(unescapeProp(classNameOpts, "value"));
  26471. } else if (~hasId.indexOf(ind)) {
  26472. var idOpts = {
  26473. value: value.slice(1),
  26474. source: source,
  26475. sourceIndex: sourceIndex
  26476. };
  26477. node = new _id.default(unescapeProp(idOpts, "value"));
  26478. } else {
  26479. var tagOpts = {
  26480. value: value,
  26481. source: source,
  26482. sourceIndex: sourceIndex
  26483. };
  26484. unescapeProp(tagOpts, "value");
  26485. node = new _tag.default(tagOpts);
  26486. }
  26487. _this5.newNode(node, namespace); // Ensure that the namespace is used only once
  26488. namespace = null;
  26489. });
  26490. this.position++;
  26491. };
  26492. _proto.word = function word(namespace) {
  26493. var nextToken = this.nextToken;
  26494. if (nextToken && this.content(nextToken) === '|') {
  26495. this.position++;
  26496. return this.namespace();
  26497. }
  26498. return this.splitWord(namespace);
  26499. };
  26500. _proto.loop = function loop() {
  26501. while (this.position < this.tokens.length) {
  26502. this.parse(true);
  26503. }
  26504. this.current._inferEndPosition();
  26505. return this.root;
  26506. };
  26507. _proto.parse = function parse(throwOnParenthesis) {
  26508. switch (this.currToken[_tokenize.FIELDS.TYPE]) {
  26509. case tokens.space:
  26510. this.space();
  26511. break;
  26512. case tokens.comment:
  26513. this.comment();
  26514. break;
  26515. case tokens.openParenthesis:
  26516. this.parentheses();
  26517. break;
  26518. case tokens.closeParenthesis:
  26519. if (throwOnParenthesis) {
  26520. this.missingParenthesis();
  26521. }
  26522. break;
  26523. case tokens.openSquare:
  26524. this.attribute();
  26525. break;
  26526. case tokens.dollar:
  26527. case tokens.caret:
  26528. case tokens.equals:
  26529. case tokens.word:
  26530. this.word();
  26531. break;
  26532. case tokens.colon:
  26533. this.pseudo();
  26534. break;
  26535. case tokens.comma:
  26536. this.comma();
  26537. break;
  26538. case tokens.asterisk:
  26539. this.universal();
  26540. break;
  26541. case tokens.ampersand:
  26542. this.nesting();
  26543. break;
  26544. case tokens.slash:
  26545. case tokens.combinator:
  26546. this.combinator();
  26547. break;
  26548. case tokens.str:
  26549. this.string();
  26550. break;
  26551. // These cases throw; no break needed.
  26552. case tokens.closeSquare:
  26553. this.missingSquareBracket();
  26554. case tokens.semicolon:
  26555. this.missingBackslash();
  26556. default:
  26557. this.unexpected();
  26558. }
  26559. }
  26560. /**
  26561. * Helpers
  26562. */
  26563. ;
  26564. _proto.expected = function expected(description, index, found) {
  26565. if (Array.isArray(description)) {
  26566. var last = description.pop();
  26567. description = description.join(', ') + " or " + last;
  26568. }
  26569. var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a';
  26570. if (!found) {
  26571. return this.error("Expected " + an + " " + description + ".", {
  26572. index: index
  26573. });
  26574. }
  26575. return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", {
  26576. index: index
  26577. });
  26578. };
  26579. _proto.requiredSpace = function requiredSpace(space) {
  26580. return this.options.lossy ? ' ' : space;
  26581. };
  26582. _proto.optionalSpace = function optionalSpace(space) {
  26583. return this.options.lossy ? '' : space;
  26584. };
  26585. _proto.lossySpace = function lossySpace(space, required) {
  26586. if (this.options.lossy) {
  26587. return required ? ' ' : '';
  26588. } else {
  26589. return space;
  26590. }
  26591. };
  26592. _proto.parseParenthesisToken = function parseParenthesisToken(token) {
  26593. var content = this.content(token);
  26594. if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
  26595. return this.requiredSpace(content);
  26596. } else {
  26597. return content;
  26598. }
  26599. };
  26600. _proto.newNode = function newNode(node, namespace) {
  26601. if (namespace) {
  26602. if (/^ +$/.test(namespace)) {
  26603. if (!this.options.lossy) {
  26604. this.spaces = (this.spaces || '') + namespace;
  26605. }
  26606. namespace = true;
  26607. }
  26608. node.namespace = namespace;
  26609. unescapeProp(node, "namespace");
  26610. }
  26611. if (this.spaces) {
  26612. node.spaces.before = this.spaces;
  26613. this.spaces = '';
  26614. }
  26615. return this.current.append(node);
  26616. };
  26617. _proto.content = function content(token) {
  26618. if (token === void 0) {
  26619. token = this.currToken;
  26620. }
  26621. return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
  26622. };
  26623. /**
  26624. * returns the index of the next non-whitespace, non-comment token.
  26625. * returns -1 if no meaningful token is found.
  26626. */
  26627. _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
  26628. if (startPosition === void 0) {
  26629. startPosition = this.position + 1;
  26630. }
  26631. var searchPosition = startPosition;
  26632. while (searchPosition < this.tokens.length) {
  26633. if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
  26634. searchPosition++;
  26635. continue;
  26636. } else {
  26637. return searchPosition;
  26638. }
  26639. }
  26640. return -1;
  26641. };
  26642. _createClass(Parser, [{
  26643. key: "currToken",
  26644. get: function get() {
  26645. return this.tokens[this.position];
  26646. }
  26647. }, {
  26648. key: "nextToken",
  26649. get: function get() {
  26650. return this.tokens[this.position + 1];
  26651. }
  26652. }, {
  26653. key: "prevToken",
  26654. get: function get() {
  26655. return this.tokens[this.position - 1];
  26656. }
  26657. }]);
  26658. return Parser;
  26659. }();
  26660. exports.default = Parser;
  26661. module.exports = exports.default;
  26662. });
  26663. var processor = createCommonjsModule(function (module, exports) {
  26664. exports.__esModule = true;
  26665. exports.default = void 0;
  26666. var _parser = _interopRequireDefault(parser);
  26667. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26668. var Processor =
  26669. /*#__PURE__*/
  26670. function () {
  26671. function Processor(func, options) {
  26672. this.func = func || function noop() {};
  26673. this.funcRes = null;
  26674. this.options = options;
  26675. }
  26676. var _proto = Processor.prototype;
  26677. _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) {
  26678. if (options === void 0) {
  26679. options = {};
  26680. }
  26681. var merged = Object.assign({}, this.options, options);
  26682. if (merged.updateSelector === false) {
  26683. return false;
  26684. } else {
  26685. return typeof rule !== "string";
  26686. }
  26687. };
  26688. _proto._isLossy = function _isLossy(options) {
  26689. if (options === void 0) {
  26690. options = {};
  26691. }
  26692. var merged = Object.assign({}, this.options, options);
  26693. if (merged.lossless === false) {
  26694. return true;
  26695. } else {
  26696. return false;
  26697. }
  26698. };
  26699. _proto._root = function _root(rule, options) {
  26700. if (options === void 0) {
  26701. options = {};
  26702. }
  26703. var parser = new _parser.default(rule, this._parseOptions(options));
  26704. return parser.root;
  26705. };
  26706. _proto._parseOptions = function _parseOptions(options) {
  26707. return {
  26708. lossy: this._isLossy(options)
  26709. };
  26710. };
  26711. _proto._run = function _run(rule, options) {
  26712. var _this = this;
  26713. if (options === void 0) {
  26714. options = {};
  26715. }
  26716. return new Promise(function (resolve, reject) {
  26717. try {
  26718. var root = _this._root(rule, options);
  26719. Promise.resolve(_this.func(root)).then(function (transform) {
  26720. var string = undefined;
  26721. if (_this._shouldUpdateSelector(rule, options)) {
  26722. string = root.toString();
  26723. rule.selector = string;
  26724. }
  26725. return {
  26726. transform: transform,
  26727. root: root,
  26728. string: string
  26729. };
  26730. }).then(resolve, reject);
  26731. } catch (e) {
  26732. reject(e);
  26733. return;
  26734. }
  26735. });
  26736. };
  26737. _proto._runSync = function _runSync(rule, options) {
  26738. if (options === void 0) {
  26739. options = {};
  26740. }
  26741. var root = this._root(rule, options);
  26742. var transform = this.func(root);
  26743. if (transform && typeof transform.then === "function") {
  26744. throw new Error("Selector processor returned a promise to a synchronous call.");
  26745. }
  26746. var string = undefined;
  26747. if (options.updateSelector && typeof rule !== "string") {
  26748. string = root.toString();
  26749. rule.selector = string;
  26750. }
  26751. return {
  26752. transform: transform,
  26753. root: root,
  26754. string: string
  26755. };
  26756. }
  26757. /**
  26758. * Process rule into a selector AST.
  26759. *
  26760. * @param rule {postcss.Rule | string} The css selector to be processed
  26761. * @param options The options for processing
  26762. * @returns {Promise<parser.Root>} The AST of the selector after processing it.
  26763. */
  26764. ;
  26765. _proto.ast = function ast(rule, options) {
  26766. return this._run(rule, options).then(function (result) {
  26767. return result.root;
  26768. });
  26769. }
  26770. /**
  26771. * Process rule into a selector AST synchronously.
  26772. *
  26773. * @param rule {postcss.Rule | string} The css selector to be processed
  26774. * @param options The options for processing
  26775. * @returns {parser.Root} The AST of the selector after processing it.
  26776. */
  26777. ;
  26778. _proto.astSync = function astSync(rule, options) {
  26779. return this._runSync(rule, options).root;
  26780. }
  26781. /**
  26782. * Process a selector into a transformed value asynchronously
  26783. *
  26784. * @param rule {postcss.Rule | string} The css selector to be processed
  26785. * @param options The options for processing
  26786. * @returns {Promise<any>} The value returned by the processor.
  26787. */
  26788. ;
  26789. _proto.transform = function transform(rule, options) {
  26790. return this._run(rule, options).then(function (result) {
  26791. return result.transform;
  26792. });
  26793. }
  26794. /**
  26795. * Process a selector into a transformed value synchronously.
  26796. *
  26797. * @param rule {postcss.Rule | string} The css selector to be processed
  26798. * @param options The options for processing
  26799. * @returns {any} The value returned by the processor.
  26800. */
  26801. ;
  26802. _proto.transformSync = function transformSync(rule, options) {
  26803. return this._runSync(rule, options).transform;
  26804. }
  26805. /**
  26806. * Process a selector into a new selector string asynchronously.
  26807. *
  26808. * @param rule {postcss.Rule | string} The css selector to be processed
  26809. * @param options The options for processing
  26810. * @returns {string} the selector after processing.
  26811. */
  26812. ;
  26813. _proto.process = function process(rule, options) {
  26814. return this._run(rule, options).then(function (result) {
  26815. return result.string || result.root.toString();
  26816. });
  26817. }
  26818. /**
  26819. * Process a selector into a new selector string synchronously.
  26820. *
  26821. * @param rule {postcss.Rule | string} The css selector to be processed
  26822. * @param options The options for processing
  26823. * @returns {string} the selector after processing.
  26824. */
  26825. ;
  26826. _proto.processSync = function processSync(rule, options) {
  26827. var result = this._runSync(rule, options);
  26828. return result.string || result.root.toString();
  26829. };
  26830. return Processor;
  26831. }();
  26832. exports.default = Processor;
  26833. module.exports = exports.default;
  26834. });
  26835. var constructors = createCommonjsModule(function (module, exports) {
  26836. exports.__esModule = true;
  26837. 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;
  26838. var _attribute = _interopRequireDefault(attribute);
  26839. var _className = _interopRequireDefault(className);
  26840. var _combinator = _interopRequireDefault(combinator);
  26841. var _comment = _interopRequireDefault(comment);
  26842. var _id = _interopRequireDefault(id);
  26843. var _nesting = _interopRequireDefault(nesting);
  26844. var _pseudo = _interopRequireDefault(pseudo);
  26845. var _root = _interopRequireDefault(root);
  26846. var _selector = _interopRequireDefault(selector);
  26847. var _string = _interopRequireDefault(string);
  26848. var _tag = _interopRequireDefault(tag);
  26849. var _universal = _interopRequireDefault(universal);
  26850. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26851. var attribute$1 = function attribute(opts) {
  26852. return new _attribute.default(opts);
  26853. };
  26854. exports.attribute = attribute$1;
  26855. var className$1 = function className(opts) {
  26856. return new _className.default(opts);
  26857. };
  26858. exports.className = className$1;
  26859. var combinator$1 = function combinator(opts) {
  26860. return new _combinator.default(opts);
  26861. };
  26862. exports.combinator = combinator$1;
  26863. var comment$1 = function comment(opts) {
  26864. return new _comment.default(opts);
  26865. };
  26866. exports.comment = comment$1;
  26867. var id$1 = function id(opts) {
  26868. return new _id.default(opts);
  26869. };
  26870. exports.id = id$1;
  26871. var nesting$1 = function nesting(opts) {
  26872. return new _nesting.default(opts);
  26873. };
  26874. exports.nesting = nesting$1;
  26875. var pseudo$1 = function pseudo(opts) {
  26876. return new _pseudo.default(opts);
  26877. };
  26878. exports.pseudo = pseudo$1;
  26879. var root$1 = function root(opts) {
  26880. return new _root.default(opts);
  26881. };
  26882. exports.root = root$1;
  26883. var selector$1 = function selector(opts) {
  26884. return new _selector.default(opts);
  26885. };
  26886. exports.selector = selector$1;
  26887. var string$1 = function string(opts) {
  26888. return new _string.default(opts);
  26889. };
  26890. exports.string = string$1;
  26891. var tag$1 = function tag(opts) {
  26892. return new _tag.default(opts);
  26893. };
  26894. exports.tag = tag$1;
  26895. var universal$1 = function universal(opts) {
  26896. return new _universal.default(opts);
  26897. };
  26898. exports.universal = universal$1;
  26899. });
  26900. var guards = createCommonjsModule(function (module, exports) {
  26901. exports.__esModule = true;
  26902. exports.isNode = isNode;
  26903. exports.isPseudoElement = isPseudoElement;
  26904. exports.isPseudoClass = isPseudoClass;
  26905. exports.isContainer = isContainer;
  26906. exports.isNamespace = isNamespace;
  26907. 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;
  26908. var _IS_TYPE;
  26909. 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);
  26910. function isNode(node) {
  26911. return typeof node === "object" && IS_TYPE[node.type];
  26912. }
  26913. function isNodeType(type, node) {
  26914. return isNode(node) && node.type === type;
  26915. }
  26916. var isAttribute = isNodeType.bind(null, types$2.ATTRIBUTE);
  26917. exports.isAttribute = isAttribute;
  26918. var isClassName = isNodeType.bind(null, types$2.CLASS);
  26919. exports.isClassName = isClassName;
  26920. var isCombinator = isNodeType.bind(null, types$2.COMBINATOR);
  26921. exports.isCombinator = isCombinator;
  26922. var isComment = isNodeType.bind(null, types$2.COMMENT);
  26923. exports.isComment = isComment;
  26924. var isIdentifier = isNodeType.bind(null, types$2.ID);
  26925. exports.isIdentifier = isIdentifier;
  26926. var isNesting = isNodeType.bind(null, types$2.NESTING);
  26927. exports.isNesting = isNesting;
  26928. var isPseudo = isNodeType.bind(null, types$2.PSEUDO);
  26929. exports.isPseudo = isPseudo;
  26930. var isRoot = isNodeType.bind(null, types$2.ROOT);
  26931. exports.isRoot = isRoot;
  26932. var isSelector = isNodeType.bind(null, types$2.SELECTOR);
  26933. exports.isSelector = isSelector;
  26934. var isString = isNodeType.bind(null, types$2.STRING);
  26935. exports.isString = isString;
  26936. var isTag = isNodeType.bind(null, types$2.TAG);
  26937. exports.isTag = isTag;
  26938. var isUniversal = isNodeType.bind(null, types$2.UNIVERSAL);
  26939. exports.isUniversal = isUniversal;
  26940. function isPseudoElement(node) {
  26941. return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after");
  26942. }
  26943. function isPseudoClass(node) {
  26944. return isPseudo(node) && !isPseudoElement(node);
  26945. }
  26946. function isContainer(node) {
  26947. return !!(isNode(node) && node.walk);
  26948. }
  26949. function isNamespace(node) {
  26950. return isAttribute(node) || isTag(node);
  26951. }
  26952. });
  26953. var selectors = createCommonjsModule(function (module, exports) {
  26954. exports.__esModule = true;
  26955. Object.keys(types$2).forEach(function (key) {
  26956. if (key === "default" || key === "__esModule") return;
  26957. exports[key] = types$2[key];
  26958. });
  26959. Object.keys(constructors).forEach(function (key) {
  26960. if (key === "default" || key === "__esModule") return;
  26961. exports[key] = constructors[key];
  26962. });
  26963. Object.keys(guards).forEach(function (key) {
  26964. if (key === "default" || key === "__esModule") return;
  26965. exports[key] = guards[key];
  26966. });
  26967. });
  26968. var dist = createCommonjsModule(function (module, exports) {
  26969. exports.__esModule = true;
  26970. exports.default = void 0;
  26971. var _processor = _interopRequireDefault(processor);
  26972. var selectors$1 = _interopRequireWildcard(selectors);
  26973. 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; } }
  26974. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26975. var parser = function parser(processor) {
  26976. return new _processor.default(processor);
  26977. };
  26978. Object.assign(parser, selectors$1);
  26979. delete parser.__esModule;
  26980. var _default = parser;
  26981. exports.default = _default;
  26982. module.exports = exports.default;
  26983. });
  26984. var selectorParser = /*@__PURE__*/getDefaultExportFromCjs(dist);
  26985. const animationNameRE = /^(-\w+-)?animation-name$/;
  26986. const animationRE = /^(-\w+-)?animation$/;
  26987. var scopedPlugin = postcss__default.plugin('vue-scoped', (id) => (root) => {
  26988. const keyframes = Object.create(null);
  26989. const shortId = id.replace(/^data-v-/, '');
  26990. root.each(function rewriteSelectors(node) {
  26991. if (node.type !== 'rule') {
  26992. // handle media queries
  26993. if (node.type === 'atrule') {
  26994. if (node.name === 'media' || node.name === 'supports') {
  26995. node.each(rewriteSelectors);
  26996. }
  26997. else if (/-?keyframes$/.test(node.name)) {
  26998. // register keyframes
  26999. keyframes[node.params] = node.params = node.params + '-' + shortId;
  27000. }
  27001. }
  27002. return;
  27003. }
  27004. node.selector = selectorParser(selectors => {
  27005. function rewriteSelector(selector, slotted) {
  27006. let node = null;
  27007. let shouldInject = true;
  27008. // find the last child node to insert attribute selector
  27009. selector.each(n => {
  27010. // DEPRECATED ">>>" and "/deep/" combinator
  27011. if (n.type === 'combinator' &&
  27012. (n.value === '>>>' || n.value === '/deep/')) {
  27013. n.value = ' ';
  27014. n.spaces.before = n.spaces.after = '';
  27015. warn(`the >>> and /deep/ combinators have been deprecated. ` +
  27016. `Use :deep() instead.`);
  27017. return false;
  27018. }
  27019. if (n.type === 'pseudo') {
  27020. const { value } = n;
  27021. // deep: inject [id] attribute at the node before the ::v-deep
  27022. // combinator.
  27023. if (value === ':deep' || value === '::v-deep') {
  27024. if (n.nodes.length) {
  27025. // .foo ::v-deep(.bar) -> .foo[xxxxxxx] .bar
  27026. // replace the current node with ::v-deep's inner selector
  27027. let last = n;
  27028. n.nodes[0].each(ss => {
  27029. selector.insertAfter(last, ss);
  27030. last = ss;
  27031. });
  27032. // insert a space combinator before if it doesn't already have one
  27033. const prev = selector.at(selector.index(n) - 1);
  27034. if (!prev || !isSpaceCombinator(prev)) {
  27035. selector.insertAfter(n, selectorParser.combinator({
  27036. value: ' '
  27037. }));
  27038. }
  27039. selector.removeChild(n);
  27040. }
  27041. else {
  27042. // DEPRECATED usage
  27043. // .foo ::v-deep .bar -> .foo[xxxxxxx] .bar
  27044. warn(`::v-deep usage as a combinator has ` +
  27045. `been deprecated. Use :deep(<inner-selector>) instead.`);
  27046. const prev = selector.at(selector.index(n) - 1);
  27047. if (prev && isSpaceCombinator(prev)) {
  27048. selector.removeChild(prev);
  27049. }
  27050. selector.removeChild(n);
  27051. }
  27052. return false;
  27053. }
  27054. // slot: use selector inside `::v-slotted` and inject [id + '-s']
  27055. // instead.
  27056. // ::v-slotted(.foo) -> .foo[xxxxxxx-s]
  27057. if (value === ':slotted' || value === '::v-slotted') {
  27058. rewriteSelector(n.nodes[0], true /* slotted */);
  27059. let last = n;
  27060. n.nodes[0].each(ss => {
  27061. selector.insertAfter(last, ss);
  27062. last = ss;
  27063. });
  27064. // selector.insertAfter(n, n.nodes[0])
  27065. selector.removeChild(n);
  27066. // since slotted attribute already scopes the selector there's no
  27067. // need for the non-slot attribute.
  27068. shouldInject = false;
  27069. return false;
  27070. }
  27071. // global: replace with inner selector and do not inject [id].
  27072. // ::v-global(.foo) -> .foo
  27073. if (value === ':global' || value === '::v-global') {
  27074. selectors.insertAfter(selector, n.nodes[0]);
  27075. selectors.removeChild(selector);
  27076. return false;
  27077. }
  27078. }
  27079. if (n.type !== 'pseudo' && n.type !== 'combinator') {
  27080. node = n;
  27081. }
  27082. });
  27083. if (node) {
  27084. node.spaces.after = '';
  27085. }
  27086. else {
  27087. // For deep selectors & standalone pseudo selectors,
  27088. // the attribute selectors are prepended rather than appended.
  27089. // So all leading spaces must be eliminated to avoid problems.
  27090. selector.first.spaces.before = '';
  27091. }
  27092. if (shouldInject) {
  27093. const idToAdd = slotted ? id + '-s' : id;
  27094. selector.insertAfter(
  27095. // If node is null it means we need to inject [id] at the start
  27096. // insertAfter can handle `null` here
  27097. node, selectorParser.attribute({
  27098. attribute: idToAdd,
  27099. value: idToAdd,
  27100. raws: {},
  27101. quoteMark: `"`
  27102. }));
  27103. }
  27104. }
  27105. selectors.each(selector => rewriteSelector(selector));
  27106. }).processSync(node.selector);
  27107. });
  27108. if (Object.keys(keyframes).length) {
  27109. // If keyframes are found in this <style>, find and rewrite animation names
  27110. // in declarations.
  27111. // Caveat: this only works for keyframes and animation rules in the same
  27112. // <style> element.
  27113. // individual animation-name declaration
  27114. root.walkDecls(decl => {
  27115. if (animationNameRE.test(decl.prop)) {
  27116. decl.value = decl.value
  27117. .split(',')
  27118. .map(v => keyframes[v.trim()] || v.trim())
  27119. .join(',');
  27120. }
  27121. // shorthand
  27122. if (animationRE.test(decl.prop)) {
  27123. decl.value = decl.value
  27124. .split(',')
  27125. .map(v => {
  27126. const vals = v.trim().split(/\s+/);
  27127. const i = vals.findIndex(val => keyframes[val]);
  27128. if (i !== -1) {
  27129. vals.splice(i, 1, keyframes[vals[i]]);
  27130. return vals.join(' ');
  27131. }
  27132. else {
  27133. return v;
  27134. }
  27135. })
  27136. .join(',');
  27137. }
  27138. });
  27139. }
  27140. });
  27141. function isSpaceCombinator(node) {
  27142. return node.type === 'combinator' && /^\s+$/.test(node.value);
  27143. }
  27144. var SourceMapConsumer$2 = sourceMap.SourceMapConsumer;
  27145. var SourceMapGenerator$3 = sourceMap.SourceMapGenerator;
  27146. var mergeSourceMap = merge$1;
  27147. /**
  27148. * Merge old source map and new source map and return merged.
  27149. * If old or new source map value is falsy, return another one as it is.
  27150. *
  27151. * @param {object|string} [oldMap] old source map object
  27152. * @param {object|string} [newmap] new source map object
  27153. * @return {object|undefined} merged source map object, or undefined when both old and new source map are undefined
  27154. */
  27155. function merge$1(oldMap, newMap) {
  27156. if (!oldMap) return newMap
  27157. if (!newMap) return oldMap
  27158. var oldMapConsumer = new SourceMapConsumer$2(oldMap);
  27159. var newMapConsumer = new SourceMapConsumer$2(newMap);
  27160. var mergedMapGenerator = new SourceMapGenerator$3();
  27161. // iterate on new map and overwrite original position of new map with one of old map
  27162. newMapConsumer.eachMapping(function(m) {
  27163. // pass when `originalLine` is null.
  27164. // It occurs in case that the node does not have origin in original code.
  27165. if (m.originalLine == null) return
  27166. var origPosInOldMap = oldMapConsumer.originalPositionFor({
  27167. line: m.originalLine,
  27168. column: m.originalColumn
  27169. });
  27170. if (origPosInOldMap.source == null) return
  27171. mergedMapGenerator.addMapping({
  27172. original: {
  27173. line: origPosInOldMap.line,
  27174. column: origPosInOldMap.column
  27175. },
  27176. generated: {
  27177. line: m.generatedLine,
  27178. column: m.generatedColumn
  27179. },
  27180. source: origPosInOldMap.source,
  27181. name: origPosInOldMap.name
  27182. });
  27183. });
  27184. var consumers = [oldMapConsumer, newMapConsumer];
  27185. consumers.forEach(function(consumer) {
  27186. consumer.sources.forEach(function(sourceFile) {
  27187. mergedMapGenerator._sources.add(sourceFile);
  27188. var sourceContent = consumer.sourceContentFor(sourceFile);
  27189. if (sourceContent != null) {
  27190. mergedMapGenerator.setSourceContent(sourceFile, sourceContent);
  27191. }
  27192. });
  27193. });
  27194. mergedMapGenerator._sourceRoot = oldMap.sourceRoot;
  27195. mergedMapGenerator._file = oldMap.file;
  27196. return JSON.parse(mergedMapGenerator.toString())
  27197. }
  27198. // .scss/.sass processor
  27199. const scss = (source, map, options, load = require) => {
  27200. const nodeSass = load('sass');
  27201. const finalOptions = {
  27202. ...options,
  27203. data: getSource(source, options.filename, options.additionalData),
  27204. file: options.filename,
  27205. outFile: options.filename,
  27206. sourceMap: !!map
  27207. };
  27208. try {
  27209. const result = nodeSass.renderSync(finalOptions);
  27210. const dependencies = result.stats.includedFiles;
  27211. if (map) {
  27212. return {
  27213. code: result.css.toString(),
  27214. map: mergeSourceMap(map, JSON.parse(result.map.toString())),
  27215. errors: [],
  27216. dependencies
  27217. };
  27218. }
  27219. return { code: result.css.toString(), errors: [], dependencies };
  27220. }
  27221. catch (e) {
  27222. return { code: '', errors: [e], dependencies: [] };
  27223. }
  27224. };
  27225. const sass = (source, map, options, load) => scss(source, map, {
  27226. ...options,
  27227. indentedSyntax: true
  27228. }, load);
  27229. // .less
  27230. const less = (source, map, options, load = require) => {
  27231. const nodeLess = load('less');
  27232. let result;
  27233. let error = null;
  27234. nodeLess.render(getSource(source, options.filename, options.additionalData), { ...options, syncImport: true }, (err, output) => {
  27235. error = err;
  27236. result = output;
  27237. });
  27238. if (error)
  27239. return { code: '', errors: [error], dependencies: [] };
  27240. const dependencies = result.imports;
  27241. if (map) {
  27242. return {
  27243. code: result.css.toString(),
  27244. map: mergeSourceMap(map, result.map),
  27245. errors: [],
  27246. dependencies: dependencies
  27247. };
  27248. }
  27249. return {
  27250. code: result.css.toString(),
  27251. errors: [],
  27252. dependencies: dependencies
  27253. };
  27254. };
  27255. // .styl
  27256. const styl = (source, map, options, load = require) => {
  27257. const nodeStylus = load('stylus');
  27258. try {
  27259. const ref = nodeStylus(source);
  27260. Object.keys(options).forEach(key => ref.set(key, options[key]));
  27261. if (map)
  27262. ref.set('sourcemap', { inline: false, comment: false });
  27263. const result = ref.render();
  27264. const dependencies = ref.deps();
  27265. if (map) {
  27266. return {
  27267. code: result,
  27268. map: mergeSourceMap(map, ref.sourcemap),
  27269. errors: [],
  27270. dependencies
  27271. };
  27272. }
  27273. return { code: result, errors: [], dependencies };
  27274. }
  27275. catch (e) {
  27276. return { code: '', errors: [e], dependencies: [] };
  27277. }
  27278. };
  27279. function getSource(source, filename, additionalData) {
  27280. if (!additionalData)
  27281. return source;
  27282. if (isFunction(additionalData)) {
  27283. return additionalData(source, filename);
  27284. }
  27285. return additionalData + source;
  27286. }
  27287. const processors = {
  27288. less,
  27289. sass,
  27290. scss,
  27291. styl,
  27292. stylus: styl
  27293. };
  27294. function compileStyle(options) {
  27295. return doCompileStyle({
  27296. ...options,
  27297. isAsync: false
  27298. });
  27299. }
  27300. function compileStyleAsync(options) {
  27301. return doCompileStyle({ ...options, isAsync: true });
  27302. }
  27303. function doCompileStyle(options) {
  27304. const { filename, id, scoped = false, trim = true, isProd = false, modules = false, modulesOptions = {}, preprocessLang, postcssOptions, postcssPlugins } = options;
  27305. const preprocessor = preprocessLang && processors[preprocessLang];
  27306. const preProcessedSource = preprocessor && preprocess$1(options, preprocessor);
  27307. const map = preProcessedSource
  27308. ? preProcessedSource.map
  27309. : options.inMap || options.map;
  27310. const source = preProcessedSource ? preProcessedSource.code : options.source;
  27311. const shortId = id.replace(/^data-v-/, '');
  27312. const longId = `data-v-${shortId}`;
  27313. const plugins = (postcssPlugins || []).slice();
  27314. plugins.unshift(cssVarsPlugin({ id: shortId, isProd }));
  27315. if (trim) {
  27316. plugins.push(trimPlugin());
  27317. }
  27318. if (scoped) {
  27319. plugins.push(scopedPlugin(longId));
  27320. }
  27321. let cssModules;
  27322. if (modules) {
  27323. {
  27324. throw new Error('[@vue/compiler-sfc] `modules` option is not supported in the browser build.');
  27325. }
  27326. }
  27327. const postCSSOptions = {
  27328. ...postcssOptions,
  27329. to: filename,
  27330. from: filename
  27331. };
  27332. if (map) {
  27333. postCSSOptions.map = {
  27334. inline: false,
  27335. annotation: false,
  27336. prev: map
  27337. };
  27338. }
  27339. let result;
  27340. let code;
  27341. let outMap;
  27342. // stylus output include plain css. so need remove the repeat item
  27343. const dependencies = new Set(preProcessedSource ? preProcessedSource.dependencies : []);
  27344. // sass has filename self when provided filename option
  27345. dependencies.delete(filename);
  27346. const errors = [];
  27347. if (preProcessedSource && preProcessedSource.errors.length) {
  27348. errors.push(...preProcessedSource.errors);
  27349. }
  27350. const recordPlainCssDependencies = (messages) => {
  27351. messages.forEach(msg => {
  27352. if (msg.type === 'dependency') {
  27353. // postcss output path is absolute position path
  27354. dependencies.add(msg.file);
  27355. }
  27356. });
  27357. return dependencies;
  27358. };
  27359. try {
  27360. result = postcss__default(plugins).process(source, postCSSOptions);
  27361. // In async mode, return a promise.
  27362. if (options.isAsync) {
  27363. return result
  27364. .then(result => ({
  27365. code: result.css || '',
  27366. map: result.map && result.map.toJSON(),
  27367. errors,
  27368. modules: cssModules,
  27369. rawResult: result,
  27370. dependencies: recordPlainCssDependencies(result.messages)
  27371. }))
  27372. .catch(error => ({
  27373. code: '',
  27374. map: undefined,
  27375. errors: [...errors, error],
  27376. rawResult: undefined,
  27377. dependencies
  27378. }));
  27379. }
  27380. recordPlainCssDependencies(result.messages);
  27381. // force synchronous transform (we know we only have sync plugins)
  27382. code = result.css;
  27383. outMap = result.map;
  27384. }
  27385. catch (e) {
  27386. errors.push(e);
  27387. }
  27388. return {
  27389. code: code || ``,
  27390. map: outMap && outMap.toJSON(),
  27391. errors,
  27392. rawResult: result,
  27393. dependencies
  27394. };
  27395. }
  27396. function preprocess$1(options, preprocessor) {
  27397. if ( !options.preprocessCustomRequire) {
  27398. throw new Error(`[@vue/compiler-sfc] Style preprocessing in the browser build must ` +
  27399. `provide the \`preprocessCustomRequire\` option to return the in-browser ` +
  27400. `version of the preprocessor.`);
  27401. }
  27402. return preprocessor(options.source, options.map, {
  27403. filename: options.filename,
  27404. ...options.preprocessOptions
  27405. }, options.preprocessCustomRequire);
  27406. }
  27407. var global$1 = (typeof global !== "undefined" ? global :
  27408. typeof self !== "undefined" ? self :
  27409. typeof window !== "undefined" ? window : {});
  27410. var lookup = [];
  27411. var revLookup = [];
  27412. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  27413. var inited = false;
  27414. function init () {
  27415. inited = true;
  27416. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  27417. for (var i = 0, len = code.length; i < len; ++i) {
  27418. lookup[i] = code[i];
  27419. revLookup[code.charCodeAt(i)] = i;
  27420. }
  27421. revLookup['-'.charCodeAt(0)] = 62;
  27422. revLookup['_'.charCodeAt(0)] = 63;
  27423. }
  27424. function toByteArray (b64) {
  27425. if (!inited) {
  27426. init();
  27427. }
  27428. var i, j, l, tmp, placeHolders, arr;
  27429. var len = b64.length;
  27430. if (len % 4 > 0) {
  27431. throw new Error('Invalid string. Length must be a multiple of 4')
  27432. }
  27433. // the number of equal signs (place holders)
  27434. // if there are two placeholders, than the two characters before it
  27435. // represent one byte
  27436. // if there is only one, then the three characters before it represent 2 bytes
  27437. // this is just a cheap hack to not do indexOf twice
  27438. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  27439. // base64 is 4/3 + up to two characters of the original data
  27440. arr = new Arr(len * 3 / 4 - placeHolders);
  27441. // if there are placeholders, only get up to the last complete 4 chars
  27442. l = placeHolders > 0 ? len - 4 : len;
  27443. var L = 0;
  27444. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  27445. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  27446. arr[L++] = (tmp >> 16) & 0xFF;
  27447. arr[L++] = (tmp >> 8) & 0xFF;
  27448. arr[L++] = tmp & 0xFF;
  27449. }
  27450. if (placeHolders === 2) {
  27451. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  27452. arr[L++] = tmp & 0xFF;
  27453. } else if (placeHolders === 1) {
  27454. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  27455. arr[L++] = (tmp >> 8) & 0xFF;
  27456. arr[L++] = tmp & 0xFF;
  27457. }
  27458. return arr
  27459. }
  27460. function tripletToBase64 (num) {
  27461. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  27462. }
  27463. function encodeChunk (uint8, start, end) {
  27464. var tmp;
  27465. var output = [];
  27466. for (var i = start; i < end; i += 3) {
  27467. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  27468. output.push(tripletToBase64(tmp));
  27469. }
  27470. return output.join('')
  27471. }
  27472. function fromByteArray (uint8) {
  27473. if (!inited) {
  27474. init();
  27475. }
  27476. var tmp;
  27477. var len = uint8.length;
  27478. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  27479. var output = '';
  27480. var parts = [];
  27481. var maxChunkLength = 16383; // must be multiple of 3
  27482. // go through the array every three bytes, we'll deal with trailing stuff later
  27483. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  27484. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  27485. }
  27486. // pad the end with zeros, but make sure to not forget the extra bytes
  27487. if (extraBytes === 1) {
  27488. tmp = uint8[len - 1];
  27489. output += lookup[tmp >> 2];
  27490. output += lookup[(tmp << 4) & 0x3F];
  27491. output += '==';
  27492. } else if (extraBytes === 2) {
  27493. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  27494. output += lookup[tmp >> 10];
  27495. output += lookup[(tmp >> 4) & 0x3F];
  27496. output += lookup[(tmp << 2) & 0x3F];
  27497. output += '=';
  27498. }
  27499. parts.push(output);
  27500. return parts.join('')
  27501. }
  27502. function read (buffer, offset, isLE, mLen, nBytes) {
  27503. var e, m;
  27504. var eLen = nBytes * 8 - mLen - 1;
  27505. var eMax = (1 << eLen) - 1;
  27506. var eBias = eMax >> 1;
  27507. var nBits = -7;
  27508. var i = isLE ? (nBytes - 1) : 0;
  27509. var d = isLE ? -1 : 1;
  27510. var s = buffer[offset + i];
  27511. i += d;
  27512. e = s & ((1 << (-nBits)) - 1);
  27513. s >>= (-nBits);
  27514. nBits += eLen;
  27515. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  27516. m = e & ((1 << (-nBits)) - 1);
  27517. e >>= (-nBits);
  27518. nBits += mLen;
  27519. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  27520. if (e === 0) {
  27521. e = 1 - eBias;
  27522. } else if (e === eMax) {
  27523. return m ? NaN : ((s ? -1 : 1) * Infinity)
  27524. } else {
  27525. m = m + Math.pow(2, mLen);
  27526. e = e - eBias;
  27527. }
  27528. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  27529. }
  27530. function write (buffer, value, offset, isLE, mLen, nBytes) {
  27531. var e, m, c;
  27532. var eLen = nBytes * 8 - mLen - 1;
  27533. var eMax = (1 << eLen) - 1;
  27534. var eBias = eMax >> 1;
  27535. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  27536. var i = isLE ? 0 : (nBytes - 1);
  27537. var d = isLE ? 1 : -1;
  27538. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  27539. value = Math.abs(value);
  27540. if (isNaN(value) || value === Infinity) {
  27541. m = isNaN(value) ? 1 : 0;
  27542. e = eMax;
  27543. } else {
  27544. e = Math.floor(Math.log(value) / Math.LN2);
  27545. if (value * (c = Math.pow(2, -e)) < 1) {
  27546. e--;
  27547. c *= 2;
  27548. }
  27549. if (e + eBias >= 1) {
  27550. value += rt / c;
  27551. } else {
  27552. value += rt * Math.pow(2, 1 - eBias);
  27553. }
  27554. if (value * c >= 2) {
  27555. e++;
  27556. c /= 2;
  27557. }
  27558. if (e + eBias >= eMax) {
  27559. m = 0;
  27560. e = eMax;
  27561. } else if (e + eBias >= 1) {
  27562. m = (value * c - 1) * Math.pow(2, mLen);
  27563. e = e + eBias;
  27564. } else {
  27565. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  27566. e = 0;
  27567. }
  27568. }
  27569. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  27570. e = (e << mLen) | m;
  27571. eLen += mLen;
  27572. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  27573. buffer[offset + i - d] |= s * 128;
  27574. }
  27575. var toString$1 = {}.toString;
  27576. var isArray$1 = Array.isArray || function (arr) {
  27577. return toString$1.call(arr) == '[object Array]';
  27578. };
  27579. var INSPECT_MAX_BYTES = 50;
  27580. /**
  27581. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  27582. * === true Use Uint8Array implementation (fastest)
  27583. * === false Use Object implementation (most compatible, even IE6)
  27584. *
  27585. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  27586. * Opera 11.6+, iOS 4.2+.
  27587. *
  27588. * Due to various browser bugs, sometimes the Object implementation will be used even
  27589. * when the browser supports typed arrays.
  27590. *
  27591. * Note:
  27592. *
  27593. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  27594. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  27595. *
  27596. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  27597. *
  27598. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  27599. * incorrect length in some situations.
  27600. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  27601. * get the Object implementation, which is slower but behaves correctly.
  27602. */
  27603. Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
  27604. ? global$1.TYPED_ARRAY_SUPPORT
  27605. : true;
  27606. function kMaxLength () {
  27607. return Buffer.TYPED_ARRAY_SUPPORT
  27608. ? 0x7fffffff
  27609. : 0x3fffffff
  27610. }
  27611. function createBuffer (that, length) {
  27612. if (kMaxLength() < length) {
  27613. throw new RangeError('Invalid typed array length')
  27614. }
  27615. if (Buffer.TYPED_ARRAY_SUPPORT) {
  27616. // Return an augmented `Uint8Array` instance, for best performance
  27617. that = new Uint8Array(length);
  27618. that.__proto__ = Buffer.prototype;
  27619. } else {
  27620. // Fallback: Return an object instance of the Buffer class
  27621. if (that === null) {
  27622. that = new Buffer(length);
  27623. }
  27624. that.length = length;
  27625. }
  27626. return that
  27627. }
  27628. /**
  27629. * The Buffer constructor returns instances of `Uint8Array` that have their
  27630. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  27631. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  27632. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  27633. * returns a single octet.
  27634. *
  27635. * The `Uint8Array` prototype remains unmodified.
  27636. */
  27637. function Buffer (arg, encodingOrOffset, length) {
  27638. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  27639. return new Buffer(arg, encodingOrOffset, length)
  27640. }
  27641. // Common case.
  27642. if (typeof arg === 'number') {
  27643. if (typeof encodingOrOffset === 'string') {
  27644. throw new Error(
  27645. 'If encoding is specified then the first argument must be a string'
  27646. )
  27647. }
  27648. return allocUnsafe(this, arg)
  27649. }
  27650. return from(this, arg, encodingOrOffset, length)
  27651. }
  27652. Buffer.poolSize = 8192; // not used by this implementation
  27653. // TODO: Legacy, not needed anymore. Remove in next major version.
  27654. Buffer._augment = function (arr) {
  27655. arr.__proto__ = Buffer.prototype;
  27656. return arr
  27657. };
  27658. function from (that, value, encodingOrOffset, length) {
  27659. if (typeof value === 'number') {
  27660. throw new TypeError('"value" argument must not be a number')
  27661. }
  27662. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  27663. return fromArrayBuffer(that, value, encodingOrOffset, length)
  27664. }
  27665. if (typeof value === 'string') {
  27666. return fromString(that, value, encodingOrOffset)
  27667. }
  27668. return fromObject(that, value)
  27669. }
  27670. /**
  27671. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  27672. * if value is a number.
  27673. * Buffer.from(str[, encoding])
  27674. * Buffer.from(array)
  27675. * Buffer.from(buffer)
  27676. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  27677. **/
  27678. Buffer.from = function (value, encodingOrOffset, length) {
  27679. return from(null, value, encodingOrOffset, length)
  27680. };
  27681. if (Buffer.TYPED_ARRAY_SUPPORT) {
  27682. Buffer.prototype.__proto__ = Uint8Array.prototype;
  27683. Buffer.__proto__ = Uint8Array;
  27684. }
  27685. function assertSize (size) {
  27686. if (typeof size !== 'number') {
  27687. throw new TypeError('"size" argument must be a number')
  27688. } else if (size < 0) {
  27689. throw new RangeError('"size" argument must not be negative')
  27690. }
  27691. }
  27692. function alloc (that, size, fill, encoding) {
  27693. assertSize(size);
  27694. if (size <= 0) {
  27695. return createBuffer(that, size)
  27696. }
  27697. if (fill !== undefined) {
  27698. // Only pay attention to encoding if it's a string. This
  27699. // prevents accidentally sending in a number that would
  27700. // be interpretted as a start offset.
  27701. return typeof encoding === 'string'
  27702. ? createBuffer(that, size).fill(fill, encoding)
  27703. : createBuffer(that, size).fill(fill)
  27704. }
  27705. return createBuffer(that, size)
  27706. }
  27707. /**
  27708. * Creates a new filled Buffer instance.
  27709. * alloc(size[, fill[, encoding]])
  27710. **/
  27711. Buffer.alloc = function (size, fill, encoding) {
  27712. return alloc(null, size, fill, encoding)
  27713. };
  27714. function allocUnsafe (that, size) {
  27715. assertSize(size);
  27716. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  27717. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  27718. for (var i = 0; i < size; ++i) {
  27719. that[i] = 0;
  27720. }
  27721. }
  27722. return that
  27723. }
  27724. /**
  27725. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  27726. * */
  27727. Buffer.allocUnsafe = function (size) {
  27728. return allocUnsafe(null, size)
  27729. };
  27730. /**
  27731. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  27732. */
  27733. Buffer.allocUnsafeSlow = function (size) {
  27734. return allocUnsafe(null, size)
  27735. };
  27736. function fromString (that, string, encoding) {
  27737. if (typeof encoding !== 'string' || encoding === '') {
  27738. encoding = 'utf8';
  27739. }
  27740. if (!Buffer.isEncoding(encoding)) {
  27741. throw new TypeError('"encoding" must be a valid string encoding')
  27742. }
  27743. var length = byteLength(string, encoding) | 0;
  27744. that = createBuffer(that, length);
  27745. var actual = that.write(string, encoding);
  27746. if (actual !== length) {
  27747. // Writing a hex string, for example, that contains invalid characters will
  27748. // cause everything after the first invalid character to be ignored. (e.g.
  27749. // 'abxxcd' will be treated as 'ab')
  27750. that = that.slice(0, actual);
  27751. }
  27752. return that
  27753. }
  27754. function fromArrayLike (that, array) {
  27755. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  27756. that = createBuffer(that, length);
  27757. for (var i = 0; i < length; i += 1) {
  27758. that[i] = array[i] & 255;
  27759. }
  27760. return that
  27761. }
  27762. function fromArrayBuffer (that, array, byteOffset, length) {
  27763. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  27764. if (byteOffset < 0 || array.byteLength < byteOffset) {
  27765. throw new RangeError('\'offset\' is out of bounds')
  27766. }
  27767. if (array.byteLength < byteOffset + (length || 0)) {
  27768. throw new RangeError('\'length\' is out of bounds')
  27769. }
  27770. if (byteOffset === undefined && length === undefined) {
  27771. array = new Uint8Array(array);
  27772. } else if (length === undefined) {
  27773. array = new Uint8Array(array, byteOffset);
  27774. } else {
  27775. array = new Uint8Array(array, byteOffset, length);
  27776. }
  27777. if (Buffer.TYPED_ARRAY_SUPPORT) {
  27778. // Return an augmented `Uint8Array` instance, for best performance
  27779. that = array;
  27780. that.__proto__ = Buffer.prototype;
  27781. } else {
  27782. // Fallback: Return an object instance of the Buffer class
  27783. that = fromArrayLike(that, array);
  27784. }
  27785. return that
  27786. }
  27787. function fromObject (that, obj) {
  27788. if (internalIsBuffer(obj)) {
  27789. var len = checked(obj.length) | 0;
  27790. that = createBuffer(that, len);
  27791. if (that.length === 0) {
  27792. return that
  27793. }
  27794. obj.copy(that, 0, 0, len);
  27795. return that
  27796. }
  27797. if (obj) {
  27798. if ((typeof ArrayBuffer !== 'undefined' &&
  27799. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  27800. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  27801. return createBuffer(that, 0)
  27802. }
  27803. return fromArrayLike(that, obj)
  27804. }
  27805. if (obj.type === 'Buffer' && isArray$1(obj.data)) {
  27806. return fromArrayLike(that, obj.data)
  27807. }
  27808. }
  27809. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  27810. }
  27811. function checked (length) {
  27812. // Note: cannot use `length < kMaxLength()` here because that fails when
  27813. // length is NaN (which is otherwise coerced to zero.)
  27814. if (length >= kMaxLength()) {
  27815. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  27816. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  27817. }
  27818. return length | 0
  27819. }
  27820. Buffer.isBuffer = isBuffer;
  27821. function internalIsBuffer (b) {
  27822. return !!(b != null && b._isBuffer)
  27823. }
  27824. Buffer.compare = function compare (a, b) {
  27825. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  27826. throw new TypeError('Arguments must be Buffers')
  27827. }
  27828. if (a === b) return 0
  27829. var x = a.length;
  27830. var y = b.length;
  27831. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  27832. if (a[i] !== b[i]) {
  27833. x = a[i];
  27834. y = b[i];
  27835. break
  27836. }
  27837. }
  27838. if (x < y) return -1
  27839. if (y < x) return 1
  27840. return 0
  27841. };
  27842. Buffer.isEncoding = function isEncoding (encoding) {
  27843. switch (String(encoding).toLowerCase()) {
  27844. case 'hex':
  27845. case 'utf8':
  27846. case 'utf-8':
  27847. case 'ascii':
  27848. case 'latin1':
  27849. case 'binary':
  27850. case 'base64':
  27851. case 'ucs2':
  27852. case 'ucs-2':
  27853. case 'utf16le':
  27854. case 'utf-16le':
  27855. return true
  27856. default:
  27857. return false
  27858. }
  27859. };
  27860. Buffer.concat = function concat (list, length) {
  27861. if (!isArray$1(list)) {
  27862. throw new TypeError('"list" argument must be an Array of Buffers')
  27863. }
  27864. if (list.length === 0) {
  27865. return Buffer.alloc(0)
  27866. }
  27867. var i;
  27868. if (length === undefined) {
  27869. length = 0;
  27870. for (i = 0; i < list.length; ++i) {
  27871. length += list[i].length;
  27872. }
  27873. }
  27874. var buffer = Buffer.allocUnsafe(length);
  27875. var pos = 0;
  27876. for (i = 0; i < list.length; ++i) {
  27877. var buf = list[i];
  27878. if (!internalIsBuffer(buf)) {
  27879. throw new TypeError('"list" argument must be an Array of Buffers')
  27880. }
  27881. buf.copy(buffer, pos);
  27882. pos += buf.length;
  27883. }
  27884. return buffer
  27885. };
  27886. function byteLength (string, encoding) {
  27887. if (internalIsBuffer(string)) {
  27888. return string.length
  27889. }
  27890. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  27891. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  27892. return string.byteLength
  27893. }
  27894. if (typeof string !== 'string') {
  27895. string = '' + string;
  27896. }
  27897. var len = string.length;
  27898. if (len === 0) return 0
  27899. // Use a for loop to avoid recursion
  27900. var loweredCase = false;
  27901. for (;;) {
  27902. switch (encoding) {
  27903. case 'ascii':
  27904. case 'latin1':
  27905. case 'binary':
  27906. return len
  27907. case 'utf8':
  27908. case 'utf-8':
  27909. case undefined:
  27910. return utf8ToBytes(string).length
  27911. case 'ucs2':
  27912. case 'ucs-2':
  27913. case 'utf16le':
  27914. case 'utf-16le':
  27915. return len * 2
  27916. case 'hex':
  27917. return len >>> 1
  27918. case 'base64':
  27919. return base64ToBytes(string).length
  27920. default:
  27921. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  27922. encoding = ('' + encoding).toLowerCase();
  27923. loweredCase = true;
  27924. }
  27925. }
  27926. }
  27927. Buffer.byteLength = byteLength;
  27928. function slowToString (encoding, start, end) {
  27929. var loweredCase = false;
  27930. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  27931. // property of a typed array.
  27932. // This behaves neither like String nor Uint8Array in that we set start/end
  27933. // to their upper/lower bounds if the value passed is out of range.
  27934. // undefined is handled specially as per ECMA-262 6th Edition,
  27935. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  27936. if (start === undefined || start < 0) {
  27937. start = 0;
  27938. }
  27939. // Return early if start > this.length. Done here to prevent potential uint32
  27940. // coercion fail below.
  27941. if (start > this.length) {
  27942. return ''
  27943. }
  27944. if (end === undefined || end > this.length) {
  27945. end = this.length;
  27946. }
  27947. if (end <= 0) {
  27948. return ''
  27949. }
  27950. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  27951. end >>>= 0;
  27952. start >>>= 0;
  27953. if (end <= start) {
  27954. return ''
  27955. }
  27956. if (!encoding) encoding = 'utf8';
  27957. while (true) {
  27958. switch (encoding) {
  27959. case 'hex':
  27960. return hexSlice(this, start, end)
  27961. case 'utf8':
  27962. case 'utf-8':
  27963. return utf8Slice(this, start, end)
  27964. case 'ascii':
  27965. return asciiSlice(this, start, end)
  27966. case 'latin1':
  27967. case 'binary':
  27968. return latin1Slice(this, start, end)
  27969. case 'base64':
  27970. return base64Slice(this, start, end)
  27971. case 'ucs2':
  27972. case 'ucs-2':
  27973. case 'utf16le':
  27974. case 'utf-16le':
  27975. return utf16leSlice(this, start, end)
  27976. default:
  27977. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  27978. encoding = (encoding + '').toLowerCase();
  27979. loweredCase = true;
  27980. }
  27981. }
  27982. }
  27983. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  27984. // Buffer instances.
  27985. Buffer.prototype._isBuffer = true;
  27986. function swap$1 (b, n, m) {
  27987. var i = b[n];
  27988. b[n] = b[m];
  27989. b[m] = i;
  27990. }
  27991. Buffer.prototype.swap16 = function swap16 () {
  27992. var len = this.length;
  27993. if (len % 2 !== 0) {
  27994. throw new RangeError('Buffer size must be a multiple of 16-bits')
  27995. }
  27996. for (var i = 0; i < len; i += 2) {
  27997. swap$1(this, i, i + 1);
  27998. }
  27999. return this
  28000. };
  28001. Buffer.prototype.swap32 = function swap32 () {
  28002. var len = this.length;
  28003. if (len % 4 !== 0) {
  28004. throw new RangeError('Buffer size must be a multiple of 32-bits')
  28005. }
  28006. for (var i = 0; i < len; i += 4) {
  28007. swap$1(this, i, i + 3);
  28008. swap$1(this, i + 1, i + 2);
  28009. }
  28010. return this
  28011. };
  28012. Buffer.prototype.swap64 = function swap64 () {
  28013. var len = this.length;
  28014. if (len % 8 !== 0) {
  28015. throw new RangeError('Buffer size must be a multiple of 64-bits')
  28016. }
  28017. for (var i = 0; i < len; i += 8) {
  28018. swap$1(this, i, i + 7);
  28019. swap$1(this, i + 1, i + 6);
  28020. swap$1(this, i + 2, i + 5);
  28021. swap$1(this, i + 3, i + 4);
  28022. }
  28023. return this
  28024. };
  28025. Buffer.prototype.toString = function toString () {
  28026. var length = this.length | 0;
  28027. if (length === 0) return ''
  28028. if (arguments.length === 0) return utf8Slice(this, 0, length)
  28029. return slowToString.apply(this, arguments)
  28030. };
  28031. Buffer.prototype.equals = function equals (b) {
  28032. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  28033. if (this === b) return true
  28034. return Buffer.compare(this, b) === 0
  28035. };
  28036. Buffer.prototype.inspect = function inspect () {
  28037. var str = '';
  28038. var max = INSPECT_MAX_BYTES;
  28039. if (this.length > 0) {
  28040. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  28041. if (this.length > max) str += ' ... ';
  28042. }
  28043. return '<Buffer ' + str + '>'
  28044. };
  28045. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  28046. if (!internalIsBuffer(target)) {
  28047. throw new TypeError('Argument must be a Buffer')
  28048. }
  28049. if (start === undefined) {
  28050. start = 0;
  28051. }
  28052. if (end === undefined) {
  28053. end = target ? target.length : 0;
  28054. }
  28055. if (thisStart === undefined) {
  28056. thisStart = 0;
  28057. }
  28058. if (thisEnd === undefined) {
  28059. thisEnd = this.length;
  28060. }
  28061. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  28062. throw new RangeError('out of range index')
  28063. }
  28064. if (thisStart >= thisEnd && start >= end) {
  28065. return 0
  28066. }
  28067. if (thisStart >= thisEnd) {
  28068. return -1
  28069. }
  28070. if (start >= end) {
  28071. return 1
  28072. }
  28073. start >>>= 0;
  28074. end >>>= 0;
  28075. thisStart >>>= 0;
  28076. thisEnd >>>= 0;
  28077. if (this === target) return 0
  28078. var x = thisEnd - thisStart;
  28079. var y = end - start;
  28080. var len = Math.min(x, y);
  28081. var thisCopy = this.slice(thisStart, thisEnd);
  28082. var targetCopy = target.slice(start, end);
  28083. for (var i = 0; i < len; ++i) {
  28084. if (thisCopy[i] !== targetCopy[i]) {
  28085. x = thisCopy[i];
  28086. y = targetCopy[i];
  28087. break
  28088. }
  28089. }
  28090. if (x < y) return -1
  28091. if (y < x) return 1
  28092. return 0
  28093. };
  28094. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  28095. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  28096. //
  28097. // Arguments:
  28098. // - buffer - a Buffer to search
  28099. // - val - a string, Buffer, or number
  28100. // - byteOffset - an index into `buffer`; will be clamped to an int32
  28101. // - encoding - an optional encoding, relevant is val is a string
  28102. // - dir - true for indexOf, false for lastIndexOf
  28103. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  28104. // Empty buffer means no match
  28105. if (buffer.length === 0) return -1
  28106. // Normalize byteOffset
  28107. if (typeof byteOffset === 'string') {
  28108. encoding = byteOffset;
  28109. byteOffset = 0;
  28110. } else if (byteOffset > 0x7fffffff) {
  28111. byteOffset = 0x7fffffff;
  28112. } else if (byteOffset < -0x80000000) {
  28113. byteOffset = -0x80000000;
  28114. }
  28115. byteOffset = +byteOffset; // Coerce to Number.
  28116. if (isNaN(byteOffset)) {
  28117. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  28118. byteOffset = dir ? 0 : (buffer.length - 1);
  28119. }
  28120. // Normalize byteOffset: negative offsets start from the end of the buffer
  28121. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  28122. if (byteOffset >= buffer.length) {
  28123. if (dir) return -1
  28124. else byteOffset = buffer.length - 1;
  28125. } else if (byteOffset < 0) {
  28126. if (dir) byteOffset = 0;
  28127. else return -1
  28128. }
  28129. // Normalize val
  28130. if (typeof val === 'string') {
  28131. val = Buffer.from(val, encoding);
  28132. }
  28133. // Finally, search either indexOf (if dir is true) or lastIndexOf
  28134. if (internalIsBuffer(val)) {
  28135. // Special case: looking for empty string/buffer always fails
  28136. if (val.length === 0) {
  28137. return -1
  28138. }
  28139. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  28140. } else if (typeof val === 'number') {
  28141. val = val & 0xFF; // Search for a byte value [0-255]
  28142. if (Buffer.TYPED_ARRAY_SUPPORT &&
  28143. typeof Uint8Array.prototype.indexOf === 'function') {
  28144. if (dir) {
  28145. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  28146. } else {
  28147. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  28148. }
  28149. }
  28150. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  28151. }
  28152. throw new TypeError('val must be string, number or Buffer')
  28153. }
  28154. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  28155. var indexSize = 1;
  28156. var arrLength = arr.length;
  28157. var valLength = val.length;
  28158. if (encoding !== undefined) {
  28159. encoding = String(encoding).toLowerCase();
  28160. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  28161. encoding === 'utf16le' || encoding === 'utf-16le') {
  28162. if (arr.length < 2 || val.length < 2) {
  28163. return -1
  28164. }
  28165. indexSize = 2;
  28166. arrLength /= 2;
  28167. valLength /= 2;
  28168. byteOffset /= 2;
  28169. }
  28170. }
  28171. function read (buf, i) {
  28172. if (indexSize === 1) {
  28173. return buf[i]
  28174. } else {
  28175. return buf.readUInt16BE(i * indexSize)
  28176. }
  28177. }
  28178. var i;
  28179. if (dir) {
  28180. var foundIndex = -1;
  28181. for (i = byteOffset; i < arrLength; i++) {
  28182. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  28183. if (foundIndex === -1) foundIndex = i;
  28184. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  28185. } else {
  28186. if (foundIndex !== -1) i -= i - foundIndex;
  28187. foundIndex = -1;
  28188. }
  28189. }
  28190. } else {
  28191. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  28192. for (i = byteOffset; i >= 0; i--) {
  28193. var found = true;
  28194. for (var j = 0; j < valLength; j++) {
  28195. if (read(arr, i + j) !== read(val, j)) {
  28196. found = false;
  28197. break
  28198. }
  28199. }
  28200. if (found) return i
  28201. }
  28202. }
  28203. return -1
  28204. }
  28205. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  28206. return this.indexOf(val, byteOffset, encoding) !== -1
  28207. };
  28208. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  28209. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  28210. };
  28211. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  28212. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  28213. };
  28214. function hexWrite (buf, string, offset, length) {
  28215. offset = Number(offset) || 0;
  28216. var remaining = buf.length - offset;
  28217. if (!length) {
  28218. length = remaining;
  28219. } else {
  28220. length = Number(length);
  28221. if (length > remaining) {
  28222. length = remaining;
  28223. }
  28224. }
  28225. // must be an even number of digits
  28226. var strLen = string.length;
  28227. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  28228. if (length > strLen / 2) {
  28229. length = strLen / 2;
  28230. }
  28231. for (var i = 0; i < length; ++i) {
  28232. var parsed = parseInt(string.substr(i * 2, 2), 16);
  28233. if (isNaN(parsed)) return i
  28234. buf[offset + i] = parsed;
  28235. }
  28236. return i
  28237. }
  28238. function utf8Write (buf, string, offset, length) {
  28239. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  28240. }
  28241. function asciiWrite (buf, string, offset, length) {
  28242. return blitBuffer(asciiToBytes(string), buf, offset, length)
  28243. }
  28244. function latin1Write (buf, string, offset, length) {
  28245. return asciiWrite(buf, string, offset, length)
  28246. }
  28247. function base64Write (buf, string, offset, length) {
  28248. return blitBuffer(base64ToBytes(string), buf, offset, length)
  28249. }
  28250. function ucs2Write (buf, string, offset, length) {
  28251. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  28252. }
  28253. Buffer.prototype.write = function write (string, offset, length, encoding) {
  28254. // Buffer#write(string)
  28255. if (offset === undefined) {
  28256. encoding = 'utf8';
  28257. length = this.length;
  28258. offset = 0;
  28259. // Buffer#write(string, encoding)
  28260. } else if (length === undefined && typeof offset === 'string') {
  28261. encoding = offset;
  28262. length = this.length;
  28263. offset = 0;
  28264. // Buffer#write(string, offset[, length][, encoding])
  28265. } else if (isFinite(offset)) {
  28266. offset = offset | 0;
  28267. if (isFinite(length)) {
  28268. length = length | 0;
  28269. if (encoding === undefined) encoding = 'utf8';
  28270. } else {
  28271. encoding = length;
  28272. length = undefined;
  28273. }
  28274. // legacy write(string, encoding, offset, length) - remove in v0.13
  28275. } else {
  28276. throw new Error(
  28277. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  28278. )
  28279. }
  28280. var remaining = this.length - offset;
  28281. if (length === undefined || length > remaining) length = remaining;
  28282. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  28283. throw new RangeError('Attempt to write outside buffer bounds')
  28284. }
  28285. if (!encoding) encoding = 'utf8';
  28286. var loweredCase = false;
  28287. for (;;) {
  28288. switch (encoding) {
  28289. case 'hex':
  28290. return hexWrite(this, string, offset, length)
  28291. case 'utf8':
  28292. case 'utf-8':
  28293. return utf8Write(this, string, offset, length)
  28294. case 'ascii':
  28295. return asciiWrite(this, string, offset, length)
  28296. case 'latin1':
  28297. case 'binary':
  28298. return latin1Write(this, string, offset, length)
  28299. case 'base64':
  28300. // Warning: maxLength not taken into account in base64Write
  28301. return base64Write(this, string, offset, length)
  28302. case 'ucs2':
  28303. case 'ucs-2':
  28304. case 'utf16le':
  28305. case 'utf-16le':
  28306. return ucs2Write(this, string, offset, length)
  28307. default:
  28308. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  28309. encoding = ('' + encoding).toLowerCase();
  28310. loweredCase = true;
  28311. }
  28312. }
  28313. };
  28314. Buffer.prototype.toJSON = function toJSON () {
  28315. return {
  28316. type: 'Buffer',
  28317. data: Array.prototype.slice.call(this._arr || this, 0)
  28318. }
  28319. };
  28320. function base64Slice (buf, start, end) {
  28321. if (start === 0 && end === buf.length) {
  28322. return fromByteArray(buf)
  28323. } else {
  28324. return fromByteArray(buf.slice(start, end))
  28325. }
  28326. }
  28327. function utf8Slice (buf, start, end) {
  28328. end = Math.min(buf.length, end);
  28329. var res = [];
  28330. var i = start;
  28331. while (i < end) {
  28332. var firstByte = buf[i];
  28333. var codePoint = null;
  28334. var bytesPerSequence = (firstByte > 0xEF) ? 4
  28335. : (firstByte > 0xDF) ? 3
  28336. : (firstByte > 0xBF) ? 2
  28337. : 1;
  28338. if (i + bytesPerSequence <= end) {
  28339. var secondByte, thirdByte, fourthByte, tempCodePoint;
  28340. switch (bytesPerSequence) {
  28341. case 1:
  28342. if (firstByte < 0x80) {
  28343. codePoint = firstByte;
  28344. }
  28345. break
  28346. case 2:
  28347. secondByte = buf[i + 1];
  28348. if ((secondByte & 0xC0) === 0x80) {
  28349. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  28350. if (tempCodePoint > 0x7F) {
  28351. codePoint = tempCodePoint;
  28352. }
  28353. }
  28354. break
  28355. case 3:
  28356. secondByte = buf[i + 1];
  28357. thirdByte = buf[i + 2];
  28358. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  28359. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  28360. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  28361. codePoint = tempCodePoint;
  28362. }
  28363. }
  28364. break
  28365. case 4:
  28366. secondByte = buf[i + 1];
  28367. thirdByte = buf[i + 2];
  28368. fourthByte = buf[i + 3];
  28369. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  28370. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  28371. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  28372. codePoint = tempCodePoint;
  28373. }
  28374. }
  28375. }
  28376. }
  28377. if (codePoint === null) {
  28378. // we did not generate a valid codePoint so insert a
  28379. // replacement char (U+FFFD) and advance only 1 byte
  28380. codePoint = 0xFFFD;
  28381. bytesPerSequence = 1;
  28382. } else if (codePoint > 0xFFFF) {
  28383. // encode to utf16 (surrogate pair dance)
  28384. codePoint -= 0x10000;
  28385. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  28386. codePoint = 0xDC00 | codePoint & 0x3FF;
  28387. }
  28388. res.push(codePoint);
  28389. i += bytesPerSequence;
  28390. }
  28391. return decodeCodePointsArray(res)
  28392. }
  28393. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  28394. // the lowest limit is Chrome, with 0x10000 args.
  28395. // We go 1 magnitude less, for safety
  28396. var MAX_ARGUMENTS_LENGTH = 0x1000;
  28397. function decodeCodePointsArray (codePoints) {
  28398. var len = codePoints.length;
  28399. if (len <= MAX_ARGUMENTS_LENGTH) {
  28400. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  28401. }
  28402. // Decode in chunks to avoid "call stack size exceeded".
  28403. var res = '';
  28404. var i = 0;
  28405. while (i < len) {
  28406. res += String.fromCharCode.apply(
  28407. String,
  28408. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  28409. );
  28410. }
  28411. return res
  28412. }
  28413. function asciiSlice (buf, start, end) {
  28414. var ret = '';
  28415. end = Math.min(buf.length, end);
  28416. for (var i = start; i < end; ++i) {
  28417. ret += String.fromCharCode(buf[i] & 0x7F);
  28418. }
  28419. return ret
  28420. }
  28421. function latin1Slice (buf, start, end) {
  28422. var ret = '';
  28423. end = Math.min(buf.length, end);
  28424. for (var i = start; i < end; ++i) {
  28425. ret += String.fromCharCode(buf[i]);
  28426. }
  28427. return ret
  28428. }
  28429. function hexSlice (buf, start, end) {
  28430. var len = buf.length;
  28431. if (!start || start < 0) start = 0;
  28432. if (!end || end < 0 || end > len) end = len;
  28433. var out = '';
  28434. for (var i = start; i < end; ++i) {
  28435. out += toHex(buf[i]);
  28436. }
  28437. return out
  28438. }
  28439. function utf16leSlice (buf, start, end) {
  28440. var bytes = buf.slice(start, end);
  28441. var res = '';
  28442. for (var i = 0; i < bytes.length; i += 2) {
  28443. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  28444. }
  28445. return res
  28446. }
  28447. Buffer.prototype.slice = function slice (start, end) {
  28448. var len = this.length;
  28449. start = ~~start;
  28450. end = end === undefined ? len : ~~end;
  28451. if (start < 0) {
  28452. start += len;
  28453. if (start < 0) start = 0;
  28454. } else if (start > len) {
  28455. start = len;
  28456. }
  28457. if (end < 0) {
  28458. end += len;
  28459. if (end < 0) end = 0;
  28460. } else if (end > len) {
  28461. end = len;
  28462. }
  28463. if (end < start) end = start;
  28464. var newBuf;
  28465. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28466. newBuf = this.subarray(start, end);
  28467. newBuf.__proto__ = Buffer.prototype;
  28468. } else {
  28469. var sliceLen = end - start;
  28470. newBuf = new Buffer(sliceLen, undefined);
  28471. for (var i = 0; i < sliceLen; ++i) {
  28472. newBuf[i] = this[i + start];
  28473. }
  28474. }
  28475. return newBuf
  28476. };
  28477. /*
  28478. * Need to make sure that buffer isn't trying to write out of bounds.
  28479. */
  28480. function checkOffset (offset, ext, length) {
  28481. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  28482. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  28483. }
  28484. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  28485. offset = offset | 0;
  28486. byteLength = byteLength | 0;
  28487. if (!noAssert) checkOffset(offset, byteLength, this.length);
  28488. var val = this[offset];
  28489. var mul = 1;
  28490. var i = 0;
  28491. while (++i < byteLength && (mul *= 0x100)) {
  28492. val += this[offset + i] * mul;
  28493. }
  28494. return val
  28495. };
  28496. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  28497. offset = offset | 0;
  28498. byteLength = byteLength | 0;
  28499. if (!noAssert) {
  28500. checkOffset(offset, byteLength, this.length);
  28501. }
  28502. var val = this[offset + --byteLength];
  28503. var mul = 1;
  28504. while (byteLength > 0 && (mul *= 0x100)) {
  28505. val += this[offset + --byteLength] * mul;
  28506. }
  28507. return val
  28508. };
  28509. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  28510. if (!noAssert) checkOffset(offset, 1, this.length);
  28511. return this[offset]
  28512. };
  28513. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  28514. if (!noAssert) checkOffset(offset, 2, this.length);
  28515. return this[offset] | (this[offset + 1] << 8)
  28516. };
  28517. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  28518. if (!noAssert) checkOffset(offset, 2, this.length);
  28519. return (this[offset] << 8) | this[offset + 1]
  28520. };
  28521. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  28522. if (!noAssert) checkOffset(offset, 4, this.length);
  28523. return ((this[offset]) |
  28524. (this[offset + 1] << 8) |
  28525. (this[offset + 2] << 16)) +
  28526. (this[offset + 3] * 0x1000000)
  28527. };
  28528. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  28529. if (!noAssert) checkOffset(offset, 4, this.length);
  28530. return (this[offset] * 0x1000000) +
  28531. ((this[offset + 1] << 16) |
  28532. (this[offset + 2] << 8) |
  28533. this[offset + 3])
  28534. };
  28535. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  28536. offset = offset | 0;
  28537. byteLength = byteLength | 0;
  28538. if (!noAssert) checkOffset(offset, byteLength, this.length);
  28539. var val = this[offset];
  28540. var mul = 1;
  28541. var i = 0;
  28542. while (++i < byteLength && (mul *= 0x100)) {
  28543. val += this[offset + i] * mul;
  28544. }
  28545. mul *= 0x80;
  28546. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  28547. return val
  28548. };
  28549. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  28550. offset = offset | 0;
  28551. byteLength = byteLength | 0;
  28552. if (!noAssert) checkOffset(offset, byteLength, this.length);
  28553. var i = byteLength;
  28554. var mul = 1;
  28555. var val = this[offset + --i];
  28556. while (i > 0 && (mul *= 0x100)) {
  28557. val += this[offset + --i] * mul;
  28558. }
  28559. mul *= 0x80;
  28560. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  28561. return val
  28562. };
  28563. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  28564. if (!noAssert) checkOffset(offset, 1, this.length);
  28565. if (!(this[offset] & 0x80)) return (this[offset])
  28566. return ((0xff - this[offset] + 1) * -1)
  28567. };
  28568. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  28569. if (!noAssert) checkOffset(offset, 2, this.length);
  28570. var val = this[offset] | (this[offset + 1] << 8);
  28571. return (val & 0x8000) ? val | 0xFFFF0000 : val
  28572. };
  28573. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  28574. if (!noAssert) checkOffset(offset, 2, this.length);
  28575. var val = this[offset + 1] | (this[offset] << 8);
  28576. return (val & 0x8000) ? val | 0xFFFF0000 : val
  28577. };
  28578. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  28579. if (!noAssert) checkOffset(offset, 4, this.length);
  28580. return (this[offset]) |
  28581. (this[offset + 1] << 8) |
  28582. (this[offset + 2] << 16) |
  28583. (this[offset + 3] << 24)
  28584. };
  28585. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  28586. if (!noAssert) checkOffset(offset, 4, this.length);
  28587. return (this[offset] << 24) |
  28588. (this[offset + 1] << 16) |
  28589. (this[offset + 2] << 8) |
  28590. (this[offset + 3])
  28591. };
  28592. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  28593. if (!noAssert) checkOffset(offset, 4, this.length);
  28594. return read(this, offset, true, 23, 4)
  28595. };
  28596. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  28597. if (!noAssert) checkOffset(offset, 4, this.length);
  28598. return read(this, offset, false, 23, 4)
  28599. };
  28600. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  28601. if (!noAssert) checkOffset(offset, 8, this.length);
  28602. return read(this, offset, true, 52, 8)
  28603. };
  28604. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  28605. if (!noAssert) checkOffset(offset, 8, this.length);
  28606. return read(this, offset, false, 52, 8)
  28607. };
  28608. function checkInt (buf, value, offset, ext, max, min) {
  28609. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  28610. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  28611. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  28612. }
  28613. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  28614. value = +value;
  28615. offset = offset | 0;
  28616. byteLength = byteLength | 0;
  28617. if (!noAssert) {
  28618. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  28619. checkInt(this, value, offset, byteLength, maxBytes, 0);
  28620. }
  28621. var mul = 1;
  28622. var i = 0;
  28623. this[offset] = value & 0xFF;
  28624. while (++i < byteLength && (mul *= 0x100)) {
  28625. this[offset + i] = (value / mul) & 0xFF;
  28626. }
  28627. return offset + byteLength
  28628. };
  28629. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  28630. value = +value;
  28631. offset = offset | 0;
  28632. byteLength = byteLength | 0;
  28633. if (!noAssert) {
  28634. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  28635. checkInt(this, value, offset, byteLength, maxBytes, 0);
  28636. }
  28637. var i = byteLength - 1;
  28638. var mul = 1;
  28639. this[offset + i] = value & 0xFF;
  28640. while (--i >= 0 && (mul *= 0x100)) {
  28641. this[offset + i] = (value / mul) & 0xFF;
  28642. }
  28643. return offset + byteLength
  28644. };
  28645. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  28646. value = +value;
  28647. offset = offset | 0;
  28648. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  28649. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  28650. this[offset] = (value & 0xff);
  28651. return offset + 1
  28652. };
  28653. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  28654. if (value < 0) value = 0xffff + value + 1;
  28655. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  28656. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  28657. (littleEndian ? i : 1 - i) * 8;
  28658. }
  28659. }
  28660. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  28661. value = +value;
  28662. offset = offset | 0;
  28663. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  28664. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28665. this[offset] = (value & 0xff);
  28666. this[offset + 1] = (value >>> 8);
  28667. } else {
  28668. objectWriteUInt16(this, value, offset, true);
  28669. }
  28670. return offset + 2
  28671. };
  28672. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  28673. value = +value;
  28674. offset = offset | 0;
  28675. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  28676. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28677. this[offset] = (value >>> 8);
  28678. this[offset + 1] = (value & 0xff);
  28679. } else {
  28680. objectWriteUInt16(this, value, offset, false);
  28681. }
  28682. return offset + 2
  28683. };
  28684. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  28685. if (value < 0) value = 0xffffffff + value + 1;
  28686. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  28687. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  28688. }
  28689. }
  28690. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  28691. value = +value;
  28692. offset = offset | 0;
  28693. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  28694. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28695. this[offset + 3] = (value >>> 24);
  28696. this[offset + 2] = (value >>> 16);
  28697. this[offset + 1] = (value >>> 8);
  28698. this[offset] = (value & 0xff);
  28699. } else {
  28700. objectWriteUInt32(this, value, offset, true);
  28701. }
  28702. return offset + 4
  28703. };
  28704. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  28705. value = +value;
  28706. offset = offset | 0;
  28707. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  28708. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28709. this[offset] = (value >>> 24);
  28710. this[offset + 1] = (value >>> 16);
  28711. this[offset + 2] = (value >>> 8);
  28712. this[offset + 3] = (value & 0xff);
  28713. } else {
  28714. objectWriteUInt32(this, value, offset, false);
  28715. }
  28716. return offset + 4
  28717. };
  28718. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  28719. value = +value;
  28720. offset = offset | 0;
  28721. if (!noAssert) {
  28722. var limit = Math.pow(2, 8 * byteLength - 1);
  28723. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  28724. }
  28725. var i = 0;
  28726. var mul = 1;
  28727. var sub = 0;
  28728. this[offset] = value & 0xFF;
  28729. while (++i < byteLength && (mul *= 0x100)) {
  28730. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  28731. sub = 1;
  28732. }
  28733. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  28734. }
  28735. return offset + byteLength
  28736. };
  28737. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  28738. value = +value;
  28739. offset = offset | 0;
  28740. if (!noAssert) {
  28741. var limit = Math.pow(2, 8 * byteLength - 1);
  28742. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  28743. }
  28744. var i = byteLength - 1;
  28745. var mul = 1;
  28746. var sub = 0;
  28747. this[offset + i] = value & 0xFF;
  28748. while (--i >= 0 && (mul *= 0x100)) {
  28749. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  28750. sub = 1;
  28751. }
  28752. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  28753. }
  28754. return offset + byteLength
  28755. };
  28756. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  28757. value = +value;
  28758. offset = offset | 0;
  28759. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  28760. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  28761. if (value < 0) value = 0xff + value + 1;
  28762. this[offset] = (value & 0xff);
  28763. return offset + 1
  28764. };
  28765. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  28766. value = +value;
  28767. offset = offset | 0;
  28768. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  28769. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28770. this[offset] = (value & 0xff);
  28771. this[offset + 1] = (value >>> 8);
  28772. } else {
  28773. objectWriteUInt16(this, value, offset, true);
  28774. }
  28775. return offset + 2
  28776. };
  28777. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  28778. value = +value;
  28779. offset = offset | 0;
  28780. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  28781. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28782. this[offset] = (value >>> 8);
  28783. this[offset + 1] = (value & 0xff);
  28784. } else {
  28785. objectWriteUInt16(this, value, offset, false);
  28786. }
  28787. return offset + 2
  28788. };
  28789. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  28790. value = +value;
  28791. offset = offset | 0;
  28792. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  28793. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28794. this[offset] = (value & 0xff);
  28795. this[offset + 1] = (value >>> 8);
  28796. this[offset + 2] = (value >>> 16);
  28797. this[offset + 3] = (value >>> 24);
  28798. } else {
  28799. objectWriteUInt32(this, value, offset, true);
  28800. }
  28801. return offset + 4
  28802. };
  28803. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  28804. value = +value;
  28805. offset = offset | 0;
  28806. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  28807. if (value < 0) value = 0xffffffff + value + 1;
  28808. if (Buffer.TYPED_ARRAY_SUPPORT) {
  28809. this[offset] = (value >>> 24);
  28810. this[offset + 1] = (value >>> 16);
  28811. this[offset + 2] = (value >>> 8);
  28812. this[offset + 3] = (value & 0xff);
  28813. } else {
  28814. objectWriteUInt32(this, value, offset, false);
  28815. }
  28816. return offset + 4
  28817. };
  28818. function checkIEEE754 (buf, value, offset, ext, max, min) {
  28819. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  28820. if (offset < 0) throw new RangeError('Index out of range')
  28821. }
  28822. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  28823. if (!noAssert) {
  28824. checkIEEE754(buf, value, offset, 4);
  28825. }
  28826. write(buf, value, offset, littleEndian, 23, 4);
  28827. return offset + 4
  28828. }
  28829. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  28830. return writeFloat(this, value, offset, true, noAssert)
  28831. };
  28832. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  28833. return writeFloat(this, value, offset, false, noAssert)
  28834. };
  28835. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  28836. if (!noAssert) {
  28837. checkIEEE754(buf, value, offset, 8);
  28838. }
  28839. write(buf, value, offset, littleEndian, 52, 8);
  28840. return offset + 8
  28841. }
  28842. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  28843. return writeDouble(this, value, offset, true, noAssert)
  28844. };
  28845. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  28846. return writeDouble(this, value, offset, false, noAssert)
  28847. };
  28848. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  28849. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  28850. if (!start) start = 0;
  28851. if (!end && end !== 0) end = this.length;
  28852. if (targetStart >= target.length) targetStart = target.length;
  28853. if (!targetStart) targetStart = 0;
  28854. if (end > 0 && end < start) end = start;
  28855. // Copy 0 bytes; we're done
  28856. if (end === start) return 0
  28857. if (target.length === 0 || this.length === 0) return 0
  28858. // Fatal error conditions
  28859. if (targetStart < 0) {
  28860. throw new RangeError('targetStart out of bounds')
  28861. }
  28862. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  28863. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  28864. // Are we oob?
  28865. if (end > this.length) end = this.length;
  28866. if (target.length - targetStart < end - start) {
  28867. end = target.length - targetStart + start;
  28868. }
  28869. var len = end - start;
  28870. var i;
  28871. if (this === target && start < targetStart && targetStart < end) {
  28872. // descending copy from end
  28873. for (i = len - 1; i >= 0; --i) {
  28874. target[i + targetStart] = this[i + start];
  28875. }
  28876. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  28877. // ascending copy from start
  28878. for (i = 0; i < len; ++i) {
  28879. target[i + targetStart] = this[i + start];
  28880. }
  28881. } else {
  28882. Uint8Array.prototype.set.call(
  28883. target,
  28884. this.subarray(start, start + len),
  28885. targetStart
  28886. );
  28887. }
  28888. return len
  28889. };
  28890. // Usage:
  28891. // buffer.fill(number[, offset[, end]])
  28892. // buffer.fill(buffer[, offset[, end]])
  28893. // buffer.fill(string[, offset[, end]][, encoding])
  28894. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  28895. // Handle string cases:
  28896. if (typeof val === 'string') {
  28897. if (typeof start === 'string') {
  28898. encoding = start;
  28899. start = 0;
  28900. end = this.length;
  28901. } else if (typeof end === 'string') {
  28902. encoding = end;
  28903. end = this.length;
  28904. }
  28905. if (val.length === 1) {
  28906. var code = val.charCodeAt(0);
  28907. if (code < 256) {
  28908. val = code;
  28909. }
  28910. }
  28911. if (encoding !== undefined && typeof encoding !== 'string') {
  28912. throw new TypeError('encoding must be a string')
  28913. }
  28914. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  28915. throw new TypeError('Unknown encoding: ' + encoding)
  28916. }
  28917. } else if (typeof val === 'number') {
  28918. val = val & 255;
  28919. }
  28920. // Invalid ranges are not set to a default, so can range check early.
  28921. if (start < 0 || this.length < start || this.length < end) {
  28922. throw new RangeError('Out of range index')
  28923. }
  28924. if (end <= start) {
  28925. return this
  28926. }
  28927. start = start >>> 0;
  28928. end = end === undefined ? this.length : end >>> 0;
  28929. if (!val) val = 0;
  28930. var i;
  28931. if (typeof val === 'number') {
  28932. for (i = start; i < end; ++i) {
  28933. this[i] = val;
  28934. }
  28935. } else {
  28936. var bytes = internalIsBuffer(val)
  28937. ? val
  28938. : utf8ToBytes(new Buffer(val, encoding).toString());
  28939. var len = bytes.length;
  28940. for (i = 0; i < end - start; ++i) {
  28941. this[i + start] = bytes[i % len];
  28942. }
  28943. }
  28944. return this
  28945. };
  28946. // HELPER FUNCTIONS
  28947. // ================
  28948. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  28949. function base64clean (str) {
  28950. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  28951. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  28952. // Node converts strings with length < 2 to ''
  28953. if (str.length < 2) return ''
  28954. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  28955. while (str.length % 4 !== 0) {
  28956. str = str + '=';
  28957. }
  28958. return str
  28959. }
  28960. function stringtrim (str) {
  28961. if (str.trim) return str.trim()
  28962. return str.replace(/^\s+|\s+$/g, '')
  28963. }
  28964. function toHex (n) {
  28965. if (n < 16) return '0' + n.toString(16)
  28966. return n.toString(16)
  28967. }
  28968. function utf8ToBytes (string, units) {
  28969. units = units || Infinity;
  28970. var codePoint;
  28971. var length = string.length;
  28972. var leadSurrogate = null;
  28973. var bytes = [];
  28974. for (var i = 0; i < length; ++i) {
  28975. codePoint = string.charCodeAt(i);
  28976. // is surrogate component
  28977. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  28978. // last char was a lead
  28979. if (!leadSurrogate) {
  28980. // no lead yet
  28981. if (codePoint > 0xDBFF) {
  28982. // unexpected trail
  28983. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  28984. continue
  28985. } else if (i + 1 === length) {
  28986. // unpaired lead
  28987. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  28988. continue
  28989. }
  28990. // valid lead
  28991. leadSurrogate = codePoint;
  28992. continue
  28993. }
  28994. // 2 leads in a row
  28995. if (codePoint < 0xDC00) {
  28996. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  28997. leadSurrogate = codePoint;
  28998. continue
  28999. }
  29000. // valid surrogate pair
  29001. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  29002. } else if (leadSurrogate) {
  29003. // valid bmp char, but last char was a lead
  29004. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  29005. }
  29006. leadSurrogate = null;
  29007. // encode utf8
  29008. if (codePoint < 0x80) {
  29009. if ((units -= 1) < 0) break
  29010. bytes.push(codePoint);
  29011. } else if (codePoint < 0x800) {
  29012. if ((units -= 2) < 0) break
  29013. bytes.push(
  29014. codePoint >> 0x6 | 0xC0,
  29015. codePoint & 0x3F | 0x80
  29016. );
  29017. } else if (codePoint < 0x10000) {
  29018. if ((units -= 3) < 0) break
  29019. bytes.push(
  29020. codePoint >> 0xC | 0xE0,
  29021. codePoint >> 0x6 & 0x3F | 0x80,
  29022. codePoint & 0x3F | 0x80
  29023. );
  29024. } else if (codePoint < 0x110000) {
  29025. if ((units -= 4) < 0) break
  29026. bytes.push(
  29027. codePoint >> 0x12 | 0xF0,
  29028. codePoint >> 0xC & 0x3F | 0x80,
  29029. codePoint >> 0x6 & 0x3F | 0x80,
  29030. codePoint & 0x3F | 0x80
  29031. );
  29032. } else {
  29033. throw new Error('Invalid code point')
  29034. }
  29035. }
  29036. return bytes
  29037. }
  29038. function asciiToBytes (str) {
  29039. var byteArray = [];
  29040. for (var i = 0; i < str.length; ++i) {
  29041. // Node's code seems to be doing this and not & 0x7F..
  29042. byteArray.push(str.charCodeAt(i) & 0xFF);
  29043. }
  29044. return byteArray
  29045. }
  29046. function utf16leToBytes (str, units) {
  29047. var c, hi, lo;
  29048. var byteArray = [];
  29049. for (var i = 0; i < str.length; ++i) {
  29050. if ((units -= 2) < 0) break
  29051. c = str.charCodeAt(i);
  29052. hi = c >> 8;
  29053. lo = c % 256;
  29054. byteArray.push(lo);
  29055. byteArray.push(hi);
  29056. }
  29057. return byteArray
  29058. }
  29059. function base64ToBytes (str) {
  29060. return toByteArray(base64clean(str))
  29061. }
  29062. function blitBuffer (src, dst, offset, length) {
  29063. for (var i = 0; i < length; ++i) {
  29064. if ((i + offset >= dst.length) || (i >= src.length)) break
  29065. dst[i + offset] = src[i];
  29066. }
  29067. return i
  29068. }
  29069. function isnan (val) {
  29070. return val !== val // eslint-disable-line no-self-compare
  29071. }
  29072. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  29073. // The _isBuffer check is for Safari 5-7 support, because it's missing
  29074. // Object.prototype.constructor. Remove this eventually
  29075. function isBuffer(obj) {
  29076. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  29077. }
  29078. function isFastBuffer (obj) {
  29079. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  29080. }
  29081. // For Node v0.10 support. Remove this eventually.
  29082. function isSlowBuffer (obj) {
  29083. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  29084. }
  29085. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  29086. function encode$2(decoded) {
  29087. var sourceFileIndex = 0; // second field
  29088. var sourceCodeLine = 0; // third field
  29089. var sourceCodeColumn = 0; // fourth field
  29090. var nameIndex = 0; // fifth field
  29091. var mappings = '';
  29092. for (var i = 0; i < decoded.length; i++) {
  29093. var line = decoded[i];
  29094. if (i > 0)
  29095. mappings += ';';
  29096. if (line.length === 0)
  29097. continue;
  29098. var generatedCodeColumn = 0; // first field
  29099. var lineMappings = [];
  29100. for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
  29101. var segment = line_1[_i];
  29102. var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
  29103. generatedCodeColumn = segment[0];
  29104. if (segment.length > 1) {
  29105. segmentMappings +=
  29106. encodeInteger(segment[1] - sourceFileIndex) +
  29107. encodeInteger(segment[2] - sourceCodeLine) +
  29108. encodeInteger(segment[3] - sourceCodeColumn);
  29109. sourceFileIndex = segment[1];
  29110. sourceCodeLine = segment[2];
  29111. sourceCodeColumn = segment[3];
  29112. }
  29113. if (segment.length === 5) {
  29114. segmentMappings += encodeInteger(segment[4] - nameIndex);
  29115. nameIndex = segment[4];
  29116. }
  29117. lineMappings.push(segmentMappings);
  29118. }
  29119. mappings += lineMappings.join(',');
  29120. }
  29121. return mappings;
  29122. }
  29123. function encodeInteger(num) {
  29124. var result = '';
  29125. num = num < 0 ? (-num << 1) | 1 : num << 1;
  29126. do {
  29127. var clamped = num & 31;
  29128. num >>>= 5;
  29129. if (num > 0) {
  29130. clamped |= 32;
  29131. }
  29132. result += chars[clamped];
  29133. } while (num > 0);
  29134. return result;
  29135. }
  29136. var BitSet = function BitSet(arg) {
  29137. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  29138. };
  29139. BitSet.prototype.add = function add (n) {
  29140. this.bits[n >> 5] |= 1 << (n & 31);
  29141. };
  29142. BitSet.prototype.has = function has (n) {
  29143. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  29144. };
  29145. var Chunk = function Chunk(start, end, content) {
  29146. this.start = start;
  29147. this.end = end;
  29148. this.original = content;
  29149. this.intro = '';
  29150. this.outro = '';
  29151. this.content = content;
  29152. this.storeName = false;
  29153. this.edited = false;
  29154. // we make these non-enumerable, for sanity while debugging
  29155. Object.defineProperties(this, {
  29156. previous: { writable: true, value: null },
  29157. next: { writable: true, value: null }
  29158. });
  29159. };
  29160. Chunk.prototype.appendLeft = function appendLeft (content) {
  29161. this.outro += content;
  29162. };
  29163. Chunk.prototype.appendRight = function appendRight (content) {
  29164. this.intro = this.intro + content;
  29165. };
  29166. Chunk.prototype.clone = function clone () {
  29167. var chunk = new Chunk(this.start, this.end, this.original);
  29168. chunk.intro = this.intro;
  29169. chunk.outro = this.outro;
  29170. chunk.content = this.content;
  29171. chunk.storeName = this.storeName;
  29172. chunk.edited = this.edited;
  29173. return chunk;
  29174. };
  29175. Chunk.prototype.contains = function contains (index) {
  29176. return this.start < index && index < this.end;
  29177. };
  29178. Chunk.prototype.eachNext = function eachNext (fn) {
  29179. var chunk = this;
  29180. while (chunk) {
  29181. fn(chunk);
  29182. chunk = chunk.next;
  29183. }
  29184. };
  29185. Chunk.prototype.eachPrevious = function eachPrevious (fn) {
  29186. var chunk = this;
  29187. while (chunk) {
  29188. fn(chunk);
  29189. chunk = chunk.previous;
  29190. }
  29191. };
  29192. Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
  29193. this.content = content;
  29194. if (!contentOnly) {
  29195. this.intro = '';
  29196. this.outro = '';
  29197. }
  29198. this.storeName = storeName;
  29199. this.edited = true;
  29200. return this;
  29201. };
  29202. Chunk.prototype.prependLeft = function prependLeft (content) {
  29203. this.outro = content + this.outro;
  29204. };
  29205. Chunk.prototype.prependRight = function prependRight (content) {
  29206. this.intro = content + this.intro;
  29207. };
  29208. Chunk.prototype.split = function split (index) {
  29209. var sliceIndex = index - this.start;
  29210. var originalBefore = this.original.slice(0, sliceIndex);
  29211. var originalAfter = this.original.slice(sliceIndex);
  29212. this.original = originalBefore;
  29213. var newChunk = new Chunk(index, this.end, originalAfter);
  29214. newChunk.outro = this.outro;
  29215. this.outro = '';
  29216. this.end = index;
  29217. if (this.edited) {
  29218. // TODO is this block necessary?...
  29219. newChunk.edit('', false);
  29220. this.content = '';
  29221. } else {
  29222. this.content = originalBefore;
  29223. }
  29224. newChunk.next = this.next;
  29225. if (newChunk.next) { newChunk.next.previous = newChunk; }
  29226. newChunk.previous = this;
  29227. this.next = newChunk;
  29228. return newChunk;
  29229. };
  29230. Chunk.prototype.toString = function toString () {
  29231. return this.intro + this.content + this.outro;
  29232. };
  29233. Chunk.prototype.trimEnd = function trimEnd (rx) {
  29234. this.outro = this.outro.replace(rx, '');
  29235. if (this.outro.length) { return true; }
  29236. var trimmed = this.content.replace(rx, '');
  29237. if (trimmed.length) {
  29238. if (trimmed !== this.content) {
  29239. this.split(this.start + trimmed.length).edit('', undefined, true);
  29240. }
  29241. return true;
  29242. } else {
  29243. this.edit('', undefined, true);
  29244. this.intro = this.intro.replace(rx, '');
  29245. if (this.intro.length) { return true; }
  29246. }
  29247. };
  29248. Chunk.prototype.trimStart = function trimStart (rx) {
  29249. this.intro = this.intro.replace(rx, '');
  29250. if (this.intro.length) { return true; }
  29251. var trimmed = this.content.replace(rx, '');
  29252. if (trimmed.length) {
  29253. if (trimmed !== this.content) {
  29254. this.split(this.end - trimmed.length);
  29255. this.edit('', undefined, true);
  29256. }
  29257. return true;
  29258. } else {
  29259. this.edit('', undefined, true);
  29260. this.outro = this.outro.replace(rx, '');
  29261. if (this.outro.length) { return true; }
  29262. }
  29263. };
  29264. var btoa = function () {
  29265. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  29266. };
  29267. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  29268. btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
  29269. } else if (typeof Buffer === 'function') {
  29270. btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
  29271. }
  29272. var SourceMap = function SourceMap(properties) {
  29273. this.version = 3;
  29274. this.file = properties.file;
  29275. this.sources = properties.sources;
  29276. this.sourcesContent = properties.sourcesContent;
  29277. this.names = properties.names;
  29278. this.mappings = encode$2(properties.mappings);
  29279. };
  29280. SourceMap.prototype.toString = function toString () {
  29281. return JSON.stringify(this);
  29282. };
  29283. SourceMap.prototype.toUrl = function toUrl () {
  29284. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  29285. };
  29286. function guessIndent(code) {
  29287. var lines = code.split('\n');
  29288. var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
  29289. var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
  29290. if (tabbed.length === 0 && spaced.length === 0) {
  29291. return null;
  29292. }
  29293. // More lines tabbed than spaced? Assume tabs, and
  29294. // default to tabs in the case of a tie (or nothing
  29295. // to go on)
  29296. if (tabbed.length >= spaced.length) {
  29297. return '\t';
  29298. }
  29299. // Otherwise, we need to guess the multiple
  29300. var min = spaced.reduce(function (previous, current) {
  29301. var numSpaces = /^ +/.exec(current)[0].length;
  29302. return Math.min(numSpaces, previous);
  29303. }, Infinity);
  29304. return new Array(min + 1).join(' ');
  29305. }
  29306. function getRelativePath(from, to) {
  29307. var fromParts = from.split(/[/\\]/);
  29308. var toParts = to.split(/[/\\]/);
  29309. fromParts.pop(); // get dirname
  29310. while (fromParts[0] === toParts[0]) {
  29311. fromParts.shift();
  29312. toParts.shift();
  29313. }
  29314. if (fromParts.length) {
  29315. var i = fromParts.length;
  29316. while (i--) { fromParts[i] = '..'; }
  29317. }
  29318. return fromParts.concat(toParts).join('/');
  29319. }
  29320. var toString$2 = Object.prototype.toString;
  29321. function isObject$1(thing) {
  29322. return toString$2.call(thing) === '[object Object]';
  29323. }
  29324. function getLocator(source) {
  29325. var originalLines = source.split('\n');
  29326. var lineOffsets = [];
  29327. for (var i = 0, pos = 0; i < originalLines.length; i++) {
  29328. lineOffsets.push(pos);
  29329. pos += originalLines[i].length + 1;
  29330. }
  29331. return function locate(index) {
  29332. var i = 0;
  29333. var j = lineOffsets.length;
  29334. while (i < j) {
  29335. var m = (i + j) >> 1;
  29336. if (index < lineOffsets[m]) {
  29337. j = m;
  29338. } else {
  29339. i = m + 1;
  29340. }
  29341. }
  29342. var line = i - 1;
  29343. var column = index - lineOffsets[line];
  29344. return { line: line, column: column };
  29345. };
  29346. }
  29347. var Mappings = function Mappings(hires) {
  29348. this.hires = hires;
  29349. this.generatedCodeLine = 0;
  29350. this.generatedCodeColumn = 0;
  29351. this.raw = [];
  29352. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  29353. this.pending = null;
  29354. };
  29355. Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
  29356. if (content.length) {
  29357. var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  29358. if (nameIndex >= 0) {
  29359. segment.push(nameIndex);
  29360. }
  29361. this.rawSegments.push(segment);
  29362. } else if (this.pending) {
  29363. this.rawSegments.push(this.pending);
  29364. }
  29365. this.advance(content);
  29366. this.pending = null;
  29367. };
  29368. Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
  29369. var originalCharIndex = chunk.start;
  29370. var first = true;
  29371. while (originalCharIndex < chunk.end) {
  29372. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  29373. this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
  29374. }
  29375. if (original[originalCharIndex] === '\n') {
  29376. loc.line += 1;
  29377. loc.column = 0;
  29378. this.generatedCodeLine += 1;
  29379. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  29380. this.generatedCodeColumn = 0;
  29381. first = true;
  29382. } else {
  29383. loc.column += 1;
  29384. this.generatedCodeColumn += 1;
  29385. first = false;
  29386. }
  29387. originalCharIndex += 1;
  29388. }
  29389. this.pending = null;
  29390. };
  29391. Mappings.prototype.advance = function advance (str) {
  29392. if (!str) { return; }
  29393. var lines = str.split('\n');
  29394. if (lines.length > 1) {
  29395. for (var i = 0; i < lines.length - 1; i++) {
  29396. this.generatedCodeLine++;
  29397. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  29398. }
  29399. this.generatedCodeColumn = 0;
  29400. }
  29401. this.generatedCodeColumn += lines[lines.length - 1].length;
  29402. };
  29403. var n = '\n';
  29404. var warned = {
  29405. insertLeft: false,
  29406. insertRight: false,
  29407. storeName: false
  29408. };
  29409. var MagicString = function MagicString(string, options) {
  29410. if ( options === void 0 ) options = {};
  29411. var chunk = new Chunk(0, string.length, string);
  29412. Object.defineProperties(this, {
  29413. original: { writable: true, value: string },
  29414. outro: { writable: true, value: '' },
  29415. intro: { writable: true, value: '' },
  29416. firstChunk: { writable: true, value: chunk },
  29417. lastChunk: { writable: true, value: chunk },
  29418. lastSearchedChunk: { writable: true, value: chunk },
  29419. byStart: { writable: true, value: {} },
  29420. byEnd: { writable: true, value: {} },
  29421. filename: { writable: true, value: options.filename },
  29422. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  29423. sourcemapLocations: { writable: true, value: new BitSet() },
  29424. storedNames: { writable: true, value: {} },
  29425. indentStr: { writable: true, value: guessIndent(string) }
  29426. });
  29427. this.byStart[0] = chunk;
  29428. this.byEnd[string.length] = chunk;
  29429. };
  29430. MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
  29431. this.sourcemapLocations.add(char);
  29432. };
  29433. MagicString.prototype.append = function append (content) {
  29434. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  29435. this.outro += content;
  29436. return this;
  29437. };
  29438. MagicString.prototype.appendLeft = function appendLeft (index, content) {
  29439. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  29440. this._split(index);
  29441. var chunk = this.byEnd[index];
  29442. if (chunk) {
  29443. chunk.appendLeft(content);
  29444. } else {
  29445. this.intro += content;
  29446. }
  29447. return this;
  29448. };
  29449. MagicString.prototype.appendRight = function appendRight (index, content) {
  29450. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  29451. this._split(index);
  29452. var chunk = this.byStart[index];
  29453. if (chunk) {
  29454. chunk.appendRight(content);
  29455. } else {
  29456. this.outro += content;
  29457. }
  29458. return this;
  29459. };
  29460. MagicString.prototype.clone = function clone () {
  29461. var cloned = new MagicString(this.original, { filename: this.filename });
  29462. var originalChunk = this.firstChunk;
  29463. var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  29464. while (originalChunk) {
  29465. cloned.byStart[clonedChunk.start] = clonedChunk;
  29466. cloned.byEnd[clonedChunk.end] = clonedChunk;
  29467. var nextOriginalChunk = originalChunk.next;
  29468. var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  29469. if (nextClonedChunk) {
  29470. clonedChunk.next = nextClonedChunk;
  29471. nextClonedChunk.previous = clonedChunk;
  29472. clonedChunk = nextClonedChunk;
  29473. }
  29474. originalChunk = nextOriginalChunk;
  29475. }
  29476. cloned.lastChunk = clonedChunk;
  29477. if (this.indentExclusionRanges) {
  29478. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  29479. }
  29480. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  29481. cloned.intro = this.intro;
  29482. cloned.outro = this.outro;
  29483. return cloned;
  29484. };
  29485. MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
  29486. var this$1 = this;
  29487. options = options || {};
  29488. var sourceIndex = 0;
  29489. var names = Object.keys(this.storedNames);
  29490. var mappings = new Mappings(options.hires);
  29491. var locate = getLocator(this.original);
  29492. if (this.intro) {
  29493. mappings.advance(this.intro);
  29494. }
  29495. this.firstChunk.eachNext(function (chunk) {
  29496. var loc = locate(chunk.start);
  29497. if (chunk.intro.length) { mappings.advance(chunk.intro); }
  29498. if (chunk.edited) {
  29499. mappings.addEdit(
  29500. sourceIndex,
  29501. chunk.content,
  29502. loc,
  29503. chunk.storeName ? names.indexOf(chunk.original) : -1
  29504. );
  29505. } else {
  29506. mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
  29507. }
  29508. if (chunk.outro.length) { mappings.advance(chunk.outro); }
  29509. });
  29510. return {
  29511. file: options.file ? options.file.split(/[/\\]/).pop() : null,
  29512. sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
  29513. sourcesContent: options.includeContent ? [this.original] : [null],
  29514. names: names,
  29515. mappings: mappings.raw
  29516. };
  29517. };
  29518. MagicString.prototype.generateMap = function generateMap (options) {
  29519. return new SourceMap(this.generateDecodedMap(options));
  29520. };
  29521. MagicString.prototype.getIndentString = function getIndentString () {
  29522. return this.indentStr === null ? '\t' : this.indentStr;
  29523. };
  29524. MagicString.prototype.indent = function indent (indentStr, options) {
  29525. var pattern = /^[^\r\n]/gm;
  29526. if (isObject$1(indentStr)) {
  29527. options = indentStr;
  29528. indentStr = undefined;
  29529. }
  29530. indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
  29531. if (indentStr === '') { return this; } // noop
  29532. options = options || {};
  29533. // Process exclusion ranges
  29534. var isExcluded = {};
  29535. if (options.exclude) {
  29536. var exclusions =
  29537. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  29538. exclusions.forEach(function (exclusion) {
  29539. for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
  29540. isExcluded[i] = true;
  29541. }
  29542. });
  29543. }
  29544. var shouldIndentNextCharacter = options.indentStart !== false;
  29545. var replacer = function (match) {
  29546. if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
  29547. shouldIndentNextCharacter = true;
  29548. return match;
  29549. };
  29550. this.intro = this.intro.replace(pattern, replacer);
  29551. var charIndex = 0;
  29552. var chunk = this.firstChunk;
  29553. while (chunk) {
  29554. var end = chunk.end;
  29555. if (chunk.edited) {
  29556. if (!isExcluded[charIndex]) {
  29557. chunk.content = chunk.content.replace(pattern, replacer);
  29558. if (chunk.content.length) {
  29559. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  29560. }
  29561. }
  29562. } else {
  29563. charIndex = chunk.start;
  29564. while (charIndex < end) {
  29565. if (!isExcluded[charIndex]) {
  29566. var char = this.original[charIndex];
  29567. if (char === '\n') {
  29568. shouldIndentNextCharacter = true;
  29569. } else if (char !== '\r' && shouldIndentNextCharacter) {
  29570. shouldIndentNextCharacter = false;
  29571. if (charIndex === chunk.start) {
  29572. chunk.prependRight(indentStr);
  29573. } else {
  29574. this._splitChunk(chunk, charIndex);
  29575. chunk = chunk.next;
  29576. chunk.prependRight(indentStr);
  29577. }
  29578. }
  29579. }
  29580. charIndex += 1;
  29581. }
  29582. }
  29583. charIndex = chunk.end;
  29584. chunk = chunk.next;
  29585. }
  29586. this.outro = this.outro.replace(pattern, replacer);
  29587. return this;
  29588. };
  29589. MagicString.prototype.insert = function insert () {
  29590. throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
  29591. };
  29592. MagicString.prototype.insertLeft = function insertLeft (index, content) {
  29593. if (!warned.insertLeft) {
  29594. console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
  29595. warned.insertLeft = true;
  29596. }
  29597. return this.appendLeft(index, content);
  29598. };
  29599. MagicString.prototype.insertRight = function insertRight (index, content) {
  29600. if (!warned.insertRight) {
  29601. console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
  29602. warned.insertRight = true;
  29603. }
  29604. return this.prependRight(index, content);
  29605. };
  29606. MagicString.prototype.move = function move (start, end, index) {
  29607. if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
  29608. this._split(start);
  29609. this._split(end);
  29610. this._split(index);
  29611. var first = this.byStart[start];
  29612. var last = this.byEnd[end];
  29613. var oldLeft = first.previous;
  29614. var oldRight = last.next;
  29615. var newRight = this.byStart[index];
  29616. if (!newRight && last === this.lastChunk) { return this; }
  29617. var newLeft = newRight ? newRight.previous : this.lastChunk;
  29618. if (oldLeft) { oldLeft.next = oldRight; }
  29619. if (oldRight) { oldRight.previous = oldLeft; }
  29620. if (newLeft) { newLeft.next = first; }
  29621. if (newRight) { newRight.previous = last; }
  29622. if (!first.previous) { this.firstChunk = last.next; }
  29623. if (!last.next) {
  29624. this.lastChunk = first.previous;
  29625. this.lastChunk.next = null;
  29626. }
  29627. first.previous = newLeft;
  29628. last.next = newRight || null;
  29629. if (!newLeft) { this.firstChunk = first; }
  29630. if (!newRight) { this.lastChunk = last; }
  29631. return this;
  29632. };
  29633. MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
  29634. if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
  29635. while (start < 0) { start += this.original.length; }
  29636. while (end < 0) { end += this.original.length; }
  29637. if (end > this.original.length) { throw new Error('end is out of bounds'); }
  29638. if (start === end)
  29639. { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
  29640. this._split(start);
  29641. this._split(end);
  29642. if (options === true) {
  29643. if (!warned.storeName) {
  29644. 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
  29645. warned.storeName = true;
  29646. }
  29647. options = { storeName: true };
  29648. }
  29649. var storeName = options !== undefined ? options.storeName : false;
  29650. var contentOnly = options !== undefined ? options.contentOnly : false;
  29651. if (storeName) {
  29652. var original = this.original.slice(start, end);
  29653. this.storedNames[original] = true;
  29654. }
  29655. var first = this.byStart[start];
  29656. var last = this.byEnd[end];
  29657. if (first) {
  29658. if (end > first.end && first.next !== this.byStart[first.end]) {
  29659. throw new Error('Cannot overwrite across a split point');
  29660. }
  29661. first.edit(content, storeName, contentOnly);
  29662. if (first !== last) {
  29663. var chunk = first.next;
  29664. while (chunk !== last) {
  29665. chunk.edit('', false);
  29666. chunk = chunk.next;
  29667. }
  29668. chunk.edit('', false);
  29669. }
  29670. } else {
  29671. // must be inserting at the end
  29672. var newChunk = new Chunk(start, end, '').edit(content, storeName);
  29673. // TODO last chunk in the array may not be the last chunk, if it's moved...
  29674. last.next = newChunk;
  29675. newChunk.previous = last;
  29676. }
  29677. return this;
  29678. };
  29679. MagicString.prototype.prepend = function prepend (content) {
  29680. if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
  29681. this.intro = content + this.intro;
  29682. return this;
  29683. };
  29684. MagicString.prototype.prependLeft = function prependLeft (index, content) {
  29685. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  29686. this._split(index);
  29687. var chunk = this.byEnd[index];
  29688. if (chunk) {
  29689. chunk.prependLeft(content);
  29690. } else {
  29691. this.intro = content + this.intro;
  29692. }
  29693. return this;
  29694. };
  29695. MagicString.prototype.prependRight = function prependRight (index, content) {
  29696. if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
  29697. this._split(index);
  29698. var chunk = this.byStart[index];
  29699. if (chunk) {
  29700. chunk.prependRight(content);
  29701. } else {
  29702. this.outro = content + this.outro;
  29703. }
  29704. return this;
  29705. };
  29706. MagicString.prototype.remove = function remove (start, end) {
  29707. while (start < 0) { start += this.original.length; }
  29708. while (end < 0) { end += this.original.length; }
  29709. if (start === end) { return this; }
  29710. if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
  29711. if (start > end) { throw new Error('end must be greater than start'); }
  29712. this._split(start);
  29713. this._split(end);
  29714. var chunk = this.byStart[start];
  29715. while (chunk) {
  29716. chunk.intro = '';
  29717. chunk.outro = '';
  29718. chunk.edit('');
  29719. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  29720. }
  29721. return this;
  29722. };
  29723. MagicString.prototype.lastChar = function lastChar () {
  29724. if (this.outro.length)
  29725. { return this.outro[this.outro.length - 1]; }
  29726. var chunk = this.lastChunk;
  29727. do {
  29728. if (chunk.outro.length)
  29729. { return chunk.outro[chunk.outro.length - 1]; }
  29730. if (chunk.content.length)
  29731. { return chunk.content[chunk.content.length - 1]; }
  29732. if (chunk.intro.length)
  29733. { return chunk.intro[chunk.intro.length - 1]; }
  29734. } while (chunk = chunk.previous);
  29735. if (this.intro.length)
  29736. { return this.intro[this.intro.length - 1]; }
  29737. return '';
  29738. };
  29739. MagicString.prototype.lastLine = function lastLine () {
  29740. var lineIndex = this.outro.lastIndexOf(n);
  29741. if (lineIndex !== -1)
  29742. { return this.outro.substr(lineIndex + 1); }
  29743. var lineStr = this.outro;
  29744. var chunk = this.lastChunk;
  29745. do {
  29746. if (chunk.outro.length > 0) {
  29747. lineIndex = chunk.outro.lastIndexOf(n);
  29748. if (lineIndex !== -1)
  29749. { return chunk.outro.substr(lineIndex + 1) + lineStr; }
  29750. lineStr = chunk.outro + lineStr;
  29751. }
  29752. if (chunk.content.length > 0) {
  29753. lineIndex = chunk.content.lastIndexOf(n);
  29754. if (lineIndex !== -1)
  29755. { return chunk.content.substr(lineIndex + 1) + lineStr; }
  29756. lineStr = chunk.content + lineStr;
  29757. }
  29758. if (chunk.intro.length > 0) {
  29759. lineIndex = chunk.intro.lastIndexOf(n);
  29760. if (lineIndex !== -1)
  29761. { return chunk.intro.substr(lineIndex + 1) + lineStr; }
  29762. lineStr = chunk.intro + lineStr;
  29763. }
  29764. } while (chunk = chunk.previous);
  29765. lineIndex = this.intro.lastIndexOf(n);
  29766. if (lineIndex !== -1)
  29767. { return this.intro.substr(lineIndex + 1) + lineStr; }
  29768. return this.intro + lineStr;
  29769. };
  29770. MagicString.prototype.slice = function slice (start, end) {
  29771. if ( start === void 0 ) start = 0;
  29772. if ( end === void 0 ) end = this.original.length;
  29773. while (start < 0) { start += this.original.length; }
  29774. while (end < 0) { end += this.original.length; }
  29775. var result = '';
  29776. // find start chunk
  29777. var chunk = this.firstChunk;
  29778. while (chunk && (chunk.start > start || chunk.end <= start)) {
  29779. // found end chunk before start
  29780. if (chunk.start < end && chunk.end >= end) {
  29781. return result;
  29782. }
  29783. chunk = chunk.next;
  29784. }
  29785. if (chunk && chunk.edited && chunk.start !== start)
  29786. { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
  29787. var startChunk = chunk;
  29788. while (chunk) {
  29789. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  29790. result += chunk.intro;
  29791. }
  29792. var containsEnd = chunk.start < end && chunk.end >= end;
  29793. if (containsEnd && chunk.edited && chunk.end !== end)
  29794. { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
  29795. var sliceStart = startChunk === chunk ? start - chunk.start : 0;
  29796. var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  29797. result += chunk.content.slice(sliceStart, sliceEnd);
  29798. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  29799. result += chunk.outro;
  29800. }
  29801. if (containsEnd) {
  29802. break;
  29803. }
  29804. chunk = chunk.next;
  29805. }
  29806. return result;
  29807. };
  29808. // TODO deprecate this? not really very useful
  29809. MagicString.prototype.snip = function snip (start, end) {
  29810. var clone = this.clone();
  29811. clone.remove(0, start);
  29812. clone.remove(end, clone.original.length);
  29813. return clone;
  29814. };
  29815. MagicString.prototype._split = function _split (index) {
  29816. if (this.byStart[index] || this.byEnd[index]) { return; }
  29817. var chunk = this.lastSearchedChunk;
  29818. var searchForward = index > chunk.end;
  29819. while (chunk) {
  29820. if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
  29821. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  29822. }
  29823. };
  29824. MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
  29825. if (chunk.edited && chunk.content.length) {
  29826. // zero-length edited chunks are a special case (overlapping replacements)
  29827. var loc = getLocator(this.original)(index);
  29828. throw new Error(
  29829. ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
  29830. );
  29831. }
  29832. var newChunk = chunk.split(index);
  29833. this.byEnd[index] = chunk;
  29834. this.byStart[index] = newChunk;
  29835. this.byEnd[newChunk.end] = newChunk;
  29836. if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
  29837. this.lastSearchedChunk = chunk;
  29838. return true;
  29839. };
  29840. MagicString.prototype.toString = function toString () {
  29841. var str = this.intro;
  29842. var chunk = this.firstChunk;
  29843. while (chunk) {
  29844. str += chunk.toString();
  29845. chunk = chunk.next;
  29846. }
  29847. return str + this.outro;
  29848. };
  29849. MagicString.prototype.isEmpty = function isEmpty () {
  29850. var chunk = this.firstChunk;
  29851. do {
  29852. if (chunk.intro.length && chunk.intro.trim() ||
  29853. chunk.content.length && chunk.content.trim() ||
  29854. chunk.outro.length && chunk.outro.trim())
  29855. { return false; }
  29856. } while (chunk = chunk.next);
  29857. return true;
  29858. };
  29859. MagicString.prototype.length = function length () {
  29860. var chunk = this.firstChunk;
  29861. var length = 0;
  29862. do {
  29863. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  29864. } while (chunk = chunk.next);
  29865. return length;
  29866. };
  29867. MagicString.prototype.trimLines = function trimLines () {
  29868. return this.trim('[\\r\\n]');
  29869. };
  29870. MagicString.prototype.trim = function trim (charType) {
  29871. return this.trimStart(charType).trimEnd(charType);
  29872. };
  29873. MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
  29874. var rx = new RegExp((charType || '\\s') + '+$');
  29875. this.outro = this.outro.replace(rx, '');
  29876. if (this.outro.length) { return true; }
  29877. var chunk = this.lastChunk;
  29878. do {
  29879. var end = chunk.end;
  29880. var aborted = chunk.trimEnd(rx);
  29881. // if chunk was trimmed, we have a new lastChunk
  29882. if (chunk.end !== end) {
  29883. if (this.lastChunk === chunk) {
  29884. this.lastChunk = chunk.next;
  29885. }
  29886. this.byEnd[chunk.end] = chunk;
  29887. this.byStart[chunk.next.start] = chunk.next;
  29888. this.byEnd[chunk.next.end] = chunk.next;
  29889. }
  29890. if (aborted) { return true; }
  29891. chunk = chunk.previous;
  29892. } while (chunk);
  29893. return false;
  29894. };
  29895. MagicString.prototype.trimEnd = function trimEnd (charType) {
  29896. this.trimEndAborted(charType);
  29897. return this;
  29898. };
  29899. MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
  29900. var rx = new RegExp('^' + (charType || '\\s') + '+');
  29901. this.intro = this.intro.replace(rx, '');
  29902. if (this.intro.length) { return true; }
  29903. var chunk = this.firstChunk;
  29904. do {
  29905. var end = chunk.end;
  29906. var aborted = chunk.trimStart(rx);
  29907. if (chunk.end !== end) {
  29908. // special case...
  29909. if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
  29910. this.byEnd[chunk.end] = chunk;
  29911. this.byStart[chunk.next.start] = chunk.next;
  29912. this.byEnd[chunk.next.end] = chunk.next;
  29913. }
  29914. if (aborted) { return true; }
  29915. chunk = chunk.next;
  29916. } while (chunk);
  29917. return false;
  29918. };
  29919. MagicString.prototype.trimStart = function trimStart (charType) {
  29920. this.trimStartAborted(charType);
  29921. return this;
  29922. };
  29923. const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/;
  29924. const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/;
  29925. /**
  29926. * Utility for rewriting `export default` in a script block into a variable
  29927. * declaration so that we can inject things into it
  29928. */
  29929. function rewriteDefault(input, as, parserPlugins) {
  29930. if (!hasDefaultExport(input)) {
  29931. return input + `\nconst ${as} = {}`;
  29932. }
  29933. const replaced = input.replace(defaultExportRE, `$1const ${as} =`);
  29934. if (!hasDefaultExport(replaced)) {
  29935. return replaced;
  29936. }
  29937. // if the script somehow still contains `default export`, it probably has
  29938. // multi-line comments or template strings. fallback to a full parse.
  29939. const s = new MagicString(input);
  29940. const ast = parse_1(input, {
  29941. sourceType: 'module',
  29942. plugins: parserPlugins
  29943. }).program.body;
  29944. ast.forEach(node => {
  29945. if (node.type === 'ExportDefaultDeclaration') {
  29946. s.overwrite(node.start, node.declaration.start, `const ${as} = `);
  29947. }
  29948. if (node.type === 'ExportNamedDeclaration') {
  29949. node.specifiers.forEach(specifier => {
  29950. if (specifier.type === 'ExportSpecifier' &&
  29951. specifier.exported.type === 'Identifier' &&
  29952. specifier.exported.name === 'default') {
  29953. const end = specifier.end;
  29954. s.overwrite(specifier.start, input.charAt(end) === ',' ? end + 1 : end, ``);
  29955. s.append(`\nconst ${as} = ${specifier.local.name}`);
  29956. }
  29957. });
  29958. }
  29959. });
  29960. return s.toString();
  29961. }
  29962. function hasDefaultExport(input) {
  29963. return defaultExportRE.test(input) || namedDefaultExportRE.test(input);
  29964. }
  29965. const DEFINE_PROPS = 'defineProps';
  29966. const DEFINE_EMIT = 'defineEmit';
  29967. /**
  29968. * Compile `<script setup>`
  29969. * It requires the whole SFC descriptor because we need to handle and merge
  29970. * normal `<script>` + `<script setup>` if both are present.
  29971. */
  29972. function compileScript(sfc, options) {
  29973. const { script, scriptSetup, source, filename } = sfc;
  29974. if (scriptSetup) {
  29975. warnExperimental(`<script setup>`, 227);
  29976. }
  29977. // for backwards compat
  29978. if (!options) {
  29979. options = { id: '' };
  29980. }
  29981. if (!options.id) {
  29982. warnOnce(`compileScript now requires passing the \`id\` option.\n` +
  29983. `Upgrade your vite or vue-loader version for compatibility with ` +
  29984. `the latest experimental proposals.`);
  29985. }
  29986. const scopeId = options.id ? options.id.replace(/^data-v-/, '') : '';
  29987. const cssVars = sfc.cssVars;
  29988. const hasInheritAttrsFlag = sfc.template && sfc.template.attrs['inherit-attrs'] === 'false';
  29989. const scriptLang = script && script.lang;
  29990. const scriptSetupLang = scriptSetup && scriptSetup.lang;
  29991. const isTS = scriptLang === 'ts' || scriptSetupLang === 'ts';
  29992. const plugins = [...babelParserDefaultPlugins, 'jsx'];
  29993. if (options.babelParserPlugins)
  29994. plugins.push(...options.babelParserPlugins);
  29995. if (isTS)
  29996. plugins.push('typescript', 'decorators-legacy');
  29997. if (!scriptSetup) {
  29998. if (!script) {
  29999. throw new Error(`[@vue/compiler-sfc] SFC contains no <script> tags.`);
  30000. }
  30001. if (scriptLang && scriptLang !== 'ts') {
  30002. // do not process non js/ts script blocks
  30003. return script;
  30004. }
  30005. try {
  30006. const scriptAst = parse_1(script.content, {
  30007. plugins,
  30008. sourceType: 'module'
  30009. }).program.body;
  30010. const bindings = analyzeScriptBindings(scriptAst);
  30011. const needRewrite = cssVars.length || hasInheritAttrsFlag;
  30012. let content = script.content;
  30013. if (needRewrite) {
  30014. content = rewriteDefault(content, `__default__`, plugins);
  30015. if (cssVars.length) {
  30016. content += genNormalScriptCssVarsCode(cssVars, bindings, scopeId, !!options.isProd);
  30017. }
  30018. if (hasInheritAttrsFlag) {
  30019. content += `__default__.inheritAttrs = false`;
  30020. }
  30021. content += `\nexport default __default__`;
  30022. }
  30023. return {
  30024. ...script,
  30025. content,
  30026. bindings,
  30027. scriptAst
  30028. };
  30029. }
  30030. catch (e) {
  30031. // silently fallback if parse fails since user may be using custom
  30032. // babel syntax
  30033. return script;
  30034. }
  30035. }
  30036. if (script && scriptLang !== scriptSetupLang) {
  30037. throw new Error(`[@vue/compiler-sfc] <script> and <script setup> must have the same language type.`);
  30038. }
  30039. if (scriptSetupLang && scriptSetupLang !== 'ts') {
  30040. // do not process non js/ts script blocks
  30041. return scriptSetup;
  30042. }
  30043. const defaultTempVar = `__default__`;
  30044. const bindingMetadata = {};
  30045. const helperImports = new Set();
  30046. const userImports = Object.create(null);
  30047. const userImportAlias = Object.create(null);
  30048. const setupBindings = Object.create(null);
  30049. const refBindings = Object.create(null);
  30050. const refIdentifiers = new Set();
  30051. const enableRefSugar = options.refSugar !== false;
  30052. let defaultExport;
  30053. let hasDefinePropsCall = false;
  30054. let hasDefineEmitCall = false;
  30055. let propsRuntimeDecl;
  30056. let propsTypeDecl;
  30057. let propsIdentifier;
  30058. let emitRuntimeDecl;
  30059. let emitTypeDecl;
  30060. let emitIdentifier;
  30061. let hasAwait = false;
  30062. let hasInlinedSsrRenderFn = false;
  30063. // props/emits declared via types
  30064. const typeDeclaredProps = {};
  30065. const typeDeclaredEmits = new Set();
  30066. // record declared types for runtime props type generation
  30067. const declaredTypes = {};
  30068. // magic-string state
  30069. const s = new MagicString(source);
  30070. const startOffset = scriptSetup.loc.start.offset;
  30071. const endOffset = scriptSetup.loc.end.offset;
  30072. const scriptStartOffset = script && script.loc.start.offset;
  30073. const scriptEndOffset = script && script.loc.end.offset;
  30074. function helper(key) {
  30075. helperImports.add(key);
  30076. return `_${key}`;
  30077. }
  30078. function parse(input, options, offset) {
  30079. try {
  30080. return parse_1(input, options).program.body;
  30081. }
  30082. catch (e) {
  30083. e.message = `[@vue/compiler-sfc] ${e.message}\n\n${sfc.filename}\n${generateCodeFrame(source, e.pos + offset, e.pos + offset + 1)}`;
  30084. throw e;
  30085. }
  30086. }
  30087. function error(msg, node, end = node.end + startOffset) {
  30088. throw new Error(`[@vue/compiler-sfc] ${msg}\n\n${sfc.filename}\n${generateCodeFrame(source, node.start + startOffset, end)}`);
  30089. }
  30090. function registerUserImport(source, local, imported, isType) {
  30091. if (source === 'vue' && imported) {
  30092. userImportAlias[imported] = local;
  30093. }
  30094. userImports[local] = {
  30095. isType,
  30096. imported: imported || 'default',
  30097. source
  30098. };
  30099. }
  30100. function processDefineProps(node) {
  30101. if (isCallOf(node, DEFINE_PROPS)) {
  30102. if (hasDefinePropsCall) {
  30103. error(`duplicate ${DEFINE_PROPS}() call`, node);
  30104. }
  30105. hasDefinePropsCall = true;
  30106. propsRuntimeDecl = node.arguments[0];
  30107. // context call has type parameters - infer runtime types from it
  30108. if (node.typeParameters) {
  30109. if (propsRuntimeDecl) {
  30110. error(`${DEFINE_PROPS}() cannot accept both type and non-type arguments ` +
  30111. `at the same time. Use one or the other.`, node);
  30112. }
  30113. const typeArg = node.typeParameters.params[0];
  30114. if (typeArg.type === 'TSTypeLiteral') {
  30115. propsTypeDecl = typeArg;
  30116. }
  30117. else {
  30118. error(`type argument passed to ${DEFINE_PROPS}() must be a literal type.`, typeArg);
  30119. }
  30120. }
  30121. return true;
  30122. }
  30123. return false;
  30124. }
  30125. function processDefineEmit(node) {
  30126. if (isCallOf(node, DEFINE_EMIT)) {
  30127. if (hasDefineEmitCall) {
  30128. error(`duplicate ${DEFINE_EMIT}() call`, node);
  30129. }
  30130. hasDefineEmitCall = true;
  30131. emitRuntimeDecl = node.arguments[0];
  30132. if (node.typeParameters) {
  30133. if (emitRuntimeDecl) {
  30134. error(`${DEFINE_EMIT}() cannot accept both type and non-type arguments ` +
  30135. `at the same time. Use one or the other.`, node);
  30136. }
  30137. const typeArg = node.typeParameters.params[0];
  30138. if (typeArg.type === 'TSFunctionType' ||
  30139. typeArg.type === 'TSUnionType') {
  30140. emitTypeDecl = typeArg;
  30141. }
  30142. else {
  30143. error(`type argument passed to ${DEFINE_EMIT}() must be a function type ` +
  30144. `or a union of function types.`, typeArg);
  30145. }
  30146. }
  30147. return true;
  30148. }
  30149. return false;
  30150. }
  30151. function checkInvalidScopeReference(node, method) {
  30152. if (!node)
  30153. return;
  30154. walkIdentifiers(node, id => {
  30155. if (setupBindings[id.name]) {
  30156. error(`\`${method}()\` in <script setup> cannot reference locally ` +
  30157. `declared variables because it will be hoisted outside of the ` +
  30158. `setup() function. If your component options requires initialization ` +
  30159. `in the module scope, use a separate normal <script> to export ` +
  30160. `the options instead.`, id);
  30161. }
  30162. });
  30163. }
  30164. function processRefExpression(exp, statement) {
  30165. if (exp.type === 'AssignmentExpression') {
  30166. const { left, right } = exp;
  30167. if (left.type === 'Identifier') {
  30168. registerRefBinding(left);
  30169. s.prependRight(right.start + startOffset, `${helper('ref')}(`);
  30170. s.appendLeft(right.end + startOffset, ')');
  30171. }
  30172. else if (left.type === 'ObjectPattern') {
  30173. // remove wrapping parens
  30174. for (let i = left.start; i > 0; i--) {
  30175. const char = source[i + startOffset];
  30176. if (char === '(') {
  30177. s.remove(i + startOffset, i + startOffset + 1);
  30178. break;
  30179. }
  30180. }
  30181. for (let i = left.end; i > 0; i++) {
  30182. const char = source[i + startOffset];
  30183. if (char === ')') {
  30184. s.remove(i + startOffset, i + startOffset + 1);
  30185. break;
  30186. }
  30187. }
  30188. processRefObjectPattern(left, statement);
  30189. }
  30190. else if (left.type === 'ArrayPattern') {
  30191. processRefArrayPattern(left, statement);
  30192. }
  30193. }
  30194. else if (exp.type === 'SequenceExpression') {
  30195. // possible multiple declarations
  30196. // ref: x = 1, y = 2
  30197. exp.expressions.forEach(e => processRefExpression(e, statement));
  30198. }
  30199. else if (exp.type === 'Identifier') {
  30200. registerRefBinding(exp);
  30201. s.appendLeft(exp.end + startOffset, ` = ${helper('ref')}()`);
  30202. }
  30203. else {
  30204. error(`ref: statements can only contain assignment expressions.`, exp);
  30205. }
  30206. }
  30207. function registerRefBinding(id) {
  30208. if (id.name[0] === '$') {
  30209. error(`ref variable identifiers cannot start with $.`, id);
  30210. }
  30211. refBindings[id.name] = setupBindings[id.name] = "setup-ref" /* SETUP_REF */;
  30212. refIdentifiers.add(id);
  30213. }
  30214. function processRefObjectPattern(pattern, statement) {
  30215. for (const p of pattern.properties) {
  30216. let nameId;
  30217. if (p.type === 'ObjectProperty') {
  30218. if (p.key.start === p.value.start) {
  30219. // shorthand { foo } --> { foo: __foo }
  30220. nameId = p.key;
  30221. s.appendLeft(nameId.end + startOffset, `: __${nameId.name}`);
  30222. if (p.value.type === 'AssignmentPattern') {
  30223. // { foo = 1 }
  30224. refIdentifiers.add(p.value.left);
  30225. }
  30226. }
  30227. else {
  30228. if (p.value.type === 'Identifier') {
  30229. // { foo: bar } --> { foo: __bar }
  30230. nameId = p.value;
  30231. s.prependRight(nameId.start + startOffset, `__`);
  30232. }
  30233. else if (p.value.type === 'ObjectPattern') {
  30234. processRefObjectPattern(p.value, statement);
  30235. }
  30236. else if (p.value.type === 'ArrayPattern') {
  30237. processRefArrayPattern(p.value, statement);
  30238. }
  30239. else if (p.value.type === 'AssignmentPattern') {
  30240. // { foo: bar = 1 } --> { foo: __bar = 1 }
  30241. nameId = p.value.left;
  30242. s.prependRight(nameId.start + startOffset, `__`);
  30243. }
  30244. }
  30245. }
  30246. else {
  30247. // rest element { ...foo } --> { ...__foo }
  30248. nameId = p.argument;
  30249. s.prependRight(nameId.start + startOffset, `__`);
  30250. }
  30251. if (nameId) {
  30252. registerRefBinding(nameId);
  30253. // append binding declarations after the parent statement
  30254. s.appendLeft(statement.end + startOffset, `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`);
  30255. }
  30256. }
  30257. }
  30258. function processRefArrayPattern(pattern, statement) {
  30259. for (const e of pattern.elements) {
  30260. if (!e)
  30261. continue;
  30262. let nameId;
  30263. if (e.type === 'Identifier') {
  30264. // [a] --> [__a]
  30265. nameId = e;
  30266. }
  30267. else if (e.type === 'AssignmentPattern') {
  30268. // [a = 1] --> [__a = 1]
  30269. nameId = e.left;
  30270. }
  30271. else if (e.type === 'RestElement') {
  30272. // [...a] --> [...__a]
  30273. nameId = e.argument;
  30274. }
  30275. else if (e.type === 'ObjectPattern') {
  30276. processRefObjectPattern(e, statement);
  30277. }
  30278. else if (e.type === 'ArrayPattern') {
  30279. processRefArrayPattern(e, statement);
  30280. }
  30281. if (nameId) {
  30282. registerRefBinding(nameId);
  30283. // prefix original
  30284. s.prependRight(nameId.start + startOffset, `__`);
  30285. // append binding declarations after the parent statement
  30286. s.appendLeft(statement.end + startOffset, `\nconst ${nameId.name} = ${helper('ref')}(__${nameId.name});`);
  30287. }
  30288. }
  30289. }
  30290. // 1. process normal <script> first if it exists
  30291. let scriptAst;
  30292. if (script) {
  30293. // import dedupe between <script> and <script setup>
  30294. scriptAst = parse(script.content, {
  30295. plugins,
  30296. sourceType: 'module'
  30297. }, scriptStartOffset);
  30298. for (const node of scriptAst) {
  30299. if (node.type === 'ImportDeclaration') {
  30300. // record imports for dedupe
  30301. for (const specifier of node.specifiers) {
  30302. const imported = specifier.type === 'ImportSpecifier' &&
  30303. specifier.imported.type === 'Identifier' &&
  30304. specifier.imported.name;
  30305. registerUserImport(node.source.value, specifier.local.name, imported, node.importKind === 'type');
  30306. }
  30307. }
  30308. else if (node.type === 'ExportDefaultDeclaration') {
  30309. // export default
  30310. defaultExport = node;
  30311. const start = node.start + scriptStartOffset;
  30312. s.overwrite(start, start + `export default`.length, `const ${defaultTempVar} =`);
  30313. }
  30314. else if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
  30315. const defaultSpecifier = node.specifiers.find(s => s.exported.type === 'Identifier' && s.exported.name === 'default');
  30316. if (defaultSpecifier) {
  30317. defaultExport = node;
  30318. // 1. remove specifier
  30319. if (node.specifiers.length > 1) {
  30320. s.remove(defaultSpecifier.start + scriptStartOffset, defaultSpecifier.end + scriptStartOffset);
  30321. }
  30322. else {
  30323. s.remove(node.start + scriptStartOffset, node.end + scriptStartOffset);
  30324. }
  30325. if (node.source) {
  30326. // export { x as default } from './x'
  30327. // rewrite to `import { x as __default__ } from './x'` and
  30328. // add to top
  30329. s.prepend(`import { ${defaultSpecifier.local.name} as ${defaultTempVar} } from '${node.source.value}'\n`);
  30330. }
  30331. else {
  30332. // export { x as default }
  30333. // rewrite to `const __default__ = x` and move to end
  30334. s.append(`\nconst ${defaultTempVar} = ${defaultSpecifier.local.name}\n`);
  30335. }
  30336. }
  30337. }
  30338. }
  30339. }
  30340. // 2. parse <script setup> and walk over top level statements
  30341. const scriptSetupAst = parse(scriptSetup.content, {
  30342. plugins: [
  30343. ...plugins,
  30344. // allow top level await but only inside <script setup>
  30345. 'topLevelAwait'
  30346. ],
  30347. sourceType: 'module'
  30348. }, startOffset);
  30349. for (const node of scriptSetupAst) {
  30350. const start = node.start + startOffset;
  30351. let end = node.end + startOffset;
  30352. // import or type declarations: move to top
  30353. // locate comment
  30354. if (node.trailingComments && node.trailingComments.length > 0) {
  30355. const lastCommentNode = node.trailingComments[node.trailingComments.length - 1];
  30356. end = lastCommentNode.end + startOffset;
  30357. }
  30358. // locate the end of whitespace between this statement and the next
  30359. while (end <= source.length) {
  30360. if (!/\s/.test(source.charAt(end))) {
  30361. break;
  30362. }
  30363. end++;
  30364. }
  30365. // process `ref: x` bindings (convert to refs)
  30366. if (node.type === 'LabeledStatement' &&
  30367. node.label.name === 'ref' &&
  30368. node.body.type === 'ExpressionStatement') {
  30369. if (enableRefSugar) {
  30370. warnExperimental(`ref: sugar`, 228);
  30371. s.overwrite(node.label.start + startOffset, node.body.start + startOffset, 'const ');
  30372. processRefExpression(node.body.expression, node);
  30373. }
  30374. else {
  30375. // TODO if we end up shipping ref: sugar as an opt-in feature,
  30376. // need to proxy the option in vite, vue-loader and rollup-plugin-vue.
  30377. error(`ref: sugar needs to be explicitly enabled via vite or vue-loader options.`, node);
  30378. }
  30379. }
  30380. if (node.type === 'ImportDeclaration') {
  30381. // import declarations are moved to top
  30382. s.move(start, end, 0);
  30383. // dedupe imports
  30384. let removed = 0;
  30385. let prev, next;
  30386. const removeSpecifier = (node) => {
  30387. removed++;
  30388. s.remove(prev ? prev.end + startOffset : node.start + startOffset, next && !prev ? next.start + startOffset : node.end + startOffset);
  30389. };
  30390. for (let i = 0; i < node.specifiers.length; i++) {
  30391. const specifier = node.specifiers[i];
  30392. prev = node.specifiers[i - 1];
  30393. next = node.specifiers[i + 1];
  30394. const local = specifier.local.name;
  30395. const imported = specifier.type === 'ImportSpecifier' &&
  30396. specifier.imported.type === 'Identifier' &&
  30397. specifier.imported.name;
  30398. const source = node.source.value;
  30399. const existing = userImports[local];
  30400. if (source === 'vue' &&
  30401. (imported === DEFINE_PROPS || imported === DEFINE_EMIT)) {
  30402. removeSpecifier(specifier);
  30403. }
  30404. else if (existing) {
  30405. if (existing.source === source && existing.imported === imported) {
  30406. // already imported in <script setup>, dedupe
  30407. removeSpecifier(specifier);
  30408. }
  30409. else {
  30410. error(`different imports aliased to same local name.`, specifier);
  30411. }
  30412. }
  30413. else {
  30414. registerUserImport(source, local, imported, node.importKind === 'type');
  30415. }
  30416. }
  30417. if (node.specifiers.length && removed === node.specifiers.length) {
  30418. s.remove(node.start + startOffset, node.end + startOffset);
  30419. }
  30420. }
  30421. // process `defineProps` and `defineEmit` calls
  30422. if (node.type === 'ExpressionStatement' &&
  30423. (processDefineProps(node.expression) ||
  30424. processDefineEmit(node.expression))) {
  30425. s.remove(node.start + startOffset, node.end + startOffset);
  30426. }
  30427. if (node.type === 'VariableDeclaration' && !node.declare) {
  30428. for (const decl of node.declarations) {
  30429. if (decl.init) {
  30430. const isDefineProps = processDefineProps(decl.init);
  30431. if (isDefineProps) {
  30432. propsIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
  30433. }
  30434. const isDefineEmit = processDefineEmit(decl.init);
  30435. if (isDefineEmit) {
  30436. emitIdentifier = scriptSetup.content.slice(decl.id.start, decl.id.end);
  30437. }
  30438. if (isDefineProps || isDefineEmit)
  30439. if (node.declarations.length === 1) {
  30440. s.remove(node.start + startOffset, node.end + startOffset);
  30441. }
  30442. else {
  30443. s.remove(decl.start + startOffset, decl.end + startOffset);
  30444. }
  30445. }
  30446. }
  30447. }
  30448. // walk decalrations to record declared bindings
  30449. if ((node.type === 'VariableDeclaration' ||
  30450. node.type === 'FunctionDeclaration' ||
  30451. node.type === 'ClassDeclaration') &&
  30452. !node.declare) {
  30453. walkDeclaration(node, setupBindings, userImportAlias);
  30454. }
  30455. // Type declarations
  30456. if (node.type === 'VariableDeclaration' && node.declare) {
  30457. s.remove(start, end);
  30458. }
  30459. // move all type declarations to outer scope
  30460. if (node.type.startsWith('TS') ||
  30461. (node.type === 'ExportNamedDeclaration' && node.exportKind === 'type')) {
  30462. recordType(node, declaredTypes);
  30463. s.move(start, end, 0);
  30464. }
  30465. // walk statements & named exports / variable declarations for top level
  30466. // await
  30467. if ((node.type === 'VariableDeclaration' && !node.declare) ||
  30468. node.type.endsWith('Statement')) {
  30469. walk$1(node, {
  30470. enter(node) {
  30471. if (isFunction$2(node)) {
  30472. this.skip();
  30473. }
  30474. if (node.type === 'AwaitExpression') {
  30475. hasAwait = true;
  30476. }
  30477. }
  30478. });
  30479. }
  30480. if ((node.type === 'ExportNamedDeclaration' && node.exportKind !== 'type') ||
  30481. node.type === 'ExportAllDeclaration' ||
  30482. node.type === 'ExportDefaultDeclaration') {
  30483. error(`<script setup> cannot contain ES module exports. ` +
  30484. `If you are using a previous version of <script setup>, please ` +
  30485. `consult the updated RFC at https://github.com/vuejs/rfcs/pull/227.`, node);
  30486. }
  30487. }
  30488. // 3. Do a full walk to rewrite identifiers referencing let exports with ref
  30489. // value access
  30490. if (enableRefSugar && Object.keys(refBindings).length) {
  30491. for (const node of scriptSetupAst) {
  30492. if (node.type !== 'ImportDeclaration') {
  30493. walkIdentifiers(node, (id, parent) => {
  30494. if (refBindings[id.name] && !refIdentifiers.has(id)) {
  30495. if (isStaticProperty$1(parent) && parent.shorthand) {
  30496. // let binding used in a property shorthand
  30497. // { foo } -> { foo: foo.value }
  30498. // skip for destructure patterns
  30499. if (!parent.inPattern ||
  30500. isInDestructureAssignment$1(parent, parentStack)) {
  30501. s.appendLeft(id.end + startOffset, `: ${id.name}.value`);
  30502. }
  30503. }
  30504. else {
  30505. s.appendLeft(id.end + startOffset, '.value');
  30506. }
  30507. }
  30508. else if (id.name[0] === '$' && refBindings[id.name.slice(1)]) {
  30509. // $xxx raw ref access variables, remove the $ prefix
  30510. s.remove(id.start + startOffset, id.start + startOffset + 1);
  30511. }
  30512. });
  30513. }
  30514. }
  30515. }
  30516. // 4. extract runtime props/emits code from setup context type
  30517. if (propsTypeDecl) {
  30518. extractRuntimeProps(propsTypeDecl, typeDeclaredProps, declaredTypes);
  30519. }
  30520. if (emitTypeDecl) {
  30521. extractRuntimeEmits(emitTypeDecl, typeDeclaredEmits);
  30522. }
  30523. // 5. check useOptions args to make sure it doesn't reference setup scope
  30524. // variables
  30525. checkInvalidScopeReference(propsRuntimeDecl, DEFINE_PROPS);
  30526. checkInvalidScopeReference(emitRuntimeDecl, DEFINE_PROPS);
  30527. // 6. remove non-script content
  30528. if (script) {
  30529. if (startOffset < scriptStartOffset) {
  30530. // <script setup> before <script>
  30531. s.remove(0, startOffset);
  30532. s.remove(endOffset, scriptStartOffset);
  30533. s.remove(scriptEndOffset, source.length);
  30534. }
  30535. else {
  30536. // <script> before <script setup>
  30537. s.remove(0, scriptStartOffset);
  30538. s.remove(scriptEndOffset, startOffset);
  30539. s.remove(endOffset, source.length);
  30540. }
  30541. }
  30542. else {
  30543. // only <script setup>
  30544. s.remove(0, startOffset);
  30545. s.remove(endOffset, source.length);
  30546. }
  30547. // 7. analyze binding metadata
  30548. if (scriptAst) {
  30549. Object.assign(bindingMetadata, analyzeScriptBindings(scriptAst));
  30550. }
  30551. if (propsRuntimeDecl) {
  30552. for (const key of getObjectOrArrayExpressionKeys(propsRuntimeDecl)) {
  30553. bindingMetadata[key] = "props" /* PROPS */;
  30554. }
  30555. }
  30556. for (const key in typeDeclaredProps) {
  30557. bindingMetadata[key] = "props" /* PROPS */;
  30558. }
  30559. for (const [key, { isType, imported, source }] of Object.entries(userImports)) {
  30560. if (isType)
  30561. continue;
  30562. bindingMetadata[key] =
  30563. (imported === 'default' && source.endsWith('.vue')) || source === 'vue'
  30564. ? "setup-const" /* SETUP_CONST */
  30565. : "setup-maybe-ref" /* SETUP_MAYBE_REF */;
  30566. }
  30567. for (const key in setupBindings) {
  30568. bindingMetadata[key] = setupBindings[key];
  30569. }
  30570. // 8. inject `useCssVars` calls
  30571. if (cssVars.length) {
  30572. helperImports.add(CSS_VARS_HELPER);
  30573. helperImports.add('unref');
  30574. s.prependRight(startOffset, `\n${genCssVarsCode(cssVars, bindingMetadata, scopeId, !!options.isProd)}\n`);
  30575. }
  30576. // 9. finalize setup() argument signature
  30577. let args = `__props`;
  30578. if (propsTypeDecl) {
  30579. args += `: ${scriptSetup.content.slice(propsTypeDecl.start, propsTypeDecl.end)}`;
  30580. }
  30581. // inject user assignment of props
  30582. // we use a default __props so that template expressions referencing props
  30583. // can use it directly
  30584. if (propsIdentifier) {
  30585. s.prependRight(startOffset, `\nconst ${propsIdentifier} = __props`);
  30586. }
  30587. if (emitIdentifier) {
  30588. args +=
  30589. emitIdentifier === `emit` ? `, { emit }` : `, { emit: ${emitIdentifier} }`;
  30590. if (emitTypeDecl) {
  30591. args += `: {
  30592. emit: (${scriptSetup.content.slice(emitTypeDecl.start, emitTypeDecl.end)}),
  30593. slots: any,
  30594. attrs: any
  30595. }`;
  30596. }
  30597. }
  30598. // 10. generate return statement
  30599. let returned;
  30600. if (options.inlineTemplate) {
  30601. if (sfc.template && !sfc.template.src) {
  30602. if (options.templateOptions && options.templateOptions.ssr) {
  30603. hasInlinedSsrRenderFn = true;
  30604. }
  30605. // inline render function mode - we are going to compile the template and
  30606. // inline it right here
  30607. const { code, ast, preamble, tips, errors } = compileTemplate({
  30608. filename,
  30609. source: sfc.template.content,
  30610. inMap: sfc.template.map,
  30611. ...options.templateOptions,
  30612. id: scopeId,
  30613. scoped: sfc.styles.some(s => s.scoped),
  30614. isProd: options.isProd,
  30615. ssrCssVars: sfc.cssVars,
  30616. compilerOptions: {
  30617. ...(options.templateOptions &&
  30618. options.templateOptions.compilerOptions),
  30619. inline: true,
  30620. isTS,
  30621. bindingMetadata
  30622. }
  30623. });
  30624. if (tips.length) {
  30625. tips.forEach(warnOnce);
  30626. }
  30627. const err = errors[0];
  30628. if (typeof err === 'string') {
  30629. throw new Error(err);
  30630. }
  30631. else if (err) {
  30632. if (err.loc) {
  30633. err.message +=
  30634. `\n\n` +
  30635. sfc.filename +
  30636. '\n' +
  30637. generateCodeFrame(source, err.loc.start.offset, err.loc.end.offset) +
  30638. `\n`;
  30639. }
  30640. throw err;
  30641. }
  30642. if (preamble) {
  30643. s.prepend(preamble);
  30644. }
  30645. // avoid duplicated unref import
  30646. // as this may get injected by the render function preamble OR the
  30647. // css vars codegen
  30648. if (ast && ast.helpers.includes(UNREF)) {
  30649. helperImports.delete('unref');
  30650. }
  30651. returned = code;
  30652. }
  30653. else {
  30654. returned = `() => {}`;
  30655. }
  30656. }
  30657. else {
  30658. // return bindings from setup
  30659. const allBindings = { ...setupBindings };
  30660. for (const key in userImports) {
  30661. if (!userImports[key].isType) {
  30662. allBindings[key] = true;
  30663. }
  30664. }
  30665. returned = `{ ${Object.keys(allBindings).join(', ')} }`;
  30666. }
  30667. s.appendRight(endOffset, `\nreturn ${returned}\n}\n\n`);
  30668. // 11. finalize default export
  30669. // expose: [] makes <script setup> components "closed" by default.
  30670. let runtimeOptions = `\n expose: [],`;
  30671. if (hasInheritAttrsFlag) {
  30672. runtimeOptions += `\n inheritAttrs: false,`;
  30673. }
  30674. if (hasInlinedSsrRenderFn) {
  30675. runtimeOptions += `\n __ssrInlineRender: true,`;
  30676. }
  30677. if (propsRuntimeDecl) {
  30678. runtimeOptions += `\n props: ${scriptSetup.content
  30679. .slice(propsRuntimeDecl.start, propsRuntimeDecl.end)
  30680. .trim()},`;
  30681. }
  30682. else if (propsTypeDecl) {
  30683. runtimeOptions += genRuntimeProps(typeDeclaredProps);
  30684. }
  30685. if (emitRuntimeDecl) {
  30686. runtimeOptions += `\n emits: ${scriptSetup.content
  30687. .slice(emitRuntimeDecl.start, emitRuntimeDecl.end)
  30688. .trim()},`;
  30689. }
  30690. else if (emitTypeDecl) {
  30691. runtimeOptions += genRuntimeEmits(typeDeclaredEmits);
  30692. }
  30693. if (isTS) {
  30694. // for TS, make sure the exported type is still valid type with
  30695. // correct props information
  30696. // we have to use object spread for types to be merged properly
  30697. // user's TS setting should compile it down to proper targets
  30698. const def = defaultExport ? `\n ...${defaultTempVar},` : ``;
  30699. // wrap setup code with function.
  30700. // export the content of <script setup> as a named export, `setup`.
  30701. // this allows `import { setup } from '*.vue'` for testing purposes.
  30702. s.prependLeft(startOffset, `\nexport default ${helper(`defineComponent`)}({${def}${runtimeOptions}\n ${hasAwait ? `async ` : ``}setup(${args}) {\n`);
  30703. s.appendRight(endOffset, `})`);
  30704. }
  30705. else {
  30706. if (defaultExport) {
  30707. // can't rely on spread operator in non ts mode
  30708. s.prependLeft(startOffset, `\n${hasAwait ? `async ` : ``}function setup(${args}) {\n`);
  30709. s.append(`\nexport default /*#__PURE__*/ Object.assign(${defaultTempVar}, {${runtimeOptions}\n setup\n})\n`);
  30710. }
  30711. else {
  30712. s.prependLeft(startOffset, `\nexport default {${runtimeOptions}\n ` +
  30713. `${hasAwait ? `async ` : ``}setup(${args}) {\n`);
  30714. s.appendRight(endOffset, `}`);
  30715. }
  30716. }
  30717. // 12. finalize Vue helper imports
  30718. if (helperImports.size > 0) {
  30719. s.prepend(`import { ${[...helperImports]
  30720. .map(h => `${h} as _${h}`)
  30721. .join(', ')} } from 'vue'\n`);
  30722. }
  30723. s.trim();
  30724. return {
  30725. ...scriptSetup,
  30726. bindings: bindingMetadata,
  30727. content: s.toString(),
  30728. map: s.generateMap({
  30729. source: filename,
  30730. hires: true,
  30731. includeContent: true
  30732. }),
  30733. scriptAst,
  30734. scriptSetupAst
  30735. };
  30736. }
  30737. function walkDeclaration(node, bindings, userImportAlias) {
  30738. if (node.type === 'VariableDeclaration') {
  30739. const isConst = node.kind === 'const';
  30740. // export const foo = ...
  30741. for (const { id, init } of node.declarations) {
  30742. const isDefineCall = !!(isConst &&
  30743. (isCallOf(init, DEFINE_PROPS) || isCallOf(init, DEFINE_EMIT)));
  30744. if (id.type === 'Identifier') {
  30745. let bindingType;
  30746. if (
  30747. // if a declaration is a const literal, we can mark it so that
  30748. // the generated render fn code doesn't need to unref() it
  30749. isDefineCall ||
  30750. (isConst &&
  30751. canNeverBeRef(init, userImportAlias['reactive'] || 'reactive'))) {
  30752. bindingType = "setup-const" /* SETUP_CONST */;
  30753. }
  30754. else if (isConst) {
  30755. if (isCallOf(init, userImportAlias['ref'] || 'ref')) {
  30756. bindingType = "setup-ref" /* SETUP_REF */;
  30757. }
  30758. else {
  30759. bindingType = "setup-maybe-ref" /* SETUP_MAYBE_REF */;
  30760. }
  30761. }
  30762. else {
  30763. bindingType = "setup-let" /* SETUP_LET */;
  30764. }
  30765. bindings[id.name] = bindingType;
  30766. }
  30767. else if (id.type === 'ObjectPattern') {
  30768. walkObjectPattern(id, bindings, isConst, isDefineCall);
  30769. }
  30770. else if (id.type === 'ArrayPattern') {
  30771. walkArrayPattern(id, bindings, isConst, isDefineCall);
  30772. }
  30773. }
  30774. }
  30775. else if (node.type === 'FunctionDeclaration' ||
  30776. node.type === 'ClassDeclaration') {
  30777. // export function foo() {} / export class Foo {}
  30778. // export declarations must be named.
  30779. bindings[node.id.name] = "setup-const" /* SETUP_CONST */;
  30780. }
  30781. }
  30782. function walkObjectPattern(node, bindings, isConst, isDefineCall = false) {
  30783. for (const p of node.properties) {
  30784. if (p.type === 'ObjectProperty') {
  30785. // key can only be Identifier in ObjectPattern
  30786. if (p.key.type === 'Identifier') {
  30787. if (p.key === p.value) {
  30788. // const { x } = ...
  30789. bindings[p.key.name] = isDefineCall
  30790. ? "setup-const" /* SETUP_CONST */
  30791. : isConst
  30792. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  30793. : "setup-let" /* SETUP_LET */;
  30794. }
  30795. else {
  30796. walkPattern(p.value, bindings, isConst, isDefineCall);
  30797. }
  30798. }
  30799. }
  30800. else {
  30801. // ...rest
  30802. // argument can only be identifer when destructuring
  30803. bindings[p.argument.name] = isConst
  30804. ? "setup-const" /* SETUP_CONST */
  30805. : "setup-let" /* SETUP_LET */;
  30806. }
  30807. }
  30808. }
  30809. function walkArrayPattern(node, bindings, isConst, isDefineCall = false) {
  30810. for (const e of node.elements) {
  30811. e && walkPattern(e, bindings, isConst, isDefineCall);
  30812. }
  30813. }
  30814. function walkPattern(node, bindings, isConst, isDefineCall = false) {
  30815. if (node.type === 'Identifier') {
  30816. bindings[node.name] = isDefineCall
  30817. ? "setup-const" /* SETUP_CONST */
  30818. : isConst
  30819. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  30820. : "setup-let" /* SETUP_LET */;
  30821. }
  30822. else if (node.type === 'RestElement') {
  30823. // argument can only be identifer when destructuring
  30824. bindings[node.argument.name] = isConst
  30825. ? "setup-const" /* SETUP_CONST */
  30826. : "setup-let" /* SETUP_LET */;
  30827. }
  30828. else if (node.type === 'ObjectPattern') {
  30829. walkObjectPattern(node, bindings, isConst);
  30830. }
  30831. else if (node.type === 'ArrayPattern') {
  30832. walkArrayPattern(node, bindings, isConst);
  30833. }
  30834. else if (node.type === 'AssignmentPattern') {
  30835. if (node.left.type === 'Identifier') {
  30836. bindings[node.left.name] = isDefineCall
  30837. ? "setup-const" /* SETUP_CONST */
  30838. : isConst
  30839. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  30840. : "setup-let" /* SETUP_LET */;
  30841. }
  30842. else {
  30843. walkPattern(node.left, bindings, isConst);
  30844. }
  30845. }
  30846. }
  30847. function recordType(node, declaredTypes) {
  30848. if (node.type === 'TSInterfaceDeclaration') {
  30849. declaredTypes[node.id.name] = [`Object`];
  30850. }
  30851. else if (node.type === 'TSTypeAliasDeclaration') {
  30852. declaredTypes[node.id.name] = inferRuntimeType(node.typeAnnotation, declaredTypes);
  30853. }
  30854. else if (node.type === 'ExportNamedDeclaration' && node.declaration) {
  30855. recordType(node.declaration, declaredTypes);
  30856. }
  30857. }
  30858. function extractRuntimeProps(node, props, declaredTypes) {
  30859. for (const m of node.members) {
  30860. if (m.type === 'TSPropertySignature' && m.key.type === 'Identifier') {
  30861. props[m.key.name] = {
  30862. key: m.key.name,
  30863. required: !m.optional,
  30864. type: m.typeAnnotation
  30865. ? inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes)
  30866. : [`null`]
  30867. };
  30868. }
  30869. }
  30870. }
  30871. function inferRuntimeType(node, declaredTypes) {
  30872. switch (node.type) {
  30873. case 'TSStringKeyword':
  30874. return ['String'];
  30875. case 'TSNumberKeyword':
  30876. return ['Number'];
  30877. case 'TSBooleanKeyword':
  30878. return ['Boolean'];
  30879. case 'TSObjectKeyword':
  30880. return ['Object'];
  30881. case 'TSTypeLiteral':
  30882. // TODO (nice to have) generate runtime property validation
  30883. return ['Object'];
  30884. case 'TSFunctionType':
  30885. return ['Function'];
  30886. case 'TSArrayType':
  30887. case 'TSTupleType':
  30888. // TODO (nice to have) generate runtime element type/length checks
  30889. return ['Array'];
  30890. case 'TSLiteralType':
  30891. switch (node.literal.type) {
  30892. case 'StringLiteral':
  30893. return ['String'];
  30894. case 'BooleanLiteral':
  30895. return ['Boolean'];
  30896. case 'NumericLiteral':
  30897. case 'BigIntLiteral':
  30898. return ['Number'];
  30899. default:
  30900. return [`null`];
  30901. }
  30902. case 'TSTypeReference':
  30903. if (node.typeName.type === 'Identifier') {
  30904. if (declaredTypes[node.typeName.name]) {
  30905. return declaredTypes[node.typeName.name];
  30906. }
  30907. switch (node.typeName.name) {
  30908. case 'Array':
  30909. case 'Function':
  30910. case 'Object':
  30911. case 'Set':
  30912. case 'Map':
  30913. case 'WeakSet':
  30914. case 'WeakMap':
  30915. return [node.typeName.name];
  30916. case 'Record':
  30917. case 'Partial':
  30918. case 'Readonly':
  30919. case 'Pick':
  30920. case 'Omit':
  30921. case 'Exclude':
  30922. case 'Extract':
  30923. case 'Required':
  30924. case 'InstanceType':
  30925. return ['Object'];
  30926. }
  30927. }
  30928. return [`null`];
  30929. case 'TSUnionType':
  30930. return [
  30931. ...new Set([].concat(node.types.map(t => inferRuntimeType(t, declaredTypes))))
  30932. ];
  30933. case 'TSIntersectionType':
  30934. return ['Object'];
  30935. default:
  30936. return [`null`]; // no runtime check
  30937. }
  30938. }
  30939. function genRuntimeProps(props) {
  30940. const keys = Object.keys(props);
  30941. if (!keys.length) {
  30942. return ``;
  30943. }
  30944. return `\n props: {\n ${keys
  30945. .map(key => {
  30946. const { type, required } = props[key];
  30947. return `${key}: { type: ${toRuntimeTypeString(type)}, required: ${required} }`;
  30948. })
  30949. .join(',\n ')}\n } as unknown as undefined,`;
  30950. }
  30951. function toRuntimeTypeString(types) {
  30952. return types.some(t => t === 'null')
  30953. ? `null`
  30954. : types.length > 1
  30955. ? `[${types.join(', ')}]`
  30956. : types[0];
  30957. }
  30958. function extractRuntimeEmits(node, emits) {
  30959. if (node.type === 'TSUnionType') {
  30960. for (let t of node.types) {
  30961. if (t.type === 'TSParenthesizedType')
  30962. t = t.typeAnnotation;
  30963. if (t.type === 'TSFunctionType') {
  30964. extractRuntimeEmits(t, emits);
  30965. }
  30966. }
  30967. return;
  30968. }
  30969. const eventName = node.parameters[0];
  30970. if (eventName.type === 'Identifier' &&
  30971. eventName.typeAnnotation &&
  30972. eventName.typeAnnotation.type === 'TSTypeAnnotation') {
  30973. const typeNode = eventName.typeAnnotation.typeAnnotation;
  30974. if (typeNode.type === 'TSLiteralType') {
  30975. emits.add(String(typeNode.literal.value));
  30976. }
  30977. else if (typeNode.type === 'TSUnionType') {
  30978. for (const t of typeNode.types) {
  30979. if (t.type === 'TSLiteralType') {
  30980. emits.add(String(t.literal.value));
  30981. }
  30982. }
  30983. }
  30984. }
  30985. }
  30986. function genRuntimeEmits(emits) {
  30987. return emits.size
  30988. ? `\n emits: [${Array.from(emits)
  30989. .map(p => JSON.stringify(p))
  30990. .join(', ')}] as unknown as undefined,`
  30991. : ``;
  30992. }
  30993. const parentStack = [];
  30994. /**
  30995. * Walk an AST and find identifiers that are variable references.
  30996. * This is largely the same logic with `transformExpressions` in compiler-core
  30997. * but with some subtle differences as this needs to handle a wider range of
  30998. * possible syntax.
  30999. */
  31000. function walkIdentifiers(root, onIdentifier) {
  31001. const knownIds = Object.create(null);
  31002. walk$1(root, {
  31003. enter(node, parent) {
  31004. parent && parentStack.push(parent);
  31005. if (node.type === 'Identifier') {
  31006. if (!knownIds[node.name] && isRefIdentifier(node, parent)) {
  31007. onIdentifier(node, parent);
  31008. }
  31009. }
  31010. else if (isFunction$2(node)) {
  31011. // walk function expressions and add its arguments to known identifiers
  31012. // so that we don't prefix them
  31013. node.params.forEach(p => walk$1(p, {
  31014. enter(child, parent) {
  31015. if (child.type === 'Identifier' &&
  31016. // do not record as scope variable if is a destructured key
  31017. !isStaticPropertyKey$1(child, parent) &&
  31018. // do not record if this is a default value
  31019. // assignment of a destructured variable
  31020. !(parent &&
  31021. parent.type === 'AssignmentPattern' &&
  31022. parent.right === child)) {
  31023. const { name } = child;
  31024. if (node.scopeIds && node.scopeIds.has(name)) {
  31025. return;
  31026. }
  31027. if (name in knownIds) {
  31028. knownIds[name]++;
  31029. }
  31030. else {
  31031. knownIds[name] = 1;
  31032. }
  31033. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  31034. }
  31035. }
  31036. }));
  31037. }
  31038. else if (node.type === 'ObjectProperty' &&
  31039. parent.type === 'ObjectPattern') {
  31040. node.inPattern = true;
  31041. }
  31042. },
  31043. leave(node, parent) {
  31044. parent && parentStack.pop();
  31045. if (node.scopeIds) {
  31046. node.scopeIds.forEach((id) => {
  31047. knownIds[id]--;
  31048. if (knownIds[id] === 0) {
  31049. delete knownIds[id];
  31050. }
  31051. });
  31052. }
  31053. }
  31054. });
  31055. }
  31056. function isRefIdentifier(id, parent) {
  31057. // declaration id
  31058. if ((parent.type === 'VariableDeclarator' ||
  31059. parent.type === 'ClassDeclaration') &&
  31060. parent.id === id) {
  31061. return false;
  31062. }
  31063. if (isFunction$2(parent)) {
  31064. // function decalration/expression id
  31065. if (parent.id === id) {
  31066. return false;
  31067. }
  31068. // params list
  31069. if (parent.params.includes(id)) {
  31070. return false;
  31071. }
  31072. }
  31073. // property key
  31074. // this also covers object destructure pattern
  31075. if (isStaticPropertyKey$1(id, parent)) {
  31076. return false;
  31077. }
  31078. // non-assignment array destructure pattern
  31079. if (parent.type === 'ArrayPattern' &&
  31080. !isInDestructureAssignment$1(parent, parentStack)) {
  31081. return false;
  31082. }
  31083. // member expression property
  31084. if ((parent.type === 'MemberExpression' ||
  31085. parent.type === 'OptionalMemberExpression') &&
  31086. parent.property === id &&
  31087. !parent.computed) {
  31088. return false;
  31089. }
  31090. // is a special keyword but parsed as identifier
  31091. if (id.name === 'arguments') {
  31092. return false;
  31093. }
  31094. return true;
  31095. }
  31096. const isStaticProperty$1 = (node) => node &&
  31097. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  31098. !node.computed;
  31099. const isStaticPropertyKey$1 = (node, parent) => isStaticProperty$1(parent) && parent.key === node;
  31100. function isFunction$2(node) {
  31101. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  31102. }
  31103. function isCallOf(node, name) {
  31104. return !!(node &&
  31105. node.type === 'CallExpression' &&
  31106. node.callee.type === 'Identifier' &&
  31107. node.callee.name === name);
  31108. }
  31109. function canNeverBeRef(node, userReactiveImport) {
  31110. if (isCallOf(node, userReactiveImport)) {
  31111. return true;
  31112. }
  31113. switch (node.type) {
  31114. case 'UnaryExpression':
  31115. case 'BinaryExpression':
  31116. case 'ArrayExpression':
  31117. case 'ObjectExpression':
  31118. case 'FunctionExpression':
  31119. case 'ArrowFunctionExpression':
  31120. case 'UpdateExpression':
  31121. case 'ClassExpression':
  31122. case 'TaggedTemplateExpression':
  31123. return true;
  31124. case 'SequenceExpression':
  31125. return canNeverBeRef(node.expressions[node.expressions.length - 1], userReactiveImport);
  31126. default:
  31127. if (node.type.endsWith('Literal')) {
  31128. return true;
  31129. }
  31130. return false;
  31131. }
  31132. }
  31133. function isInDestructureAssignment$1(parent, parentStack) {
  31134. if (parent &&
  31135. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  31136. let i = parentStack.length;
  31137. while (i--) {
  31138. const p = parentStack[i];
  31139. if (p.type === 'AssignmentExpression') {
  31140. const root = parentStack[0];
  31141. // if this is a ref: destructure, it should be treated like a
  31142. // variable decalration!
  31143. return !(root.type === 'LabeledStatement' && root.label.name === 'ref');
  31144. }
  31145. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  31146. break;
  31147. }
  31148. }
  31149. }
  31150. return false;
  31151. }
  31152. /**
  31153. * Analyze bindings in normal `<script>`
  31154. * Note that `compileScriptSetup` already analyzes bindings as part of its
  31155. * compilation process so this should only be used on single `<script>` SFCs.
  31156. */
  31157. function analyzeScriptBindings(ast) {
  31158. for (const node of ast) {
  31159. if (node.type === 'ExportDefaultDeclaration' &&
  31160. node.declaration.type === 'ObjectExpression') {
  31161. return analyzeBindingsFromOptions(node.declaration);
  31162. }
  31163. }
  31164. return {};
  31165. }
  31166. function analyzeBindingsFromOptions(node) {
  31167. const bindings = {};
  31168. for (const property of node.properties) {
  31169. if (property.type === 'ObjectProperty' &&
  31170. !property.computed &&
  31171. property.key.type === 'Identifier') {
  31172. // props
  31173. if (property.key.name === 'props') {
  31174. // props: ['foo']
  31175. // props: { foo: ... }
  31176. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  31177. bindings[key] = "props" /* PROPS */;
  31178. }
  31179. }
  31180. // inject
  31181. else if (property.key.name === 'inject') {
  31182. // inject: ['foo']
  31183. // inject: { foo: {} }
  31184. for (const key of getObjectOrArrayExpressionKeys(property.value)) {
  31185. bindings[key] = "options" /* OPTIONS */;
  31186. }
  31187. }
  31188. // computed & methods
  31189. else if (property.value.type === 'ObjectExpression' &&
  31190. (property.key.name === 'computed' || property.key.name === 'methods')) {
  31191. // methods: { foo() {} }
  31192. // computed: { foo() {} }
  31193. for (const key of getObjectExpressionKeys(property.value)) {
  31194. bindings[key] = "options" /* OPTIONS */;
  31195. }
  31196. }
  31197. }
  31198. // setup & data
  31199. else if (property.type === 'ObjectMethod' &&
  31200. property.key.type === 'Identifier' &&
  31201. (property.key.name === 'setup' || property.key.name === 'data')) {
  31202. for (const bodyItem of property.body.body) {
  31203. // setup() {
  31204. // return {
  31205. // foo: null
  31206. // }
  31207. // }
  31208. if (bodyItem.type === 'ReturnStatement' &&
  31209. bodyItem.argument &&
  31210. bodyItem.argument.type === 'ObjectExpression') {
  31211. for (const key of getObjectExpressionKeys(bodyItem.argument)) {
  31212. bindings[key] =
  31213. property.key.name === 'setup'
  31214. ? "setup-maybe-ref" /* SETUP_MAYBE_REF */
  31215. : "data" /* DATA */;
  31216. }
  31217. }
  31218. }
  31219. }
  31220. }
  31221. return bindings;
  31222. }
  31223. function getObjectExpressionKeys(node) {
  31224. const keys = [];
  31225. for (const prop of node.properties) {
  31226. if ((prop.type === 'ObjectProperty' || prop.type === 'ObjectMethod') &&
  31227. !prop.computed) {
  31228. if (prop.key.type === 'Identifier') {
  31229. keys.push(prop.key.name);
  31230. }
  31231. else if (prop.key.type === 'StringLiteral') {
  31232. keys.push(prop.key.value);
  31233. }
  31234. }
  31235. }
  31236. return keys;
  31237. }
  31238. function getArrayExpressionKeys(node) {
  31239. const keys = [];
  31240. for (const element of node.elements) {
  31241. if (element && element.type === 'StringLiteral') {
  31242. keys.push(element.value);
  31243. }
  31244. }
  31245. return keys;
  31246. }
  31247. function getObjectOrArrayExpressionKeys(value) {
  31248. if (value.type === 'ArrayExpression') {
  31249. return getArrayExpressionKeys(value);
  31250. }
  31251. if (value.type === 'ObjectExpression') {
  31252. return getObjectExpressionKeys(value);
  31253. }
  31254. return [];
  31255. }
  31256. exports.compileScript = compileScript;
  31257. exports.compileStyle = compileStyle;
  31258. exports.compileStyleAsync = compileStyleAsync;
  31259. exports.compileTemplate = compileTemplate;
  31260. exports.generateCodeFrame = generateCodeFrame;
  31261. exports.parse = parse$2;
  31262. exports.rewriteDefault = rewriteDefault;
  31263. Object.defineProperty(exports, '__esModule', { value: true });
  31264. return exports;
  31265. }({}, postcss, path, url, require$$0));