compiler-core.esm-bundler.js 195 KB

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