compiler-dom.global.js 220 KB

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