compiler-core.cjs.js 228 KB

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