compiler-dom.esm-browser.js 216 KB

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