compiler-dom.esm-browser.js 159 KB

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