compiler-core.esm-bundler.js 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919
  1. import { isString, hyphenate, extend, isObject, isArray, NO, makeMap, isSymbol, NOOP, PatchFlagNames, isGloballyWhitelisted, babelParserDefaultPlugins, hasOwn, isOn, isReservedProp, toHandlerKey, camelize } from '@vue/shared';
  2. export { generateCodeFrame } from '@vue/shared';
  3. import { parse } from '@babel/parser';
  4. import { walk as walk$1 } from 'estree-walker';
  5. function defaultOnError(error) {
  6. throw error;
  7. }
  8. function createCompilerError(code, loc, messages, additionalMessage) {
  9. const msg = (process.env.NODE_ENV !== 'production') || !true
  10. ? (messages || errorMessages)[code] + (additionalMessage || ``)
  11. : code;
  12. const error = new SyntaxError(String(msg));
  13. error.code = code;
  14. error.loc = loc;
  15. return error;
  16. }
  17. const errorMessages = {
  18. // parse errors
  19. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  20. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  21. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  22. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  23. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  24. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  25. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  26. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  27. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  28. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  29. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  30. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  31. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  32. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  33. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  34. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  35. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  36. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  37. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  38. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  39. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  40. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  41. // Vue-specific parse errors
  42. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  43. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  44. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  45. [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  46. 'Note that dynamic directive argument cannot contain spaces.',
  47. // transform errors
  48. [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  49. [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  50. [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
  51. [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  52. [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  53. [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  54. [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  55. [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  56. [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  57. [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  58. `When there are multiple named slots, all slots should use <template> ` +
  59. `syntax to avoid scope ambiguity.`,
  60. [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  61. [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  62. `default slot. These children will be ignored.`,
  63. [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  64. [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  65. [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  66. [42 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  67. [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  68. [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  69. // generic errors
  70. [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  71. [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  72. [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  73. [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
  74. };
  75. const FRAGMENT = Symbol((process.env.NODE_ENV !== 'production') ? `Fragment` : ``);
  76. const TELEPORT = Symbol((process.env.NODE_ENV !== 'production') ? `Teleport` : ``);
  77. const SUSPENSE = Symbol((process.env.NODE_ENV !== 'production') ? `Suspense` : ``);
  78. const KEEP_ALIVE = Symbol((process.env.NODE_ENV !== 'production') ? `KeepAlive` : ``);
  79. const BASE_TRANSITION = Symbol((process.env.NODE_ENV !== 'production') ? `BaseTransition` : ``);
  80. const OPEN_BLOCK = Symbol((process.env.NODE_ENV !== 'production') ? `openBlock` : ``);
  81. const CREATE_BLOCK = Symbol((process.env.NODE_ENV !== 'production') ? `createBlock` : ``);
  82. const CREATE_VNODE = Symbol((process.env.NODE_ENV !== 'production') ? `createVNode` : ``);
  83. const CREATE_COMMENT = Symbol((process.env.NODE_ENV !== 'production') ? `createCommentVNode` : ``);
  84. const CREATE_TEXT = Symbol((process.env.NODE_ENV !== 'production') ? `createTextVNode` : ``);
  85. const CREATE_STATIC = Symbol((process.env.NODE_ENV !== 'production') ? `createStaticVNode` : ``);
  86. const RESOLVE_COMPONENT = Symbol((process.env.NODE_ENV !== 'production') ? `resolveComponent` : ``);
  87. const RESOLVE_DYNAMIC_COMPONENT = Symbol((process.env.NODE_ENV !== 'production') ? `resolveDynamicComponent` : ``);
  88. const RESOLVE_DIRECTIVE = Symbol((process.env.NODE_ENV !== 'production') ? `resolveDirective` : ``);
  89. const WITH_DIRECTIVES = Symbol((process.env.NODE_ENV !== 'production') ? `withDirectives` : ``);
  90. const RENDER_LIST = Symbol((process.env.NODE_ENV !== 'production') ? `renderList` : ``);
  91. const RENDER_SLOT = Symbol((process.env.NODE_ENV !== 'production') ? `renderSlot` : ``);
  92. const CREATE_SLOTS = Symbol((process.env.NODE_ENV !== 'production') ? `createSlots` : ``);
  93. const TO_DISPLAY_STRING = Symbol((process.env.NODE_ENV !== 'production') ? `toDisplayString` : ``);
  94. const MERGE_PROPS = Symbol((process.env.NODE_ENV !== 'production') ? `mergeProps` : ``);
  95. const TO_HANDLERS = Symbol((process.env.NODE_ENV !== 'production') ? `toHandlers` : ``);
  96. const CAMELIZE = Symbol((process.env.NODE_ENV !== 'production') ? `camelize` : ``);
  97. const CAPITALIZE = Symbol((process.env.NODE_ENV !== 'production') ? `capitalize` : ``);
  98. const TO_HANDLER_KEY = Symbol((process.env.NODE_ENV !== 'production') ? `toHandlerKey` : ``);
  99. const SET_BLOCK_TRACKING = Symbol((process.env.NODE_ENV !== 'production') ? `setBlockTracking` : ``);
  100. const PUSH_SCOPE_ID = Symbol((process.env.NODE_ENV !== 'production') ? `pushScopeId` : ``);
  101. const POP_SCOPE_ID = Symbol((process.env.NODE_ENV !== 'production') ? `popScopeId` : ``);
  102. const WITH_SCOPE_ID = Symbol((process.env.NODE_ENV !== 'production') ? `withScopeId` : ``);
  103. const WITH_CTX = Symbol((process.env.NODE_ENV !== 'production') ? `withCtx` : ``);
  104. // Name mapping for runtime helpers that need to be imported from 'vue' in
  105. // generated code. Make sure these are correctly exported in the runtime!
  106. // Using `any` here because TS doesn't allow symbols as index type.
  107. const helperNameMap = {
  108. [FRAGMENT]: `Fragment`,
  109. [TELEPORT]: `Teleport`,
  110. [SUSPENSE]: `Suspense`,
  111. [KEEP_ALIVE]: `KeepAlive`,
  112. [BASE_TRANSITION]: `BaseTransition`,
  113. [OPEN_BLOCK]: `openBlock`,
  114. [CREATE_BLOCK]: `createBlock`,
  115. [CREATE_VNODE]: `createVNode`,
  116. [CREATE_COMMENT]: `createCommentVNode`,
  117. [CREATE_TEXT]: `createTextVNode`,
  118. [CREATE_STATIC]: `createStaticVNode`,
  119. [RESOLVE_COMPONENT]: `resolveComponent`,
  120. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  121. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  122. [WITH_DIRECTIVES]: `withDirectives`,
  123. [RENDER_LIST]: `renderList`,
  124. [RENDER_SLOT]: `renderSlot`,
  125. [CREATE_SLOTS]: `createSlots`,
  126. [TO_DISPLAY_STRING]: `toDisplayString`,
  127. [MERGE_PROPS]: `mergeProps`,
  128. [TO_HANDLERS]: `toHandlers`,
  129. [CAMELIZE]: `camelize`,
  130. [CAPITALIZE]: `capitalize`,
  131. [TO_HANDLER_KEY]: `toHandlerKey`,
  132. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  133. [PUSH_SCOPE_ID]: `pushScopeId`,
  134. [POP_SCOPE_ID]: `popScopeId`,
  135. [WITH_SCOPE_ID]: `withScopeId`,
  136. [WITH_CTX]: `withCtx`
  137. };
  138. function registerRuntimeHelpers(helpers) {
  139. Object.getOwnPropertySymbols(helpers).forEach(s => {
  140. helperNameMap[s] = helpers[s];
  141. });
  142. }
  143. // AST Utilities ---------------------------------------------------------------
  144. // Some expressions, e.g. sequence and conditional expressions, are never
  145. // associated with template nodes, so their source locations are just a stub.
  146. // Container types like CompoundExpression also don't need a real location.
  147. const locStub = {
  148. source: '',
  149. start: { line: 1, column: 1, offset: 0 },
  150. end: { line: 1, column: 1, offset: 0 }
  151. };
  152. function createRoot(children, loc = locStub) {
  153. return {
  154. type: 0 /* ROOT */,
  155. children,
  156. helpers: [],
  157. components: [],
  158. directives: [],
  159. hoists: [],
  160. imports: [],
  161. cached: 0,
  162. temps: 0,
  163. codegenNode: undefined,
  164. loc
  165. };
  166. }
  167. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
  168. if (context) {
  169. if (isBlock) {
  170. context.helper(OPEN_BLOCK);
  171. context.helper(CREATE_BLOCK);
  172. }
  173. else {
  174. context.helper(CREATE_VNODE);
  175. }
  176. if (directives) {
  177. context.helper(WITH_DIRECTIVES);
  178. }
  179. }
  180. return {
  181. type: 13 /* VNODE_CALL */,
  182. tag,
  183. props,
  184. children,
  185. patchFlag,
  186. dynamicProps,
  187. directives,
  188. isBlock,
  189. disableTracking,
  190. loc
  191. };
  192. }
  193. function createArrayExpression(elements, loc = locStub) {
  194. return {
  195. type: 17 /* JS_ARRAY_EXPRESSION */,
  196. loc,
  197. elements
  198. };
  199. }
  200. function createObjectExpression(properties, loc = locStub) {
  201. return {
  202. type: 15 /* JS_OBJECT_EXPRESSION */,
  203. loc,
  204. properties
  205. };
  206. }
  207. function createObjectProperty(key, value) {
  208. return {
  209. type: 16 /* JS_PROPERTY */,
  210. loc: locStub,
  211. key: isString(key) ? createSimpleExpression(key, true) : key,
  212. value
  213. };
  214. }
  215. function createSimpleExpression(content, isStatic, loc = locStub, isConstant = false) {
  216. return {
  217. type: 4 /* SIMPLE_EXPRESSION */,
  218. loc,
  219. isConstant,
  220. content,
  221. isStatic
  222. };
  223. }
  224. function createInterpolation(content, loc) {
  225. return {
  226. type: 5 /* INTERPOLATION */,
  227. loc,
  228. content: isString(content)
  229. ? createSimpleExpression(content, false, loc)
  230. : content
  231. };
  232. }
  233. function createCompoundExpression(children, loc = locStub) {
  234. return {
  235. type: 8 /* COMPOUND_EXPRESSION */,
  236. loc,
  237. children
  238. };
  239. }
  240. function createCallExpression(callee, args = [], loc = locStub) {
  241. return {
  242. type: 14 /* JS_CALL_EXPRESSION */,
  243. loc,
  244. callee,
  245. arguments: args
  246. };
  247. }
  248. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  249. return {
  250. type: 18 /* JS_FUNCTION_EXPRESSION */,
  251. params,
  252. returns,
  253. newline,
  254. isSlot,
  255. loc
  256. };
  257. }
  258. function createConditionalExpression(test, consequent, alternate, newline = true) {
  259. return {
  260. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  261. test,
  262. consequent,
  263. alternate,
  264. newline,
  265. loc: locStub
  266. };
  267. }
  268. function createCacheExpression(index, value, isVNode = false) {
  269. return {
  270. type: 20 /* JS_CACHE_EXPRESSION */,
  271. index,
  272. value,
  273. isVNode,
  274. loc: locStub
  275. };
  276. }
  277. function createBlockStatement(body) {
  278. return {
  279. type: 21 /* JS_BLOCK_STATEMENT */,
  280. body,
  281. loc: locStub
  282. };
  283. }
  284. function createTemplateLiteral(elements) {
  285. return {
  286. type: 22 /* JS_TEMPLATE_LITERAL */,
  287. elements,
  288. loc: locStub
  289. };
  290. }
  291. function createIfStatement(test, consequent, alternate) {
  292. return {
  293. type: 23 /* JS_IF_STATEMENT */,
  294. test,
  295. consequent,
  296. alternate,
  297. loc: locStub
  298. };
  299. }
  300. function createAssignmentExpression(left, right) {
  301. return {
  302. type: 24 /* JS_ASSIGNMENT_EXPRESSION */,
  303. left,
  304. right,
  305. loc: locStub
  306. };
  307. }
  308. function createSequenceExpression(expressions) {
  309. return {
  310. type: 25 /* JS_SEQUENCE_EXPRESSION */,
  311. expressions,
  312. loc: locStub
  313. };
  314. }
  315. function createReturnStatement(returns) {
  316. return {
  317. type: 26 /* JS_RETURN_STATEMENT */,
  318. returns,
  319. loc: locStub
  320. };
  321. }
  322. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  323. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  324. function isCoreComponent(tag) {
  325. if (isBuiltInType(tag, 'Teleport')) {
  326. return TELEPORT;
  327. }
  328. else if (isBuiltInType(tag, 'Suspense')) {
  329. return SUSPENSE;
  330. }
  331. else if (isBuiltInType(tag, 'KeepAlive')) {
  332. return KEEP_ALIVE;
  333. }
  334. else if (isBuiltInType(tag, 'BaseTransition')) {
  335. return BASE_TRANSITION;
  336. }
  337. }
  338. const nonIdentifierRE = /^\d|[^\$\w]/;
  339. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  340. const memberExpRE = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]]+\])*$/;
  341. const isMemberExpression = (path) => {
  342. if (!path)
  343. return false;
  344. return memberExpRE.test(path.trim());
  345. };
  346. function getInnerRange(loc, offset, length) {
  347. const source = loc.source.substr(offset, length);
  348. const newLoc = {
  349. source,
  350. start: advancePositionWithClone(loc.start, loc.source, offset),
  351. end: loc.end
  352. };
  353. if (length != null) {
  354. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  355. }
  356. return newLoc;
  357. }
  358. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  359. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  360. }
  361. // advance by mutation without cloning (for performance reasons), since this
  362. // gets called a lot in the parser
  363. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  364. let linesCount = 0;
  365. let lastNewLinePos = -1;
  366. for (let i = 0; i < numberOfCharacters; i++) {
  367. if (source.charCodeAt(i) === 10 /* newline char code */) {
  368. linesCount++;
  369. lastNewLinePos = i;
  370. }
  371. }
  372. pos.offset += numberOfCharacters;
  373. pos.line += linesCount;
  374. pos.column =
  375. lastNewLinePos === -1
  376. ? pos.column + numberOfCharacters
  377. : numberOfCharacters - lastNewLinePos;
  378. return pos;
  379. }
  380. function assert(condition, msg) {
  381. /* istanbul ignore if */
  382. if (!condition) {
  383. throw new Error(msg || `unexpected compiler condition`);
  384. }
  385. }
  386. function findDir(node, name, allowEmpty = false) {
  387. for (let i = 0; i < node.props.length; i++) {
  388. const p = node.props[i];
  389. if (p.type === 7 /* DIRECTIVE */ &&
  390. (allowEmpty || p.exp) &&
  391. (isString(name) ? p.name === name : name.test(p.name))) {
  392. return p;
  393. }
  394. }
  395. }
  396. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  397. for (let i = 0; i < node.props.length; i++) {
  398. const p = node.props[i];
  399. if (p.type === 6 /* ATTRIBUTE */) {
  400. if (dynamicOnly)
  401. continue;
  402. if (p.name === name && (p.value || allowEmpty)) {
  403. return p;
  404. }
  405. }
  406. else if (p.name === 'bind' &&
  407. (p.exp || allowEmpty) &&
  408. isBindKey(p.arg, name)) {
  409. return p;
  410. }
  411. }
  412. }
  413. function isBindKey(arg, name) {
  414. return !!(arg && isStaticExp(arg) && arg.content === name);
  415. }
  416. function hasDynamicKeyVBind(node) {
  417. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  418. p.name === 'bind' &&
  419. (!p.arg || // v-bind="obj"
  420. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  421. !p.arg.isStatic) // v-bind:[foo]
  422. );
  423. }
  424. function isText(node) {
  425. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  426. }
  427. function isVSlot(p) {
  428. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  429. }
  430. function isTemplateNode(node) {
  431. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  432. }
  433. function isSlotOutlet(node) {
  434. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  435. }
  436. function injectProp(node, prop, context) {
  437. let propsWithInjection;
  438. const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  439. if (props == null || isString(props)) {
  440. propsWithInjection = createObjectExpression([prop]);
  441. }
  442. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  443. // merged props... add ours
  444. // only inject key to object literal if it's the first argument so that
  445. // if doesn't override user provided keys
  446. const first = props.arguments[0];
  447. if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  448. first.properties.unshift(prop);
  449. }
  450. else {
  451. if (props.callee === TO_HANDLERS) {
  452. // #2366
  453. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  454. createObjectExpression([prop]),
  455. props
  456. ]);
  457. }
  458. else {
  459. props.arguments.unshift(createObjectExpression([prop]));
  460. }
  461. }
  462. !propsWithInjection && (propsWithInjection = props);
  463. }
  464. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  465. let alreadyExists = false;
  466. // check existing key to avoid overriding user provided keys
  467. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  468. const propKeyName = prop.key.content;
  469. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  470. p.key.content === propKeyName);
  471. }
  472. if (!alreadyExists) {
  473. props.properties.unshift(prop);
  474. }
  475. propsWithInjection = props;
  476. }
  477. else {
  478. // single v-bind with expression, return a merged replacement
  479. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  480. createObjectExpression([prop]),
  481. props
  482. ]);
  483. }
  484. if (node.type === 13 /* VNODE_CALL */) {
  485. node.props = propsWithInjection;
  486. }
  487. else {
  488. node.arguments[2] = propsWithInjection;
  489. }
  490. }
  491. function toValidAssetId(name, type) {
  492. return `_${type}_${name.replace(/[^\w]/g, '_')}`;
  493. }
  494. // Check if a node contains expressions that reference current context scope ids
  495. function hasScopeRef(node, ids) {
  496. if (!node || Object.keys(ids).length === 0) {
  497. return false;
  498. }
  499. switch (node.type) {
  500. case 1 /* ELEMENT */:
  501. for (let i = 0; i < node.props.length; i++) {
  502. const p = node.props[i];
  503. if (p.type === 7 /* DIRECTIVE */ &&
  504. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  505. return true;
  506. }
  507. }
  508. return node.children.some(c => hasScopeRef(c, ids));
  509. case 11 /* FOR */:
  510. if (hasScopeRef(node.source, ids)) {
  511. return true;
  512. }
  513. return node.children.some(c => hasScopeRef(c, ids));
  514. case 9 /* IF */:
  515. return node.branches.some(b => hasScopeRef(b, ids));
  516. case 10 /* IF_BRANCH */:
  517. if (hasScopeRef(node.condition, ids)) {
  518. return true;
  519. }
  520. return node.children.some(c => hasScopeRef(c, ids));
  521. case 4 /* SIMPLE_EXPRESSION */:
  522. return (!node.isStatic &&
  523. isSimpleIdentifier(node.content) &&
  524. !!ids[node.content]);
  525. case 8 /* COMPOUND_EXPRESSION */:
  526. return node.children.some(c => isObject(c) && hasScopeRef(c, ids));
  527. case 5 /* INTERPOLATION */:
  528. case 12 /* TEXT_CALL */:
  529. return hasScopeRef(node.content, ids);
  530. case 2 /* TEXT */:
  531. case 3 /* COMMENT */:
  532. return false;
  533. default:
  534. if ((process.env.NODE_ENV !== 'production')) ;
  535. return false;
  536. }
  537. }
  538. // The default decoder only provides escapes for characters reserved as part of
  539. // the template syntax, and is only used if the custom renderer did not provide
  540. // a platform-specific decoder.
  541. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  542. const decodeMap = {
  543. gt: '>',
  544. lt: '<',
  545. amp: '&',
  546. apos: "'",
  547. quot: '"'
  548. };
  549. const defaultParserOptions = {
  550. delimiters: [`{{`, `}}`],
  551. getNamespace: () => 0 /* HTML */,
  552. getTextMode: () => 0 /* DATA */,
  553. isVoidTag: NO,
  554. isPreTag: NO,
  555. isCustomElement: NO,
  556. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  557. onError: defaultOnError,
  558. comments: false
  559. };
  560. function baseParse(content, options = {}) {
  561. const context = createParserContext(content, options);
  562. const start = getCursor(context);
  563. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  564. }
  565. function createParserContext(content, rawOptions) {
  566. const options = extend({}, defaultParserOptions);
  567. for (const key in rawOptions) {
  568. // @ts-ignore
  569. options[key] = rawOptions[key] || defaultParserOptions[key];
  570. }
  571. return {
  572. options,
  573. column: 1,
  574. line: 1,
  575. offset: 0,
  576. originalSource: content,
  577. source: content,
  578. inPre: false,
  579. inVPre: false
  580. };
  581. }
  582. function parseChildren(context, mode, ancestors) {
  583. const parent = last(ancestors);
  584. const ns = parent ? parent.ns : 0 /* HTML */;
  585. const nodes = [];
  586. while (!isEnd(context, mode, ancestors)) {
  587. const s = context.source;
  588. let node = undefined;
  589. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  590. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  591. // '{{'
  592. node = parseInterpolation(context, mode);
  593. }
  594. else if (mode === 0 /* DATA */ && s[0] === '<') {
  595. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  596. if (s.length === 1) {
  597. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  598. }
  599. else if (s[1] === '!') {
  600. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  601. if (startsWith(s, '<!--')) {
  602. node = parseComment(context);
  603. }
  604. else if (startsWith(s, '<!DOCTYPE')) {
  605. // Ignore DOCTYPE by a limitation.
  606. node = parseBogusComment(context);
  607. }
  608. else if (startsWith(s, '<![CDATA[')) {
  609. if (ns !== 0 /* HTML */) {
  610. node = parseCDATA(context, ancestors);
  611. }
  612. else {
  613. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  614. node = parseBogusComment(context);
  615. }
  616. }
  617. else {
  618. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  619. node = parseBogusComment(context);
  620. }
  621. }
  622. else if (s[1] === '/') {
  623. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  624. if (s.length === 2) {
  625. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  626. }
  627. else if (s[2] === '>') {
  628. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  629. advanceBy(context, 3);
  630. continue;
  631. }
  632. else if (/[a-z]/i.test(s[2])) {
  633. emitError(context, 23 /* X_INVALID_END_TAG */);
  634. parseTag(context, 1 /* End */, parent);
  635. continue;
  636. }
  637. else {
  638. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  639. node = parseBogusComment(context);
  640. }
  641. }
  642. else if (/[a-z]/i.test(s[1])) {
  643. node = parseElement(context, ancestors);
  644. }
  645. else if (s[1] === '?') {
  646. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  647. node = parseBogusComment(context);
  648. }
  649. else {
  650. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  651. }
  652. }
  653. }
  654. if (!node) {
  655. node = parseText(context, mode);
  656. }
  657. if (isArray(node)) {
  658. for (let i = 0; i < node.length; i++) {
  659. pushNode(nodes, node[i]);
  660. }
  661. }
  662. else {
  663. pushNode(nodes, node);
  664. }
  665. }
  666. // Whitespace management for more efficient output
  667. // (same as v2 whitespace: 'condense')
  668. let removedWhitespace = false;
  669. if (mode !== 2 /* RAWTEXT */) {
  670. for (let i = 0; i < nodes.length; i++) {
  671. const node = nodes[i];
  672. if (!context.inPre && node.type === 2 /* TEXT */) {
  673. if (!/[^\t\r\n\f ]/.test(node.content)) {
  674. const prev = nodes[i - 1];
  675. const next = nodes[i + 1];
  676. // If:
  677. // - the whitespace is the first or last node, or:
  678. // - the whitespace is adjacent to a comment, or:
  679. // - the whitespace is between two elements AND contains newline
  680. // Then the whitespace is ignored.
  681. if (!prev ||
  682. !next ||
  683. prev.type === 3 /* COMMENT */ ||
  684. next.type === 3 /* COMMENT */ ||
  685. (prev.type === 1 /* ELEMENT */ &&
  686. next.type === 1 /* ELEMENT */ &&
  687. /[\r\n]/.test(node.content))) {
  688. removedWhitespace = true;
  689. nodes[i] = null;
  690. }
  691. else {
  692. // Otherwise, condensed consecutive whitespace inside the text
  693. // down to a single space
  694. node.content = ' ';
  695. }
  696. }
  697. else {
  698. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  699. }
  700. }
  701. // also remove comment nodes in prod by default
  702. if (!(process.env.NODE_ENV !== 'production') &&
  703. node.type === 3 /* COMMENT */ &&
  704. !context.options.comments) {
  705. removedWhitespace = true;
  706. nodes[i] = null;
  707. }
  708. }
  709. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  710. // remove leading newline per html spec
  711. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  712. const first = nodes[0];
  713. if (first && first.type === 2 /* TEXT */) {
  714. first.content = first.content.replace(/^\r?\n/, '');
  715. }
  716. }
  717. }
  718. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  719. }
  720. function pushNode(nodes, node) {
  721. if (node.type === 2 /* TEXT */) {
  722. const prev = last(nodes);
  723. // Merge if both this and the previous node are text and those are
  724. // consecutive. This happens for cases like "a < b".
  725. if (prev &&
  726. prev.type === 2 /* TEXT */ &&
  727. prev.loc.end.offset === node.loc.start.offset) {
  728. prev.content += node.content;
  729. prev.loc.end = node.loc.end;
  730. prev.loc.source += node.loc.source;
  731. return;
  732. }
  733. }
  734. nodes.push(node);
  735. }
  736. function parseCDATA(context, ancestors) {
  737. advanceBy(context, 9);
  738. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  739. if (context.source.length === 0) {
  740. emitError(context, 6 /* EOF_IN_CDATA */);
  741. }
  742. else {
  743. advanceBy(context, 3);
  744. }
  745. return nodes;
  746. }
  747. function parseComment(context) {
  748. const start = getCursor(context);
  749. let content;
  750. // Regular comment.
  751. const match = /--(\!)?>/.exec(context.source);
  752. if (!match) {
  753. content = context.source.slice(4);
  754. advanceBy(context, context.source.length);
  755. emitError(context, 7 /* EOF_IN_COMMENT */);
  756. }
  757. else {
  758. if (match.index <= 3) {
  759. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  760. }
  761. if (match[1]) {
  762. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  763. }
  764. content = context.source.slice(4, match.index);
  765. // Advancing with reporting nested comments.
  766. const s = context.source.slice(0, match.index);
  767. let prevIndex = 1, nestedIndex = 0;
  768. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  769. advanceBy(context, nestedIndex - prevIndex + 1);
  770. if (nestedIndex + 4 < s.length) {
  771. emitError(context, 16 /* NESTED_COMMENT */);
  772. }
  773. prevIndex = nestedIndex + 1;
  774. }
  775. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  776. }
  777. return {
  778. type: 3 /* COMMENT */,
  779. content,
  780. loc: getSelection(context, start)
  781. };
  782. }
  783. function parseBogusComment(context) {
  784. const start = getCursor(context);
  785. const contentStart = context.source[1] === '?' ? 1 : 2;
  786. let content;
  787. const closeIndex = context.source.indexOf('>');
  788. if (closeIndex === -1) {
  789. content = context.source.slice(contentStart);
  790. advanceBy(context, context.source.length);
  791. }
  792. else {
  793. content = context.source.slice(contentStart, closeIndex);
  794. advanceBy(context, closeIndex + 1);
  795. }
  796. return {
  797. type: 3 /* COMMENT */,
  798. content,
  799. loc: getSelection(context, start)
  800. };
  801. }
  802. function parseElement(context, ancestors) {
  803. // Start tag.
  804. const wasInPre = context.inPre;
  805. const wasInVPre = context.inVPre;
  806. const parent = last(ancestors);
  807. const element = parseTag(context, 0 /* Start */, parent);
  808. const isPreBoundary = context.inPre && !wasInPre;
  809. const isVPreBoundary = context.inVPre && !wasInVPre;
  810. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  811. return element;
  812. }
  813. // Children.
  814. ancestors.push(element);
  815. const mode = context.options.getTextMode(element, parent);
  816. const children = parseChildren(context, mode, ancestors);
  817. ancestors.pop();
  818. element.children = children;
  819. // End tag.
  820. if (startsWithEndTagOpen(context.source, element.tag)) {
  821. parseTag(context, 1 /* End */, parent);
  822. }
  823. else {
  824. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  825. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  826. const first = children[0];
  827. if (first && startsWith(first.loc.source, '<!--')) {
  828. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  829. }
  830. }
  831. }
  832. element.loc = getSelection(context, element.loc.start);
  833. if (isPreBoundary) {
  834. context.inPre = false;
  835. }
  836. if (isVPreBoundary) {
  837. context.inVPre = false;
  838. }
  839. return element;
  840. }
  841. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  842. /**
  843. * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
  844. */
  845. function parseTag(context, type, parent) {
  846. // Tag open.
  847. const start = getCursor(context);
  848. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  849. const tag = match[1];
  850. const ns = context.options.getNamespace(tag, parent);
  851. advanceBy(context, match[0].length);
  852. advanceSpaces(context);
  853. // save current state in case we need to re-parse attributes with v-pre
  854. const cursor = getCursor(context);
  855. const currentSource = context.source;
  856. // Attributes.
  857. let props = parseAttributes(context, type);
  858. // check <pre> tag
  859. if (context.options.isPreTag(tag)) {
  860. context.inPre = true;
  861. }
  862. // check v-pre
  863. if (!context.inVPre &&
  864. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  865. context.inVPre = true;
  866. // reset context
  867. extend(context, cursor);
  868. context.source = currentSource;
  869. // re-parse attrs and filter out v-pre itself
  870. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  871. }
  872. // Tag close.
  873. let isSelfClosing = false;
  874. if (context.source.length === 0) {
  875. emitError(context, 9 /* EOF_IN_TAG */);
  876. }
  877. else {
  878. isSelfClosing = startsWith(context.source, '/>');
  879. if (type === 1 /* End */ && isSelfClosing) {
  880. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  881. }
  882. advanceBy(context, isSelfClosing ? 2 : 1);
  883. }
  884. let tagType = 0 /* ELEMENT */;
  885. const options = context.options;
  886. if (!context.inVPre && !options.isCustomElement(tag)) {
  887. const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
  888. if (options.isNativeTag && !hasVIs) {
  889. if (!options.isNativeTag(tag))
  890. tagType = 1 /* COMPONENT */;
  891. }
  892. else if (hasVIs ||
  893. isCoreComponent(tag) ||
  894. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  895. /^[A-Z]/.test(tag) ||
  896. tag === 'component') {
  897. tagType = 1 /* COMPONENT */;
  898. }
  899. if (tag === 'slot') {
  900. tagType = 2 /* SLOT */;
  901. }
  902. else if (tag === 'template' &&
  903. props.some(p => {
  904. return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
  905. })) {
  906. tagType = 3 /* TEMPLATE */;
  907. }
  908. }
  909. return {
  910. type: 1 /* ELEMENT */,
  911. ns,
  912. tag,
  913. tagType,
  914. props,
  915. isSelfClosing,
  916. children: [],
  917. loc: getSelection(context, start),
  918. codegenNode: undefined // to be created during transform phase
  919. };
  920. }
  921. function parseAttributes(context, type) {
  922. const props = [];
  923. const attributeNames = new Set();
  924. while (context.source.length > 0 &&
  925. !startsWith(context.source, '>') &&
  926. !startsWith(context.source, '/>')) {
  927. if (startsWith(context.source, '/')) {
  928. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  929. advanceBy(context, 1);
  930. advanceSpaces(context);
  931. continue;
  932. }
  933. if (type === 1 /* End */) {
  934. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  935. }
  936. const attr = parseAttribute(context, attributeNames);
  937. if (type === 0 /* Start */) {
  938. props.push(attr);
  939. }
  940. if (/^[^\t\r\n\f />]/.test(context.source)) {
  941. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  942. }
  943. advanceSpaces(context);
  944. }
  945. return props;
  946. }
  947. function parseAttribute(context, nameSet) {
  948. // Name.
  949. const start = getCursor(context);
  950. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  951. const name = match[0];
  952. if (nameSet.has(name)) {
  953. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  954. }
  955. nameSet.add(name);
  956. if (name[0] === '=') {
  957. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  958. }
  959. {
  960. const pattern = /["'<]/g;
  961. let m;
  962. while ((m = pattern.exec(name))) {
  963. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  964. }
  965. }
  966. advanceBy(context, name.length);
  967. // Value
  968. let value = undefined;
  969. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  970. advanceSpaces(context);
  971. advanceBy(context, 1);
  972. advanceSpaces(context);
  973. value = parseAttributeValue(context);
  974. if (!value) {
  975. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  976. }
  977. }
  978. const loc = getSelection(context, start);
  979. if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
  980. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  981. const dirName = match[1] ||
  982. (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
  983. let arg;
  984. if (match[2]) {
  985. const isSlot = dirName === 'slot';
  986. const startOffset = name.indexOf(match[2]);
  987. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  988. let content = match[2];
  989. let isStatic = true;
  990. if (content.startsWith('[')) {
  991. isStatic = false;
  992. if (!content.endsWith(']')) {
  993. emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  994. }
  995. content = content.substr(1, content.length - 2);
  996. }
  997. else if (isSlot) {
  998. // #1241 special case for v-slot: vuetify relies extensively on slot
  999. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  1000. // supports such usage so we are keeping it consistent with 2.x.
  1001. content += match[3] || '';
  1002. }
  1003. arg = {
  1004. type: 4 /* SIMPLE_EXPRESSION */,
  1005. content,
  1006. isStatic,
  1007. isConstant: isStatic,
  1008. loc
  1009. };
  1010. }
  1011. if (value && value.isQuoted) {
  1012. const valueLoc = value.loc;
  1013. valueLoc.start.offset++;
  1014. valueLoc.start.column++;
  1015. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  1016. valueLoc.source = valueLoc.source.slice(1, -1);
  1017. }
  1018. return {
  1019. type: 7 /* DIRECTIVE */,
  1020. name: dirName,
  1021. exp: value && {
  1022. type: 4 /* SIMPLE_EXPRESSION */,
  1023. content: value.content,
  1024. isStatic: false,
  1025. // Treat as non-constant by default. This can be potentially set to
  1026. // true by `transformExpression` to make it eligible for hoisting.
  1027. isConstant: false,
  1028. loc: value.loc
  1029. },
  1030. arg,
  1031. modifiers: match[3] ? match[3].substr(1).split('.') : [],
  1032. loc
  1033. };
  1034. }
  1035. return {
  1036. type: 6 /* ATTRIBUTE */,
  1037. name,
  1038. value: value && {
  1039. type: 2 /* TEXT */,
  1040. content: value.content,
  1041. loc: value.loc
  1042. },
  1043. loc
  1044. };
  1045. }
  1046. function parseAttributeValue(context) {
  1047. const start = getCursor(context);
  1048. let content;
  1049. const quote = context.source[0];
  1050. const isQuoted = quote === `"` || quote === `'`;
  1051. if (isQuoted) {
  1052. // Quoted value.
  1053. advanceBy(context, 1);
  1054. const endIndex = context.source.indexOf(quote);
  1055. if (endIndex === -1) {
  1056. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  1057. }
  1058. else {
  1059. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  1060. advanceBy(context, 1);
  1061. }
  1062. }
  1063. else {
  1064. // Unquoted
  1065. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  1066. if (!match) {
  1067. return undefined;
  1068. }
  1069. const unexpectedChars = /["'<=`]/g;
  1070. let m;
  1071. while ((m = unexpectedChars.exec(match[0]))) {
  1072. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  1073. }
  1074. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  1075. }
  1076. return { content, isQuoted, loc: getSelection(context, start) };
  1077. }
  1078. function parseInterpolation(context, mode) {
  1079. const [open, close] = context.options.delimiters;
  1080. const closeIndex = context.source.indexOf(close, open.length);
  1081. if (closeIndex === -1) {
  1082. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  1083. return undefined;
  1084. }
  1085. const start = getCursor(context);
  1086. advanceBy(context, open.length);
  1087. const innerStart = getCursor(context);
  1088. const innerEnd = getCursor(context);
  1089. const rawContentLength = closeIndex - open.length;
  1090. const rawContent = context.source.slice(0, rawContentLength);
  1091. const preTrimContent = parseTextData(context, rawContentLength, mode);
  1092. const content = preTrimContent.trim();
  1093. const startOffset = preTrimContent.indexOf(content);
  1094. if (startOffset > 0) {
  1095. advancePositionWithMutation(innerStart, rawContent, startOffset);
  1096. }
  1097. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  1098. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  1099. advanceBy(context, close.length);
  1100. return {
  1101. type: 5 /* INTERPOLATION */,
  1102. content: {
  1103. type: 4 /* SIMPLE_EXPRESSION */,
  1104. isStatic: false,
  1105. // Set `isConstant` to false by default and will decide in transformExpression
  1106. isConstant: false,
  1107. content,
  1108. loc: getSelection(context, innerStart, innerEnd)
  1109. },
  1110. loc: getSelection(context, start)
  1111. };
  1112. }
  1113. function parseText(context, mode) {
  1114. const endTokens = ['<', context.options.delimiters[0]];
  1115. if (mode === 3 /* CDATA */) {
  1116. endTokens.push(']]>');
  1117. }
  1118. let endIndex = context.source.length;
  1119. for (let i = 0; i < endTokens.length; i++) {
  1120. const index = context.source.indexOf(endTokens[i], 1);
  1121. if (index !== -1 && endIndex > index) {
  1122. endIndex = index;
  1123. }
  1124. }
  1125. const start = getCursor(context);
  1126. const content = parseTextData(context, endIndex, mode);
  1127. return {
  1128. type: 2 /* TEXT */,
  1129. content,
  1130. loc: getSelection(context, start)
  1131. };
  1132. }
  1133. /**
  1134. * Get text data with a given length from the current location.
  1135. * This translates HTML entities in the text data.
  1136. */
  1137. function parseTextData(context, length, mode) {
  1138. const rawText = context.source.slice(0, length);
  1139. advanceBy(context, length);
  1140. if (mode === 2 /* RAWTEXT */ ||
  1141. mode === 3 /* CDATA */ ||
  1142. rawText.indexOf('&') === -1) {
  1143. return rawText;
  1144. }
  1145. else {
  1146. // DATA or RCDATA containing "&"". Entity decoding required.
  1147. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  1148. }
  1149. }
  1150. function getCursor(context) {
  1151. const { column, line, offset } = context;
  1152. return { column, line, offset };
  1153. }
  1154. function getSelection(context, start, end) {
  1155. end = end || getCursor(context);
  1156. return {
  1157. start,
  1158. end,
  1159. source: context.originalSource.slice(start.offset, end.offset)
  1160. };
  1161. }
  1162. function last(xs) {
  1163. return xs[xs.length - 1];
  1164. }
  1165. function startsWith(source, searchString) {
  1166. return source.startsWith(searchString);
  1167. }
  1168. function advanceBy(context, numberOfCharacters) {
  1169. const { source } = context;
  1170. advancePositionWithMutation(context, source, numberOfCharacters);
  1171. context.source = source.slice(numberOfCharacters);
  1172. }
  1173. function advanceSpaces(context) {
  1174. const match = /^[\t\r\n\f ]+/.exec(context.source);
  1175. if (match) {
  1176. advanceBy(context, match[0].length);
  1177. }
  1178. }
  1179. function getNewPosition(context, start, numberOfCharacters) {
  1180. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  1181. }
  1182. function emitError(context, code, offset, loc = getCursor(context)) {
  1183. if (offset) {
  1184. loc.offset += offset;
  1185. loc.column += offset;
  1186. }
  1187. context.options.onError(createCompilerError(code, {
  1188. start: loc,
  1189. end: loc,
  1190. source: ''
  1191. }));
  1192. }
  1193. function isEnd(context, mode, ancestors) {
  1194. const s = context.source;
  1195. switch (mode) {
  1196. case 0 /* DATA */:
  1197. if (startsWith(s, '</')) {
  1198. //TODO: probably bad performance
  1199. for (let i = ancestors.length - 1; i >= 0; --i) {
  1200. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  1201. return true;
  1202. }
  1203. }
  1204. }
  1205. break;
  1206. case 1 /* RCDATA */:
  1207. case 2 /* RAWTEXT */: {
  1208. const parent = last(ancestors);
  1209. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  1210. return true;
  1211. }
  1212. break;
  1213. }
  1214. case 3 /* CDATA */:
  1215. if (startsWith(s, ']]>')) {
  1216. return true;
  1217. }
  1218. break;
  1219. }
  1220. return !s;
  1221. }
  1222. function startsWithEndTagOpen(source, tag) {
  1223. return (startsWith(source, '</') &&
  1224. source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
  1225. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  1226. }
  1227. function hoistStatic(root, context) {
  1228. walk(root, context, new Map(),
  1229. // Root node is unfortunately non-hoistable due to potential parent
  1230. // fallthrough attributes.
  1231. isSingleElementRoot(root, root.children[0]));
  1232. }
  1233. function isSingleElementRoot(root, child) {
  1234. const { children } = root;
  1235. return (children.length === 1 &&
  1236. child.type === 1 /* ELEMENT */ &&
  1237. !isSlotOutlet(child));
  1238. }
  1239. function walk(node, context, resultCache, doNotHoistNode = false) {
  1240. let hasHoistedNode = false;
  1241. // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
  1242. // static bindings with expressions. These expressions are guaranteed to be
  1243. // constant so they are still eligible for hoisting, but they are only
  1244. // available at runtime and therefore cannot be evaluated ahead of time.
  1245. // This is only a concern for pre-stringification (via transformHoist by
  1246. // @vue/compiler-dom), but doing it here allows us to perform only one full
  1247. // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
  1248. // stringficiation threshold is met.
  1249. let hasRuntimeConstant = false;
  1250. const { children } = node;
  1251. for (let i = 0; i < children.length; i++) {
  1252. const child = children[i];
  1253. // only plain elements & text calls are eligible for hoisting.
  1254. if (child.type === 1 /* ELEMENT */ &&
  1255. child.tagType === 0 /* ELEMENT */) {
  1256. let staticType;
  1257. if (!doNotHoistNode &&
  1258. (staticType = getStaticType(child, resultCache)) > 0) {
  1259. if (staticType === 2 /* HAS_RUNTIME_CONSTANT */) {
  1260. hasRuntimeConstant = true;
  1261. }
  1262. child.codegenNode.patchFlag =
  1263. -1 /* HOISTED */ + ((process.env.NODE_ENV !== 'production') ? ` /* HOISTED */` : ``);
  1264. child.codegenNode = context.hoist(child.codegenNode);
  1265. hasHoistedNode = true;
  1266. continue;
  1267. }
  1268. else {
  1269. // node may contain dynamic children, but its props may be eligible for
  1270. // hoisting.
  1271. const codegenNode = child.codegenNode;
  1272. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1273. const flag = getPatchFlag(codegenNode);
  1274. if ((!flag ||
  1275. flag === 512 /* NEED_PATCH */ ||
  1276. flag === 1 /* TEXT */) &&
  1277. !hasNonHoistableProps(child)) {
  1278. const props = getNodeProps(child);
  1279. if (props) {
  1280. codegenNode.props = context.hoist(props);
  1281. }
  1282. }
  1283. }
  1284. }
  1285. }
  1286. else if (child.type === 12 /* TEXT_CALL */) {
  1287. const staticType = getStaticType(child.content, resultCache);
  1288. if (staticType > 0) {
  1289. if (staticType === 2 /* HAS_RUNTIME_CONSTANT */) {
  1290. hasRuntimeConstant = true;
  1291. }
  1292. child.codegenNode = context.hoist(child.codegenNode);
  1293. hasHoistedNode = true;
  1294. }
  1295. }
  1296. // walk further
  1297. if (child.type === 1 /* ELEMENT */) {
  1298. walk(child, context, resultCache);
  1299. }
  1300. else if (child.type === 11 /* FOR */) {
  1301. // Do not hoist v-for single child because it has to be a block
  1302. walk(child, context, resultCache, child.children.length === 1);
  1303. }
  1304. else if (child.type === 9 /* IF */) {
  1305. for (let i = 0; i < child.branches.length; i++) {
  1306. // Do not hoist v-if single child because it has to be a block
  1307. walk(child.branches[i], context, resultCache, child.branches[i].children.length === 1);
  1308. }
  1309. }
  1310. }
  1311. if (!hasRuntimeConstant && hasHoistedNode && context.transformHoist) {
  1312. context.transformHoist(children, context, node);
  1313. }
  1314. }
  1315. function getStaticType(node, resultCache = new Map()) {
  1316. switch (node.type) {
  1317. case 1 /* ELEMENT */:
  1318. if (node.tagType !== 0 /* ELEMENT */) {
  1319. return 0 /* NOT_STATIC */;
  1320. }
  1321. const cached = resultCache.get(node);
  1322. if (cached !== undefined) {
  1323. return cached;
  1324. }
  1325. const codegenNode = node.codegenNode;
  1326. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  1327. return 0 /* NOT_STATIC */;
  1328. }
  1329. const flag = getPatchFlag(codegenNode);
  1330. if (!flag && !hasNonHoistableProps(node)) {
  1331. // element self is static. check its children.
  1332. let returnType = 1 /* FULL_STATIC */;
  1333. for (let i = 0; i < node.children.length; i++) {
  1334. const childType = getStaticType(node.children[i], resultCache);
  1335. if (childType === 0 /* NOT_STATIC */) {
  1336. resultCache.set(node, 0 /* NOT_STATIC */);
  1337. return 0 /* NOT_STATIC */;
  1338. }
  1339. else if (childType === 2 /* HAS_RUNTIME_CONSTANT */) {
  1340. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  1341. }
  1342. }
  1343. // check if any of the props contain runtime constants
  1344. if (returnType !== 2 /* HAS_RUNTIME_CONSTANT */) {
  1345. for (let i = 0; i < node.props.length; i++) {
  1346. const p = node.props[i];
  1347. if (p.type === 7 /* DIRECTIVE */ &&
  1348. p.name === 'bind' &&
  1349. p.exp &&
  1350. (p.exp.type === 8 /* COMPOUND_EXPRESSION */ ||
  1351. p.exp.isRuntimeConstant)) {
  1352. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  1353. }
  1354. }
  1355. }
  1356. // only svg/foreignObject could be block here, however if they are
  1357. // stati then they don't need to be blocks since there will be no
  1358. // nested updates.
  1359. if (codegenNode.isBlock) {
  1360. codegenNode.isBlock = false;
  1361. }
  1362. resultCache.set(node, returnType);
  1363. return returnType;
  1364. }
  1365. else {
  1366. resultCache.set(node, 0 /* NOT_STATIC */);
  1367. return 0 /* NOT_STATIC */;
  1368. }
  1369. case 2 /* TEXT */:
  1370. case 3 /* COMMENT */:
  1371. return 1 /* FULL_STATIC */;
  1372. case 9 /* IF */:
  1373. case 11 /* FOR */:
  1374. case 10 /* IF_BRANCH */:
  1375. return 0 /* NOT_STATIC */;
  1376. case 5 /* INTERPOLATION */:
  1377. case 12 /* TEXT_CALL */:
  1378. return getStaticType(node.content, resultCache);
  1379. case 4 /* SIMPLE_EXPRESSION */:
  1380. return node.isConstant
  1381. ? node.isRuntimeConstant
  1382. ? 2 /* HAS_RUNTIME_CONSTANT */
  1383. : 1 /* FULL_STATIC */
  1384. : 0 /* NOT_STATIC */;
  1385. case 8 /* COMPOUND_EXPRESSION */:
  1386. let returnType = 1 /* FULL_STATIC */;
  1387. for (let i = 0; i < node.children.length; i++) {
  1388. const child = node.children[i];
  1389. if (isString(child) || isSymbol(child)) {
  1390. continue;
  1391. }
  1392. const childType = getStaticType(child, resultCache);
  1393. if (childType === 0 /* NOT_STATIC */) {
  1394. return 0 /* NOT_STATIC */;
  1395. }
  1396. else if (childType === 2 /* HAS_RUNTIME_CONSTANT */) {
  1397. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  1398. }
  1399. }
  1400. return returnType;
  1401. default:
  1402. if ((process.env.NODE_ENV !== 'production')) ;
  1403. return 0 /* NOT_STATIC */;
  1404. }
  1405. }
  1406. /**
  1407. * Even for a node with no patch flag, it is possible for it to contain
  1408. * non-hoistable expressions that refers to scope variables, e.g. compiler
  1409. * injected keys or cached event handlers. Therefore we need to always check the
  1410. * codegenNode's props to be sure.
  1411. */
  1412. function hasNonHoistableProps(node) {
  1413. const props = getNodeProps(node);
  1414. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  1415. const { properties } = props;
  1416. for (let i = 0; i < properties.length; i++) {
  1417. const { key, value } = properties[i];
  1418. if (key.type !== 4 /* SIMPLE_EXPRESSION */ ||
  1419. !key.isStatic ||
  1420. (value.type !== 4 /* SIMPLE_EXPRESSION */ ||
  1421. (!value.isStatic && !value.isConstant))) {
  1422. return true;
  1423. }
  1424. }
  1425. }
  1426. return false;
  1427. }
  1428. function getNodeProps(node) {
  1429. const codegenNode = node.codegenNode;
  1430. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1431. return codegenNode.props;
  1432. }
  1433. }
  1434. function getPatchFlag(node) {
  1435. const flag = node.patchFlag;
  1436. return flag ? parseInt(flag, 10) : undefined;
  1437. }
  1438. function createTransformContext(root, { prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, ssr = false, ssrCssVars = ``, bindingMetadata = {}, onError = defaultOnError }) {
  1439. const context = {
  1440. // options
  1441. prefixIdentifiers,
  1442. hoistStatic,
  1443. cacheHandlers,
  1444. nodeTransforms,
  1445. directiveTransforms,
  1446. transformHoist,
  1447. isBuiltInComponent,
  1448. isCustomElement,
  1449. expressionPlugins,
  1450. scopeId,
  1451. ssr,
  1452. ssrCssVars,
  1453. bindingMetadata,
  1454. onError,
  1455. // state
  1456. root,
  1457. helpers: new Set(),
  1458. components: new Set(),
  1459. directives: new Set(),
  1460. hoists: [],
  1461. imports: new Set(),
  1462. temps: 0,
  1463. cached: 0,
  1464. identifiers: Object.create(null),
  1465. scopes: {
  1466. vFor: 0,
  1467. vSlot: 0,
  1468. vPre: 0,
  1469. vOnce: 0
  1470. },
  1471. parent: null,
  1472. currentNode: root,
  1473. childIndex: 0,
  1474. // methods
  1475. helper(name) {
  1476. context.helpers.add(name);
  1477. return name;
  1478. },
  1479. helperString(name) {
  1480. return `_${helperNameMap[context.helper(name)]}`;
  1481. },
  1482. replaceNode(node) {
  1483. /* istanbul ignore if */
  1484. if ((process.env.NODE_ENV !== 'production')) {
  1485. if (!context.currentNode) {
  1486. throw new Error(`Node being replaced is already removed.`);
  1487. }
  1488. if (!context.parent) {
  1489. throw new Error(`Cannot replace root node.`);
  1490. }
  1491. }
  1492. context.parent.children[context.childIndex] = context.currentNode = node;
  1493. },
  1494. removeNode(node) {
  1495. if ((process.env.NODE_ENV !== 'production') && !context.parent) {
  1496. throw new Error(`Cannot remove root node.`);
  1497. }
  1498. const list = context.parent.children;
  1499. const removalIndex = node
  1500. ? list.indexOf(node)
  1501. : context.currentNode
  1502. ? context.childIndex
  1503. : -1;
  1504. /* istanbul ignore if */
  1505. if ((process.env.NODE_ENV !== 'production') && removalIndex < 0) {
  1506. throw new Error(`node being removed is not a child of current parent`);
  1507. }
  1508. if (!node || node === context.currentNode) {
  1509. // current node removed
  1510. context.currentNode = null;
  1511. context.onNodeRemoved();
  1512. }
  1513. else {
  1514. // sibling node removed
  1515. if (context.childIndex > removalIndex) {
  1516. context.childIndex--;
  1517. context.onNodeRemoved();
  1518. }
  1519. }
  1520. context.parent.children.splice(removalIndex, 1);
  1521. },
  1522. onNodeRemoved: () => { },
  1523. addIdentifiers(exp) {
  1524. },
  1525. removeIdentifiers(exp) {
  1526. },
  1527. hoist(exp) {
  1528. context.hoists.push(exp);
  1529. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, true);
  1530. identifier.hoisted = exp;
  1531. return identifier;
  1532. },
  1533. cache(exp, isVNode = false) {
  1534. return createCacheExpression(++context.cached, exp, isVNode);
  1535. }
  1536. };
  1537. return context;
  1538. }
  1539. function transform(root, options) {
  1540. const context = createTransformContext(root, options);
  1541. traverseNode(root, context);
  1542. if (options.hoistStatic) {
  1543. hoistStatic(root, context);
  1544. }
  1545. if (!options.ssr) {
  1546. createRootCodegen(root, context);
  1547. }
  1548. // finalize meta information
  1549. root.helpers = [...context.helpers];
  1550. root.components = [...context.components];
  1551. root.directives = [...context.directives];
  1552. root.imports = [...context.imports];
  1553. root.hoists = context.hoists;
  1554. root.temps = context.temps;
  1555. root.cached = context.cached;
  1556. }
  1557. function createRootCodegen(root, context) {
  1558. const { helper } = context;
  1559. const { children } = root;
  1560. if (children.length === 1) {
  1561. const child = children[0];
  1562. // if the single child is an element, turn it into a block.
  1563. if (isSingleElementRoot(root, child) && child.codegenNode) {
  1564. // single element root is never hoisted so codegenNode will never be
  1565. // SimpleExpressionNode
  1566. const codegenNode = child.codegenNode;
  1567. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1568. codegenNode.isBlock = true;
  1569. helper(OPEN_BLOCK);
  1570. helper(CREATE_BLOCK);
  1571. }
  1572. root.codegenNode = codegenNode;
  1573. }
  1574. else {
  1575. // - single <slot/>, IfNode, ForNode: already blocks.
  1576. // - single text node: always patched.
  1577. // root codegen falls through via genNode()
  1578. root.codegenNode = child;
  1579. }
  1580. }
  1581. else if (children.length > 1) {
  1582. // root has multiple nodes - return a fragment block.
  1583. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, `${64 /* STABLE_FRAGMENT */} /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true);
  1584. }
  1585. else ;
  1586. }
  1587. function traverseChildren(parent, context) {
  1588. let i = 0;
  1589. const nodeRemoved = () => {
  1590. i--;
  1591. };
  1592. for (; i < parent.children.length; i++) {
  1593. const child = parent.children[i];
  1594. if (isString(child))
  1595. continue;
  1596. context.parent = parent;
  1597. context.childIndex = i;
  1598. context.onNodeRemoved = nodeRemoved;
  1599. traverseNode(child, context);
  1600. }
  1601. }
  1602. function traverseNode(node, context) {
  1603. context.currentNode = node;
  1604. // apply transform plugins
  1605. const { nodeTransforms } = context;
  1606. const exitFns = [];
  1607. for (let i = 0; i < nodeTransforms.length; i++) {
  1608. const onExit = nodeTransforms[i](node, context);
  1609. if (onExit) {
  1610. if (isArray(onExit)) {
  1611. exitFns.push(...onExit);
  1612. }
  1613. else {
  1614. exitFns.push(onExit);
  1615. }
  1616. }
  1617. if (!context.currentNode) {
  1618. // node was removed
  1619. return;
  1620. }
  1621. else {
  1622. // node may have been replaced
  1623. node = context.currentNode;
  1624. }
  1625. }
  1626. switch (node.type) {
  1627. case 3 /* COMMENT */:
  1628. if (!context.ssr) {
  1629. // inject import for the Comment symbol, which is needed for creating
  1630. // comment nodes with `createVNode`
  1631. context.helper(CREATE_COMMENT);
  1632. }
  1633. break;
  1634. case 5 /* INTERPOLATION */:
  1635. // no need to traverse, but we need to inject toString helper
  1636. if (!context.ssr) {
  1637. context.helper(TO_DISPLAY_STRING);
  1638. }
  1639. break;
  1640. // for container types, further traverse downwards
  1641. case 9 /* IF */:
  1642. for (let i = 0; i < node.branches.length; i++) {
  1643. traverseNode(node.branches[i], context);
  1644. }
  1645. break;
  1646. case 10 /* IF_BRANCH */:
  1647. case 11 /* FOR */:
  1648. case 1 /* ELEMENT */:
  1649. case 0 /* ROOT */:
  1650. traverseChildren(node, context);
  1651. break;
  1652. }
  1653. // exit transforms
  1654. context.currentNode = node;
  1655. let i = exitFns.length;
  1656. while (i--) {
  1657. exitFns[i]();
  1658. }
  1659. }
  1660. function createStructuralDirectiveTransform(name, fn) {
  1661. const matches = isString(name)
  1662. ? (n) => n === name
  1663. : (n) => name.test(n);
  1664. return (node, context) => {
  1665. if (node.type === 1 /* ELEMENT */) {
  1666. const { props } = node;
  1667. // structural directive transforms are not concerned with slots
  1668. // as they are handled separately in vSlot.ts
  1669. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  1670. return;
  1671. }
  1672. const exitFns = [];
  1673. for (let i = 0; i < props.length; i++) {
  1674. const prop = props[i];
  1675. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  1676. // structural directives are removed to avoid infinite recursion
  1677. // also we remove them *before* applying so that it can further
  1678. // traverse itself in case it moves the node around
  1679. props.splice(i, 1);
  1680. i--;
  1681. const onExit = fn(node, prop, context);
  1682. if (onExit)
  1683. exitFns.push(onExit);
  1684. }
  1685. }
  1686. return exitFns;
  1687. }
  1688. };
  1689. }
  1690. const PURE_ANNOTATION = `/*#__PURE__*/`;
  1691. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
  1692. const context = {
  1693. mode,
  1694. prefixIdentifiers,
  1695. sourceMap,
  1696. filename,
  1697. scopeId,
  1698. optimizeImports,
  1699. runtimeGlobalName,
  1700. runtimeModuleName,
  1701. ssr,
  1702. source: ast.loc.source,
  1703. code: ``,
  1704. column: 1,
  1705. line: 1,
  1706. offset: 0,
  1707. indentLevel: 0,
  1708. pure: false,
  1709. map: undefined,
  1710. helper(key) {
  1711. return `_${helperNameMap[key]}`;
  1712. },
  1713. push(code, node) {
  1714. context.code += code;
  1715. },
  1716. indent() {
  1717. newline(++context.indentLevel);
  1718. },
  1719. deindent(withoutNewLine = false) {
  1720. if (withoutNewLine) {
  1721. --context.indentLevel;
  1722. }
  1723. else {
  1724. newline(--context.indentLevel);
  1725. }
  1726. },
  1727. newline() {
  1728. newline(context.indentLevel);
  1729. }
  1730. };
  1731. function newline(n) {
  1732. context.push('\n' + ` `.repeat(n));
  1733. }
  1734. return context;
  1735. }
  1736. function generate(ast, options = {}) {
  1737. const context = createCodegenContext(ast, options);
  1738. if (options.onContextCreated)
  1739. options.onContextCreated(context);
  1740. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  1741. const hasHelpers = ast.helpers.length > 0;
  1742. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  1743. // preambles
  1744. {
  1745. genFunctionPreamble(ast, context);
  1746. }
  1747. // binding optimizations
  1748. const optimizeSources = options.bindingMetadata
  1749. ? `, $props, $setup, $data, $options`
  1750. : ``;
  1751. // enter render function
  1752. if (!ssr) {
  1753. push(`function render(_ctx, _cache${optimizeSources}) {`);
  1754. }
  1755. else {
  1756. push(`function ssrRender(_ctx, _push, _parent, _attrs${optimizeSources}) {`);
  1757. }
  1758. indent();
  1759. if (useWithBlock) {
  1760. push(`with (_ctx) {`);
  1761. indent();
  1762. // function mode const declarations should be inside with block
  1763. // also they should be renamed to avoid collision with user properties
  1764. if (hasHelpers) {
  1765. push(`const { ${ast.helpers
  1766. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  1767. .join(', ')} } = _Vue`);
  1768. push(`\n`);
  1769. newline();
  1770. }
  1771. }
  1772. // generate asset resolution statements
  1773. if (ast.components.length) {
  1774. genAssets(ast.components, 'component', context);
  1775. if (ast.directives.length || ast.temps > 0) {
  1776. newline();
  1777. }
  1778. }
  1779. if (ast.directives.length) {
  1780. genAssets(ast.directives, 'directive', context);
  1781. if (ast.temps > 0) {
  1782. newline();
  1783. }
  1784. }
  1785. if (ast.temps > 0) {
  1786. push(`let `);
  1787. for (let i = 0; i < ast.temps; i++) {
  1788. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  1789. }
  1790. }
  1791. if (ast.components.length || ast.directives.length || ast.temps) {
  1792. push(`\n`);
  1793. newline();
  1794. }
  1795. // generate the VNode tree expression
  1796. if (!ssr) {
  1797. push(`return `);
  1798. }
  1799. if (ast.codegenNode) {
  1800. genNode(ast.codegenNode, context);
  1801. }
  1802. else {
  1803. push(`null`);
  1804. }
  1805. if (useWithBlock) {
  1806. deindent();
  1807. push(`}`);
  1808. }
  1809. deindent();
  1810. push(`}`);
  1811. return {
  1812. ast,
  1813. code: context.code,
  1814. // SourceMapGenerator does have toJSON() method but it's not in the types
  1815. map: context.map ? context.map.toJSON() : undefined
  1816. };
  1817. }
  1818. function genFunctionPreamble(ast, context) {
  1819. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
  1820. const VueBinding = runtimeGlobalName;
  1821. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  1822. // Generate const declaration for helpers
  1823. // In prefix mode, we place the const declaration at top so it's done
  1824. // only once; But if we not prefixing, we place the declaration inside the
  1825. // with block so it doesn't incur the `in` check cost for every helper access.
  1826. if (ast.helpers.length > 0) {
  1827. {
  1828. // "with" mode.
  1829. // save Vue in a separate variable to avoid collision
  1830. push(`const _Vue = ${VueBinding}\n`);
  1831. // in "with" mode, helpers are declared inside the with block to avoid
  1832. // has check cost, but hoists are lifted out of the function - we need
  1833. // to provide the helper here.
  1834. if (ast.hoists.length) {
  1835. const staticHelpers = [
  1836. CREATE_VNODE,
  1837. CREATE_COMMENT,
  1838. CREATE_TEXT,
  1839. CREATE_STATIC
  1840. ]
  1841. .filter(helper => ast.helpers.includes(helper))
  1842. .map(aliasHelper)
  1843. .join(', ');
  1844. push(`const { ${staticHelpers} } = _Vue\n`);
  1845. }
  1846. }
  1847. }
  1848. genHoists(ast.hoists, context);
  1849. newline();
  1850. push(`return `);
  1851. }
  1852. function genAssets(assets, type, { helper, push, newline }) {
  1853. const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
  1854. for (let i = 0; i < assets.length; i++) {
  1855. const id = assets[i];
  1856. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})`);
  1857. if (i < assets.length - 1) {
  1858. newline();
  1859. }
  1860. }
  1861. }
  1862. function genHoists(hoists, context) {
  1863. if (!hoists.length) {
  1864. return;
  1865. }
  1866. context.pure = true;
  1867. const { push, newline, helper, scopeId, mode } = context;
  1868. newline();
  1869. hoists.forEach((exp, i) => {
  1870. if (exp) {
  1871. push(`const _hoisted_${i + 1} = `);
  1872. genNode(exp, context);
  1873. newline();
  1874. }
  1875. });
  1876. context.pure = false;
  1877. }
  1878. function isText$1(n) {
  1879. return (isString(n) ||
  1880. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  1881. n.type === 2 /* TEXT */ ||
  1882. n.type === 5 /* INTERPOLATION */ ||
  1883. n.type === 8 /* COMPOUND_EXPRESSION */);
  1884. }
  1885. function genNodeListAsArray(nodes, context) {
  1886. const multilines = nodes.length > 3 ||
  1887. (( (process.env.NODE_ENV !== 'production')) && nodes.some(n => isArray(n) || !isText$1(n)));
  1888. context.push(`[`);
  1889. multilines && context.indent();
  1890. genNodeList(nodes, context, multilines);
  1891. multilines && context.deindent();
  1892. context.push(`]`);
  1893. }
  1894. function genNodeList(nodes, context, multilines = false, comma = true) {
  1895. const { push, newline } = context;
  1896. for (let i = 0; i < nodes.length; i++) {
  1897. const node = nodes[i];
  1898. if (isString(node)) {
  1899. push(node);
  1900. }
  1901. else if (isArray(node)) {
  1902. genNodeListAsArray(node, context);
  1903. }
  1904. else {
  1905. genNode(node, context);
  1906. }
  1907. if (i < nodes.length - 1) {
  1908. if (multilines) {
  1909. comma && push(',');
  1910. newline();
  1911. }
  1912. else {
  1913. comma && push(', ');
  1914. }
  1915. }
  1916. }
  1917. }
  1918. function genNode(node, context) {
  1919. if (isString(node)) {
  1920. context.push(node);
  1921. return;
  1922. }
  1923. if (isSymbol(node)) {
  1924. context.push(context.helper(node));
  1925. return;
  1926. }
  1927. switch (node.type) {
  1928. case 1 /* ELEMENT */:
  1929. case 9 /* IF */:
  1930. case 11 /* FOR */:
  1931. (process.env.NODE_ENV !== 'production') &&
  1932. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  1933. `Apply appropriate transforms first.`);
  1934. genNode(node.codegenNode, context);
  1935. break;
  1936. case 2 /* TEXT */:
  1937. genText(node, context);
  1938. break;
  1939. case 4 /* SIMPLE_EXPRESSION */:
  1940. genExpression(node, context);
  1941. break;
  1942. case 5 /* INTERPOLATION */:
  1943. genInterpolation(node, context);
  1944. break;
  1945. case 12 /* TEXT_CALL */:
  1946. genNode(node.codegenNode, context);
  1947. break;
  1948. case 8 /* COMPOUND_EXPRESSION */:
  1949. genCompoundExpression(node, context);
  1950. break;
  1951. case 3 /* COMMENT */:
  1952. genComment(node, context);
  1953. break;
  1954. case 13 /* VNODE_CALL */:
  1955. genVNodeCall(node, context);
  1956. break;
  1957. case 14 /* JS_CALL_EXPRESSION */:
  1958. genCallExpression(node, context);
  1959. break;
  1960. case 15 /* JS_OBJECT_EXPRESSION */:
  1961. genObjectExpression(node, context);
  1962. break;
  1963. case 17 /* JS_ARRAY_EXPRESSION */:
  1964. genArrayExpression(node, context);
  1965. break;
  1966. case 18 /* JS_FUNCTION_EXPRESSION */:
  1967. genFunctionExpression(node, context);
  1968. break;
  1969. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  1970. genConditionalExpression(node, context);
  1971. break;
  1972. case 20 /* JS_CACHE_EXPRESSION */:
  1973. genCacheExpression(node, context);
  1974. break;
  1975. // SSR only types
  1976. case 21 /* JS_BLOCK_STATEMENT */:
  1977. break;
  1978. case 22 /* JS_TEMPLATE_LITERAL */:
  1979. break;
  1980. case 23 /* JS_IF_STATEMENT */:
  1981. break;
  1982. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  1983. break;
  1984. case 25 /* JS_SEQUENCE_EXPRESSION */:
  1985. break;
  1986. case 26 /* JS_RETURN_STATEMENT */:
  1987. break;
  1988. /* istanbul ignore next */
  1989. case 10 /* IF_BRANCH */:
  1990. // noop
  1991. break;
  1992. default:
  1993. if ((process.env.NODE_ENV !== 'production')) {
  1994. assert(false, `unhandled codegen node type: ${node.type}`);
  1995. // make sure we exhaust all possible types
  1996. const exhaustiveCheck = node;
  1997. return exhaustiveCheck;
  1998. }
  1999. }
  2000. }
  2001. function genText(node, context) {
  2002. context.push(JSON.stringify(node.content), node);
  2003. }
  2004. function genExpression(node, context) {
  2005. const { content, isStatic } = node;
  2006. context.push(isStatic ? JSON.stringify(content) : content, node);
  2007. }
  2008. function genInterpolation(node, context) {
  2009. const { push, helper, pure } = context;
  2010. if (pure)
  2011. push(PURE_ANNOTATION);
  2012. push(`${helper(TO_DISPLAY_STRING)}(`);
  2013. genNode(node.content, context);
  2014. push(`)`);
  2015. }
  2016. function genCompoundExpression(node, context) {
  2017. for (let i = 0; i < node.children.length; i++) {
  2018. const child = node.children[i];
  2019. if (isString(child)) {
  2020. context.push(child);
  2021. }
  2022. else {
  2023. genNode(child, context);
  2024. }
  2025. }
  2026. }
  2027. function genExpressionAsPropertyKey(node, context) {
  2028. const { push } = context;
  2029. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  2030. push(`[`);
  2031. genCompoundExpression(node, context);
  2032. push(`]`);
  2033. }
  2034. else if (node.isStatic) {
  2035. // only quote keys if necessary
  2036. const text = isSimpleIdentifier(node.content)
  2037. ? node.content
  2038. : JSON.stringify(node.content);
  2039. push(text, node);
  2040. }
  2041. else {
  2042. push(`[${node.content}]`, node);
  2043. }
  2044. }
  2045. function genComment(node, context) {
  2046. if ((process.env.NODE_ENV !== 'production')) {
  2047. const { push, helper, pure } = context;
  2048. if (pure) {
  2049. push(PURE_ANNOTATION);
  2050. }
  2051. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  2052. }
  2053. }
  2054. function genVNodeCall(node, context) {
  2055. const { push, helper, pure } = context;
  2056. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
  2057. if (directives) {
  2058. push(helper(WITH_DIRECTIVES) + `(`);
  2059. }
  2060. if (isBlock) {
  2061. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  2062. }
  2063. if (pure) {
  2064. push(PURE_ANNOTATION);
  2065. }
  2066. push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
  2067. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  2068. push(`)`);
  2069. if (isBlock) {
  2070. push(`)`);
  2071. }
  2072. if (directives) {
  2073. push(`, `);
  2074. genNode(directives, context);
  2075. push(`)`);
  2076. }
  2077. }
  2078. function genNullableArgs(args) {
  2079. let i = args.length;
  2080. while (i--) {
  2081. if (args[i] != null)
  2082. break;
  2083. }
  2084. return args.slice(0, i + 1).map(arg => arg || `null`);
  2085. }
  2086. // JavaScript
  2087. function genCallExpression(node, context) {
  2088. const { push, helper, pure } = context;
  2089. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  2090. if (pure) {
  2091. push(PURE_ANNOTATION);
  2092. }
  2093. push(callee + `(`, node);
  2094. genNodeList(node.arguments, context);
  2095. push(`)`);
  2096. }
  2097. function genObjectExpression(node, context) {
  2098. const { push, indent, deindent, newline } = context;
  2099. const { properties } = node;
  2100. if (!properties.length) {
  2101. push(`{}`, node);
  2102. return;
  2103. }
  2104. const multilines = properties.length > 1 ||
  2105. (( (process.env.NODE_ENV !== 'production')) &&
  2106. properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  2107. push(multilines ? `{` : `{ `);
  2108. multilines && indent();
  2109. for (let i = 0; i < properties.length; i++) {
  2110. const { key, value } = properties[i];
  2111. // key
  2112. genExpressionAsPropertyKey(key, context);
  2113. push(`: `);
  2114. // value
  2115. genNode(value, context);
  2116. if (i < properties.length - 1) {
  2117. // will only reach this if it's multilines
  2118. push(`,`);
  2119. newline();
  2120. }
  2121. }
  2122. multilines && deindent();
  2123. push(multilines ? `}` : ` }`);
  2124. }
  2125. function genArrayExpression(node, context) {
  2126. genNodeListAsArray(node.elements, context);
  2127. }
  2128. function genFunctionExpression(node, context) {
  2129. const { push, indent, deindent, scopeId, mode } = context;
  2130. const { params, returns, body, newline, isSlot } = node;
  2131. if (isSlot) {
  2132. push(`_${helperNameMap[WITH_CTX]}(`);
  2133. }
  2134. push(`(`, node);
  2135. if (isArray(params)) {
  2136. genNodeList(params, context);
  2137. }
  2138. else if (params) {
  2139. genNode(params, context);
  2140. }
  2141. push(`) => `);
  2142. if (newline || body) {
  2143. push(`{`);
  2144. indent();
  2145. }
  2146. if (returns) {
  2147. if (newline) {
  2148. push(`return `);
  2149. }
  2150. if (isArray(returns)) {
  2151. genNodeListAsArray(returns, context);
  2152. }
  2153. else {
  2154. genNode(returns, context);
  2155. }
  2156. }
  2157. else if (body) {
  2158. genNode(body, context);
  2159. }
  2160. if (newline || body) {
  2161. deindent();
  2162. push(`}`);
  2163. }
  2164. if ( isSlot) {
  2165. push(`)`);
  2166. }
  2167. }
  2168. function genConditionalExpression(node, context) {
  2169. const { test, consequent, alternate, newline: needNewline } = node;
  2170. const { push, indent, deindent, newline } = context;
  2171. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  2172. const needsParens = !isSimpleIdentifier(test.content);
  2173. needsParens && push(`(`);
  2174. genExpression(test, context);
  2175. needsParens && push(`)`);
  2176. }
  2177. else {
  2178. push(`(`);
  2179. genNode(test, context);
  2180. push(`)`);
  2181. }
  2182. needNewline && indent();
  2183. context.indentLevel++;
  2184. needNewline || push(` `);
  2185. push(`? `);
  2186. genNode(consequent, context);
  2187. context.indentLevel--;
  2188. needNewline && newline();
  2189. needNewline || push(` `);
  2190. push(`: `);
  2191. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  2192. if (!isNested) {
  2193. context.indentLevel++;
  2194. }
  2195. genNode(alternate, context);
  2196. if (!isNested) {
  2197. context.indentLevel--;
  2198. }
  2199. needNewline && deindent(true /* without newline */);
  2200. }
  2201. function genCacheExpression(node, context) {
  2202. const { push, helper, indent, deindent, newline } = context;
  2203. push(`_cache[${node.index}] || (`);
  2204. if (node.isVNode) {
  2205. indent();
  2206. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  2207. newline();
  2208. }
  2209. push(`_cache[${node.index}] = `);
  2210. genNode(node.value, context);
  2211. if (node.isVNode) {
  2212. push(`,`);
  2213. newline();
  2214. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  2215. newline();
  2216. push(`_cache[${node.index}]`);
  2217. deindent();
  2218. }
  2219. push(`)`);
  2220. }
  2221. // these keywords should not appear inside expressions, but operators like
  2222. // typeof, instanceof and in are allowed
  2223. const prohibitedKeywordRE = new RegExp('\\b' +
  2224. ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
  2225. 'super,throw,while,yield,delete,export,import,return,switch,default,' +
  2226. 'extends,finally,continue,debugger,function,arguments,typeof,void')
  2227. .split(',')
  2228. .join('\\b|\\b') +
  2229. '\\b');
  2230. // strip strings in expressions
  2231. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  2232. /**
  2233. * Validate a non-prefixed expression.
  2234. * This is only called when using the in-browser runtime compiler since it
  2235. * doesn't prefix expressions.
  2236. */
  2237. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  2238. const exp = node.content;
  2239. // empty expressions are validated per-directive since some directives
  2240. // do allow empty expressions.
  2241. if (!exp.trim()) {
  2242. return;
  2243. }
  2244. try {
  2245. new Function(asRawStatements
  2246. ? ` ${exp} `
  2247. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  2248. }
  2249. catch (e) {
  2250. let message = e.message;
  2251. const keywordMatch = exp
  2252. .replace(stripStringRE, '')
  2253. .match(prohibitedKeywordRE);
  2254. if (keywordMatch) {
  2255. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  2256. }
  2257. context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
  2258. }
  2259. }
  2260. const isLiteralWhitelisted = /*#__PURE__*/ makeMap('true,false,null,this');
  2261. const transformExpression = (node, context) => {
  2262. if (node.type === 5 /* INTERPOLATION */) {
  2263. node.content = processExpression(node.content, context);
  2264. }
  2265. else if (node.type === 1 /* ELEMENT */) {
  2266. // handle directives on element
  2267. for (let i = 0; i < node.props.length; i++) {
  2268. const dir = node.props[i];
  2269. // do not process for v-on & v-for since they are special handled
  2270. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  2271. const exp = dir.exp;
  2272. const arg = dir.arg;
  2273. // do not process exp if this is v-on:arg - we need special handling
  2274. // for wrapping inline statements.
  2275. if (exp &&
  2276. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  2277. !(dir.name === 'on' && arg)) {
  2278. dir.exp = processExpression(exp, context,
  2279. // slot args must be processed as function params
  2280. dir.name === 'slot');
  2281. }
  2282. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  2283. dir.arg = processExpression(arg, context);
  2284. }
  2285. }
  2286. }
  2287. }
  2288. };
  2289. // Important: since this function uses Node.js only dependencies, it should
  2290. // always be used with a leading !true check so that it can be
  2291. // tree-shaken from the browser build.
  2292. function processExpression(node, context,
  2293. // some expressions like v-slot props & v-for aliases should be parsed as
  2294. // function params
  2295. asParams = false,
  2296. // v-on handler values may contain multiple statements
  2297. asRawStatements = false) {
  2298. if ((process.env.NODE_ENV !== 'production') && true) {
  2299. // simple in-browser validation (same logic in 2.x)
  2300. validateBrowserExpression(node, context, asParams, asRawStatements);
  2301. return node;
  2302. }
  2303. if (!context.prefixIdentifiers || !node.content.trim()) {
  2304. return node;
  2305. }
  2306. const { bindingMetadata } = context;
  2307. const prefix = (raw) => {
  2308. const source = hasOwn(bindingMetadata, raw)
  2309. ? `$` + bindingMetadata[raw]
  2310. : `_ctx`;
  2311. return `${source}.${raw}`;
  2312. };
  2313. // fast path if expression is a simple identifier.
  2314. const rawExp = node.content;
  2315. // bail on parens to prevent any possible function invocations.
  2316. const bailConstant = rawExp.indexOf(`(`) > -1;
  2317. if (isSimpleIdentifier(rawExp)) {
  2318. if (!asParams &&
  2319. !context.identifiers[rawExp] &&
  2320. !isGloballyWhitelisted(rawExp) &&
  2321. !isLiteralWhitelisted(rawExp)) {
  2322. node.content = prefix(rawExp);
  2323. }
  2324. else if (!context.identifiers[rawExp] && !bailConstant) {
  2325. // mark node constant for hoisting unless it's referring a scope variable
  2326. node.isConstant = true;
  2327. }
  2328. return node;
  2329. }
  2330. let ast;
  2331. // exp needs to be parsed differently:
  2332. // 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
  2333. // exp, but make sure to pad with spaces for consistent ranges
  2334. // 2. Expressions: wrap with parens (for e.g. object expressions)
  2335. // 3. Function arguments (v-for, v-slot): place in a function argument position
  2336. const source = asRawStatements
  2337. ? ` ${rawExp} `
  2338. : `(${rawExp})${asParams ? `=>{}` : ``}`;
  2339. try {
  2340. ast = parse(source, {
  2341. plugins: [...context.expressionPlugins, ...babelParserDefaultPlugins]
  2342. }).program;
  2343. }
  2344. catch (e) {
  2345. context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
  2346. return node;
  2347. }
  2348. const ids = [];
  2349. const knownIds = Object.create(context.identifiers);
  2350. const isDuplicate = (node) => ids.some(id => id.start === node.start);
  2351. walk$1(ast, {
  2352. enter(node, parent) {
  2353. if (node.type === 'Identifier') {
  2354. if (!isDuplicate(node)) {
  2355. const needPrefix = shouldPrefix(node, parent);
  2356. if (!knownIds[node.name] && needPrefix) {
  2357. if (isPropertyShorthand(node, parent)) {
  2358. // property shorthand like { foo }, we need to add the key since we
  2359. // rewrite the value
  2360. node.prefix = `${node.name}: `;
  2361. }
  2362. node.name = prefix(node.name);
  2363. ids.push(node);
  2364. }
  2365. else if (!isStaticPropertyKey(node, parent)) {
  2366. // The identifier is considered constant unless it's pointing to a
  2367. // scope variable (a v-for alias, or a v-slot prop)
  2368. if (!(needPrefix && knownIds[node.name]) && !bailConstant) {
  2369. node.isConstant = true;
  2370. }
  2371. // also generate sub-expressions for other identifiers for better
  2372. // source map support. (except for property keys which are static)
  2373. ids.push(node);
  2374. }
  2375. }
  2376. }
  2377. else if (isFunction(node)) {
  2378. // walk function expressions and add its arguments to known identifiers
  2379. // so that we don't prefix them
  2380. node.params.forEach(p => walk$1(p, {
  2381. enter(child, parent) {
  2382. if (child.type === 'Identifier' &&
  2383. // do not record as scope variable if is a destructured key
  2384. !isStaticPropertyKey(child, parent) &&
  2385. // do not record if this is a default value
  2386. // assignment of a destructured variable
  2387. !(parent &&
  2388. parent.type === 'AssignmentPattern' &&
  2389. parent.right === child)) {
  2390. const { name } = child;
  2391. if (node.scopeIds && node.scopeIds.has(name)) {
  2392. return;
  2393. }
  2394. if (name in knownIds) {
  2395. knownIds[name]++;
  2396. }
  2397. else {
  2398. knownIds[name] = 1;
  2399. }
  2400. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  2401. }
  2402. }
  2403. }));
  2404. }
  2405. },
  2406. leave(node) {
  2407. if (node !== ast.body[0].expression && node.scopeIds) {
  2408. node.scopeIds.forEach((id) => {
  2409. knownIds[id]--;
  2410. if (knownIds[id] === 0) {
  2411. delete knownIds[id];
  2412. }
  2413. });
  2414. }
  2415. }
  2416. });
  2417. // We break up the compound expression into an array of strings and sub
  2418. // expressions (for identifiers that have been prefixed). In codegen, if
  2419. // an ExpressionNode has the `.children` property, it will be used instead of
  2420. // `.content`.
  2421. const children = [];
  2422. ids.sort((a, b) => a.start - b.start);
  2423. ids.forEach((id, i) => {
  2424. // range is offset by -1 due to the wrapping parens when parsed
  2425. const start = id.start - 1;
  2426. const end = id.end - 1;
  2427. const last = ids[i - 1];
  2428. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  2429. if (leadingText.length || id.prefix) {
  2430. children.push(leadingText + (id.prefix || ``));
  2431. }
  2432. const source = rawExp.slice(start, end);
  2433. children.push(createSimpleExpression(id.name, false, {
  2434. source,
  2435. start: advancePositionWithClone(node.loc.start, source, start),
  2436. end: advancePositionWithClone(node.loc.start, source, end)
  2437. }, id.isConstant /* isConstant */));
  2438. if (i === ids.length - 1 && end < rawExp.length) {
  2439. children.push(rawExp.slice(end));
  2440. }
  2441. });
  2442. let ret;
  2443. if (children.length) {
  2444. ret = createCompoundExpression(children, node.loc);
  2445. }
  2446. else {
  2447. ret = node;
  2448. ret.isConstant = !bailConstant;
  2449. }
  2450. ret.identifiers = Object.keys(knownIds);
  2451. return ret;
  2452. }
  2453. const isFunction = (node) => {
  2454. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  2455. };
  2456. const isStaticProperty = (node) => node &&
  2457. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  2458. !node.computed;
  2459. const isPropertyShorthand = (node, parent) => {
  2460. return (isStaticProperty(parent) &&
  2461. parent.value === node &&
  2462. parent.key.type === 'Identifier' &&
  2463. parent.key.name === node.name &&
  2464. parent.key.start === node.start);
  2465. };
  2466. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  2467. function shouldPrefix(identifier, parent) {
  2468. if (!(isFunction(parent) &&
  2469. // not id of a FunctionDeclaration
  2470. (parent.id === identifier ||
  2471. // not a params of a function
  2472. parent.params.includes(identifier))) &&
  2473. // not a key of Property
  2474. !isStaticPropertyKey(identifier, parent) &&
  2475. // not a property of a MemberExpression
  2476. !((parent.type === 'MemberExpression' ||
  2477. parent.type === 'OptionalMemberExpression') &&
  2478. parent.property === identifier &&
  2479. !parent.computed) &&
  2480. // not in an Array destructure pattern
  2481. !(parent.type === 'ArrayPattern') &&
  2482. // skip whitelisted globals
  2483. !isGloballyWhitelisted(identifier.name) &&
  2484. // special case for webpack compilation
  2485. identifier.name !== `require` &&
  2486. // is a special keyword but parsed as identifier
  2487. identifier.name !== `arguments`) {
  2488. return true;
  2489. }
  2490. }
  2491. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  2492. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  2493. // #1587: We need to dynamically increment the key based on the current
  2494. // node's sibling nodes, since chained v-if/else branches are
  2495. // rendered at the same depth
  2496. const siblings = context.parent.children;
  2497. let i = siblings.indexOf(ifNode);
  2498. let key = 0;
  2499. while (i-- >= 0) {
  2500. const sibling = siblings[i];
  2501. if (sibling && sibling.type === 9 /* IF */) {
  2502. key += sibling.branches.length;
  2503. }
  2504. }
  2505. // Exit callback. Complete the codegenNode when all children have been
  2506. // transformed.
  2507. return () => {
  2508. if (isRoot) {
  2509. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  2510. }
  2511. else {
  2512. // attach this branch's codegen node to the v-if root.
  2513. const parentCondition = getParentCondition(ifNode.codegenNode);
  2514. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  2515. }
  2516. };
  2517. });
  2518. });
  2519. // target-agnostic transform used for both Client and SSR
  2520. function processIf(node, dir, context, processCodegen) {
  2521. if (dir.name !== 'else' &&
  2522. (!dir.exp || !dir.exp.content.trim())) {
  2523. const loc = dir.exp ? dir.exp.loc : node.loc;
  2524. context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  2525. dir.exp = createSimpleExpression(`true`, false, loc);
  2526. }
  2527. if ((process.env.NODE_ENV !== 'production') && true && dir.exp) {
  2528. validateBrowserExpression(dir.exp, context);
  2529. }
  2530. if (dir.name === 'if') {
  2531. const branch = createIfBranch(node, dir);
  2532. const ifNode = {
  2533. type: 9 /* IF */,
  2534. loc: node.loc,
  2535. branches: [branch]
  2536. };
  2537. context.replaceNode(ifNode);
  2538. if (processCodegen) {
  2539. return processCodegen(ifNode, branch, true);
  2540. }
  2541. }
  2542. else {
  2543. // locate the adjacent v-if
  2544. const siblings = context.parent.children;
  2545. const comments = [];
  2546. let i = siblings.indexOf(node);
  2547. while (i-- >= -1) {
  2548. const sibling = siblings[i];
  2549. if ((process.env.NODE_ENV !== 'production') && sibling && sibling.type === 3 /* COMMENT */) {
  2550. context.removeNode(sibling);
  2551. comments.unshift(sibling);
  2552. continue;
  2553. }
  2554. if (sibling &&
  2555. sibling.type === 2 /* TEXT */ &&
  2556. !sibling.content.trim().length) {
  2557. context.removeNode(sibling);
  2558. continue;
  2559. }
  2560. if (sibling && sibling.type === 9 /* IF */) {
  2561. // move the node to the if node's branches
  2562. context.removeNode();
  2563. const branch = createIfBranch(node, dir);
  2564. if ((process.env.NODE_ENV !== 'production') && comments.length) {
  2565. branch.children = [...comments, ...branch.children];
  2566. }
  2567. // check if user is forcing same key on different branches
  2568. if ((process.env.NODE_ENV !== 'production') || !true) {
  2569. const key = branch.userKey;
  2570. if (key) {
  2571. sibling.branches.forEach(({ userKey }) => {
  2572. if (isSameKey(userKey, key)) {
  2573. context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  2574. }
  2575. });
  2576. }
  2577. }
  2578. sibling.branches.push(branch);
  2579. const onExit = processCodegen && processCodegen(sibling, branch, false);
  2580. // since the branch was removed, it will not be traversed.
  2581. // make sure to traverse here.
  2582. traverseNode(branch, context);
  2583. // call on exit
  2584. if (onExit)
  2585. onExit();
  2586. // make sure to reset currentNode after traversal to indicate this
  2587. // node has been removed.
  2588. context.currentNode = null;
  2589. }
  2590. else {
  2591. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  2592. }
  2593. break;
  2594. }
  2595. }
  2596. }
  2597. function createIfBranch(node, dir) {
  2598. return {
  2599. type: 10 /* IF_BRANCH */,
  2600. loc: node.loc,
  2601. condition: dir.name === 'else' ? undefined : dir.exp,
  2602. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  2603. ? node.children
  2604. : [node],
  2605. userKey: findProp(node, `key`)
  2606. };
  2607. }
  2608. function createCodegenNodeForBranch(branch, keyIndex, context) {
  2609. if (branch.condition) {
  2610. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  2611. // make sure to pass in asBlock: true so that the comment node call
  2612. // closes the current block.
  2613. createCallExpression(context.helper(CREATE_COMMENT), [
  2614. (process.env.NODE_ENV !== 'production') ? '"v-if"' : '""',
  2615. 'true'
  2616. ]));
  2617. }
  2618. else {
  2619. return createChildrenCodegenNode(branch, keyIndex, context);
  2620. }
  2621. }
  2622. function createChildrenCodegenNode(branch, keyIndex, context) {
  2623. const { helper } = context;
  2624. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, true));
  2625. const { children } = branch;
  2626. const firstChild = children[0];
  2627. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  2628. if (needFragmentWrapper) {
  2629. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  2630. // optimize away nested fragments when child is a ForNode
  2631. const vnodeCall = firstChild.codegenNode;
  2632. injectProp(vnodeCall, keyProperty, context);
  2633. return vnodeCall;
  2634. }
  2635. else {
  2636. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, `${64 /* STABLE_FRAGMENT */} /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true, false, branch.loc);
  2637. }
  2638. }
  2639. else {
  2640. const vnodeCall = firstChild
  2641. .codegenNode;
  2642. // Change createVNode to createBlock.
  2643. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  2644. vnodeCall.isBlock = true;
  2645. helper(OPEN_BLOCK);
  2646. helper(CREATE_BLOCK);
  2647. }
  2648. // inject branch key
  2649. injectProp(vnodeCall, keyProperty, context);
  2650. return vnodeCall;
  2651. }
  2652. }
  2653. function isSameKey(a, b) {
  2654. if (!a || a.type !== b.type) {
  2655. return false;
  2656. }
  2657. if (a.type === 6 /* ATTRIBUTE */) {
  2658. if (a.value.content !== b.value.content) {
  2659. return false;
  2660. }
  2661. }
  2662. else {
  2663. // directive
  2664. const exp = a.exp;
  2665. const branchExp = b.exp;
  2666. if (exp.type !== branchExp.type) {
  2667. return false;
  2668. }
  2669. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  2670. (exp.isStatic !== branchExp.isStatic ||
  2671. exp.content !== branchExp.content)) {
  2672. return false;
  2673. }
  2674. }
  2675. return true;
  2676. }
  2677. function getParentCondition(node) {
  2678. while (true) {
  2679. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  2680. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  2681. node = node.alternate;
  2682. }
  2683. else {
  2684. return node;
  2685. }
  2686. }
  2687. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  2688. node = node.value;
  2689. }
  2690. }
  2691. }
  2692. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  2693. const { helper } = context;
  2694. return processFor(node, dir, context, forNode => {
  2695. // create the loop render function expression now, and add the
  2696. // iterator on exit after all children have been traversed
  2697. const renderExp = createCallExpression(helper(RENDER_LIST), [
  2698. forNode.source
  2699. ]);
  2700. const keyProp = findProp(node, `key`);
  2701. const keyProperty = keyProp
  2702. ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
  2703. ? createSimpleExpression(keyProp.value.content, true)
  2704. : keyProp.exp)
  2705. : null;
  2706. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  2707. forNode.source.isConstant;
  2708. const fragmentFlag = isStableFragment
  2709. ? 64 /* STABLE_FRAGMENT */
  2710. : keyProp
  2711. ? 128 /* KEYED_FRAGMENT */
  2712. : 256 /* UNKEYED_FRAGMENT */;
  2713. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, `${fragmentFlag} /* ${PatchFlagNames[fragmentFlag]} */`, undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
  2714. return () => {
  2715. // finish the codegen now that all children have been traversed
  2716. let childBlock;
  2717. const isTemplate = isTemplateNode(node);
  2718. const { children } = forNode;
  2719. // check <template v-for> key placement
  2720. if (((process.env.NODE_ENV !== 'production') || !true) && isTemplate) {
  2721. node.children.some(c => {
  2722. if (c.type === 1 /* ELEMENT */) {
  2723. const key = findProp(c, 'key');
  2724. if (key) {
  2725. context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  2726. return true;
  2727. }
  2728. }
  2729. });
  2730. }
  2731. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  2732. const slotOutlet = isSlotOutlet(node)
  2733. ? node
  2734. : isTemplate &&
  2735. node.children.length === 1 &&
  2736. isSlotOutlet(node.children[0])
  2737. ? node.children[0] // api-extractor somehow fails to infer this
  2738. : null;
  2739. if (slotOutlet) {
  2740. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  2741. childBlock = slotOutlet.codegenNode;
  2742. if (isTemplate && keyProperty) {
  2743. // <template v-for="..." :key="..."><slot/></template>
  2744. // we need to inject the key to the renderSlot() call.
  2745. // the props for renderSlot is passed as the 3rd argument.
  2746. injectProp(childBlock, keyProperty, context);
  2747. }
  2748. }
  2749. else if (needFragmentWrapper) {
  2750. // <template v-for="..."> with text or multi-elements
  2751. // should generate a fragment block for each loop
  2752. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, `${64 /* STABLE_FRAGMENT */} /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true);
  2753. }
  2754. else {
  2755. // Normal element v-for. Directly use the child's codegenNode
  2756. // but mark it as a block.
  2757. childBlock = children[0]
  2758. .codegenNode;
  2759. if (isTemplate && keyProperty) {
  2760. injectProp(childBlock, keyProperty, context);
  2761. }
  2762. childBlock.isBlock = !isStableFragment;
  2763. if (childBlock.isBlock) {
  2764. helper(OPEN_BLOCK);
  2765. helper(CREATE_BLOCK);
  2766. }
  2767. }
  2768. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  2769. };
  2770. });
  2771. });
  2772. // target-agnostic transform used for both Client and SSR
  2773. function processFor(node, dir, context, processCodegen) {
  2774. if (!dir.exp) {
  2775. context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  2776. return;
  2777. }
  2778. const parseResult = parseForExpression(
  2779. // can only be simple expression because vFor transform is applied
  2780. // before expression transform.
  2781. dir.exp, context);
  2782. if (!parseResult) {
  2783. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  2784. return;
  2785. }
  2786. const { addIdentifiers, removeIdentifiers, scopes } = context;
  2787. const { source, value, key, index } = parseResult;
  2788. const forNode = {
  2789. type: 11 /* FOR */,
  2790. loc: dir.loc,
  2791. source,
  2792. valueAlias: value,
  2793. keyAlias: key,
  2794. objectIndexAlias: index,
  2795. parseResult,
  2796. children: isTemplateNode(node) ? node.children : [node]
  2797. };
  2798. context.replaceNode(forNode);
  2799. // bookkeeping
  2800. scopes.vFor++;
  2801. const onExit = processCodegen && processCodegen(forNode);
  2802. return () => {
  2803. scopes.vFor--;
  2804. if (onExit)
  2805. onExit();
  2806. };
  2807. }
  2808. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  2809. // This regex doesn't cover the case if key or index aliases have destructuring,
  2810. // but those do not make sense in the first place, so this works in practice.
  2811. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  2812. const stripParensRE = /^\(|\)$/g;
  2813. function parseForExpression(input, context) {
  2814. const loc = input.loc;
  2815. const exp = input.content;
  2816. const inMatch = exp.match(forAliasRE);
  2817. if (!inMatch)
  2818. return;
  2819. const [, LHS, RHS] = inMatch;
  2820. const result = {
  2821. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  2822. value: undefined,
  2823. key: undefined,
  2824. index: undefined
  2825. };
  2826. if ((process.env.NODE_ENV !== 'production') && true) {
  2827. validateBrowserExpression(result.source, context);
  2828. }
  2829. let valueContent = LHS.trim()
  2830. .replace(stripParensRE, '')
  2831. .trim();
  2832. const trimmedOffset = LHS.indexOf(valueContent);
  2833. const iteratorMatch = valueContent.match(forIteratorRE);
  2834. if (iteratorMatch) {
  2835. valueContent = valueContent.replace(forIteratorRE, '').trim();
  2836. const keyContent = iteratorMatch[1].trim();
  2837. let keyOffset;
  2838. if (keyContent) {
  2839. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  2840. result.key = createAliasExpression(loc, keyContent, keyOffset);
  2841. if ((process.env.NODE_ENV !== 'production') && true) {
  2842. validateBrowserExpression(result.key, context, true);
  2843. }
  2844. }
  2845. if (iteratorMatch[2]) {
  2846. const indexContent = iteratorMatch[2].trim();
  2847. if (indexContent) {
  2848. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  2849. ? keyOffset + keyContent.length
  2850. : trimmedOffset + valueContent.length));
  2851. if ((process.env.NODE_ENV !== 'production') && true) {
  2852. validateBrowserExpression(result.index, context, true);
  2853. }
  2854. }
  2855. }
  2856. }
  2857. if (valueContent) {
  2858. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  2859. if ((process.env.NODE_ENV !== 'production') && true) {
  2860. validateBrowserExpression(result.value, context, true);
  2861. }
  2862. }
  2863. return result;
  2864. }
  2865. function createAliasExpression(range, content, offset) {
  2866. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  2867. }
  2868. function createForLoopParams({ value, key, index }) {
  2869. const params = [];
  2870. if (value) {
  2871. params.push(value);
  2872. }
  2873. if (key) {
  2874. if (!value) {
  2875. params.push(createSimpleExpression(`_`, false));
  2876. }
  2877. params.push(key);
  2878. }
  2879. if (index) {
  2880. if (!key) {
  2881. if (!value) {
  2882. params.push(createSimpleExpression(`_`, false));
  2883. }
  2884. params.push(createSimpleExpression(`__`, false));
  2885. }
  2886. params.push(index);
  2887. }
  2888. return params;
  2889. }
  2890. const defaultFallback = createSimpleExpression(`undefined`, false);
  2891. // A NodeTransform that:
  2892. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  2893. // by transformExpression. This is only applied in non-browser builds with
  2894. // { prefixIdentifiers: true }.
  2895. // 2. Track v-slot depths so that we know a slot is inside another slot.
  2896. // Note the exit callback is executed before buildSlots() on the same node,
  2897. // so only nested slots see positive numbers.
  2898. const trackSlotScopes = (node, context) => {
  2899. if (node.type === 1 /* ELEMENT */ &&
  2900. (node.tagType === 1 /* COMPONENT */ ||
  2901. node.tagType === 3 /* TEMPLATE */)) {
  2902. // We are only checking non-empty v-slot here
  2903. // since we only care about slots that introduce scope variables.
  2904. const vSlot = findDir(node, 'slot');
  2905. if (vSlot) {
  2906. const slotProps = vSlot.exp;
  2907. context.scopes.vSlot++;
  2908. return () => {
  2909. context.scopes.vSlot--;
  2910. };
  2911. }
  2912. }
  2913. };
  2914. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  2915. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  2916. const trackVForSlotScopes = (node, context) => {
  2917. let vFor;
  2918. if (isTemplateNode(node) &&
  2919. node.props.some(isVSlot) &&
  2920. (vFor = findDir(node, 'for'))) {
  2921. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  2922. if (result) {
  2923. const { value, key, index } = result;
  2924. const { addIdentifiers, removeIdentifiers } = context;
  2925. value && addIdentifiers(value);
  2926. key && addIdentifiers(key);
  2927. index && addIdentifiers(index);
  2928. return () => {
  2929. value && removeIdentifiers(value);
  2930. key && removeIdentifiers(key);
  2931. index && removeIdentifiers(index);
  2932. };
  2933. }
  2934. }
  2935. };
  2936. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  2937. // Instead of being a DirectiveTransform, v-slot processing is called during
  2938. // transformElement to build the slots object for a component.
  2939. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  2940. context.helper(WITH_CTX);
  2941. const { children, loc } = node;
  2942. const slotsProperties = [];
  2943. const dynamicSlots = [];
  2944. const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
  2945. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  2946. // since it likely uses a scope variable.
  2947. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  2948. // 1. Check for slot with slotProps on component itself.
  2949. // <Comp v-slot="{ prop }"/>
  2950. const onComponentSlot = findDir(node, 'slot', true);
  2951. if (onComponentSlot) {
  2952. const { arg, exp } = onComponentSlot;
  2953. if (arg && !isStaticExp(arg)) {
  2954. hasDynamicSlots = true;
  2955. }
  2956. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  2957. }
  2958. // 2. Iterate through children and check for template slots
  2959. // <template v-slot:foo="{ prop }">
  2960. let hasTemplateSlots = false;
  2961. let hasNamedDefaultSlot = false;
  2962. const implicitDefaultChildren = [];
  2963. const seenSlotNames = new Set();
  2964. for (let i = 0; i < children.length; i++) {
  2965. const slotElement = children[i];
  2966. let slotDir;
  2967. if (!isTemplateNode(slotElement) ||
  2968. !(slotDir = findDir(slotElement, 'slot', true))) {
  2969. // not a <template v-slot>, skip.
  2970. if (slotElement.type !== 3 /* COMMENT */) {
  2971. implicitDefaultChildren.push(slotElement);
  2972. }
  2973. continue;
  2974. }
  2975. if (onComponentSlot) {
  2976. // already has on-component slot - this is incorrect usage.
  2977. context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  2978. break;
  2979. }
  2980. hasTemplateSlots = true;
  2981. const { children: slotChildren, loc: slotLoc } = slotElement;
  2982. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  2983. // check if name is dynamic.
  2984. let staticSlotName;
  2985. if (isStaticExp(slotName)) {
  2986. staticSlotName = slotName ? slotName.content : `default`;
  2987. }
  2988. else {
  2989. hasDynamicSlots = true;
  2990. }
  2991. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  2992. // check if this slot is conditional (v-if/v-for)
  2993. let vIf;
  2994. let vElse;
  2995. let vFor;
  2996. if ((vIf = findDir(slotElement, 'if'))) {
  2997. hasDynamicSlots = true;
  2998. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  2999. }
  3000. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  3001. // find adjacent v-if
  3002. let j = i;
  3003. let prev;
  3004. while (j--) {
  3005. prev = children[j];
  3006. if (prev.type !== 3 /* COMMENT */) {
  3007. break;
  3008. }
  3009. }
  3010. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  3011. // remove node
  3012. children.splice(i, 1);
  3013. i--;
  3014. // attach this slot to previous conditional
  3015. let conditional = dynamicSlots[dynamicSlots.length - 1];
  3016. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  3017. conditional = conditional.alternate;
  3018. }
  3019. conditional.alternate = vElse.exp
  3020. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  3021. : buildDynamicSlot(slotName, slotFunction);
  3022. }
  3023. else {
  3024. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  3025. }
  3026. }
  3027. else if ((vFor = findDir(slotElement, 'for'))) {
  3028. hasDynamicSlots = true;
  3029. const parseResult = vFor.parseResult ||
  3030. parseForExpression(vFor.exp, context);
  3031. if (parseResult) {
  3032. // Render the dynamic slots as an array and add it to the createSlot()
  3033. // args. The runtime knows how to handle it appropriately.
  3034. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  3035. parseResult.source,
  3036. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  3037. ]));
  3038. }
  3039. else {
  3040. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  3041. }
  3042. }
  3043. else {
  3044. // check duplicate static names
  3045. if (staticSlotName) {
  3046. if (seenSlotNames.has(staticSlotName)) {
  3047. context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  3048. continue;
  3049. }
  3050. seenSlotNames.add(staticSlotName);
  3051. if (staticSlotName === 'default') {
  3052. hasNamedDefaultSlot = true;
  3053. }
  3054. }
  3055. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  3056. }
  3057. }
  3058. if (!onComponentSlot) {
  3059. if (!hasTemplateSlots) {
  3060. // implicit default slot (on component)
  3061. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  3062. }
  3063. else if (implicitDefaultChildren.length) {
  3064. // implicit default slot (mixed with named slots)
  3065. if (hasNamedDefaultSlot) {
  3066. context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  3067. }
  3068. else {
  3069. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  3070. }
  3071. }
  3072. }
  3073. const slotFlag = hasDynamicSlots
  3074. ? 2 /* DYNAMIC */
  3075. : hasForwardedSlots(node.children)
  3076. ? 3 /* FORWARDED */
  3077. : 1 /* STABLE */;
  3078. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  3079. // 2 = compiled but dynamic = can skip normalization, but must run diff
  3080. // 1 = compiled and static = can skip normalization AND diff as optimized
  3081. createSimpleExpression('' + slotFlag, false))), loc);
  3082. if (dynamicSlots.length) {
  3083. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  3084. slots,
  3085. createArrayExpression(dynamicSlots)
  3086. ]);
  3087. }
  3088. return {
  3089. slots,
  3090. hasDynamicSlots
  3091. };
  3092. }
  3093. function buildDynamicSlot(name, fn) {
  3094. return createObjectExpression([
  3095. createObjectProperty(`name`, name),
  3096. createObjectProperty(`fn`, fn)
  3097. ]);
  3098. }
  3099. function hasForwardedSlots(children) {
  3100. for (let i = 0; i < children.length; i++) {
  3101. const child = children[i];
  3102. if (child.type === 1 /* ELEMENT */) {
  3103. if (child.tagType === 2 /* SLOT */ ||
  3104. (child.tagType === 0 /* ELEMENT */ &&
  3105. hasForwardedSlots(child.children))) {
  3106. return true;
  3107. }
  3108. }
  3109. }
  3110. return false;
  3111. }
  3112. // some directive transforms (e.g. v-model) may return a symbol for runtime
  3113. // import, which should be used instead of a resolveDirective call.
  3114. const directiveImportMap = new WeakMap();
  3115. // generate a JavaScript AST for this element's codegen
  3116. const transformElement = (node, context) => {
  3117. if (!(node.type === 1 /* ELEMENT */ &&
  3118. (node.tagType === 0 /* ELEMENT */ ||
  3119. node.tagType === 1 /* COMPONENT */))) {
  3120. return;
  3121. }
  3122. // perform the work on exit, after all child expressions have been
  3123. // processed and merged.
  3124. return function postTransformElement() {
  3125. const { tag, props } = node;
  3126. const isComponent = node.tagType === 1 /* COMPONENT */;
  3127. // The goal of the transform is to create a codegenNode implementing the
  3128. // VNodeCall interface.
  3129. const vnodeTag = isComponent
  3130. ? resolveComponentType(node, context)
  3131. : `"${tag}"`;
  3132. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  3133. let vnodeProps;
  3134. let vnodeChildren;
  3135. let vnodePatchFlag;
  3136. let patchFlag = 0;
  3137. let vnodeDynamicProps;
  3138. let dynamicPropNames;
  3139. let vnodeDirectives;
  3140. let shouldUseBlock =
  3141. // dynamic component may resolve to plain elements
  3142. isDynamicComponent ||
  3143. vnodeTag === TELEPORT ||
  3144. vnodeTag === SUSPENSE ||
  3145. (!isComponent &&
  3146. // <svg> and <foreignObject> must be forced into blocks so that block
  3147. // updates inside get proper isSVG flag at runtime. (#639, #643)
  3148. // This is technically web-specific, but splitting the logic out of core
  3149. // leads to too much unnecessary complexity.
  3150. (tag === 'svg' ||
  3151. tag === 'foreignObject' ||
  3152. // #938: elements with dynamic keys should be forced into blocks
  3153. findProp(node, 'key', true)));
  3154. // props
  3155. if (props.length > 0) {
  3156. const propsBuildResult = buildProps(node, context);
  3157. vnodeProps = propsBuildResult.props;
  3158. patchFlag = propsBuildResult.patchFlag;
  3159. dynamicPropNames = propsBuildResult.dynamicPropNames;
  3160. const directives = propsBuildResult.directives;
  3161. vnodeDirectives =
  3162. directives && directives.length
  3163. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  3164. : undefined;
  3165. }
  3166. // children
  3167. if (node.children.length > 0) {
  3168. if (vnodeTag === KEEP_ALIVE) {
  3169. // Although a built-in component, we compile KeepAlive with raw children
  3170. // instead of slot functions so that it can be used inside Transition
  3171. // or other Transition-wrapping HOCs.
  3172. // To ensure correct updates with block optimizations, we need to:
  3173. // 1. Force keep-alive into a block. This avoids its children being
  3174. // collected by a parent block.
  3175. shouldUseBlock = true;
  3176. // 2. Force keep-alive to always be updated, since it uses raw children.
  3177. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  3178. if ((process.env.NODE_ENV !== 'production') && node.children.length > 1) {
  3179. context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  3180. start: node.children[0].loc.start,
  3181. end: node.children[node.children.length - 1].loc.end,
  3182. source: ''
  3183. }));
  3184. }
  3185. }
  3186. const shouldBuildAsSlots = isComponent &&
  3187. // Teleport is not a real component and has dedicated runtime handling
  3188. vnodeTag !== TELEPORT &&
  3189. // explained above.
  3190. vnodeTag !== KEEP_ALIVE;
  3191. if (shouldBuildAsSlots) {
  3192. const { slots, hasDynamicSlots } = buildSlots(node, context);
  3193. vnodeChildren = slots;
  3194. if (hasDynamicSlots) {
  3195. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  3196. }
  3197. }
  3198. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  3199. const child = node.children[0];
  3200. const type = child.type;
  3201. // check for dynamic text children
  3202. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  3203. type === 8 /* COMPOUND_EXPRESSION */;
  3204. if (hasDynamicTextChild && !getStaticType(child)) {
  3205. patchFlag |= 1 /* TEXT */;
  3206. }
  3207. // pass directly if the only child is a text node
  3208. // (plain / interpolation / expression)
  3209. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  3210. vnodeChildren = child;
  3211. }
  3212. else {
  3213. vnodeChildren = node.children;
  3214. }
  3215. }
  3216. else {
  3217. vnodeChildren = node.children;
  3218. }
  3219. }
  3220. // patchFlag & dynamicPropNames
  3221. if (patchFlag !== 0) {
  3222. if ((process.env.NODE_ENV !== 'production')) {
  3223. if (patchFlag < 0) {
  3224. // special flags (negative and mutually exclusive)
  3225. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  3226. }
  3227. else {
  3228. // bitwise flags
  3229. const flagNames = Object.keys(PatchFlagNames)
  3230. .map(Number)
  3231. .filter(n => n > 0 && patchFlag & n)
  3232. .map(n => PatchFlagNames[n])
  3233. .join(`, `);
  3234. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  3235. }
  3236. }
  3237. else {
  3238. vnodePatchFlag = String(patchFlag);
  3239. }
  3240. if (dynamicPropNames && dynamicPropNames.length) {
  3241. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  3242. }
  3243. }
  3244. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
  3245. };
  3246. };
  3247. function resolveComponentType(node, context, ssr = false) {
  3248. const { tag } = node;
  3249. // 1. dynamic component
  3250. const isProp = node.tag === 'component' ? findProp(node, 'is') : findDir(node, 'is');
  3251. if (isProp) {
  3252. const exp = isProp.type === 6 /* ATTRIBUTE */
  3253. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  3254. : isProp.exp;
  3255. if (exp) {
  3256. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  3257. exp
  3258. ]);
  3259. }
  3260. }
  3261. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  3262. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  3263. if (builtIn) {
  3264. // built-ins are simply fallthroughs / have special handling during ssr
  3265. // no we don't need to import their runtime equivalents
  3266. if (!ssr)
  3267. context.helper(builtIn);
  3268. return builtIn;
  3269. }
  3270. // 3. user component (from setup bindings)
  3271. if (context.bindingMetadata[tag] === 'setup') {
  3272. return `$setup[${JSON.stringify(tag)}]`;
  3273. }
  3274. // 4. user component (resolve)
  3275. context.helper(RESOLVE_COMPONENT);
  3276. context.components.add(tag);
  3277. return toValidAssetId(tag, `component`);
  3278. }
  3279. function buildProps(node, context, props = node.props, ssr = false) {
  3280. const { tag, loc: elementLoc } = node;
  3281. const isComponent = node.tagType === 1 /* COMPONENT */;
  3282. let properties = [];
  3283. const mergeArgs = [];
  3284. const runtimeDirectives = [];
  3285. // patchFlag analysis
  3286. let patchFlag = 0;
  3287. let hasRef = false;
  3288. let hasClassBinding = false;
  3289. let hasStyleBinding = false;
  3290. let hasHydrationEventBinding = false;
  3291. let hasDynamicKeys = false;
  3292. let hasVnodeHook = false;
  3293. const dynamicPropNames = [];
  3294. const analyzePatchFlag = ({ key, value }) => {
  3295. if (isStaticExp(key)) {
  3296. const name = key.content;
  3297. const isEventHandler = isOn(name);
  3298. if (!isComponent &&
  3299. isEventHandler &&
  3300. // omit the flag for click handlers because hydration gives click
  3301. // dedicated fast path.
  3302. name.toLowerCase() !== 'onclick' &&
  3303. // omit v-model handlers
  3304. name !== 'onUpdate:modelValue' &&
  3305. // omit onVnodeXXX hooks
  3306. !isReservedProp(name)) {
  3307. hasHydrationEventBinding = true;
  3308. }
  3309. if (isEventHandler && isReservedProp(name)) {
  3310. hasVnodeHook = true;
  3311. }
  3312. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  3313. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  3314. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  3315. getStaticType(value) > 0)) {
  3316. // skip if the prop is a cached handler or has constant value
  3317. return;
  3318. }
  3319. if (name === 'ref') {
  3320. hasRef = true;
  3321. }
  3322. else if (name === 'class' && !isComponent) {
  3323. hasClassBinding = true;
  3324. }
  3325. else if (name === 'style' && !isComponent) {
  3326. hasStyleBinding = true;
  3327. }
  3328. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  3329. dynamicPropNames.push(name);
  3330. }
  3331. }
  3332. else {
  3333. hasDynamicKeys = true;
  3334. }
  3335. };
  3336. for (let i = 0; i < props.length; i++) {
  3337. // static attribute
  3338. const prop = props[i];
  3339. if (prop.type === 6 /* ATTRIBUTE */) {
  3340. const { loc, name, value } = prop;
  3341. if (name === 'ref') {
  3342. hasRef = true;
  3343. }
  3344. // skip :is on <component>
  3345. if (name === 'is' && tag === 'component') {
  3346. continue;
  3347. }
  3348. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', true, value ? value.loc : loc)));
  3349. }
  3350. else {
  3351. // directives
  3352. const { name, arg, exp, loc } = prop;
  3353. const isBind = name === 'bind';
  3354. const isOn = name === 'on';
  3355. // skip v-slot - it is handled by its dedicated transform.
  3356. if (name === 'slot') {
  3357. if (!isComponent) {
  3358. context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
  3359. }
  3360. continue;
  3361. }
  3362. // skip v-once - it is handled by its dedicated transform.
  3363. if (name === 'once') {
  3364. continue;
  3365. }
  3366. // skip v-is and :is on <component>
  3367. if (name === 'is' ||
  3368. (isBind && tag === 'component' && isBindKey(arg, 'is'))) {
  3369. continue;
  3370. }
  3371. // skip v-on in SSR compilation
  3372. if (isOn && ssr) {
  3373. continue;
  3374. }
  3375. // special case for v-bind and v-on with no argument
  3376. if (!arg && (isBind || isOn)) {
  3377. hasDynamicKeys = true;
  3378. if (exp) {
  3379. if (properties.length) {
  3380. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  3381. properties = [];
  3382. }
  3383. if (isBind) {
  3384. mergeArgs.push(exp);
  3385. }
  3386. else {
  3387. // v-on="obj" -> toHandlers(obj)
  3388. mergeArgs.push({
  3389. type: 14 /* JS_CALL_EXPRESSION */,
  3390. loc,
  3391. callee: context.helper(TO_HANDLERS),
  3392. arguments: [exp]
  3393. });
  3394. }
  3395. }
  3396. else {
  3397. context.onError(createCompilerError(isBind
  3398. ? 33 /* X_V_BIND_NO_EXPRESSION */
  3399. : 34 /* X_V_ON_NO_EXPRESSION */, loc));
  3400. }
  3401. continue;
  3402. }
  3403. const directiveTransform = context.directiveTransforms[name];
  3404. if (directiveTransform) {
  3405. // has built-in directive transform.
  3406. const { props, needRuntime } = directiveTransform(prop, node, context);
  3407. !ssr && props.forEach(analyzePatchFlag);
  3408. properties.push(...props);
  3409. if (needRuntime) {
  3410. runtimeDirectives.push(prop);
  3411. if (isSymbol(needRuntime)) {
  3412. directiveImportMap.set(prop, needRuntime);
  3413. }
  3414. }
  3415. }
  3416. else {
  3417. // no built-in transform, this is a user custom directive.
  3418. runtimeDirectives.push(prop);
  3419. }
  3420. }
  3421. }
  3422. let propsExpression = undefined;
  3423. // has v-bind="object" or v-on="object", wrap with mergeProps
  3424. if (mergeArgs.length) {
  3425. if (properties.length) {
  3426. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  3427. }
  3428. if (mergeArgs.length > 1) {
  3429. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  3430. }
  3431. else {
  3432. // single v-bind with nothing else - no need for a mergeProps call
  3433. propsExpression = mergeArgs[0];
  3434. }
  3435. }
  3436. else if (properties.length) {
  3437. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  3438. }
  3439. // patchFlag analysis
  3440. if (hasDynamicKeys) {
  3441. patchFlag |= 16 /* FULL_PROPS */;
  3442. }
  3443. else {
  3444. if (hasClassBinding) {
  3445. patchFlag |= 2 /* CLASS */;
  3446. }
  3447. if (hasStyleBinding) {
  3448. patchFlag |= 4 /* STYLE */;
  3449. }
  3450. if (dynamicPropNames.length) {
  3451. patchFlag |= 8 /* PROPS */;
  3452. }
  3453. if (hasHydrationEventBinding) {
  3454. patchFlag |= 32 /* HYDRATE_EVENTS */;
  3455. }
  3456. }
  3457. if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  3458. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  3459. patchFlag |= 512 /* NEED_PATCH */;
  3460. }
  3461. return {
  3462. props: propsExpression,
  3463. directives: runtimeDirectives,
  3464. patchFlag,
  3465. dynamicPropNames
  3466. };
  3467. }
  3468. // Dedupe props in an object literal.
  3469. // Literal duplicated attributes would have been warned during the parse phase,
  3470. // however, it's possible to encounter duplicated `onXXX` handlers with different
  3471. // modifiers. We also need to merge static and dynamic class / style attributes.
  3472. // - onXXX handlers / style: merge into array
  3473. // - class: merge into single expression with concatenation
  3474. function dedupeProperties(properties) {
  3475. const knownProps = new Map();
  3476. const deduped = [];
  3477. for (let i = 0; i < properties.length; i++) {
  3478. const prop = properties[i];
  3479. // dynamic keys are always allowed
  3480. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  3481. deduped.push(prop);
  3482. continue;
  3483. }
  3484. const name = prop.key.content;
  3485. const existing = knownProps.get(name);
  3486. if (existing) {
  3487. if (name === 'style' || name === 'class' || name.startsWith('on')) {
  3488. mergeAsArray(existing, prop);
  3489. }
  3490. // unexpected duplicate, should have emitted error during parse
  3491. }
  3492. else {
  3493. knownProps.set(name, prop);
  3494. deduped.push(prop);
  3495. }
  3496. }
  3497. return deduped;
  3498. }
  3499. function mergeAsArray(existing, incoming) {
  3500. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  3501. existing.value.elements.push(incoming.value);
  3502. }
  3503. else {
  3504. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  3505. }
  3506. }
  3507. function buildDirectiveArgs(dir, context) {
  3508. const dirArgs = [];
  3509. const runtime = directiveImportMap.get(dir);
  3510. if (runtime) {
  3511. dirArgs.push(context.helperString(runtime));
  3512. }
  3513. else {
  3514. // inject statement for resolving directive
  3515. context.helper(RESOLVE_DIRECTIVE);
  3516. context.directives.add(dir.name);
  3517. dirArgs.push(toValidAssetId(dir.name, `directive`));
  3518. }
  3519. const { loc } = dir;
  3520. if (dir.exp)
  3521. dirArgs.push(dir.exp);
  3522. if (dir.arg) {
  3523. if (!dir.exp) {
  3524. dirArgs.push(`void 0`);
  3525. }
  3526. dirArgs.push(dir.arg);
  3527. }
  3528. if (Object.keys(dir.modifiers).length) {
  3529. if (!dir.arg) {
  3530. if (!dir.exp) {
  3531. dirArgs.push(`void 0`);
  3532. }
  3533. dirArgs.push(`void 0`);
  3534. }
  3535. const trueExpression = createSimpleExpression(`true`, false, loc);
  3536. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  3537. }
  3538. return createArrayExpression(dirArgs, dir.loc);
  3539. }
  3540. function stringifyDynamicPropNames(props) {
  3541. let propsNamesString = `[`;
  3542. for (let i = 0, l = props.length; i < l; i++) {
  3543. propsNamesString += JSON.stringify(props[i]);
  3544. if (i < l - 1)
  3545. propsNamesString += ', ';
  3546. }
  3547. return propsNamesString + `]`;
  3548. }
  3549. const transformSlotOutlet = (node, context) => {
  3550. if (isSlotOutlet(node)) {
  3551. const { children, loc } = node;
  3552. const { slotName, slotProps } = processSlotOutlet(node, context);
  3553. const slotArgs = [
  3554. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  3555. slotName
  3556. ];
  3557. if (slotProps) {
  3558. slotArgs.push(slotProps);
  3559. }
  3560. if (children.length) {
  3561. if (!slotProps) {
  3562. slotArgs.push(`{}`);
  3563. }
  3564. slotArgs.push(createFunctionExpression([], children, false, false, loc));
  3565. }
  3566. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  3567. }
  3568. };
  3569. function processSlotOutlet(node, context) {
  3570. let slotName = `"default"`;
  3571. let slotProps = undefined;
  3572. // check for <slot name="xxx" OR :name="xxx" />
  3573. const name = findProp(node, 'name');
  3574. if (name) {
  3575. if (name.type === 6 /* ATTRIBUTE */ && name.value) {
  3576. // static name
  3577. slotName = JSON.stringify(name.value.content);
  3578. }
  3579. else if (name.type === 7 /* DIRECTIVE */ && name.exp) {
  3580. // dynamic name
  3581. slotName = name.exp;
  3582. }
  3583. }
  3584. const propsWithoutName = name
  3585. ? node.props.filter(p => p !== name)
  3586. : node.props;
  3587. if (propsWithoutName.length > 0) {
  3588. const { props, directives } = buildProps(node, context, propsWithoutName);
  3589. slotProps = props;
  3590. if (directives.length) {
  3591. context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  3592. }
  3593. }
  3594. return {
  3595. slotName,
  3596. slotProps
  3597. };
  3598. }
  3599. const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
  3600. const transformOn = (dir, node, context, augmentor) => {
  3601. const { loc, modifiers, arg } = dir;
  3602. if (!dir.exp && !modifiers.length) {
  3603. context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
  3604. }
  3605. let eventName;
  3606. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  3607. if (arg.isStatic) {
  3608. const rawName = arg.content;
  3609. // for all event listeners, auto convert it to camelCase. See issue #2249
  3610. eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
  3611. }
  3612. else {
  3613. // #2388
  3614. eventName = createCompoundExpression([
  3615. `${context.helperString(TO_HANDLER_KEY)}(`,
  3616. arg,
  3617. `)`
  3618. ]);
  3619. }
  3620. }
  3621. else {
  3622. // already a compound expression.
  3623. eventName = arg;
  3624. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  3625. eventName.children.push(`)`);
  3626. }
  3627. // handler processing
  3628. let exp = dir.exp;
  3629. if (exp && !exp.content.trim()) {
  3630. exp = undefined;
  3631. }
  3632. let isCacheable = context.cacheHandlers && !exp;
  3633. if (exp) {
  3634. const isMemberExp = isMemberExpression(exp.content);
  3635. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  3636. const hasMultipleStatements = exp.content.includes(`;`);
  3637. if ((process.env.NODE_ENV !== 'production') && true) {
  3638. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  3639. }
  3640. if (isInlineStatement || (isCacheable && isMemberExp)) {
  3641. // wrap inline statement in a function expression
  3642. exp = createCompoundExpression([
  3643. `${isInlineStatement ? `$event` : `(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  3644. exp,
  3645. hasMultipleStatements ? `}` : `)`
  3646. ]);
  3647. }
  3648. }
  3649. let ret = {
  3650. props: [
  3651. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  3652. ]
  3653. };
  3654. // apply extended compiler augmentor
  3655. if (augmentor) {
  3656. ret = augmentor(ret);
  3657. }
  3658. if (isCacheable) {
  3659. // cache handlers so that it's always the same handler being passed down.
  3660. // this avoids unnecessary re-renders when users use inline handlers on
  3661. // components.
  3662. ret.props[0].value = context.cache(ret.props[0].value);
  3663. }
  3664. return ret;
  3665. };
  3666. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  3667. // codegen for the entire props object. This transform here is only for v-bind
  3668. // *with* args.
  3669. const transformBind = (dir, node, context) => {
  3670. const { exp, modifiers, loc } = dir;
  3671. const arg = dir.arg;
  3672. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  3673. arg.children.unshift(`(`);
  3674. arg.children.push(`) || ""`);
  3675. }
  3676. else if (!arg.isStatic) {
  3677. arg.content = `${arg.content} || ""`;
  3678. }
  3679. // .prop is no longer necessary due to new patch behavior
  3680. // .sync is replaced by v-model:arg
  3681. if (modifiers.includes('camel')) {
  3682. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  3683. if (arg.isStatic) {
  3684. arg.content = camelize(arg.content);
  3685. }
  3686. else {
  3687. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  3688. }
  3689. }
  3690. else {
  3691. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  3692. arg.children.push(`)`);
  3693. }
  3694. }
  3695. if (!exp ||
  3696. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  3697. context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
  3698. return {
  3699. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  3700. };
  3701. }
  3702. return {
  3703. props: [createObjectProperty(arg, exp)]
  3704. };
  3705. };
  3706. // Merge adjacent text nodes and expressions into a single expression
  3707. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  3708. const transformText = (node, context) => {
  3709. if (node.type === 0 /* ROOT */ ||
  3710. node.type === 1 /* ELEMENT */ ||
  3711. node.type === 11 /* FOR */ ||
  3712. node.type === 10 /* IF_BRANCH */) {
  3713. // perform the transform on node exit so that all expressions have already
  3714. // been processed.
  3715. return () => {
  3716. const children = node.children;
  3717. let currentContainer = undefined;
  3718. let hasText = false;
  3719. for (let i = 0; i < children.length; i++) {
  3720. const child = children[i];
  3721. if (isText(child)) {
  3722. hasText = true;
  3723. for (let j = i + 1; j < children.length; j++) {
  3724. const next = children[j];
  3725. if (isText(next)) {
  3726. if (!currentContainer) {
  3727. currentContainer = children[i] = {
  3728. type: 8 /* COMPOUND_EXPRESSION */,
  3729. loc: child.loc,
  3730. children: [child]
  3731. };
  3732. }
  3733. // merge adjacent text node into current
  3734. currentContainer.children.push(` + `, next);
  3735. children.splice(j, 1);
  3736. j--;
  3737. }
  3738. else {
  3739. currentContainer = undefined;
  3740. break;
  3741. }
  3742. }
  3743. }
  3744. }
  3745. if (!hasText ||
  3746. // if this is a plain element with a single text child, leave it
  3747. // as-is since the runtime has dedicated fast path for this by directly
  3748. // setting textContent of the element.
  3749. // for component root it's always normalized anyway.
  3750. (children.length === 1 &&
  3751. (node.type === 0 /* ROOT */ ||
  3752. (node.type === 1 /* ELEMENT */ &&
  3753. node.tagType === 0 /* ELEMENT */)))) {
  3754. return;
  3755. }
  3756. // pre-convert text nodes into createTextVNode(text) calls to avoid
  3757. // runtime normalization.
  3758. for (let i = 0; i < children.length; i++) {
  3759. const child = children[i];
  3760. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  3761. const callArgs = [];
  3762. // createTextVNode defaults to single whitespace, so if it is a
  3763. // single space the code could be an empty call to save bytes.
  3764. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  3765. callArgs.push(child);
  3766. }
  3767. // mark dynamic text with flag so it gets patched inside a block
  3768. if (!context.ssr && child.type !== 2 /* TEXT */) {
  3769. callArgs.push(`${1 /* TEXT */} /* ${PatchFlagNames[1 /* TEXT */]} */`);
  3770. }
  3771. children[i] = {
  3772. type: 12 /* TEXT_CALL */,
  3773. content: child,
  3774. loc: child.loc,
  3775. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  3776. };
  3777. }
  3778. }
  3779. };
  3780. }
  3781. };
  3782. const seen = new WeakSet();
  3783. const transformOnce = (node, context) => {
  3784. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  3785. if (seen.has(node)) {
  3786. return;
  3787. }
  3788. seen.add(node);
  3789. context.helper(SET_BLOCK_TRACKING);
  3790. return () => {
  3791. const cur = context.currentNode;
  3792. if (cur.codegenNode) {
  3793. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  3794. }
  3795. };
  3796. }
  3797. };
  3798. const transformModel = (dir, node, context) => {
  3799. const { exp, arg } = dir;
  3800. if (!exp) {
  3801. context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  3802. return createTransformProps();
  3803. }
  3804. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : exp.loc.source;
  3805. if (!isMemberExpression(expString)) {
  3806. context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  3807. return createTransformProps();
  3808. }
  3809. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  3810. const eventName = arg
  3811. ? isStaticExp(arg)
  3812. ? `onUpdate:${arg.content}`
  3813. : createCompoundExpression(['"onUpdate:" + ', arg])
  3814. : `onUpdate:modelValue`;
  3815. const props = [
  3816. // modelValue: foo
  3817. createObjectProperty(propName, dir.exp),
  3818. // "onUpdate:modelValue": $event => (foo = $event)
  3819. createObjectProperty(eventName, createCompoundExpression([`$event => (`, exp, ` = $event)`]))
  3820. ];
  3821. // modelModifiers: { foo: true, "bar-baz": true }
  3822. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  3823. const modifiers = dir.modifiers
  3824. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  3825. .join(`, `);
  3826. const modifiersKey = arg
  3827. ? isStaticExp(arg)
  3828. ? `${arg.content}Modifiers`
  3829. : createCompoundExpression([arg, ' + "Modifiers"'])
  3830. : `modelModifiers`;
  3831. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, true)));
  3832. }
  3833. return createTransformProps(props);
  3834. };
  3835. function createTransformProps(props = []) {
  3836. return { props };
  3837. }
  3838. function getBaseTransformPreset(prefixIdentifiers) {
  3839. return [
  3840. [
  3841. transformOnce,
  3842. transformIf,
  3843. transformFor,
  3844. ...( (process.env.NODE_ENV !== 'production')
  3845. ? [transformExpression]
  3846. : []),
  3847. transformSlotOutlet,
  3848. transformElement,
  3849. trackSlotScopes,
  3850. transformText
  3851. ],
  3852. {
  3853. on: transformOn,
  3854. bind: transformBind,
  3855. model: transformModel
  3856. }
  3857. ];
  3858. }
  3859. // we name it `baseCompile` so that higher order compilers like
  3860. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  3861. function baseCompile(template, options = {}) {
  3862. const onError = options.onError || defaultOnError;
  3863. const isModuleMode = options.mode === 'module';
  3864. /* istanbul ignore if */
  3865. {
  3866. if (options.prefixIdentifiers === true) {
  3867. onError(createCompilerError(45 /* X_PREFIX_ID_NOT_SUPPORTED */));
  3868. }
  3869. else if (isModuleMode) {
  3870. onError(createCompilerError(46 /* X_MODULE_MODE_NOT_SUPPORTED */));
  3871. }
  3872. }
  3873. const prefixIdentifiers = !true ;
  3874. if ( options.cacheHandlers) {
  3875. onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  3876. }
  3877. if (options.scopeId && !isModuleMode) {
  3878. onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
  3879. }
  3880. const ast = isString(template) ? baseParse(template, options) : template;
  3881. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  3882. transform(ast, extend({}, options, {
  3883. prefixIdentifiers,
  3884. nodeTransforms: [
  3885. ...nodeTransforms,
  3886. ...(options.nodeTransforms || []) // user transforms
  3887. ],
  3888. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  3889. )
  3890. }));
  3891. return generate(ast, extend({}, options, {
  3892. prefixIdentifiers
  3893. }));
  3894. }
  3895. const noopDirectiveTransform = () => ({ props: [] });
  3896. export { BASE_TRANSITION, CAMELIZE, CAPITALIZE, CREATE_BLOCK, CREATE_COMMENT, CREATE_SLOTS, CREATE_STATIC, CREATE_TEXT, CREATE_VNODE, FRAGMENT, KEEP_ALIVE, MERGE_PROPS, OPEN_BLOCK, POP_SCOPE_ID, PUSH_SCOPE_ID, RENDER_LIST, RENDER_SLOT, RESOLVE_COMPONENT, RESOLVE_DIRECTIVE, RESOLVE_DYNAMIC_COMPONENT, SET_BLOCK_TRACKING, SUSPENSE, TELEPORT, TO_DISPLAY_STRING, TO_HANDLERS, TO_HANDLER_KEY, WITH_CTX, WITH_DIRECTIVES, WITH_SCOPE_ID, advancePositionWithClone, advancePositionWithMutation, assert, baseCompile, baseParse, buildProps, buildSlots, createArrayExpression, createAssignmentExpression, createBlockStatement, createCacheExpression, createCallExpression, createCompilerError, createCompoundExpression, createConditionalExpression, createForLoopParams, createFunctionExpression, createIfStatement, createInterpolation, createObjectExpression, createObjectProperty, createReturnStatement, createRoot, createSequenceExpression, createSimpleExpression, createStructuralDirectiveTransform, createTemplateLiteral, createTransformContext, createVNodeCall, findDir, findProp, generate, getBaseTransformPreset, getInnerRange, hasDynamicKeyVBind, hasScopeRef, helperNameMap, injectProp, isBindKey, isBuiltInType, isCoreComponent, isMemberExpression, isSimpleIdentifier, isSlotOutlet, isStaticExp, isTemplateNode, isText, isVSlot, locStub, noopDirectiveTransform, processExpression, processFor, processIf, processSlotOutlet, registerRuntimeHelpers, resolveComponentType, toValidAssetId, trackSlotScopes, trackVForSlotScopes, transform, transformBind, transformElement, transformExpression, transformModel, transformOn, traverseNode };