compiler-dom.global.js 224 KB

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