compiler-dom.esm-browser.js 210 KB

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