compiler-core.cjs.prod.js 221 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var shared = require('@vue/shared');
  4. var parser = require('@babel/parser');
  5. var sourceMap = require('source-map');
  6. var estreeWalker = require('estree-walker');
  7. function defaultOnError(error) {
  8. throw error;
  9. }
  10. function defaultOnWarn(msg) {
  11. }
  12. function createCompilerError(code, loc, messages, additionalMessage) {
  13. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  14. ;
  15. const error = new SyntaxError(String(msg));
  16. error.code = code;
  17. error.loc = loc;
  18. return error;
  19. }
  20. const errorMessages = {
  21. // parse errors
  22. [0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  23. [1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  24. [2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  25. [3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  26. [4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  27. [5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  28. [6 /* ErrorCodes.EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  29. [7 /* ErrorCodes.EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  30. [8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  31. [9 /* ErrorCodes.EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  32. [10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  33. [11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  34. [12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  35. [13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  36. [14 /* ErrorCodes.MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  37. [15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  38. [16 /* ErrorCodes.NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  39. [17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  40. [18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  41. [19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  42. [21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  43. [20 /* ErrorCodes.UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  44. [22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  45. // Vue-specific parse errors
  46. [23 /* ErrorCodes.X_INVALID_END_TAG */]: 'Invalid end tag.',
  47. [24 /* ErrorCodes.X_MISSING_END_TAG */]: 'Element is missing end tag.',
  48. [25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  49. [27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  50. 'Note that dynamic directive argument cannot contain spaces.',
  51. [26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  52. // transform errors
  53. [28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  54. [29 /* ErrorCodes.X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  55. [30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  56. [31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  57. [32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  58. [33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  59. [34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  60. [35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  61. [36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  62. [37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  63. `When there are multiple named slots, all slots should use <template> ` +
  64. `syntax to avoid scope ambiguity.`,
  65. [38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  66. [39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  67. `default slot. These children will be ignored.`,
  68. [40 /* ErrorCodes.X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  69. [41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  70. [42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  71. [43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  72. [44 /* ErrorCodes.X_V_MODEL_ON_PROPS */]: `v-model cannot be used on a prop, because local prop bindings are not writable.\nUse a v-bind binding combined with a v-on listener that emits update:x event instead.`,
  73. [45 /* ErrorCodes.X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  74. [46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  75. // generic errors
  76. [47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  77. [48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  78. [49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  79. [50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  80. // just to fulfill types
  81. [51 /* ErrorCodes.__EXTEND_POINT__ */]: ``
  82. };
  83. const FRAGMENT = Symbol(``);
  84. const TELEPORT = Symbol(``);
  85. const SUSPENSE = Symbol(``);
  86. const KEEP_ALIVE = Symbol(``);
  87. const BASE_TRANSITION = Symbol(``);
  88. const OPEN_BLOCK = Symbol(``);
  89. const CREATE_BLOCK = Symbol(``);
  90. const CREATE_ELEMENT_BLOCK = Symbol(``);
  91. const CREATE_VNODE = Symbol(``);
  92. const CREATE_ELEMENT_VNODE = Symbol(``);
  93. const CREATE_COMMENT = Symbol(``);
  94. const CREATE_TEXT = Symbol(``);
  95. const CREATE_STATIC = Symbol(``);
  96. const RESOLVE_COMPONENT = Symbol(``);
  97. const RESOLVE_DYNAMIC_COMPONENT = Symbol(``);
  98. const RESOLVE_DIRECTIVE = Symbol(``);
  99. const RESOLVE_FILTER = Symbol(``);
  100. const WITH_DIRECTIVES = Symbol(``);
  101. const RENDER_LIST = Symbol(``);
  102. const RENDER_SLOT = Symbol(``);
  103. const CREATE_SLOTS = Symbol(``);
  104. const TO_DISPLAY_STRING = Symbol(``);
  105. const MERGE_PROPS = Symbol(``);
  106. const NORMALIZE_CLASS = Symbol(``);
  107. const NORMALIZE_STYLE = Symbol(``);
  108. const NORMALIZE_PROPS = Symbol(``);
  109. const GUARD_REACTIVE_PROPS = Symbol(``);
  110. const TO_HANDLERS = Symbol(``);
  111. const CAMELIZE = Symbol(``);
  112. const CAPITALIZE = Symbol(``);
  113. const TO_HANDLER_KEY = Symbol(``);
  114. const SET_BLOCK_TRACKING = Symbol(``);
  115. const PUSH_SCOPE_ID = Symbol(``);
  116. const POP_SCOPE_ID = Symbol(``);
  117. const WITH_CTX = Symbol(``);
  118. const UNREF = Symbol(``);
  119. const IS_REF = Symbol(``);
  120. const WITH_MEMO = Symbol(``);
  121. const IS_MEMO_SAME = Symbol(``);
  122. // Name mapping for runtime helpers that need to be imported from 'vue' in
  123. // generated code. Make sure these are correctly exported in the runtime!
  124. const helperNameMap = {
  125. [FRAGMENT]: `Fragment`,
  126. [TELEPORT]: `Teleport`,
  127. [SUSPENSE]: `Suspense`,
  128. [KEEP_ALIVE]: `KeepAlive`,
  129. [BASE_TRANSITION]: `BaseTransition`,
  130. [OPEN_BLOCK]: `openBlock`,
  131. [CREATE_BLOCK]: `createBlock`,
  132. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  133. [CREATE_VNODE]: `createVNode`,
  134. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  135. [CREATE_COMMENT]: `createCommentVNode`,
  136. [CREATE_TEXT]: `createTextVNode`,
  137. [CREATE_STATIC]: `createStaticVNode`,
  138. [RESOLVE_COMPONENT]: `resolveComponent`,
  139. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  140. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  141. [RESOLVE_FILTER]: `resolveFilter`,
  142. [WITH_DIRECTIVES]: `withDirectives`,
  143. [RENDER_LIST]: `renderList`,
  144. [RENDER_SLOT]: `renderSlot`,
  145. [CREATE_SLOTS]: `createSlots`,
  146. [TO_DISPLAY_STRING]: `toDisplayString`,
  147. [MERGE_PROPS]: `mergeProps`,
  148. [NORMALIZE_CLASS]: `normalizeClass`,
  149. [NORMALIZE_STYLE]: `normalizeStyle`,
  150. [NORMALIZE_PROPS]: `normalizeProps`,
  151. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  152. [TO_HANDLERS]: `toHandlers`,
  153. [CAMELIZE]: `camelize`,
  154. [CAPITALIZE]: `capitalize`,
  155. [TO_HANDLER_KEY]: `toHandlerKey`,
  156. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  157. [PUSH_SCOPE_ID]: `pushScopeId`,
  158. [POP_SCOPE_ID]: `popScopeId`,
  159. [WITH_CTX]: `withCtx`,
  160. [UNREF]: `unref`,
  161. [IS_REF]: `isRef`,
  162. [WITH_MEMO]: `withMemo`,
  163. [IS_MEMO_SAME]: `isMemoSame`
  164. };
  165. function registerRuntimeHelpers(helpers) {
  166. Object.getOwnPropertySymbols(helpers).forEach(s => {
  167. helperNameMap[s] = helpers[s];
  168. });
  169. }
  170. // AST Utilities ---------------------------------------------------------------
  171. // Some expressions, e.g. sequence and conditional expressions, are never
  172. // associated with template nodes, so their source locations are just a stub.
  173. // Container types like CompoundExpression also don't need a real location.
  174. const locStub = {
  175. source: '',
  176. start: { line: 1, column: 1, offset: 0 },
  177. end: { line: 1, column: 1, offset: 0 }
  178. };
  179. function createRoot(children, loc = locStub) {
  180. return {
  181. type: 0 /* NodeTypes.ROOT */,
  182. children,
  183. helpers: [],
  184. components: [],
  185. directives: [],
  186. hoists: [],
  187. imports: [],
  188. cached: 0,
  189. temps: 0,
  190. codegenNode: undefined,
  191. loc
  192. };
  193. }
  194. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  195. if (context) {
  196. if (isBlock) {
  197. context.helper(OPEN_BLOCK);
  198. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  199. }
  200. else {
  201. context.helper(getVNodeHelper(context.inSSR, isComponent));
  202. }
  203. if (directives) {
  204. context.helper(WITH_DIRECTIVES);
  205. }
  206. }
  207. return {
  208. type: 13 /* NodeTypes.VNODE_CALL */,
  209. tag,
  210. props,
  211. children,
  212. patchFlag,
  213. dynamicProps,
  214. directives,
  215. isBlock,
  216. disableTracking,
  217. isComponent,
  218. loc
  219. };
  220. }
  221. function createArrayExpression(elements, loc = locStub) {
  222. return {
  223. type: 17 /* NodeTypes.JS_ARRAY_EXPRESSION */,
  224. loc,
  225. elements
  226. };
  227. }
  228. function createObjectExpression(properties, loc = locStub) {
  229. return {
  230. type: 15 /* NodeTypes.JS_OBJECT_EXPRESSION */,
  231. loc,
  232. properties
  233. };
  234. }
  235. function createObjectProperty(key, value) {
  236. return {
  237. type: 16 /* NodeTypes.JS_PROPERTY */,
  238. loc: locStub,
  239. key: shared.isString(key) ? createSimpleExpression(key, true) : key,
  240. value
  241. };
  242. }
  243. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* ConstantTypes.NOT_CONSTANT */) {
  244. return {
  245. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  246. loc,
  247. content,
  248. isStatic,
  249. constType: isStatic ? 3 /* ConstantTypes.CAN_STRINGIFY */ : constType
  250. };
  251. }
  252. function createInterpolation(content, loc) {
  253. return {
  254. type: 5 /* NodeTypes.INTERPOLATION */,
  255. loc,
  256. content: shared.isString(content)
  257. ? createSimpleExpression(content, false, loc)
  258. : content
  259. };
  260. }
  261. function createCompoundExpression(children, loc = locStub) {
  262. return {
  263. type: 8 /* NodeTypes.COMPOUND_EXPRESSION */,
  264. loc,
  265. children
  266. };
  267. }
  268. function createCallExpression(callee, args = [], loc = locStub) {
  269. return {
  270. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  271. loc,
  272. callee,
  273. arguments: args
  274. };
  275. }
  276. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  277. return {
  278. type: 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */,
  279. params,
  280. returns,
  281. newline,
  282. isSlot,
  283. loc
  284. };
  285. }
  286. function createConditionalExpression(test, consequent, alternate, newline = true) {
  287. return {
  288. type: 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */,
  289. test,
  290. consequent,
  291. alternate,
  292. newline,
  293. loc: locStub
  294. };
  295. }
  296. function createCacheExpression(index, value, isVNode = false) {
  297. return {
  298. type: 20 /* NodeTypes.JS_CACHE_EXPRESSION */,
  299. index,
  300. value,
  301. isVNode,
  302. loc: locStub
  303. };
  304. }
  305. function createBlockStatement(body) {
  306. return {
  307. type: 21 /* NodeTypes.JS_BLOCK_STATEMENT */,
  308. body,
  309. loc: locStub
  310. };
  311. }
  312. function createTemplateLiteral(elements) {
  313. return {
  314. type: 22 /* NodeTypes.JS_TEMPLATE_LITERAL */,
  315. elements,
  316. loc: locStub
  317. };
  318. }
  319. function createIfStatement(test, consequent, alternate) {
  320. return {
  321. type: 23 /* NodeTypes.JS_IF_STATEMENT */,
  322. test,
  323. consequent,
  324. alternate,
  325. loc: locStub
  326. };
  327. }
  328. function createAssignmentExpression(left, right) {
  329. return {
  330. type: 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */,
  331. left,
  332. right,
  333. loc: locStub
  334. };
  335. }
  336. function createSequenceExpression(expressions) {
  337. return {
  338. type: 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */,
  339. expressions,
  340. loc: locStub
  341. };
  342. }
  343. function createReturnStatement(returns) {
  344. return {
  345. type: 26 /* NodeTypes.JS_RETURN_STATEMENT */,
  346. returns,
  347. loc: locStub
  348. };
  349. }
  350. const isStaticExp = (p) => p.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && p.isStatic;
  351. const isBuiltInType = (tag, expected) => tag === expected || tag === shared.hyphenate(expected);
  352. function isCoreComponent(tag) {
  353. if (isBuiltInType(tag, 'Teleport')) {
  354. return TELEPORT;
  355. }
  356. else if (isBuiltInType(tag, 'Suspense')) {
  357. return SUSPENSE;
  358. }
  359. else if (isBuiltInType(tag, 'KeepAlive')) {
  360. return KEEP_ALIVE;
  361. }
  362. else if (isBuiltInType(tag, 'BaseTransition')) {
  363. return BASE_TRANSITION;
  364. }
  365. }
  366. const nonIdentifierRE = /^\d|[^\$\w]/;
  367. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  368. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  369. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  370. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  371. /**
  372. * Simple lexer to check if an expression is a member expression. This is
  373. * lax and only checks validity at the root level (i.e. does not validate exps
  374. * inside square brackets), but it's ok since these are only used on template
  375. * expressions and false positives are invalid expressions in the first place.
  376. */
  377. const isMemberExpressionBrowser = (path) => {
  378. // remove whitespaces around . or [ first
  379. path = path.trim().replace(whitespaceRE, s => s.trim());
  380. let state = 0 /* MemberExpLexState.inMemberExp */;
  381. let stateStack = [];
  382. let currentOpenBracketCount = 0;
  383. let currentOpenParensCount = 0;
  384. let currentStringType = null;
  385. for (let i = 0; i < path.length; i++) {
  386. const char = path.charAt(i);
  387. switch (state) {
  388. case 0 /* MemberExpLexState.inMemberExp */:
  389. if (char === '[') {
  390. stateStack.push(state);
  391. state = 1 /* MemberExpLexState.inBrackets */;
  392. currentOpenBracketCount++;
  393. }
  394. else if (char === '(') {
  395. stateStack.push(state);
  396. state = 2 /* MemberExpLexState.inParens */;
  397. currentOpenParensCount++;
  398. }
  399. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  400. return false;
  401. }
  402. break;
  403. case 1 /* MemberExpLexState.inBrackets */:
  404. if (char === `'` || char === `"` || char === '`') {
  405. stateStack.push(state);
  406. state = 3 /* MemberExpLexState.inString */;
  407. currentStringType = char;
  408. }
  409. else if (char === `[`) {
  410. currentOpenBracketCount++;
  411. }
  412. else if (char === `]`) {
  413. if (!--currentOpenBracketCount) {
  414. state = stateStack.pop();
  415. }
  416. }
  417. break;
  418. case 2 /* MemberExpLexState.inParens */:
  419. if (char === `'` || char === `"` || char === '`') {
  420. stateStack.push(state);
  421. state = 3 /* MemberExpLexState.inString */;
  422. currentStringType = char;
  423. }
  424. else if (char === `(`) {
  425. currentOpenParensCount++;
  426. }
  427. else if (char === `)`) {
  428. // if the exp ends as a call then it should not be considered valid
  429. if (i === path.length - 1) {
  430. return false;
  431. }
  432. if (!--currentOpenParensCount) {
  433. state = stateStack.pop();
  434. }
  435. }
  436. break;
  437. case 3 /* MemberExpLexState.inString */:
  438. if (char === currentStringType) {
  439. state = stateStack.pop();
  440. currentStringType = null;
  441. }
  442. break;
  443. }
  444. }
  445. return !currentOpenBracketCount && !currentOpenParensCount;
  446. };
  447. const isMemberExpressionNode = (path, context) => {
  448. try {
  449. let ret = parser.parseExpression(path, {
  450. plugins: context.expressionPlugins
  451. });
  452. if (ret.type === 'TSAsExpression' || ret.type === 'TSTypeAssertion') {
  453. ret = ret.expression;
  454. }
  455. return (ret.type === 'MemberExpression' ||
  456. ret.type === 'OptionalMemberExpression' ||
  457. ret.type === 'Identifier');
  458. }
  459. catch (e) {
  460. return false;
  461. }
  462. };
  463. const isMemberExpression = isMemberExpressionNode;
  464. function getInnerRange(loc, offset, length) {
  465. const source = loc.source.slice(offset, offset + length);
  466. const newLoc = {
  467. source,
  468. start: advancePositionWithClone(loc.start, loc.source, offset),
  469. end: loc.end
  470. };
  471. if (length != null) {
  472. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  473. }
  474. return newLoc;
  475. }
  476. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  477. return advancePositionWithMutation(shared.extend({}, pos), source, numberOfCharacters);
  478. }
  479. // advance by mutation without cloning (for performance reasons), since this
  480. // gets called a lot in the parser
  481. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  482. let linesCount = 0;
  483. let lastNewLinePos = -1;
  484. for (let i = 0; i < numberOfCharacters; i++) {
  485. if (source.charCodeAt(i) === 10 /* newline char code */) {
  486. linesCount++;
  487. lastNewLinePos = i;
  488. }
  489. }
  490. pos.offset += numberOfCharacters;
  491. pos.line += linesCount;
  492. pos.column =
  493. lastNewLinePos === -1
  494. ? pos.column + numberOfCharacters
  495. : numberOfCharacters - lastNewLinePos;
  496. return pos;
  497. }
  498. function assert(condition, msg) {
  499. /* istanbul ignore if */
  500. if (!condition) {
  501. throw new Error(msg || `unexpected compiler condition`);
  502. }
  503. }
  504. function findDir(node, name, allowEmpty = false) {
  505. for (let i = 0; i < node.props.length; i++) {
  506. const p = node.props[i];
  507. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  508. (allowEmpty || p.exp) &&
  509. (shared.isString(name) ? p.name === name : name.test(p.name))) {
  510. return p;
  511. }
  512. }
  513. }
  514. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  515. for (let i = 0; i < node.props.length; i++) {
  516. const p = node.props[i];
  517. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  518. if (dynamicOnly)
  519. continue;
  520. if (p.name === name && (p.value || allowEmpty)) {
  521. return p;
  522. }
  523. }
  524. else if (p.name === 'bind' &&
  525. (p.exp || allowEmpty) &&
  526. isStaticArgOf(p.arg, name)) {
  527. return p;
  528. }
  529. }
  530. }
  531. function isStaticArgOf(arg, name) {
  532. return !!(arg && isStaticExp(arg) && arg.content === name);
  533. }
  534. function hasDynamicKeyVBind(node) {
  535. return node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  536. p.name === 'bind' &&
  537. (!p.arg || // v-bind="obj"
  538. p.arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  539. !p.arg.isStatic) // v-bind:[foo]
  540. );
  541. }
  542. function isText(node) {
  543. return node.type === 5 /* NodeTypes.INTERPOLATION */ || node.type === 2 /* NodeTypes.TEXT */;
  544. }
  545. function isVSlot(p) {
  546. return p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'slot';
  547. }
  548. function isTemplateNode(node) {
  549. return (node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 3 /* ElementTypes.TEMPLATE */);
  550. }
  551. function isSlotOutlet(node) {
  552. return node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 2 /* ElementTypes.SLOT */;
  553. }
  554. function getVNodeHelper(ssr, isComponent) {
  555. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  556. }
  557. function getVNodeBlockHelper(ssr, isComponent) {
  558. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  559. }
  560. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  561. function getUnnormalizedProps(props, callPath = []) {
  562. if (props &&
  563. !shared.isString(props) &&
  564. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  565. const callee = props.callee;
  566. if (!shared.isString(callee) && propsHelperSet.has(callee)) {
  567. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  568. }
  569. }
  570. return [props, callPath];
  571. }
  572. function injectProp(node, prop, context) {
  573. let propsWithInjection;
  574. /**
  575. * 1. mergeProps(...)
  576. * 2. toHandlers(...)
  577. * 3. normalizeProps(...)
  578. * 4. normalizeProps(guardReactiveProps(...))
  579. *
  580. * we need to get the real props before normalization
  581. */
  582. let props = node.type === 13 /* NodeTypes.VNODE_CALL */ ? node.props : node.arguments[2];
  583. let callPath = [];
  584. let parentCall;
  585. if (props &&
  586. !shared.isString(props) &&
  587. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  588. const ret = getUnnormalizedProps(props);
  589. props = ret[0];
  590. callPath = ret[1];
  591. parentCall = callPath[callPath.length - 1];
  592. }
  593. if (props == null || shared.isString(props)) {
  594. propsWithInjection = createObjectExpression([prop]);
  595. }
  596. else if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  597. // merged props... add ours
  598. // only inject key to object literal if it's the first argument so that
  599. // if doesn't override user provided keys
  600. const first = props.arguments[0];
  601. if (!shared.isString(first) && first.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  602. // #6631
  603. if (!hasProp(prop, first)) {
  604. first.properties.unshift(prop);
  605. }
  606. }
  607. else {
  608. if (props.callee === TO_HANDLERS) {
  609. // #2366
  610. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  611. createObjectExpression([prop]),
  612. props
  613. ]);
  614. }
  615. else {
  616. props.arguments.unshift(createObjectExpression([prop]));
  617. }
  618. }
  619. !propsWithInjection && (propsWithInjection = props);
  620. }
  621. else if (props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  622. if (!hasProp(prop, props)) {
  623. props.properties.unshift(prop);
  624. }
  625. propsWithInjection = props;
  626. }
  627. else {
  628. // single v-bind with expression, return a merged replacement
  629. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  630. createObjectExpression([prop]),
  631. props
  632. ]);
  633. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  634. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  635. // the `guardReactiveProps` will no longer be needed
  636. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  637. parentCall = callPath[callPath.length - 2];
  638. }
  639. }
  640. if (node.type === 13 /* NodeTypes.VNODE_CALL */) {
  641. if (parentCall) {
  642. parentCall.arguments[0] = propsWithInjection;
  643. }
  644. else {
  645. node.props = propsWithInjection;
  646. }
  647. }
  648. else {
  649. if (parentCall) {
  650. parentCall.arguments[0] = propsWithInjection;
  651. }
  652. else {
  653. node.arguments[2] = propsWithInjection;
  654. }
  655. }
  656. }
  657. // check existing key to avoid overriding user provided keys
  658. function hasProp(prop, props) {
  659. let result = false;
  660. if (prop.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  661. const propKeyName = prop.key.content;
  662. result = props.properties.some(p => p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  663. p.key.content === propKeyName);
  664. }
  665. return result;
  666. }
  667. function toValidAssetId(name, type) {
  668. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  669. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  670. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  671. })}`;
  672. }
  673. // Check if a node contains expressions that reference current context scope ids
  674. function hasScopeRef(node, ids) {
  675. if (!node || Object.keys(ids).length === 0) {
  676. return false;
  677. }
  678. switch (node.type) {
  679. case 1 /* NodeTypes.ELEMENT */:
  680. for (let i = 0; i < node.props.length; i++) {
  681. const p = node.props[i];
  682. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  683. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  684. return true;
  685. }
  686. }
  687. return node.children.some(c => hasScopeRef(c, ids));
  688. case 11 /* NodeTypes.FOR */:
  689. if (hasScopeRef(node.source, ids)) {
  690. return true;
  691. }
  692. return node.children.some(c => hasScopeRef(c, ids));
  693. case 9 /* NodeTypes.IF */:
  694. return node.branches.some(b => hasScopeRef(b, ids));
  695. case 10 /* NodeTypes.IF_BRANCH */:
  696. if (hasScopeRef(node.condition, ids)) {
  697. return true;
  698. }
  699. return node.children.some(c => hasScopeRef(c, ids));
  700. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  701. return (!node.isStatic &&
  702. isSimpleIdentifier(node.content) &&
  703. !!ids[node.content]);
  704. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  705. return node.children.some(c => shared.isObject(c) && hasScopeRef(c, ids));
  706. case 5 /* NodeTypes.INTERPOLATION */:
  707. case 12 /* NodeTypes.TEXT_CALL */:
  708. return hasScopeRef(node.content, ids);
  709. case 2 /* NodeTypes.TEXT */:
  710. case 3 /* NodeTypes.COMMENT */:
  711. return false;
  712. default:
  713. return false;
  714. }
  715. }
  716. function getMemoedVNodeCall(node) {
  717. if (node.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  718. return node.arguments[1].returns;
  719. }
  720. else {
  721. return node;
  722. }
  723. }
  724. function makeBlock(node, { helper, removeHelper, inSSR }) {
  725. if (!node.isBlock) {
  726. node.isBlock = true;
  727. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  728. helper(OPEN_BLOCK);
  729. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  730. }
  731. }
  732. const deprecationData = {
  733. ["COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */]: {
  734. message: `Platform-native elements with "is" prop will no longer be ` +
  735. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  736. `prefixed with "vue:".`,
  737. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  738. },
  739. ["COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */]: {
  740. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  741. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  742. `\`v-model:${key}\`.`,
  743. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  744. },
  745. ["COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */]: {
  746. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  747. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  748. },
  749. ["COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */]: {
  750. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  751. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  752. `that appears before v-bind in the case of conflict. ` +
  753. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  754. `You can also suppress this warning if the usage is intended.`,
  755. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  756. },
  757. ["COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */]: {
  758. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  759. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  760. },
  761. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  762. message: `v-if / v-for precedence when used on the same element has changed ` +
  763. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  764. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  765. `with <template> tags or use a computed property that filters v-for ` +
  766. `data source.`,
  767. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  768. },
  769. ["COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */]: {
  770. message: `<template> with no special directives will render as a native template ` +
  771. `element instead of its inner content in Vue 3.`
  772. },
  773. ["COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */]: {
  774. message: `"inline-template" has been removed in Vue 3.`,
  775. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  776. },
  777. ["COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */]: {
  778. message: `filters have been removed in Vue 3. ` +
  779. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  780. `Use method calls or computed properties instead.`,
  781. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  782. }
  783. };
  784. function getCompatValue(key, context) {
  785. const config = context.options
  786. ? context.options.compatConfig
  787. : context.compatConfig;
  788. const value = config && config[key];
  789. if (key === 'MODE') {
  790. return value || 3; // compiler defaults to v3 behavior
  791. }
  792. else {
  793. return value;
  794. }
  795. }
  796. function isCompatEnabled(key, context) {
  797. const mode = getCompatValue('MODE', context);
  798. const value = getCompatValue(key, context);
  799. // in v3 mode, only enable if explicitly set to true
  800. // otherwise enable for any non-false value
  801. return mode === 3 ? value === true : value !== false;
  802. }
  803. function checkCompatEnabled(key, context, loc, ...args) {
  804. const enabled = isCompatEnabled(key, context);
  805. return enabled;
  806. }
  807. function warnDeprecation(key, context, loc, ...args) {
  808. const val = getCompatValue(key, context);
  809. if (val === 'suppress-warning') {
  810. return;
  811. }
  812. const { message, link } = deprecationData[key];
  813. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  814. const err = new SyntaxError(msg);
  815. err.code = key;
  816. if (loc)
  817. err.loc = loc;
  818. context.onWarn(err);
  819. }
  820. // The default decoder only provides escapes for characters reserved as part of
  821. // the template syntax, and is only used if the custom renderer did not provide
  822. // a platform-specific decoder.
  823. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  824. const decodeMap = {
  825. gt: '>',
  826. lt: '<',
  827. amp: '&',
  828. apos: "'",
  829. quot: '"'
  830. };
  831. const defaultParserOptions = {
  832. delimiters: [`{{`, `}}`],
  833. getNamespace: () => 0 /* Namespaces.HTML */,
  834. getTextMode: () => 0 /* TextModes.DATA */,
  835. isVoidTag: shared.NO,
  836. isPreTag: shared.NO,
  837. isCustomElement: shared.NO,
  838. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  839. onError: defaultOnError,
  840. onWarn: defaultOnWarn,
  841. comments: false
  842. };
  843. function baseParse(content, options = {}) {
  844. const context = createParserContext(content, options);
  845. const start = getCursor(context);
  846. return createRoot(parseChildren(context, 0 /* TextModes.DATA */, []), getSelection(context, start));
  847. }
  848. function createParserContext(content, rawOptions) {
  849. const options = shared.extend({}, defaultParserOptions);
  850. let key;
  851. for (key in rawOptions) {
  852. // @ts-ignore
  853. options[key] =
  854. rawOptions[key] === undefined
  855. ? defaultParserOptions[key]
  856. : rawOptions[key];
  857. }
  858. return {
  859. options,
  860. column: 1,
  861. line: 1,
  862. offset: 0,
  863. originalSource: content,
  864. source: content,
  865. inPre: false,
  866. inVPre: false,
  867. onWarn: options.onWarn
  868. };
  869. }
  870. function parseChildren(context, mode, ancestors) {
  871. const parent = last(ancestors);
  872. const ns = parent ? parent.ns : 0 /* Namespaces.HTML */;
  873. const nodes = [];
  874. while (!isEnd(context, mode, ancestors)) {
  875. const s = context.source;
  876. let node = undefined;
  877. if (mode === 0 /* TextModes.DATA */ || mode === 1 /* TextModes.RCDATA */) {
  878. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  879. // '{{'
  880. node = parseInterpolation(context, mode);
  881. }
  882. else if (mode === 0 /* TextModes.DATA */ && s[0] === '<') {
  883. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  884. if (s.length === 1) {
  885. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 1);
  886. }
  887. else if (s[1] === '!') {
  888. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  889. if (startsWith(s, '<!--')) {
  890. node = parseComment(context);
  891. }
  892. else if (startsWith(s, '<!DOCTYPE')) {
  893. // Ignore DOCTYPE by a limitation.
  894. node = parseBogusComment(context);
  895. }
  896. else if (startsWith(s, '<![CDATA[')) {
  897. if (ns !== 0 /* Namespaces.HTML */) {
  898. node = parseCDATA(context, ancestors);
  899. }
  900. else {
  901. emitError(context, 1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */);
  902. node = parseBogusComment(context);
  903. }
  904. }
  905. else {
  906. emitError(context, 11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */);
  907. node = parseBogusComment(context);
  908. }
  909. }
  910. else if (s[1] === '/') {
  911. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  912. if (s.length === 2) {
  913. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 2);
  914. }
  915. else if (s[2] === '>') {
  916. emitError(context, 14 /* ErrorCodes.MISSING_END_TAG_NAME */, 2);
  917. advanceBy(context, 3);
  918. continue;
  919. }
  920. else if (/[a-z]/i.test(s[2])) {
  921. emitError(context, 23 /* ErrorCodes.X_INVALID_END_TAG */);
  922. parseTag(context, 1 /* TagType.End */, parent);
  923. continue;
  924. }
  925. else {
  926. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  927. node = parseBogusComment(context);
  928. }
  929. }
  930. else if (/[a-z]/i.test(s[1])) {
  931. node = parseElement(context, ancestors);
  932. // 2.x <template> with no directive compat
  933. if (isCompatEnabled("COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */, context) &&
  934. node &&
  935. node.tag === 'template' &&
  936. !node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  937. isSpecialTemplateDirective(p.name))) {
  938. node = node.children;
  939. }
  940. }
  941. else if (s[1] === '?') {
  942. emitError(context, 21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  943. node = parseBogusComment(context);
  944. }
  945. else {
  946. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  947. }
  948. }
  949. }
  950. if (!node) {
  951. node = parseText(context, mode);
  952. }
  953. if (shared.isArray(node)) {
  954. for (let i = 0; i < node.length; i++) {
  955. pushNode(nodes, node[i]);
  956. }
  957. }
  958. else {
  959. pushNode(nodes, node);
  960. }
  961. }
  962. // Whitespace handling strategy like v2
  963. let removedWhitespace = false;
  964. if (mode !== 2 /* TextModes.RAWTEXT */ && mode !== 1 /* TextModes.RCDATA */) {
  965. const shouldCondense = context.options.whitespace !== 'preserve';
  966. for (let i = 0; i < nodes.length; i++) {
  967. const node = nodes[i];
  968. if (node.type === 2 /* NodeTypes.TEXT */) {
  969. if (!context.inPre) {
  970. if (!/[^\t\r\n\f ]/.test(node.content)) {
  971. const prev = nodes[i - 1];
  972. const next = nodes[i + 1];
  973. // Remove if:
  974. // - the whitespace is the first or last node, or:
  975. // - (condense mode) the whitespace is between twos comments, or:
  976. // - (condense mode) the whitespace is between comment and element, or:
  977. // - (condense mode) the whitespace is between two elements AND contains newline
  978. if (!prev ||
  979. !next ||
  980. (shouldCondense &&
  981. ((prev.type === 3 /* NodeTypes.COMMENT */ &&
  982. next.type === 3 /* NodeTypes.COMMENT */) ||
  983. (prev.type === 3 /* NodeTypes.COMMENT */ &&
  984. next.type === 1 /* NodeTypes.ELEMENT */) ||
  985. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  986. next.type === 3 /* NodeTypes.COMMENT */) ||
  987. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  988. next.type === 1 /* NodeTypes.ELEMENT */ &&
  989. /[\r\n]/.test(node.content))))) {
  990. removedWhitespace = true;
  991. nodes[i] = null;
  992. }
  993. else {
  994. // Otherwise, the whitespace is condensed into a single space
  995. node.content = ' ';
  996. }
  997. }
  998. else if (shouldCondense) {
  999. // in condense mode, consecutive whitespaces in text are condensed
  1000. // down to a single space.
  1001. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  1002. }
  1003. }
  1004. else {
  1005. // #6410 normalize windows newlines in <pre>:
  1006. // in SSR, browsers normalize server-rendered \r\n into a single \n
  1007. // in the DOM
  1008. node.content = node.content.replace(/\r\n/g, '\n');
  1009. }
  1010. }
  1011. // Remove comment nodes if desired by configuration.
  1012. else if (node.type === 3 /* NodeTypes.COMMENT */ && !context.options.comments) {
  1013. removedWhitespace = true;
  1014. nodes[i] = null;
  1015. }
  1016. }
  1017. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  1018. // remove leading newline per html spec
  1019. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  1020. const first = nodes[0];
  1021. if (first && first.type === 2 /* NodeTypes.TEXT */) {
  1022. first.content = first.content.replace(/^\r?\n/, '');
  1023. }
  1024. }
  1025. }
  1026. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  1027. }
  1028. function pushNode(nodes, node) {
  1029. if (node.type === 2 /* NodeTypes.TEXT */) {
  1030. const prev = last(nodes);
  1031. // Merge if both this and the previous node are text and those are
  1032. // consecutive. This happens for cases like "a < b".
  1033. if (prev &&
  1034. prev.type === 2 /* NodeTypes.TEXT */ &&
  1035. prev.loc.end.offset === node.loc.start.offset) {
  1036. prev.content += node.content;
  1037. prev.loc.end = node.loc.end;
  1038. prev.loc.source += node.loc.source;
  1039. return;
  1040. }
  1041. }
  1042. nodes.push(node);
  1043. }
  1044. function parseCDATA(context, ancestors) {
  1045. advanceBy(context, 9);
  1046. const nodes = parseChildren(context, 3 /* TextModes.CDATA */, ancestors);
  1047. if (context.source.length === 0) {
  1048. emitError(context, 6 /* ErrorCodes.EOF_IN_CDATA */);
  1049. }
  1050. else {
  1051. advanceBy(context, 3);
  1052. }
  1053. return nodes;
  1054. }
  1055. function parseComment(context) {
  1056. const start = getCursor(context);
  1057. let content;
  1058. // Regular comment.
  1059. const match = /--(\!)?>/.exec(context.source);
  1060. if (!match) {
  1061. content = context.source.slice(4);
  1062. advanceBy(context, context.source.length);
  1063. emitError(context, 7 /* ErrorCodes.EOF_IN_COMMENT */);
  1064. }
  1065. else {
  1066. if (match.index <= 3) {
  1067. emitError(context, 0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  1068. }
  1069. if (match[1]) {
  1070. emitError(context, 10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */);
  1071. }
  1072. content = context.source.slice(4, match.index);
  1073. // Advancing with reporting nested comments.
  1074. const s = context.source.slice(0, match.index);
  1075. let prevIndex = 1, nestedIndex = 0;
  1076. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  1077. advanceBy(context, nestedIndex - prevIndex + 1);
  1078. if (nestedIndex + 4 < s.length) {
  1079. emitError(context, 16 /* ErrorCodes.NESTED_COMMENT */);
  1080. }
  1081. prevIndex = nestedIndex + 1;
  1082. }
  1083. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  1084. }
  1085. return {
  1086. type: 3 /* NodeTypes.COMMENT */,
  1087. content,
  1088. loc: getSelection(context, start)
  1089. };
  1090. }
  1091. function parseBogusComment(context) {
  1092. const start = getCursor(context);
  1093. const contentStart = context.source[1] === '?' ? 1 : 2;
  1094. let content;
  1095. const closeIndex = context.source.indexOf('>');
  1096. if (closeIndex === -1) {
  1097. content = context.source.slice(contentStart);
  1098. advanceBy(context, context.source.length);
  1099. }
  1100. else {
  1101. content = context.source.slice(contentStart, closeIndex);
  1102. advanceBy(context, closeIndex + 1);
  1103. }
  1104. return {
  1105. type: 3 /* NodeTypes.COMMENT */,
  1106. content,
  1107. loc: getSelection(context, start)
  1108. };
  1109. }
  1110. function parseElement(context, ancestors) {
  1111. // Start tag.
  1112. const wasInPre = context.inPre;
  1113. const wasInVPre = context.inVPre;
  1114. const parent = last(ancestors);
  1115. const element = parseTag(context, 0 /* TagType.Start */, parent);
  1116. const isPreBoundary = context.inPre && !wasInPre;
  1117. const isVPreBoundary = context.inVPre && !wasInVPre;
  1118. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  1119. // #4030 self-closing <pre> tag
  1120. if (isPreBoundary) {
  1121. context.inPre = false;
  1122. }
  1123. if (isVPreBoundary) {
  1124. context.inVPre = false;
  1125. }
  1126. return element;
  1127. }
  1128. // Children.
  1129. ancestors.push(element);
  1130. const mode = context.options.getTextMode(element, parent);
  1131. const children = parseChildren(context, mode, ancestors);
  1132. ancestors.pop();
  1133. // 2.x inline-template compat
  1134. {
  1135. const inlineTemplateProp = element.props.find(p => p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'inline-template');
  1136. if (inlineTemplateProp &&
  1137. checkCompatEnabled("COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */, context, inlineTemplateProp.loc)) {
  1138. const loc = getSelection(context, element.loc.end);
  1139. inlineTemplateProp.value = {
  1140. type: 2 /* NodeTypes.TEXT */,
  1141. content: loc.source,
  1142. loc
  1143. };
  1144. }
  1145. }
  1146. element.children = children;
  1147. // End tag.
  1148. if (startsWithEndTagOpen(context.source, element.tag)) {
  1149. parseTag(context, 1 /* TagType.End */, parent);
  1150. }
  1151. else {
  1152. emitError(context, 24 /* ErrorCodes.X_MISSING_END_TAG */, 0, element.loc.start);
  1153. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  1154. const first = children[0];
  1155. if (first && startsWith(first.loc.source, '<!--')) {
  1156. emitError(context, 8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  1157. }
  1158. }
  1159. }
  1160. element.loc = getSelection(context, element.loc.start);
  1161. if (isPreBoundary) {
  1162. context.inPre = false;
  1163. }
  1164. if (isVPreBoundary) {
  1165. context.inVPre = false;
  1166. }
  1167. return element;
  1168. }
  1169. const isSpecialTemplateDirective = /*#__PURE__*/ shared.makeMap(`if,else,else-if,for,slot`);
  1170. function parseTag(context, type, parent) {
  1171. // Tag open.
  1172. const start = getCursor(context);
  1173. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  1174. const tag = match[1];
  1175. const ns = context.options.getNamespace(tag, parent);
  1176. advanceBy(context, match[0].length);
  1177. advanceSpaces(context);
  1178. // save current state in case we need to re-parse attributes with v-pre
  1179. const cursor = getCursor(context);
  1180. const currentSource = context.source;
  1181. // check <pre> tag
  1182. if (context.options.isPreTag(tag)) {
  1183. context.inPre = true;
  1184. }
  1185. // Attributes.
  1186. let props = parseAttributes(context, type);
  1187. // check v-pre
  1188. if (type === 0 /* TagType.Start */ &&
  1189. !context.inVPre &&
  1190. props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'pre')) {
  1191. context.inVPre = true;
  1192. // reset context
  1193. shared.extend(context, cursor);
  1194. context.source = currentSource;
  1195. // re-parse attrs and filter out v-pre itself
  1196. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  1197. }
  1198. // Tag close.
  1199. let isSelfClosing = false;
  1200. if (context.source.length === 0) {
  1201. emitError(context, 9 /* ErrorCodes.EOF_IN_TAG */);
  1202. }
  1203. else {
  1204. isSelfClosing = startsWith(context.source, '/>');
  1205. if (type === 1 /* TagType.End */ && isSelfClosing) {
  1206. emitError(context, 4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */);
  1207. }
  1208. advanceBy(context, isSelfClosing ? 2 : 1);
  1209. }
  1210. if (type === 1 /* TagType.End */) {
  1211. return;
  1212. }
  1213. let tagType = 0 /* ElementTypes.ELEMENT */;
  1214. if (!context.inVPre) {
  1215. if (tag === 'slot') {
  1216. tagType = 2 /* ElementTypes.SLOT */;
  1217. }
  1218. else if (tag === 'template') {
  1219. if (props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  1220. tagType = 3 /* ElementTypes.TEMPLATE */;
  1221. }
  1222. }
  1223. else if (isComponent(tag, props, context)) {
  1224. tagType = 1 /* ElementTypes.COMPONENT */;
  1225. }
  1226. }
  1227. return {
  1228. type: 1 /* NodeTypes.ELEMENT */,
  1229. ns,
  1230. tag,
  1231. tagType,
  1232. props,
  1233. isSelfClosing,
  1234. children: [],
  1235. loc: getSelection(context, start),
  1236. codegenNode: undefined // to be created during transform phase
  1237. };
  1238. }
  1239. function isComponent(tag, props, context) {
  1240. const options = context.options;
  1241. if (options.isCustomElement(tag)) {
  1242. return false;
  1243. }
  1244. if (tag === 'component' ||
  1245. /^[A-Z]/.test(tag) ||
  1246. isCoreComponent(tag) ||
  1247. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  1248. (options.isNativeTag && !options.isNativeTag(tag))) {
  1249. return true;
  1250. }
  1251. // at this point the tag should be a native tag, but check for potential "is"
  1252. // casting
  1253. for (let i = 0; i < props.length; i++) {
  1254. const p = props[i];
  1255. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  1256. if (p.name === 'is' && p.value) {
  1257. if (p.value.content.startsWith('vue:')) {
  1258. return true;
  1259. }
  1260. else if (checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  1261. return true;
  1262. }
  1263. }
  1264. }
  1265. else {
  1266. // directive
  1267. // v-is (TODO Deprecate)
  1268. if (p.name === 'is') {
  1269. return true;
  1270. }
  1271. else if (
  1272. // :is on plain element - only treat as component in compat mode
  1273. p.name === 'bind' &&
  1274. isStaticArgOf(p.arg, 'is') &&
  1275. true &&
  1276. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  1277. return true;
  1278. }
  1279. }
  1280. }
  1281. }
  1282. function parseAttributes(context, type) {
  1283. const props = [];
  1284. const attributeNames = new Set();
  1285. while (context.source.length > 0 &&
  1286. !startsWith(context.source, '>') &&
  1287. !startsWith(context.source, '/>')) {
  1288. if (startsWith(context.source, '/')) {
  1289. emitError(context, 22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */);
  1290. advanceBy(context, 1);
  1291. advanceSpaces(context);
  1292. continue;
  1293. }
  1294. if (type === 1 /* TagType.End */) {
  1295. emitError(context, 3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */);
  1296. }
  1297. const attr = parseAttribute(context, attributeNames);
  1298. // Trim whitespace between class
  1299. // https://github.com/vuejs/core/issues/4251
  1300. if (attr.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  1301. attr.value &&
  1302. attr.name === 'class') {
  1303. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  1304. }
  1305. if (type === 0 /* TagType.Start */) {
  1306. props.push(attr);
  1307. }
  1308. if (/^[^\t\r\n\f />]/.test(context.source)) {
  1309. emitError(context, 15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  1310. }
  1311. advanceSpaces(context);
  1312. }
  1313. return props;
  1314. }
  1315. function parseAttribute(context, nameSet) {
  1316. // Name.
  1317. const start = getCursor(context);
  1318. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  1319. const name = match[0];
  1320. if (nameSet.has(name)) {
  1321. emitError(context, 2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */);
  1322. }
  1323. nameSet.add(name);
  1324. if (name[0] === '=') {
  1325. emitError(context, 19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  1326. }
  1327. {
  1328. const pattern = /["'<]/g;
  1329. let m;
  1330. while ((m = pattern.exec(name))) {
  1331. emitError(context, 17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  1332. }
  1333. }
  1334. advanceBy(context, name.length);
  1335. // Value
  1336. let value = undefined;
  1337. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  1338. advanceSpaces(context);
  1339. advanceBy(context, 1);
  1340. advanceSpaces(context);
  1341. value = parseAttributeValue(context);
  1342. if (!value) {
  1343. emitError(context, 13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */);
  1344. }
  1345. }
  1346. const loc = getSelection(context, start);
  1347. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  1348. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  1349. let isPropShorthand = startsWith(name, '.');
  1350. let dirName = match[1] ||
  1351. (isPropShorthand || startsWith(name, ':')
  1352. ? 'bind'
  1353. : startsWith(name, '@')
  1354. ? 'on'
  1355. : 'slot');
  1356. let arg;
  1357. if (match[2]) {
  1358. const isSlot = dirName === 'slot';
  1359. const startOffset = name.lastIndexOf(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, 27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  1367. content = content.slice(1);
  1368. }
  1369. else {
  1370. content = content.slice(1, content.length - 1);
  1371. }
  1372. }
  1373. else if (isSlot) {
  1374. // #1241 special case for v-slot: vuetify relies extensively on slot
  1375. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  1376. // supports such usage so we are keeping it consistent with 2.x.
  1377. content += match[3] || '';
  1378. }
  1379. arg = {
  1380. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  1381. content,
  1382. isStatic,
  1383. constType: isStatic
  1384. ? 3 /* ConstantTypes.CAN_STRINGIFY */
  1385. : 0 /* ConstantTypes.NOT_CONSTANT */,
  1386. loc
  1387. };
  1388. }
  1389. if (value && value.isQuoted) {
  1390. const valueLoc = value.loc;
  1391. valueLoc.start.offset++;
  1392. valueLoc.start.column++;
  1393. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  1394. valueLoc.source = valueLoc.source.slice(1, -1);
  1395. }
  1396. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  1397. if (isPropShorthand)
  1398. modifiers.push('prop');
  1399. // 2.x compat v-bind:foo.sync -> v-model:foo
  1400. if (dirName === 'bind' && arg) {
  1401. if (modifiers.includes('sync') &&
  1402. checkCompatEnabled("COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */, context, loc, arg.loc.source)) {
  1403. dirName = 'model';
  1404. modifiers.splice(modifiers.indexOf('sync'), 1);
  1405. }
  1406. }
  1407. return {
  1408. type: 7 /* NodeTypes.DIRECTIVE */,
  1409. name: dirName,
  1410. exp: value && {
  1411. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  1412. content: value.content,
  1413. isStatic: false,
  1414. // Treat as non-constant by default. This can be potentially set to
  1415. // other values by `transformExpression` to make it eligible for hoisting.
  1416. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  1417. loc: value.loc
  1418. },
  1419. arg,
  1420. modifiers,
  1421. loc
  1422. };
  1423. }
  1424. // missing directive name or illegal directive name
  1425. if (!context.inVPre && startsWith(name, 'v-')) {
  1426. emitError(context, 26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */);
  1427. }
  1428. return {
  1429. type: 6 /* NodeTypes.ATTRIBUTE */,
  1430. name,
  1431. value: value && {
  1432. type: 2 /* NodeTypes.TEXT */,
  1433. content: value.content,
  1434. loc: value.loc
  1435. },
  1436. loc
  1437. };
  1438. }
  1439. function parseAttributeValue(context) {
  1440. const start = getCursor(context);
  1441. let content;
  1442. const quote = context.source[0];
  1443. const isQuoted = quote === `"` || quote === `'`;
  1444. if (isQuoted) {
  1445. // Quoted value.
  1446. advanceBy(context, 1);
  1447. const endIndex = context.source.indexOf(quote);
  1448. if (endIndex === -1) {
  1449. content = parseTextData(context, context.source.length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  1450. }
  1451. else {
  1452. content = parseTextData(context, endIndex, 4 /* TextModes.ATTRIBUTE_VALUE */);
  1453. advanceBy(context, 1);
  1454. }
  1455. }
  1456. else {
  1457. // Unquoted
  1458. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  1459. if (!match) {
  1460. return undefined;
  1461. }
  1462. const unexpectedChars = /["'<=`]/g;
  1463. let m;
  1464. while ((m = unexpectedChars.exec(match[0]))) {
  1465. emitError(context, 18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  1466. }
  1467. content = parseTextData(context, match[0].length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  1468. }
  1469. return { content, isQuoted, loc: getSelection(context, start) };
  1470. }
  1471. function parseInterpolation(context, mode) {
  1472. const [open, close] = context.options.delimiters;
  1473. const closeIndex = context.source.indexOf(close, open.length);
  1474. if (closeIndex === -1) {
  1475. emitError(context, 25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */);
  1476. return undefined;
  1477. }
  1478. const start = getCursor(context);
  1479. advanceBy(context, open.length);
  1480. const innerStart = getCursor(context);
  1481. const innerEnd = getCursor(context);
  1482. const rawContentLength = closeIndex - open.length;
  1483. const rawContent = context.source.slice(0, rawContentLength);
  1484. const preTrimContent = parseTextData(context, rawContentLength, mode);
  1485. const content = preTrimContent.trim();
  1486. const startOffset = preTrimContent.indexOf(content);
  1487. if (startOffset > 0) {
  1488. advancePositionWithMutation(innerStart, rawContent, startOffset);
  1489. }
  1490. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  1491. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  1492. advanceBy(context, close.length);
  1493. return {
  1494. type: 5 /* NodeTypes.INTERPOLATION */,
  1495. content: {
  1496. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  1497. isStatic: false,
  1498. // Set `isConstant` to false by default and will decide in transformExpression
  1499. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  1500. content,
  1501. loc: getSelection(context, innerStart, innerEnd)
  1502. },
  1503. loc: getSelection(context, start)
  1504. };
  1505. }
  1506. function parseText(context, mode) {
  1507. const endTokens = mode === 3 /* TextModes.CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  1508. let endIndex = context.source.length;
  1509. for (let i = 0; i < endTokens.length; i++) {
  1510. const index = context.source.indexOf(endTokens[i], 1);
  1511. if (index !== -1 && endIndex > index) {
  1512. endIndex = index;
  1513. }
  1514. }
  1515. const start = getCursor(context);
  1516. const content = parseTextData(context, endIndex, mode);
  1517. return {
  1518. type: 2 /* NodeTypes.TEXT */,
  1519. content,
  1520. loc: getSelection(context, start)
  1521. };
  1522. }
  1523. /**
  1524. * Get text data with a given length from the current location.
  1525. * This translates HTML entities in the text data.
  1526. */
  1527. function parseTextData(context, length, mode) {
  1528. const rawText = context.source.slice(0, length);
  1529. advanceBy(context, length);
  1530. if (mode === 2 /* TextModes.RAWTEXT */ ||
  1531. mode === 3 /* TextModes.CDATA */ ||
  1532. !rawText.includes('&')) {
  1533. return rawText;
  1534. }
  1535. else {
  1536. // DATA or RCDATA containing "&"". Entity decoding required.
  1537. return context.options.decodeEntities(rawText, mode === 4 /* TextModes.ATTRIBUTE_VALUE */);
  1538. }
  1539. }
  1540. function getCursor(context) {
  1541. const { column, line, offset } = context;
  1542. return { column, line, offset };
  1543. }
  1544. function getSelection(context, start, end) {
  1545. end = end || getCursor(context);
  1546. return {
  1547. start,
  1548. end,
  1549. source: context.originalSource.slice(start.offset, end.offset)
  1550. };
  1551. }
  1552. function last(xs) {
  1553. return xs[xs.length - 1];
  1554. }
  1555. function startsWith(source, searchString) {
  1556. return source.startsWith(searchString);
  1557. }
  1558. function advanceBy(context, numberOfCharacters) {
  1559. const { source } = context;
  1560. advancePositionWithMutation(context, source, numberOfCharacters);
  1561. context.source = source.slice(numberOfCharacters);
  1562. }
  1563. function advanceSpaces(context) {
  1564. const match = /^[\t\r\n\f ]+/.exec(context.source);
  1565. if (match) {
  1566. advanceBy(context, match[0].length);
  1567. }
  1568. }
  1569. function getNewPosition(context, start, numberOfCharacters) {
  1570. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  1571. }
  1572. function emitError(context, code, offset, loc = getCursor(context)) {
  1573. if (offset) {
  1574. loc.offset += offset;
  1575. loc.column += offset;
  1576. }
  1577. context.options.onError(createCompilerError(code, {
  1578. start: loc,
  1579. end: loc,
  1580. source: ''
  1581. }));
  1582. }
  1583. function isEnd(context, mode, ancestors) {
  1584. const s = context.source;
  1585. switch (mode) {
  1586. case 0 /* TextModes.DATA */:
  1587. if (startsWith(s, '</')) {
  1588. // TODO: probably bad performance
  1589. for (let i = ancestors.length - 1; i >= 0; --i) {
  1590. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  1591. return true;
  1592. }
  1593. }
  1594. }
  1595. break;
  1596. case 1 /* TextModes.RCDATA */:
  1597. case 2 /* TextModes.RAWTEXT */: {
  1598. const parent = last(ancestors);
  1599. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  1600. return true;
  1601. }
  1602. break;
  1603. }
  1604. case 3 /* TextModes.CDATA */:
  1605. if (startsWith(s, ']]>')) {
  1606. return true;
  1607. }
  1608. break;
  1609. }
  1610. return !s;
  1611. }
  1612. function startsWithEndTagOpen(source, tag) {
  1613. return (startsWith(source, '</') &&
  1614. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  1615. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  1616. }
  1617. function hoistStatic(root, context) {
  1618. walk(root, context,
  1619. // Root node is unfortunately non-hoistable due to potential parent
  1620. // fallthrough attributes.
  1621. isSingleElementRoot(root, root.children[0]));
  1622. }
  1623. function isSingleElementRoot(root, child) {
  1624. const { children } = root;
  1625. return (children.length === 1 &&
  1626. child.type === 1 /* NodeTypes.ELEMENT */ &&
  1627. !isSlotOutlet(child));
  1628. }
  1629. function walk(node, context, doNotHoistNode = false) {
  1630. const { children } = node;
  1631. const originalCount = children.length;
  1632. let hoistedCount = 0;
  1633. for (let i = 0; i < children.length; i++) {
  1634. const child = children[i];
  1635. // only plain elements & text calls are eligible for hoisting.
  1636. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  1637. child.tagType === 0 /* ElementTypes.ELEMENT */) {
  1638. const constantType = doNotHoistNode
  1639. ? 0 /* ConstantTypes.NOT_CONSTANT */
  1640. : getConstantType(child, context);
  1641. if (constantType > 0 /* ConstantTypes.NOT_CONSTANT */) {
  1642. if (constantType >= 2 /* ConstantTypes.CAN_HOIST */) {
  1643. child.codegenNode.patchFlag =
  1644. -1 /* PatchFlags.HOISTED */ + (``);
  1645. child.codegenNode = context.hoist(child.codegenNode);
  1646. hoistedCount++;
  1647. continue;
  1648. }
  1649. }
  1650. else {
  1651. // node may contain dynamic children, but its props may be eligible for
  1652. // hoisting.
  1653. const codegenNode = child.codegenNode;
  1654. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  1655. const flag = getPatchFlag(codegenNode);
  1656. if ((!flag ||
  1657. flag === 512 /* PatchFlags.NEED_PATCH */ ||
  1658. flag === 1 /* PatchFlags.TEXT */) &&
  1659. getGeneratedPropsConstantType(child, context) >=
  1660. 2 /* ConstantTypes.CAN_HOIST */) {
  1661. const props = getNodeProps(child);
  1662. if (props) {
  1663. codegenNode.props = context.hoist(props);
  1664. }
  1665. }
  1666. if (codegenNode.dynamicProps) {
  1667. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  1668. }
  1669. }
  1670. }
  1671. }
  1672. // walk further
  1673. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  1674. const isComponent = child.tagType === 1 /* ElementTypes.COMPONENT */;
  1675. if (isComponent) {
  1676. context.scopes.vSlot++;
  1677. }
  1678. walk(child, context);
  1679. if (isComponent) {
  1680. context.scopes.vSlot--;
  1681. }
  1682. }
  1683. else if (child.type === 11 /* NodeTypes.FOR */) {
  1684. // Do not hoist v-for single child because it has to be a block
  1685. walk(child, context, child.children.length === 1);
  1686. }
  1687. else if (child.type === 9 /* NodeTypes.IF */) {
  1688. for (let i = 0; i < child.branches.length; i++) {
  1689. // Do not hoist v-if single child because it has to be a block
  1690. walk(child.branches[i], context, child.branches[i].children.length === 1);
  1691. }
  1692. }
  1693. }
  1694. if (hoistedCount && context.transformHoist) {
  1695. context.transformHoist(children, context, node);
  1696. }
  1697. // all children were hoisted - the entire children array is hoistable.
  1698. if (hoistedCount &&
  1699. hoistedCount === originalCount &&
  1700. node.type === 1 /* NodeTypes.ELEMENT */ &&
  1701. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  1702. node.codegenNode &&
  1703. node.codegenNode.type === 13 /* NodeTypes.VNODE_CALL */ &&
  1704. shared.isArray(node.codegenNode.children)) {
  1705. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  1706. }
  1707. }
  1708. function getConstantType(node, context) {
  1709. const { constantCache } = context;
  1710. switch (node.type) {
  1711. case 1 /* NodeTypes.ELEMENT */:
  1712. if (node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  1713. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1714. }
  1715. const cached = constantCache.get(node);
  1716. if (cached !== undefined) {
  1717. return cached;
  1718. }
  1719. const codegenNode = node.codegenNode;
  1720. if (codegenNode.type !== 13 /* NodeTypes.VNODE_CALL */) {
  1721. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1722. }
  1723. if (codegenNode.isBlock &&
  1724. node.tag !== 'svg' &&
  1725. node.tag !== 'foreignObject') {
  1726. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1727. }
  1728. const flag = getPatchFlag(codegenNode);
  1729. if (!flag) {
  1730. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  1731. // Element itself has no patch flag. However we still need to check:
  1732. // 1. Even for a node with no patch flag, it is possible for it to contain
  1733. // non-hoistable expressions that refers to scope variables, e.g. compiler
  1734. // injected keys or cached event handlers. Therefore we need to always
  1735. // check the codegenNode's props to be sure.
  1736. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  1737. if (generatedPropsType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1738. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1739. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1740. }
  1741. if (generatedPropsType < returnType) {
  1742. returnType = generatedPropsType;
  1743. }
  1744. // 2. its children.
  1745. for (let i = 0; i < node.children.length; i++) {
  1746. const childType = getConstantType(node.children[i], context);
  1747. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1748. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1749. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1750. }
  1751. if (childType < returnType) {
  1752. returnType = childType;
  1753. }
  1754. }
  1755. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  1756. // type, check if any of the props can cause the type to be lowered
  1757. // we can skip can_patch because it's guaranteed by the absence of a
  1758. // patchFlag.
  1759. if (returnType > 1 /* ConstantTypes.CAN_SKIP_PATCH */) {
  1760. for (let i = 0; i < node.props.length; i++) {
  1761. const p = node.props[i];
  1762. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind' && p.exp) {
  1763. const expType = getConstantType(p.exp, context);
  1764. if (expType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1765. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1766. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1767. }
  1768. if (expType < returnType) {
  1769. returnType = expType;
  1770. }
  1771. }
  1772. }
  1773. }
  1774. // only svg/foreignObject could be block here, however if they are
  1775. // static then they don't need to be blocks since there will be no
  1776. // nested updates.
  1777. if (codegenNode.isBlock) {
  1778. // except set custom directives.
  1779. for (let i = 0; i < node.props.length; i++) {
  1780. const p = node.props[i];
  1781. if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  1782. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1783. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1784. }
  1785. }
  1786. context.removeHelper(OPEN_BLOCK);
  1787. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  1788. codegenNode.isBlock = false;
  1789. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  1790. }
  1791. constantCache.set(node, returnType);
  1792. return returnType;
  1793. }
  1794. else {
  1795. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  1796. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1797. }
  1798. case 2 /* NodeTypes.TEXT */:
  1799. case 3 /* NodeTypes.COMMENT */:
  1800. return 3 /* ConstantTypes.CAN_STRINGIFY */;
  1801. case 9 /* NodeTypes.IF */:
  1802. case 11 /* NodeTypes.FOR */:
  1803. case 10 /* NodeTypes.IF_BRANCH */:
  1804. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1805. case 5 /* NodeTypes.INTERPOLATION */:
  1806. case 12 /* NodeTypes.TEXT_CALL */:
  1807. return getConstantType(node.content, context);
  1808. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  1809. return node.constType;
  1810. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  1811. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  1812. for (let i = 0; i < node.children.length; i++) {
  1813. const child = node.children[i];
  1814. if (shared.isString(child) || shared.isSymbol(child)) {
  1815. continue;
  1816. }
  1817. const childType = getConstantType(child, context);
  1818. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1819. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1820. }
  1821. else if (childType < returnType) {
  1822. returnType = childType;
  1823. }
  1824. }
  1825. return returnType;
  1826. default:
  1827. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1828. }
  1829. }
  1830. const allowHoistedHelperSet = new Set([
  1831. NORMALIZE_CLASS,
  1832. NORMALIZE_STYLE,
  1833. NORMALIZE_PROPS,
  1834. GUARD_REACTIVE_PROPS
  1835. ]);
  1836. function getConstantTypeOfHelperCall(value, context) {
  1837. if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ &&
  1838. !shared.isString(value.callee) &&
  1839. allowHoistedHelperSet.has(value.callee)) {
  1840. const arg = value.arguments[0];
  1841. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  1842. return getConstantType(arg, context);
  1843. }
  1844. else if (arg.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  1845. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  1846. return getConstantTypeOfHelperCall(arg, context);
  1847. }
  1848. }
  1849. return 0 /* ConstantTypes.NOT_CONSTANT */;
  1850. }
  1851. function getGeneratedPropsConstantType(node, context) {
  1852. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  1853. const props = getNodeProps(node);
  1854. if (props && props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  1855. const { properties } = props;
  1856. for (let i = 0; i < properties.length; i++) {
  1857. const { key, value } = properties[i];
  1858. const keyType = getConstantType(key, context);
  1859. if (keyType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1860. return keyType;
  1861. }
  1862. if (keyType < returnType) {
  1863. returnType = keyType;
  1864. }
  1865. let valueType;
  1866. if (value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  1867. valueType = getConstantType(value, context);
  1868. }
  1869. else if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  1870. // some helper calls can be hoisted,
  1871. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  1872. // in this case we need to respect the ConstantType of the helper's arguments
  1873. valueType = getConstantTypeOfHelperCall(value, context);
  1874. }
  1875. else {
  1876. valueType = 0 /* ConstantTypes.NOT_CONSTANT */;
  1877. }
  1878. if (valueType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  1879. return valueType;
  1880. }
  1881. if (valueType < returnType) {
  1882. returnType = valueType;
  1883. }
  1884. }
  1885. }
  1886. return returnType;
  1887. }
  1888. function getNodeProps(node) {
  1889. const codegenNode = node.codegenNode;
  1890. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  1891. return codegenNode.props;
  1892. }
  1893. }
  1894. function getPatchFlag(node) {
  1895. const flag = node.patchFlag;
  1896. return flag ? parseInt(flag, 10) : undefined;
  1897. }
  1898. function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = shared.NOOP, isCustomElement = shared.NOOP, expressionPlugins = [], scopeId = null, slotted = true, ssr = false, inSSR = false, ssrCssVars = ``, bindingMetadata = shared.EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError, onWarn = defaultOnWarn, compatConfig }) {
  1899. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  1900. const context = {
  1901. // options
  1902. selfName: nameMatch && shared.capitalize(shared.camelize(nameMatch[1])),
  1903. prefixIdentifiers,
  1904. hoistStatic,
  1905. cacheHandlers,
  1906. nodeTransforms,
  1907. directiveTransforms,
  1908. transformHoist,
  1909. isBuiltInComponent,
  1910. isCustomElement,
  1911. expressionPlugins,
  1912. scopeId,
  1913. slotted,
  1914. ssr,
  1915. inSSR,
  1916. ssrCssVars,
  1917. bindingMetadata,
  1918. inline,
  1919. isTS,
  1920. onError,
  1921. onWarn,
  1922. compatConfig,
  1923. // state
  1924. root,
  1925. helpers: new Map(),
  1926. components: new Set(),
  1927. directives: new Set(),
  1928. hoists: [],
  1929. imports: [],
  1930. constantCache: new Map(),
  1931. temps: 0,
  1932. cached: 0,
  1933. identifiers: Object.create(null),
  1934. scopes: {
  1935. vFor: 0,
  1936. vSlot: 0,
  1937. vPre: 0,
  1938. vOnce: 0
  1939. },
  1940. parent: null,
  1941. currentNode: root,
  1942. childIndex: 0,
  1943. inVOnce: false,
  1944. // methods
  1945. helper(name) {
  1946. const count = context.helpers.get(name) || 0;
  1947. context.helpers.set(name, count + 1);
  1948. return name;
  1949. },
  1950. removeHelper(name) {
  1951. const count = context.helpers.get(name);
  1952. if (count) {
  1953. const currentCount = count - 1;
  1954. if (!currentCount) {
  1955. context.helpers.delete(name);
  1956. }
  1957. else {
  1958. context.helpers.set(name, currentCount);
  1959. }
  1960. }
  1961. },
  1962. helperString(name) {
  1963. return `_${helperNameMap[context.helper(name)]}`;
  1964. },
  1965. replaceNode(node) {
  1966. context.parent.children[context.childIndex] = context.currentNode = node;
  1967. },
  1968. removeNode(node) {
  1969. const list = context.parent.children;
  1970. const removalIndex = node
  1971. ? list.indexOf(node)
  1972. : context.currentNode
  1973. ? context.childIndex
  1974. : -1;
  1975. if (!node || node === context.currentNode) {
  1976. // current node removed
  1977. context.currentNode = null;
  1978. context.onNodeRemoved();
  1979. }
  1980. else {
  1981. // sibling node removed
  1982. if (context.childIndex > removalIndex) {
  1983. context.childIndex--;
  1984. context.onNodeRemoved();
  1985. }
  1986. }
  1987. context.parent.children.splice(removalIndex, 1);
  1988. },
  1989. onNodeRemoved: () => { },
  1990. addIdentifiers(exp) {
  1991. // identifier tracking only happens in non-browser builds.
  1992. {
  1993. if (shared.isString(exp)) {
  1994. addId(exp);
  1995. }
  1996. else if (exp.identifiers) {
  1997. exp.identifiers.forEach(addId);
  1998. }
  1999. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  2000. addId(exp.content);
  2001. }
  2002. }
  2003. },
  2004. removeIdentifiers(exp) {
  2005. {
  2006. if (shared.isString(exp)) {
  2007. removeId(exp);
  2008. }
  2009. else if (exp.identifiers) {
  2010. exp.identifiers.forEach(removeId);
  2011. }
  2012. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  2013. removeId(exp.content);
  2014. }
  2015. }
  2016. },
  2017. hoist(exp) {
  2018. if (shared.isString(exp))
  2019. exp = createSimpleExpression(exp);
  2020. context.hoists.push(exp);
  2021. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* ConstantTypes.CAN_HOIST */);
  2022. identifier.hoisted = exp;
  2023. return identifier;
  2024. },
  2025. cache(exp, isVNode = false) {
  2026. return createCacheExpression(context.cached++, exp, isVNode);
  2027. }
  2028. };
  2029. {
  2030. context.filters = new Set();
  2031. }
  2032. function addId(id) {
  2033. const { identifiers } = context;
  2034. if (identifiers[id] === undefined) {
  2035. identifiers[id] = 0;
  2036. }
  2037. identifiers[id]++;
  2038. }
  2039. function removeId(id) {
  2040. context.identifiers[id]--;
  2041. }
  2042. return context;
  2043. }
  2044. function transform(root, options) {
  2045. const context = createTransformContext(root, options);
  2046. traverseNode(root, context);
  2047. if (options.hoistStatic) {
  2048. hoistStatic(root, context);
  2049. }
  2050. if (!options.ssr) {
  2051. createRootCodegen(root, context);
  2052. }
  2053. // finalize meta information
  2054. root.helpers = [...context.helpers.keys()];
  2055. root.components = [...context.components];
  2056. root.directives = [...context.directives];
  2057. root.imports = context.imports;
  2058. root.hoists = context.hoists;
  2059. root.temps = context.temps;
  2060. root.cached = context.cached;
  2061. {
  2062. root.filters = [...context.filters];
  2063. }
  2064. }
  2065. function createRootCodegen(root, context) {
  2066. const { helper } = context;
  2067. const { children } = root;
  2068. if (children.length === 1) {
  2069. const child = children[0];
  2070. // if the single child is an element, turn it into a block.
  2071. if (isSingleElementRoot(root, child) && child.codegenNode) {
  2072. // single element root is never hoisted so codegenNode will never be
  2073. // SimpleExpressionNode
  2074. const codegenNode = child.codegenNode;
  2075. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  2076. makeBlock(codegenNode, context);
  2077. }
  2078. root.codegenNode = codegenNode;
  2079. }
  2080. else {
  2081. // - single <slot/>, IfNode, ForNode: already blocks.
  2082. // - single text node: always patched.
  2083. // root codegen falls through via genNode()
  2084. root.codegenNode = child;
  2085. }
  2086. }
  2087. else if (children.length > 1) {
  2088. // root has multiple nodes - return a fragment block.
  2089. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  2090. shared.PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  2091. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (``), undefined, undefined, true, undefined, false /* isComponent */);
  2092. }
  2093. else ;
  2094. }
  2095. function traverseChildren(parent, context) {
  2096. let i = 0;
  2097. const nodeRemoved = () => {
  2098. i--;
  2099. };
  2100. for (; i < parent.children.length; i++) {
  2101. const child = parent.children[i];
  2102. if (shared.isString(child))
  2103. continue;
  2104. context.parent = parent;
  2105. context.childIndex = i;
  2106. context.onNodeRemoved = nodeRemoved;
  2107. traverseNode(child, context);
  2108. }
  2109. }
  2110. function traverseNode(node, context) {
  2111. context.currentNode = node;
  2112. // apply transform plugins
  2113. const { nodeTransforms } = context;
  2114. const exitFns = [];
  2115. for (let i = 0; i < nodeTransforms.length; i++) {
  2116. const onExit = nodeTransforms[i](node, context);
  2117. if (onExit) {
  2118. if (shared.isArray(onExit)) {
  2119. exitFns.push(...onExit);
  2120. }
  2121. else {
  2122. exitFns.push(onExit);
  2123. }
  2124. }
  2125. if (!context.currentNode) {
  2126. // node was removed
  2127. return;
  2128. }
  2129. else {
  2130. // node may have been replaced
  2131. node = context.currentNode;
  2132. }
  2133. }
  2134. switch (node.type) {
  2135. case 3 /* NodeTypes.COMMENT */:
  2136. if (!context.ssr) {
  2137. // inject import for the Comment symbol, which is needed for creating
  2138. // comment nodes with `createVNode`
  2139. context.helper(CREATE_COMMENT);
  2140. }
  2141. break;
  2142. case 5 /* NodeTypes.INTERPOLATION */:
  2143. // no need to traverse, but we need to inject toString helper
  2144. if (!context.ssr) {
  2145. context.helper(TO_DISPLAY_STRING);
  2146. }
  2147. break;
  2148. // for container types, further traverse downwards
  2149. case 9 /* NodeTypes.IF */:
  2150. for (let i = 0; i < node.branches.length; i++) {
  2151. traverseNode(node.branches[i], context);
  2152. }
  2153. break;
  2154. case 10 /* NodeTypes.IF_BRANCH */:
  2155. case 11 /* NodeTypes.FOR */:
  2156. case 1 /* NodeTypes.ELEMENT */:
  2157. case 0 /* NodeTypes.ROOT */:
  2158. traverseChildren(node, context);
  2159. break;
  2160. }
  2161. // exit transforms
  2162. context.currentNode = node;
  2163. let i = exitFns.length;
  2164. while (i--) {
  2165. exitFns[i]();
  2166. }
  2167. }
  2168. function createStructuralDirectiveTransform(name, fn) {
  2169. const matches = shared.isString(name)
  2170. ? (n) => n === name
  2171. : (n) => name.test(n);
  2172. return (node, context) => {
  2173. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  2174. const { props } = node;
  2175. // structural directive transforms are not concerned with slots
  2176. // as they are handled separately in vSlot.ts
  2177. if (node.tagType === 3 /* ElementTypes.TEMPLATE */ && props.some(isVSlot)) {
  2178. return;
  2179. }
  2180. const exitFns = [];
  2181. for (let i = 0; i < props.length; i++) {
  2182. const prop = props[i];
  2183. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ && matches(prop.name)) {
  2184. // structural directives are removed to avoid infinite recursion
  2185. // also we remove them *before* applying so that it can further
  2186. // traverse itself in case it moves the node around
  2187. props.splice(i, 1);
  2188. i--;
  2189. const onExit = fn(node, prop, context);
  2190. if (onExit)
  2191. exitFns.push(onExit);
  2192. }
  2193. }
  2194. return exitFns;
  2195. }
  2196. };
  2197. }
  2198. const PURE_ANNOTATION = `/*#__PURE__*/`;
  2199. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  2200. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap: sourceMap$1 = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssrRuntimeModuleName = 'vue/server-renderer', ssr = false, isTS = false, inSSR = false }) {
  2201. const context = {
  2202. mode,
  2203. prefixIdentifiers,
  2204. sourceMap: sourceMap$1,
  2205. filename,
  2206. scopeId,
  2207. optimizeImports,
  2208. runtimeGlobalName,
  2209. runtimeModuleName,
  2210. ssrRuntimeModuleName,
  2211. ssr,
  2212. isTS,
  2213. inSSR,
  2214. source: ast.loc.source,
  2215. code: ``,
  2216. column: 1,
  2217. line: 1,
  2218. offset: 0,
  2219. indentLevel: 0,
  2220. pure: false,
  2221. map: undefined,
  2222. helper(key) {
  2223. return `_${helperNameMap[key]}`;
  2224. },
  2225. push(code, node) {
  2226. context.code += code;
  2227. if (context.map) {
  2228. if (node) {
  2229. let name;
  2230. if (node.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !node.isStatic) {
  2231. const content = node.content.replace(/^_ctx\./, '');
  2232. if (content !== node.content && isSimpleIdentifier(content)) {
  2233. name = content;
  2234. }
  2235. }
  2236. addMapping(node.loc.start, name);
  2237. }
  2238. advancePositionWithMutation(context, code);
  2239. if (node && node.loc !== locStub) {
  2240. addMapping(node.loc.end);
  2241. }
  2242. }
  2243. },
  2244. indent() {
  2245. newline(++context.indentLevel);
  2246. },
  2247. deindent(withoutNewLine = false) {
  2248. if (withoutNewLine) {
  2249. --context.indentLevel;
  2250. }
  2251. else {
  2252. newline(--context.indentLevel);
  2253. }
  2254. },
  2255. newline() {
  2256. newline(context.indentLevel);
  2257. }
  2258. };
  2259. function newline(n) {
  2260. context.push('\n' + ` `.repeat(n));
  2261. }
  2262. function addMapping(loc, name) {
  2263. context.map.addMapping({
  2264. name,
  2265. source: context.filename,
  2266. original: {
  2267. line: loc.line,
  2268. column: loc.column - 1 // source-map column is 0 based
  2269. },
  2270. generated: {
  2271. line: context.line,
  2272. column: context.column - 1
  2273. }
  2274. });
  2275. }
  2276. if (sourceMap$1) {
  2277. // lazy require source-map implementation, only in non-browser builds
  2278. context.map = new sourceMap.SourceMapGenerator();
  2279. context.map.setSourceContent(filename, context.source);
  2280. }
  2281. return context;
  2282. }
  2283. function generate(ast, options = {}) {
  2284. const context = createCodegenContext(ast, options);
  2285. if (options.onContextCreated)
  2286. options.onContextCreated(context);
  2287. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  2288. const hasHelpers = ast.helpers.length > 0;
  2289. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  2290. const genScopeId = scopeId != null && mode === 'module';
  2291. const isSetupInlined = !!options.inline;
  2292. // preambles
  2293. // in setup() inline mode, the preamble is generated in a sub context
  2294. // and returned separately.
  2295. const preambleContext = isSetupInlined
  2296. ? createCodegenContext(ast, options)
  2297. : context;
  2298. if (mode === 'module') {
  2299. genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  2300. }
  2301. else {
  2302. genFunctionPreamble(ast, preambleContext);
  2303. }
  2304. // enter render function
  2305. const functionName = ssr ? `ssrRender` : `render`;
  2306. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  2307. if (options.bindingMetadata && !options.inline) {
  2308. // binding optimization args
  2309. args.push('$props', '$setup', '$data', '$options');
  2310. }
  2311. const signature = options.isTS
  2312. ? args.map(arg => `${arg}: any`).join(',')
  2313. : args.join(', ');
  2314. if (isSetupInlined) {
  2315. push(`(${signature}) => {`);
  2316. }
  2317. else {
  2318. push(`function ${functionName}(${signature}) {`);
  2319. }
  2320. indent();
  2321. if (useWithBlock) {
  2322. push(`with (_ctx) {`);
  2323. indent();
  2324. // function mode const declarations should be inside with block
  2325. // also they should be renamed to avoid collision with user properties
  2326. if (hasHelpers) {
  2327. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = _Vue`);
  2328. push(`\n`);
  2329. newline();
  2330. }
  2331. }
  2332. // generate asset resolution statements
  2333. if (ast.components.length) {
  2334. genAssets(ast.components, 'component', context);
  2335. if (ast.directives.length || ast.temps > 0) {
  2336. newline();
  2337. }
  2338. }
  2339. if (ast.directives.length) {
  2340. genAssets(ast.directives, 'directive', context);
  2341. if (ast.temps > 0) {
  2342. newline();
  2343. }
  2344. }
  2345. if (ast.filters && ast.filters.length) {
  2346. newline();
  2347. genAssets(ast.filters, 'filter', context);
  2348. newline();
  2349. }
  2350. if (ast.temps > 0) {
  2351. push(`let `);
  2352. for (let i = 0; i < ast.temps; i++) {
  2353. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  2354. }
  2355. }
  2356. if (ast.components.length || ast.directives.length || ast.temps) {
  2357. push(`\n`);
  2358. newline();
  2359. }
  2360. // generate the VNode tree expression
  2361. if (!ssr) {
  2362. push(`return `);
  2363. }
  2364. if (ast.codegenNode) {
  2365. genNode(ast.codegenNode, context);
  2366. }
  2367. else {
  2368. push(`null`);
  2369. }
  2370. if (useWithBlock) {
  2371. deindent();
  2372. push(`}`);
  2373. }
  2374. deindent();
  2375. push(`}`);
  2376. return {
  2377. ast,
  2378. code: context.code,
  2379. preamble: isSetupInlined ? preambleContext.code : ``,
  2380. // SourceMapGenerator does have toJSON() method but it's not in the types
  2381. map: context.map ? context.map.toJSON() : undefined
  2382. };
  2383. }
  2384. function genFunctionPreamble(ast, context) {
  2385. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  2386. const VueBinding = ssr
  2387. ? `require(${JSON.stringify(runtimeModuleName)})`
  2388. : runtimeGlobalName;
  2389. // Generate const declaration for helpers
  2390. // In prefix mode, we place the const declaration at top so it's done
  2391. // only once; But if we not prefixing, we place the declaration inside the
  2392. // with block so it doesn't incur the `in` check cost for every helper access.
  2393. if (ast.helpers.length > 0) {
  2394. if (prefixIdentifiers) {
  2395. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n`);
  2396. }
  2397. else {
  2398. // "with" mode.
  2399. // save Vue in a separate variable to avoid collision
  2400. push(`const _Vue = ${VueBinding}\n`);
  2401. // in "with" mode, helpers are declared inside the with block to avoid
  2402. // has check cost, but hoists are lifted out of the function - we need
  2403. // to provide the helper here.
  2404. if (ast.hoists.length) {
  2405. const staticHelpers = [
  2406. CREATE_VNODE,
  2407. CREATE_ELEMENT_VNODE,
  2408. CREATE_COMMENT,
  2409. CREATE_TEXT,
  2410. CREATE_STATIC
  2411. ]
  2412. .filter(helper => ast.helpers.includes(helper))
  2413. .map(aliasHelper)
  2414. .join(', ');
  2415. push(`const { ${staticHelpers} } = _Vue\n`);
  2416. }
  2417. }
  2418. }
  2419. // generate variables for ssr helpers
  2420. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  2421. // ssr guarantees prefixIdentifier: true
  2422. push(`const { ${ast.ssrHelpers
  2423. .map(aliasHelper)
  2424. .join(', ')} } = require("${ssrRuntimeModuleName}")\n`);
  2425. }
  2426. genHoists(ast.hoists, context);
  2427. newline();
  2428. push(`return `);
  2429. }
  2430. function genModulePreamble(ast, context, genScopeId, inline) {
  2431. const { push, newline, optimizeImports, runtimeModuleName, ssrRuntimeModuleName } = context;
  2432. if (genScopeId && ast.hoists.length) {
  2433. ast.helpers.push(PUSH_SCOPE_ID, POP_SCOPE_ID);
  2434. }
  2435. // generate import statements for helpers
  2436. if (ast.helpers.length) {
  2437. if (optimizeImports) {
  2438. // when bundled with webpack with code-split, calling an import binding
  2439. // as a function leads to it being wrapped with `Object(a.b)` or `(0,a.b)`,
  2440. // incurring both payload size increase and potential perf overhead.
  2441. // therefore we assign the imports to variables (which is a constant ~50b
  2442. // cost per-component instead of scaling with template size)
  2443. push(`import { ${ast.helpers
  2444. .map(s => helperNameMap[s])
  2445. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  2446. push(`\n// Binding optimization for webpack code-split\nconst ${ast.helpers
  2447. .map(s => `_${helperNameMap[s]} = ${helperNameMap[s]}`)
  2448. .join(', ')}\n`);
  2449. }
  2450. else {
  2451. push(`import { ${ast.helpers
  2452. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  2453. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  2454. }
  2455. }
  2456. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  2457. push(`import { ${ast.ssrHelpers
  2458. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  2459. .join(', ')} } from "${ssrRuntimeModuleName}"\n`);
  2460. }
  2461. if (ast.imports.length) {
  2462. genImports(ast.imports, context);
  2463. newline();
  2464. }
  2465. genHoists(ast.hoists, context);
  2466. newline();
  2467. if (!inline) {
  2468. push(`export `);
  2469. }
  2470. }
  2471. function genAssets(assets, type, { helper, push, newline, isTS }) {
  2472. const resolver = helper(type === 'filter'
  2473. ? RESOLVE_FILTER
  2474. : type === 'component'
  2475. ? RESOLVE_COMPONENT
  2476. : RESOLVE_DIRECTIVE);
  2477. for (let i = 0; i < assets.length; i++) {
  2478. let id = assets[i];
  2479. // potential component implicit self-reference inferred from SFC filename
  2480. const maybeSelfReference = id.endsWith('__self');
  2481. if (maybeSelfReference) {
  2482. id = id.slice(0, -6);
  2483. }
  2484. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  2485. if (i < assets.length - 1) {
  2486. newline();
  2487. }
  2488. }
  2489. }
  2490. function genHoists(hoists, context) {
  2491. if (!hoists.length) {
  2492. return;
  2493. }
  2494. context.pure = true;
  2495. const { push, newline, helper, scopeId, mode } = context;
  2496. const genScopeId = scopeId != null && mode !== 'function';
  2497. newline();
  2498. // generate inlined withScopeId helper
  2499. if (genScopeId) {
  2500. push(`const _withScopeId = n => (${helper(PUSH_SCOPE_ID)}("${scopeId}"),n=n(),${helper(POP_SCOPE_ID)}(),n)`);
  2501. newline();
  2502. }
  2503. for (let i = 0; i < hoists.length; i++) {
  2504. const exp = hoists[i];
  2505. if (exp) {
  2506. const needScopeIdWrapper = genScopeId && exp.type === 13 /* NodeTypes.VNODE_CALL */;
  2507. push(`const _hoisted_${i + 1} = ${needScopeIdWrapper ? `${PURE_ANNOTATION} _withScopeId(() => ` : ``}`);
  2508. genNode(exp, context);
  2509. if (needScopeIdWrapper) {
  2510. push(`)`);
  2511. }
  2512. newline();
  2513. }
  2514. }
  2515. context.pure = false;
  2516. }
  2517. function genImports(importsOptions, context) {
  2518. if (!importsOptions.length) {
  2519. return;
  2520. }
  2521. importsOptions.forEach(imports => {
  2522. context.push(`import `);
  2523. genNode(imports.exp, context);
  2524. context.push(` from '${imports.path}'`);
  2525. context.newline();
  2526. });
  2527. }
  2528. function isText$1(n) {
  2529. return (shared.isString(n) ||
  2530. n.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  2531. n.type === 2 /* NodeTypes.TEXT */ ||
  2532. n.type === 5 /* NodeTypes.INTERPOLATION */ ||
  2533. n.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
  2534. }
  2535. function genNodeListAsArray(nodes, context) {
  2536. const multilines = nodes.length > 3 ||
  2537. (nodes.some(n => shared.isArray(n) || !isText$1(n)));
  2538. context.push(`[`);
  2539. multilines && context.indent();
  2540. genNodeList(nodes, context, multilines);
  2541. multilines && context.deindent();
  2542. context.push(`]`);
  2543. }
  2544. function genNodeList(nodes, context, multilines = false, comma = true) {
  2545. const { push, newline } = context;
  2546. for (let i = 0; i < nodes.length; i++) {
  2547. const node = nodes[i];
  2548. if (shared.isString(node)) {
  2549. push(node);
  2550. }
  2551. else if (shared.isArray(node)) {
  2552. genNodeListAsArray(node, context);
  2553. }
  2554. else {
  2555. genNode(node, context);
  2556. }
  2557. if (i < nodes.length - 1) {
  2558. if (multilines) {
  2559. comma && push(',');
  2560. newline();
  2561. }
  2562. else {
  2563. comma && push(', ');
  2564. }
  2565. }
  2566. }
  2567. }
  2568. function genNode(node, context) {
  2569. if (shared.isString(node)) {
  2570. context.push(node);
  2571. return;
  2572. }
  2573. if (shared.isSymbol(node)) {
  2574. context.push(context.helper(node));
  2575. return;
  2576. }
  2577. switch (node.type) {
  2578. case 1 /* NodeTypes.ELEMENT */:
  2579. case 9 /* NodeTypes.IF */:
  2580. case 11 /* NodeTypes.FOR */:
  2581. genNode(node.codegenNode, context);
  2582. break;
  2583. case 2 /* NodeTypes.TEXT */:
  2584. genText(node, context);
  2585. break;
  2586. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  2587. genExpression(node, context);
  2588. break;
  2589. case 5 /* NodeTypes.INTERPOLATION */:
  2590. genInterpolation(node, context);
  2591. break;
  2592. case 12 /* NodeTypes.TEXT_CALL */:
  2593. genNode(node.codegenNode, context);
  2594. break;
  2595. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  2596. genCompoundExpression(node, context);
  2597. break;
  2598. case 3 /* NodeTypes.COMMENT */:
  2599. genComment(node, context);
  2600. break;
  2601. case 13 /* NodeTypes.VNODE_CALL */:
  2602. genVNodeCall(node, context);
  2603. break;
  2604. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  2605. genCallExpression(node, context);
  2606. break;
  2607. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  2608. genObjectExpression(node, context);
  2609. break;
  2610. case 17 /* NodeTypes.JS_ARRAY_EXPRESSION */:
  2611. genArrayExpression(node, context);
  2612. break;
  2613. case 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */:
  2614. genFunctionExpression(node, context);
  2615. break;
  2616. case 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */:
  2617. genConditionalExpression(node, context);
  2618. break;
  2619. case 20 /* NodeTypes.JS_CACHE_EXPRESSION */:
  2620. genCacheExpression(node, context);
  2621. break;
  2622. case 21 /* NodeTypes.JS_BLOCK_STATEMENT */:
  2623. genNodeList(node.body, context, true, false);
  2624. break;
  2625. // SSR only types
  2626. case 22 /* NodeTypes.JS_TEMPLATE_LITERAL */:
  2627. genTemplateLiteral(node, context);
  2628. break;
  2629. case 23 /* NodeTypes.JS_IF_STATEMENT */:
  2630. genIfStatement(node, context);
  2631. break;
  2632. case 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */:
  2633. genAssignmentExpression(node, context);
  2634. break;
  2635. case 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */:
  2636. genSequenceExpression(node, context);
  2637. break;
  2638. case 26 /* NodeTypes.JS_RETURN_STATEMENT */:
  2639. genReturnStatement(node, context);
  2640. break;
  2641. }
  2642. }
  2643. function genText(node, context) {
  2644. context.push(JSON.stringify(node.content), node);
  2645. }
  2646. function genExpression(node, context) {
  2647. const { content, isStatic } = node;
  2648. context.push(isStatic ? JSON.stringify(content) : content, node);
  2649. }
  2650. function genInterpolation(node, context) {
  2651. const { push, helper, pure } = context;
  2652. if (pure)
  2653. push(PURE_ANNOTATION);
  2654. push(`${helper(TO_DISPLAY_STRING)}(`);
  2655. genNode(node.content, context);
  2656. push(`)`);
  2657. }
  2658. function genCompoundExpression(node, context) {
  2659. for (let i = 0; i < node.children.length; i++) {
  2660. const child = node.children[i];
  2661. if (shared.isString(child)) {
  2662. context.push(child);
  2663. }
  2664. else {
  2665. genNode(child, context);
  2666. }
  2667. }
  2668. }
  2669. function genExpressionAsPropertyKey(node, context) {
  2670. const { push } = context;
  2671. if (node.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  2672. push(`[`);
  2673. genCompoundExpression(node, context);
  2674. push(`]`);
  2675. }
  2676. else if (node.isStatic) {
  2677. // only quote keys if necessary
  2678. const text = isSimpleIdentifier(node.content)
  2679. ? node.content
  2680. : JSON.stringify(node.content);
  2681. push(text, node);
  2682. }
  2683. else {
  2684. push(`[${node.content}]`, node);
  2685. }
  2686. }
  2687. function genComment(node, context) {
  2688. const { push, helper, pure } = context;
  2689. if (pure) {
  2690. push(PURE_ANNOTATION);
  2691. }
  2692. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  2693. }
  2694. function genVNodeCall(node, context) {
  2695. const { push, helper, pure } = context;
  2696. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  2697. if (directives) {
  2698. push(helper(WITH_DIRECTIVES) + `(`);
  2699. }
  2700. if (isBlock) {
  2701. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  2702. }
  2703. if (pure) {
  2704. push(PURE_ANNOTATION);
  2705. }
  2706. const callHelper = isBlock
  2707. ? getVNodeBlockHelper(context.inSSR, isComponent)
  2708. : getVNodeHelper(context.inSSR, isComponent);
  2709. push(helper(callHelper) + `(`, node);
  2710. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  2711. push(`)`);
  2712. if (isBlock) {
  2713. push(`)`);
  2714. }
  2715. if (directives) {
  2716. push(`, `);
  2717. genNode(directives, context);
  2718. push(`)`);
  2719. }
  2720. }
  2721. function genNullableArgs(args) {
  2722. let i = args.length;
  2723. while (i--) {
  2724. if (args[i] != null)
  2725. break;
  2726. }
  2727. return args.slice(0, i + 1).map(arg => arg || `null`);
  2728. }
  2729. // JavaScript
  2730. function genCallExpression(node, context) {
  2731. const { push, helper, pure } = context;
  2732. const callee = shared.isString(node.callee) ? node.callee : helper(node.callee);
  2733. if (pure) {
  2734. push(PURE_ANNOTATION);
  2735. }
  2736. push(callee + `(`, node);
  2737. genNodeList(node.arguments, context);
  2738. push(`)`);
  2739. }
  2740. function genObjectExpression(node, context) {
  2741. const { push, indent, deindent, newline } = context;
  2742. const { properties } = node;
  2743. if (!properties.length) {
  2744. push(`{}`, node);
  2745. return;
  2746. }
  2747. const multilines = properties.length > 1 ||
  2748. (properties.some(p => p.value.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */));
  2749. push(multilines ? `{` : `{ `);
  2750. multilines && indent();
  2751. for (let i = 0; i < properties.length; i++) {
  2752. const { key, value } = properties[i];
  2753. // key
  2754. genExpressionAsPropertyKey(key, context);
  2755. push(`: `);
  2756. // value
  2757. genNode(value, context);
  2758. if (i < properties.length - 1) {
  2759. // will only reach this if it's multilines
  2760. push(`,`);
  2761. newline();
  2762. }
  2763. }
  2764. multilines && deindent();
  2765. push(multilines ? `}` : ` }`);
  2766. }
  2767. function genArrayExpression(node, context) {
  2768. genNodeListAsArray(node.elements, context);
  2769. }
  2770. function genFunctionExpression(node, context) {
  2771. const { push, indent, deindent } = context;
  2772. const { params, returns, body, newline, isSlot } = node;
  2773. if (isSlot) {
  2774. // wrap slot functions with owner context
  2775. push(`_${helperNameMap[WITH_CTX]}(`);
  2776. }
  2777. push(`(`, node);
  2778. if (shared.isArray(params)) {
  2779. genNodeList(params, context);
  2780. }
  2781. else if (params) {
  2782. genNode(params, context);
  2783. }
  2784. push(`) => `);
  2785. if (newline || body) {
  2786. push(`{`);
  2787. indent();
  2788. }
  2789. if (returns) {
  2790. if (newline) {
  2791. push(`return `);
  2792. }
  2793. if (shared.isArray(returns)) {
  2794. genNodeListAsArray(returns, context);
  2795. }
  2796. else {
  2797. genNode(returns, context);
  2798. }
  2799. }
  2800. else if (body) {
  2801. genNode(body, context);
  2802. }
  2803. if (newline || body) {
  2804. deindent();
  2805. push(`}`);
  2806. }
  2807. if (isSlot) {
  2808. if (node.isNonScopedSlot) {
  2809. push(`, undefined, true`);
  2810. }
  2811. push(`)`);
  2812. }
  2813. }
  2814. function genConditionalExpression(node, context) {
  2815. const { test, consequent, alternate, newline: needNewline } = node;
  2816. const { push, indent, deindent, newline } = context;
  2817. if (test.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  2818. const needsParens = !isSimpleIdentifier(test.content);
  2819. needsParens && push(`(`);
  2820. genExpression(test, context);
  2821. needsParens && push(`)`);
  2822. }
  2823. else {
  2824. push(`(`);
  2825. genNode(test, context);
  2826. push(`)`);
  2827. }
  2828. needNewline && indent();
  2829. context.indentLevel++;
  2830. needNewline || push(` `);
  2831. push(`? `);
  2832. genNode(consequent, context);
  2833. context.indentLevel--;
  2834. needNewline && newline();
  2835. needNewline || push(` `);
  2836. push(`: `);
  2837. const isNested = alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */;
  2838. if (!isNested) {
  2839. context.indentLevel++;
  2840. }
  2841. genNode(alternate, context);
  2842. if (!isNested) {
  2843. context.indentLevel--;
  2844. }
  2845. needNewline && deindent(true /* without newline */);
  2846. }
  2847. function genCacheExpression(node, context) {
  2848. const { push, helper, indent, deindent, newline } = context;
  2849. push(`_cache[${node.index}] || (`);
  2850. if (node.isVNode) {
  2851. indent();
  2852. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  2853. newline();
  2854. }
  2855. push(`_cache[${node.index}] = `);
  2856. genNode(node.value, context);
  2857. if (node.isVNode) {
  2858. push(`,`);
  2859. newline();
  2860. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  2861. newline();
  2862. push(`_cache[${node.index}]`);
  2863. deindent();
  2864. }
  2865. push(`)`);
  2866. }
  2867. function genTemplateLiteral(node, context) {
  2868. const { push, indent, deindent } = context;
  2869. push('`');
  2870. const l = node.elements.length;
  2871. const multilines = l > 3;
  2872. for (let i = 0; i < l; i++) {
  2873. const e = node.elements[i];
  2874. if (shared.isString(e)) {
  2875. push(e.replace(/(`|\$|\\)/g, '\\$1'));
  2876. }
  2877. else {
  2878. push('${');
  2879. if (multilines)
  2880. indent();
  2881. genNode(e, context);
  2882. if (multilines)
  2883. deindent();
  2884. push('}');
  2885. }
  2886. }
  2887. push('`');
  2888. }
  2889. function genIfStatement(node, context) {
  2890. const { push, indent, deindent } = context;
  2891. const { test, consequent, alternate } = node;
  2892. push(`if (`);
  2893. genNode(test, context);
  2894. push(`) {`);
  2895. indent();
  2896. genNode(consequent, context);
  2897. deindent();
  2898. push(`}`);
  2899. if (alternate) {
  2900. push(` else `);
  2901. if (alternate.type === 23 /* NodeTypes.JS_IF_STATEMENT */) {
  2902. genIfStatement(alternate, context);
  2903. }
  2904. else {
  2905. push(`{`);
  2906. indent();
  2907. genNode(alternate, context);
  2908. deindent();
  2909. push(`}`);
  2910. }
  2911. }
  2912. }
  2913. function genAssignmentExpression(node, context) {
  2914. genNode(node.left, context);
  2915. context.push(` = `);
  2916. genNode(node.right, context);
  2917. }
  2918. function genSequenceExpression(node, context) {
  2919. context.push(`(`);
  2920. genNodeList(node.expressions, context);
  2921. context.push(`)`);
  2922. }
  2923. function genReturnStatement({ returns }, context) {
  2924. context.push(`return `);
  2925. if (shared.isArray(returns)) {
  2926. genNodeListAsArray(returns, context);
  2927. }
  2928. else {
  2929. genNode(returns, context);
  2930. }
  2931. }
  2932. function walkIdentifiers(root, onIdentifier, includeAll = false, parentStack = [], knownIds = Object.create(null)) {
  2933. const rootExp = root.type === 'Program' &&
  2934. root.body[0].type === 'ExpressionStatement' &&
  2935. root.body[0].expression;
  2936. estreeWalker.walk(root, {
  2937. enter(node, parent) {
  2938. parent && parentStack.push(parent);
  2939. if (parent &&
  2940. parent.type.startsWith('TS') &&
  2941. parent.type !== 'TSAsExpression' &&
  2942. parent.type !== 'TSNonNullExpression' &&
  2943. parent.type !== 'TSTypeAssertion') {
  2944. return this.skip();
  2945. }
  2946. if (node.type === 'Identifier') {
  2947. const isLocal = !!knownIds[node.name];
  2948. const isRefed = isReferencedIdentifier(node, parent, parentStack);
  2949. if (includeAll || (isRefed && !isLocal)) {
  2950. onIdentifier(node, parent, parentStack, isRefed, isLocal);
  2951. }
  2952. }
  2953. else if (node.type === 'ObjectProperty' &&
  2954. parent.type === 'ObjectPattern') {
  2955. node.inPattern = true;
  2956. }
  2957. else if (isFunctionType(node)) {
  2958. // walk function expressions and add its arguments to known identifiers
  2959. // so that we don't prefix them
  2960. walkFunctionParams(node, id => markScopeIdentifier(node, id, knownIds));
  2961. }
  2962. else if (node.type === 'BlockStatement') {
  2963. // #3445 record block-level local variables
  2964. walkBlockDeclarations(node, id => markScopeIdentifier(node, id, knownIds));
  2965. }
  2966. },
  2967. leave(node, parent) {
  2968. parent && parentStack.pop();
  2969. if (node !== rootExp && node.scopeIds) {
  2970. for (const id of node.scopeIds) {
  2971. knownIds[id]--;
  2972. if (knownIds[id] === 0) {
  2973. delete knownIds[id];
  2974. }
  2975. }
  2976. }
  2977. }
  2978. });
  2979. }
  2980. function isReferencedIdentifier(id, parent, parentStack) {
  2981. if (!parent) {
  2982. return true;
  2983. }
  2984. // is a special keyword but parsed as identifier
  2985. if (id.name === 'arguments') {
  2986. return false;
  2987. }
  2988. if (isReferenced(id, parent)) {
  2989. return true;
  2990. }
  2991. // babel's isReferenced check returns false for ids being assigned to, so we
  2992. // need to cover those cases here
  2993. switch (parent.type) {
  2994. case 'AssignmentExpression':
  2995. case 'AssignmentPattern':
  2996. return true;
  2997. case 'ObjectPattern':
  2998. case 'ArrayPattern':
  2999. return isInDestructureAssignment(parent, parentStack);
  3000. }
  3001. return false;
  3002. }
  3003. function isInDestructureAssignment(parent, parentStack) {
  3004. if (parent &&
  3005. (parent.type === 'ObjectProperty' || parent.type === 'ArrayPattern')) {
  3006. let i = parentStack.length;
  3007. while (i--) {
  3008. const p = parentStack[i];
  3009. if (p.type === 'AssignmentExpression') {
  3010. return true;
  3011. }
  3012. else if (p.type !== 'ObjectProperty' && !p.type.endsWith('Pattern')) {
  3013. break;
  3014. }
  3015. }
  3016. }
  3017. return false;
  3018. }
  3019. function walkFunctionParams(node, onIdent) {
  3020. for (const p of node.params) {
  3021. for (const id of extractIdentifiers(p)) {
  3022. onIdent(id);
  3023. }
  3024. }
  3025. }
  3026. function walkBlockDeclarations(block, onIdent) {
  3027. for (const stmt of block.body) {
  3028. if (stmt.type === 'VariableDeclaration') {
  3029. if (stmt.declare)
  3030. continue;
  3031. for (const decl of stmt.declarations) {
  3032. for (const id of extractIdentifiers(decl.id)) {
  3033. onIdent(id);
  3034. }
  3035. }
  3036. }
  3037. else if (stmt.type === 'FunctionDeclaration' ||
  3038. stmt.type === 'ClassDeclaration') {
  3039. if (stmt.declare || !stmt.id)
  3040. continue;
  3041. onIdent(stmt.id);
  3042. }
  3043. }
  3044. }
  3045. function extractIdentifiers(param, nodes = []) {
  3046. switch (param.type) {
  3047. case 'Identifier':
  3048. nodes.push(param);
  3049. break;
  3050. case 'MemberExpression':
  3051. let object = param;
  3052. while (object.type === 'MemberExpression') {
  3053. object = object.object;
  3054. }
  3055. nodes.push(object);
  3056. break;
  3057. case 'ObjectPattern':
  3058. for (const prop of param.properties) {
  3059. if (prop.type === 'RestElement') {
  3060. extractIdentifiers(prop.argument, nodes);
  3061. }
  3062. else {
  3063. extractIdentifiers(prop.value, nodes);
  3064. }
  3065. }
  3066. break;
  3067. case 'ArrayPattern':
  3068. param.elements.forEach(element => {
  3069. if (element)
  3070. extractIdentifiers(element, nodes);
  3071. });
  3072. break;
  3073. case 'RestElement':
  3074. extractIdentifiers(param.argument, nodes);
  3075. break;
  3076. case 'AssignmentPattern':
  3077. extractIdentifiers(param.left, nodes);
  3078. break;
  3079. }
  3080. return nodes;
  3081. }
  3082. function markScopeIdentifier(node, child, knownIds) {
  3083. const { name } = child;
  3084. if (node.scopeIds && node.scopeIds.has(name)) {
  3085. return;
  3086. }
  3087. if (name in knownIds) {
  3088. knownIds[name]++;
  3089. }
  3090. else {
  3091. knownIds[name] = 1;
  3092. }
  3093. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  3094. }
  3095. const isFunctionType = (node) => {
  3096. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  3097. };
  3098. const isStaticProperty = (node) => node &&
  3099. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  3100. !node.computed;
  3101. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  3102. /**
  3103. * Copied from https://github.com/babel/babel/blob/main/packages/babel-types/src/validators/isReferenced.ts
  3104. * To avoid runtime dependency on @babel/types (which includes process references)
  3105. * This file should not change very often in babel but we may need to keep it
  3106. * up-to-date from time to time.
  3107. *
  3108. * https://github.com/babel/babel/blob/main/LICENSE
  3109. *
  3110. */
  3111. function isReferenced(node, parent, grandparent) {
  3112. switch (parent.type) {
  3113. // yes: PARENT[NODE]
  3114. // yes: NODE.child
  3115. // no: parent.NODE
  3116. case 'MemberExpression':
  3117. case 'OptionalMemberExpression':
  3118. if (parent.property === node) {
  3119. return !!parent.computed;
  3120. }
  3121. return parent.object === node;
  3122. case 'JSXMemberExpression':
  3123. return parent.object === node;
  3124. // no: let NODE = init;
  3125. // yes: let id = NODE;
  3126. case 'VariableDeclarator':
  3127. return parent.init === node;
  3128. // yes: () => NODE
  3129. // no: (NODE) => {}
  3130. case 'ArrowFunctionExpression':
  3131. return parent.body === node;
  3132. // no: class { #NODE; }
  3133. // no: class { get #NODE() {} }
  3134. // no: class { #NODE() {} }
  3135. // no: class { fn() { return this.#NODE; } }
  3136. case 'PrivateName':
  3137. return false;
  3138. // no: class { NODE() {} }
  3139. // yes: class { [NODE]() {} }
  3140. // no: class { foo(NODE) {} }
  3141. case 'ClassMethod':
  3142. case 'ClassPrivateMethod':
  3143. case 'ObjectMethod':
  3144. if (parent.key === node) {
  3145. return !!parent.computed;
  3146. }
  3147. return false;
  3148. // yes: { [NODE]: "" }
  3149. // no: { NODE: "" }
  3150. // depends: { NODE }
  3151. // depends: { key: NODE }
  3152. case 'ObjectProperty':
  3153. if (parent.key === node) {
  3154. return !!parent.computed;
  3155. }
  3156. // parent.value === node
  3157. return !grandparent || grandparent.type !== 'ObjectPattern';
  3158. // no: class { NODE = value; }
  3159. // yes: class { [NODE] = value; }
  3160. // yes: class { key = NODE; }
  3161. case 'ClassProperty':
  3162. if (parent.key === node) {
  3163. return !!parent.computed;
  3164. }
  3165. return true;
  3166. case 'ClassPrivateProperty':
  3167. return parent.key !== node;
  3168. // no: class NODE {}
  3169. // yes: class Foo extends NODE {}
  3170. case 'ClassDeclaration':
  3171. case 'ClassExpression':
  3172. return parent.superClass === node;
  3173. // yes: left = NODE;
  3174. // no: NODE = right;
  3175. case 'AssignmentExpression':
  3176. return parent.right === node;
  3177. // no: [NODE = foo] = [];
  3178. // yes: [foo = NODE] = [];
  3179. case 'AssignmentPattern':
  3180. return parent.right === node;
  3181. // no: NODE: for (;;) {}
  3182. case 'LabeledStatement':
  3183. return false;
  3184. // no: try {} catch (NODE) {}
  3185. case 'CatchClause':
  3186. return false;
  3187. // no: function foo(...NODE) {}
  3188. case 'RestElement':
  3189. return false;
  3190. case 'BreakStatement':
  3191. case 'ContinueStatement':
  3192. return false;
  3193. // no: function NODE() {}
  3194. // no: function foo(NODE) {}
  3195. case 'FunctionDeclaration':
  3196. case 'FunctionExpression':
  3197. return false;
  3198. // no: export NODE from "foo";
  3199. // no: export * as NODE from "foo";
  3200. case 'ExportNamespaceSpecifier':
  3201. case 'ExportDefaultSpecifier':
  3202. return false;
  3203. // no: export { foo as NODE };
  3204. // yes: export { NODE as foo };
  3205. // no: export { NODE as foo } from "foo";
  3206. case 'ExportSpecifier':
  3207. // @ts-expect-error
  3208. if (grandparent === null || grandparent === void 0 ? void 0 : grandparent.source) {
  3209. return false;
  3210. }
  3211. return parent.local === node;
  3212. // no: import NODE from "foo";
  3213. // no: import * as NODE from "foo";
  3214. // no: import { NODE as foo } from "foo";
  3215. // no: import { foo as NODE } from "foo";
  3216. // no: import NODE from "bar";
  3217. case 'ImportDefaultSpecifier':
  3218. case 'ImportNamespaceSpecifier':
  3219. case 'ImportSpecifier':
  3220. return false;
  3221. // no: import "foo" assert { NODE: "json" }
  3222. case 'ImportAttribute':
  3223. return false;
  3224. // no: <div NODE="foo" />
  3225. case 'JSXAttribute':
  3226. return false;
  3227. // no: [NODE] = [];
  3228. // no: ({ NODE }) = [];
  3229. case 'ObjectPattern':
  3230. case 'ArrayPattern':
  3231. return false;
  3232. // no: new.NODE
  3233. // no: NODE.target
  3234. case 'MetaProperty':
  3235. return false;
  3236. // yes: type X = { someProperty: NODE }
  3237. // no: type X = { NODE: OtherType }
  3238. case 'ObjectTypeProperty':
  3239. return parent.key !== node;
  3240. // yes: enum X { Foo = NODE }
  3241. // no: enum X { NODE }
  3242. case 'TSEnumMember':
  3243. return parent.id !== node;
  3244. // yes: { [NODE]: value }
  3245. // no: { NODE: value }
  3246. case 'TSPropertySignature':
  3247. if (parent.key === node) {
  3248. return !!parent.computed;
  3249. }
  3250. return true;
  3251. }
  3252. return true;
  3253. }
  3254. const isLiteralWhitelisted = /*#__PURE__*/ shared.makeMap('true,false,null,this');
  3255. const transformExpression = (node, context) => {
  3256. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  3257. node.content = processExpression(node.content, context);
  3258. }
  3259. else if (node.type === 1 /* NodeTypes.ELEMENT */) {
  3260. // handle directives on element
  3261. for (let i = 0; i < node.props.length; i++) {
  3262. const dir = node.props[i];
  3263. // do not process for v-on & v-for since they are special handled
  3264. if (dir.type === 7 /* NodeTypes.DIRECTIVE */ && dir.name !== 'for') {
  3265. const exp = dir.exp;
  3266. const arg = dir.arg;
  3267. // do not process exp if this is v-on:arg - we need special handling
  3268. // for wrapping inline statements.
  3269. if (exp &&
  3270. exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  3271. !(dir.name === 'on' && arg)) {
  3272. dir.exp = processExpression(exp, context,
  3273. // slot args must be processed as function params
  3274. dir.name === 'slot');
  3275. }
  3276. if (arg && arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !arg.isStatic) {
  3277. dir.arg = processExpression(arg, context);
  3278. }
  3279. }
  3280. }
  3281. }
  3282. };
  3283. // Important: since this function uses Node.js only dependencies, it should
  3284. // always be used with a leading !false check so that it can be
  3285. // tree-shaken from the browser build.
  3286. function processExpression(node, context,
  3287. // some expressions like v-slot props & v-for aliases should be parsed as
  3288. // function params
  3289. asParams = false,
  3290. // v-on handler values may contain multiple statements
  3291. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  3292. if (!context.prefixIdentifiers || !node.content.trim()) {
  3293. return node;
  3294. }
  3295. const { inline, bindingMetadata } = context;
  3296. const rewriteIdentifier = (raw, parent, id) => {
  3297. const type = shared.hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
  3298. if (inline) {
  3299. // x = y
  3300. const isAssignmentLVal = parent && parent.type === 'AssignmentExpression' && parent.left === id;
  3301. // x++
  3302. const isUpdateArg = parent && parent.type === 'UpdateExpression' && parent.argument === id;
  3303. // ({ x } = y)
  3304. const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
  3305. if (type === "setup-const" /* BindingTypes.SETUP_CONST */ ||
  3306. type === "setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */ ||
  3307. localVars[raw]) {
  3308. return raw;
  3309. }
  3310. else if (type === "setup-ref" /* BindingTypes.SETUP_REF */) {
  3311. return `${raw}.value`;
  3312. }
  3313. else if (type === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */) {
  3314. // const binding that may or may not be ref
  3315. // if it's not a ref, then assignments don't make sense -
  3316. // so we ignore the non-ref assignment case and generate code
  3317. // that assumes the value to be a ref for more efficiency
  3318. return isAssignmentLVal || isUpdateArg || isDestructureAssignment
  3319. ? `${raw}.value`
  3320. : `${context.helperString(UNREF)}(${raw})`;
  3321. }
  3322. else if (type === "setup-let" /* BindingTypes.SETUP_LET */) {
  3323. if (isAssignmentLVal) {
  3324. // let binding.
  3325. // this is a bit more tricky as we need to cover the case where
  3326. // let is a local non-ref value, and we need to replicate the
  3327. // right hand side value.
  3328. // x = y --> isRef(x) ? x.value = y : x = y
  3329. const { right: rVal, operator } = parent;
  3330. const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
  3331. const rExpString = stringifyExpression(processExpression(createSimpleExpression(rExp, false), context, false, false, knownIds));
  3332. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`;
  3333. }
  3334. else if (isUpdateArg) {
  3335. // make id replace parent in the code range so the raw update operator
  3336. // is removed
  3337. id.start = parent.start;
  3338. id.end = parent.end;
  3339. const { prefix: isPrefix, operator } = parent;
  3340. const prefix = isPrefix ? operator : ``;
  3341. const postfix = isPrefix ? `` : operator;
  3342. // let binding.
  3343. // x++ --> isRef(a) ? a.value++ : a++
  3344. return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore\n` : ``} ? ${prefix}${raw}.value${postfix} : ${prefix}${raw}${postfix}`;
  3345. }
  3346. else if (isDestructureAssignment) {
  3347. // TODO
  3348. // let binding in a destructure assignment - it's very tricky to
  3349. // handle both possible cases here without altering the original
  3350. // structure of the code, so we just assume it's not a ref here
  3351. // for now
  3352. return raw;
  3353. }
  3354. else {
  3355. return `${context.helperString(UNREF)}(${raw})`;
  3356. }
  3357. }
  3358. else if (type === "props" /* BindingTypes.PROPS */) {
  3359. // use __props which is generated by compileScript so in ts mode
  3360. // it gets correct type
  3361. return shared.genPropsAccessExp(raw);
  3362. }
  3363. else if (type === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  3364. // prop with a different local alias (from defineProps() destructure)
  3365. return shared.genPropsAccessExp(bindingMetadata.__propsAliases[raw]);
  3366. }
  3367. }
  3368. else {
  3369. if (type && type.startsWith('setup')) {
  3370. // setup bindings in non-inline mode
  3371. return `$setup.${raw}`;
  3372. }
  3373. else if (type === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  3374. return `$props['${bindingMetadata.__propsAliases[raw]}']`;
  3375. }
  3376. else if (type) {
  3377. return `$${type}.${raw}`;
  3378. }
  3379. }
  3380. // fallback to ctx
  3381. return `_ctx.${raw}`;
  3382. };
  3383. // fast path if expression is a simple identifier.
  3384. const rawExp = node.content;
  3385. // bail constant on parens (function invocation) and dot (member access)
  3386. const bailConstant = rawExp.indexOf(`(`) > -1 || rawExp.indexOf('.') > 0;
  3387. if (isSimpleIdentifier(rawExp)) {
  3388. const isScopeVarReference = context.identifiers[rawExp];
  3389. const isAllowedGlobal = shared.isGloballyWhitelisted(rawExp);
  3390. const isLiteral = isLiteralWhitelisted(rawExp);
  3391. if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
  3392. // const bindings exposed from setup can be skipped for patching but
  3393. // cannot be hoisted to module scope
  3394. if (bindingMetadata[node.content] === "setup-const" /* BindingTypes.SETUP_CONST */) {
  3395. node.constType = 1 /* ConstantTypes.CAN_SKIP_PATCH */;
  3396. }
  3397. node.content = rewriteIdentifier(rawExp);
  3398. }
  3399. else if (!isScopeVarReference) {
  3400. if (isLiteral) {
  3401. node.constType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  3402. }
  3403. else {
  3404. node.constType = 2 /* ConstantTypes.CAN_HOIST */;
  3405. }
  3406. }
  3407. return node;
  3408. }
  3409. let ast;
  3410. // exp needs to be parsed differently:
  3411. // 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
  3412. // exp, but make sure to pad with spaces for consistent ranges
  3413. // 2. Expressions: wrap with parens (for e.g. object expressions)
  3414. // 3. Function arguments (v-for, v-slot): place in a function argument position
  3415. const source = asRawStatements
  3416. ? ` ${rawExp} `
  3417. : `(${rawExp})${asParams ? `=>{}` : ``}`;
  3418. try {
  3419. ast = parser.parse(source, {
  3420. plugins: context.expressionPlugins
  3421. }).program;
  3422. }
  3423. catch (e) {
  3424. context.onError(createCompilerError(45 /* ErrorCodes.X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
  3425. return node;
  3426. }
  3427. const ids = [];
  3428. const parentStack = [];
  3429. const knownIds = Object.create(context.identifiers);
  3430. walkIdentifiers(ast, (node, parent, _, isReferenced, isLocal) => {
  3431. if (isStaticPropertyKey(node, parent)) {
  3432. return;
  3433. }
  3434. // v2 wrapped filter call
  3435. if (node.name.startsWith('_filter_')) {
  3436. return;
  3437. }
  3438. const needPrefix = isReferenced && canPrefix(node);
  3439. if (needPrefix && !isLocal) {
  3440. if (isStaticProperty(parent) && parent.shorthand) {
  3441. node.prefix = `${node.name}: `;
  3442. }
  3443. node.name = rewriteIdentifier(node.name, parent, node);
  3444. ids.push(node);
  3445. }
  3446. else {
  3447. // The identifier is considered constant unless it's pointing to a
  3448. // local scope variable (a v-for alias, or a v-slot prop)
  3449. if (!(needPrefix && isLocal) && !bailConstant) {
  3450. node.isConstant = true;
  3451. }
  3452. // also generate sub-expressions for other identifiers for better
  3453. // source map support. (except for property keys which are static)
  3454. ids.push(node);
  3455. }
  3456. }, true, // invoke on ALL identifiers
  3457. parentStack, knownIds);
  3458. // We break up the compound expression into an array of strings and sub
  3459. // expressions (for identifiers that have been prefixed). In codegen, if
  3460. // an ExpressionNode has the `.children` property, it will be used instead of
  3461. // `.content`.
  3462. const children = [];
  3463. ids.sort((a, b) => a.start - b.start);
  3464. ids.forEach((id, i) => {
  3465. // range is offset by -1 due to the wrapping parens when parsed
  3466. const start = id.start - 1;
  3467. const end = id.end - 1;
  3468. const last = ids[i - 1];
  3469. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  3470. if (leadingText.length || id.prefix) {
  3471. children.push(leadingText + (id.prefix || ``));
  3472. }
  3473. const source = rawExp.slice(start, end);
  3474. children.push(createSimpleExpression(id.name, false, {
  3475. source,
  3476. start: advancePositionWithClone(node.loc.start, source, start),
  3477. end: advancePositionWithClone(node.loc.start, source, end)
  3478. }, id.isConstant ? 3 /* ConstantTypes.CAN_STRINGIFY */ : 0 /* ConstantTypes.NOT_CONSTANT */));
  3479. if (i === ids.length - 1 && end < rawExp.length) {
  3480. children.push(rawExp.slice(end));
  3481. }
  3482. });
  3483. let ret;
  3484. if (children.length) {
  3485. ret = createCompoundExpression(children, node.loc);
  3486. }
  3487. else {
  3488. ret = node;
  3489. ret.constType = bailConstant
  3490. ? 0 /* ConstantTypes.NOT_CONSTANT */
  3491. : 3 /* ConstantTypes.CAN_STRINGIFY */;
  3492. }
  3493. ret.identifiers = Object.keys(knownIds);
  3494. return ret;
  3495. }
  3496. function canPrefix(id) {
  3497. // skip whitelisted globals
  3498. if (shared.isGloballyWhitelisted(id.name)) {
  3499. return false;
  3500. }
  3501. // special case for webpack compilation
  3502. if (id.name === 'require') {
  3503. return false;
  3504. }
  3505. return true;
  3506. }
  3507. function stringifyExpression(exp) {
  3508. if (shared.isString(exp)) {
  3509. return exp;
  3510. }
  3511. else if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  3512. return exp.content;
  3513. }
  3514. else {
  3515. return exp.children
  3516. .map(stringifyExpression)
  3517. .join('');
  3518. }
  3519. }
  3520. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  3521. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  3522. // #1587: We need to dynamically increment the key based on the current
  3523. // node's sibling nodes, since chained v-if/else branches are
  3524. // rendered at the same depth
  3525. const siblings = context.parent.children;
  3526. let i = siblings.indexOf(ifNode);
  3527. let key = 0;
  3528. while (i-- >= 0) {
  3529. const sibling = siblings[i];
  3530. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  3531. key += sibling.branches.length;
  3532. }
  3533. }
  3534. // Exit callback. Complete the codegenNode when all children have been
  3535. // transformed.
  3536. return () => {
  3537. if (isRoot) {
  3538. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  3539. }
  3540. else {
  3541. // attach this branch's codegen node to the v-if root.
  3542. const parentCondition = getParentCondition(ifNode.codegenNode);
  3543. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  3544. }
  3545. };
  3546. });
  3547. });
  3548. // target-agnostic transform used for both Client and SSR
  3549. function processIf(node, dir, context, processCodegen) {
  3550. if (dir.name !== 'else' &&
  3551. (!dir.exp || !dir.exp.content.trim())) {
  3552. const loc = dir.exp ? dir.exp.loc : node.loc;
  3553. context.onError(createCompilerError(28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */, dir.loc));
  3554. dir.exp = createSimpleExpression(`true`, false, loc);
  3555. }
  3556. if (context.prefixIdentifiers && dir.exp) {
  3557. // dir.exp can only be simple expression because vIf transform is applied
  3558. // before expression transform.
  3559. dir.exp = processExpression(dir.exp, context);
  3560. }
  3561. if (dir.name === 'if') {
  3562. const branch = createIfBranch(node, dir);
  3563. const ifNode = {
  3564. type: 9 /* NodeTypes.IF */,
  3565. loc: node.loc,
  3566. branches: [branch]
  3567. };
  3568. context.replaceNode(ifNode);
  3569. if (processCodegen) {
  3570. return processCodegen(ifNode, branch, true);
  3571. }
  3572. }
  3573. else {
  3574. // locate the adjacent v-if
  3575. const siblings = context.parent.children;
  3576. let i = siblings.indexOf(node);
  3577. while (i-- >= -1) {
  3578. const sibling = siblings[i];
  3579. if (sibling && sibling.type === 3 /* NodeTypes.COMMENT */) {
  3580. context.removeNode(sibling);
  3581. continue;
  3582. }
  3583. if (sibling &&
  3584. sibling.type === 2 /* NodeTypes.TEXT */ &&
  3585. !sibling.content.trim().length) {
  3586. context.removeNode(sibling);
  3587. continue;
  3588. }
  3589. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  3590. // Check if v-else was followed by v-else-if
  3591. if (dir.name === 'else-if' &&
  3592. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  3593. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  3594. }
  3595. // move the node to the if node's branches
  3596. context.removeNode();
  3597. const branch = createIfBranch(node, dir);
  3598. // check if user is forcing same key on different branches
  3599. {
  3600. const key = branch.userKey;
  3601. if (key) {
  3602. sibling.branches.forEach(({ userKey }) => {
  3603. if (isSameKey(userKey, key)) {
  3604. context.onError(createCompilerError(29 /* ErrorCodes.X_V_IF_SAME_KEY */, branch.userKey.loc));
  3605. }
  3606. });
  3607. }
  3608. }
  3609. sibling.branches.push(branch);
  3610. const onExit = processCodegen && processCodegen(sibling, branch, false);
  3611. // since the branch was removed, it will not be traversed.
  3612. // make sure to traverse here.
  3613. traverseNode(branch, context);
  3614. // call on exit
  3615. if (onExit)
  3616. onExit();
  3617. // make sure to reset currentNode after traversal to indicate this
  3618. // node has been removed.
  3619. context.currentNode = null;
  3620. }
  3621. else {
  3622. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  3623. }
  3624. break;
  3625. }
  3626. }
  3627. }
  3628. function createIfBranch(node, dir) {
  3629. const isTemplateIf = node.tagType === 3 /* ElementTypes.TEMPLATE */;
  3630. return {
  3631. type: 10 /* NodeTypes.IF_BRANCH */,
  3632. loc: node.loc,
  3633. condition: dir.name === 'else' ? undefined : dir.exp,
  3634. children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
  3635. userKey: findProp(node, `key`),
  3636. isTemplateIf
  3637. };
  3638. }
  3639. function createCodegenNodeForBranch(branch, keyIndex, context) {
  3640. if (branch.condition) {
  3641. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  3642. // make sure to pass in asBlock: true so that the comment node call
  3643. // closes the current block.
  3644. createCallExpression(context.helper(CREATE_COMMENT), [
  3645. '""',
  3646. 'true'
  3647. ]));
  3648. }
  3649. else {
  3650. return createChildrenCodegenNode(branch, keyIndex, context);
  3651. }
  3652. }
  3653. function createChildrenCodegenNode(branch, keyIndex, context) {
  3654. const { helper } = context;
  3655. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* ConstantTypes.CAN_HOIST */));
  3656. const { children } = branch;
  3657. const firstChild = children[0];
  3658. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* NodeTypes.ELEMENT */;
  3659. if (needFragmentWrapper) {
  3660. if (children.length === 1 && firstChild.type === 11 /* NodeTypes.FOR */) {
  3661. // optimize away nested fragments when child is a ForNode
  3662. const vnodeCall = firstChild.codegenNode;
  3663. injectProp(vnodeCall, keyProperty, context);
  3664. return vnodeCall;
  3665. }
  3666. else {
  3667. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  3668. shared.PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  3669. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (``), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  3670. }
  3671. }
  3672. else {
  3673. const ret = firstChild.codegenNode;
  3674. const vnodeCall = getMemoedVNodeCall(ret);
  3675. // Change createVNode to createBlock.
  3676. if (vnodeCall.type === 13 /* NodeTypes.VNODE_CALL */) {
  3677. makeBlock(vnodeCall, context);
  3678. }
  3679. // inject branch key
  3680. injectProp(vnodeCall, keyProperty, context);
  3681. return ret;
  3682. }
  3683. }
  3684. function isSameKey(a, b) {
  3685. if (!a || a.type !== b.type) {
  3686. return false;
  3687. }
  3688. if (a.type === 6 /* NodeTypes.ATTRIBUTE */) {
  3689. if (a.value.content !== b.value.content) {
  3690. return false;
  3691. }
  3692. }
  3693. else {
  3694. // directive
  3695. const exp = a.exp;
  3696. const branchExp = b.exp;
  3697. if (exp.type !== branchExp.type) {
  3698. return false;
  3699. }
  3700. if (exp.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  3701. exp.isStatic !== branchExp.isStatic ||
  3702. exp.content !== branchExp.content) {
  3703. return false;
  3704. }
  3705. }
  3706. return true;
  3707. }
  3708. function getParentCondition(node) {
  3709. while (true) {
  3710. if (node.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  3711. if (node.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  3712. node = node.alternate;
  3713. }
  3714. else {
  3715. return node;
  3716. }
  3717. }
  3718. else if (node.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */) {
  3719. node = node.value;
  3720. }
  3721. }
  3722. }
  3723. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  3724. const { helper, removeHelper } = context;
  3725. return processFor(node, dir, context, forNode => {
  3726. // create the loop render function expression now, and add the
  3727. // iterator on exit after all children have been traversed
  3728. const renderExp = createCallExpression(helper(RENDER_LIST), [
  3729. forNode.source
  3730. ]);
  3731. const isTemplate = isTemplateNode(node);
  3732. const memo = findDir(node, 'memo');
  3733. const keyProp = findProp(node, `key`);
  3734. const keyExp = keyProp &&
  3735. (keyProp.type === 6 /* NodeTypes.ATTRIBUTE */
  3736. ? createSimpleExpression(keyProp.value.content, true)
  3737. : keyProp.exp);
  3738. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  3739. if (isTemplate) {
  3740. // #2085 / #5288 process :key and v-memo expressions need to be
  3741. // processed on `<template v-for>`. In this case the node is discarded
  3742. // and never traversed so its binding expressions won't be processed
  3743. // by the normal transforms.
  3744. if (memo) {
  3745. memo.exp = processExpression(memo.exp, context);
  3746. }
  3747. if (keyProperty && keyProp.type !== 6 /* NodeTypes.ATTRIBUTE */) {
  3748. keyProperty.value = processExpression(keyProperty.value, context);
  3749. }
  3750. }
  3751. const isStableFragment = forNode.source.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  3752. forNode.source.constType > 0 /* ConstantTypes.NOT_CONSTANT */;
  3753. const fragmentFlag = isStableFragment
  3754. ? 64 /* PatchFlags.STABLE_FRAGMENT */
  3755. : keyProp
  3756. ? 128 /* PatchFlags.KEYED_FRAGMENT */
  3757. : 256 /* PatchFlags.UNKEYED_FRAGMENT */;
  3758. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  3759. (``), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  3760. return () => {
  3761. // finish the codegen now that all children have been traversed
  3762. let childBlock;
  3763. const { children } = forNode;
  3764. // check <template v-for> key placement
  3765. if (isTemplate) {
  3766. node.children.some(c => {
  3767. if (c.type === 1 /* NodeTypes.ELEMENT */) {
  3768. const key = findProp(c, 'key');
  3769. if (key) {
  3770. context.onError(createCompilerError(33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  3771. return true;
  3772. }
  3773. }
  3774. });
  3775. }
  3776. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */;
  3777. const slotOutlet = isSlotOutlet(node)
  3778. ? node
  3779. : isTemplate &&
  3780. node.children.length === 1 &&
  3781. isSlotOutlet(node.children[0])
  3782. ? node.children[0] // api-extractor somehow fails to infer this
  3783. : null;
  3784. if (slotOutlet) {
  3785. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  3786. childBlock = slotOutlet.codegenNode;
  3787. if (isTemplate && keyProperty) {
  3788. // <template v-for="..." :key="..."><slot/></template>
  3789. // we need to inject the key to the renderSlot() call.
  3790. // the props for renderSlot is passed as the 3rd argument.
  3791. injectProp(childBlock, keyProperty, context);
  3792. }
  3793. }
  3794. else if (needFragmentWrapper) {
  3795. // <template v-for="..."> with text or multi-elements
  3796. // should generate a fragment block for each loop
  3797. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* PatchFlags.STABLE_FRAGMENT */ +
  3798. (``), undefined, undefined, true, undefined, false /* isComponent */);
  3799. }
  3800. else {
  3801. // Normal element v-for. Directly use the child's codegenNode
  3802. // but mark it as a block.
  3803. childBlock = children[0]
  3804. .codegenNode;
  3805. if (isTemplate && keyProperty) {
  3806. injectProp(childBlock, keyProperty, context);
  3807. }
  3808. if (childBlock.isBlock !== !isStableFragment) {
  3809. if (childBlock.isBlock) {
  3810. // switch from block to vnode
  3811. removeHelper(OPEN_BLOCK);
  3812. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  3813. }
  3814. else {
  3815. // switch from vnode to block
  3816. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  3817. }
  3818. }
  3819. childBlock.isBlock = !isStableFragment;
  3820. if (childBlock.isBlock) {
  3821. helper(OPEN_BLOCK);
  3822. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  3823. }
  3824. else {
  3825. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  3826. }
  3827. }
  3828. if (memo) {
  3829. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  3830. createSimpleExpression(`_cached`)
  3831. ]));
  3832. loop.body = createBlockStatement([
  3833. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  3834. createCompoundExpression([
  3835. `if (_cached`,
  3836. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  3837. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  3838. ]),
  3839. createCompoundExpression([`const _item = `, childBlock]),
  3840. createSimpleExpression(`_item.memo = _memo`),
  3841. createSimpleExpression(`return _item`)
  3842. ]);
  3843. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  3844. }
  3845. else {
  3846. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  3847. }
  3848. };
  3849. });
  3850. });
  3851. // target-agnostic transform used for both Client and SSR
  3852. function processFor(node, dir, context, processCodegen) {
  3853. if (!dir.exp) {
  3854. context.onError(createCompilerError(31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */, dir.loc));
  3855. return;
  3856. }
  3857. const parseResult = parseForExpression(
  3858. // can only be simple expression because vFor transform is applied
  3859. // before expression transform.
  3860. dir.exp, context);
  3861. if (!parseResult) {
  3862. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  3863. return;
  3864. }
  3865. const { addIdentifiers, removeIdentifiers, scopes } = context;
  3866. const { source, value, key, index } = parseResult;
  3867. const forNode = {
  3868. type: 11 /* NodeTypes.FOR */,
  3869. loc: dir.loc,
  3870. source,
  3871. valueAlias: value,
  3872. keyAlias: key,
  3873. objectIndexAlias: index,
  3874. parseResult,
  3875. children: isTemplateNode(node) ? node.children : [node]
  3876. };
  3877. context.replaceNode(forNode);
  3878. // bookkeeping
  3879. scopes.vFor++;
  3880. if (context.prefixIdentifiers) {
  3881. // scope management
  3882. // inject identifiers to context
  3883. value && addIdentifiers(value);
  3884. key && addIdentifiers(key);
  3885. index && addIdentifiers(index);
  3886. }
  3887. const onExit = processCodegen && processCodegen(forNode);
  3888. return () => {
  3889. scopes.vFor--;
  3890. if (context.prefixIdentifiers) {
  3891. value && removeIdentifiers(value);
  3892. key && removeIdentifiers(key);
  3893. index && removeIdentifiers(index);
  3894. }
  3895. if (onExit)
  3896. onExit();
  3897. };
  3898. }
  3899. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  3900. // This regex doesn't cover the case if key or index aliases have destructuring,
  3901. // but those do not make sense in the first place, so this works in practice.
  3902. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  3903. const stripParensRE = /^\(|\)$/g;
  3904. function parseForExpression(input, context) {
  3905. const loc = input.loc;
  3906. const exp = input.content;
  3907. const inMatch = exp.match(forAliasRE);
  3908. if (!inMatch)
  3909. return;
  3910. const [, LHS, RHS] = inMatch;
  3911. const result = {
  3912. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  3913. value: undefined,
  3914. key: undefined,
  3915. index: undefined
  3916. };
  3917. if (context.prefixIdentifiers) {
  3918. result.source = processExpression(result.source, context);
  3919. }
  3920. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  3921. const trimmedOffset = LHS.indexOf(valueContent);
  3922. const iteratorMatch = valueContent.match(forIteratorRE);
  3923. if (iteratorMatch) {
  3924. valueContent = valueContent.replace(forIteratorRE, '').trim();
  3925. const keyContent = iteratorMatch[1].trim();
  3926. let keyOffset;
  3927. if (keyContent) {
  3928. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  3929. result.key = createAliasExpression(loc, keyContent, keyOffset);
  3930. if (context.prefixIdentifiers) {
  3931. result.key = processExpression(result.key, context, true);
  3932. }
  3933. }
  3934. if (iteratorMatch[2]) {
  3935. const indexContent = iteratorMatch[2].trim();
  3936. if (indexContent) {
  3937. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  3938. ? keyOffset + keyContent.length
  3939. : trimmedOffset + valueContent.length));
  3940. if (context.prefixIdentifiers) {
  3941. result.index = processExpression(result.index, context, true);
  3942. }
  3943. }
  3944. }
  3945. }
  3946. if (valueContent) {
  3947. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  3948. if (context.prefixIdentifiers) {
  3949. result.value = processExpression(result.value, context, true);
  3950. }
  3951. }
  3952. return result;
  3953. }
  3954. function createAliasExpression(range, content, offset) {
  3955. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  3956. }
  3957. function createForLoopParams({ value, key, index }, memoArgs = []) {
  3958. return createParamsList([value, key, index, ...memoArgs]);
  3959. }
  3960. function createParamsList(args) {
  3961. let i = args.length;
  3962. while (i--) {
  3963. if (args[i])
  3964. break;
  3965. }
  3966. return args
  3967. .slice(0, i + 1)
  3968. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  3969. }
  3970. const defaultFallback = createSimpleExpression(`undefined`, false);
  3971. // A NodeTransform that:
  3972. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  3973. // by transformExpression. This is only applied in non-browser builds with
  3974. // { prefixIdentifiers: true }.
  3975. // 2. Track v-slot depths so that we know a slot is inside another slot.
  3976. // Note the exit callback is executed before buildSlots() on the same node,
  3977. // so only nested slots see positive numbers.
  3978. const trackSlotScopes = (node, context) => {
  3979. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  3980. (node.tagType === 1 /* ElementTypes.COMPONENT */ ||
  3981. node.tagType === 3 /* ElementTypes.TEMPLATE */)) {
  3982. // We are only checking non-empty v-slot here
  3983. // since we only care about slots that introduce scope variables.
  3984. const vSlot = findDir(node, 'slot');
  3985. if (vSlot) {
  3986. const slotProps = vSlot.exp;
  3987. if (context.prefixIdentifiers) {
  3988. slotProps && context.addIdentifiers(slotProps);
  3989. }
  3990. context.scopes.vSlot++;
  3991. return () => {
  3992. if (context.prefixIdentifiers) {
  3993. slotProps && context.removeIdentifiers(slotProps);
  3994. }
  3995. context.scopes.vSlot--;
  3996. };
  3997. }
  3998. }
  3999. };
  4000. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  4001. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  4002. const trackVForSlotScopes = (node, context) => {
  4003. let vFor;
  4004. if (isTemplateNode(node) &&
  4005. node.props.some(isVSlot) &&
  4006. (vFor = findDir(node, 'for'))) {
  4007. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  4008. if (result) {
  4009. const { value, key, index } = result;
  4010. const { addIdentifiers, removeIdentifiers } = context;
  4011. value && addIdentifiers(value);
  4012. key && addIdentifiers(key);
  4013. index && addIdentifiers(index);
  4014. return () => {
  4015. value && removeIdentifiers(value);
  4016. key && removeIdentifiers(key);
  4017. index && removeIdentifiers(index);
  4018. };
  4019. }
  4020. }
  4021. };
  4022. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  4023. // Instead of being a DirectiveTransform, v-slot processing is called during
  4024. // transformElement to build the slots object for a component.
  4025. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  4026. context.helper(WITH_CTX);
  4027. const { children, loc } = node;
  4028. const slotsProperties = [];
  4029. const dynamicSlots = [];
  4030. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  4031. // since it likely uses a scope variable.
  4032. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  4033. // with `prefixIdentifiers: true`, this can be further optimized to make
  4034. // it dynamic only when the slot actually uses the scope variables.
  4035. if (!context.ssr && context.prefixIdentifiers) {
  4036. hasDynamicSlots = hasScopeRef(node, context.identifiers);
  4037. }
  4038. // 1. Check for slot with slotProps on component itself.
  4039. // <Comp v-slot="{ prop }"/>
  4040. const onComponentSlot = findDir(node, 'slot', true);
  4041. if (onComponentSlot) {
  4042. const { arg, exp } = onComponentSlot;
  4043. if (arg && !isStaticExp(arg)) {
  4044. hasDynamicSlots = true;
  4045. }
  4046. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  4047. }
  4048. // 2. Iterate through children and check for template slots
  4049. // <template v-slot:foo="{ prop }">
  4050. let hasTemplateSlots = false;
  4051. let hasNamedDefaultSlot = false;
  4052. const implicitDefaultChildren = [];
  4053. const seenSlotNames = new Set();
  4054. let conditionalBranchIndex = 0;
  4055. for (let i = 0; i < children.length; i++) {
  4056. const slotElement = children[i];
  4057. let slotDir;
  4058. if (!isTemplateNode(slotElement) ||
  4059. !(slotDir = findDir(slotElement, 'slot', true))) {
  4060. // not a <template v-slot>, skip.
  4061. if (slotElement.type !== 3 /* NodeTypes.COMMENT */) {
  4062. implicitDefaultChildren.push(slotElement);
  4063. }
  4064. continue;
  4065. }
  4066. if (onComponentSlot) {
  4067. // already has on-component slot - this is incorrect usage.
  4068. context.onError(createCompilerError(37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  4069. break;
  4070. }
  4071. hasTemplateSlots = true;
  4072. const { children: slotChildren, loc: slotLoc } = slotElement;
  4073. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  4074. // check if name is dynamic.
  4075. let staticSlotName;
  4076. if (isStaticExp(slotName)) {
  4077. staticSlotName = slotName ? slotName.content : `default`;
  4078. }
  4079. else {
  4080. hasDynamicSlots = true;
  4081. }
  4082. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  4083. // check if this slot is conditional (v-if/v-for)
  4084. let vIf;
  4085. let vElse;
  4086. let vFor;
  4087. if ((vIf = findDir(slotElement, 'if'))) {
  4088. hasDynamicSlots = true;
  4089. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback));
  4090. }
  4091. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  4092. // find adjacent v-if
  4093. let j = i;
  4094. let prev;
  4095. while (j--) {
  4096. prev = children[j];
  4097. if (prev.type !== 3 /* NodeTypes.COMMENT */) {
  4098. break;
  4099. }
  4100. }
  4101. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  4102. // remove node
  4103. children.splice(i, 1);
  4104. i--;
  4105. // attach this slot to previous conditional
  4106. let conditional = dynamicSlots[dynamicSlots.length - 1];
  4107. while (conditional.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  4108. conditional = conditional.alternate;
  4109. }
  4110. conditional.alternate = vElse.exp
  4111. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback)
  4112. : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  4113. }
  4114. else {
  4115. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  4116. }
  4117. }
  4118. else if ((vFor = findDir(slotElement, 'for'))) {
  4119. hasDynamicSlots = true;
  4120. const parseResult = vFor.parseResult ||
  4121. parseForExpression(vFor.exp, context);
  4122. if (parseResult) {
  4123. // Render the dynamic slots as an array and add it to the createSlot()
  4124. // args. The runtime knows how to handle it appropriately.
  4125. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  4126. parseResult.source,
  4127. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  4128. ]));
  4129. }
  4130. else {
  4131. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  4132. }
  4133. }
  4134. else {
  4135. // check duplicate static names
  4136. if (staticSlotName) {
  4137. if (seenSlotNames.has(staticSlotName)) {
  4138. context.onError(createCompilerError(38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  4139. continue;
  4140. }
  4141. seenSlotNames.add(staticSlotName);
  4142. if (staticSlotName === 'default') {
  4143. hasNamedDefaultSlot = true;
  4144. }
  4145. }
  4146. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  4147. }
  4148. }
  4149. if (!onComponentSlot) {
  4150. const buildDefaultSlotProperty = (props, children) => {
  4151. const fn = buildSlotFn(props, children, loc);
  4152. if (context.compatConfig) {
  4153. fn.isNonScopedSlot = true;
  4154. }
  4155. return createObjectProperty(`default`, fn);
  4156. };
  4157. if (!hasTemplateSlots) {
  4158. // implicit default slot (on component)
  4159. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  4160. }
  4161. else if (implicitDefaultChildren.length &&
  4162. // #3766
  4163. // with whitespace: 'preserve', whitespaces between slots will end up in
  4164. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  4165. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  4166. // implicit default slot (mixed with named slots)
  4167. if (hasNamedDefaultSlot) {
  4168. context.onError(createCompilerError(39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  4169. }
  4170. else {
  4171. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  4172. }
  4173. }
  4174. }
  4175. const slotFlag = hasDynamicSlots
  4176. ? 2 /* SlotFlags.DYNAMIC */
  4177. : hasForwardedSlots(node.children)
  4178. ? 3 /* SlotFlags.FORWARDED */
  4179. : 1 /* SlotFlags.STABLE */;
  4180. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  4181. // 2 = compiled but dynamic = can skip normalization, but must run diff
  4182. // 1 = compiled and static = can skip normalization AND diff as optimized
  4183. createSimpleExpression(slotFlag + (``), false))), loc);
  4184. if (dynamicSlots.length) {
  4185. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  4186. slots,
  4187. createArrayExpression(dynamicSlots)
  4188. ]);
  4189. }
  4190. return {
  4191. slots,
  4192. hasDynamicSlots
  4193. };
  4194. }
  4195. function buildDynamicSlot(name, fn, index) {
  4196. const props = [
  4197. createObjectProperty(`name`, name),
  4198. createObjectProperty(`fn`, fn)
  4199. ];
  4200. if (index != null) {
  4201. props.push(createObjectProperty(`key`, createSimpleExpression(String(index), true)));
  4202. }
  4203. return createObjectExpression(props);
  4204. }
  4205. function hasForwardedSlots(children) {
  4206. for (let i = 0; i < children.length; i++) {
  4207. const child = children[i];
  4208. switch (child.type) {
  4209. case 1 /* NodeTypes.ELEMENT */:
  4210. if (child.tagType === 2 /* ElementTypes.SLOT */ ||
  4211. hasForwardedSlots(child.children)) {
  4212. return true;
  4213. }
  4214. break;
  4215. case 9 /* NodeTypes.IF */:
  4216. if (hasForwardedSlots(child.branches))
  4217. return true;
  4218. break;
  4219. case 10 /* NodeTypes.IF_BRANCH */:
  4220. case 11 /* NodeTypes.FOR */:
  4221. if (hasForwardedSlots(child.children))
  4222. return true;
  4223. break;
  4224. }
  4225. }
  4226. return false;
  4227. }
  4228. function isNonWhitespaceContent(node) {
  4229. if (node.type !== 2 /* NodeTypes.TEXT */ && node.type !== 12 /* NodeTypes.TEXT_CALL */)
  4230. return true;
  4231. return node.type === 2 /* NodeTypes.TEXT */
  4232. ? !!node.content.trim()
  4233. : isNonWhitespaceContent(node.content);
  4234. }
  4235. // some directive transforms (e.g. v-model) may return a symbol for runtime
  4236. // import, which should be used instead of a resolveDirective call.
  4237. const directiveImportMap = new WeakMap();
  4238. // generate a JavaScript AST for this element's codegen
  4239. const transformElement = (node, context) => {
  4240. // perform the work on exit, after all child expressions have been
  4241. // processed and merged.
  4242. return function postTransformElement() {
  4243. node = context.currentNode;
  4244. if (!(node.type === 1 /* NodeTypes.ELEMENT */ &&
  4245. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  4246. node.tagType === 1 /* ElementTypes.COMPONENT */))) {
  4247. return;
  4248. }
  4249. const { tag, props } = node;
  4250. const isComponent = node.tagType === 1 /* ElementTypes.COMPONENT */;
  4251. // The goal of the transform is to create a codegenNode implementing the
  4252. // VNodeCall interface.
  4253. let vnodeTag = isComponent
  4254. ? resolveComponentType(node, context)
  4255. : `"${tag}"`;
  4256. const isDynamicComponent = shared.isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  4257. let vnodeProps;
  4258. let vnodeChildren;
  4259. let vnodePatchFlag;
  4260. let patchFlag = 0;
  4261. let vnodeDynamicProps;
  4262. let dynamicPropNames;
  4263. let vnodeDirectives;
  4264. let shouldUseBlock =
  4265. // dynamic component may resolve to plain elements
  4266. isDynamicComponent ||
  4267. vnodeTag === TELEPORT ||
  4268. vnodeTag === SUSPENSE ||
  4269. (!isComponent &&
  4270. // <svg> and <foreignObject> must be forced into blocks so that block
  4271. // updates inside get proper isSVG flag at runtime. (#639, #643)
  4272. // This is technically web-specific, but splitting the logic out of core
  4273. // leads to too much unnecessary complexity.
  4274. (tag === 'svg' || tag === 'foreignObject'));
  4275. // props
  4276. if (props.length > 0) {
  4277. const propsBuildResult = buildProps(node, context, undefined, isComponent, isDynamicComponent);
  4278. vnodeProps = propsBuildResult.props;
  4279. patchFlag = propsBuildResult.patchFlag;
  4280. dynamicPropNames = propsBuildResult.dynamicPropNames;
  4281. const directives = propsBuildResult.directives;
  4282. vnodeDirectives =
  4283. directives && directives.length
  4284. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  4285. : undefined;
  4286. if (propsBuildResult.shouldUseBlock) {
  4287. shouldUseBlock = true;
  4288. }
  4289. }
  4290. // children
  4291. if (node.children.length > 0) {
  4292. if (vnodeTag === KEEP_ALIVE) {
  4293. // Although a built-in component, we compile KeepAlive with raw children
  4294. // instead of slot functions so that it can be used inside Transition
  4295. // or other Transition-wrapping HOCs.
  4296. // To ensure correct updates with block optimizations, we need to:
  4297. // 1. Force keep-alive into a block. This avoids its children being
  4298. // collected by a parent block.
  4299. shouldUseBlock = true;
  4300. // 2. Force keep-alive to always be updated, since it uses raw children.
  4301. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  4302. }
  4303. const shouldBuildAsSlots = isComponent &&
  4304. // Teleport is not a real component and has dedicated runtime handling
  4305. vnodeTag !== TELEPORT &&
  4306. // explained above.
  4307. vnodeTag !== KEEP_ALIVE;
  4308. if (shouldBuildAsSlots) {
  4309. const { slots, hasDynamicSlots } = buildSlots(node, context);
  4310. vnodeChildren = slots;
  4311. if (hasDynamicSlots) {
  4312. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  4313. }
  4314. }
  4315. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  4316. const child = node.children[0];
  4317. const type = child.type;
  4318. // check for dynamic text children
  4319. const hasDynamicTextChild = type === 5 /* NodeTypes.INTERPOLATION */ ||
  4320. type === 8 /* NodeTypes.COMPOUND_EXPRESSION */;
  4321. if (hasDynamicTextChild &&
  4322. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  4323. patchFlag |= 1 /* PatchFlags.TEXT */;
  4324. }
  4325. // pass directly if the only child is a text node
  4326. // (plain / interpolation / expression)
  4327. if (hasDynamicTextChild || type === 2 /* NodeTypes.TEXT */) {
  4328. vnodeChildren = child;
  4329. }
  4330. else {
  4331. vnodeChildren = node.children;
  4332. }
  4333. }
  4334. else {
  4335. vnodeChildren = node.children;
  4336. }
  4337. }
  4338. // patchFlag & dynamicPropNames
  4339. if (patchFlag !== 0) {
  4340. {
  4341. vnodePatchFlag = String(patchFlag);
  4342. }
  4343. if (dynamicPropNames && dynamicPropNames.length) {
  4344. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  4345. }
  4346. }
  4347. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  4348. };
  4349. };
  4350. function resolveComponentType(node, context, ssr = false) {
  4351. let { tag } = node;
  4352. // 1. dynamic component
  4353. const isExplicitDynamic = isComponentTag(tag);
  4354. const isProp = findProp(node, 'is');
  4355. if (isProp) {
  4356. if (isExplicitDynamic ||
  4357. (isCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context))) {
  4358. const exp = isProp.type === 6 /* NodeTypes.ATTRIBUTE */
  4359. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  4360. : isProp.exp;
  4361. if (exp) {
  4362. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  4363. exp
  4364. ]);
  4365. }
  4366. }
  4367. else if (isProp.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  4368. isProp.value.content.startsWith('vue:')) {
  4369. // <button is="vue:xxx">
  4370. // if not <component>, only is value that starts with "vue:" will be
  4371. // treated as component by the parse phase and reach here, unless it's
  4372. // compat mode where all is values are considered components
  4373. tag = isProp.value.content.slice(4);
  4374. }
  4375. }
  4376. // 1.5 v-is (TODO: Deprecate)
  4377. const isDir = !isExplicitDynamic && findDir(node, 'is');
  4378. if (isDir && isDir.exp) {
  4379. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  4380. isDir.exp
  4381. ]);
  4382. }
  4383. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  4384. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  4385. if (builtIn) {
  4386. // built-ins are simply fallthroughs / have special handling during ssr
  4387. // so we don't need to import their runtime equivalents
  4388. if (!ssr)
  4389. context.helper(builtIn);
  4390. return builtIn;
  4391. }
  4392. // 3. user component (from setup bindings)
  4393. // this is skipped in browser build since browser builds do not perform
  4394. // binding analysis.
  4395. {
  4396. const fromSetup = resolveSetupReference(tag, context);
  4397. if (fromSetup) {
  4398. return fromSetup;
  4399. }
  4400. const dotIndex = tag.indexOf('.');
  4401. if (dotIndex > 0) {
  4402. const ns = resolveSetupReference(tag.slice(0, dotIndex), context);
  4403. if (ns) {
  4404. return ns + tag.slice(dotIndex);
  4405. }
  4406. }
  4407. }
  4408. // 4. Self referencing component (inferred from filename)
  4409. if (context.selfName &&
  4410. shared.capitalize(shared.camelize(tag)) === context.selfName) {
  4411. context.helper(RESOLVE_COMPONENT);
  4412. // codegen.ts has special check for __self postfix when generating
  4413. // component imports, which will pass additional `maybeSelfReference` flag
  4414. // to `resolveComponent`.
  4415. context.components.add(tag + `__self`);
  4416. return toValidAssetId(tag, `component`);
  4417. }
  4418. // 5. user component (resolve)
  4419. context.helper(RESOLVE_COMPONENT);
  4420. context.components.add(tag);
  4421. return toValidAssetId(tag, `component`);
  4422. }
  4423. function resolveSetupReference(name, context) {
  4424. const bindings = context.bindingMetadata;
  4425. if (!bindings || bindings.__isScriptSetup === false) {
  4426. return;
  4427. }
  4428. const camelName = shared.camelize(name);
  4429. const PascalName = shared.capitalize(camelName);
  4430. const checkType = (type) => {
  4431. if (bindings[name] === type) {
  4432. return name;
  4433. }
  4434. if (bindings[camelName] === type) {
  4435. return camelName;
  4436. }
  4437. if (bindings[PascalName] === type) {
  4438. return PascalName;
  4439. }
  4440. };
  4441. const fromConst = checkType("setup-const" /* BindingTypes.SETUP_CONST */) ||
  4442. checkType("setup-reactive-const" /* BindingTypes.SETUP_REACTIVE_CONST */);
  4443. if (fromConst) {
  4444. return context.inline
  4445. ? // in inline mode, const setup bindings (e.g. imports) can be used as-is
  4446. fromConst
  4447. : `$setup[${JSON.stringify(fromConst)}]`;
  4448. }
  4449. const fromMaybeRef = checkType("setup-let" /* BindingTypes.SETUP_LET */) ||
  4450. checkType("setup-ref" /* BindingTypes.SETUP_REF */) ||
  4451. checkType("setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */);
  4452. if (fromMaybeRef) {
  4453. return context.inline
  4454. ? // setup scope bindings that may be refs need to be unrefed
  4455. `${context.helperString(UNREF)}(${fromMaybeRef})`
  4456. : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  4457. }
  4458. }
  4459. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  4460. const { tag, loc: elementLoc, children } = node;
  4461. let properties = [];
  4462. const mergeArgs = [];
  4463. const runtimeDirectives = [];
  4464. const hasChildren = children.length > 0;
  4465. let shouldUseBlock = false;
  4466. // patchFlag analysis
  4467. let patchFlag = 0;
  4468. let hasRef = false;
  4469. let hasClassBinding = false;
  4470. let hasStyleBinding = false;
  4471. let hasHydrationEventBinding = false;
  4472. let hasDynamicKeys = false;
  4473. let hasVnodeHook = false;
  4474. const dynamicPropNames = [];
  4475. const pushMergeArg = (arg) => {
  4476. if (properties.length) {
  4477. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  4478. properties = [];
  4479. }
  4480. if (arg)
  4481. mergeArgs.push(arg);
  4482. };
  4483. const analyzePatchFlag = ({ key, value }) => {
  4484. if (isStaticExp(key)) {
  4485. const name = key.content;
  4486. const isEventHandler = shared.isOn(name);
  4487. if (isEventHandler &&
  4488. (!isComponent || isDynamicComponent) &&
  4489. // omit the flag for click handlers because hydration gives click
  4490. // dedicated fast path.
  4491. name.toLowerCase() !== 'onclick' &&
  4492. // omit v-model handlers
  4493. name !== 'onUpdate:modelValue' &&
  4494. // omit onVnodeXXX hooks
  4495. !shared.isReservedProp(name)) {
  4496. hasHydrationEventBinding = true;
  4497. }
  4498. if (isEventHandler && shared.isReservedProp(name)) {
  4499. hasVnodeHook = true;
  4500. }
  4501. if (value.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */ ||
  4502. ((value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  4503. value.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) &&
  4504. getConstantType(value, context) > 0)) {
  4505. // skip if the prop is a cached handler or has constant value
  4506. return;
  4507. }
  4508. if (name === 'ref') {
  4509. hasRef = true;
  4510. }
  4511. else if (name === 'class') {
  4512. hasClassBinding = true;
  4513. }
  4514. else if (name === 'style') {
  4515. hasStyleBinding = true;
  4516. }
  4517. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  4518. dynamicPropNames.push(name);
  4519. }
  4520. // treat the dynamic class and style binding of the component as dynamic props
  4521. if (isComponent &&
  4522. (name === 'class' || name === 'style') &&
  4523. !dynamicPropNames.includes(name)) {
  4524. dynamicPropNames.push(name);
  4525. }
  4526. }
  4527. else {
  4528. hasDynamicKeys = true;
  4529. }
  4530. };
  4531. for (let i = 0; i < props.length; i++) {
  4532. // static attribute
  4533. const prop = props[i];
  4534. if (prop.type === 6 /* NodeTypes.ATTRIBUTE */) {
  4535. const { loc, name, value } = prop;
  4536. let isStatic = true;
  4537. if (name === 'ref') {
  4538. hasRef = true;
  4539. if (context.scopes.vFor > 0) {
  4540. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  4541. }
  4542. // in inline mode there is no setupState object, so we can't use string
  4543. // keys to set the ref. Instead, we need to transform it to pass the
  4544. // actual ref instead.
  4545. if (value && context.inline) {
  4546. const binding = context.bindingMetadata[value.content];
  4547. if (binding === "setup-let" /* BindingTypes.SETUP_LET */ ||
  4548. binding === "setup-ref" /* BindingTypes.SETUP_REF */ ||
  4549. binding === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */) {
  4550. isStatic = false;
  4551. properties.push(createObjectProperty(createSimpleExpression('ref_key', true), createSimpleExpression(value.content, true, value.loc)));
  4552. }
  4553. }
  4554. }
  4555. // skip is on <component>, or is="vue:xxx"
  4556. if (name === 'is' &&
  4557. (isComponentTag(tag) ||
  4558. (value && value.content.startsWith('vue:')) ||
  4559. (isCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context)))) {
  4560. continue;
  4561. }
  4562. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  4563. }
  4564. else {
  4565. // directives
  4566. const { name, arg, exp, loc } = prop;
  4567. const isVBind = name === 'bind';
  4568. const isVOn = name === 'on';
  4569. // skip v-slot - it is handled by its dedicated transform.
  4570. if (name === 'slot') {
  4571. if (!isComponent) {
  4572. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, loc));
  4573. }
  4574. continue;
  4575. }
  4576. // skip v-once/v-memo - they are handled by dedicated transforms.
  4577. if (name === 'once' || name === 'memo') {
  4578. continue;
  4579. }
  4580. // skip v-is and :is on <component>
  4581. if (name === 'is' ||
  4582. (isVBind &&
  4583. isStaticArgOf(arg, 'is') &&
  4584. (isComponentTag(tag) ||
  4585. (isCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context))))) {
  4586. continue;
  4587. }
  4588. // skip v-on in SSR compilation
  4589. if (isVOn && ssr) {
  4590. continue;
  4591. }
  4592. if (
  4593. // #938: elements with dynamic keys should be forced into blocks
  4594. (isVBind && isStaticArgOf(arg, 'key')) ||
  4595. // inline before-update hooks need to force block so that it is invoked
  4596. // before children
  4597. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  4598. shouldUseBlock = true;
  4599. }
  4600. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  4601. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  4602. }
  4603. // special case for v-bind and v-on with no argument
  4604. if (!arg && (isVBind || isVOn)) {
  4605. hasDynamicKeys = true;
  4606. if (exp) {
  4607. if (isVBind) {
  4608. // have to merge early for compat build check
  4609. pushMergeArg();
  4610. {
  4611. if (isCompatEnabled("COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */, context)) {
  4612. mergeArgs.unshift(exp);
  4613. continue;
  4614. }
  4615. }
  4616. mergeArgs.push(exp);
  4617. }
  4618. else {
  4619. // v-on="obj" -> toHandlers(obj)
  4620. pushMergeArg({
  4621. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  4622. loc,
  4623. callee: context.helper(TO_HANDLERS),
  4624. arguments: isComponent ? [exp] : [exp, `true`]
  4625. });
  4626. }
  4627. }
  4628. else {
  4629. context.onError(createCompilerError(isVBind
  4630. ? 34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */
  4631. : 35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  4632. }
  4633. continue;
  4634. }
  4635. const directiveTransform = context.directiveTransforms[name];
  4636. if (directiveTransform) {
  4637. // has built-in directive transform.
  4638. const { props, needRuntime } = directiveTransform(prop, node, context);
  4639. !ssr && props.forEach(analyzePatchFlag);
  4640. if (isVOn && arg && !isStaticExp(arg)) {
  4641. pushMergeArg(createObjectExpression(props, elementLoc));
  4642. }
  4643. else {
  4644. properties.push(...props);
  4645. }
  4646. if (needRuntime) {
  4647. runtimeDirectives.push(prop);
  4648. if (shared.isSymbol(needRuntime)) {
  4649. directiveImportMap.set(prop, needRuntime);
  4650. }
  4651. }
  4652. }
  4653. else if (!shared.isBuiltInDirective(name)) {
  4654. // no built-in transform, this is a user custom directive.
  4655. runtimeDirectives.push(prop);
  4656. // custom dirs may use beforeUpdate so they need to force blocks
  4657. // to ensure before-update gets called before children update
  4658. if (hasChildren) {
  4659. shouldUseBlock = true;
  4660. }
  4661. }
  4662. }
  4663. }
  4664. let propsExpression = undefined;
  4665. // has v-bind="object" or v-on="object", wrap with mergeProps
  4666. if (mergeArgs.length) {
  4667. // close up any not-yet-merged props
  4668. pushMergeArg();
  4669. if (mergeArgs.length > 1) {
  4670. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  4671. }
  4672. else {
  4673. // single v-bind with nothing else - no need for a mergeProps call
  4674. propsExpression = mergeArgs[0];
  4675. }
  4676. }
  4677. else if (properties.length) {
  4678. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  4679. }
  4680. // patchFlag analysis
  4681. if (hasDynamicKeys) {
  4682. patchFlag |= 16 /* PatchFlags.FULL_PROPS */;
  4683. }
  4684. else {
  4685. if (hasClassBinding && !isComponent) {
  4686. patchFlag |= 2 /* PatchFlags.CLASS */;
  4687. }
  4688. if (hasStyleBinding && !isComponent) {
  4689. patchFlag |= 4 /* PatchFlags.STYLE */;
  4690. }
  4691. if (dynamicPropNames.length) {
  4692. patchFlag |= 8 /* PatchFlags.PROPS */;
  4693. }
  4694. if (hasHydrationEventBinding) {
  4695. patchFlag |= 32 /* PatchFlags.HYDRATE_EVENTS */;
  4696. }
  4697. }
  4698. if (!shouldUseBlock &&
  4699. (patchFlag === 0 || patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) &&
  4700. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  4701. patchFlag |= 512 /* PatchFlags.NEED_PATCH */;
  4702. }
  4703. // pre-normalize props, SSR is skipped for now
  4704. if (!context.inSSR && propsExpression) {
  4705. switch (propsExpression.type) {
  4706. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  4707. // means that there is no v-bind,
  4708. // but still need to deal with dynamic key binding
  4709. let classKeyIndex = -1;
  4710. let styleKeyIndex = -1;
  4711. let hasDynamicKey = false;
  4712. for (let i = 0; i < propsExpression.properties.length; i++) {
  4713. const key = propsExpression.properties[i].key;
  4714. if (isStaticExp(key)) {
  4715. if (key.content === 'class') {
  4716. classKeyIndex = i;
  4717. }
  4718. else if (key.content === 'style') {
  4719. styleKeyIndex = i;
  4720. }
  4721. }
  4722. else if (!key.isHandlerKey) {
  4723. hasDynamicKey = true;
  4724. }
  4725. }
  4726. const classProp = propsExpression.properties[classKeyIndex];
  4727. const styleProp = propsExpression.properties[styleKeyIndex];
  4728. // no dynamic key
  4729. if (!hasDynamicKey) {
  4730. if (classProp && !isStaticExp(classProp.value)) {
  4731. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  4732. }
  4733. if (styleProp &&
  4734. // the static style is compiled into an object,
  4735. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  4736. (hasStyleBinding ||
  4737. (styleProp.value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  4738. styleProp.value.content.trim()[0] === `[`) ||
  4739. // v-bind:style and style both exist,
  4740. // v-bind:style with static literal object
  4741. styleProp.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */)) {
  4742. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  4743. }
  4744. }
  4745. else {
  4746. // dynamic key binding, wrap with `normalizeProps`
  4747. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  4748. }
  4749. break;
  4750. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  4751. // mergeProps call, do nothing
  4752. break;
  4753. default:
  4754. // single v-bind
  4755. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  4756. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  4757. propsExpression
  4758. ])
  4759. ]);
  4760. break;
  4761. }
  4762. }
  4763. return {
  4764. props: propsExpression,
  4765. directives: runtimeDirectives,
  4766. patchFlag,
  4767. dynamicPropNames,
  4768. shouldUseBlock
  4769. };
  4770. }
  4771. // Dedupe props in an object literal.
  4772. // Literal duplicated attributes would have been warned during the parse phase,
  4773. // however, it's possible to encounter duplicated `onXXX` handlers with different
  4774. // modifiers. We also need to merge static and dynamic class / style attributes.
  4775. // - onXXX handlers / style: merge into array
  4776. // - class: merge into single expression with concatenation
  4777. function dedupeProperties(properties) {
  4778. const knownProps = new Map();
  4779. const deduped = [];
  4780. for (let i = 0; i < properties.length; i++) {
  4781. const prop = properties[i];
  4782. // dynamic keys are always allowed
  4783. if (prop.key.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  4784. deduped.push(prop);
  4785. continue;
  4786. }
  4787. const name = prop.key.content;
  4788. const existing = knownProps.get(name);
  4789. if (existing) {
  4790. if (name === 'style' || name === 'class' || shared.isOn(name)) {
  4791. mergeAsArray(existing, prop);
  4792. }
  4793. // unexpected duplicate, should have emitted error during parse
  4794. }
  4795. else {
  4796. knownProps.set(name, prop);
  4797. deduped.push(prop);
  4798. }
  4799. }
  4800. return deduped;
  4801. }
  4802. function mergeAsArray(existing, incoming) {
  4803. if (existing.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  4804. existing.value.elements.push(incoming.value);
  4805. }
  4806. else {
  4807. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  4808. }
  4809. }
  4810. function buildDirectiveArgs(dir, context) {
  4811. const dirArgs = [];
  4812. const runtime = directiveImportMap.get(dir);
  4813. if (runtime) {
  4814. // built-in directive with runtime
  4815. dirArgs.push(context.helperString(runtime));
  4816. }
  4817. else {
  4818. // user directive.
  4819. // see if we have directives exposed via <script setup>
  4820. const fromSetup = resolveSetupReference('v-' + dir.name, context);
  4821. if (fromSetup) {
  4822. dirArgs.push(fromSetup);
  4823. }
  4824. else {
  4825. // inject statement for resolving directive
  4826. context.helper(RESOLVE_DIRECTIVE);
  4827. context.directives.add(dir.name);
  4828. dirArgs.push(toValidAssetId(dir.name, `directive`));
  4829. }
  4830. }
  4831. const { loc } = dir;
  4832. if (dir.exp)
  4833. dirArgs.push(dir.exp);
  4834. if (dir.arg) {
  4835. if (!dir.exp) {
  4836. dirArgs.push(`void 0`);
  4837. }
  4838. dirArgs.push(dir.arg);
  4839. }
  4840. if (Object.keys(dir.modifiers).length) {
  4841. if (!dir.arg) {
  4842. if (!dir.exp) {
  4843. dirArgs.push(`void 0`);
  4844. }
  4845. dirArgs.push(`void 0`);
  4846. }
  4847. const trueExpression = createSimpleExpression(`true`, false, loc);
  4848. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  4849. }
  4850. return createArrayExpression(dirArgs, dir.loc);
  4851. }
  4852. function stringifyDynamicPropNames(props) {
  4853. let propsNamesString = `[`;
  4854. for (let i = 0, l = props.length; i < l; i++) {
  4855. propsNamesString += JSON.stringify(props[i]);
  4856. if (i < l - 1)
  4857. propsNamesString += ', ';
  4858. }
  4859. return propsNamesString + `]`;
  4860. }
  4861. function isComponentTag(tag) {
  4862. return tag === 'component' || tag === 'Component';
  4863. }
  4864. const cacheStringFunction = (fn) => {
  4865. const cache = Object.create(null);
  4866. return ((str) => {
  4867. const hit = cache[str];
  4868. return hit || (cache[str] = fn(str));
  4869. });
  4870. };
  4871. const camelizeRE = /-(\w)/g;
  4872. /**
  4873. * @private
  4874. */
  4875. const camelize = cacheStringFunction((str) => {
  4876. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  4877. });
  4878. const transformSlotOutlet = (node, context) => {
  4879. if (isSlotOutlet(node)) {
  4880. const { children, loc } = node;
  4881. const { slotName, slotProps } = processSlotOutlet(node, context);
  4882. const slotArgs = [
  4883. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  4884. slotName,
  4885. '{}',
  4886. 'undefined',
  4887. 'true'
  4888. ];
  4889. let expectedLen = 2;
  4890. if (slotProps) {
  4891. slotArgs[2] = slotProps;
  4892. expectedLen = 3;
  4893. }
  4894. if (children.length) {
  4895. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  4896. expectedLen = 4;
  4897. }
  4898. if (context.scopeId && !context.slotted) {
  4899. expectedLen = 5;
  4900. }
  4901. slotArgs.splice(expectedLen); // remove unused arguments
  4902. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  4903. }
  4904. };
  4905. function processSlotOutlet(node, context) {
  4906. let slotName = `"default"`;
  4907. let slotProps = undefined;
  4908. const nonNameProps = [];
  4909. for (let i = 0; i < node.props.length; i++) {
  4910. const p = node.props[i];
  4911. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  4912. if (p.value) {
  4913. if (p.name === 'name') {
  4914. slotName = JSON.stringify(p.value.content);
  4915. }
  4916. else {
  4917. p.name = camelize(p.name);
  4918. nonNameProps.push(p);
  4919. }
  4920. }
  4921. }
  4922. else {
  4923. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  4924. if (p.exp)
  4925. slotName = p.exp;
  4926. }
  4927. else {
  4928. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  4929. p.arg.content = camelize(p.arg.content);
  4930. }
  4931. nonNameProps.push(p);
  4932. }
  4933. }
  4934. }
  4935. if (nonNameProps.length > 0) {
  4936. const { props, directives } = buildProps(node, context, nonNameProps, false, false);
  4937. slotProps = props;
  4938. if (directives.length) {
  4939. context.onError(createCompilerError(36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  4940. }
  4941. }
  4942. return {
  4943. slotName,
  4944. slotProps
  4945. };
  4946. }
  4947. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  4948. const transformOn = (dir, node, context, augmentor) => {
  4949. const { loc, modifiers, arg } = dir;
  4950. if (!dir.exp && !modifiers.length) {
  4951. context.onError(createCompilerError(35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  4952. }
  4953. let eventName;
  4954. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  4955. if (arg.isStatic) {
  4956. let rawName = arg.content;
  4957. // TODO deprecate @vnodeXXX usage
  4958. if (rawName.startsWith('vue:')) {
  4959. rawName = `vnode-${rawName.slice(4)}`;
  4960. }
  4961. const eventString = node.tagType !== 0 /* ElementTypes.ELEMENT */ ||
  4962. rawName.startsWith('vnode') ||
  4963. !/[A-Z]/.test(rawName)
  4964. ? // for non-element and vnode lifecycle event listeners, auto convert
  4965. // it to camelCase. See issue #2249
  4966. shared.toHandlerKey(shared.camelize(rawName))
  4967. : // preserve case for plain element listeners that have uppercase
  4968. // letters, as these may be custom elements' custom events
  4969. `on:${rawName}`;
  4970. eventName = createSimpleExpression(eventString, true, arg.loc);
  4971. }
  4972. else {
  4973. // #2388
  4974. eventName = createCompoundExpression([
  4975. `${context.helperString(TO_HANDLER_KEY)}(`,
  4976. arg,
  4977. `)`
  4978. ]);
  4979. }
  4980. }
  4981. else {
  4982. // already a compound expression.
  4983. eventName = arg;
  4984. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  4985. eventName.children.push(`)`);
  4986. }
  4987. // handler processing
  4988. let exp = dir.exp;
  4989. if (exp && !exp.content.trim()) {
  4990. exp = undefined;
  4991. }
  4992. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  4993. if (exp) {
  4994. const isMemberExp = isMemberExpression(exp.content, context);
  4995. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  4996. const hasMultipleStatements = exp.content.includes(`;`);
  4997. // process the expression since it's been skipped
  4998. if (context.prefixIdentifiers) {
  4999. isInlineStatement && context.addIdentifiers(`$event`);
  5000. exp = dir.exp = processExpression(exp, context, false, hasMultipleStatements);
  5001. isInlineStatement && context.removeIdentifiers(`$event`);
  5002. // with scope analysis, the function is hoistable if it has no reference
  5003. // to scope variables.
  5004. shouldCache =
  5005. context.cacheHandlers &&
  5006. // unnecessary to cache inside v-once
  5007. !context.inVOnce &&
  5008. // runtime constants don't need to be cached
  5009. // (this is analyzed by compileScript in SFC <script setup>)
  5010. !(exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && exp.constType > 0) &&
  5011. // #1541 bail if this is a member exp handler passed to a component -
  5012. // we need to use the original function to preserve arity,
  5013. // e.g. <transition> relies on checking cb.length to determine
  5014. // transition end handling. Inline function is ok since its arity
  5015. // is preserved even when cached.
  5016. !(isMemberExp && node.tagType === 1 /* ElementTypes.COMPONENT */) &&
  5017. // bail if the function references closure variables (v-for, v-slot)
  5018. // it must be passed fresh to avoid stale values.
  5019. !hasScopeRef(exp, context.identifiers);
  5020. // If the expression is optimizable and is a member expression pointing
  5021. // to a function, turn it into invocation (and wrap in an arrow function
  5022. // below) so that it always accesses the latest value when called - thus
  5023. // avoiding the need to be patched.
  5024. if (shouldCache && isMemberExp) {
  5025. if (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  5026. exp.content = `${exp.content} && ${exp.content}(...args)`;
  5027. }
  5028. else {
  5029. exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
  5030. }
  5031. }
  5032. }
  5033. if (isInlineStatement || (shouldCache && isMemberExp)) {
  5034. // wrap inline statement in a function expression
  5035. exp = createCompoundExpression([
  5036. `${isInlineStatement
  5037. ? context.isTS
  5038. ? `($event: any)`
  5039. : `$event`
  5040. : `${context.isTS ? `\n//@ts-ignore\n` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  5041. exp,
  5042. hasMultipleStatements ? `}` : `)`
  5043. ]);
  5044. }
  5045. }
  5046. let ret = {
  5047. props: [
  5048. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  5049. ]
  5050. };
  5051. // apply extended compiler augmentor
  5052. if (augmentor) {
  5053. ret = augmentor(ret);
  5054. }
  5055. if (shouldCache) {
  5056. // cache handlers so that it's always the same handler being passed down.
  5057. // this avoids unnecessary re-renders when users use inline handlers on
  5058. // components.
  5059. ret.props[0].value = context.cache(ret.props[0].value);
  5060. }
  5061. // mark the key as handler for props normalization check
  5062. ret.props.forEach(p => (p.key.isHandlerKey = true));
  5063. return ret;
  5064. };
  5065. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  5066. // codegen for the entire props object. This transform here is only for v-bind
  5067. // *with* args.
  5068. const transformBind = (dir, _node, context) => {
  5069. const { exp, modifiers, loc } = dir;
  5070. const arg = dir.arg;
  5071. if (arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  5072. arg.children.unshift(`(`);
  5073. arg.children.push(`) || ""`);
  5074. }
  5075. else if (!arg.isStatic) {
  5076. arg.content = `${arg.content} || ""`;
  5077. }
  5078. // .sync is replaced by v-model:arg
  5079. if (modifiers.includes('camel')) {
  5080. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  5081. if (arg.isStatic) {
  5082. arg.content = shared.camelize(arg.content);
  5083. }
  5084. else {
  5085. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  5086. }
  5087. }
  5088. else {
  5089. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  5090. arg.children.push(`)`);
  5091. }
  5092. }
  5093. if (!context.inSSR) {
  5094. if (modifiers.includes('prop')) {
  5095. injectPrefix(arg, '.');
  5096. }
  5097. if (modifiers.includes('attr')) {
  5098. injectPrefix(arg, '^');
  5099. }
  5100. }
  5101. if (!exp ||
  5102. (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  5103. context.onError(createCompilerError(34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */, loc));
  5104. return {
  5105. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  5106. };
  5107. }
  5108. return {
  5109. props: [createObjectProperty(arg, exp)]
  5110. };
  5111. };
  5112. const injectPrefix = (arg, prefix) => {
  5113. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  5114. if (arg.isStatic) {
  5115. arg.content = prefix + arg.content;
  5116. }
  5117. else {
  5118. arg.content = `\`${prefix}\${${arg.content}}\``;
  5119. }
  5120. }
  5121. else {
  5122. arg.children.unshift(`'${prefix}' + (`);
  5123. arg.children.push(`)`);
  5124. }
  5125. };
  5126. // Merge adjacent text nodes and expressions into a single expression
  5127. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  5128. const transformText = (node, context) => {
  5129. if (node.type === 0 /* NodeTypes.ROOT */ ||
  5130. node.type === 1 /* NodeTypes.ELEMENT */ ||
  5131. node.type === 11 /* NodeTypes.FOR */ ||
  5132. node.type === 10 /* NodeTypes.IF_BRANCH */) {
  5133. // perform the transform on node exit so that all expressions have already
  5134. // been processed.
  5135. return () => {
  5136. const children = node.children;
  5137. let currentContainer = undefined;
  5138. let hasText = false;
  5139. for (let i = 0; i < children.length; i++) {
  5140. const child = children[i];
  5141. if (isText(child)) {
  5142. hasText = true;
  5143. for (let j = i + 1; j < children.length; j++) {
  5144. const next = children[j];
  5145. if (isText(next)) {
  5146. if (!currentContainer) {
  5147. currentContainer = children[i] = createCompoundExpression([child], child.loc);
  5148. }
  5149. // merge adjacent text node into current
  5150. currentContainer.children.push(` + `, next);
  5151. children.splice(j, 1);
  5152. j--;
  5153. }
  5154. else {
  5155. currentContainer = undefined;
  5156. break;
  5157. }
  5158. }
  5159. }
  5160. }
  5161. if (!hasText ||
  5162. // if this is a plain element with a single text child, leave it
  5163. // as-is since the runtime has dedicated fast path for this by directly
  5164. // setting textContent of the element.
  5165. // for component root it's always normalized anyway.
  5166. (children.length === 1 &&
  5167. (node.type === 0 /* NodeTypes.ROOT */ ||
  5168. (node.type === 1 /* NodeTypes.ELEMENT */ &&
  5169. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  5170. // #3756
  5171. // custom directives can potentially add DOM elements arbitrarily,
  5172. // we need to avoid setting textContent of the element at runtime
  5173. // to avoid accidentally overwriting the DOM elements added
  5174. // by the user through custom directives.
  5175. !node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  5176. !context.directiveTransforms[p.name]) &&
  5177. // in compat mode, <template> tags with no special directives
  5178. // will be rendered as a fragment so its children must be
  5179. // converted into vnodes.
  5180. !(node.tag === 'template'))))) {
  5181. return;
  5182. }
  5183. // pre-convert text nodes into createTextVNode(text) calls to avoid
  5184. // runtime normalization.
  5185. for (let i = 0; i < children.length; i++) {
  5186. const child = children[i];
  5187. if (isText(child) || child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  5188. const callArgs = [];
  5189. // createTextVNode defaults to single whitespace, so if it is a
  5190. // single space the code could be an empty call to save bytes.
  5191. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content !== ' ') {
  5192. callArgs.push(child);
  5193. }
  5194. // mark dynamic text with flag so it gets patched inside a block
  5195. if (!context.ssr &&
  5196. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  5197. callArgs.push(1 /* PatchFlags.TEXT */ +
  5198. (``));
  5199. }
  5200. children[i] = {
  5201. type: 12 /* NodeTypes.TEXT_CALL */,
  5202. content: child,
  5203. loc: child.loc,
  5204. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  5205. };
  5206. }
  5207. }
  5208. };
  5209. }
  5210. };
  5211. const seen = new WeakSet();
  5212. const transformOnce = (node, context) => {
  5213. if (node.type === 1 /* NodeTypes.ELEMENT */ && findDir(node, 'once', true)) {
  5214. if (seen.has(node) || context.inVOnce) {
  5215. return;
  5216. }
  5217. seen.add(node);
  5218. context.inVOnce = true;
  5219. context.helper(SET_BLOCK_TRACKING);
  5220. return () => {
  5221. context.inVOnce = false;
  5222. const cur = context.currentNode;
  5223. if (cur.codegenNode) {
  5224. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  5225. }
  5226. };
  5227. }
  5228. };
  5229. const transformModel = (dir, node, context) => {
  5230. const { exp, arg } = dir;
  5231. if (!exp) {
  5232. context.onError(createCompilerError(41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */, dir.loc));
  5233. return createTransformProps();
  5234. }
  5235. const rawExp = exp.loc.source;
  5236. const expString = exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  5237. // im SFC <script setup> inline mode, the exp may have been transformed into
  5238. // _unref(exp)
  5239. const bindingType = context.bindingMetadata[rawExp];
  5240. // check props
  5241. if (bindingType === "props" /* BindingTypes.PROPS */ ||
  5242. bindingType === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  5243. context.onError(createCompilerError(44 /* ErrorCodes.X_V_MODEL_ON_PROPS */, exp.loc));
  5244. return createTransformProps();
  5245. }
  5246. const maybeRef = context.inline &&
  5247. (bindingType === "setup-let" /* BindingTypes.SETUP_LET */ ||
  5248. bindingType === "setup-ref" /* BindingTypes.SETUP_REF */ ||
  5249. bindingType === "setup-maybe-ref" /* BindingTypes.SETUP_MAYBE_REF */);
  5250. if (!expString.trim() ||
  5251. (!isMemberExpression(expString, context) && !maybeRef)) {
  5252. context.onError(createCompilerError(42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  5253. return createTransformProps();
  5254. }
  5255. if (context.prefixIdentifiers &&
  5256. isSimpleIdentifier(expString) &&
  5257. context.identifiers[expString]) {
  5258. context.onError(createCompilerError(43 /* ErrorCodes.X_V_MODEL_ON_SCOPE_VARIABLE */, exp.loc));
  5259. return createTransformProps();
  5260. }
  5261. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  5262. const eventName = arg
  5263. ? isStaticExp(arg)
  5264. ? `onUpdate:${arg.content}`
  5265. : createCompoundExpression(['"onUpdate:" + ', arg])
  5266. : `onUpdate:modelValue`;
  5267. let assignmentExp;
  5268. const eventArg = context.isTS ? `($event: any)` : `$event`;
  5269. if (maybeRef) {
  5270. if (bindingType === "setup-ref" /* BindingTypes.SETUP_REF */) {
  5271. // v-model used on known ref.
  5272. assignmentExp = createCompoundExpression([
  5273. `${eventArg} => ((`,
  5274. createSimpleExpression(rawExp, false, exp.loc),
  5275. `).value = $event)`
  5276. ]);
  5277. }
  5278. else {
  5279. // v-model used on a potentially ref binding in <script setup> inline mode.
  5280. // the assignment needs to check whether the binding is actually a ref.
  5281. const altAssignment = bindingType === "setup-let" /* BindingTypes.SETUP_LET */ ? `${rawExp} = $event` : `null`;
  5282. assignmentExp = createCompoundExpression([
  5283. `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,
  5284. createSimpleExpression(rawExp, false, exp.loc),
  5285. `).value = $event : ${altAssignment})`
  5286. ]);
  5287. }
  5288. }
  5289. else {
  5290. assignmentExp = createCompoundExpression([
  5291. `${eventArg} => ((`,
  5292. exp,
  5293. `) = $event)`
  5294. ]);
  5295. }
  5296. const props = [
  5297. // modelValue: foo
  5298. createObjectProperty(propName, dir.exp),
  5299. // "onUpdate:modelValue": $event => (foo = $event)
  5300. createObjectProperty(eventName, assignmentExp)
  5301. ];
  5302. // cache v-model handler if applicable (when it doesn't refer any scope vars)
  5303. if (context.prefixIdentifiers &&
  5304. !context.inVOnce &&
  5305. context.cacheHandlers &&
  5306. !hasScopeRef(exp, context.identifiers)) {
  5307. props[1].value = context.cache(props[1].value);
  5308. }
  5309. // modelModifiers: { foo: true, "bar-baz": true }
  5310. if (dir.modifiers.length && node.tagType === 1 /* ElementTypes.COMPONENT */) {
  5311. const modifiers = dir.modifiers
  5312. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  5313. .join(`, `);
  5314. const modifiersKey = arg
  5315. ? isStaticExp(arg)
  5316. ? `${arg.content}Modifiers`
  5317. : createCompoundExpression([arg, ' + "Modifiers"'])
  5318. : `modelModifiers`;
  5319. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* ConstantTypes.CAN_HOIST */)));
  5320. }
  5321. return createTransformProps(props);
  5322. };
  5323. function createTransformProps(props = []) {
  5324. return { props };
  5325. }
  5326. const validDivisionCharRE = /[\w).+\-_$\]]/;
  5327. const transformFilter = (node, context) => {
  5328. if (!isCompatEnabled("COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */, context)) {
  5329. return;
  5330. }
  5331. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  5332. // filter rewrite is applied before expression transform so only
  5333. // simple expressions are possible at this stage
  5334. rewriteFilter(node.content, context);
  5335. }
  5336. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  5337. node.props.forEach((prop) => {
  5338. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ &&
  5339. prop.name !== 'for' &&
  5340. prop.exp) {
  5341. rewriteFilter(prop.exp, context);
  5342. }
  5343. });
  5344. }
  5345. };
  5346. function rewriteFilter(node, context) {
  5347. if (node.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  5348. parseFilter(node, context);
  5349. }
  5350. else {
  5351. for (let i = 0; i < node.children.length; i++) {
  5352. const child = node.children[i];
  5353. if (typeof child !== 'object')
  5354. continue;
  5355. if (child.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  5356. parseFilter(child, context);
  5357. }
  5358. else if (child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  5359. rewriteFilter(node, context);
  5360. }
  5361. else if (child.type === 5 /* NodeTypes.INTERPOLATION */) {
  5362. rewriteFilter(child.content, context);
  5363. }
  5364. }
  5365. }
  5366. }
  5367. function parseFilter(node, context) {
  5368. const exp = node.content;
  5369. let inSingle = false;
  5370. let inDouble = false;
  5371. let inTemplateString = false;
  5372. let inRegex = false;
  5373. let curly = 0;
  5374. let square = 0;
  5375. let paren = 0;
  5376. let lastFilterIndex = 0;
  5377. let c, prev, i, expression, filters = [];
  5378. for (i = 0; i < exp.length; i++) {
  5379. prev = c;
  5380. c = exp.charCodeAt(i);
  5381. if (inSingle) {
  5382. if (c === 0x27 && prev !== 0x5c)
  5383. inSingle = false;
  5384. }
  5385. else if (inDouble) {
  5386. if (c === 0x22 && prev !== 0x5c)
  5387. inDouble = false;
  5388. }
  5389. else if (inTemplateString) {
  5390. if (c === 0x60 && prev !== 0x5c)
  5391. inTemplateString = false;
  5392. }
  5393. else if (inRegex) {
  5394. if (c === 0x2f && prev !== 0x5c)
  5395. inRegex = false;
  5396. }
  5397. else if (c === 0x7c && // pipe
  5398. exp.charCodeAt(i + 1) !== 0x7c &&
  5399. exp.charCodeAt(i - 1) !== 0x7c &&
  5400. !curly &&
  5401. !square &&
  5402. !paren) {
  5403. if (expression === undefined) {
  5404. // first filter, end of expression
  5405. lastFilterIndex = i + 1;
  5406. expression = exp.slice(0, i).trim();
  5407. }
  5408. else {
  5409. pushFilter();
  5410. }
  5411. }
  5412. else {
  5413. switch (c) {
  5414. case 0x22:
  5415. inDouble = true;
  5416. break; // "
  5417. case 0x27:
  5418. inSingle = true;
  5419. break; // '
  5420. case 0x60:
  5421. inTemplateString = true;
  5422. break; // `
  5423. case 0x28:
  5424. paren++;
  5425. break; // (
  5426. case 0x29:
  5427. paren--;
  5428. break; // )
  5429. case 0x5b:
  5430. square++;
  5431. break; // [
  5432. case 0x5d:
  5433. square--;
  5434. break; // ]
  5435. case 0x7b:
  5436. curly++;
  5437. break; // {
  5438. case 0x7d:
  5439. curly--;
  5440. break; // }
  5441. }
  5442. if (c === 0x2f) {
  5443. // /
  5444. let j = i - 1;
  5445. let p;
  5446. // find first non-whitespace prev char
  5447. for (; j >= 0; j--) {
  5448. p = exp.charAt(j);
  5449. if (p !== ' ')
  5450. break;
  5451. }
  5452. if (!p || !validDivisionCharRE.test(p)) {
  5453. inRegex = true;
  5454. }
  5455. }
  5456. }
  5457. }
  5458. if (expression === undefined) {
  5459. expression = exp.slice(0, i).trim();
  5460. }
  5461. else if (lastFilterIndex !== 0) {
  5462. pushFilter();
  5463. }
  5464. function pushFilter() {
  5465. filters.push(exp.slice(lastFilterIndex, i).trim());
  5466. lastFilterIndex = i + 1;
  5467. }
  5468. if (filters.length) {
  5469. for (i = 0; i < filters.length; i++) {
  5470. expression = wrapFilter(expression, filters[i], context);
  5471. }
  5472. node.content = expression;
  5473. }
  5474. }
  5475. function wrapFilter(exp, filter, context) {
  5476. context.helper(RESOLVE_FILTER);
  5477. const i = filter.indexOf('(');
  5478. if (i < 0) {
  5479. context.filters.add(filter);
  5480. return `${toValidAssetId(filter, 'filter')}(${exp})`;
  5481. }
  5482. else {
  5483. const name = filter.slice(0, i);
  5484. const args = filter.slice(i + 1);
  5485. context.filters.add(name);
  5486. return `${toValidAssetId(name, 'filter')}(${exp}${args !== ')' ? ',' + args : args}`;
  5487. }
  5488. }
  5489. const seen$1 = new WeakSet();
  5490. const transformMemo = (node, context) => {
  5491. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  5492. const dir = findDir(node, 'memo');
  5493. if (!dir || seen$1.has(node)) {
  5494. return;
  5495. }
  5496. seen$1.add(node);
  5497. return () => {
  5498. const codegenNode = node.codegenNode ||
  5499. context.currentNode.codegenNode;
  5500. if (codegenNode && codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  5501. // non-component sub tree should be turned into a block
  5502. if (node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  5503. makeBlock(codegenNode, context);
  5504. }
  5505. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  5506. dir.exp,
  5507. createFunctionExpression(undefined, codegenNode),
  5508. `_cache`,
  5509. String(context.cached++)
  5510. ]);
  5511. }
  5512. };
  5513. }
  5514. };
  5515. function getBaseTransformPreset(prefixIdentifiers) {
  5516. return [
  5517. [
  5518. transformOnce,
  5519. transformIf,
  5520. transformMemo,
  5521. transformFor,
  5522. ...([transformFilter] ),
  5523. ...(prefixIdentifiers
  5524. ? [
  5525. // order is important
  5526. trackVForSlotScopes,
  5527. transformExpression
  5528. ]
  5529. : []),
  5530. transformSlotOutlet,
  5531. transformElement,
  5532. trackSlotScopes,
  5533. transformText
  5534. ],
  5535. {
  5536. on: transformOn,
  5537. bind: transformBind,
  5538. model: transformModel
  5539. }
  5540. ];
  5541. }
  5542. // we name it `baseCompile` so that higher order compilers like
  5543. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  5544. function baseCompile(template, options = {}) {
  5545. const onError = options.onError || defaultOnError;
  5546. const isModuleMode = options.mode === 'module';
  5547. const prefixIdentifiers = (options.prefixIdentifiers === true || isModuleMode);
  5548. if (!prefixIdentifiers && options.cacheHandlers) {
  5549. onError(createCompilerError(49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */));
  5550. }
  5551. if (options.scopeId && !isModuleMode) {
  5552. onError(createCompilerError(50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */));
  5553. }
  5554. const ast = shared.isString(template) ? baseParse(template, options) : template;
  5555. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  5556. if (options.isTS) {
  5557. const { expressionPlugins } = options;
  5558. if (!expressionPlugins || !expressionPlugins.includes('typescript')) {
  5559. options.expressionPlugins = [...(expressionPlugins || []), 'typescript'];
  5560. }
  5561. }
  5562. transform(ast, shared.extend({}, options, {
  5563. prefixIdentifiers,
  5564. nodeTransforms: [
  5565. ...nodeTransforms,
  5566. ...(options.nodeTransforms || []) // user transforms
  5567. ],
  5568. directiveTransforms: shared.extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  5569. )
  5570. }));
  5571. return generate(ast, shared.extend({}, options, {
  5572. prefixIdentifiers
  5573. }));
  5574. }
  5575. const noopDirectiveTransform = () => ({ props: [] });
  5576. exports.generateCodeFrame = shared.generateCodeFrame;
  5577. exports.BASE_TRANSITION = BASE_TRANSITION;
  5578. exports.CAMELIZE = CAMELIZE;
  5579. exports.CAPITALIZE = CAPITALIZE;
  5580. exports.CREATE_BLOCK = CREATE_BLOCK;
  5581. exports.CREATE_COMMENT = CREATE_COMMENT;
  5582. exports.CREATE_ELEMENT_BLOCK = CREATE_ELEMENT_BLOCK;
  5583. exports.CREATE_ELEMENT_VNODE = CREATE_ELEMENT_VNODE;
  5584. exports.CREATE_SLOTS = CREATE_SLOTS;
  5585. exports.CREATE_STATIC = CREATE_STATIC;
  5586. exports.CREATE_TEXT = CREATE_TEXT;
  5587. exports.CREATE_VNODE = CREATE_VNODE;
  5588. exports.FRAGMENT = FRAGMENT;
  5589. exports.GUARD_REACTIVE_PROPS = GUARD_REACTIVE_PROPS;
  5590. exports.IS_MEMO_SAME = IS_MEMO_SAME;
  5591. exports.IS_REF = IS_REF;
  5592. exports.KEEP_ALIVE = KEEP_ALIVE;
  5593. exports.MERGE_PROPS = MERGE_PROPS;
  5594. exports.NORMALIZE_CLASS = NORMALIZE_CLASS;
  5595. exports.NORMALIZE_PROPS = NORMALIZE_PROPS;
  5596. exports.NORMALIZE_STYLE = NORMALIZE_STYLE;
  5597. exports.OPEN_BLOCK = OPEN_BLOCK;
  5598. exports.POP_SCOPE_ID = POP_SCOPE_ID;
  5599. exports.PUSH_SCOPE_ID = PUSH_SCOPE_ID;
  5600. exports.RENDER_LIST = RENDER_LIST;
  5601. exports.RENDER_SLOT = RENDER_SLOT;
  5602. exports.RESOLVE_COMPONENT = RESOLVE_COMPONENT;
  5603. exports.RESOLVE_DIRECTIVE = RESOLVE_DIRECTIVE;
  5604. exports.RESOLVE_DYNAMIC_COMPONENT = RESOLVE_DYNAMIC_COMPONENT;
  5605. exports.RESOLVE_FILTER = RESOLVE_FILTER;
  5606. exports.SET_BLOCK_TRACKING = SET_BLOCK_TRACKING;
  5607. exports.SUSPENSE = SUSPENSE;
  5608. exports.TELEPORT = TELEPORT;
  5609. exports.TO_DISPLAY_STRING = TO_DISPLAY_STRING;
  5610. exports.TO_HANDLERS = TO_HANDLERS;
  5611. exports.TO_HANDLER_KEY = TO_HANDLER_KEY;
  5612. exports.UNREF = UNREF;
  5613. exports.WITH_CTX = WITH_CTX;
  5614. exports.WITH_DIRECTIVES = WITH_DIRECTIVES;
  5615. exports.WITH_MEMO = WITH_MEMO;
  5616. exports.advancePositionWithClone = advancePositionWithClone;
  5617. exports.advancePositionWithMutation = advancePositionWithMutation;
  5618. exports.assert = assert;
  5619. exports.baseCompile = baseCompile;
  5620. exports.baseParse = baseParse;
  5621. exports.buildDirectiveArgs = buildDirectiveArgs;
  5622. exports.buildProps = buildProps;
  5623. exports.buildSlots = buildSlots;
  5624. exports.checkCompatEnabled = checkCompatEnabled;
  5625. exports.createArrayExpression = createArrayExpression;
  5626. exports.createAssignmentExpression = createAssignmentExpression;
  5627. exports.createBlockStatement = createBlockStatement;
  5628. exports.createCacheExpression = createCacheExpression;
  5629. exports.createCallExpression = createCallExpression;
  5630. exports.createCompilerError = createCompilerError;
  5631. exports.createCompoundExpression = createCompoundExpression;
  5632. exports.createConditionalExpression = createConditionalExpression;
  5633. exports.createForLoopParams = createForLoopParams;
  5634. exports.createFunctionExpression = createFunctionExpression;
  5635. exports.createIfStatement = createIfStatement;
  5636. exports.createInterpolation = createInterpolation;
  5637. exports.createObjectExpression = createObjectExpression;
  5638. exports.createObjectProperty = createObjectProperty;
  5639. exports.createReturnStatement = createReturnStatement;
  5640. exports.createRoot = createRoot;
  5641. exports.createSequenceExpression = createSequenceExpression;
  5642. exports.createSimpleExpression = createSimpleExpression;
  5643. exports.createStructuralDirectiveTransform = createStructuralDirectiveTransform;
  5644. exports.createTemplateLiteral = createTemplateLiteral;
  5645. exports.createTransformContext = createTransformContext;
  5646. exports.createVNodeCall = createVNodeCall;
  5647. exports.extractIdentifiers = extractIdentifiers;
  5648. exports.findDir = findDir;
  5649. exports.findProp = findProp;
  5650. exports.generate = generate;
  5651. exports.getBaseTransformPreset = getBaseTransformPreset;
  5652. exports.getConstantType = getConstantType;
  5653. exports.getInnerRange = getInnerRange;
  5654. exports.getMemoedVNodeCall = getMemoedVNodeCall;
  5655. exports.getVNodeBlockHelper = getVNodeBlockHelper;
  5656. exports.getVNodeHelper = getVNodeHelper;
  5657. exports.hasDynamicKeyVBind = hasDynamicKeyVBind;
  5658. exports.hasScopeRef = hasScopeRef;
  5659. exports.helperNameMap = helperNameMap;
  5660. exports.injectProp = injectProp;
  5661. exports.isBuiltInType = isBuiltInType;
  5662. exports.isCoreComponent = isCoreComponent;
  5663. exports.isFunctionType = isFunctionType;
  5664. exports.isInDestructureAssignment = isInDestructureAssignment;
  5665. exports.isMemberExpression = isMemberExpression;
  5666. exports.isMemberExpressionBrowser = isMemberExpressionBrowser;
  5667. exports.isMemberExpressionNode = isMemberExpressionNode;
  5668. exports.isReferencedIdentifier = isReferencedIdentifier;
  5669. exports.isSimpleIdentifier = isSimpleIdentifier;
  5670. exports.isSlotOutlet = isSlotOutlet;
  5671. exports.isStaticArgOf = isStaticArgOf;
  5672. exports.isStaticExp = isStaticExp;
  5673. exports.isStaticProperty = isStaticProperty;
  5674. exports.isStaticPropertyKey = isStaticPropertyKey;
  5675. exports.isTemplateNode = isTemplateNode;
  5676. exports.isText = isText;
  5677. exports.isVSlot = isVSlot;
  5678. exports.locStub = locStub;
  5679. exports.makeBlock = makeBlock;
  5680. exports.noopDirectiveTransform = noopDirectiveTransform;
  5681. exports.processExpression = processExpression;
  5682. exports.processFor = processFor;
  5683. exports.processIf = processIf;
  5684. exports.processSlotOutlet = processSlotOutlet;
  5685. exports.registerRuntimeHelpers = registerRuntimeHelpers;
  5686. exports.resolveComponentType = resolveComponentType;
  5687. exports.stringifyExpression = stringifyExpression;
  5688. exports.toValidAssetId = toValidAssetId;
  5689. exports.trackSlotScopes = trackSlotScopes;
  5690. exports.trackVForSlotScopes = trackVForSlotScopes;
  5691. exports.transform = transform;
  5692. exports.transformBind = transformBind;
  5693. exports.transformElement = transformElement;
  5694. exports.transformExpression = transformExpression;
  5695. exports.transformModel = transformModel;
  5696. exports.transformOn = transformOn;
  5697. exports.traverseNode = traverseNode;
  5698. exports.walkBlockDeclarations = walkBlockDeclarations;
  5699. exports.walkFunctionParams = walkFunctionParams;
  5700. exports.walkIdentifiers = walkIdentifiers;
  5701. exports.warnDeprecation = warnDeprecation;