compiler-core.cjs.js 228 KB

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