compiler-core.cjs.prod.js 221 KB

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