compiler-dom.global.js 175 KB

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