vue.esm-browser.js 598 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173
  1. /**
  2. * Make a map and return a function for checking if a key
  3. * is in that map.
  4. * IMPORTANT: all calls of this function must be prefixed with
  5. * \/\*#\_\_PURE\_\_\*\/
  6. * So that rollup can tree-shake them if necessary.
  7. */
  8. function makeMap(str, expectsLowerCase) {
  9. const map = Object.create(null);
  10. const list = str.split(',');
  11. for (let i = 0; i < list.length; i++) {
  12. map[list[i]] = true;
  13. }
  14. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  15. }
  16. /**
  17. * dev only flag -> name mapping
  18. */
  19. const PatchFlagNames = {
  20. [1 /* PatchFlags.TEXT */]: `TEXT`,
  21. [2 /* PatchFlags.CLASS */]: `CLASS`,
  22. [4 /* PatchFlags.STYLE */]: `STYLE`,
  23. [8 /* PatchFlags.PROPS */]: `PROPS`,
  24. [16 /* PatchFlags.FULL_PROPS */]: `FULL_PROPS`,
  25. [32 /* PatchFlags.HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  26. [64 /* PatchFlags.STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  27. [128 /* PatchFlags.KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  28. [256 /* PatchFlags.UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  29. [512 /* PatchFlags.NEED_PATCH */]: `NEED_PATCH`,
  30. [1024 /* PatchFlags.DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  31. [2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  32. [-1 /* PatchFlags.HOISTED */]: `HOISTED`,
  33. [-2 /* PatchFlags.BAIL */]: `BAIL`
  34. };
  35. /**
  36. * Dev only
  37. */
  38. const slotFlagsText = {
  39. [1 /* SlotFlags.STABLE */]: 'STABLE',
  40. [2 /* SlotFlags.DYNAMIC */]: 'DYNAMIC',
  41. [3 /* SlotFlags.FORWARDED */]: 'FORWARDED'
  42. };
  43. const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  44. 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  45. 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
  46. const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
  47. const range = 2;
  48. function generateCodeFrame(source, start = 0, end = source.length) {
  49. // Split the content into individual lines but capture the newline sequence
  50. // that separated each line. This is important because the actual sequence is
  51. // needed to properly take into account the full line length for offset
  52. // comparison
  53. let lines = source.split(/(\r?\n)/);
  54. // Separate the lines and newline sequences into separate arrays for easier referencing
  55. const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
  56. lines = lines.filter((_, idx) => idx % 2 === 0);
  57. let count = 0;
  58. const res = [];
  59. for (let i = 0; i < lines.length; i++) {
  60. count +=
  61. lines[i].length +
  62. ((newlineSequences[i] && newlineSequences[i].length) || 0);
  63. if (count >= start) {
  64. for (let j = i - range; j <= i + range || end > count; j++) {
  65. if (j < 0 || j >= lines.length)
  66. continue;
  67. const line = j + 1;
  68. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  69. const lineLength = lines[j].length;
  70. const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
  71. if (j === i) {
  72. // push underline
  73. const pad = start - (count - (lineLength + newLineSeqLength));
  74. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  75. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  76. }
  77. else if (j > i) {
  78. if (end > count) {
  79. const length = Math.max(Math.min(end - count, lineLength), 1);
  80. res.push(` | ` + '^'.repeat(length));
  81. }
  82. count += lineLength + newLineSeqLength;
  83. }
  84. }
  85. break;
  86. }
  87. }
  88. return res.join('\n');
  89. }
  90. function normalizeStyle(value) {
  91. if (isArray(value)) {
  92. const res = {};
  93. for (let i = 0; i < value.length; i++) {
  94. const item = value[i];
  95. const normalized = isString(item)
  96. ? parseStringStyle(item)
  97. : normalizeStyle(item);
  98. if (normalized) {
  99. for (const key in normalized) {
  100. res[key] = normalized[key];
  101. }
  102. }
  103. }
  104. return res;
  105. }
  106. else if (isString(value)) {
  107. return value;
  108. }
  109. else if (isObject(value)) {
  110. return value;
  111. }
  112. }
  113. const listDelimiterRE = /;(?![^(]*\))/g;
  114. const propertyDelimiterRE = /:([^]+)/;
  115. const styleCommentRE = /\/\*.*?\*\//gs;
  116. function parseStringStyle(cssText) {
  117. const ret = {};
  118. cssText
  119. .replace(styleCommentRE, '')
  120. .split(listDelimiterRE)
  121. .forEach(item => {
  122. if (item) {
  123. const tmp = item.split(propertyDelimiterRE);
  124. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  125. }
  126. });
  127. return ret;
  128. }
  129. function normalizeClass(value) {
  130. let res = '';
  131. if (isString(value)) {
  132. res = value;
  133. }
  134. else if (isArray(value)) {
  135. for (let i = 0; i < value.length; i++) {
  136. const normalized = normalizeClass(value[i]);
  137. if (normalized) {
  138. res += normalized + ' ';
  139. }
  140. }
  141. }
  142. else if (isObject(value)) {
  143. for (const name in value) {
  144. if (value[name]) {
  145. res += name + ' ';
  146. }
  147. }
  148. }
  149. return res.trim();
  150. }
  151. function normalizeProps(props) {
  152. if (!props)
  153. return null;
  154. let { class: klass, style } = props;
  155. if (klass && !isString(klass)) {
  156. props.class = normalizeClass(klass);
  157. }
  158. if (style) {
  159. props.style = normalizeStyle(style);
  160. }
  161. return props;
  162. }
  163. // These tag configs are shared between compiler-dom and runtime-dom, so they
  164. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  165. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  166. 'header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
  167. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  168. 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
  169. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  170. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  171. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  172. 'option,output,progress,select,textarea,details,dialog,menu,' +
  173. 'summary,template,blockquote,iframe,tfoot';
  174. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  175. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  176. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  177. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  178. 'feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  179. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  180. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  181. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  182. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  183. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  184. 'text,textPath,title,tspan,unknown,use,view';
  185. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  186. /**
  187. * Compiler only.
  188. * Do NOT use in runtime code paths unless behind `true` flag.
  189. */
  190. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  191. /**
  192. * Compiler only.
  193. * Do NOT use in runtime code paths unless behind `true` flag.
  194. */
  195. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  196. /**
  197. * Compiler only.
  198. * Do NOT use in runtime code paths unless behind `true` flag.
  199. */
  200. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  201. /**
  202. * On the client we only need to offer special cases for boolean attributes that
  203. * have different names from their corresponding dom properties:
  204. * - itemscope -> N/A
  205. * - allowfullscreen -> allowFullscreen
  206. * - formnovalidate -> formNoValidate
  207. * - ismap -> isMap
  208. * - nomodule -> noModule
  209. * - novalidate -> noValidate
  210. * - readonly -> readOnly
  211. */
  212. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  213. const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
  214. /**
  215. * Boolean attributes should be included if the value is truthy or ''.
  216. * e.g. `<select multiple>` compiles to `{ multiple: '' }`
  217. */
  218. function includeBooleanAttr(value) {
  219. return !!value || value === '';
  220. }
  221. function looseCompareArrays(a, b) {
  222. if (a.length !== b.length)
  223. return false;
  224. let equal = true;
  225. for (let i = 0; equal && i < a.length; i++) {
  226. equal = looseEqual(a[i], b[i]);
  227. }
  228. return equal;
  229. }
  230. function looseEqual(a, b) {
  231. if (a === b)
  232. return true;
  233. let aValidType = isDate(a);
  234. let bValidType = isDate(b);
  235. if (aValidType || bValidType) {
  236. return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  237. }
  238. aValidType = isSymbol(a);
  239. bValidType = isSymbol(b);
  240. if (aValidType || bValidType) {
  241. return a === b;
  242. }
  243. aValidType = isArray(a);
  244. bValidType = isArray(b);
  245. if (aValidType || bValidType) {
  246. return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  247. }
  248. aValidType = isObject(a);
  249. bValidType = isObject(b);
  250. if (aValidType || bValidType) {
  251. /* istanbul ignore if: this if will probably never be called */
  252. if (!aValidType || !bValidType) {
  253. return false;
  254. }
  255. const aKeysCount = Object.keys(a).length;
  256. const bKeysCount = Object.keys(b).length;
  257. if (aKeysCount !== bKeysCount) {
  258. return false;
  259. }
  260. for (const key in a) {
  261. const aHasKey = a.hasOwnProperty(key);
  262. const bHasKey = b.hasOwnProperty(key);
  263. if ((aHasKey && !bHasKey) ||
  264. (!aHasKey && bHasKey) ||
  265. !looseEqual(a[key], b[key])) {
  266. return false;
  267. }
  268. }
  269. }
  270. return String(a) === String(b);
  271. }
  272. function looseIndexOf(arr, val) {
  273. return arr.findIndex(item => looseEqual(item, val));
  274. }
  275. /**
  276. * For converting {{ interpolation }} values to displayed strings.
  277. * @private
  278. */
  279. const toDisplayString = (val) => {
  280. return isString(val)
  281. ? val
  282. : val == null
  283. ? ''
  284. : isArray(val) ||
  285. (isObject(val) &&
  286. (val.toString === objectToString || !isFunction(val.toString)))
  287. ? JSON.stringify(val, replacer, 2)
  288. : String(val);
  289. };
  290. const replacer = (_key, val) => {
  291. // can't use isRef here since @vue/shared has no deps
  292. if (val && val.__v_isRef) {
  293. return replacer(_key, val.value);
  294. }
  295. else if (isMap(val)) {
  296. return {
  297. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  298. entries[`${key} =>`] = val;
  299. return entries;
  300. }, {})
  301. };
  302. }
  303. else if (isSet(val)) {
  304. return {
  305. [`Set(${val.size})`]: [...val.values()]
  306. };
  307. }
  308. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  309. return String(val);
  310. }
  311. return val;
  312. };
  313. const EMPTY_OBJ = Object.freeze({})
  314. ;
  315. const EMPTY_ARR = Object.freeze([]) ;
  316. const NOOP = () => { };
  317. /**
  318. * Always return false.
  319. */
  320. const NO = () => false;
  321. const onRE = /^on[^a-z]/;
  322. const isOn = (key) => onRE.test(key);
  323. const isModelListener = (key) => key.startsWith('onUpdate:');
  324. const extend = Object.assign;
  325. const remove = (arr, el) => {
  326. const i = arr.indexOf(el);
  327. if (i > -1) {
  328. arr.splice(i, 1);
  329. }
  330. };
  331. const hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  332. const hasOwn = (val, key) => hasOwnProperty$1.call(val, key);
  333. const isArray = Array.isArray;
  334. const isMap = (val) => toTypeString(val) === '[object Map]';
  335. const isSet = (val) => toTypeString(val) === '[object Set]';
  336. const isDate = (val) => toTypeString(val) === '[object Date]';
  337. const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
  338. const isFunction = (val) => typeof val === 'function';
  339. const isString = (val) => typeof val === 'string';
  340. const isSymbol = (val) => typeof val === 'symbol';
  341. const isObject = (val) => val !== null && typeof val === 'object';
  342. const isPromise = (val) => {
  343. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  344. };
  345. const objectToString = Object.prototype.toString;
  346. const toTypeString = (value) => objectToString.call(value);
  347. const toRawType = (value) => {
  348. // extract "RawType" from strings like "[object RawType]"
  349. return toTypeString(value).slice(8, -1);
  350. };
  351. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  352. const isIntegerKey = (key) => isString(key) &&
  353. key !== 'NaN' &&
  354. key[0] !== '-' &&
  355. '' + parseInt(key, 10) === key;
  356. const isReservedProp = /*#__PURE__*/ makeMap(
  357. // the leading comma is intentional so empty string "" is also included
  358. ',key,ref,ref_for,ref_key,' +
  359. 'onVnodeBeforeMount,onVnodeMounted,' +
  360. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  361. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  362. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
  363. const cacheStringFunction = (fn) => {
  364. const cache = Object.create(null);
  365. return ((str) => {
  366. const hit = cache[str];
  367. return hit || (cache[str] = fn(str));
  368. });
  369. };
  370. const camelizeRE = /-(\w)/g;
  371. /**
  372. * @private
  373. */
  374. const camelize = cacheStringFunction((str) => {
  375. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  376. });
  377. const hyphenateRE = /\B([A-Z])/g;
  378. /**
  379. * @private
  380. */
  381. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  382. /**
  383. * @private
  384. */
  385. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  386. /**
  387. * @private
  388. */
  389. const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
  390. // compare whether a value has changed, accounting for NaN.
  391. const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
  392. const invokeArrayFns = (fns, arg) => {
  393. for (let i = 0; i < fns.length; i++) {
  394. fns[i](arg);
  395. }
  396. };
  397. const def = (obj, key, value) => {
  398. Object.defineProperty(obj, key, {
  399. configurable: true,
  400. enumerable: false,
  401. value
  402. });
  403. };
  404. /**
  405. * "123-foo" will be parsed to 123
  406. * This is used for the .number modifier in v-model
  407. */
  408. const looseToNumber = (val) => {
  409. const n = parseFloat(val);
  410. return isNaN(n) ? val : n;
  411. };
  412. /**
  413. * Only conerces number-like strings
  414. * "123-foo" will be returned as-is
  415. */
  416. const toNumber = (val) => {
  417. const n = isString(val) ? Number(val) : NaN;
  418. return isNaN(n) ? val : n;
  419. };
  420. let _globalThis;
  421. const getGlobalThis = () => {
  422. return (_globalThis ||
  423. (_globalThis =
  424. typeof globalThis !== 'undefined'
  425. ? globalThis
  426. : typeof self !== 'undefined'
  427. ? self
  428. : typeof window !== 'undefined'
  429. ? window
  430. : typeof global !== 'undefined'
  431. ? global
  432. : {}));
  433. };
  434. function warn$1(msg, ...args) {
  435. console.warn(`[Vue warn] ${msg}`, ...args);
  436. }
  437. let activeEffectScope;
  438. class EffectScope {
  439. constructor(detached = false) {
  440. this.detached = detached;
  441. /**
  442. * @internal
  443. */
  444. this._active = true;
  445. /**
  446. * @internal
  447. */
  448. this.effects = [];
  449. /**
  450. * @internal
  451. */
  452. this.cleanups = [];
  453. this.parent = activeEffectScope;
  454. if (!detached && activeEffectScope) {
  455. this.index =
  456. (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
  457. }
  458. }
  459. get active() {
  460. return this._active;
  461. }
  462. run(fn) {
  463. if (this._active) {
  464. const currentEffectScope = activeEffectScope;
  465. try {
  466. activeEffectScope = this;
  467. return fn();
  468. }
  469. finally {
  470. activeEffectScope = currentEffectScope;
  471. }
  472. }
  473. else {
  474. warn$1(`cannot run an inactive effect scope.`);
  475. }
  476. }
  477. /**
  478. * This should only be called on non-detached scopes
  479. * @internal
  480. */
  481. on() {
  482. activeEffectScope = this;
  483. }
  484. /**
  485. * This should only be called on non-detached scopes
  486. * @internal
  487. */
  488. off() {
  489. activeEffectScope = this.parent;
  490. }
  491. stop(fromParent) {
  492. if (this._active) {
  493. let i, l;
  494. for (i = 0, l = this.effects.length; i < l; i++) {
  495. this.effects[i].stop();
  496. }
  497. for (i = 0, l = this.cleanups.length; i < l; i++) {
  498. this.cleanups[i]();
  499. }
  500. if (this.scopes) {
  501. for (i = 0, l = this.scopes.length; i < l; i++) {
  502. this.scopes[i].stop(true);
  503. }
  504. }
  505. // nested scope, dereference from parent to avoid memory leaks
  506. if (!this.detached && this.parent && !fromParent) {
  507. // optimized O(1) removal
  508. const last = this.parent.scopes.pop();
  509. if (last && last !== this) {
  510. this.parent.scopes[this.index] = last;
  511. last.index = this.index;
  512. }
  513. }
  514. this.parent = undefined;
  515. this._active = false;
  516. }
  517. }
  518. }
  519. function effectScope(detached) {
  520. return new EffectScope(detached);
  521. }
  522. function recordEffectScope(effect, scope = activeEffectScope) {
  523. if (scope && scope.active) {
  524. scope.effects.push(effect);
  525. }
  526. }
  527. function getCurrentScope() {
  528. return activeEffectScope;
  529. }
  530. function onScopeDispose(fn) {
  531. if (activeEffectScope) {
  532. activeEffectScope.cleanups.push(fn);
  533. }
  534. else {
  535. warn$1(`onScopeDispose() is called when there is no active effect scope` +
  536. ` to be associated with.`);
  537. }
  538. }
  539. const createDep = (effects) => {
  540. const dep = new Set(effects);
  541. dep.w = 0;
  542. dep.n = 0;
  543. return dep;
  544. };
  545. const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
  546. const newTracked = (dep) => (dep.n & trackOpBit) > 0;
  547. const initDepMarkers = ({ deps }) => {
  548. if (deps.length) {
  549. for (let i = 0; i < deps.length; i++) {
  550. deps[i].w |= trackOpBit; // set was tracked
  551. }
  552. }
  553. };
  554. const finalizeDepMarkers = (effect) => {
  555. const { deps } = effect;
  556. if (deps.length) {
  557. let ptr = 0;
  558. for (let i = 0; i < deps.length; i++) {
  559. const dep = deps[i];
  560. if (wasTracked(dep) && !newTracked(dep)) {
  561. dep.delete(effect);
  562. }
  563. else {
  564. deps[ptr++] = dep;
  565. }
  566. // clear bits
  567. dep.w &= ~trackOpBit;
  568. dep.n &= ~trackOpBit;
  569. }
  570. deps.length = ptr;
  571. }
  572. };
  573. const targetMap = new WeakMap();
  574. // The number of effects currently being tracked recursively.
  575. let effectTrackDepth = 0;
  576. let trackOpBit = 1;
  577. /**
  578. * The bitwise track markers support at most 30 levels of recursion.
  579. * This value is chosen to enable modern JS engines to use a SMI on all platforms.
  580. * When recursion depth is greater, fall back to using a full cleanup.
  581. */
  582. const maxMarkerBits = 30;
  583. let activeEffect;
  584. const ITERATE_KEY = Symbol('iterate' );
  585. const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
  586. class ReactiveEffect {
  587. constructor(fn, scheduler = null, scope) {
  588. this.fn = fn;
  589. this.scheduler = scheduler;
  590. this.active = true;
  591. this.deps = [];
  592. this.parent = undefined;
  593. recordEffectScope(this, scope);
  594. }
  595. run() {
  596. if (!this.active) {
  597. return this.fn();
  598. }
  599. let parent = activeEffect;
  600. let lastShouldTrack = shouldTrack;
  601. while (parent) {
  602. if (parent === this) {
  603. return;
  604. }
  605. parent = parent.parent;
  606. }
  607. try {
  608. this.parent = activeEffect;
  609. activeEffect = this;
  610. shouldTrack = true;
  611. trackOpBit = 1 << ++effectTrackDepth;
  612. if (effectTrackDepth <= maxMarkerBits) {
  613. initDepMarkers(this);
  614. }
  615. else {
  616. cleanupEffect(this);
  617. }
  618. return this.fn();
  619. }
  620. finally {
  621. if (effectTrackDepth <= maxMarkerBits) {
  622. finalizeDepMarkers(this);
  623. }
  624. trackOpBit = 1 << --effectTrackDepth;
  625. activeEffect = this.parent;
  626. shouldTrack = lastShouldTrack;
  627. this.parent = undefined;
  628. if (this.deferStop) {
  629. this.stop();
  630. }
  631. }
  632. }
  633. stop() {
  634. // stopped while running itself - defer the cleanup
  635. if (activeEffect === this) {
  636. this.deferStop = true;
  637. }
  638. else if (this.active) {
  639. cleanupEffect(this);
  640. if (this.onStop) {
  641. this.onStop();
  642. }
  643. this.active = false;
  644. }
  645. }
  646. }
  647. function cleanupEffect(effect) {
  648. const { deps } = effect;
  649. if (deps.length) {
  650. for (let i = 0; i < deps.length; i++) {
  651. deps[i].delete(effect);
  652. }
  653. deps.length = 0;
  654. }
  655. }
  656. function effect(fn, options) {
  657. if (fn.effect) {
  658. fn = fn.effect.fn;
  659. }
  660. const _effect = new ReactiveEffect(fn);
  661. if (options) {
  662. extend(_effect, options);
  663. if (options.scope)
  664. recordEffectScope(_effect, options.scope);
  665. }
  666. if (!options || !options.lazy) {
  667. _effect.run();
  668. }
  669. const runner = _effect.run.bind(_effect);
  670. runner.effect = _effect;
  671. return runner;
  672. }
  673. function stop(runner) {
  674. runner.effect.stop();
  675. }
  676. let shouldTrack = true;
  677. const trackStack = [];
  678. function pauseTracking() {
  679. trackStack.push(shouldTrack);
  680. shouldTrack = false;
  681. }
  682. function resetTracking() {
  683. const last = trackStack.pop();
  684. shouldTrack = last === undefined ? true : last;
  685. }
  686. function track(target, type, key) {
  687. if (shouldTrack && activeEffect) {
  688. let depsMap = targetMap.get(target);
  689. if (!depsMap) {
  690. targetMap.set(target, (depsMap = new Map()));
  691. }
  692. let dep = depsMap.get(key);
  693. if (!dep) {
  694. depsMap.set(key, (dep = createDep()));
  695. }
  696. const eventInfo = { effect: activeEffect, target, type, key }
  697. ;
  698. trackEffects(dep, eventInfo);
  699. }
  700. }
  701. function trackEffects(dep, debuggerEventExtraInfo) {
  702. let shouldTrack = false;
  703. if (effectTrackDepth <= maxMarkerBits) {
  704. if (!newTracked(dep)) {
  705. dep.n |= trackOpBit; // set newly tracked
  706. shouldTrack = !wasTracked(dep);
  707. }
  708. }
  709. else {
  710. // Full cleanup mode.
  711. shouldTrack = !dep.has(activeEffect);
  712. }
  713. if (shouldTrack) {
  714. dep.add(activeEffect);
  715. activeEffect.deps.push(dep);
  716. if (activeEffect.onTrack) {
  717. activeEffect.onTrack(Object.assign({ effect: activeEffect }, debuggerEventExtraInfo));
  718. }
  719. }
  720. }
  721. function trigger(target, type, key, newValue, oldValue, oldTarget) {
  722. const depsMap = targetMap.get(target);
  723. if (!depsMap) {
  724. // never been tracked
  725. return;
  726. }
  727. let deps = [];
  728. if (type === "clear" /* TriggerOpTypes.CLEAR */) {
  729. // collection being cleared
  730. // trigger all effects for target
  731. deps = [...depsMap.values()];
  732. }
  733. else if (key === 'length' && isArray(target)) {
  734. const newLength = Number(newValue);
  735. depsMap.forEach((dep, key) => {
  736. if (key === 'length' || key >= newLength) {
  737. deps.push(dep);
  738. }
  739. });
  740. }
  741. else {
  742. // schedule runs for SET | ADD | DELETE
  743. if (key !== void 0) {
  744. deps.push(depsMap.get(key));
  745. }
  746. // also run for iteration key on ADD | DELETE | Map.SET
  747. switch (type) {
  748. case "add" /* TriggerOpTypes.ADD */:
  749. if (!isArray(target)) {
  750. deps.push(depsMap.get(ITERATE_KEY));
  751. if (isMap(target)) {
  752. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  753. }
  754. }
  755. else if (isIntegerKey(key)) {
  756. // new index added to array -> length changes
  757. deps.push(depsMap.get('length'));
  758. }
  759. break;
  760. case "delete" /* TriggerOpTypes.DELETE */:
  761. if (!isArray(target)) {
  762. deps.push(depsMap.get(ITERATE_KEY));
  763. if (isMap(target)) {
  764. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  765. }
  766. }
  767. break;
  768. case "set" /* TriggerOpTypes.SET */:
  769. if (isMap(target)) {
  770. deps.push(depsMap.get(ITERATE_KEY));
  771. }
  772. break;
  773. }
  774. }
  775. const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
  776. ;
  777. if (deps.length === 1) {
  778. if (deps[0]) {
  779. {
  780. triggerEffects(deps[0], eventInfo);
  781. }
  782. }
  783. }
  784. else {
  785. const effects = [];
  786. for (const dep of deps) {
  787. if (dep) {
  788. effects.push(...dep);
  789. }
  790. }
  791. {
  792. triggerEffects(createDep(effects), eventInfo);
  793. }
  794. }
  795. }
  796. function triggerEffects(dep, debuggerEventExtraInfo) {
  797. // spread into array for stabilization
  798. const effects = isArray(dep) ? dep : [...dep];
  799. for (const effect of effects) {
  800. if (effect.computed) {
  801. triggerEffect(effect, debuggerEventExtraInfo);
  802. }
  803. }
  804. for (const effect of effects) {
  805. if (!effect.computed) {
  806. triggerEffect(effect, debuggerEventExtraInfo);
  807. }
  808. }
  809. }
  810. function triggerEffect(effect, debuggerEventExtraInfo) {
  811. if (effect !== activeEffect || effect.allowRecurse) {
  812. if (effect.onTrigger) {
  813. effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
  814. }
  815. if (effect.scheduler) {
  816. effect.scheduler();
  817. }
  818. else {
  819. effect.run();
  820. }
  821. }
  822. }
  823. function getDepFromReactive(object, key) {
  824. var _a;
  825. return (_a = targetMap.get(object)) === null || _a === void 0 ? void 0 : _a.get(key);
  826. }
  827. const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
  828. const builtInSymbols = new Set(
  829. /*#__PURE__*/
  830. Object.getOwnPropertyNames(Symbol)
  831. // ios10.x Object.getOwnPropertyNames(Symbol) can enumerate 'arguments' and 'caller'
  832. // but accessing them on Symbol leads to TypeError because Symbol is a strict mode
  833. // function
  834. .filter(key => key !== 'arguments' && key !== 'caller')
  835. .map(key => Symbol[key])
  836. .filter(isSymbol));
  837. const get$1 = /*#__PURE__*/ createGetter();
  838. const shallowGet = /*#__PURE__*/ createGetter(false, true);
  839. const readonlyGet = /*#__PURE__*/ createGetter(true);
  840. const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
  841. const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
  842. function createArrayInstrumentations() {
  843. const instrumentations = {};
  844. ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
  845. instrumentations[key] = function (...args) {
  846. const arr = toRaw(this);
  847. for (let i = 0, l = this.length; i < l; i++) {
  848. track(arr, "get" /* TrackOpTypes.GET */, i + '');
  849. }
  850. // we run the method using the original args first (which may be reactive)
  851. const res = arr[key](...args);
  852. if (res === -1 || res === false) {
  853. // if that didn't work, run it again using raw values.
  854. return arr[key](...args.map(toRaw));
  855. }
  856. else {
  857. return res;
  858. }
  859. };
  860. });
  861. ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
  862. instrumentations[key] = function (...args) {
  863. pauseTracking();
  864. const res = toRaw(this)[key].apply(this, args);
  865. resetTracking();
  866. return res;
  867. };
  868. });
  869. return instrumentations;
  870. }
  871. function hasOwnProperty(key) {
  872. const obj = toRaw(this);
  873. track(obj, "has" /* TrackOpTypes.HAS */, key);
  874. return obj.hasOwnProperty(key);
  875. }
  876. function createGetter(isReadonly = false, shallow = false) {
  877. return function get(target, key, receiver) {
  878. if (key === "__v_isReactive" /* ReactiveFlags.IS_REACTIVE */) {
  879. return !isReadonly;
  880. }
  881. else if (key === "__v_isReadonly" /* ReactiveFlags.IS_READONLY */) {
  882. return isReadonly;
  883. }
  884. else if (key === "__v_isShallow" /* ReactiveFlags.IS_SHALLOW */) {
  885. return shallow;
  886. }
  887. else if (key === "__v_raw" /* ReactiveFlags.RAW */ &&
  888. receiver ===
  889. (isReadonly
  890. ? shallow
  891. ? shallowReadonlyMap
  892. : readonlyMap
  893. : shallow
  894. ? shallowReactiveMap
  895. : reactiveMap).get(target)) {
  896. return target;
  897. }
  898. const targetIsArray = isArray(target);
  899. if (!isReadonly) {
  900. if (targetIsArray && hasOwn(arrayInstrumentations, key)) {
  901. return Reflect.get(arrayInstrumentations, key, receiver);
  902. }
  903. if (key === 'hasOwnProperty') {
  904. return hasOwnProperty;
  905. }
  906. }
  907. const res = Reflect.get(target, key, receiver);
  908. if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
  909. return res;
  910. }
  911. if (!isReadonly) {
  912. track(target, "get" /* TrackOpTypes.GET */, key);
  913. }
  914. if (shallow) {
  915. return res;
  916. }
  917. if (isRef(res)) {
  918. // ref unwrapping - skip unwrap for Array + integer key.
  919. return targetIsArray && isIntegerKey(key) ? res : res.value;
  920. }
  921. if (isObject(res)) {
  922. // Convert returned value into a proxy as well. we do the isObject check
  923. // here to avoid invalid value warning. Also need to lazy access readonly
  924. // and reactive here to avoid circular dependency.
  925. return isReadonly ? readonly(res) : reactive(res);
  926. }
  927. return res;
  928. };
  929. }
  930. const set$1 = /*#__PURE__*/ createSetter();
  931. const shallowSet = /*#__PURE__*/ createSetter(true);
  932. function createSetter(shallow = false) {
  933. return function set(target, key, value, receiver) {
  934. let oldValue = target[key];
  935. if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
  936. return false;
  937. }
  938. if (!shallow) {
  939. if (!isShallow(value) && !isReadonly(value)) {
  940. oldValue = toRaw(oldValue);
  941. value = toRaw(value);
  942. }
  943. if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
  944. oldValue.value = value;
  945. return true;
  946. }
  947. }
  948. const hadKey = isArray(target) && isIntegerKey(key)
  949. ? Number(key) < target.length
  950. : hasOwn(target, key);
  951. const result = Reflect.set(target, key, value, receiver);
  952. // don't trigger if target is something up in the prototype chain of original
  953. if (target === toRaw(receiver)) {
  954. if (!hadKey) {
  955. trigger(target, "add" /* TriggerOpTypes.ADD */, key, value);
  956. }
  957. else if (hasChanged(value, oldValue)) {
  958. trigger(target, "set" /* TriggerOpTypes.SET */, key, value, oldValue);
  959. }
  960. }
  961. return result;
  962. };
  963. }
  964. function deleteProperty(target, key) {
  965. const hadKey = hasOwn(target, key);
  966. const oldValue = target[key];
  967. const result = Reflect.deleteProperty(target, key);
  968. if (result && hadKey) {
  969. trigger(target, "delete" /* TriggerOpTypes.DELETE */, key, undefined, oldValue);
  970. }
  971. return result;
  972. }
  973. function has$1(target, key) {
  974. const result = Reflect.has(target, key);
  975. if (!isSymbol(key) || !builtInSymbols.has(key)) {
  976. track(target, "has" /* TrackOpTypes.HAS */, key);
  977. }
  978. return result;
  979. }
  980. function ownKeys(target) {
  981. track(target, "iterate" /* TrackOpTypes.ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
  982. return Reflect.ownKeys(target);
  983. }
  984. const mutableHandlers = {
  985. get: get$1,
  986. set: set$1,
  987. deleteProperty,
  988. has: has$1,
  989. ownKeys
  990. };
  991. const readonlyHandlers = {
  992. get: readonlyGet,
  993. set(target, key) {
  994. {
  995. warn$1(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
  996. }
  997. return true;
  998. },
  999. deleteProperty(target, key) {
  1000. {
  1001. warn$1(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
  1002. }
  1003. return true;
  1004. }
  1005. };
  1006. const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
  1007. get: shallowGet,
  1008. set: shallowSet
  1009. });
  1010. // Props handlers are special in the sense that it should not unwrap top-level
  1011. // refs (in order to allow refs to be explicitly passed down), but should
  1012. // retain the reactivity of the normal readonly object.
  1013. const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
  1014. get: shallowReadonlyGet
  1015. });
  1016. const toShallow = (value) => value;
  1017. const getProto = (v) => Reflect.getPrototypeOf(v);
  1018. function get(target, key, isReadonly = false, isShallow = false) {
  1019. // #1772: readonly(reactive(Map)) should return readonly + reactive version
  1020. // of the value
  1021. target = target["__v_raw" /* ReactiveFlags.RAW */];
  1022. const rawTarget = toRaw(target);
  1023. const rawKey = toRaw(key);
  1024. if (!isReadonly) {
  1025. if (key !== rawKey) {
  1026. track(rawTarget, "get" /* TrackOpTypes.GET */, key);
  1027. }
  1028. track(rawTarget, "get" /* TrackOpTypes.GET */, rawKey);
  1029. }
  1030. const { has } = getProto(rawTarget);
  1031. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  1032. if (has.call(rawTarget, key)) {
  1033. return wrap(target.get(key));
  1034. }
  1035. else if (has.call(rawTarget, rawKey)) {
  1036. return wrap(target.get(rawKey));
  1037. }
  1038. else if (target !== rawTarget) {
  1039. // #3602 readonly(reactive(Map))
  1040. // ensure that the nested reactive `Map` can do tracking for itself
  1041. target.get(key);
  1042. }
  1043. }
  1044. function has(key, isReadonly = false) {
  1045. const target = this["__v_raw" /* ReactiveFlags.RAW */];
  1046. const rawTarget = toRaw(target);
  1047. const rawKey = toRaw(key);
  1048. if (!isReadonly) {
  1049. if (key !== rawKey) {
  1050. track(rawTarget, "has" /* TrackOpTypes.HAS */, key);
  1051. }
  1052. track(rawTarget, "has" /* TrackOpTypes.HAS */, rawKey);
  1053. }
  1054. return key === rawKey
  1055. ? target.has(key)
  1056. : target.has(key) || target.has(rawKey);
  1057. }
  1058. function size(target, isReadonly = false) {
  1059. target = target["__v_raw" /* ReactiveFlags.RAW */];
  1060. !isReadonly && track(toRaw(target), "iterate" /* TrackOpTypes.ITERATE */, ITERATE_KEY);
  1061. return Reflect.get(target, 'size', target);
  1062. }
  1063. function add(value) {
  1064. value = toRaw(value);
  1065. const target = toRaw(this);
  1066. const proto = getProto(target);
  1067. const hadKey = proto.has.call(target, value);
  1068. if (!hadKey) {
  1069. target.add(value);
  1070. trigger(target, "add" /* TriggerOpTypes.ADD */, value, value);
  1071. }
  1072. return this;
  1073. }
  1074. function set(key, value) {
  1075. value = toRaw(value);
  1076. const target = toRaw(this);
  1077. const { has, get } = getProto(target);
  1078. let hadKey = has.call(target, key);
  1079. if (!hadKey) {
  1080. key = toRaw(key);
  1081. hadKey = has.call(target, key);
  1082. }
  1083. else {
  1084. checkIdentityKeys(target, has, key);
  1085. }
  1086. const oldValue = get.call(target, key);
  1087. target.set(key, value);
  1088. if (!hadKey) {
  1089. trigger(target, "add" /* TriggerOpTypes.ADD */, key, value);
  1090. }
  1091. else if (hasChanged(value, oldValue)) {
  1092. trigger(target, "set" /* TriggerOpTypes.SET */, key, value, oldValue);
  1093. }
  1094. return this;
  1095. }
  1096. function deleteEntry(key) {
  1097. const target = toRaw(this);
  1098. const { has, get } = getProto(target);
  1099. let hadKey = has.call(target, key);
  1100. if (!hadKey) {
  1101. key = toRaw(key);
  1102. hadKey = has.call(target, key);
  1103. }
  1104. else {
  1105. checkIdentityKeys(target, has, key);
  1106. }
  1107. const oldValue = get ? get.call(target, key) : undefined;
  1108. // forward the operation before queueing reactions
  1109. const result = target.delete(key);
  1110. if (hadKey) {
  1111. trigger(target, "delete" /* TriggerOpTypes.DELETE */, key, undefined, oldValue);
  1112. }
  1113. return result;
  1114. }
  1115. function clear() {
  1116. const target = toRaw(this);
  1117. const hadItems = target.size !== 0;
  1118. const oldTarget = isMap(target)
  1119. ? new Map(target)
  1120. : new Set(target)
  1121. ;
  1122. // forward the operation before queueing reactions
  1123. const result = target.clear();
  1124. if (hadItems) {
  1125. trigger(target, "clear" /* TriggerOpTypes.CLEAR */, undefined, undefined, oldTarget);
  1126. }
  1127. return result;
  1128. }
  1129. function createForEach(isReadonly, isShallow) {
  1130. return function forEach(callback, thisArg) {
  1131. const observed = this;
  1132. const target = observed["__v_raw" /* ReactiveFlags.RAW */];
  1133. const rawTarget = toRaw(target);
  1134. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  1135. !isReadonly && track(rawTarget, "iterate" /* TrackOpTypes.ITERATE */, ITERATE_KEY);
  1136. return target.forEach((value, key) => {
  1137. // important: make sure the callback is
  1138. // 1. invoked with the reactive map as `this` and 3rd arg
  1139. // 2. the value received should be a corresponding reactive/readonly.
  1140. return callback.call(thisArg, wrap(value), wrap(key), observed);
  1141. });
  1142. };
  1143. }
  1144. function createIterableMethod(method, isReadonly, isShallow) {
  1145. return function (...args) {
  1146. const target = this["__v_raw" /* ReactiveFlags.RAW */];
  1147. const rawTarget = toRaw(target);
  1148. const targetIsMap = isMap(rawTarget);
  1149. const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
  1150. const isKeyOnly = method === 'keys' && targetIsMap;
  1151. const innerIterator = target[method](...args);
  1152. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  1153. !isReadonly &&
  1154. track(rawTarget, "iterate" /* TrackOpTypes.ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
  1155. // return a wrapped iterator which returns observed versions of the
  1156. // values emitted from the real iterator
  1157. return {
  1158. // iterator protocol
  1159. next() {
  1160. const { value, done } = innerIterator.next();
  1161. return done
  1162. ? { value, done }
  1163. : {
  1164. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  1165. done
  1166. };
  1167. },
  1168. // iterable protocol
  1169. [Symbol.iterator]() {
  1170. return this;
  1171. }
  1172. };
  1173. };
  1174. }
  1175. function createReadonlyMethod(type) {
  1176. return function (...args) {
  1177. {
  1178. const key = args[0] ? `on key "${args[0]}" ` : ``;
  1179. console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
  1180. }
  1181. return type === "delete" /* TriggerOpTypes.DELETE */ ? false : this;
  1182. };
  1183. }
  1184. function createInstrumentations() {
  1185. const mutableInstrumentations = {
  1186. get(key) {
  1187. return get(this, key);
  1188. },
  1189. get size() {
  1190. return size(this);
  1191. },
  1192. has,
  1193. add,
  1194. set,
  1195. delete: deleteEntry,
  1196. clear,
  1197. forEach: createForEach(false, false)
  1198. };
  1199. const shallowInstrumentations = {
  1200. get(key) {
  1201. return get(this, key, false, true);
  1202. },
  1203. get size() {
  1204. return size(this);
  1205. },
  1206. has,
  1207. add,
  1208. set,
  1209. delete: deleteEntry,
  1210. clear,
  1211. forEach: createForEach(false, true)
  1212. };
  1213. const readonlyInstrumentations = {
  1214. get(key) {
  1215. return get(this, key, true);
  1216. },
  1217. get size() {
  1218. return size(this, true);
  1219. },
  1220. has(key) {
  1221. return has.call(this, key, true);
  1222. },
  1223. add: createReadonlyMethod("add" /* TriggerOpTypes.ADD */),
  1224. set: createReadonlyMethod("set" /* TriggerOpTypes.SET */),
  1225. delete: createReadonlyMethod("delete" /* TriggerOpTypes.DELETE */),
  1226. clear: createReadonlyMethod("clear" /* TriggerOpTypes.CLEAR */),
  1227. forEach: createForEach(true, false)
  1228. };
  1229. const shallowReadonlyInstrumentations = {
  1230. get(key) {
  1231. return get(this, key, true, true);
  1232. },
  1233. get size() {
  1234. return size(this, true);
  1235. },
  1236. has(key) {
  1237. return has.call(this, key, true);
  1238. },
  1239. add: createReadonlyMethod("add" /* TriggerOpTypes.ADD */),
  1240. set: createReadonlyMethod("set" /* TriggerOpTypes.SET */),
  1241. delete: createReadonlyMethod("delete" /* TriggerOpTypes.DELETE */),
  1242. clear: createReadonlyMethod("clear" /* TriggerOpTypes.CLEAR */),
  1243. forEach: createForEach(true, true)
  1244. };
  1245. const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
  1246. iteratorMethods.forEach(method => {
  1247. mutableInstrumentations[method] = createIterableMethod(method, false, false);
  1248. readonlyInstrumentations[method] = createIterableMethod(method, true, false);
  1249. shallowInstrumentations[method] = createIterableMethod(method, false, true);
  1250. shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
  1251. });
  1252. return [
  1253. mutableInstrumentations,
  1254. readonlyInstrumentations,
  1255. shallowInstrumentations,
  1256. shallowReadonlyInstrumentations
  1257. ];
  1258. }
  1259. const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
  1260. function createInstrumentationGetter(isReadonly, shallow) {
  1261. const instrumentations = shallow
  1262. ? isReadonly
  1263. ? shallowReadonlyInstrumentations
  1264. : shallowInstrumentations
  1265. : isReadonly
  1266. ? readonlyInstrumentations
  1267. : mutableInstrumentations;
  1268. return (target, key, receiver) => {
  1269. if (key === "__v_isReactive" /* ReactiveFlags.IS_REACTIVE */) {
  1270. return !isReadonly;
  1271. }
  1272. else if (key === "__v_isReadonly" /* ReactiveFlags.IS_READONLY */) {
  1273. return isReadonly;
  1274. }
  1275. else if (key === "__v_raw" /* ReactiveFlags.RAW */) {
  1276. return target;
  1277. }
  1278. return Reflect.get(hasOwn(instrumentations, key) && key in target
  1279. ? instrumentations
  1280. : target, key, receiver);
  1281. };
  1282. }
  1283. const mutableCollectionHandlers = {
  1284. get: /*#__PURE__*/ createInstrumentationGetter(false, false)
  1285. };
  1286. const shallowCollectionHandlers = {
  1287. get: /*#__PURE__*/ createInstrumentationGetter(false, true)
  1288. };
  1289. const readonlyCollectionHandlers = {
  1290. get: /*#__PURE__*/ createInstrumentationGetter(true, false)
  1291. };
  1292. const shallowReadonlyCollectionHandlers = {
  1293. get: /*#__PURE__*/ createInstrumentationGetter(true, true)
  1294. };
  1295. function checkIdentityKeys(target, has, key) {
  1296. const rawKey = toRaw(key);
  1297. if (rawKey !== key && has.call(target, rawKey)) {
  1298. const type = toRawType(target);
  1299. console.warn(`Reactive ${type} contains both the raw and reactive ` +
  1300. `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
  1301. `which can lead to inconsistencies. ` +
  1302. `Avoid differentiating between the raw and reactive versions ` +
  1303. `of an object and only use the reactive version if possible.`);
  1304. }
  1305. }
  1306. const reactiveMap = new WeakMap();
  1307. const shallowReactiveMap = new WeakMap();
  1308. const readonlyMap = new WeakMap();
  1309. const shallowReadonlyMap = new WeakMap();
  1310. function targetTypeMap(rawType) {
  1311. switch (rawType) {
  1312. case 'Object':
  1313. case 'Array':
  1314. return 1 /* TargetType.COMMON */;
  1315. case 'Map':
  1316. case 'Set':
  1317. case 'WeakMap':
  1318. case 'WeakSet':
  1319. return 2 /* TargetType.COLLECTION */;
  1320. default:
  1321. return 0 /* TargetType.INVALID */;
  1322. }
  1323. }
  1324. function getTargetType(value) {
  1325. return value["__v_skip" /* ReactiveFlags.SKIP */] || !Object.isExtensible(value)
  1326. ? 0 /* TargetType.INVALID */
  1327. : targetTypeMap(toRawType(value));
  1328. }
  1329. function reactive(target) {
  1330. // if trying to observe a readonly proxy, return the readonly version.
  1331. if (isReadonly(target)) {
  1332. return target;
  1333. }
  1334. return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
  1335. }
  1336. /**
  1337. * Return a shallowly-reactive copy of the original object, where only the root
  1338. * level properties are reactive. It also does not auto-unwrap refs (even at the
  1339. * root level).
  1340. */
  1341. function shallowReactive(target) {
  1342. return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
  1343. }
  1344. /**
  1345. * Creates a readonly copy of the original object. Note the returned copy is not
  1346. * made reactive, but `readonly` can be called on an already reactive object.
  1347. */
  1348. function readonly(target) {
  1349. return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
  1350. }
  1351. /**
  1352. * Returns a reactive-copy of the original object, where only the root level
  1353. * properties are readonly, and does NOT unwrap refs nor recursively convert
  1354. * returned properties.
  1355. * This is used for creating the props proxy object for stateful components.
  1356. */
  1357. function shallowReadonly(target) {
  1358. return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
  1359. }
  1360. function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
  1361. if (!isObject(target)) {
  1362. {
  1363. console.warn(`value cannot be made reactive: ${String(target)}`);
  1364. }
  1365. return target;
  1366. }
  1367. // target is already a Proxy, return it.
  1368. // exception: calling readonly() on a reactive object
  1369. if (target["__v_raw" /* ReactiveFlags.RAW */] &&
  1370. !(isReadonly && target["__v_isReactive" /* ReactiveFlags.IS_REACTIVE */])) {
  1371. return target;
  1372. }
  1373. // target already has corresponding Proxy
  1374. const existingProxy = proxyMap.get(target);
  1375. if (existingProxy) {
  1376. return existingProxy;
  1377. }
  1378. // only specific value types can be observed.
  1379. const targetType = getTargetType(target);
  1380. if (targetType === 0 /* TargetType.INVALID */) {
  1381. return target;
  1382. }
  1383. const proxy = new Proxy(target, targetType === 2 /* TargetType.COLLECTION */ ? collectionHandlers : baseHandlers);
  1384. proxyMap.set(target, proxy);
  1385. return proxy;
  1386. }
  1387. function isReactive(value) {
  1388. if (isReadonly(value)) {
  1389. return isReactive(value["__v_raw" /* ReactiveFlags.RAW */]);
  1390. }
  1391. return !!(value && value["__v_isReactive" /* ReactiveFlags.IS_REACTIVE */]);
  1392. }
  1393. function isReadonly(value) {
  1394. return !!(value && value["__v_isReadonly" /* ReactiveFlags.IS_READONLY */]);
  1395. }
  1396. function isShallow(value) {
  1397. return !!(value && value["__v_isShallow" /* ReactiveFlags.IS_SHALLOW */]);
  1398. }
  1399. function isProxy(value) {
  1400. return isReactive(value) || isReadonly(value);
  1401. }
  1402. function toRaw(observed) {
  1403. const raw = observed && observed["__v_raw" /* ReactiveFlags.RAW */];
  1404. return raw ? toRaw(raw) : observed;
  1405. }
  1406. function markRaw(value) {
  1407. def(value, "__v_skip" /* ReactiveFlags.SKIP */, true);
  1408. return value;
  1409. }
  1410. const toReactive = (value) => isObject(value) ? reactive(value) : value;
  1411. const toReadonly = (value) => isObject(value) ? readonly(value) : value;
  1412. function trackRefValue(ref) {
  1413. if (shouldTrack && activeEffect) {
  1414. ref = toRaw(ref);
  1415. {
  1416. trackEffects(ref.dep || (ref.dep = createDep()), {
  1417. target: ref,
  1418. type: "get" /* TrackOpTypes.GET */,
  1419. key: 'value'
  1420. });
  1421. }
  1422. }
  1423. }
  1424. function triggerRefValue(ref, newVal) {
  1425. ref = toRaw(ref);
  1426. const dep = ref.dep;
  1427. if (dep) {
  1428. {
  1429. triggerEffects(dep, {
  1430. target: ref,
  1431. type: "set" /* TriggerOpTypes.SET */,
  1432. key: 'value',
  1433. newValue: newVal
  1434. });
  1435. }
  1436. }
  1437. }
  1438. function isRef(r) {
  1439. return !!(r && r.__v_isRef === true);
  1440. }
  1441. function ref(value) {
  1442. return createRef(value, false);
  1443. }
  1444. function shallowRef(value) {
  1445. return createRef(value, true);
  1446. }
  1447. function createRef(rawValue, shallow) {
  1448. if (isRef(rawValue)) {
  1449. return rawValue;
  1450. }
  1451. return new RefImpl(rawValue, shallow);
  1452. }
  1453. class RefImpl {
  1454. constructor(value, __v_isShallow) {
  1455. this.__v_isShallow = __v_isShallow;
  1456. this.dep = undefined;
  1457. this.__v_isRef = true;
  1458. this._rawValue = __v_isShallow ? value : toRaw(value);
  1459. this._value = __v_isShallow ? value : toReactive(value);
  1460. }
  1461. get value() {
  1462. trackRefValue(this);
  1463. return this._value;
  1464. }
  1465. set value(newVal) {
  1466. const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal);
  1467. newVal = useDirectValue ? newVal : toRaw(newVal);
  1468. if (hasChanged(newVal, this._rawValue)) {
  1469. this._rawValue = newVal;
  1470. this._value = useDirectValue ? newVal : toReactive(newVal);
  1471. triggerRefValue(this, newVal);
  1472. }
  1473. }
  1474. }
  1475. function triggerRef(ref) {
  1476. triggerRefValue(ref, ref.value );
  1477. }
  1478. function unref(ref) {
  1479. return isRef(ref) ? ref.value : ref;
  1480. }
  1481. const shallowUnwrapHandlers = {
  1482. get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  1483. set: (target, key, value, receiver) => {
  1484. const oldValue = target[key];
  1485. if (isRef(oldValue) && !isRef(value)) {
  1486. oldValue.value = value;
  1487. return true;
  1488. }
  1489. else {
  1490. return Reflect.set(target, key, value, receiver);
  1491. }
  1492. }
  1493. };
  1494. function proxyRefs(objectWithRefs) {
  1495. return isReactive(objectWithRefs)
  1496. ? objectWithRefs
  1497. : new Proxy(objectWithRefs, shallowUnwrapHandlers);
  1498. }
  1499. class CustomRefImpl {
  1500. constructor(factory) {
  1501. this.dep = undefined;
  1502. this.__v_isRef = true;
  1503. const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
  1504. this._get = get;
  1505. this._set = set;
  1506. }
  1507. get value() {
  1508. return this._get();
  1509. }
  1510. set value(newVal) {
  1511. this._set(newVal);
  1512. }
  1513. }
  1514. function customRef(factory) {
  1515. return new CustomRefImpl(factory);
  1516. }
  1517. function toRefs(object) {
  1518. if (!isProxy(object)) {
  1519. console.warn(`toRefs() expects a reactive object but received a plain one.`);
  1520. }
  1521. const ret = isArray(object) ? new Array(object.length) : {};
  1522. for (const key in object) {
  1523. ret[key] = toRef(object, key);
  1524. }
  1525. return ret;
  1526. }
  1527. class ObjectRefImpl {
  1528. constructor(_object, _key, _defaultValue) {
  1529. this._object = _object;
  1530. this._key = _key;
  1531. this._defaultValue = _defaultValue;
  1532. this.__v_isRef = true;
  1533. }
  1534. get value() {
  1535. const val = this._object[this._key];
  1536. return val === undefined ? this._defaultValue : val;
  1537. }
  1538. set value(newVal) {
  1539. this._object[this._key] = newVal;
  1540. }
  1541. get dep() {
  1542. return getDepFromReactive(toRaw(this._object), this._key);
  1543. }
  1544. }
  1545. function toRef(object, key, defaultValue) {
  1546. const val = object[key];
  1547. return isRef(val)
  1548. ? val
  1549. : new ObjectRefImpl(object, key, defaultValue);
  1550. }
  1551. var _a;
  1552. class ComputedRefImpl {
  1553. constructor(getter, _setter, isReadonly, isSSR) {
  1554. this._setter = _setter;
  1555. this.dep = undefined;
  1556. this.__v_isRef = true;
  1557. this[_a] = false;
  1558. this._dirty = true;
  1559. this.effect = new ReactiveEffect(getter, () => {
  1560. if (!this._dirty) {
  1561. this._dirty = true;
  1562. triggerRefValue(this);
  1563. }
  1564. });
  1565. this.effect.computed = this;
  1566. this.effect.active = this._cacheable = !isSSR;
  1567. this["__v_isReadonly" /* ReactiveFlags.IS_READONLY */] = isReadonly;
  1568. }
  1569. get value() {
  1570. // the computed ref may get wrapped by other proxies e.g. readonly() #3376
  1571. const self = toRaw(this);
  1572. trackRefValue(self);
  1573. if (self._dirty || !self._cacheable) {
  1574. self._dirty = false;
  1575. self._value = self.effect.run();
  1576. }
  1577. return self._value;
  1578. }
  1579. set value(newValue) {
  1580. this._setter(newValue);
  1581. }
  1582. }
  1583. _a = "__v_isReadonly" /* ReactiveFlags.IS_READONLY */;
  1584. function computed$1(getterOrOptions, debugOptions, isSSR = false) {
  1585. let getter;
  1586. let setter;
  1587. const onlyGetter = isFunction(getterOrOptions);
  1588. if (onlyGetter) {
  1589. getter = getterOrOptions;
  1590. setter = () => {
  1591. console.warn('Write operation failed: computed value is readonly');
  1592. }
  1593. ;
  1594. }
  1595. else {
  1596. getter = getterOrOptions.get;
  1597. setter = getterOrOptions.set;
  1598. }
  1599. const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
  1600. if (debugOptions && !isSSR) {
  1601. cRef.effect.onTrack = debugOptions.onTrack;
  1602. cRef.effect.onTrigger = debugOptions.onTrigger;
  1603. }
  1604. return cRef;
  1605. }
  1606. const stack = [];
  1607. function pushWarningContext(vnode) {
  1608. stack.push(vnode);
  1609. }
  1610. function popWarningContext() {
  1611. stack.pop();
  1612. }
  1613. function warn(msg, ...args) {
  1614. // avoid props formatting or warn handler tracking deps that might be mutated
  1615. // during patch, leading to infinite recursion.
  1616. pauseTracking();
  1617. const instance = stack.length ? stack[stack.length - 1].component : null;
  1618. const appWarnHandler = instance && instance.appContext.config.warnHandler;
  1619. const trace = getComponentTrace();
  1620. if (appWarnHandler) {
  1621. callWithErrorHandling(appWarnHandler, instance, 11 /* ErrorCodes.APP_WARN_HANDLER */, [
  1622. msg + args.join(''),
  1623. instance && instance.proxy,
  1624. trace
  1625. .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
  1626. .join('\n'),
  1627. trace
  1628. ]);
  1629. }
  1630. else {
  1631. const warnArgs = [`[Vue warn]: ${msg}`, ...args];
  1632. /* istanbul ignore if */
  1633. if (trace.length &&
  1634. // avoid spamming console during tests
  1635. !false) {
  1636. warnArgs.push(`\n`, ...formatTrace(trace));
  1637. }
  1638. console.warn(...warnArgs);
  1639. }
  1640. resetTracking();
  1641. }
  1642. function getComponentTrace() {
  1643. let currentVNode = stack[stack.length - 1];
  1644. if (!currentVNode) {
  1645. return [];
  1646. }
  1647. // we can't just use the stack because it will be incomplete during updates
  1648. // that did not start from the root. Re-construct the parent chain using
  1649. // instance parent pointers.
  1650. const normalizedStack = [];
  1651. while (currentVNode) {
  1652. const last = normalizedStack[0];
  1653. if (last && last.vnode === currentVNode) {
  1654. last.recurseCount++;
  1655. }
  1656. else {
  1657. normalizedStack.push({
  1658. vnode: currentVNode,
  1659. recurseCount: 0
  1660. });
  1661. }
  1662. const parentInstance = currentVNode.component && currentVNode.component.parent;
  1663. currentVNode = parentInstance && parentInstance.vnode;
  1664. }
  1665. return normalizedStack;
  1666. }
  1667. /* istanbul ignore next */
  1668. function formatTrace(trace) {
  1669. const logs = [];
  1670. trace.forEach((entry, i) => {
  1671. logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
  1672. });
  1673. return logs;
  1674. }
  1675. function formatTraceEntry({ vnode, recurseCount }) {
  1676. const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
  1677. const isRoot = vnode.component ? vnode.component.parent == null : false;
  1678. const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
  1679. const close = `>` + postfix;
  1680. return vnode.props
  1681. ? [open, ...formatProps(vnode.props), close]
  1682. : [open + close];
  1683. }
  1684. /* istanbul ignore next */
  1685. function formatProps(props) {
  1686. const res = [];
  1687. const keys = Object.keys(props);
  1688. keys.slice(0, 3).forEach(key => {
  1689. res.push(...formatProp(key, props[key]));
  1690. });
  1691. if (keys.length > 3) {
  1692. res.push(` ...`);
  1693. }
  1694. return res;
  1695. }
  1696. /* istanbul ignore next */
  1697. function formatProp(key, value, raw) {
  1698. if (isString(value)) {
  1699. value = JSON.stringify(value);
  1700. return raw ? value : [`${key}=${value}`];
  1701. }
  1702. else if (typeof value === 'number' ||
  1703. typeof value === 'boolean' ||
  1704. value == null) {
  1705. return raw ? value : [`${key}=${value}`];
  1706. }
  1707. else if (isRef(value)) {
  1708. value = formatProp(key, toRaw(value.value), true);
  1709. return raw ? value : [`${key}=Ref<`, value, `>`];
  1710. }
  1711. else if (isFunction(value)) {
  1712. return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
  1713. }
  1714. else {
  1715. value = toRaw(value);
  1716. return raw ? value : [`${key}=`, value];
  1717. }
  1718. }
  1719. /**
  1720. * @internal
  1721. */
  1722. function assertNumber(val, type) {
  1723. if (val === undefined) {
  1724. return;
  1725. }
  1726. else if (typeof val !== 'number') {
  1727. warn(`${type} is not a valid number - ` + `got ${JSON.stringify(val)}.`);
  1728. }
  1729. else if (isNaN(val)) {
  1730. warn(`${type} is NaN - ` + 'the duration expression might be incorrect.');
  1731. }
  1732. }
  1733. const ErrorTypeStrings = {
  1734. ["sp" /* LifecycleHooks.SERVER_PREFETCH */]: 'serverPrefetch hook',
  1735. ["bc" /* LifecycleHooks.BEFORE_CREATE */]: 'beforeCreate hook',
  1736. ["c" /* LifecycleHooks.CREATED */]: 'created hook',
  1737. ["bm" /* LifecycleHooks.BEFORE_MOUNT */]: 'beforeMount hook',
  1738. ["m" /* LifecycleHooks.MOUNTED */]: 'mounted hook',
  1739. ["bu" /* LifecycleHooks.BEFORE_UPDATE */]: 'beforeUpdate hook',
  1740. ["u" /* LifecycleHooks.UPDATED */]: 'updated',
  1741. ["bum" /* LifecycleHooks.BEFORE_UNMOUNT */]: 'beforeUnmount hook',
  1742. ["um" /* LifecycleHooks.UNMOUNTED */]: 'unmounted hook',
  1743. ["a" /* LifecycleHooks.ACTIVATED */]: 'activated hook',
  1744. ["da" /* LifecycleHooks.DEACTIVATED */]: 'deactivated hook',
  1745. ["ec" /* LifecycleHooks.ERROR_CAPTURED */]: 'errorCaptured hook',
  1746. ["rtc" /* LifecycleHooks.RENDER_TRACKED */]: 'renderTracked hook',
  1747. ["rtg" /* LifecycleHooks.RENDER_TRIGGERED */]: 'renderTriggered hook',
  1748. [0 /* ErrorCodes.SETUP_FUNCTION */]: 'setup function',
  1749. [1 /* ErrorCodes.RENDER_FUNCTION */]: 'render function',
  1750. [2 /* ErrorCodes.WATCH_GETTER */]: 'watcher getter',
  1751. [3 /* ErrorCodes.WATCH_CALLBACK */]: 'watcher callback',
  1752. [4 /* ErrorCodes.WATCH_CLEANUP */]: 'watcher cleanup function',
  1753. [5 /* ErrorCodes.NATIVE_EVENT_HANDLER */]: 'native event handler',
  1754. [6 /* ErrorCodes.COMPONENT_EVENT_HANDLER */]: 'component event handler',
  1755. [7 /* ErrorCodes.VNODE_HOOK */]: 'vnode hook',
  1756. [8 /* ErrorCodes.DIRECTIVE_HOOK */]: 'directive hook',
  1757. [9 /* ErrorCodes.TRANSITION_HOOK */]: 'transition hook',
  1758. [10 /* ErrorCodes.APP_ERROR_HANDLER */]: 'app errorHandler',
  1759. [11 /* ErrorCodes.APP_WARN_HANDLER */]: 'app warnHandler',
  1760. [12 /* ErrorCodes.FUNCTION_REF */]: 'ref function',
  1761. [13 /* ErrorCodes.ASYNC_COMPONENT_LOADER */]: 'async component loader',
  1762. [14 /* ErrorCodes.SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
  1763. 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core'
  1764. };
  1765. function callWithErrorHandling(fn, instance, type, args) {
  1766. let res;
  1767. try {
  1768. res = args ? fn(...args) : fn();
  1769. }
  1770. catch (err) {
  1771. handleError(err, instance, type);
  1772. }
  1773. return res;
  1774. }
  1775. function callWithAsyncErrorHandling(fn, instance, type, args) {
  1776. if (isFunction(fn)) {
  1777. const res = callWithErrorHandling(fn, instance, type, args);
  1778. if (res && isPromise(res)) {
  1779. res.catch(err => {
  1780. handleError(err, instance, type);
  1781. });
  1782. }
  1783. return res;
  1784. }
  1785. const values = [];
  1786. for (let i = 0; i < fn.length; i++) {
  1787. values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
  1788. }
  1789. return values;
  1790. }
  1791. function handleError(err, instance, type, throwInDev = true) {
  1792. const contextVNode = instance ? instance.vnode : null;
  1793. if (instance) {
  1794. let cur = instance.parent;
  1795. // the exposed instance is the render proxy to keep it consistent with 2.x
  1796. const exposedInstance = instance.proxy;
  1797. // in production the hook receives only the error code
  1798. const errorInfo = ErrorTypeStrings[type] ;
  1799. while (cur) {
  1800. const errorCapturedHooks = cur.ec;
  1801. if (errorCapturedHooks) {
  1802. for (let i = 0; i < errorCapturedHooks.length; i++) {
  1803. if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
  1804. return;
  1805. }
  1806. }
  1807. }
  1808. cur = cur.parent;
  1809. }
  1810. // app-level handling
  1811. const appErrorHandler = instance.appContext.config.errorHandler;
  1812. if (appErrorHandler) {
  1813. callWithErrorHandling(appErrorHandler, null, 10 /* ErrorCodes.APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
  1814. return;
  1815. }
  1816. }
  1817. logError(err, type, contextVNode, throwInDev);
  1818. }
  1819. function logError(err, type, contextVNode, throwInDev = true) {
  1820. {
  1821. const info = ErrorTypeStrings[type];
  1822. if (contextVNode) {
  1823. pushWarningContext(contextVNode);
  1824. }
  1825. warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
  1826. if (contextVNode) {
  1827. popWarningContext();
  1828. }
  1829. // crash in dev by default so it's more noticeable
  1830. if (throwInDev) {
  1831. throw err;
  1832. }
  1833. else {
  1834. console.error(err);
  1835. }
  1836. }
  1837. }
  1838. let isFlushing = false;
  1839. let isFlushPending = false;
  1840. const queue = [];
  1841. let flushIndex = 0;
  1842. const pendingPostFlushCbs = [];
  1843. let activePostFlushCbs = null;
  1844. let postFlushIndex = 0;
  1845. const resolvedPromise = /*#__PURE__*/ Promise.resolve();
  1846. let currentFlushPromise = null;
  1847. const RECURSION_LIMIT = 100;
  1848. function nextTick(fn) {
  1849. const p = currentFlushPromise || resolvedPromise;
  1850. return fn ? p.then(this ? fn.bind(this) : fn) : p;
  1851. }
  1852. // #2768
  1853. // Use binary-search to find a suitable position in the queue,
  1854. // so that the queue maintains the increasing order of job's id,
  1855. // which can prevent the job from being skipped and also can avoid repeated patching.
  1856. function findInsertionIndex(id) {
  1857. // the start index should be `flushIndex + 1`
  1858. let start = flushIndex + 1;
  1859. let end = queue.length;
  1860. while (start < end) {
  1861. const middle = (start + end) >>> 1;
  1862. const middleJobId = getId(queue[middle]);
  1863. middleJobId < id ? (start = middle + 1) : (end = middle);
  1864. }
  1865. return start;
  1866. }
  1867. function queueJob(job) {
  1868. // the dedupe search uses the startIndex argument of Array.includes()
  1869. // by default the search index includes the current job that is being run
  1870. // so it cannot recursively trigger itself again.
  1871. // if the job is a watch() callback, the search will start with a +1 index to
  1872. // allow it recursively trigger itself - it is the user's responsibility to
  1873. // ensure it doesn't end up in an infinite loop.
  1874. if (!queue.length ||
  1875. !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) {
  1876. if (job.id == null) {
  1877. queue.push(job);
  1878. }
  1879. else {
  1880. queue.splice(findInsertionIndex(job.id), 0, job);
  1881. }
  1882. queueFlush();
  1883. }
  1884. }
  1885. function queueFlush() {
  1886. if (!isFlushing && !isFlushPending) {
  1887. isFlushPending = true;
  1888. currentFlushPromise = resolvedPromise.then(flushJobs);
  1889. }
  1890. }
  1891. function invalidateJob(job) {
  1892. const i = queue.indexOf(job);
  1893. if (i > flushIndex) {
  1894. queue.splice(i, 1);
  1895. }
  1896. }
  1897. function queuePostFlushCb(cb) {
  1898. if (!isArray(cb)) {
  1899. if (!activePostFlushCbs ||
  1900. !activePostFlushCbs.includes(cb, cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex)) {
  1901. pendingPostFlushCbs.push(cb);
  1902. }
  1903. }
  1904. else {
  1905. // if cb is an array, it is a component lifecycle hook which can only be
  1906. // triggered by a job, which is already deduped in the main queue, so
  1907. // we can skip duplicate check here to improve perf
  1908. pendingPostFlushCbs.push(...cb);
  1909. }
  1910. queueFlush();
  1911. }
  1912. function flushPreFlushCbs(seen,
  1913. // if currently flushing, skip the current job itself
  1914. i = isFlushing ? flushIndex + 1 : 0) {
  1915. {
  1916. seen = seen || new Map();
  1917. }
  1918. for (; i < queue.length; i++) {
  1919. const cb = queue[i];
  1920. if (cb && cb.pre) {
  1921. if (checkRecursiveUpdates(seen, cb)) {
  1922. continue;
  1923. }
  1924. queue.splice(i, 1);
  1925. i--;
  1926. cb();
  1927. }
  1928. }
  1929. }
  1930. function flushPostFlushCbs(seen) {
  1931. if (pendingPostFlushCbs.length) {
  1932. const deduped = [...new Set(pendingPostFlushCbs)];
  1933. pendingPostFlushCbs.length = 0;
  1934. // #1947 already has active queue, nested flushPostFlushCbs call
  1935. if (activePostFlushCbs) {
  1936. activePostFlushCbs.push(...deduped);
  1937. return;
  1938. }
  1939. activePostFlushCbs = deduped;
  1940. {
  1941. seen = seen || new Map();
  1942. }
  1943. activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
  1944. for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
  1945. if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
  1946. continue;
  1947. }
  1948. activePostFlushCbs[postFlushIndex]();
  1949. }
  1950. activePostFlushCbs = null;
  1951. postFlushIndex = 0;
  1952. }
  1953. }
  1954. const getId = (job) => job.id == null ? Infinity : job.id;
  1955. const comparator = (a, b) => {
  1956. const diff = getId(a) - getId(b);
  1957. if (diff === 0) {
  1958. if (a.pre && !b.pre)
  1959. return -1;
  1960. if (b.pre && !a.pre)
  1961. return 1;
  1962. }
  1963. return diff;
  1964. };
  1965. function flushJobs(seen) {
  1966. isFlushPending = false;
  1967. isFlushing = true;
  1968. {
  1969. seen = seen || new Map();
  1970. }
  1971. // Sort queue before flush.
  1972. // This ensures that:
  1973. // 1. Components are updated from parent to child. (because parent is always
  1974. // created before the child so its render effect will have smaller
  1975. // priority number)
  1976. // 2. If a component is unmounted during a parent component's update,
  1977. // its update can be skipped.
  1978. queue.sort(comparator);
  1979. // conditional usage of checkRecursiveUpdate must be determined out of
  1980. // try ... catch block since Rollup by default de-optimizes treeshaking
  1981. // inside try-catch. This can leave all warning code unshaked. Although
  1982. // they would get eventually shaken by a minifier like terser, some minifiers
  1983. // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)
  1984. const check = (job) => checkRecursiveUpdates(seen, job)
  1985. ;
  1986. try {
  1987. for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
  1988. const job = queue[flushIndex];
  1989. if (job && job.active !== false) {
  1990. if (true && check(job)) {
  1991. continue;
  1992. }
  1993. // console.log(`running:`, job.id)
  1994. callWithErrorHandling(job, null, 14 /* ErrorCodes.SCHEDULER */);
  1995. }
  1996. }
  1997. }
  1998. finally {
  1999. flushIndex = 0;
  2000. queue.length = 0;
  2001. flushPostFlushCbs(seen);
  2002. isFlushing = false;
  2003. currentFlushPromise = null;
  2004. // some postFlushCb queued jobs!
  2005. // keep flushing until it drains.
  2006. if (queue.length || pendingPostFlushCbs.length) {
  2007. flushJobs(seen);
  2008. }
  2009. }
  2010. }
  2011. function checkRecursiveUpdates(seen, fn) {
  2012. if (!seen.has(fn)) {
  2013. seen.set(fn, 1);
  2014. }
  2015. else {
  2016. const count = seen.get(fn);
  2017. if (count > RECURSION_LIMIT) {
  2018. const instance = fn.ownerInstance;
  2019. const componentName = instance && getComponentName(instance.type);
  2020. warn(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
  2021. `This means you have a reactive effect that is mutating its own ` +
  2022. `dependencies and thus recursively triggering itself. Possible sources ` +
  2023. `include component template, render function, updated hook or ` +
  2024. `watcher source function.`);
  2025. return true;
  2026. }
  2027. else {
  2028. seen.set(fn, count + 1);
  2029. }
  2030. }
  2031. }
  2032. /* eslint-disable no-restricted-globals */
  2033. let isHmrUpdating = false;
  2034. const hmrDirtyComponents = new Set();
  2035. // Expose the HMR runtime on the global object
  2036. // This makes it entirely tree-shakable without polluting the exports and makes
  2037. // it easier to be used in toolings like vue-loader
  2038. // Note: for a component to be eligible for HMR it also needs the __hmrId option
  2039. // to be set so that its instances can be registered / removed.
  2040. {
  2041. getGlobalThis().__VUE_HMR_RUNTIME__ = {
  2042. createRecord: tryWrap(createRecord),
  2043. rerender: tryWrap(rerender),
  2044. reload: tryWrap(reload)
  2045. };
  2046. }
  2047. const map = new Map();
  2048. function registerHMR(instance) {
  2049. const id = instance.type.__hmrId;
  2050. let record = map.get(id);
  2051. if (!record) {
  2052. createRecord(id, instance.type);
  2053. record = map.get(id);
  2054. }
  2055. record.instances.add(instance);
  2056. }
  2057. function unregisterHMR(instance) {
  2058. map.get(instance.type.__hmrId).instances.delete(instance);
  2059. }
  2060. function createRecord(id, initialDef) {
  2061. if (map.has(id)) {
  2062. return false;
  2063. }
  2064. map.set(id, {
  2065. initialDef: normalizeClassComponent(initialDef),
  2066. instances: new Set()
  2067. });
  2068. return true;
  2069. }
  2070. function normalizeClassComponent(component) {
  2071. return isClassComponent(component) ? component.__vccOpts : component;
  2072. }
  2073. function rerender(id, newRender) {
  2074. const record = map.get(id);
  2075. if (!record) {
  2076. return;
  2077. }
  2078. // update initial record (for not-yet-rendered component)
  2079. record.initialDef.render = newRender;
  2080. [...record.instances].forEach(instance => {
  2081. if (newRender) {
  2082. instance.render = newRender;
  2083. normalizeClassComponent(instance.type).render = newRender;
  2084. }
  2085. instance.renderCache = [];
  2086. // this flag forces child components with slot content to update
  2087. isHmrUpdating = true;
  2088. instance.update();
  2089. isHmrUpdating = false;
  2090. });
  2091. }
  2092. function reload(id, newComp) {
  2093. const record = map.get(id);
  2094. if (!record)
  2095. return;
  2096. newComp = normalizeClassComponent(newComp);
  2097. // update initial def (for not-yet-rendered components)
  2098. updateComponentDef(record.initialDef, newComp);
  2099. // create a snapshot which avoids the set being mutated during updates
  2100. const instances = [...record.instances];
  2101. for (const instance of instances) {
  2102. const oldComp = normalizeClassComponent(instance.type);
  2103. if (!hmrDirtyComponents.has(oldComp)) {
  2104. // 1. Update existing comp definition to match new one
  2105. if (oldComp !== record.initialDef) {
  2106. updateComponentDef(oldComp, newComp);
  2107. }
  2108. // 2. mark definition dirty. This forces the renderer to replace the
  2109. // component on patch.
  2110. hmrDirtyComponents.add(oldComp);
  2111. }
  2112. // 3. invalidate options resolution cache
  2113. instance.appContext.optionsCache.delete(instance.type);
  2114. // 4. actually update
  2115. if (instance.ceReload) {
  2116. // custom element
  2117. hmrDirtyComponents.add(oldComp);
  2118. instance.ceReload(newComp.styles);
  2119. hmrDirtyComponents.delete(oldComp);
  2120. }
  2121. else if (instance.parent) {
  2122. // 4. Force the parent instance to re-render. This will cause all updated
  2123. // components to be unmounted and re-mounted. Queue the update so that we
  2124. // don't end up forcing the same parent to re-render multiple times.
  2125. queueJob(instance.parent.update);
  2126. }
  2127. else if (instance.appContext.reload) {
  2128. // root instance mounted via createApp() has a reload method
  2129. instance.appContext.reload();
  2130. }
  2131. else if (typeof window !== 'undefined') {
  2132. // root instance inside tree created via raw render(). Force reload.
  2133. window.location.reload();
  2134. }
  2135. else {
  2136. console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
  2137. }
  2138. }
  2139. // 5. make sure to cleanup dirty hmr components after update
  2140. queuePostFlushCb(() => {
  2141. for (const instance of instances) {
  2142. hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
  2143. }
  2144. });
  2145. }
  2146. function updateComponentDef(oldComp, newComp) {
  2147. extend(oldComp, newComp);
  2148. for (const key in oldComp) {
  2149. if (key !== '__file' && !(key in newComp)) {
  2150. delete oldComp[key];
  2151. }
  2152. }
  2153. }
  2154. function tryWrap(fn) {
  2155. return (id, arg) => {
  2156. try {
  2157. return fn(id, arg);
  2158. }
  2159. catch (e) {
  2160. console.error(e);
  2161. console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
  2162. `Full reload required.`);
  2163. }
  2164. };
  2165. }
  2166. let devtools;
  2167. let buffer = [];
  2168. let devtoolsNotInstalled = false;
  2169. function emit$1(event, ...args) {
  2170. if (devtools) {
  2171. devtools.emit(event, ...args);
  2172. }
  2173. else if (!devtoolsNotInstalled) {
  2174. buffer.push({ event, args });
  2175. }
  2176. }
  2177. function setDevtoolsHook(hook, target) {
  2178. var _a, _b;
  2179. devtools = hook;
  2180. if (devtools) {
  2181. devtools.enabled = true;
  2182. buffer.forEach(({ event, args }) => devtools.emit(event, ...args));
  2183. buffer = [];
  2184. }
  2185. else if (
  2186. // handle late devtools injection - only do this if we are in an actual
  2187. // browser environment to avoid the timer handle stalling test runner exit
  2188. // (#4815)
  2189. typeof window !== 'undefined' &&
  2190. // some envs mock window but not fully
  2191. window.HTMLElement &&
  2192. // also exclude jsdom
  2193. !((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) === null || _b === void 0 ? void 0 : _b.includes('jsdom'))) {
  2194. const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ =
  2195. target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []);
  2196. replay.push((newHook) => {
  2197. setDevtoolsHook(newHook, target);
  2198. });
  2199. // clear buffer after 3s - the user probably doesn't have devtools installed
  2200. // at all, and keeping the buffer will cause memory leaks (#4738)
  2201. setTimeout(() => {
  2202. if (!devtools) {
  2203. target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
  2204. devtoolsNotInstalled = true;
  2205. buffer = [];
  2206. }
  2207. }, 3000);
  2208. }
  2209. else {
  2210. // non-browser env, assume not installed
  2211. devtoolsNotInstalled = true;
  2212. buffer = [];
  2213. }
  2214. }
  2215. function devtoolsInitApp(app, version) {
  2216. emit$1("app:init" /* DevtoolsHooks.APP_INIT */, app, version, {
  2217. Fragment,
  2218. Text,
  2219. Comment,
  2220. Static
  2221. });
  2222. }
  2223. function devtoolsUnmountApp(app) {
  2224. emit$1("app:unmount" /* DevtoolsHooks.APP_UNMOUNT */, app);
  2225. }
  2226. const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* DevtoolsHooks.COMPONENT_ADDED */);
  2227. const devtoolsComponentUpdated =
  2228. /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* DevtoolsHooks.COMPONENT_UPDATED */);
  2229. const _devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* DevtoolsHooks.COMPONENT_REMOVED */);
  2230. const devtoolsComponentRemoved = (component) => {
  2231. if (devtools &&
  2232. typeof devtools.cleanupBuffer === 'function' &&
  2233. // remove the component if it wasn't buffered
  2234. !devtools.cleanupBuffer(component)) {
  2235. _devtoolsComponentRemoved(component);
  2236. }
  2237. };
  2238. function createDevtoolsComponentHook(hook) {
  2239. return (component) => {
  2240. emit$1(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
  2241. };
  2242. }
  2243. const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* DevtoolsHooks.PERFORMANCE_START */);
  2244. const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* DevtoolsHooks.PERFORMANCE_END */);
  2245. function createDevtoolsPerformanceHook(hook) {
  2246. return (component, type, time) => {
  2247. emit$1(hook, component.appContext.app, component.uid, component, type, time);
  2248. };
  2249. }
  2250. function devtoolsComponentEmit(component, event, params) {
  2251. emit$1("component:emit" /* DevtoolsHooks.COMPONENT_EMIT */, component.appContext.app, component, event, params);
  2252. }
  2253. function emit(instance, event, ...rawArgs) {
  2254. if (instance.isUnmounted)
  2255. return;
  2256. const props = instance.vnode.props || EMPTY_OBJ;
  2257. {
  2258. const { emitsOptions, propsOptions: [propsOptions] } = instance;
  2259. if (emitsOptions) {
  2260. if (!(event in emitsOptions) &&
  2261. !(false )) {
  2262. if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
  2263. warn(`Component emitted event "${event}" but it is neither declared in ` +
  2264. `the emits option nor as an "${toHandlerKey(event)}" prop.`);
  2265. }
  2266. }
  2267. else {
  2268. const validator = emitsOptions[event];
  2269. if (isFunction(validator)) {
  2270. const isValid = validator(...rawArgs);
  2271. if (!isValid) {
  2272. warn(`Invalid event arguments: event validation failed for event "${event}".`);
  2273. }
  2274. }
  2275. }
  2276. }
  2277. }
  2278. let args = rawArgs;
  2279. const isModelListener = event.startsWith('update:');
  2280. // for v-model update:xxx events, apply modifiers on args
  2281. const modelArg = isModelListener && event.slice(7);
  2282. if (modelArg && modelArg in props) {
  2283. const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
  2284. const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
  2285. if (trim) {
  2286. args = rawArgs.map(a => (isString(a) ? a.trim() : a));
  2287. }
  2288. if (number) {
  2289. args = rawArgs.map(looseToNumber);
  2290. }
  2291. }
  2292. {
  2293. devtoolsComponentEmit(instance, event, args);
  2294. }
  2295. {
  2296. const lowerCaseEvent = event.toLowerCase();
  2297. if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
  2298. warn(`Event "${lowerCaseEvent}" is emitted in component ` +
  2299. `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
  2300. `Note that HTML attributes are case-insensitive and you cannot use ` +
  2301. `v-on to listen to camelCase events when using in-DOM templates. ` +
  2302. `You should probably use "${hyphenate(event)}" instead of "${event}".`);
  2303. }
  2304. }
  2305. let handlerName;
  2306. let handler = props[(handlerName = toHandlerKey(event))] ||
  2307. // also try camelCase event handler (#2249)
  2308. props[(handlerName = toHandlerKey(camelize(event)))];
  2309. // for v-model update:xxx events, also trigger kebab-case equivalent
  2310. // for props passed via kebab-case
  2311. if (!handler && isModelListener) {
  2312. handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
  2313. }
  2314. if (handler) {
  2315. callWithAsyncErrorHandling(handler, instance, 6 /* ErrorCodes.COMPONENT_EVENT_HANDLER */, args);
  2316. }
  2317. const onceHandler = props[handlerName + `Once`];
  2318. if (onceHandler) {
  2319. if (!instance.emitted) {
  2320. instance.emitted = {};
  2321. }
  2322. else if (instance.emitted[handlerName]) {
  2323. return;
  2324. }
  2325. instance.emitted[handlerName] = true;
  2326. callWithAsyncErrorHandling(onceHandler, instance, 6 /* ErrorCodes.COMPONENT_EVENT_HANDLER */, args);
  2327. }
  2328. }
  2329. function normalizeEmitsOptions(comp, appContext, asMixin = false) {
  2330. const cache = appContext.emitsCache;
  2331. const cached = cache.get(comp);
  2332. if (cached !== undefined) {
  2333. return cached;
  2334. }
  2335. const raw = comp.emits;
  2336. let normalized = {};
  2337. // apply mixin/extends props
  2338. let hasExtends = false;
  2339. if (!isFunction(comp)) {
  2340. const extendEmits = (raw) => {
  2341. const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
  2342. if (normalizedFromExtend) {
  2343. hasExtends = true;
  2344. extend(normalized, normalizedFromExtend);
  2345. }
  2346. };
  2347. if (!asMixin && appContext.mixins.length) {
  2348. appContext.mixins.forEach(extendEmits);
  2349. }
  2350. if (comp.extends) {
  2351. extendEmits(comp.extends);
  2352. }
  2353. if (comp.mixins) {
  2354. comp.mixins.forEach(extendEmits);
  2355. }
  2356. }
  2357. if (!raw && !hasExtends) {
  2358. if (isObject(comp)) {
  2359. cache.set(comp, null);
  2360. }
  2361. return null;
  2362. }
  2363. if (isArray(raw)) {
  2364. raw.forEach(key => (normalized[key] = null));
  2365. }
  2366. else {
  2367. extend(normalized, raw);
  2368. }
  2369. if (isObject(comp)) {
  2370. cache.set(comp, normalized);
  2371. }
  2372. return normalized;
  2373. }
  2374. // Check if an incoming prop key is a declared emit event listener.
  2375. // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
  2376. // both considered matched listeners.
  2377. function isEmitListener(options, key) {
  2378. if (!options || !isOn(key)) {
  2379. return false;
  2380. }
  2381. key = key.slice(2).replace(/Once$/, '');
  2382. return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
  2383. hasOwn(options, hyphenate(key)) ||
  2384. hasOwn(options, key));
  2385. }
  2386. /**
  2387. * mark the current rendering instance for asset resolution (e.g.
  2388. * resolveComponent, resolveDirective) during render
  2389. */
  2390. let currentRenderingInstance = null;
  2391. let currentScopeId = null;
  2392. /**
  2393. * Note: rendering calls maybe nested. The function returns the parent rendering
  2394. * instance if present, which should be restored after the render is done:
  2395. *
  2396. * ```js
  2397. * const prev = setCurrentRenderingInstance(i)
  2398. * // ...render
  2399. * setCurrentRenderingInstance(prev)
  2400. * ```
  2401. */
  2402. function setCurrentRenderingInstance(instance) {
  2403. const prev = currentRenderingInstance;
  2404. currentRenderingInstance = instance;
  2405. currentScopeId = (instance && instance.type.__scopeId) || null;
  2406. return prev;
  2407. }
  2408. /**
  2409. * Set scope id when creating hoisted vnodes.
  2410. * @private compiler helper
  2411. */
  2412. function pushScopeId(id) {
  2413. currentScopeId = id;
  2414. }
  2415. /**
  2416. * Technically we no longer need this after 3.0.8 but we need to keep the same
  2417. * API for backwards compat w/ code generated by compilers.
  2418. * @private
  2419. */
  2420. function popScopeId() {
  2421. currentScopeId = null;
  2422. }
  2423. /**
  2424. * Only for backwards compat
  2425. * @private
  2426. */
  2427. const withScopeId = (_id) => withCtx;
  2428. /**
  2429. * Wrap a slot function to memoize current rendering instance
  2430. * @private compiler helper
  2431. */
  2432. function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
  2433. ) {
  2434. if (!ctx)
  2435. return fn;
  2436. // already normalized
  2437. if (fn._n) {
  2438. return fn;
  2439. }
  2440. const renderFnWithContext = (...args) => {
  2441. // If a user calls a compiled slot inside a template expression (#1745), it
  2442. // can mess up block tracking, so by default we disable block tracking and
  2443. // force bail out when invoking a compiled slot (indicated by the ._d flag).
  2444. // This isn't necessary if rendering a compiled `<slot>`, so we flip the
  2445. // ._d flag off when invoking the wrapped fn inside `renderSlot`.
  2446. if (renderFnWithContext._d) {
  2447. setBlockTracking(-1);
  2448. }
  2449. const prevInstance = setCurrentRenderingInstance(ctx);
  2450. let res;
  2451. try {
  2452. res = fn(...args);
  2453. }
  2454. finally {
  2455. setCurrentRenderingInstance(prevInstance);
  2456. if (renderFnWithContext._d) {
  2457. setBlockTracking(1);
  2458. }
  2459. }
  2460. {
  2461. devtoolsComponentUpdated(ctx);
  2462. }
  2463. return res;
  2464. };
  2465. // mark normalized to avoid duplicated wrapping
  2466. renderFnWithContext._n = true;
  2467. // mark this as compiled by default
  2468. // this is used in vnode.ts -> normalizeChildren() to set the slot
  2469. // rendering flag.
  2470. renderFnWithContext._c = true;
  2471. // disable block tracking by default
  2472. renderFnWithContext._d = true;
  2473. return renderFnWithContext;
  2474. }
  2475. /**
  2476. * dev only flag to track whether $attrs was used during render.
  2477. * If $attrs was used during render then the warning for failed attrs
  2478. * fallthrough can be suppressed.
  2479. */
  2480. let accessedAttrs = false;
  2481. function markAttrsAccessed() {
  2482. accessedAttrs = true;
  2483. }
  2484. function renderComponentRoot(instance) {
  2485. const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
  2486. let result;
  2487. let fallthroughAttrs;
  2488. const prev = setCurrentRenderingInstance(instance);
  2489. {
  2490. accessedAttrs = false;
  2491. }
  2492. try {
  2493. if (vnode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */) {
  2494. // withProxy is a proxy with a different `has` trap only for
  2495. // runtime-compiled render functions using `with` block.
  2496. const proxyToUse = withProxy || proxy;
  2497. result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
  2498. fallthroughAttrs = attrs;
  2499. }
  2500. else {
  2501. // functional
  2502. const render = Component;
  2503. // in dev, mark attrs accessed if optional props (attrs === props)
  2504. if (true && attrs === props) {
  2505. markAttrsAccessed();
  2506. }
  2507. result = normalizeVNode(render.length > 1
  2508. ? render(props, true
  2509. ? {
  2510. get attrs() {
  2511. markAttrsAccessed();
  2512. return attrs;
  2513. },
  2514. slots,
  2515. emit
  2516. }
  2517. : { attrs, slots, emit })
  2518. : render(props, null /* we know it doesn't need it */));
  2519. fallthroughAttrs = Component.props
  2520. ? attrs
  2521. : getFunctionalFallthrough(attrs);
  2522. }
  2523. }
  2524. catch (err) {
  2525. blockStack.length = 0;
  2526. handleError(err, instance, 1 /* ErrorCodes.RENDER_FUNCTION */);
  2527. result = createVNode(Comment);
  2528. }
  2529. // attr merging
  2530. // in dev mode, comments are preserved, and it's possible for a template
  2531. // to have comments along side the root element which makes it a fragment
  2532. let root = result;
  2533. let setRoot = undefined;
  2534. if (result.patchFlag > 0 &&
  2535. result.patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */) {
  2536. [root, setRoot] = getChildRoot(result);
  2537. }
  2538. if (fallthroughAttrs && inheritAttrs !== false) {
  2539. const keys = Object.keys(fallthroughAttrs);
  2540. const { shapeFlag } = root;
  2541. if (keys.length) {
  2542. if (shapeFlag & (1 /* ShapeFlags.ELEMENT */ | 6 /* ShapeFlags.COMPONENT */)) {
  2543. if (propsOptions && keys.some(isModelListener)) {
  2544. // If a v-model listener (onUpdate:xxx) has a corresponding declared
  2545. // prop, it indicates this component expects to handle v-model and
  2546. // it should not fallthrough.
  2547. // related: #1543, #1643, #1989
  2548. fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
  2549. }
  2550. root = cloneVNode(root, fallthroughAttrs);
  2551. }
  2552. else if (!accessedAttrs && root.type !== Comment) {
  2553. const allAttrs = Object.keys(attrs);
  2554. const eventAttrs = [];
  2555. const extraAttrs = [];
  2556. for (let i = 0, l = allAttrs.length; i < l; i++) {
  2557. const key = allAttrs[i];
  2558. if (isOn(key)) {
  2559. // ignore v-model handlers when they fail to fallthrough
  2560. if (!isModelListener(key)) {
  2561. // remove `on`, lowercase first letter to reflect event casing
  2562. // accurately
  2563. eventAttrs.push(key[2].toLowerCase() + key.slice(3));
  2564. }
  2565. }
  2566. else {
  2567. extraAttrs.push(key);
  2568. }
  2569. }
  2570. if (extraAttrs.length) {
  2571. warn(`Extraneous non-props attributes (` +
  2572. `${extraAttrs.join(', ')}) ` +
  2573. `were passed to component but could not be automatically inherited ` +
  2574. `because component renders fragment or text root nodes.`);
  2575. }
  2576. if (eventAttrs.length) {
  2577. warn(`Extraneous non-emits event listeners (` +
  2578. `${eventAttrs.join(', ')}) ` +
  2579. `were passed to component but could not be automatically inherited ` +
  2580. `because component renders fragment or text root nodes. ` +
  2581. `If the listener is intended to be a component custom event listener only, ` +
  2582. `declare it using the "emits" option.`);
  2583. }
  2584. }
  2585. }
  2586. }
  2587. // inherit directives
  2588. if (vnode.dirs) {
  2589. if (!isElementRoot(root)) {
  2590. warn(`Runtime directive used on component with non-element root node. ` +
  2591. `The directives will not function as intended.`);
  2592. }
  2593. // clone before mutating since the root may be a hoisted vnode
  2594. root = cloneVNode(root);
  2595. root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
  2596. }
  2597. // inherit transition data
  2598. if (vnode.transition) {
  2599. if (!isElementRoot(root)) {
  2600. warn(`Component inside <Transition> renders non-element root node ` +
  2601. `that cannot be animated.`);
  2602. }
  2603. root.transition = vnode.transition;
  2604. }
  2605. if (setRoot) {
  2606. setRoot(root);
  2607. }
  2608. else {
  2609. result = root;
  2610. }
  2611. setCurrentRenderingInstance(prev);
  2612. return result;
  2613. }
  2614. /**
  2615. * dev only
  2616. * In dev mode, template root level comments are rendered, which turns the
  2617. * template into a fragment root, but we need to locate the single element
  2618. * root for attrs and scope id processing.
  2619. */
  2620. const getChildRoot = (vnode) => {
  2621. const rawChildren = vnode.children;
  2622. const dynamicChildren = vnode.dynamicChildren;
  2623. const childRoot = filterSingleRoot(rawChildren);
  2624. if (!childRoot) {
  2625. return [vnode, undefined];
  2626. }
  2627. const index = rawChildren.indexOf(childRoot);
  2628. const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
  2629. const setRoot = (updatedRoot) => {
  2630. rawChildren[index] = updatedRoot;
  2631. if (dynamicChildren) {
  2632. if (dynamicIndex > -1) {
  2633. dynamicChildren[dynamicIndex] = updatedRoot;
  2634. }
  2635. else if (updatedRoot.patchFlag > 0) {
  2636. vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
  2637. }
  2638. }
  2639. };
  2640. return [normalizeVNode(childRoot), setRoot];
  2641. };
  2642. function filterSingleRoot(children) {
  2643. let singleRoot;
  2644. for (let i = 0; i < children.length; i++) {
  2645. const child = children[i];
  2646. if (isVNode(child)) {
  2647. // ignore user comment
  2648. if (child.type !== Comment || child.children === 'v-if') {
  2649. if (singleRoot) {
  2650. // has more than 1 non-comment child, return now
  2651. return;
  2652. }
  2653. else {
  2654. singleRoot = child;
  2655. }
  2656. }
  2657. }
  2658. else {
  2659. return;
  2660. }
  2661. }
  2662. return singleRoot;
  2663. }
  2664. const getFunctionalFallthrough = (attrs) => {
  2665. let res;
  2666. for (const key in attrs) {
  2667. if (key === 'class' || key === 'style' || isOn(key)) {
  2668. (res || (res = {}))[key] = attrs[key];
  2669. }
  2670. }
  2671. return res;
  2672. };
  2673. const filterModelListeners = (attrs, props) => {
  2674. const res = {};
  2675. for (const key in attrs) {
  2676. if (!isModelListener(key) || !(key.slice(9) in props)) {
  2677. res[key] = attrs[key];
  2678. }
  2679. }
  2680. return res;
  2681. };
  2682. const isElementRoot = (vnode) => {
  2683. return (vnode.shapeFlag & (6 /* ShapeFlags.COMPONENT */ | 1 /* ShapeFlags.ELEMENT */) ||
  2684. vnode.type === Comment // potential v-if branch switch
  2685. );
  2686. };
  2687. function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
  2688. const { props: prevProps, children: prevChildren, component } = prevVNode;
  2689. const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
  2690. const emits = component.emitsOptions;
  2691. // Parent component's render function was hot-updated. Since this may have
  2692. // caused the child component's slots content to have changed, we need to
  2693. // force the child to update as well.
  2694. if ((prevChildren || nextChildren) && isHmrUpdating) {
  2695. return true;
  2696. }
  2697. // force child update for runtime directive or transition on component vnode.
  2698. if (nextVNode.dirs || nextVNode.transition) {
  2699. return true;
  2700. }
  2701. if (optimized && patchFlag >= 0) {
  2702. if (patchFlag & 1024 /* PatchFlags.DYNAMIC_SLOTS */) {
  2703. // slot content that references values that might have changed,
  2704. // e.g. in a v-for
  2705. return true;
  2706. }
  2707. if (patchFlag & 16 /* PatchFlags.FULL_PROPS */) {
  2708. if (!prevProps) {
  2709. return !!nextProps;
  2710. }
  2711. // presence of this flag indicates props are always non-null
  2712. return hasPropsChanged(prevProps, nextProps, emits);
  2713. }
  2714. else if (patchFlag & 8 /* PatchFlags.PROPS */) {
  2715. const dynamicProps = nextVNode.dynamicProps;
  2716. for (let i = 0; i < dynamicProps.length; i++) {
  2717. const key = dynamicProps[i];
  2718. if (nextProps[key] !== prevProps[key] &&
  2719. !isEmitListener(emits, key)) {
  2720. return true;
  2721. }
  2722. }
  2723. }
  2724. }
  2725. else {
  2726. // this path is only taken by manually written render functions
  2727. // so presence of any children leads to a forced update
  2728. if (prevChildren || nextChildren) {
  2729. if (!nextChildren || !nextChildren.$stable) {
  2730. return true;
  2731. }
  2732. }
  2733. if (prevProps === nextProps) {
  2734. return false;
  2735. }
  2736. if (!prevProps) {
  2737. return !!nextProps;
  2738. }
  2739. if (!nextProps) {
  2740. return true;
  2741. }
  2742. return hasPropsChanged(prevProps, nextProps, emits);
  2743. }
  2744. return false;
  2745. }
  2746. function hasPropsChanged(prevProps, nextProps, emitsOptions) {
  2747. const nextKeys = Object.keys(nextProps);
  2748. if (nextKeys.length !== Object.keys(prevProps).length) {
  2749. return true;
  2750. }
  2751. for (let i = 0; i < nextKeys.length; i++) {
  2752. const key = nextKeys[i];
  2753. if (nextProps[key] !== prevProps[key] &&
  2754. !isEmitListener(emitsOptions, key)) {
  2755. return true;
  2756. }
  2757. }
  2758. return false;
  2759. }
  2760. function updateHOCHostEl({ vnode, parent }, el // HostNode
  2761. ) {
  2762. while (parent && parent.subTree === vnode) {
  2763. (vnode = parent.vnode).el = el;
  2764. parent = parent.parent;
  2765. }
  2766. }
  2767. const isSuspense = (type) => type.__isSuspense;
  2768. // Suspense exposes a component-like API, and is treated like a component
  2769. // in the compiler, but internally it's a special built-in type that hooks
  2770. // directly into the renderer.
  2771. const SuspenseImpl = {
  2772. name: 'Suspense',
  2773. // In order to make Suspense tree-shakable, we need to avoid importing it
  2774. // directly in the renderer. The renderer checks for the __isSuspense flag
  2775. // on a vnode's type and calls the `process` method, passing in renderer
  2776. // internals.
  2777. __isSuspense: true,
  2778. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
  2779. // platform-specific impl passed from renderer
  2780. rendererInternals) {
  2781. if (n1 == null) {
  2782. mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
  2783. }
  2784. else {
  2785. patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
  2786. }
  2787. },
  2788. hydrate: hydrateSuspense,
  2789. create: createSuspenseBoundary,
  2790. normalize: normalizeSuspenseChildren
  2791. };
  2792. // Force-casted public typing for h and TSX props inference
  2793. const Suspense = (SuspenseImpl
  2794. );
  2795. function triggerEvent(vnode, name) {
  2796. const eventListener = vnode.props && vnode.props[name];
  2797. if (isFunction(eventListener)) {
  2798. eventListener();
  2799. }
  2800. }
  2801. function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
  2802. const { p: patch, o: { createElement } } = rendererInternals;
  2803. const hiddenContainer = createElement('div');
  2804. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
  2805. // start mounting the content subtree in an off-dom container
  2806. patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
  2807. // now check if we have encountered any async deps
  2808. if (suspense.deps > 0) {
  2809. // has async
  2810. // invoke @fallback event
  2811. triggerEvent(vnode, 'onPending');
  2812. triggerEvent(vnode, 'onFallback');
  2813. // mount the fallback tree
  2814. patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2815. isSVG, slotScopeIds);
  2816. setActiveBranch(suspense, vnode.ssFallback);
  2817. }
  2818. else {
  2819. // Suspense has no async deps. Just resolve.
  2820. suspense.resolve();
  2821. }
  2822. }
  2823. function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
  2824. const suspense = (n2.suspense = n1.suspense);
  2825. suspense.vnode = n2;
  2826. n2.el = n1.el;
  2827. const newBranch = n2.ssContent;
  2828. const newFallback = n2.ssFallback;
  2829. const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
  2830. if (pendingBranch) {
  2831. suspense.pendingBranch = newBranch;
  2832. if (isSameVNodeType(newBranch, pendingBranch)) {
  2833. // same root type but content may have changed.
  2834. patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2835. if (suspense.deps <= 0) {
  2836. suspense.resolve();
  2837. }
  2838. else if (isInFallback) {
  2839. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2840. isSVG, slotScopeIds, optimized);
  2841. setActiveBranch(suspense, newFallback);
  2842. }
  2843. }
  2844. else {
  2845. // toggled before pending tree is resolved
  2846. suspense.pendingId++;
  2847. if (isHydrating) {
  2848. // if toggled before hydration is finished, the current DOM tree is
  2849. // no longer valid. set it as the active branch so it will be unmounted
  2850. // when resolved
  2851. suspense.isHydrating = false;
  2852. suspense.activeBranch = pendingBranch;
  2853. }
  2854. else {
  2855. unmount(pendingBranch, parentComponent, suspense);
  2856. }
  2857. // increment pending ID. this is used to invalidate async callbacks
  2858. // reset suspense state
  2859. suspense.deps = 0;
  2860. // discard effects from pending branch
  2861. suspense.effects.length = 0;
  2862. // discard previous container
  2863. suspense.hiddenContainer = createElement('div');
  2864. if (isInFallback) {
  2865. // already in fallback state
  2866. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2867. if (suspense.deps <= 0) {
  2868. suspense.resolve();
  2869. }
  2870. else {
  2871. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2872. isSVG, slotScopeIds, optimized);
  2873. setActiveBranch(suspense, newFallback);
  2874. }
  2875. }
  2876. else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2877. // toggled "back" to current active branch
  2878. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2879. // force resolve
  2880. suspense.resolve(true);
  2881. }
  2882. else {
  2883. // switched to a 3rd branch
  2884. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2885. if (suspense.deps <= 0) {
  2886. suspense.resolve();
  2887. }
  2888. }
  2889. }
  2890. }
  2891. else {
  2892. if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2893. // root did not change, just normal patch
  2894. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2895. setActiveBranch(suspense, newBranch);
  2896. }
  2897. else {
  2898. // root node toggled
  2899. // invoke @pending event
  2900. triggerEvent(n2, 'onPending');
  2901. // mount pending branch in off-dom container
  2902. suspense.pendingBranch = newBranch;
  2903. suspense.pendingId++;
  2904. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2905. if (suspense.deps <= 0) {
  2906. // incoming branch has no async deps, resolve now.
  2907. suspense.resolve();
  2908. }
  2909. else {
  2910. const { timeout, pendingId } = suspense;
  2911. if (timeout > 0) {
  2912. setTimeout(() => {
  2913. if (suspense.pendingId === pendingId) {
  2914. suspense.fallback(newFallback);
  2915. }
  2916. }, timeout);
  2917. }
  2918. else if (timeout === 0) {
  2919. suspense.fallback(newFallback);
  2920. }
  2921. }
  2922. }
  2923. }
  2924. }
  2925. let hasWarned = false;
  2926. function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
  2927. /* istanbul ignore if */
  2928. if (!hasWarned) {
  2929. hasWarned = true;
  2930. // @ts-ignore `console.info` cannot be null error
  2931. console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
  2932. }
  2933. const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
  2934. const timeout = vnode.props ? toNumber(vnode.props.timeout) : undefined;
  2935. {
  2936. assertNumber(timeout, `Suspense timeout`);
  2937. }
  2938. const suspense = {
  2939. vnode,
  2940. parent,
  2941. parentComponent,
  2942. isSVG,
  2943. container,
  2944. hiddenContainer,
  2945. anchor,
  2946. deps: 0,
  2947. pendingId: 0,
  2948. timeout: typeof timeout === 'number' ? timeout : -1,
  2949. activeBranch: null,
  2950. pendingBranch: null,
  2951. isInFallback: true,
  2952. isHydrating,
  2953. isUnmounted: false,
  2954. effects: [],
  2955. resolve(resume = false) {
  2956. {
  2957. if (!resume && !suspense.pendingBranch) {
  2958. throw new Error(`suspense.resolve() is called without a pending branch.`);
  2959. }
  2960. if (suspense.isUnmounted) {
  2961. throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
  2962. }
  2963. }
  2964. const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
  2965. if (suspense.isHydrating) {
  2966. suspense.isHydrating = false;
  2967. }
  2968. else if (!resume) {
  2969. const delayEnter = activeBranch &&
  2970. pendingBranch.transition &&
  2971. pendingBranch.transition.mode === 'out-in';
  2972. if (delayEnter) {
  2973. activeBranch.transition.afterLeave = () => {
  2974. if (pendingId === suspense.pendingId) {
  2975. move(pendingBranch, container, anchor, 0 /* MoveType.ENTER */);
  2976. }
  2977. };
  2978. }
  2979. // this is initial anchor on mount
  2980. let { anchor } = suspense;
  2981. // unmount current active tree
  2982. if (activeBranch) {
  2983. // if the fallback tree was mounted, it may have been moved
  2984. // as part of a parent suspense. get the latest anchor for insertion
  2985. anchor = next(activeBranch);
  2986. unmount(activeBranch, parentComponent, suspense, true);
  2987. }
  2988. if (!delayEnter) {
  2989. // move content from off-dom container to actual container
  2990. move(pendingBranch, container, anchor, 0 /* MoveType.ENTER */);
  2991. }
  2992. }
  2993. setActiveBranch(suspense, pendingBranch);
  2994. suspense.pendingBranch = null;
  2995. suspense.isInFallback = false;
  2996. // flush buffered effects
  2997. // check if there is a pending parent suspense
  2998. let parent = suspense.parent;
  2999. let hasUnresolvedAncestor = false;
  3000. while (parent) {
  3001. if (parent.pendingBranch) {
  3002. // found a pending parent suspense, merge buffered post jobs
  3003. // into that parent
  3004. parent.effects.push(...effects);
  3005. hasUnresolvedAncestor = true;
  3006. break;
  3007. }
  3008. parent = parent.parent;
  3009. }
  3010. // no pending parent suspense, flush all jobs
  3011. if (!hasUnresolvedAncestor) {
  3012. queuePostFlushCb(effects);
  3013. }
  3014. suspense.effects = [];
  3015. // invoke @resolve event
  3016. triggerEvent(vnode, 'onResolve');
  3017. },
  3018. fallback(fallbackVNode) {
  3019. if (!suspense.pendingBranch) {
  3020. return;
  3021. }
  3022. const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
  3023. // invoke @fallback event
  3024. triggerEvent(vnode, 'onFallback');
  3025. const anchor = next(activeBranch);
  3026. const mountFallback = () => {
  3027. if (!suspense.isInFallback) {
  3028. return;
  3029. }
  3030. // mount the fallback tree
  3031. patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  3032. isSVG, slotScopeIds, optimized);
  3033. setActiveBranch(suspense, fallbackVNode);
  3034. };
  3035. const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
  3036. if (delayEnter) {
  3037. activeBranch.transition.afterLeave = mountFallback;
  3038. }
  3039. suspense.isInFallback = true;
  3040. // unmount current active branch
  3041. unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
  3042. true // shouldRemove
  3043. );
  3044. if (!delayEnter) {
  3045. mountFallback();
  3046. }
  3047. },
  3048. move(container, anchor, type) {
  3049. suspense.activeBranch &&
  3050. move(suspense.activeBranch, container, anchor, type);
  3051. suspense.container = container;
  3052. },
  3053. next() {
  3054. return suspense.activeBranch && next(suspense.activeBranch);
  3055. },
  3056. registerDep(instance, setupRenderEffect) {
  3057. const isInPendingSuspense = !!suspense.pendingBranch;
  3058. if (isInPendingSuspense) {
  3059. suspense.deps++;
  3060. }
  3061. const hydratedEl = instance.vnode.el;
  3062. instance
  3063. .asyncDep.catch(err => {
  3064. handleError(err, instance, 0 /* ErrorCodes.SETUP_FUNCTION */);
  3065. })
  3066. .then(asyncSetupResult => {
  3067. // retry when the setup() promise resolves.
  3068. // component may have been unmounted before resolve.
  3069. if (instance.isUnmounted ||
  3070. suspense.isUnmounted ||
  3071. suspense.pendingId !== instance.suspenseId) {
  3072. return;
  3073. }
  3074. // retry from this component
  3075. instance.asyncResolved = true;
  3076. const { vnode } = instance;
  3077. {
  3078. pushWarningContext(vnode);
  3079. }
  3080. handleSetupResult(instance, asyncSetupResult, false);
  3081. if (hydratedEl) {
  3082. // vnode may have been replaced if an update happened before the
  3083. // async dep is resolved.
  3084. vnode.el = hydratedEl;
  3085. }
  3086. const placeholder = !hydratedEl && instance.subTree.el;
  3087. setupRenderEffect(instance, vnode,
  3088. // component may have been moved before resolve.
  3089. // if this is not a hydration, instance.subTree will be the comment
  3090. // placeholder.
  3091. parentNode(hydratedEl || instance.subTree.el),
  3092. // anchor will not be used if this is hydration, so only need to
  3093. // consider the comment placeholder case.
  3094. hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
  3095. if (placeholder) {
  3096. remove(placeholder);
  3097. }
  3098. updateHOCHostEl(instance, vnode.el);
  3099. {
  3100. popWarningContext();
  3101. }
  3102. // only decrease deps count if suspense is not already resolved
  3103. if (isInPendingSuspense && --suspense.deps === 0) {
  3104. suspense.resolve();
  3105. }
  3106. });
  3107. },
  3108. unmount(parentSuspense, doRemove) {
  3109. suspense.isUnmounted = true;
  3110. if (suspense.activeBranch) {
  3111. unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
  3112. }
  3113. if (suspense.pendingBranch) {
  3114. unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
  3115. }
  3116. }
  3117. };
  3118. return suspense;
  3119. }
  3120. function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
  3121. /* eslint-disable no-restricted-globals */
  3122. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
  3123. // there are two possible scenarios for server-rendered suspense:
  3124. // - success: ssr content should be fully resolved
  3125. // - failure: ssr content should be the fallback branch.
  3126. // however, on the client we don't really know if it has failed or not
  3127. // attempt to hydrate the DOM assuming it has succeeded, but we still
  3128. // need to construct a suspense boundary first
  3129. const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
  3130. if (suspense.deps === 0) {
  3131. suspense.resolve();
  3132. }
  3133. return result;
  3134. /* eslint-enable no-restricted-globals */
  3135. }
  3136. function normalizeSuspenseChildren(vnode) {
  3137. const { shapeFlag, children } = vnode;
  3138. const isSlotChildren = shapeFlag & 32 /* ShapeFlags.SLOTS_CHILDREN */;
  3139. vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
  3140. vnode.ssFallback = isSlotChildren
  3141. ? normalizeSuspenseSlot(children.fallback)
  3142. : createVNode(Comment);
  3143. }
  3144. function normalizeSuspenseSlot(s) {
  3145. let block;
  3146. if (isFunction(s)) {
  3147. const trackBlock = isBlockTreeEnabled && s._c;
  3148. if (trackBlock) {
  3149. // disableTracking: false
  3150. // allow block tracking for compiled slots
  3151. // (see ./componentRenderContext.ts)
  3152. s._d = false;
  3153. openBlock();
  3154. }
  3155. s = s();
  3156. if (trackBlock) {
  3157. s._d = true;
  3158. block = currentBlock;
  3159. closeBlock();
  3160. }
  3161. }
  3162. if (isArray(s)) {
  3163. const singleChild = filterSingleRoot(s);
  3164. if (!singleChild) {
  3165. warn(`<Suspense> slots expect a single root node.`);
  3166. }
  3167. s = singleChild;
  3168. }
  3169. s = normalizeVNode(s);
  3170. if (block && !s.dynamicChildren) {
  3171. s.dynamicChildren = block.filter(c => c !== s);
  3172. }
  3173. return s;
  3174. }
  3175. function queueEffectWithSuspense(fn, suspense) {
  3176. if (suspense && suspense.pendingBranch) {
  3177. if (isArray(fn)) {
  3178. suspense.effects.push(...fn);
  3179. }
  3180. else {
  3181. suspense.effects.push(fn);
  3182. }
  3183. }
  3184. else {
  3185. queuePostFlushCb(fn);
  3186. }
  3187. }
  3188. function setActiveBranch(suspense, branch) {
  3189. suspense.activeBranch = branch;
  3190. const { vnode, parentComponent } = suspense;
  3191. const el = (vnode.el = branch.el);
  3192. // in case suspense is the root node of a component,
  3193. // recursively update the HOC el
  3194. if (parentComponent && parentComponent.subTree === vnode) {
  3195. parentComponent.vnode.el = el;
  3196. updateHOCHostEl(parentComponent, el);
  3197. }
  3198. }
  3199. function provide(key, value) {
  3200. if (!currentInstance) {
  3201. {
  3202. warn(`provide() can only be used inside setup().`);
  3203. }
  3204. }
  3205. else {
  3206. let provides = currentInstance.provides;
  3207. // by default an instance inherits its parent's provides object
  3208. // but when it needs to provide values of its own, it creates its
  3209. // own provides object using parent provides object as prototype.
  3210. // this way in `inject` we can simply look up injections from direct
  3211. // parent and let the prototype chain do the work.
  3212. const parentProvides = currentInstance.parent && currentInstance.parent.provides;
  3213. if (parentProvides === provides) {
  3214. provides = currentInstance.provides = Object.create(parentProvides);
  3215. }
  3216. // TS doesn't allow symbol as index type
  3217. provides[key] = value;
  3218. }
  3219. }
  3220. function inject(key, defaultValue, treatDefaultAsFactory = false) {
  3221. // fallback to `currentRenderingInstance` so that this can be called in
  3222. // a functional component
  3223. const instance = currentInstance || currentRenderingInstance;
  3224. if (instance) {
  3225. // #2400
  3226. // to support `app.use` plugins,
  3227. // fallback to appContext's `provides` if the instance is at root
  3228. const provides = instance.parent == null
  3229. ? instance.vnode.appContext && instance.vnode.appContext.provides
  3230. : instance.parent.provides;
  3231. if (provides && key in provides) {
  3232. // TS doesn't allow symbol as index type
  3233. return provides[key];
  3234. }
  3235. else if (arguments.length > 1) {
  3236. return treatDefaultAsFactory && isFunction(defaultValue)
  3237. ? defaultValue.call(instance.proxy)
  3238. : defaultValue;
  3239. }
  3240. else {
  3241. warn(`injection "${String(key)}" not found.`);
  3242. }
  3243. }
  3244. else {
  3245. warn(`inject() can only be used inside setup() or functional components.`);
  3246. }
  3247. }
  3248. // Simple effect.
  3249. function watchEffect(effect, options) {
  3250. return doWatch(effect, null, options);
  3251. }
  3252. function watchPostEffect(effect, options) {
  3253. return doWatch(effect, null, Object.assign(Object.assign({}, options), { flush: 'post' }) );
  3254. }
  3255. function watchSyncEffect(effect, options) {
  3256. return doWatch(effect, null, Object.assign(Object.assign({}, options), { flush: 'sync' }) );
  3257. }
  3258. // initial value for watchers to trigger on undefined initial values
  3259. const INITIAL_WATCHER_VALUE = {};
  3260. // implementation
  3261. function watch(source, cb, options) {
  3262. if (!isFunction(cb)) {
  3263. warn(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
  3264. `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
  3265. `supports \`watch(source, cb, options?) signature.`);
  3266. }
  3267. return doWatch(source, cb, options);
  3268. }
  3269. function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
  3270. if (!cb) {
  3271. if (immediate !== undefined) {
  3272. warn(`watch() "immediate" option is only respected when using the ` +
  3273. `watch(source, callback, options?) signature.`);
  3274. }
  3275. if (deep !== undefined) {
  3276. warn(`watch() "deep" option is only respected when using the ` +
  3277. `watch(source, callback, options?) signature.`);
  3278. }
  3279. }
  3280. const warnInvalidSource = (s) => {
  3281. warn(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
  3282. `a reactive object, or an array of these types.`);
  3283. };
  3284. const instance = getCurrentScope() === (currentInstance === null || currentInstance === void 0 ? void 0 : currentInstance.scope) ? currentInstance : null;
  3285. // const instance = currentInstance
  3286. let getter;
  3287. let forceTrigger = false;
  3288. let isMultiSource = false;
  3289. if (isRef(source)) {
  3290. getter = () => source.value;
  3291. forceTrigger = isShallow(source);
  3292. }
  3293. else if (isReactive(source)) {
  3294. getter = () => source;
  3295. deep = true;
  3296. }
  3297. else if (isArray(source)) {
  3298. isMultiSource = true;
  3299. forceTrigger = source.some(s => isReactive(s) || isShallow(s));
  3300. getter = () => source.map(s => {
  3301. if (isRef(s)) {
  3302. return s.value;
  3303. }
  3304. else if (isReactive(s)) {
  3305. return traverse(s);
  3306. }
  3307. else if (isFunction(s)) {
  3308. return callWithErrorHandling(s, instance, 2 /* ErrorCodes.WATCH_GETTER */);
  3309. }
  3310. else {
  3311. warnInvalidSource(s);
  3312. }
  3313. });
  3314. }
  3315. else if (isFunction(source)) {
  3316. if (cb) {
  3317. // getter with cb
  3318. getter = () => callWithErrorHandling(source, instance, 2 /* ErrorCodes.WATCH_GETTER */);
  3319. }
  3320. else {
  3321. // no cb -> simple effect
  3322. getter = () => {
  3323. if (instance && instance.isUnmounted) {
  3324. return;
  3325. }
  3326. if (cleanup) {
  3327. cleanup();
  3328. }
  3329. return callWithAsyncErrorHandling(source, instance, 3 /* ErrorCodes.WATCH_CALLBACK */, [onCleanup]);
  3330. };
  3331. }
  3332. }
  3333. else {
  3334. getter = NOOP;
  3335. warnInvalidSource(source);
  3336. }
  3337. if (cb && deep) {
  3338. const baseGetter = getter;
  3339. getter = () => traverse(baseGetter());
  3340. }
  3341. let cleanup;
  3342. let onCleanup = (fn) => {
  3343. cleanup = effect.onStop = () => {
  3344. callWithErrorHandling(fn, instance, 4 /* ErrorCodes.WATCH_CLEANUP */);
  3345. };
  3346. };
  3347. let oldValue = isMultiSource
  3348. ? new Array(source.length).fill(INITIAL_WATCHER_VALUE)
  3349. : INITIAL_WATCHER_VALUE;
  3350. const job = () => {
  3351. if (!effect.active) {
  3352. return;
  3353. }
  3354. if (cb) {
  3355. // watch(source, cb)
  3356. const newValue = effect.run();
  3357. if (deep ||
  3358. forceTrigger ||
  3359. (isMultiSource
  3360. ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
  3361. : hasChanged(newValue, oldValue)) ||
  3362. (false )) {
  3363. // cleanup before running cb again
  3364. if (cleanup) {
  3365. cleanup();
  3366. }
  3367. callWithAsyncErrorHandling(cb, instance, 3 /* ErrorCodes.WATCH_CALLBACK */, [
  3368. newValue,
  3369. // pass undefined as the old value when it's changed for the first time
  3370. oldValue === INITIAL_WATCHER_VALUE
  3371. ? undefined
  3372. : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE
  3373. ? []
  3374. : oldValue,
  3375. onCleanup
  3376. ]);
  3377. oldValue = newValue;
  3378. }
  3379. }
  3380. else {
  3381. // watchEffect
  3382. effect.run();
  3383. }
  3384. };
  3385. // important: mark the job as a watcher callback so that scheduler knows
  3386. // it is allowed to self-trigger (#1727)
  3387. job.allowRecurse = !!cb;
  3388. let scheduler;
  3389. if (flush === 'sync') {
  3390. scheduler = job; // the scheduler function gets called directly
  3391. }
  3392. else if (flush === 'post') {
  3393. scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
  3394. }
  3395. else {
  3396. // default: 'pre'
  3397. job.pre = true;
  3398. if (instance)
  3399. job.id = instance.uid;
  3400. scheduler = () => queueJob(job);
  3401. }
  3402. const effect = new ReactiveEffect(getter, scheduler);
  3403. {
  3404. effect.onTrack = onTrack;
  3405. effect.onTrigger = onTrigger;
  3406. }
  3407. // initial run
  3408. if (cb) {
  3409. if (immediate) {
  3410. job();
  3411. }
  3412. else {
  3413. oldValue = effect.run();
  3414. }
  3415. }
  3416. else if (flush === 'post') {
  3417. queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
  3418. }
  3419. else {
  3420. effect.run();
  3421. }
  3422. const unwatch = () => {
  3423. effect.stop();
  3424. if (instance && instance.scope) {
  3425. remove(instance.scope.effects, effect);
  3426. }
  3427. };
  3428. return unwatch;
  3429. }
  3430. // this.$watch
  3431. function instanceWatch(source, value, options) {
  3432. const publicThis = this.proxy;
  3433. const getter = isString(source)
  3434. ? source.includes('.')
  3435. ? createPathGetter(publicThis, source)
  3436. : () => publicThis[source]
  3437. : source.bind(publicThis, publicThis);
  3438. let cb;
  3439. if (isFunction(value)) {
  3440. cb = value;
  3441. }
  3442. else {
  3443. cb = value.handler;
  3444. options = value;
  3445. }
  3446. const cur = currentInstance;
  3447. setCurrentInstance(this);
  3448. const res = doWatch(getter, cb.bind(publicThis), options);
  3449. if (cur) {
  3450. setCurrentInstance(cur);
  3451. }
  3452. else {
  3453. unsetCurrentInstance();
  3454. }
  3455. return res;
  3456. }
  3457. function createPathGetter(ctx, path) {
  3458. const segments = path.split('.');
  3459. return () => {
  3460. let cur = ctx;
  3461. for (let i = 0; i < segments.length && cur; i++) {
  3462. cur = cur[segments[i]];
  3463. }
  3464. return cur;
  3465. };
  3466. }
  3467. function traverse(value, seen) {
  3468. if (!isObject(value) || value["__v_skip" /* ReactiveFlags.SKIP */]) {
  3469. return value;
  3470. }
  3471. seen = seen || new Set();
  3472. if (seen.has(value)) {
  3473. return value;
  3474. }
  3475. seen.add(value);
  3476. if (isRef(value)) {
  3477. traverse(value.value, seen);
  3478. }
  3479. else if (isArray(value)) {
  3480. for (let i = 0; i < value.length; i++) {
  3481. traverse(value[i], seen);
  3482. }
  3483. }
  3484. else if (isSet(value) || isMap(value)) {
  3485. value.forEach((v) => {
  3486. traverse(v, seen);
  3487. });
  3488. }
  3489. else if (isPlainObject(value)) {
  3490. for (const key in value) {
  3491. traverse(value[key], seen);
  3492. }
  3493. }
  3494. return value;
  3495. }
  3496. function useTransitionState() {
  3497. const state = {
  3498. isMounted: false,
  3499. isLeaving: false,
  3500. isUnmounting: false,
  3501. leavingVNodes: new Map()
  3502. };
  3503. onMounted(() => {
  3504. state.isMounted = true;
  3505. });
  3506. onBeforeUnmount(() => {
  3507. state.isUnmounting = true;
  3508. });
  3509. return state;
  3510. }
  3511. const TransitionHookValidator = [Function, Array];
  3512. const BaseTransitionImpl = {
  3513. name: `BaseTransition`,
  3514. props: {
  3515. mode: String,
  3516. appear: Boolean,
  3517. persisted: Boolean,
  3518. // enter
  3519. onBeforeEnter: TransitionHookValidator,
  3520. onEnter: TransitionHookValidator,
  3521. onAfterEnter: TransitionHookValidator,
  3522. onEnterCancelled: TransitionHookValidator,
  3523. // leave
  3524. onBeforeLeave: TransitionHookValidator,
  3525. onLeave: TransitionHookValidator,
  3526. onAfterLeave: TransitionHookValidator,
  3527. onLeaveCancelled: TransitionHookValidator,
  3528. // appear
  3529. onBeforeAppear: TransitionHookValidator,
  3530. onAppear: TransitionHookValidator,
  3531. onAfterAppear: TransitionHookValidator,
  3532. onAppearCancelled: TransitionHookValidator
  3533. },
  3534. setup(props, { slots }) {
  3535. const instance = getCurrentInstance();
  3536. const state = useTransitionState();
  3537. let prevTransitionKey;
  3538. return () => {
  3539. const children = slots.default && getTransitionRawChildren(slots.default(), true);
  3540. if (!children || !children.length) {
  3541. return;
  3542. }
  3543. let child = children[0];
  3544. if (children.length > 1) {
  3545. let hasFound = false;
  3546. // locate first non-comment child
  3547. for (const c of children) {
  3548. if (c.type !== Comment) {
  3549. if (hasFound) {
  3550. // warn more than one non-comment child
  3551. warn('<transition> can only be used on a single element or component. ' +
  3552. 'Use <transition-group> for lists.');
  3553. break;
  3554. }
  3555. child = c;
  3556. hasFound = true;
  3557. }
  3558. }
  3559. }
  3560. // there's no need to track reactivity for these props so use the raw
  3561. // props for a bit better perf
  3562. const rawProps = toRaw(props);
  3563. const { mode } = rawProps;
  3564. // check mode
  3565. if (mode &&
  3566. mode !== 'in-out' &&
  3567. mode !== 'out-in' &&
  3568. mode !== 'default') {
  3569. warn(`invalid <transition> mode: ${mode}`);
  3570. }
  3571. if (state.isLeaving) {
  3572. return emptyPlaceholder(child);
  3573. }
  3574. // in the case of <transition><keep-alive/></transition>, we need to
  3575. // compare the type of the kept-alive children.
  3576. const innerChild = getKeepAliveChild(child);
  3577. if (!innerChild) {
  3578. return emptyPlaceholder(child);
  3579. }
  3580. const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
  3581. setTransitionHooks(innerChild, enterHooks);
  3582. const oldChild = instance.subTree;
  3583. const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
  3584. let transitionKeyChanged = false;
  3585. const { getTransitionKey } = innerChild.type;
  3586. if (getTransitionKey) {
  3587. const key = getTransitionKey();
  3588. if (prevTransitionKey === undefined) {
  3589. prevTransitionKey = key;
  3590. }
  3591. else if (key !== prevTransitionKey) {
  3592. prevTransitionKey = key;
  3593. transitionKeyChanged = true;
  3594. }
  3595. }
  3596. // handle mode
  3597. if (oldInnerChild &&
  3598. oldInnerChild.type !== Comment &&
  3599. (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
  3600. const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
  3601. // update old tree's hooks in case of dynamic transition
  3602. setTransitionHooks(oldInnerChild, leavingHooks);
  3603. // switching between different views
  3604. if (mode === 'out-in') {
  3605. state.isLeaving = true;
  3606. // return placeholder node and queue update when leave finishes
  3607. leavingHooks.afterLeave = () => {
  3608. state.isLeaving = false;
  3609. // #6835
  3610. // it also needs to be updated when active is undefined
  3611. if (instance.update.active !== false) {
  3612. instance.update();
  3613. }
  3614. };
  3615. return emptyPlaceholder(child);
  3616. }
  3617. else if (mode === 'in-out' && innerChild.type !== Comment) {
  3618. leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
  3619. const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
  3620. leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
  3621. // early removal callback
  3622. el._leaveCb = () => {
  3623. earlyRemove();
  3624. el._leaveCb = undefined;
  3625. delete enterHooks.delayedLeave;
  3626. };
  3627. enterHooks.delayedLeave = delayedLeave;
  3628. };
  3629. }
  3630. }
  3631. return child;
  3632. };
  3633. }
  3634. };
  3635. // export the public type for h/tsx inference
  3636. // also to avoid inline import() in generated d.ts files
  3637. const BaseTransition = BaseTransitionImpl;
  3638. function getLeavingNodesForType(state, vnode) {
  3639. const { leavingVNodes } = state;
  3640. let leavingVNodesCache = leavingVNodes.get(vnode.type);
  3641. if (!leavingVNodesCache) {
  3642. leavingVNodesCache = Object.create(null);
  3643. leavingVNodes.set(vnode.type, leavingVNodesCache);
  3644. }
  3645. return leavingVNodesCache;
  3646. }
  3647. // The transition hooks are attached to the vnode as vnode.transition
  3648. // and will be called at appropriate timing in the renderer.
  3649. function resolveTransitionHooks(vnode, props, state, instance) {
  3650. const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
  3651. const key = String(vnode.key);
  3652. const leavingVNodesCache = getLeavingNodesForType(state, vnode);
  3653. const callHook = (hook, args) => {
  3654. hook &&
  3655. callWithAsyncErrorHandling(hook, instance, 9 /* ErrorCodes.TRANSITION_HOOK */, args);
  3656. };
  3657. const callAsyncHook = (hook, args) => {
  3658. const done = args[1];
  3659. callHook(hook, args);
  3660. if (isArray(hook)) {
  3661. if (hook.every(hook => hook.length <= 1))
  3662. done();
  3663. }
  3664. else if (hook.length <= 1) {
  3665. done();
  3666. }
  3667. };
  3668. const hooks = {
  3669. mode,
  3670. persisted,
  3671. beforeEnter(el) {
  3672. let hook = onBeforeEnter;
  3673. if (!state.isMounted) {
  3674. if (appear) {
  3675. hook = onBeforeAppear || onBeforeEnter;
  3676. }
  3677. else {
  3678. return;
  3679. }
  3680. }
  3681. // for same element (v-show)
  3682. if (el._leaveCb) {
  3683. el._leaveCb(true /* cancelled */);
  3684. }
  3685. // for toggled element with same key (v-if)
  3686. const leavingVNode = leavingVNodesCache[key];
  3687. if (leavingVNode &&
  3688. isSameVNodeType(vnode, leavingVNode) &&
  3689. leavingVNode.el._leaveCb) {
  3690. // force early removal (not cancelled)
  3691. leavingVNode.el._leaveCb();
  3692. }
  3693. callHook(hook, [el]);
  3694. },
  3695. enter(el) {
  3696. let hook = onEnter;
  3697. let afterHook = onAfterEnter;
  3698. let cancelHook = onEnterCancelled;
  3699. if (!state.isMounted) {
  3700. if (appear) {
  3701. hook = onAppear || onEnter;
  3702. afterHook = onAfterAppear || onAfterEnter;
  3703. cancelHook = onAppearCancelled || onEnterCancelled;
  3704. }
  3705. else {
  3706. return;
  3707. }
  3708. }
  3709. let called = false;
  3710. const done = (el._enterCb = (cancelled) => {
  3711. if (called)
  3712. return;
  3713. called = true;
  3714. if (cancelled) {
  3715. callHook(cancelHook, [el]);
  3716. }
  3717. else {
  3718. callHook(afterHook, [el]);
  3719. }
  3720. if (hooks.delayedLeave) {
  3721. hooks.delayedLeave();
  3722. }
  3723. el._enterCb = undefined;
  3724. });
  3725. if (hook) {
  3726. callAsyncHook(hook, [el, done]);
  3727. }
  3728. else {
  3729. done();
  3730. }
  3731. },
  3732. leave(el, remove) {
  3733. const key = String(vnode.key);
  3734. if (el._enterCb) {
  3735. el._enterCb(true /* cancelled */);
  3736. }
  3737. if (state.isUnmounting) {
  3738. return remove();
  3739. }
  3740. callHook(onBeforeLeave, [el]);
  3741. let called = false;
  3742. const done = (el._leaveCb = (cancelled) => {
  3743. if (called)
  3744. return;
  3745. called = true;
  3746. remove();
  3747. if (cancelled) {
  3748. callHook(onLeaveCancelled, [el]);
  3749. }
  3750. else {
  3751. callHook(onAfterLeave, [el]);
  3752. }
  3753. el._leaveCb = undefined;
  3754. if (leavingVNodesCache[key] === vnode) {
  3755. delete leavingVNodesCache[key];
  3756. }
  3757. });
  3758. leavingVNodesCache[key] = vnode;
  3759. if (onLeave) {
  3760. callAsyncHook(onLeave, [el, done]);
  3761. }
  3762. else {
  3763. done();
  3764. }
  3765. },
  3766. clone(vnode) {
  3767. return resolveTransitionHooks(vnode, props, state, instance);
  3768. }
  3769. };
  3770. return hooks;
  3771. }
  3772. // the placeholder really only handles one special case: KeepAlive
  3773. // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
  3774. // placeholder with empty content to avoid the KeepAlive instance from being
  3775. // unmounted.
  3776. function emptyPlaceholder(vnode) {
  3777. if (isKeepAlive(vnode)) {
  3778. vnode = cloneVNode(vnode);
  3779. vnode.children = null;
  3780. return vnode;
  3781. }
  3782. }
  3783. function getKeepAliveChild(vnode) {
  3784. return isKeepAlive(vnode)
  3785. ? vnode.children
  3786. ? vnode.children[0]
  3787. : undefined
  3788. : vnode;
  3789. }
  3790. function setTransitionHooks(vnode, hooks) {
  3791. if (vnode.shapeFlag & 6 /* ShapeFlags.COMPONENT */ && vnode.component) {
  3792. setTransitionHooks(vnode.component.subTree, hooks);
  3793. }
  3794. else if (vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  3795. vnode.ssContent.transition = hooks.clone(vnode.ssContent);
  3796. vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
  3797. }
  3798. else {
  3799. vnode.transition = hooks;
  3800. }
  3801. }
  3802. function getTransitionRawChildren(children, keepComment = false, parentKey) {
  3803. let ret = [];
  3804. let keyedFragmentCount = 0;
  3805. for (let i = 0; i < children.length; i++) {
  3806. let child = children[i];
  3807. // #5360 inherit parent key in case of <template v-for>
  3808. const key = parentKey == null
  3809. ? child.key
  3810. : String(parentKey) + String(child.key != null ? child.key : i);
  3811. // handle fragment children case, e.g. v-for
  3812. if (child.type === Fragment) {
  3813. if (child.patchFlag & 128 /* PatchFlags.KEYED_FRAGMENT */)
  3814. keyedFragmentCount++;
  3815. ret = ret.concat(getTransitionRawChildren(child.children, keepComment, key));
  3816. }
  3817. // comment placeholders should be skipped, e.g. v-if
  3818. else if (keepComment || child.type !== Comment) {
  3819. ret.push(key != null ? cloneVNode(child, { key }) : child);
  3820. }
  3821. }
  3822. // #1126 if a transition children list contains multiple sub fragments, these
  3823. // fragments will be merged into a flat children array. Since each v-for
  3824. // fragment may contain different static bindings inside, we need to de-op
  3825. // these children to force full diffs to ensure correct behavior.
  3826. if (keyedFragmentCount > 1) {
  3827. for (let i = 0; i < ret.length; i++) {
  3828. ret[i].patchFlag = -2 /* PatchFlags.BAIL */;
  3829. }
  3830. }
  3831. return ret;
  3832. }
  3833. // implementation, close to no-op
  3834. function defineComponent(options) {
  3835. return isFunction(options) ? { setup: options, name: options.name } : options;
  3836. }
  3837. const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
  3838. function defineAsyncComponent(source) {
  3839. if (isFunction(source)) {
  3840. source = { loader: source };
  3841. }
  3842. const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
  3843. suspensible = true, onError: userOnError } = source;
  3844. let pendingRequest = null;
  3845. let resolvedComp;
  3846. let retries = 0;
  3847. const retry = () => {
  3848. retries++;
  3849. pendingRequest = null;
  3850. return load();
  3851. };
  3852. const load = () => {
  3853. let thisRequest;
  3854. return (pendingRequest ||
  3855. (thisRequest = pendingRequest =
  3856. loader()
  3857. .catch(err => {
  3858. err = err instanceof Error ? err : new Error(String(err));
  3859. if (userOnError) {
  3860. return new Promise((resolve, reject) => {
  3861. const userRetry = () => resolve(retry());
  3862. const userFail = () => reject(err);
  3863. userOnError(err, userRetry, userFail, retries + 1);
  3864. });
  3865. }
  3866. else {
  3867. throw err;
  3868. }
  3869. })
  3870. .then((comp) => {
  3871. if (thisRequest !== pendingRequest && pendingRequest) {
  3872. return pendingRequest;
  3873. }
  3874. if (!comp) {
  3875. warn(`Async component loader resolved to undefined. ` +
  3876. `If you are using retry(), make sure to return its return value.`);
  3877. }
  3878. // interop module default
  3879. if (comp &&
  3880. (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
  3881. comp = comp.default;
  3882. }
  3883. if (comp && !isObject(comp) && !isFunction(comp)) {
  3884. throw new Error(`Invalid async component load result: ${comp}`);
  3885. }
  3886. resolvedComp = comp;
  3887. return comp;
  3888. })));
  3889. };
  3890. return defineComponent({
  3891. name: 'AsyncComponentWrapper',
  3892. __asyncLoader: load,
  3893. get __asyncResolved() {
  3894. return resolvedComp;
  3895. },
  3896. setup() {
  3897. const instance = currentInstance;
  3898. // already resolved
  3899. if (resolvedComp) {
  3900. return () => createInnerComp(resolvedComp, instance);
  3901. }
  3902. const onError = (err) => {
  3903. pendingRequest = null;
  3904. handleError(err, instance, 13 /* ErrorCodes.ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
  3905. };
  3906. // suspense-controlled or SSR.
  3907. if ((suspensible && instance.suspense) ||
  3908. (false )) {
  3909. return load()
  3910. .then(comp => {
  3911. return () => createInnerComp(comp, instance);
  3912. })
  3913. .catch(err => {
  3914. onError(err);
  3915. return () => errorComponent
  3916. ? createVNode(errorComponent, {
  3917. error: err
  3918. })
  3919. : null;
  3920. });
  3921. }
  3922. const loaded = ref(false);
  3923. const error = ref();
  3924. const delayed = ref(!!delay);
  3925. if (delay) {
  3926. setTimeout(() => {
  3927. delayed.value = false;
  3928. }, delay);
  3929. }
  3930. if (timeout != null) {
  3931. setTimeout(() => {
  3932. if (!loaded.value && !error.value) {
  3933. const err = new Error(`Async component timed out after ${timeout}ms.`);
  3934. onError(err);
  3935. error.value = err;
  3936. }
  3937. }, timeout);
  3938. }
  3939. load()
  3940. .then(() => {
  3941. loaded.value = true;
  3942. if (instance.parent && isKeepAlive(instance.parent.vnode)) {
  3943. // parent is keep-alive, force update so the loaded component's
  3944. // name is taken into account
  3945. queueJob(instance.parent.update);
  3946. }
  3947. })
  3948. .catch(err => {
  3949. onError(err);
  3950. error.value = err;
  3951. });
  3952. return () => {
  3953. if (loaded.value && resolvedComp) {
  3954. return createInnerComp(resolvedComp, instance);
  3955. }
  3956. else if (error.value && errorComponent) {
  3957. return createVNode(errorComponent, {
  3958. error: error.value
  3959. });
  3960. }
  3961. else if (loadingComponent && !delayed.value) {
  3962. return createVNode(loadingComponent);
  3963. }
  3964. };
  3965. }
  3966. });
  3967. }
  3968. function createInnerComp(comp, parent) {
  3969. const { ref, props, children, ce } = parent.vnode;
  3970. const vnode = createVNode(comp, props, children);
  3971. // ensure inner component inherits the async wrapper's ref owner
  3972. vnode.ref = ref;
  3973. // pass the custom element callback on to the inner comp
  3974. // and remove it from the async wrapper
  3975. vnode.ce = ce;
  3976. delete parent.vnode.ce;
  3977. return vnode;
  3978. }
  3979. const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
  3980. const KeepAliveImpl = {
  3981. name: `KeepAlive`,
  3982. // Marker for special handling inside the renderer. We are not using a ===
  3983. // check directly on KeepAlive in the renderer, because importing it directly
  3984. // would prevent it from being tree-shaken.
  3985. __isKeepAlive: true,
  3986. props: {
  3987. include: [String, RegExp, Array],
  3988. exclude: [String, RegExp, Array],
  3989. max: [String, Number]
  3990. },
  3991. setup(props, { slots }) {
  3992. const instance = getCurrentInstance();
  3993. // KeepAlive communicates with the instantiated renderer via the
  3994. // ctx where the renderer passes in its internals,
  3995. // and the KeepAlive instance exposes activate/deactivate implementations.
  3996. // The whole point of this is to avoid importing KeepAlive directly in the
  3997. // renderer to facilitate tree-shaking.
  3998. const sharedContext = instance.ctx;
  3999. const cache = new Map();
  4000. const keys = new Set();
  4001. let current = null;
  4002. {
  4003. instance.__v_cache = cache;
  4004. }
  4005. const parentSuspense = instance.suspense;
  4006. const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
  4007. const storageContainer = createElement('div');
  4008. sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
  4009. const instance = vnode.component;
  4010. move(vnode, container, anchor, 0 /* MoveType.ENTER */, parentSuspense);
  4011. // in case props have changed
  4012. patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
  4013. queuePostRenderEffect(() => {
  4014. instance.isDeactivated = false;
  4015. if (instance.a) {
  4016. invokeArrayFns(instance.a);
  4017. }
  4018. const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
  4019. if (vnodeHook) {
  4020. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  4021. }
  4022. }, parentSuspense);
  4023. {
  4024. // Update components tree
  4025. devtoolsComponentAdded(instance);
  4026. }
  4027. };
  4028. sharedContext.deactivate = (vnode) => {
  4029. const instance = vnode.component;
  4030. move(vnode, storageContainer, null, 1 /* MoveType.LEAVE */, parentSuspense);
  4031. queuePostRenderEffect(() => {
  4032. if (instance.da) {
  4033. invokeArrayFns(instance.da);
  4034. }
  4035. const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
  4036. if (vnodeHook) {
  4037. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  4038. }
  4039. instance.isDeactivated = true;
  4040. }, parentSuspense);
  4041. {
  4042. // Update components tree
  4043. devtoolsComponentAdded(instance);
  4044. }
  4045. };
  4046. function unmount(vnode) {
  4047. // reset the shapeFlag so it can be properly unmounted
  4048. resetShapeFlag(vnode);
  4049. _unmount(vnode, instance, parentSuspense, true);
  4050. }
  4051. function pruneCache(filter) {
  4052. cache.forEach((vnode, key) => {
  4053. const name = getComponentName(vnode.type);
  4054. if (name && (!filter || !filter(name))) {
  4055. pruneCacheEntry(key);
  4056. }
  4057. });
  4058. }
  4059. function pruneCacheEntry(key) {
  4060. const cached = cache.get(key);
  4061. if (!current || !isSameVNodeType(cached, current)) {
  4062. unmount(cached);
  4063. }
  4064. else if (current) {
  4065. // current active instance should no longer be kept-alive.
  4066. // we can't unmount it now but it might be later, so reset its flag now.
  4067. resetShapeFlag(current);
  4068. }
  4069. cache.delete(key);
  4070. keys.delete(key);
  4071. }
  4072. // prune cache on include/exclude prop change
  4073. watch(() => [props.include, props.exclude], ([include, exclude]) => {
  4074. include && pruneCache(name => matches(include, name));
  4075. exclude && pruneCache(name => !matches(exclude, name));
  4076. },
  4077. // prune post-render after `current` has been updated
  4078. { flush: 'post', deep: true });
  4079. // cache sub tree after render
  4080. let pendingCacheKey = null;
  4081. const cacheSubtree = () => {
  4082. // fix #1621, the pendingCacheKey could be 0
  4083. if (pendingCacheKey != null) {
  4084. cache.set(pendingCacheKey, getInnerChild(instance.subTree));
  4085. }
  4086. };
  4087. onMounted(cacheSubtree);
  4088. onUpdated(cacheSubtree);
  4089. onBeforeUnmount(() => {
  4090. cache.forEach(cached => {
  4091. const { subTree, suspense } = instance;
  4092. const vnode = getInnerChild(subTree);
  4093. if (cached.type === vnode.type && cached.key === vnode.key) {
  4094. // current instance will be unmounted as part of keep-alive's unmount
  4095. resetShapeFlag(vnode);
  4096. // but invoke its deactivated hook here
  4097. const da = vnode.component.da;
  4098. da && queuePostRenderEffect(da, suspense);
  4099. return;
  4100. }
  4101. unmount(cached);
  4102. });
  4103. });
  4104. return () => {
  4105. pendingCacheKey = null;
  4106. if (!slots.default) {
  4107. return null;
  4108. }
  4109. const children = slots.default();
  4110. const rawVNode = children[0];
  4111. if (children.length > 1) {
  4112. {
  4113. warn(`KeepAlive should contain exactly one component child.`);
  4114. }
  4115. current = null;
  4116. return children;
  4117. }
  4118. else if (!isVNode(rawVNode) ||
  4119. (!(rawVNode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */) &&
  4120. !(rawVNode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */))) {
  4121. current = null;
  4122. return rawVNode;
  4123. }
  4124. let vnode = getInnerChild(rawVNode);
  4125. const comp = vnode.type;
  4126. // for async components, name check should be based in its loaded
  4127. // inner component if available
  4128. const name = getComponentName(isAsyncWrapper(vnode)
  4129. ? vnode.type.__asyncResolved || {}
  4130. : comp);
  4131. const { include, exclude, max } = props;
  4132. if ((include && (!name || !matches(include, name))) ||
  4133. (exclude && name && matches(exclude, name))) {
  4134. current = vnode;
  4135. return rawVNode;
  4136. }
  4137. const key = vnode.key == null ? comp : vnode.key;
  4138. const cachedVNode = cache.get(key);
  4139. // clone vnode if it's reused because we are going to mutate it
  4140. if (vnode.el) {
  4141. vnode = cloneVNode(vnode);
  4142. if (rawVNode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  4143. rawVNode.ssContent = vnode;
  4144. }
  4145. }
  4146. // #1513 it's possible for the returned vnode to be cloned due to attr
  4147. // fallthrough or scopeId, so the vnode here may not be the final vnode
  4148. // that is mounted. Instead of caching it directly, we store the pending
  4149. // key and cache `instance.subTree` (the normalized vnode) in
  4150. // beforeMount/beforeUpdate hooks.
  4151. pendingCacheKey = key;
  4152. if (cachedVNode) {
  4153. // copy over mounted state
  4154. vnode.el = cachedVNode.el;
  4155. vnode.component = cachedVNode.component;
  4156. if (vnode.transition) {
  4157. // recursively update transition hooks on subTree
  4158. setTransitionHooks(vnode, vnode.transition);
  4159. }
  4160. // avoid vnode being mounted as fresh
  4161. vnode.shapeFlag |= 512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */;
  4162. // make this key the freshest
  4163. keys.delete(key);
  4164. keys.add(key);
  4165. }
  4166. else {
  4167. keys.add(key);
  4168. // prune oldest entry
  4169. if (max && keys.size > parseInt(max, 10)) {
  4170. pruneCacheEntry(keys.values().next().value);
  4171. }
  4172. }
  4173. // avoid vnode being unmounted
  4174. vnode.shapeFlag |= 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */;
  4175. current = vnode;
  4176. return isSuspense(rawVNode.type) ? rawVNode : vnode;
  4177. };
  4178. }
  4179. };
  4180. // export the public type for h/tsx inference
  4181. // also to avoid inline import() in generated d.ts files
  4182. const KeepAlive = KeepAliveImpl;
  4183. function matches(pattern, name) {
  4184. if (isArray(pattern)) {
  4185. return pattern.some((p) => matches(p, name));
  4186. }
  4187. else if (isString(pattern)) {
  4188. return pattern.split(',').includes(name);
  4189. }
  4190. else if (isRegExp(pattern)) {
  4191. return pattern.test(name);
  4192. }
  4193. /* istanbul ignore next */
  4194. return false;
  4195. }
  4196. function onActivated(hook, target) {
  4197. registerKeepAliveHook(hook, "a" /* LifecycleHooks.ACTIVATED */, target);
  4198. }
  4199. function onDeactivated(hook, target) {
  4200. registerKeepAliveHook(hook, "da" /* LifecycleHooks.DEACTIVATED */, target);
  4201. }
  4202. function registerKeepAliveHook(hook, type, target = currentInstance) {
  4203. // cache the deactivate branch check wrapper for injected hooks so the same
  4204. // hook can be properly deduped by the scheduler. "__wdc" stands for "with
  4205. // deactivation check".
  4206. const wrappedHook = hook.__wdc ||
  4207. (hook.__wdc = () => {
  4208. // only fire the hook if the target instance is NOT in a deactivated branch.
  4209. let current = target;
  4210. while (current) {
  4211. if (current.isDeactivated) {
  4212. return;
  4213. }
  4214. current = current.parent;
  4215. }
  4216. return hook();
  4217. });
  4218. injectHook(type, wrappedHook, target);
  4219. // In addition to registering it on the target instance, we walk up the parent
  4220. // chain and register it on all ancestor instances that are keep-alive roots.
  4221. // This avoids the need to walk the entire component tree when invoking these
  4222. // hooks, and more importantly, avoids the need to track child components in
  4223. // arrays.
  4224. if (target) {
  4225. let current = target.parent;
  4226. while (current && current.parent) {
  4227. if (isKeepAlive(current.parent.vnode)) {
  4228. injectToKeepAliveRoot(wrappedHook, type, target, current);
  4229. }
  4230. current = current.parent;
  4231. }
  4232. }
  4233. }
  4234. function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
  4235. // injectHook wraps the original for error handling, so make sure to remove
  4236. // the wrapped version.
  4237. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
  4238. onUnmounted(() => {
  4239. remove(keepAliveRoot[type], injected);
  4240. }, target);
  4241. }
  4242. function resetShapeFlag(vnode) {
  4243. // bitwise operations to remove keep alive flags
  4244. vnode.shapeFlag &= ~256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */;
  4245. vnode.shapeFlag &= ~512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */;
  4246. }
  4247. function getInnerChild(vnode) {
  4248. return vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */ ? vnode.ssContent : vnode;
  4249. }
  4250. function injectHook(type, hook, target = currentInstance, prepend = false) {
  4251. if (target) {
  4252. const hooks = target[type] || (target[type] = []);
  4253. // cache the error handling wrapper for injected hooks so the same hook
  4254. // can be properly deduped by the scheduler. "__weh" stands for "with error
  4255. // handling".
  4256. const wrappedHook = hook.__weh ||
  4257. (hook.__weh = (...args) => {
  4258. if (target.isUnmounted) {
  4259. return;
  4260. }
  4261. // disable tracking inside all lifecycle hooks
  4262. // since they can potentially be called inside effects.
  4263. pauseTracking();
  4264. // Set currentInstance during hook invocation.
  4265. // This assumes the hook does not synchronously trigger other hooks, which
  4266. // can only be false when the user does something really funky.
  4267. setCurrentInstance(target);
  4268. const res = callWithAsyncErrorHandling(hook, target, type, args);
  4269. unsetCurrentInstance();
  4270. resetTracking();
  4271. return res;
  4272. });
  4273. if (prepend) {
  4274. hooks.unshift(wrappedHook);
  4275. }
  4276. else {
  4277. hooks.push(wrappedHook);
  4278. }
  4279. return wrappedHook;
  4280. }
  4281. else {
  4282. const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
  4283. warn(`${apiName} is called when there is no active component instance to be ` +
  4284. `associated with. ` +
  4285. `Lifecycle injection APIs can only be used during execution of setup().` +
  4286. (` If you are using async setup(), make sure to register lifecycle ` +
  4287. `hooks before the first await statement.`
  4288. ));
  4289. }
  4290. }
  4291. const createHook = (lifecycle) => (hook, target = currentInstance) =>
  4292. // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
  4293. (!isInSSRComponentSetup || lifecycle === "sp" /* LifecycleHooks.SERVER_PREFETCH */) &&
  4294. injectHook(lifecycle, (...args) => hook(...args), target);
  4295. const onBeforeMount = createHook("bm" /* LifecycleHooks.BEFORE_MOUNT */);
  4296. const onMounted = createHook("m" /* LifecycleHooks.MOUNTED */);
  4297. const onBeforeUpdate = createHook("bu" /* LifecycleHooks.BEFORE_UPDATE */);
  4298. const onUpdated = createHook("u" /* LifecycleHooks.UPDATED */);
  4299. const onBeforeUnmount = createHook("bum" /* LifecycleHooks.BEFORE_UNMOUNT */);
  4300. const onUnmounted = createHook("um" /* LifecycleHooks.UNMOUNTED */);
  4301. const onServerPrefetch = createHook("sp" /* LifecycleHooks.SERVER_PREFETCH */);
  4302. const onRenderTriggered = createHook("rtg" /* LifecycleHooks.RENDER_TRIGGERED */);
  4303. const onRenderTracked = createHook("rtc" /* LifecycleHooks.RENDER_TRACKED */);
  4304. function onErrorCaptured(hook, target = currentInstance) {
  4305. injectHook("ec" /* LifecycleHooks.ERROR_CAPTURED */, hook, target);
  4306. }
  4307. /**
  4308. Runtime helper for applying directives to a vnode. Example usage:
  4309. const comp = resolveComponent('comp')
  4310. const foo = resolveDirective('foo')
  4311. const bar = resolveDirective('bar')
  4312. return withDirectives(h(comp), [
  4313. [foo, this.x],
  4314. [bar, this.y]
  4315. ])
  4316. */
  4317. function validateDirectiveName(name) {
  4318. if (isBuiltInDirective(name)) {
  4319. warn('Do not use built-in directive ids as custom directive id: ' + name);
  4320. }
  4321. }
  4322. /**
  4323. * Adds directives to a VNode.
  4324. */
  4325. function withDirectives(vnode, directives) {
  4326. const internalInstance = currentRenderingInstance;
  4327. if (internalInstance === null) {
  4328. warn(`withDirectives can only be used inside render functions.`);
  4329. return vnode;
  4330. }
  4331. const instance = getExposeProxy(internalInstance) ||
  4332. internalInstance.proxy;
  4333. const bindings = vnode.dirs || (vnode.dirs = []);
  4334. for (let i = 0; i < directives.length; i++) {
  4335. let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
  4336. if (dir) {
  4337. if (isFunction(dir)) {
  4338. dir = {
  4339. mounted: dir,
  4340. updated: dir
  4341. };
  4342. }
  4343. if (dir.deep) {
  4344. traverse(value);
  4345. }
  4346. bindings.push({
  4347. dir,
  4348. instance,
  4349. value,
  4350. oldValue: void 0,
  4351. arg,
  4352. modifiers
  4353. });
  4354. }
  4355. }
  4356. return vnode;
  4357. }
  4358. function invokeDirectiveHook(vnode, prevVNode, instance, name) {
  4359. const bindings = vnode.dirs;
  4360. const oldBindings = prevVNode && prevVNode.dirs;
  4361. for (let i = 0; i < bindings.length; i++) {
  4362. const binding = bindings[i];
  4363. if (oldBindings) {
  4364. binding.oldValue = oldBindings[i].value;
  4365. }
  4366. let hook = binding.dir[name];
  4367. if (hook) {
  4368. // disable tracking inside all lifecycle hooks
  4369. // since they can potentially be called inside effects.
  4370. pauseTracking();
  4371. callWithAsyncErrorHandling(hook, instance, 8 /* ErrorCodes.DIRECTIVE_HOOK */, [
  4372. vnode.el,
  4373. binding,
  4374. vnode,
  4375. prevVNode
  4376. ]);
  4377. resetTracking();
  4378. }
  4379. }
  4380. }
  4381. const COMPONENTS = 'components';
  4382. const DIRECTIVES = 'directives';
  4383. /**
  4384. * @private
  4385. */
  4386. function resolveComponent(name, maybeSelfReference) {
  4387. return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
  4388. }
  4389. const NULL_DYNAMIC_COMPONENT = Symbol();
  4390. /**
  4391. * @private
  4392. */
  4393. function resolveDynamicComponent(component) {
  4394. if (isString(component)) {
  4395. return resolveAsset(COMPONENTS, component, false) || component;
  4396. }
  4397. else {
  4398. // invalid types will fallthrough to createVNode and raise warning
  4399. return (component || NULL_DYNAMIC_COMPONENT);
  4400. }
  4401. }
  4402. /**
  4403. * @private
  4404. */
  4405. function resolveDirective(name) {
  4406. return resolveAsset(DIRECTIVES, name);
  4407. }
  4408. // implementation
  4409. function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
  4410. const instance = currentRenderingInstance || currentInstance;
  4411. if (instance) {
  4412. const Component = instance.type;
  4413. // explicit self name has highest priority
  4414. if (type === COMPONENTS) {
  4415. const selfName = getComponentName(Component, false /* do not include inferred name to avoid breaking existing code */);
  4416. if (selfName &&
  4417. (selfName === name ||
  4418. selfName === camelize(name) ||
  4419. selfName === capitalize(camelize(name)))) {
  4420. return Component;
  4421. }
  4422. }
  4423. const res =
  4424. // local registration
  4425. // check instance[type] first which is resolved for options API
  4426. resolve(instance[type] || Component[type], name) ||
  4427. // global registration
  4428. resolve(instance.appContext[type], name);
  4429. if (!res && maybeSelfReference) {
  4430. // fallback to implicit self-reference
  4431. return Component;
  4432. }
  4433. if (warnMissing && !res) {
  4434. const extra = type === COMPONENTS
  4435. ? `\nIf this is a native custom element, make sure to exclude it from ` +
  4436. `component resolution via compilerOptions.isCustomElement.`
  4437. : ``;
  4438. warn(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
  4439. }
  4440. return res;
  4441. }
  4442. else {
  4443. warn(`resolve${capitalize(type.slice(0, -1))} ` +
  4444. `can only be used in render() or setup().`);
  4445. }
  4446. }
  4447. function resolve(registry, name) {
  4448. return (registry &&
  4449. (registry[name] ||
  4450. registry[camelize(name)] ||
  4451. registry[capitalize(camelize(name))]));
  4452. }
  4453. /**
  4454. * Actual implementation
  4455. */
  4456. function renderList(source, renderItem, cache, index) {
  4457. let ret;
  4458. const cached = (cache && cache[index]);
  4459. if (isArray(source) || isString(source)) {
  4460. ret = new Array(source.length);
  4461. for (let i = 0, l = source.length; i < l; i++) {
  4462. ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
  4463. }
  4464. }
  4465. else if (typeof source === 'number') {
  4466. if (!Number.isInteger(source)) {
  4467. warn(`The v-for range expect an integer value but got ${source}.`);
  4468. }
  4469. ret = new Array(source);
  4470. for (let i = 0; i < source; i++) {
  4471. ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
  4472. }
  4473. }
  4474. else if (isObject(source)) {
  4475. if (source[Symbol.iterator]) {
  4476. ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
  4477. }
  4478. else {
  4479. const keys = Object.keys(source);
  4480. ret = new Array(keys.length);
  4481. for (let i = 0, l = keys.length; i < l; i++) {
  4482. const key = keys[i];
  4483. ret[i] = renderItem(source[key], key, i, cached && cached[i]);
  4484. }
  4485. }
  4486. }
  4487. else {
  4488. ret = [];
  4489. }
  4490. if (cache) {
  4491. cache[index] = ret;
  4492. }
  4493. return ret;
  4494. }
  4495. /**
  4496. * Compiler runtime helper for creating dynamic slots object
  4497. * @private
  4498. */
  4499. function createSlots(slots, dynamicSlots) {
  4500. for (let i = 0; i < dynamicSlots.length; i++) {
  4501. const slot = dynamicSlots[i];
  4502. // array of dynamic slot generated by <template v-for="..." #[...]>
  4503. if (isArray(slot)) {
  4504. for (let j = 0; j < slot.length; j++) {
  4505. slots[slot[j].name] = slot[j].fn;
  4506. }
  4507. }
  4508. else if (slot) {
  4509. // conditional single slot generated by <template v-if="..." #foo>
  4510. slots[slot.name] = slot.key
  4511. ? (...args) => {
  4512. const res = slot.fn(...args);
  4513. // attach branch key so each conditional branch is considered a
  4514. // different fragment
  4515. if (res)
  4516. res.key = slot.key;
  4517. return res;
  4518. }
  4519. : slot.fn;
  4520. }
  4521. }
  4522. return slots;
  4523. }
  4524. /**
  4525. * Compiler runtime helper for rendering `<slot/>`
  4526. * @private
  4527. */
  4528. function renderSlot(slots, name, props = {},
  4529. // this is not a user-facing function, so the fallback is always generated by
  4530. // the compiler and guaranteed to be a function returning an array
  4531. fallback, noSlotted) {
  4532. if (currentRenderingInstance.isCE ||
  4533. (currentRenderingInstance.parent &&
  4534. isAsyncWrapper(currentRenderingInstance.parent) &&
  4535. currentRenderingInstance.parent.isCE)) {
  4536. if (name !== 'default')
  4537. props.name = name;
  4538. return createVNode('slot', props, fallback && fallback());
  4539. }
  4540. let slot = slots[name];
  4541. if (slot && slot.length > 1) {
  4542. warn(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
  4543. `function. You need to mark this component with $dynamic-slots in the ` +
  4544. `parent template.`);
  4545. slot = () => [];
  4546. }
  4547. // a compiled slot disables block tracking by default to avoid manual
  4548. // invocation interfering with template-based block tracking, but in
  4549. // `renderSlot` we can be sure that it's template-based so we can force
  4550. // enable it.
  4551. if (slot && slot._c) {
  4552. slot._d = false;
  4553. }
  4554. openBlock();
  4555. const validSlotContent = slot && ensureValidVNode(slot(props));
  4556. const rendered = createBlock(Fragment, {
  4557. key: props.key ||
  4558. // slot content array of a dynamic conditional slot may have a branch
  4559. // key attached in the `createSlots` helper, respect that
  4560. (validSlotContent && validSlotContent.key) ||
  4561. `_${name}`
  4562. }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* SlotFlags.STABLE */
  4563. ? 64 /* PatchFlags.STABLE_FRAGMENT */
  4564. : -2 /* PatchFlags.BAIL */);
  4565. if (!noSlotted && rendered.scopeId) {
  4566. rendered.slotScopeIds = [rendered.scopeId + '-s'];
  4567. }
  4568. if (slot && slot._c) {
  4569. slot._d = true;
  4570. }
  4571. return rendered;
  4572. }
  4573. function ensureValidVNode(vnodes) {
  4574. return vnodes.some(child => {
  4575. if (!isVNode(child))
  4576. return true;
  4577. if (child.type === Comment)
  4578. return false;
  4579. if (child.type === Fragment &&
  4580. !ensureValidVNode(child.children))
  4581. return false;
  4582. return true;
  4583. })
  4584. ? vnodes
  4585. : null;
  4586. }
  4587. /**
  4588. * For prefixing keys in v-on="obj" with "on"
  4589. * @private
  4590. */
  4591. function toHandlers(obj, preserveCaseIfNecessary) {
  4592. const ret = {};
  4593. if (!isObject(obj)) {
  4594. warn(`v-on with no argument expects an object value.`);
  4595. return ret;
  4596. }
  4597. for (const key in obj) {
  4598. ret[preserveCaseIfNecessary && /[A-Z]/.test(key)
  4599. ? `on:${key}`
  4600. : toHandlerKey(key)] = obj[key];
  4601. }
  4602. return ret;
  4603. }
  4604. /**
  4605. * #2437 In Vue 3, functional components do not have a public instance proxy but
  4606. * they exist in the internal parent chain. For code that relies on traversing
  4607. * public $parent chains, skip functional ones and go to the parent instead.
  4608. */
  4609. const getPublicInstance = (i) => {
  4610. if (!i)
  4611. return null;
  4612. if (isStatefulComponent(i))
  4613. return getExposeProxy(i) || i.proxy;
  4614. return getPublicInstance(i.parent);
  4615. };
  4616. const publicPropertiesMap =
  4617. // Move PURE marker to new line to workaround compiler discarding it
  4618. // due to type annotation
  4619. /*#__PURE__*/ extend(Object.create(null), {
  4620. $: i => i,
  4621. $el: i => i.vnode.el,
  4622. $data: i => i.data,
  4623. $props: i => (shallowReadonly(i.props) ),
  4624. $attrs: i => (shallowReadonly(i.attrs) ),
  4625. $slots: i => (shallowReadonly(i.slots) ),
  4626. $refs: i => (shallowReadonly(i.refs) ),
  4627. $parent: i => getPublicInstance(i.parent),
  4628. $root: i => getPublicInstance(i.root),
  4629. $emit: i => i.emit,
  4630. $options: i => (resolveMergedOptions(i) ),
  4631. $forceUpdate: i => i.f || (i.f = () => queueJob(i.update)),
  4632. $nextTick: i => i.n || (i.n = nextTick.bind(i.proxy)),
  4633. $watch: i => (instanceWatch.bind(i) )
  4634. });
  4635. const isReservedPrefix = (key) => key === '_' || key === '$';
  4636. const hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key);
  4637. const PublicInstanceProxyHandlers = {
  4638. get({ _: instance }, key) {
  4639. const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
  4640. // for internal formatters to know that this is a Vue instance
  4641. if (key === '__isVue') {
  4642. return true;
  4643. }
  4644. // data / props / ctx
  4645. // This getter gets called for every property access on the render context
  4646. // during render and is a major hotspot. The most expensive part of this
  4647. // is the multiple hasOwn() calls. It's much faster to do a simple property
  4648. // access on a plain object, so we use an accessCache object (with null
  4649. // prototype) to memoize what access type a key corresponds to.
  4650. let normalizedProps;
  4651. if (key[0] !== '$') {
  4652. const n = accessCache[key];
  4653. if (n !== undefined) {
  4654. switch (n) {
  4655. case 1 /* AccessTypes.SETUP */:
  4656. return setupState[key];
  4657. case 2 /* AccessTypes.DATA */:
  4658. return data[key];
  4659. case 4 /* AccessTypes.CONTEXT */:
  4660. return ctx[key];
  4661. case 3 /* AccessTypes.PROPS */:
  4662. return props[key];
  4663. // default: just fallthrough
  4664. }
  4665. }
  4666. else if (hasSetupBinding(setupState, key)) {
  4667. accessCache[key] = 1 /* AccessTypes.SETUP */;
  4668. return setupState[key];
  4669. }
  4670. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  4671. accessCache[key] = 2 /* AccessTypes.DATA */;
  4672. return data[key];
  4673. }
  4674. else if (
  4675. // only cache other properties when instance has declared (thus stable)
  4676. // props
  4677. (normalizedProps = instance.propsOptions[0]) &&
  4678. hasOwn(normalizedProps, key)) {
  4679. accessCache[key] = 3 /* AccessTypes.PROPS */;
  4680. return props[key];
  4681. }
  4682. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  4683. accessCache[key] = 4 /* AccessTypes.CONTEXT */;
  4684. return ctx[key];
  4685. }
  4686. else if (shouldCacheAccess) {
  4687. accessCache[key] = 0 /* AccessTypes.OTHER */;
  4688. }
  4689. }
  4690. const publicGetter = publicPropertiesMap[key];
  4691. let cssModule, globalProperties;
  4692. // public $xxx properties
  4693. if (publicGetter) {
  4694. if (key === '$attrs') {
  4695. track(instance, "get" /* TrackOpTypes.GET */, key);
  4696. markAttrsAccessed();
  4697. }
  4698. return publicGetter(instance);
  4699. }
  4700. else if (
  4701. // css module (injected by vue-loader)
  4702. (cssModule = type.__cssModules) &&
  4703. (cssModule = cssModule[key])) {
  4704. return cssModule;
  4705. }
  4706. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  4707. // user may set custom properties to `this` that start with `$`
  4708. accessCache[key] = 4 /* AccessTypes.CONTEXT */;
  4709. return ctx[key];
  4710. }
  4711. else if (
  4712. // global properties
  4713. ((globalProperties = appContext.config.globalProperties),
  4714. hasOwn(globalProperties, key))) {
  4715. {
  4716. return globalProperties[key];
  4717. }
  4718. }
  4719. else if (currentRenderingInstance &&
  4720. (!isString(key) ||
  4721. // #1091 avoid internal isRef/isVNode checks on component instance leading
  4722. // to infinite warning loop
  4723. key.indexOf('__v') !== 0)) {
  4724. if (data !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn(data, key)) {
  4725. warn(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
  4726. `character ("$" or "_") and is not proxied on the render context.`);
  4727. }
  4728. else if (instance === currentRenderingInstance) {
  4729. warn(`Property ${JSON.stringify(key)} was accessed during render ` +
  4730. `but is not defined on instance.`);
  4731. }
  4732. }
  4733. },
  4734. set({ _: instance }, key, value) {
  4735. const { data, setupState, ctx } = instance;
  4736. if (hasSetupBinding(setupState, key)) {
  4737. setupState[key] = value;
  4738. return true;
  4739. }
  4740. else if (setupState.__isScriptSetup &&
  4741. hasOwn(setupState, key)) {
  4742. warn(`Cannot mutate <script setup> binding "${key}" from Options API.`);
  4743. return false;
  4744. }
  4745. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  4746. data[key] = value;
  4747. return true;
  4748. }
  4749. else if (hasOwn(instance.props, key)) {
  4750. warn(`Attempting to mutate prop "${key}". Props are readonly.`);
  4751. return false;
  4752. }
  4753. if (key[0] === '$' && key.slice(1) in instance) {
  4754. warn(`Attempting to mutate public property "${key}". ` +
  4755. `Properties starting with $ are reserved and readonly.`);
  4756. return false;
  4757. }
  4758. else {
  4759. if (key in instance.appContext.config.globalProperties) {
  4760. Object.defineProperty(ctx, key, {
  4761. enumerable: true,
  4762. configurable: true,
  4763. value
  4764. });
  4765. }
  4766. else {
  4767. ctx[key] = value;
  4768. }
  4769. }
  4770. return true;
  4771. },
  4772. has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
  4773. let normalizedProps;
  4774. return (!!accessCache[key] ||
  4775. (data !== EMPTY_OBJ && hasOwn(data, key)) ||
  4776. hasSetupBinding(setupState, key) ||
  4777. ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
  4778. hasOwn(ctx, key) ||
  4779. hasOwn(publicPropertiesMap, key) ||
  4780. hasOwn(appContext.config.globalProperties, key));
  4781. },
  4782. defineProperty(target, key, descriptor) {
  4783. if (descriptor.get != null) {
  4784. // invalidate key cache of a getter based property #5417
  4785. target._.accessCache[key] = 0;
  4786. }
  4787. else if (hasOwn(descriptor, 'value')) {
  4788. this.set(target, key, descriptor.value, null);
  4789. }
  4790. return Reflect.defineProperty(target, key, descriptor);
  4791. }
  4792. };
  4793. {
  4794. PublicInstanceProxyHandlers.ownKeys = (target) => {
  4795. warn(`Avoid app logic that relies on enumerating keys on a component instance. ` +
  4796. `The keys will be empty in production mode to avoid performance overhead.`);
  4797. return Reflect.ownKeys(target);
  4798. };
  4799. }
  4800. const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
  4801. get(target, key) {
  4802. // fast path for unscopables when using `with` block
  4803. if (key === Symbol.unscopables) {
  4804. return;
  4805. }
  4806. return PublicInstanceProxyHandlers.get(target, key, target);
  4807. },
  4808. has(_, key) {
  4809. const has = key[0] !== '_' && !isGloballyWhitelisted(key);
  4810. if (!has && PublicInstanceProxyHandlers.has(_, key)) {
  4811. warn(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
  4812. }
  4813. return has;
  4814. }
  4815. });
  4816. // dev only
  4817. // In dev mode, the proxy target exposes the same properties as seen on `this`
  4818. // for easier console inspection. In prod mode it will be an empty object so
  4819. // these properties definitions can be skipped.
  4820. function createDevRenderContext(instance) {
  4821. const target = {};
  4822. // expose internal instance for proxy handlers
  4823. Object.defineProperty(target, `_`, {
  4824. configurable: true,
  4825. enumerable: false,
  4826. get: () => instance
  4827. });
  4828. // expose public properties
  4829. Object.keys(publicPropertiesMap).forEach(key => {
  4830. Object.defineProperty(target, key, {
  4831. configurable: true,
  4832. enumerable: false,
  4833. get: () => publicPropertiesMap[key](instance),
  4834. // intercepted by the proxy so no need for implementation,
  4835. // but needed to prevent set errors
  4836. set: NOOP
  4837. });
  4838. });
  4839. return target;
  4840. }
  4841. // dev only
  4842. function exposePropsOnRenderContext(instance) {
  4843. const { ctx, propsOptions: [propsOptions] } = instance;
  4844. if (propsOptions) {
  4845. Object.keys(propsOptions).forEach(key => {
  4846. Object.defineProperty(ctx, key, {
  4847. enumerable: true,
  4848. configurable: true,
  4849. get: () => instance.props[key],
  4850. set: NOOP
  4851. });
  4852. });
  4853. }
  4854. }
  4855. // dev only
  4856. function exposeSetupStateOnRenderContext(instance) {
  4857. const { ctx, setupState } = instance;
  4858. Object.keys(toRaw(setupState)).forEach(key => {
  4859. if (!setupState.__isScriptSetup) {
  4860. if (isReservedPrefix(key[0])) {
  4861. warn(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
  4862. `which are reserved prefixes for Vue internals.`);
  4863. return;
  4864. }
  4865. Object.defineProperty(ctx, key, {
  4866. enumerable: true,
  4867. configurable: true,
  4868. get: () => setupState[key],
  4869. set: NOOP
  4870. });
  4871. }
  4872. });
  4873. }
  4874. function createDuplicateChecker() {
  4875. const cache = Object.create(null);
  4876. return (type, key) => {
  4877. if (cache[key]) {
  4878. warn(`${type} property "${key}" is already defined in ${cache[key]}.`);
  4879. }
  4880. else {
  4881. cache[key] = type;
  4882. }
  4883. };
  4884. }
  4885. let shouldCacheAccess = true;
  4886. function applyOptions(instance) {
  4887. const options = resolveMergedOptions(instance);
  4888. const publicThis = instance.proxy;
  4889. const ctx = instance.ctx;
  4890. // do not cache property access on public proxy during state initialization
  4891. shouldCacheAccess = false;
  4892. // call beforeCreate first before accessing other options since
  4893. // the hook may mutate resolved options (#2791)
  4894. if (options.beforeCreate) {
  4895. callHook$1(options.beforeCreate, instance, "bc" /* LifecycleHooks.BEFORE_CREATE */);
  4896. }
  4897. const {
  4898. // state
  4899. data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
  4900. // lifecycle
  4901. created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
  4902. // public API
  4903. expose, inheritAttrs,
  4904. // assets
  4905. components, directives, filters } = options;
  4906. const checkDuplicateProperties = createDuplicateChecker() ;
  4907. {
  4908. const [propsOptions] = instance.propsOptions;
  4909. if (propsOptions) {
  4910. for (const key in propsOptions) {
  4911. checkDuplicateProperties("Props" /* OptionTypes.PROPS */, key);
  4912. }
  4913. }
  4914. }
  4915. // options initialization order (to be consistent with Vue 2):
  4916. // - props (already done outside of this function)
  4917. // - inject
  4918. // - methods
  4919. // - data (deferred since it relies on `this` access)
  4920. // - computed
  4921. // - watch (deferred since it relies on `this` access)
  4922. if (injectOptions) {
  4923. resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
  4924. }
  4925. if (methods) {
  4926. for (const key in methods) {
  4927. const methodHandler = methods[key];
  4928. if (isFunction(methodHandler)) {
  4929. // In dev mode, we use the `createRenderContext` function to define
  4930. // methods to the proxy target, and those are read-only but
  4931. // reconfigurable, so it needs to be redefined here
  4932. {
  4933. Object.defineProperty(ctx, key, {
  4934. value: methodHandler.bind(publicThis),
  4935. configurable: true,
  4936. enumerable: true,
  4937. writable: true
  4938. });
  4939. }
  4940. {
  4941. checkDuplicateProperties("Methods" /* OptionTypes.METHODS */, key);
  4942. }
  4943. }
  4944. else {
  4945. warn(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
  4946. `Did you reference the function correctly?`);
  4947. }
  4948. }
  4949. }
  4950. if (dataOptions) {
  4951. if (!isFunction(dataOptions)) {
  4952. warn(`The data option must be a function. ` +
  4953. `Plain object usage is no longer supported.`);
  4954. }
  4955. const data = dataOptions.call(publicThis, publicThis);
  4956. if (isPromise(data)) {
  4957. warn(`data() returned a Promise - note data() cannot be async; If you ` +
  4958. `intend to perform data fetching before component renders, use ` +
  4959. `async setup() + <Suspense>.`);
  4960. }
  4961. if (!isObject(data)) {
  4962. warn(`data() should return an object.`);
  4963. }
  4964. else {
  4965. instance.data = reactive(data);
  4966. {
  4967. for (const key in data) {
  4968. checkDuplicateProperties("Data" /* OptionTypes.DATA */, key);
  4969. // expose data on ctx during dev
  4970. if (!isReservedPrefix(key[0])) {
  4971. Object.defineProperty(ctx, key, {
  4972. configurable: true,
  4973. enumerable: true,
  4974. get: () => data[key],
  4975. set: NOOP
  4976. });
  4977. }
  4978. }
  4979. }
  4980. }
  4981. }
  4982. // state initialization complete at this point - start caching access
  4983. shouldCacheAccess = true;
  4984. if (computedOptions) {
  4985. for (const key in computedOptions) {
  4986. const opt = computedOptions[key];
  4987. const get = isFunction(opt)
  4988. ? opt.bind(publicThis, publicThis)
  4989. : isFunction(opt.get)
  4990. ? opt.get.bind(publicThis, publicThis)
  4991. : NOOP;
  4992. if (get === NOOP) {
  4993. warn(`Computed property "${key}" has no getter.`);
  4994. }
  4995. const set = !isFunction(opt) && isFunction(opt.set)
  4996. ? opt.set.bind(publicThis)
  4997. : () => {
  4998. warn(`Write operation failed: computed property "${key}" is readonly.`);
  4999. }
  5000. ;
  5001. const c = computed({
  5002. get,
  5003. set
  5004. });
  5005. Object.defineProperty(ctx, key, {
  5006. enumerable: true,
  5007. configurable: true,
  5008. get: () => c.value,
  5009. set: v => (c.value = v)
  5010. });
  5011. {
  5012. checkDuplicateProperties("Computed" /* OptionTypes.COMPUTED */, key);
  5013. }
  5014. }
  5015. }
  5016. if (watchOptions) {
  5017. for (const key in watchOptions) {
  5018. createWatcher(watchOptions[key], ctx, publicThis, key);
  5019. }
  5020. }
  5021. if (provideOptions) {
  5022. const provides = isFunction(provideOptions)
  5023. ? provideOptions.call(publicThis)
  5024. : provideOptions;
  5025. Reflect.ownKeys(provides).forEach(key => {
  5026. provide(key, provides[key]);
  5027. });
  5028. }
  5029. if (created) {
  5030. callHook$1(created, instance, "c" /* LifecycleHooks.CREATED */);
  5031. }
  5032. function registerLifecycleHook(register, hook) {
  5033. if (isArray(hook)) {
  5034. hook.forEach(_hook => register(_hook.bind(publicThis)));
  5035. }
  5036. else if (hook) {
  5037. register(hook.bind(publicThis));
  5038. }
  5039. }
  5040. registerLifecycleHook(onBeforeMount, beforeMount);
  5041. registerLifecycleHook(onMounted, mounted);
  5042. registerLifecycleHook(onBeforeUpdate, beforeUpdate);
  5043. registerLifecycleHook(onUpdated, updated);
  5044. registerLifecycleHook(onActivated, activated);
  5045. registerLifecycleHook(onDeactivated, deactivated);
  5046. registerLifecycleHook(onErrorCaptured, errorCaptured);
  5047. registerLifecycleHook(onRenderTracked, renderTracked);
  5048. registerLifecycleHook(onRenderTriggered, renderTriggered);
  5049. registerLifecycleHook(onBeforeUnmount, beforeUnmount);
  5050. registerLifecycleHook(onUnmounted, unmounted);
  5051. registerLifecycleHook(onServerPrefetch, serverPrefetch);
  5052. if (isArray(expose)) {
  5053. if (expose.length) {
  5054. const exposed = instance.exposed || (instance.exposed = {});
  5055. expose.forEach(key => {
  5056. Object.defineProperty(exposed, key, {
  5057. get: () => publicThis[key],
  5058. set: val => (publicThis[key] = val)
  5059. });
  5060. });
  5061. }
  5062. else if (!instance.exposed) {
  5063. instance.exposed = {};
  5064. }
  5065. }
  5066. // options that are handled when creating the instance but also need to be
  5067. // applied from mixins
  5068. if (render && instance.render === NOOP) {
  5069. instance.render = render;
  5070. }
  5071. if (inheritAttrs != null) {
  5072. instance.inheritAttrs = inheritAttrs;
  5073. }
  5074. // asset options.
  5075. if (components)
  5076. instance.components = components;
  5077. if (directives)
  5078. instance.directives = directives;
  5079. }
  5080. function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
  5081. if (isArray(injectOptions)) {
  5082. injectOptions = normalizeInject(injectOptions);
  5083. }
  5084. for (const key in injectOptions) {
  5085. const opt = injectOptions[key];
  5086. let injected;
  5087. if (isObject(opt)) {
  5088. if ('default' in opt) {
  5089. injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
  5090. }
  5091. else {
  5092. injected = inject(opt.from || key);
  5093. }
  5094. }
  5095. else {
  5096. injected = inject(opt);
  5097. }
  5098. if (isRef(injected)) {
  5099. // TODO remove the check in 3.3
  5100. if (unwrapRef) {
  5101. Object.defineProperty(ctx, key, {
  5102. enumerable: true,
  5103. configurable: true,
  5104. get: () => injected.value,
  5105. set: v => (injected.value = v)
  5106. });
  5107. }
  5108. else {
  5109. {
  5110. warn(`injected property "${key}" is a ref and will be auto-unwrapped ` +
  5111. `and no longer needs \`.value\` in the next minor release. ` +
  5112. `To opt-in to the new behavior now, ` +
  5113. `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
  5114. `temporary and will not be needed in the future.)`);
  5115. }
  5116. ctx[key] = injected;
  5117. }
  5118. }
  5119. else {
  5120. ctx[key] = injected;
  5121. }
  5122. {
  5123. checkDuplicateProperties("Inject" /* OptionTypes.INJECT */, key);
  5124. }
  5125. }
  5126. }
  5127. function callHook$1(hook, instance, type) {
  5128. callWithAsyncErrorHandling(isArray(hook)
  5129. ? hook.map(h => h.bind(instance.proxy))
  5130. : hook.bind(instance.proxy), instance, type);
  5131. }
  5132. function createWatcher(raw, ctx, publicThis, key) {
  5133. const getter = key.includes('.')
  5134. ? createPathGetter(publicThis, key)
  5135. : () => publicThis[key];
  5136. if (isString(raw)) {
  5137. const handler = ctx[raw];
  5138. if (isFunction(handler)) {
  5139. watch(getter, handler);
  5140. }
  5141. else {
  5142. warn(`Invalid watch handler specified by key "${raw}"`, handler);
  5143. }
  5144. }
  5145. else if (isFunction(raw)) {
  5146. watch(getter, raw.bind(publicThis));
  5147. }
  5148. else if (isObject(raw)) {
  5149. if (isArray(raw)) {
  5150. raw.forEach(r => createWatcher(r, ctx, publicThis, key));
  5151. }
  5152. else {
  5153. const handler = isFunction(raw.handler)
  5154. ? raw.handler.bind(publicThis)
  5155. : ctx[raw.handler];
  5156. if (isFunction(handler)) {
  5157. watch(getter, handler, raw);
  5158. }
  5159. else {
  5160. warn(`Invalid watch handler specified by key "${raw.handler}"`, handler);
  5161. }
  5162. }
  5163. }
  5164. else {
  5165. warn(`Invalid watch option: "${key}"`, raw);
  5166. }
  5167. }
  5168. /**
  5169. * Resolve merged options and cache it on the component.
  5170. * This is done only once per-component since the merging does not involve
  5171. * instances.
  5172. */
  5173. function resolveMergedOptions(instance) {
  5174. const base = instance.type;
  5175. const { mixins, extends: extendsOptions } = base;
  5176. const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
  5177. const cached = cache.get(base);
  5178. let resolved;
  5179. if (cached) {
  5180. resolved = cached;
  5181. }
  5182. else if (!globalMixins.length && !mixins && !extendsOptions) {
  5183. {
  5184. resolved = base;
  5185. }
  5186. }
  5187. else {
  5188. resolved = {};
  5189. if (globalMixins.length) {
  5190. globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
  5191. }
  5192. mergeOptions(resolved, base, optionMergeStrategies);
  5193. }
  5194. if (isObject(base)) {
  5195. cache.set(base, resolved);
  5196. }
  5197. return resolved;
  5198. }
  5199. function mergeOptions(to, from, strats, asMixin = false) {
  5200. const { mixins, extends: extendsOptions } = from;
  5201. if (extendsOptions) {
  5202. mergeOptions(to, extendsOptions, strats, true);
  5203. }
  5204. if (mixins) {
  5205. mixins.forEach((m) => mergeOptions(to, m, strats, true));
  5206. }
  5207. for (const key in from) {
  5208. if (asMixin && key === 'expose') {
  5209. warn(`"expose" option is ignored when declared in mixins or extends. ` +
  5210. `It should only be declared in the base component itself.`);
  5211. }
  5212. else {
  5213. const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
  5214. to[key] = strat ? strat(to[key], from[key]) : from[key];
  5215. }
  5216. }
  5217. return to;
  5218. }
  5219. const internalOptionMergeStrats = {
  5220. data: mergeDataFn,
  5221. props: mergeObjectOptions,
  5222. emits: mergeObjectOptions,
  5223. // objects
  5224. methods: mergeObjectOptions,
  5225. computed: mergeObjectOptions,
  5226. // lifecycle
  5227. beforeCreate: mergeAsArray$1,
  5228. created: mergeAsArray$1,
  5229. beforeMount: mergeAsArray$1,
  5230. mounted: mergeAsArray$1,
  5231. beforeUpdate: mergeAsArray$1,
  5232. updated: mergeAsArray$1,
  5233. beforeDestroy: mergeAsArray$1,
  5234. beforeUnmount: mergeAsArray$1,
  5235. destroyed: mergeAsArray$1,
  5236. unmounted: mergeAsArray$1,
  5237. activated: mergeAsArray$1,
  5238. deactivated: mergeAsArray$1,
  5239. errorCaptured: mergeAsArray$1,
  5240. serverPrefetch: mergeAsArray$1,
  5241. // assets
  5242. components: mergeObjectOptions,
  5243. directives: mergeObjectOptions,
  5244. // watch
  5245. watch: mergeWatchOptions,
  5246. // provide / inject
  5247. provide: mergeDataFn,
  5248. inject: mergeInject
  5249. };
  5250. function mergeDataFn(to, from) {
  5251. if (!from) {
  5252. return to;
  5253. }
  5254. if (!to) {
  5255. return from;
  5256. }
  5257. return function mergedDataFn() {
  5258. return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
  5259. };
  5260. }
  5261. function mergeInject(to, from) {
  5262. return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
  5263. }
  5264. function normalizeInject(raw) {
  5265. if (isArray(raw)) {
  5266. const res = {};
  5267. for (let i = 0; i < raw.length; i++) {
  5268. res[raw[i]] = raw[i];
  5269. }
  5270. return res;
  5271. }
  5272. return raw;
  5273. }
  5274. function mergeAsArray$1(to, from) {
  5275. return to ? [...new Set([].concat(to, from))] : from;
  5276. }
  5277. function mergeObjectOptions(to, from) {
  5278. return to ? extend(extend(Object.create(null), to), from) : from;
  5279. }
  5280. function mergeWatchOptions(to, from) {
  5281. if (!to)
  5282. return from;
  5283. if (!from)
  5284. return to;
  5285. const merged = extend(Object.create(null), to);
  5286. for (const key in from) {
  5287. merged[key] = mergeAsArray$1(to[key], from[key]);
  5288. }
  5289. return merged;
  5290. }
  5291. function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
  5292. isSSR = false) {
  5293. const props = {};
  5294. const attrs = {};
  5295. def(attrs, InternalObjectKey, 1);
  5296. instance.propsDefaults = Object.create(null);
  5297. setFullProps(instance, rawProps, props, attrs);
  5298. // ensure all declared prop keys are present
  5299. for (const key in instance.propsOptions[0]) {
  5300. if (!(key in props)) {
  5301. props[key] = undefined;
  5302. }
  5303. }
  5304. // validation
  5305. {
  5306. validateProps(rawProps || {}, props, instance);
  5307. }
  5308. if (isStateful) {
  5309. // stateful
  5310. instance.props = isSSR ? props : shallowReactive(props);
  5311. }
  5312. else {
  5313. if (!instance.type.props) {
  5314. // functional w/ optional props, props === attrs
  5315. instance.props = attrs;
  5316. }
  5317. else {
  5318. // functional w/ declared props
  5319. instance.props = props;
  5320. }
  5321. }
  5322. instance.attrs = attrs;
  5323. }
  5324. function isInHmrContext(instance) {
  5325. while (instance) {
  5326. if (instance.type.__hmrId)
  5327. return true;
  5328. instance = instance.parent;
  5329. }
  5330. }
  5331. function updateProps(instance, rawProps, rawPrevProps, optimized) {
  5332. const { props, attrs, vnode: { patchFlag } } = instance;
  5333. const rawCurrentProps = toRaw(props);
  5334. const [options] = instance.propsOptions;
  5335. let hasAttrsChanged = false;
  5336. if (
  5337. // always force full diff in dev
  5338. // - #1942 if hmr is enabled with sfc component
  5339. // - vite#872 non-sfc component used by sfc component
  5340. !(isInHmrContext(instance)) &&
  5341. (optimized || patchFlag > 0) &&
  5342. !(patchFlag & 16 /* PatchFlags.FULL_PROPS */)) {
  5343. if (patchFlag & 8 /* PatchFlags.PROPS */) {
  5344. // Compiler-generated props & no keys change, just set the updated
  5345. // the props.
  5346. const propsToUpdate = instance.vnode.dynamicProps;
  5347. for (let i = 0; i < propsToUpdate.length; i++) {
  5348. let key = propsToUpdate[i];
  5349. // skip if the prop key is a declared emit event listener
  5350. if (isEmitListener(instance.emitsOptions, key)) {
  5351. continue;
  5352. }
  5353. // PROPS flag guarantees rawProps to be non-null
  5354. const value = rawProps[key];
  5355. if (options) {
  5356. // attr / props separation was done on init and will be consistent
  5357. // in this code path, so just check if attrs have it.
  5358. if (hasOwn(attrs, key)) {
  5359. if (value !== attrs[key]) {
  5360. attrs[key] = value;
  5361. hasAttrsChanged = true;
  5362. }
  5363. }
  5364. else {
  5365. const camelizedKey = camelize(key);
  5366. props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
  5367. }
  5368. }
  5369. else {
  5370. if (value !== attrs[key]) {
  5371. attrs[key] = value;
  5372. hasAttrsChanged = true;
  5373. }
  5374. }
  5375. }
  5376. }
  5377. }
  5378. else {
  5379. // full props update.
  5380. if (setFullProps(instance, rawProps, props, attrs)) {
  5381. hasAttrsChanged = true;
  5382. }
  5383. // in case of dynamic props, check if we need to delete keys from
  5384. // the props object
  5385. let kebabKey;
  5386. for (const key in rawCurrentProps) {
  5387. if (!rawProps ||
  5388. // for camelCase
  5389. (!hasOwn(rawProps, key) &&
  5390. // it's possible the original props was passed in as kebab-case
  5391. // and converted to camelCase (#955)
  5392. ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
  5393. if (options) {
  5394. if (rawPrevProps &&
  5395. // for camelCase
  5396. (rawPrevProps[key] !== undefined ||
  5397. // for kebab-case
  5398. rawPrevProps[kebabKey] !== undefined)) {
  5399. props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
  5400. }
  5401. }
  5402. else {
  5403. delete props[key];
  5404. }
  5405. }
  5406. }
  5407. // in the case of functional component w/o props declaration, props and
  5408. // attrs point to the same object so it should already have been updated.
  5409. if (attrs !== rawCurrentProps) {
  5410. for (const key in attrs) {
  5411. if (!rawProps ||
  5412. (!hasOwn(rawProps, key) &&
  5413. (!false ))) {
  5414. delete attrs[key];
  5415. hasAttrsChanged = true;
  5416. }
  5417. }
  5418. }
  5419. }
  5420. // trigger updates for $attrs in case it's used in component slots
  5421. if (hasAttrsChanged) {
  5422. trigger(instance, "set" /* TriggerOpTypes.SET */, '$attrs');
  5423. }
  5424. {
  5425. validateProps(rawProps || {}, props, instance);
  5426. }
  5427. }
  5428. function setFullProps(instance, rawProps, props, attrs) {
  5429. const [options, needCastKeys] = instance.propsOptions;
  5430. let hasAttrsChanged = false;
  5431. let rawCastValues;
  5432. if (rawProps) {
  5433. for (let key in rawProps) {
  5434. // key, ref are reserved and never passed down
  5435. if (isReservedProp(key)) {
  5436. continue;
  5437. }
  5438. const value = rawProps[key];
  5439. // prop option names are camelized during normalization, so to support
  5440. // kebab -> camel conversion here we need to camelize the key.
  5441. let camelKey;
  5442. if (options && hasOwn(options, (camelKey = camelize(key)))) {
  5443. if (!needCastKeys || !needCastKeys.includes(camelKey)) {
  5444. props[camelKey] = value;
  5445. }
  5446. else {
  5447. (rawCastValues || (rawCastValues = {}))[camelKey] = value;
  5448. }
  5449. }
  5450. else if (!isEmitListener(instance.emitsOptions, key)) {
  5451. if (!(key in attrs) || value !== attrs[key]) {
  5452. attrs[key] = value;
  5453. hasAttrsChanged = true;
  5454. }
  5455. }
  5456. }
  5457. }
  5458. if (needCastKeys) {
  5459. const rawCurrentProps = toRaw(props);
  5460. const castValues = rawCastValues || EMPTY_OBJ;
  5461. for (let i = 0; i < needCastKeys.length; i++) {
  5462. const key = needCastKeys[i];
  5463. props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
  5464. }
  5465. }
  5466. return hasAttrsChanged;
  5467. }
  5468. function resolvePropValue(options, props, key, value, instance, isAbsent) {
  5469. const opt = options[key];
  5470. if (opt != null) {
  5471. const hasDefault = hasOwn(opt, 'default');
  5472. // default values
  5473. if (hasDefault && value === undefined) {
  5474. const defaultValue = opt.default;
  5475. if (opt.type !== Function && isFunction(defaultValue)) {
  5476. const { propsDefaults } = instance;
  5477. if (key in propsDefaults) {
  5478. value = propsDefaults[key];
  5479. }
  5480. else {
  5481. setCurrentInstance(instance);
  5482. value = propsDefaults[key] = defaultValue.call(null, props);
  5483. unsetCurrentInstance();
  5484. }
  5485. }
  5486. else {
  5487. value = defaultValue;
  5488. }
  5489. }
  5490. // boolean casting
  5491. if (opt[0 /* BooleanFlags.shouldCast */]) {
  5492. if (isAbsent && !hasDefault) {
  5493. value = false;
  5494. }
  5495. else if (opt[1 /* BooleanFlags.shouldCastTrue */] &&
  5496. (value === '' || value === hyphenate(key))) {
  5497. value = true;
  5498. }
  5499. }
  5500. }
  5501. return value;
  5502. }
  5503. function normalizePropsOptions(comp, appContext, asMixin = false) {
  5504. const cache = appContext.propsCache;
  5505. const cached = cache.get(comp);
  5506. if (cached) {
  5507. return cached;
  5508. }
  5509. const raw = comp.props;
  5510. const normalized = {};
  5511. const needCastKeys = [];
  5512. // apply mixin/extends props
  5513. let hasExtends = false;
  5514. if (!isFunction(comp)) {
  5515. const extendProps = (raw) => {
  5516. hasExtends = true;
  5517. const [props, keys] = normalizePropsOptions(raw, appContext, true);
  5518. extend(normalized, props);
  5519. if (keys)
  5520. needCastKeys.push(...keys);
  5521. };
  5522. if (!asMixin && appContext.mixins.length) {
  5523. appContext.mixins.forEach(extendProps);
  5524. }
  5525. if (comp.extends) {
  5526. extendProps(comp.extends);
  5527. }
  5528. if (comp.mixins) {
  5529. comp.mixins.forEach(extendProps);
  5530. }
  5531. }
  5532. if (!raw && !hasExtends) {
  5533. if (isObject(comp)) {
  5534. cache.set(comp, EMPTY_ARR);
  5535. }
  5536. return EMPTY_ARR;
  5537. }
  5538. if (isArray(raw)) {
  5539. for (let i = 0; i < raw.length; i++) {
  5540. if (!isString(raw[i])) {
  5541. warn(`props must be strings when using array syntax.`, raw[i]);
  5542. }
  5543. const normalizedKey = camelize(raw[i]);
  5544. if (validatePropName(normalizedKey)) {
  5545. normalized[normalizedKey] = EMPTY_OBJ;
  5546. }
  5547. }
  5548. }
  5549. else if (raw) {
  5550. if (!isObject(raw)) {
  5551. warn(`invalid props options`, raw);
  5552. }
  5553. for (const key in raw) {
  5554. const normalizedKey = camelize(key);
  5555. if (validatePropName(normalizedKey)) {
  5556. const opt = raw[key];
  5557. const prop = (normalized[normalizedKey] =
  5558. isArray(opt) || isFunction(opt) ? { type: opt } : Object.assign({}, opt));
  5559. if (prop) {
  5560. const booleanIndex = getTypeIndex(Boolean, prop.type);
  5561. const stringIndex = getTypeIndex(String, prop.type);
  5562. prop[0 /* BooleanFlags.shouldCast */] = booleanIndex > -1;
  5563. prop[1 /* BooleanFlags.shouldCastTrue */] =
  5564. stringIndex < 0 || booleanIndex < stringIndex;
  5565. // if the prop needs boolean casting or default value
  5566. if (booleanIndex > -1 || hasOwn(prop, 'default')) {
  5567. needCastKeys.push(normalizedKey);
  5568. }
  5569. }
  5570. }
  5571. }
  5572. }
  5573. const res = [normalized, needCastKeys];
  5574. if (isObject(comp)) {
  5575. cache.set(comp, res);
  5576. }
  5577. return res;
  5578. }
  5579. function validatePropName(key) {
  5580. if (key[0] !== '$') {
  5581. return true;
  5582. }
  5583. else {
  5584. warn(`Invalid prop name: "${key}" is a reserved property.`);
  5585. }
  5586. return false;
  5587. }
  5588. // use function string name to check type constructors
  5589. // so that it works across vms / iframes.
  5590. function getType(ctor) {
  5591. const match = ctor && ctor.toString().match(/^\s*(function|class) (\w+)/);
  5592. return match ? match[2] : ctor === null ? 'null' : '';
  5593. }
  5594. function isSameType(a, b) {
  5595. return getType(a) === getType(b);
  5596. }
  5597. function getTypeIndex(type, expectedTypes) {
  5598. if (isArray(expectedTypes)) {
  5599. return expectedTypes.findIndex(t => isSameType(t, type));
  5600. }
  5601. else if (isFunction(expectedTypes)) {
  5602. return isSameType(expectedTypes, type) ? 0 : -1;
  5603. }
  5604. return -1;
  5605. }
  5606. /**
  5607. * dev only
  5608. */
  5609. function validateProps(rawProps, props, instance) {
  5610. const resolvedValues = toRaw(props);
  5611. const options = instance.propsOptions[0];
  5612. for (const key in options) {
  5613. let opt = options[key];
  5614. if (opt == null)
  5615. continue;
  5616. validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
  5617. }
  5618. }
  5619. /**
  5620. * dev only
  5621. */
  5622. function validateProp(name, value, prop, isAbsent) {
  5623. const { type, required, validator } = prop;
  5624. // required!
  5625. if (required && isAbsent) {
  5626. warn('Missing required prop: "' + name + '"');
  5627. return;
  5628. }
  5629. // missing but optional
  5630. if (value == null && !prop.required) {
  5631. return;
  5632. }
  5633. // type check
  5634. if (type != null && type !== true) {
  5635. let isValid = false;
  5636. const types = isArray(type) ? type : [type];
  5637. const expectedTypes = [];
  5638. // value is valid as long as one of the specified types match
  5639. for (let i = 0; i < types.length && !isValid; i++) {
  5640. const { valid, expectedType } = assertType(value, types[i]);
  5641. expectedTypes.push(expectedType || '');
  5642. isValid = valid;
  5643. }
  5644. if (!isValid) {
  5645. warn(getInvalidTypeMessage(name, value, expectedTypes));
  5646. return;
  5647. }
  5648. }
  5649. // custom validator
  5650. if (validator && !validator(value)) {
  5651. warn('Invalid prop: custom validator check failed for prop "' + name + '".');
  5652. }
  5653. }
  5654. const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
  5655. /**
  5656. * dev only
  5657. */
  5658. function assertType(value, type) {
  5659. let valid;
  5660. const expectedType = getType(type);
  5661. if (isSimpleType(expectedType)) {
  5662. const t = typeof value;
  5663. valid = t === expectedType.toLowerCase();
  5664. // for primitive wrapper objects
  5665. if (!valid && t === 'object') {
  5666. valid = value instanceof type;
  5667. }
  5668. }
  5669. else if (expectedType === 'Object') {
  5670. valid = isObject(value);
  5671. }
  5672. else if (expectedType === 'Array') {
  5673. valid = isArray(value);
  5674. }
  5675. else if (expectedType === 'null') {
  5676. valid = value === null;
  5677. }
  5678. else {
  5679. valid = value instanceof type;
  5680. }
  5681. return {
  5682. valid,
  5683. expectedType
  5684. };
  5685. }
  5686. /**
  5687. * dev only
  5688. */
  5689. function getInvalidTypeMessage(name, value, expectedTypes) {
  5690. let message = `Invalid prop: type check failed for prop "${name}".` +
  5691. ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
  5692. const expectedType = expectedTypes[0];
  5693. const receivedType = toRawType(value);
  5694. const expectedValue = styleValue(value, expectedType);
  5695. const receivedValue = styleValue(value, receivedType);
  5696. // check if we need to specify expected value
  5697. if (expectedTypes.length === 1 &&
  5698. isExplicable(expectedType) &&
  5699. !isBoolean(expectedType, receivedType)) {
  5700. message += ` with value ${expectedValue}`;
  5701. }
  5702. message += `, got ${receivedType} `;
  5703. // check if we need to specify received value
  5704. if (isExplicable(receivedType)) {
  5705. message += `with value ${receivedValue}.`;
  5706. }
  5707. return message;
  5708. }
  5709. /**
  5710. * dev only
  5711. */
  5712. function styleValue(value, type) {
  5713. if (type === 'String') {
  5714. return `"${value}"`;
  5715. }
  5716. else if (type === 'Number') {
  5717. return `${Number(value)}`;
  5718. }
  5719. else {
  5720. return `${value}`;
  5721. }
  5722. }
  5723. /**
  5724. * dev only
  5725. */
  5726. function isExplicable(type) {
  5727. const explicitTypes = ['string', 'number', 'boolean'];
  5728. return explicitTypes.some(elem => type.toLowerCase() === elem);
  5729. }
  5730. /**
  5731. * dev only
  5732. */
  5733. function isBoolean(...args) {
  5734. return args.some(elem => elem.toLowerCase() === 'boolean');
  5735. }
  5736. const isInternalKey = (key) => key[0] === '_' || key === '$stable';
  5737. const normalizeSlotValue = (value) => isArray(value)
  5738. ? value.map(normalizeVNode)
  5739. : [normalizeVNode(value)];
  5740. const normalizeSlot = (key, rawSlot, ctx) => {
  5741. if (rawSlot._n) {
  5742. // already normalized - #5353
  5743. return rawSlot;
  5744. }
  5745. const normalized = withCtx((...args) => {
  5746. if (true && currentInstance) {
  5747. warn(`Slot "${key}" invoked outside of the render function: ` +
  5748. `this will not track dependencies used in the slot. ` +
  5749. `Invoke the slot function inside the render function instead.`);
  5750. }
  5751. return normalizeSlotValue(rawSlot(...args));
  5752. }, ctx);
  5753. normalized._c = false;
  5754. return normalized;
  5755. };
  5756. const normalizeObjectSlots = (rawSlots, slots, instance) => {
  5757. const ctx = rawSlots._ctx;
  5758. for (const key in rawSlots) {
  5759. if (isInternalKey(key))
  5760. continue;
  5761. const value = rawSlots[key];
  5762. if (isFunction(value)) {
  5763. slots[key] = normalizeSlot(key, value, ctx);
  5764. }
  5765. else if (value != null) {
  5766. {
  5767. warn(`Non-function value encountered for slot "${key}". ` +
  5768. `Prefer function slots for better performance.`);
  5769. }
  5770. const normalized = normalizeSlotValue(value);
  5771. slots[key] = () => normalized;
  5772. }
  5773. }
  5774. };
  5775. const normalizeVNodeSlots = (instance, children) => {
  5776. if (!isKeepAlive(instance.vnode) &&
  5777. !(false )) {
  5778. warn(`Non-function value encountered for default slot. ` +
  5779. `Prefer function slots for better performance.`);
  5780. }
  5781. const normalized = normalizeSlotValue(children);
  5782. instance.slots.default = () => normalized;
  5783. };
  5784. const initSlots = (instance, children) => {
  5785. if (instance.vnode.shapeFlag & 32 /* ShapeFlags.SLOTS_CHILDREN */) {
  5786. const type = children._;
  5787. if (type) {
  5788. // users can get the shallow readonly version of the slots object through `this.$slots`,
  5789. // we should avoid the proxy object polluting the slots of the internal instance
  5790. instance.slots = toRaw(children);
  5791. // make compiler marker non-enumerable
  5792. def(children, '_', type);
  5793. }
  5794. else {
  5795. normalizeObjectSlots(children, (instance.slots = {}));
  5796. }
  5797. }
  5798. else {
  5799. instance.slots = {};
  5800. if (children) {
  5801. normalizeVNodeSlots(instance, children);
  5802. }
  5803. }
  5804. def(instance.slots, InternalObjectKey, 1);
  5805. };
  5806. const updateSlots = (instance, children, optimized) => {
  5807. const { vnode, slots } = instance;
  5808. let needDeletionCheck = true;
  5809. let deletionComparisonTarget = EMPTY_OBJ;
  5810. if (vnode.shapeFlag & 32 /* ShapeFlags.SLOTS_CHILDREN */) {
  5811. const type = children._;
  5812. if (type) {
  5813. // compiled slots.
  5814. if (isHmrUpdating) {
  5815. // Parent was HMR updated so slot content may have changed.
  5816. // force update slots and mark instance for hmr as well
  5817. extend(slots, children);
  5818. }
  5819. else if (optimized && type === 1 /* SlotFlags.STABLE */) {
  5820. // compiled AND stable.
  5821. // no need to update, and skip stale slots removal.
  5822. needDeletionCheck = false;
  5823. }
  5824. else {
  5825. // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
  5826. // normalization.
  5827. extend(slots, children);
  5828. // #2893
  5829. // when rendering the optimized slots by manually written render function,
  5830. // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
  5831. // i.e. let the `renderSlot` create the bailed Fragment
  5832. if (!optimized && type === 1 /* SlotFlags.STABLE */) {
  5833. delete slots._;
  5834. }
  5835. }
  5836. }
  5837. else {
  5838. needDeletionCheck = !children.$stable;
  5839. normalizeObjectSlots(children, slots);
  5840. }
  5841. deletionComparisonTarget = children;
  5842. }
  5843. else if (children) {
  5844. // non slot object children (direct value) passed to a component
  5845. normalizeVNodeSlots(instance, children);
  5846. deletionComparisonTarget = { default: 1 };
  5847. }
  5848. // delete stale slots
  5849. if (needDeletionCheck) {
  5850. for (const key in slots) {
  5851. if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
  5852. delete slots[key];
  5853. }
  5854. }
  5855. }
  5856. };
  5857. function createAppContext() {
  5858. return {
  5859. app: null,
  5860. config: {
  5861. isNativeTag: NO,
  5862. performance: false,
  5863. globalProperties: {},
  5864. optionMergeStrategies: {},
  5865. errorHandler: undefined,
  5866. warnHandler: undefined,
  5867. compilerOptions: {}
  5868. },
  5869. mixins: [],
  5870. components: {},
  5871. directives: {},
  5872. provides: Object.create(null),
  5873. optionsCache: new WeakMap(),
  5874. propsCache: new WeakMap(),
  5875. emitsCache: new WeakMap()
  5876. };
  5877. }
  5878. let uid$1 = 0;
  5879. function createAppAPI(render, hydrate) {
  5880. return function createApp(rootComponent, rootProps = null) {
  5881. if (!isFunction(rootComponent)) {
  5882. rootComponent = Object.assign({}, rootComponent);
  5883. }
  5884. if (rootProps != null && !isObject(rootProps)) {
  5885. warn(`root props passed to app.mount() must be an object.`);
  5886. rootProps = null;
  5887. }
  5888. const context = createAppContext();
  5889. const installedPlugins = new Set();
  5890. let isMounted = false;
  5891. const app = (context.app = {
  5892. _uid: uid$1++,
  5893. _component: rootComponent,
  5894. _props: rootProps,
  5895. _container: null,
  5896. _context: context,
  5897. _instance: null,
  5898. version,
  5899. get config() {
  5900. return context.config;
  5901. },
  5902. set config(v) {
  5903. {
  5904. warn(`app.config cannot be replaced. Modify individual options instead.`);
  5905. }
  5906. },
  5907. use(plugin, ...options) {
  5908. if (installedPlugins.has(plugin)) {
  5909. warn(`Plugin has already been applied to target app.`);
  5910. }
  5911. else if (plugin && isFunction(plugin.install)) {
  5912. installedPlugins.add(plugin);
  5913. plugin.install(app, ...options);
  5914. }
  5915. else if (isFunction(plugin)) {
  5916. installedPlugins.add(plugin);
  5917. plugin(app, ...options);
  5918. }
  5919. else {
  5920. warn(`A plugin must either be a function or an object with an "install" ` +
  5921. `function.`);
  5922. }
  5923. return app;
  5924. },
  5925. mixin(mixin) {
  5926. {
  5927. if (!context.mixins.includes(mixin)) {
  5928. context.mixins.push(mixin);
  5929. }
  5930. else {
  5931. warn('Mixin has already been applied to target app' +
  5932. (mixin.name ? `: ${mixin.name}` : ''));
  5933. }
  5934. }
  5935. return app;
  5936. },
  5937. component(name, component) {
  5938. {
  5939. validateComponentName(name, context.config);
  5940. }
  5941. if (!component) {
  5942. return context.components[name];
  5943. }
  5944. if (context.components[name]) {
  5945. warn(`Component "${name}" has already been registered in target app.`);
  5946. }
  5947. context.components[name] = component;
  5948. return app;
  5949. },
  5950. directive(name, directive) {
  5951. {
  5952. validateDirectiveName(name);
  5953. }
  5954. if (!directive) {
  5955. return context.directives[name];
  5956. }
  5957. if (context.directives[name]) {
  5958. warn(`Directive "${name}" has already been registered in target app.`);
  5959. }
  5960. context.directives[name] = directive;
  5961. return app;
  5962. },
  5963. mount(rootContainer, isHydrate, isSVG) {
  5964. if (!isMounted) {
  5965. // #5571
  5966. if (rootContainer.__vue_app__) {
  5967. warn(`There is already an app instance mounted on the host container.\n` +
  5968. ` If you want to mount another app on the same host container,` +
  5969. ` you need to unmount the previous app by calling \`app.unmount()\` first.`);
  5970. }
  5971. const vnode = createVNode(rootComponent, rootProps);
  5972. // store app context on the root VNode.
  5973. // this will be set on the root instance on initial mount.
  5974. vnode.appContext = context;
  5975. // HMR root reload
  5976. {
  5977. context.reload = () => {
  5978. render(cloneVNode(vnode), rootContainer, isSVG);
  5979. };
  5980. }
  5981. if (isHydrate && hydrate) {
  5982. hydrate(vnode, rootContainer);
  5983. }
  5984. else {
  5985. render(vnode, rootContainer, isSVG);
  5986. }
  5987. isMounted = true;
  5988. app._container = rootContainer;
  5989. rootContainer.__vue_app__ = app;
  5990. {
  5991. app._instance = vnode.component;
  5992. devtoolsInitApp(app, version);
  5993. }
  5994. return getExposeProxy(vnode.component) || vnode.component.proxy;
  5995. }
  5996. else {
  5997. warn(`App has already been mounted.\n` +
  5998. `If you want to remount the same app, move your app creation logic ` +
  5999. `into a factory function and create fresh app instances for each ` +
  6000. `mount - e.g. \`const createMyApp = () => createApp(App)\``);
  6001. }
  6002. },
  6003. unmount() {
  6004. if (isMounted) {
  6005. render(null, app._container);
  6006. {
  6007. app._instance = null;
  6008. devtoolsUnmountApp(app);
  6009. }
  6010. delete app._container.__vue_app__;
  6011. }
  6012. else {
  6013. warn(`Cannot unmount an app that is not mounted.`);
  6014. }
  6015. },
  6016. provide(key, value) {
  6017. if (key in context.provides) {
  6018. warn(`App already provides property with key "${String(key)}". ` +
  6019. `It will be overwritten with the new value.`);
  6020. }
  6021. context.provides[key] = value;
  6022. return app;
  6023. }
  6024. });
  6025. return app;
  6026. };
  6027. }
  6028. /**
  6029. * Function for handling a template ref
  6030. */
  6031. function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
  6032. if (isArray(rawRef)) {
  6033. rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
  6034. return;
  6035. }
  6036. if (isAsyncWrapper(vnode) && !isUnmount) {
  6037. // when mounting async components, nothing needs to be done,
  6038. // because the template ref is forwarded to inner component
  6039. return;
  6040. }
  6041. const refValue = vnode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */
  6042. ? getExposeProxy(vnode.component) || vnode.component.proxy
  6043. : vnode.el;
  6044. const value = isUnmount ? null : refValue;
  6045. const { i: owner, r: ref } = rawRef;
  6046. if (!owner) {
  6047. warn(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
  6048. `A vnode with ref must be created inside the render function.`);
  6049. return;
  6050. }
  6051. const oldRef = oldRawRef && oldRawRef.r;
  6052. const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
  6053. const setupState = owner.setupState;
  6054. // dynamic ref changed. unset old ref
  6055. if (oldRef != null && oldRef !== ref) {
  6056. if (isString(oldRef)) {
  6057. refs[oldRef] = null;
  6058. if (hasOwn(setupState, oldRef)) {
  6059. setupState[oldRef] = null;
  6060. }
  6061. }
  6062. else if (isRef(oldRef)) {
  6063. oldRef.value = null;
  6064. }
  6065. }
  6066. if (isFunction(ref)) {
  6067. callWithErrorHandling(ref, owner, 12 /* ErrorCodes.FUNCTION_REF */, [value, refs]);
  6068. }
  6069. else {
  6070. const _isString = isString(ref);
  6071. const _isRef = isRef(ref);
  6072. if (_isString || _isRef) {
  6073. const doSet = () => {
  6074. if (rawRef.f) {
  6075. const existing = _isString
  6076. ? hasOwn(setupState, ref)
  6077. ? setupState[ref]
  6078. : refs[ref]
  6079. : ref.value;
  6080. if (isUnmount) {
  6081. isArray(existing) && remove(existing, refValue);
  6082. }
  6083. else {
  6084. if (!isArray(existing)) {
  6085. if (_isString) {
  6086. refs[ref] = [refValue];
  6087. if (hasOwn(setupState, ref)) {
  6088. setupState[ref] = refs[ref];
  6089. }
  6090. }
  6091. else {
  6092. ref.value = [refValue];
  6093. if (rawRef.k)
  6094. refs[rawRef.k] = ref.value;
  6095. }
  6096. }
  6097. else if (!existing.includes(refValue)) {
  6098. existing.push(refValue);
  6099. }
  6100. }
  6101. }
  6102. else if (_isString) {
  6103. refs[ref] = value;
  6104. if (hasOwn(setupState, ref)) {
  6105. setupState[ref] = value;
  6106. }
  6107. }
  6108. else if (_isRef) {
  6109. ref.value = value;
  6110. if (rawRef.k)
  6111. refs[rawRef.k] = value;
  6112. }
  6113. else {
  6114. warn('Invalid template ref type:', ref, `(${typeof ref})`);
  6115. }
  6116. };
  6117. if (value) {
  6118. doSet.id = -1;
  6119. queuePostRenderEffect(doSet, parentSuspense);
  6120. }
  6121. else {
  6122. doSet();
  6123. }
  6124. }
  6125. else {
  6126. warn('Invalid template ref type:', ref, `(${typeof ref})`);
  6127. }
  6128. }
  6129. }
  6130. let hasMismatch = false;
  6131. const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
  6132. const isComment = (node) => node.nodeType === 8 /* DOMNodeTypes.COMMENT */;
  6133. // Note: hydration is DOM-specific
  6134. // But we have to place it in core due to tight coupling with core - splitting
  6135. // it out creates a ton of unnecessary complexity.
  6136. // Hydration also depends on some renderer internal logic which needs to be
  6137. // passed in via arguments.
  6138. function createHydrationFunctions(rendererInternals) {
  6139. const { mt: mountComponent, p: patch, o: { patchProp, createText, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
  6140. const hydrate = (vnode, container) => {
  6141. if (!container.hasChildNodes()) {
  6142. warn(`Attempting to hydrate existing markup but container is empty. ` +
  6143. `Performing full mount instead.`);
  6144. patch(null, vnode, container);
  6145. flushPostFlushCbs();
  6146. container._vnode = vnode;
  6147. return;
  6148. }
  6149. hasMismatch = false;
  6150. hydrateNode(container.firstChild, vnode, null, null, null);
  6151. flushPostFlushCbs();
  6152. container._vnode = vnode;
  6153. if (hasMismatch && !false) {
  6154. // this error should show up in production
  6155. console.error(`Hydration completed but contains mismatches.`);
  6156. }
  6157. };
  6158. const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
  6159. const isFragmentStart = isComment(node) && node.data === '[';
  6160. const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
  6161. const { type, ref, shapeFlag, patchFlag } = vnode;
  6162. let domType = node.nodeType;
  6163. vnode.el = node;
  6164. if (patchFlag === -2 /* PatchFlags.BAIL */) {
  6165. optimized = false;
  6166. vnode.dynamicChildren = null;
  6167. }
  6168. let nextNode = null;
  6169. switch (type) {
  6170. case Text:
  6171. if (domType !== 3 /* DOMNodeTypes.TEXT */) {
  6172. // #5728 empty text node inside a slot can cause hydration failure
  6173. // because the server rendered HTML won't contain a text node
  6174. if (vnode.children === '') {
  6175. insert((vnode.el = createText('')), parentNode(node), node);
  6176. nextNode = node;
  6177. }
  6178. else {
  6179. nextNode = onMismatch();
  6180. }
  6181. }
  6182. else {
  6183. if (node.data !== vnode.children) {
  6184. hasMismatch = true;
  6185. warn(`Hydration text mismatch:` +
  6186. `\n- Client: ${JSON.stringify(node.data)}` +
  6187. `\n- Server: ${JSON.stringify(vnode.children)}`);
  6188. node.data = vnode.children;
  6189. }
  6190. nextNode = nextSibling(node);
  6191. }
  6192. break;
  6193. case Comment:
  6194. if (domType !== 8 /* DOMNodeTypes.COMMENT */ || isFragmentStart) {
  6195. nextNode = onMismatch();
  6196. }
  6197. else {
  6198. nextNode = nextSibling(node);
  6199. }
  6200. break;
  6201. case Static:
  6202. if (isFragmentStart) {
  6203. // entire template is static but SSRed as a fragment
  6204. node = nextSibling(node);
  6205. domType = node.nodeType;
  6206. }
  6207. if (domType === 1 /* DOMNodeTypes.ELEMENT */ || domType === 3 /* DOMNodeTypes.TEXT */) {
  6208. // determine anchor, adopt content
  6209. nextNode = node;
  6210. // if the static vnode has its content stripped during build,
  6211. // adopt it from the server-rendered HTML.
  6212. const needToAdoptContent = !vnode.children.length;
  6213. for (let i = 0; i < vnode.staticCount; i++) {
  6214. if (needToAdoptContent)
  6215. vnode.children +=
  6216. nextNode.nodeType === 1 /* DOMNodeTypes.ELEMENT */
  6217. ? nextNode.outerHTML
  6218. : nextNode.data;
  6219. if (i === vnode.staticCount - 1) {
  6220. vnode.anchor = nextNode;
  6221. }
  6222. nextNode = nextSibling(nextNode);
  6223. }
  6224. return isFragmentStart ? nextSibling(nextNode) : nextNode;
  6225. }
  6226. else {
  6227. onMismatch();
  6228. }
  6229. break;
  6230. case Fragment:
  6231. if (!isFragmentStart) {
  6232. nextNode = onMismatch();
  6233. }
  6234. else {
  6235. nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  6236. }
  6237. break;
  6238. default:
  6239. if (shapeFlag & 1 /* ShapeFlags.ELEMENT */) {
  6240. if (domType !== 1 /* DOMNodeTypes.ELEMENT */ ||
  6241. vnode.type.toLowerCase() !==
  6242. node.tagName.toLowerCase()) {
  6243. nextNode = onMismatch();
  6244. }
  6245. else {
  6246. nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  6247. }
  6248. }
  6249. else if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  6250. // when setting up the render effect, if the initial vnode already
  6251. // has .el set, the component will perform hydration instead of mount
  6252. // on its sub-tree.
  6253. vnode.slotScopeIds = slotScopeIds;
  6254. const container = parentNode(node);
  6255. mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
  6256. // component may be async, so in the case of fragments we cannot rely
  6257. // on component's rendered output to determine the end of the fragment
  6258. // instead, we do a lookahead to find the end anchor node.
  6259. nextNode = isFragmentStart
  6260. ? locateClosingAsyncAnchor(node)
  6261. : nextSibling(node);
  6262. // #4293 teleport as component root
  6263. if (nextNode &&
  6264. isComment(nextNode) &&
  6265. nextNode.data === 'teleport end') {
  6266. nextNode = nextSibling(nextNode);
  6267. }
  6268. // #3787
  6269. // if component is async, it may get moved / unmounted before its
  6270. // inner component is loaded, so we need to give it a placeholder
  6271. // vnode that matches its adopted DOM.
  6272. if (isAsyncWrapper(vnode)) {
  6273. let subTree;
  6274. if (isFragmentStart) {
  6275. subTree = createVNode(Fragment);
  6276. subTree.anchor = nextNode
  6277. ? nextNode.previousSibling
  6278. : container.lastChild;
  6279. }
  6280. else {
  6281. subTree =
  6282. node.nodeType === 3 ? createTextVNode('') : createVNode('div');
  6283. }
  6284. subTree.el = node;
  6285. vnode.component.subTree = subTree;
  6286. }
  6287. }
  6288. else if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
  6289. if (domType !== 8 /* DOMNodeTypes.COMMENT */) {
  6290. nextNode = onMismatch();
  6291. }
  6292. else {
  6293. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
  6294. }
  6295. }
  6296. else if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  6297. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
  6298. }
  6299. else {
  6300. warn('Invalid HostVNode type:', type, `(${typeof type})`);
  6301. }
  6302. }
  6303. if (ref != null) {
  6304. setRef(ref, null, parentSuspense, vnode);
  6305. }
  6306. return nextNode;
  6307. };
  6308. const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  6309. optimized = optimized || !!vnode.dynamicChildren;
  6310. const { type, props, patchFlag, shapeFlag, dirs } = vnode;
  6311. // #4006 for form elements with non-string v-model value bindings
  6312. // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
  6313. const forcePatchValue = (type === 'input' && dirs) || type === 'option';
  6314. // skip props & children if this is hoisted static nodes
  6315. // #5405 in dev, always hydrate children for HMR
  6316. {
  6317. if (dirs) {
  6318. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  6319. }
  6320. // props
  6321. if (props) {
  6322. if (forcePatchValue ||
  6323. !optimized ||
  6324. patchFlag & (16 /* PatchFlags.FULL_PROPS */ | 32 /* PatchFlags.HYDRATE_EVENTS */)) {
  6325. for (const key in props) {
  6326. if ((forcePatchValue && key.endsWith('value')) ||
  6327. (isOn(key) && !isReservedProp(key))) {
  6328. patchProp(el, key, null, props[key], false, undefined, parentComponent);
  6329. }
  6330. }
  6331. }
  6332. else if (props.onClick) {
  6333. // Fast path for click listeners (which is most often) to avoid
  6334. // iterating through props.
  6335. patchProp(el, 'onClick', null, props.onClick, false, undefined, parentComponent);
  6336. }
  6337. }
  6338. // vnode / directive hooks
  6339. let vnodeHooks;
  6340. if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
  6341. invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  6342. }
  6343. if (dirs) {
  6344. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  6345. }
  6346. if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
  6347. queueEffectWithSuspense(() => {
  6348. vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  6349. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  6350. }, parentSuspense);
  6351. }
  6352. // children
  6353. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */ &&
  6354. // skip if element has innerHTML / textContent
  6355. !(props && (props.innerHTML || props.textContent))) {
  6356. let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
  6357. let hasWarned = false;
  6358. while (next) {
  6359. hasMismatch = true;
  6360. if (!hasWarned) {
  6361. warn(`Hydration children mismatch in <${vnode.type}>: ` +
  6362. `server rendered element contains more child nodes than client vdom.`);
  6363. hasWarned = true;
  6364. }
  6365. // The SSRed DOM contains more nodes than it should. Remove them.
  6366. const cur = next;
  6367. next = next.nextSibling;
  6368. remove(cur);
  6369. }
  6370. }
  6371. else if (shapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
  6372. if (el.textContent !== vnode.children) {
  6373. hasMismatch = true;
  6374. warn(`Hydration text content mismatch in <${vnode.type}>:\n` +
  6375. `- Client: ${el.textContent}\n` +
  6376. `- Server: ${vnode.children}`);
  6377. el.textContent = vnode.children;
  6378. }
  6379. }
  6380. }
  6381. return el.nextSibling;
  6382. };
  6383. const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  6384. optimized = optimized || !!parentVNode.dynamicChildren;
  6385. const children = parentVNode.children;
  6386. const l = children.length;
  6387. let hasWarned = false;
  6388. for (let i = 0; i < l; i++) {
  6389. const vnode = optimized
  6390. ? children[i]
  6391. : (children[i] = normalizeVNode(children[i]));
  6392. if (node) {
  6393. node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  6394. }
  6395. else if (vnode.type === Text && !vnode.children) {
  6396. continue;
  6397. }
  6398. else {
  6399. hasMismatch = true;
  6400. if (!hasWarned) {
  6401. warn(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
  6402. `server rendered element contains fewer child nodes than client vdom.`);
  6403. hasWarned = true;
  6404. }
  6405. // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
  6406. patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
  6407. }
  6408. }
  6409. return node;
  6410. };
  6411. const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  6412. const { slotScopeIds: fragmentSlotScopeIds } = vnode;
  6413. if (fragmentSlotScopeIds) {
  6414. slotScopeIds = slotScopeIds
  6415. ? slotScopeIds.concat(fragmentSlotScopeIds)
  6416. : fragmentSlotScopeIds;
  6417. }
  6418. const container = parentNode(node);
  6419. const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
  6420. if (next && isComment(next) && next.data === ']') {
  6421. return nextSibling((vnode.anchor = next));
  6422. }
  6423. else {
  6424. // fragment didn't hydrate successfully, since we didn't get a end anchor
  6425. // back. This should have led to node/children mismatch warnings.
  6426. hasMismatch = true;
  6427. // since the anchor is missing, we need to create one and insert it
  6428. insert((vnode.anchor = createComment(`]`)), container, next);
  6429. return next;
  6430. }
  6431. };
  6432. const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
  6433. hasMismatch = true;
  6434. warn(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* DOMNodeTypes.TEXT */
  6435. ? `(text)`
  6436. : isComment(node) && node.data === '['
  6437. ? `(start of fragment)`
  6438. : ``);
  6439. vnode.el = null;
  6440. if (isFragment) {
  6441. // remove excessive fragment nodes
  6442. const end = locateClosingAsyncAnchor(node);
  6443. while (true) {
  6444. const next = nextSibling(node);
  6445. if (next && next !== end) {
  6446. remove(next);
  6447. }
  6448. else {
  6449. break;
  6450. }
  6451. }
  6452. }
  6453. const next = nextSibling(node);
  6454. const container = parentNode(node);
  6455. remove(node);
  6456. patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
  6457. return next;
  6458. };
  6459. const locateClosingAsyncAnchor = (node) => {
  6460. let match = 0;
  6461. while (node) {
  6462. node = nextSibling(node);
  6463. if (node && isComment(node)) {
  6464. if (node.data === '[')
  6465. match++;
  6466. if (node.data === ']') {
  6467. if (match === 0) {
  6468. return nextSibling(node);
  6469. }
  6470. else {
  6471. match--;
  6472. }
  6473. }
  6474. }
  6475. }
  6476. return node;
  6477. };
  6478. return [hydrate, hydrateNode];
  6479. }
  6480. /* eslint-disable no-restricted-globals */
  6481. let supported;
  6482. let perf;
  6483. function startMeasure(instance, type) {
  6484. if (instance.appContext.config.performance && isSupported()) {
  6485. perf.mark(`vue-${type}-${instance.uid}`);
  6486. }
  6487. {
  6488. devtoolsPerfStart(instance, type, isSupported() ? perf.now() : Date.now());
  6489. }
  6490. }
  6491. function endMeasure(instance, type) {
  6492. if (instance.appContext.config.performance && isSupported()) {
  6493. const startTag = `vue-${type}-${instance.uid}`;
  6494. const endTag = startTag + `:end`;
  6495. perf.mark(endTag);
  6496. perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
  6497. perf.clearMarks(startTag);
  6498. perf.clearMarks(endTag);
  6499. }
  6500. {
  6501. devtoolsPerfEnd(instance, type, isSupported() ? perf.now() : Date.now());
  6502. }
  6503. }
  6504. function isSupported() {
  6505. if (supported !== undefined) {
  6506. return supported;
  6507. }
  6508. if (typeof window !== 'undefined' && window.performance) {
  6509. supported = true;
  6510. perf = window.performance;
  6511. }
  6512. else {
  6513. supported = false;
  6514. }
  6515. return supported;
  6516. }
  6517. const queuePostRenderEffect = queueEffectWithSuspense
  6518. ;
  6519. /**
  6520. * The createRenderer function accepts two generic arguments:
  6521. * HostNode and HostElement, corresponding to Node and Element types in the
  6522. * host environment. For example, for runtime-dom, HostNode would be the DOM
  6523. * `Node` interface and HostElement would be the DOM `Element` interface.
  6524. *
  6525. * Custom renderers can pass in the platform specific types like this:
  6526. *
  6527. * ``` js
  6528. * const { render, createApp } = createRenderer<Node, Element>({
  6529. * patchProp,
  6530. * ...nodeOps
  6531. * })
  6532. * ```
  6533. */
  6534. function createRenderer(options) {
  6535. return baseCreateRenderer(options);
  6536. }
  6537. // Separate API for creating hydration-enabled renderer.
  6538. // Hydration logic is only used when calling this function, making it
  6539. // tree-shakable.
  6540. function createHydrationRenderer(options) {
  6541. return baseCreateRenderer(options, createHydrationFunctions);
  6542. }
  6543. // implementation
  6544. function baseCreateRenderer(options, createHydrationFns) {
  6545. const target = getGlobalThis();
  6546. target.__VUE__ = true;
  6547. {
  6548. setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
  6549. }
  6550. const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, insertStaticContent: hostInsertStaticContent } = options;
  6551. // Note: functions inside this closure should use `const xxx = () => {}`
  6552. // style in order to prevent being inlined by minifiers.
  6553. const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
  6554. if (n1 === n2) {
  6555. return;
  6556. }
  6557. // patching & not same type, unmount old tree
  6558. if (n1 && !isSameVNodeType(n1, n2)) {
  6559. anchor = getNextHostNode(n1);
  6560. unmount(n1, parentComponent, parentSuspense, true);
  6561. n1 = null;
  6562. }
  6563. if (n2.patchFlag === -2 /* PatchFlags.BAIL */) {
  6564. optimized = false;
  6565. n2.dynamicChildren = null;
  6566. }
  6567. const { type, ref, shapeFlag } = n2;
  6568. switch (type) {
  6569. case Text:
  6570. processText(n1, n2, container, anchor);
  6571. break;
  6572. case Comment:
  6573. processCommentNode(n1, n2, container, anchor);
  6574. break;
  6575. case Static:
  6576. if (n1 == null) {
  6577. mountStaticNode(n2, container, anchor, isSVG);
  6578. }
  6579. else {
  6580. patchStaticNode(n1, n2, container, isSVG);
  6581. }
  6582. break;
  6583. case Fragment:
  6584. processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6585. break;
  6586. default:
  6587. if (shapeFlag & 1 /* ShapeFlags.ELEMENT */) {
  6588. processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6589. }
  6590. else if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  6591. processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6592. }
  6593. else if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
  6594. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
  6595. }
  6596. else if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  6597. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
  6598. }
  6599. else {
  6600. warn('Invalid VNode type:', type, `(${typeof type})`);
  6601. }
  6602. }
  6603. // set ref
  6604. if (ref != null && parentComponent) {
  6605. setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
  6606. }
  6607. };
  6608. const processText = (n1, n2, container, anchor) => {
  6609. if (n1 == null) {
  6610. hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
  6611. }
  6612. else {
  6613. const el = (n2.el = n1.el);
  6614. if (n2.children !== n1.children) {
  6615. hostSetText(el, n2.children);
  6616. }
  6617. }
  6618. };
  6619. const processCommentNode = (n1, n2, container, anchor) => {
  6620. if (n1 == null) {
  6621. hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
  6622. }
  6623. else {
  6624. // there's no support for dynamic comments
  6625. n2.el = n1.el;
  6626. }
  6627. };
  6628. const mountStaticNode = (n2, container, anchor, isSVG) => {
  6629. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG, n2.el, n2.anchor);
  6630. };
  6631. /**
  6632. * Dev / HMR only
  6633. */
  6634. const patchStaticNode = (n1, n2, container, isSVG) => {
  6635. // static nodes are only patched during dev for HMR
  6636. if (n2.children !== n1.children) {
  6637. const anchor = hostNextSibling(n1.anchor);
  6638. // remove existing
  6639. removeStaticNode(n1);
  6640. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  6641. }
  6642. else {
  6643. n2.el = n1.el;
  6644. n2.anchor = n1.anchor;
  6645. }
  6646. };
  6647. const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
  6648. let next;
  6649. while (el && el !== anchor) {
  6650. next = hostNextSibling(el);
  6651. hostInsert(el, container, nextSibling);
  6652. el = next;
  6653. }
  6654. hostInsert(anchor, container, nextSibling);
  6655. };
  6656. const removeStaticNode = ({ el, anchor }) => {
  6657. let next;
  6658. while (el && el !== anchor) {
  6659. next = hostNextSibling(el);
  6660. hostRemove(el);
  6661. el = next;
  6662. }
  6663. hostRemove(anchor);
  6664. };
  6665. const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6666. isSVG = isSVG || n2.type === 'svg';
  6667. if (n1 == null) {
  6668. mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6669. }
  6670. else {
  6671. patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6672. }
  6673. };
  6674. const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6675. let el;
  6676. let vnodeHook;
  6677. const { type, props, shapeFlag, transition, dirs } = vnode;
  6678. el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
  6679. // mount children first, since some props may rely on child content
  6680. // being already rendered, e.g. `<select value>`
  6681. if (shapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
  6682. hostSetElementText(el, vnode.children);
  6683. }
  6684. else if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  6685. mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
  6686. }
  6687. if (dirs) {
  6688. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  6689. }
  6690. // scopeId
  6691. setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
  6692. // props
  6693. if (props) {
  6694. for (const key in props) {
  6695. if (key !== 'value' && !isReservedProp(key)) {
  6696. hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  6697. }
  6698. }
  6699. /**
  6700. * Special case for setting value on DOM elements:
  6701. * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
  6702. * - it needs to be forced (#1471)
  6703. * #2353 proposes adding another renderer option to configure this, but
  6704. * the properties affects are so finite it is worth special casing it
  6705. * here to reduce the complexity. (Special casing it also should not
  6706. * affect non-DOM renderers)
  6707. */
  6708. if ('value' in props) {
  6709. hostPatchProp(el, 'value', null, props.value);
  6710. }
  6711. if ((vnodeHook = props.onVnodeBeforeMount)) {
  6712. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  6713. }
  6714. }
  6715. {
  6716. Object.defineProperty(el, '__vnode', {
  6717. value: vnode,
  6718. enumerable: false
  6719. });
  6720. Object.defineProperty(el, '__vueParentComponent', {
  6721. value: parentComponent,
  6722. enumerable: false
  6723. });
  6724. }
  6725. if (dirs) {
  6726. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  6727. }
  6728. // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
  6729. // #1689 For inside suspense + suspense resolved case, just call it
  6730. const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
  6731. transition &&
  6732. !transition.persisted;
  6733. if (needCallTransitionHooks) {
  6734. transition.beforeEnter(el);
  6735. }
  6736. hostInsert(el, container, anchor);
  6737. if ((vnodeHook = props && props.onVnodeMounted) ||
  6738. needCallTransitionHooks ||
  6739. dirs) {
  6740. queuePostRenderEffect(() => {
  6741. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  6742. needCallTransitionHooks && transition.enter(el);
  6743. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  6744. }, parentSuspense);
  6745. }
  6746. };
  6747. const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
  6748. if (scopeId) {
  6749. hostSetScopeId(el, scopeId);
  6750. }
  6751. if (slotScopeIds) {
  6752. for (let i = 0; i < slotScopeIds.length; i++) {
  6753. hostSetScopeId(el, slotScopeIds[i]);
  6754. }
  6755. }
  6756. if (parentComponent) {
  6757. let subTree = parentComponent.subTree;
  6758. if (subTree.patchFlag > 0 &&
  6759. subTree.patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */) {
  6760. subTree =
  6761. filterSingleRoot(subTree.children) || subTree;
  6762. }
  6763. if (vnode === subTree) {
  6764. const parentVNode = parentComponent.vnode;
  6765. setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
  6766. }
  6767. }
  6768. };
  6769. const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
  6770. for (let i = start; i < children.length; i++) {
  6771. const child = (children[i] = optimized
  6772. ? cloneIfMounted(children[i])
  6773. : normalizeVNode(children[i]));
  6774. patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6775. }
  6776. };
  6777. const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6778. const el = (n2.el = n1.el);
  6779. let { patchFlag, dynamicChildren, dirs } = n2;
  6780. // #1426 take the old vnode's patch flag into account since user may clone a
  6781. // compiler-generated vnode, which de-opts to FULL_PROPS
  6782. patchFlag |= n1.patchFlag & 16 /* PatchFlags.FULL_PROPS */;
  6783. const oldProps = n1.props || EMPTY_OBJ;
  6784. const newProps = n2.props || EMPTY_OBJ;
  6785. let vnodeHook;
  6786. // disable recurse in beforeUpdate hooks
  6787. parentComponent && toggleRecurse(parentComponent, false);
  6788. if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
  6789. invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  6790. }
  6791. if (dirs) {
  6792. invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
  6793. }
  6794. parentComponent && toggleRecurse(parentComponent, true);
  6795. if (isHmrUpdating) {
  6796. // HMR updated, force full diff
  6797. patchFlag = 0;
  6798. optimized = false;
  6799. dynamicChildren = null;
  6800. }
  6801. const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
  6802. if (dynamicChildren) {
  6803. patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
  6804. if (parentComponent && parentComponent.type.__hmrId) {
  6805. traverseStaticChildren(n1, n2);
  6806. }
  6807. }
  6808. else if (!optimized) {
  6809. // full diff
  6810. patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
  6811. }
  6812. if (patchFlag > 0) {
  6813. // the presence of a patchFlag means this element's render code was
  6814. // generated by the compiler and can take the fast path.
  6815. // in this path old node and new node are guaranteed to have the same shape
  6816. // (i.e. at the exact same position in the source template)
  6817. if (patchFlag & 16 /* PatchFlags.FULL_PROPS */) {
  6818. // element props contain dynamic keys, full diff needed
  6819. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  6820. }
  6821. else {
  6822. // class
  6823. // this flag is matched when the element has dynamic class bindings.
  6824. if (patchFlag & 2 /* PatchFlags.CLASS */) {
  6825. if (oldProps.class !== newProps.class) {
  6826. hostPatchProp(el, 'class', null, newProps.class, isSVG);
  6827. }
  6828. }
  6829. // style
  6830. // this flag is matched when the element has dynamic style bindings
  6831. if (patchFlag & 4 /* PatchFlags.STYLE */) {
  6832. hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
  6833. }
  6834. // props
  6835. // This flag is matched when the element has dynamic prop/attr bindings
  6836. // other than class and style. The keys of dynamic prop/attrs are saved for
  6837. // faster iteration.
  6838. // Note dynamic keys like :[foo]="bar" will cause this optimization to
  6839. // bail out and go through a full diff because we need to unset the old key
  6840. if (patchFlag & 8 /* PatchFlags.PROPS */) {
  6841. // if the flag is present then dynamicProps must be non-null
  6842. const propsToUpdate = n2.dynamicProps;
  6843. for (let i = 0; i < propsToUpdate.length; i++) {
  6844. const key = propsToUpdate[i];
  6845. const prev = oldProps[key];
  6846. const next = newProps[key];
  6847. // #1471 force patch value
  6848. if (next !== prev || key === 'value') {
  6849. hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
  6850. }
  6851. }
  6852. }
  6853. }
  6854. // text
  6855. // This flag is matched when the element has only dynamic text children.
  6856. if (patchFlag & 1 /* PatchFlags.TEXT */) {
  6857. if (n1.children !== n2.children) {
  6858. hostSetElementText(el, n2.children);
  6859. }
  6860. }
  6861. }
  6862. else if (!optimized && dynamicChildren == null) {
  6863. // unoptimized, full diff
  6864. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  6865. }
  6866. if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
  6867. queuePostRenderEffect(() => {
  6868. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  6869. dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
  6870. }, parentSuspense);
  6871. }
  6872. };
  6873. // The fast path for blocks.
  6874. const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
  6875. for (let i = 0; i < newChildren.length; i++) {
  6876. const oldVNode = oldChildren[i];
  6877. const newVNode = newChildren[i];
  6878. // Determine the container (parent element) for the patch.
  6879. const container =
  6880. // oldVNode may be an errored async setup() component inside Suspense
  6881. // which will not have a mounted element
  6882. oldVNode.el &&
  6883. // - In the case of a Fragment, we need to provide the actual parent
  6884. // of the Fragment itself so it can move its children.
  6885. (oldVNode.type === Fragment ||
  6886. // - In the case of different nodes, there is going to be a replacement
  6887. // which also requires the correct parent container
  6888. !isSameVNodeType(oldVNode, newVNode) ||
  6889. // - In the case of a component, it could contain anything.
  6890. oldVNode.shapeFlag & (6 /* ShapeFlags.COMPONENT */ | 64 /* ShapeFlags.TELEPORT */))
  6891. ? hostParentNode(oldVNode.el)
  6892. : // In other cases, the parent container is not actually used so we
  6893. // just pass the block element here to avoid a DOM parentNode call.
  6894. fallbackContainer;
  6895. patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
  6896. }
  6897. };
  6898. const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
  6899. if (oldProps !== newProps) {
  6900. if (oldProps !== EMPTY_OBJ) {
  6901. for (const key in oldProps) {
  6902. if (!isReservedProp(key) && !(key in newProps)) {
  6903. hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  6904. }
  6905. }
  6906. }
  6907. for (const key in newProps) {
  6908. // empty string is not valid prop
  6909. if (isReservedProp(key))
  6910. continue;
  6911. const next = newProps[key];
  6912. const prev = oldProps[key];
  6913. // defer patching value
  6914. if (next !== prev && key !== 'value') {
  6915. hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  6916. }
  6917. }
  6918. if ('value' in newProps) {
  6919. hostPatchProp(el, 'value', oldProps.value, newProps.value);
  6920. }
  6921. }
  6922. };
  6923. const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6924. const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
  6925. const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
  6926. let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
  6927. if (// #5523 dev root fragment may inherit directives
  6928. (isHmrUpdating || patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */)) {
  6929. // HMR updated / Dev root fragment (w/ comments), force full diff
  6930. patchFlag = 0;
  6931. optimized = false;
  6932. dynamicChildren = null;
  6933. }
  6934. // check if this is a slot fragment with :slotted scope ids
  6935. if (fragmentSlotScopeIds) {
  6936. slotScopeIds = slotScopeIds
  6937. ? slotScopeIds.concat(fragmentSlotScopeIds)
  6938. : fragmentSlotScopeIds;
  6939. }
  6940. if (n1 == null) {
  6941. hostInsert(fragmentStartAnchor, container, anchor);
  6942. hostInsert(fragmentEndAnchor, container, anchor);
  6943. // a fragment can only have array children
  6944. // since they are either generated by the compiler, or implicitly created
  6945. // from arrays.
  6946. mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6947. }
  6948. else {
  6949. if (patchFlag > 0 &&
  6950. patchFlag & 64 /* PatchFlags.STABLE_FRAGMENT */ &&
  6951. dynamicChildren &&
  6952. // #2715 the previous fragment could've been a BAILed one as a result
  6953. // of renderSlot() with no valid children
  6954. n1.dynamicChildren) {
  6955. // a stable fragment (template root or <template v-for>) doesn't need to
  6956. // patch children order, but it may contain dynamicChildren.
  6957. patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
  6958. if (parentComponent && parentComponent.type.__hmrId) {
  6959. traverseStaticChildren(n1, n2);
  6960. }
  6961. else if (
  6962. // #2080 if the stable fragment has a key, it's a <template v-for> that may
  6963. // get moved around. Make sure all root level vnodes inherit el.
  6964. // #2134 or if it's a component root, it may also get moved around
  6965. // as the component is being moved.
  6966. n2.key != null ||
  6967. (parentComponent && n2 === parentComponent.subTree)) {
  6968. traverseStaticChildren(n1, n2, true /* shallow */);
  6969. }
  6970. }
  6971. else {
  6972. // keyed / unkeyed, or manual fragments.
  6973. // for keyed & unkeyed, since they are compiler generated from v-for,
  6974. // each child is guaranteed to be a block so the fragment will never
  6975. // have dynamicChildren.
  6976. patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6977. }
  6978. }
  6979. };
  6980. const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6981. n2.slotScopeIds = slotScopeIds;
  6982. if (n1 == null) {
  6983. if (n2.shapeFlag & 512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */) {
  6984. parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
  6985. }
  6986. else {
  6987. mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  6988. }
  6989. }
  6990. else {
  6991. updateComponent(n1, n2, optimized);
  6992. }
  6993. };
  6994. const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  6995. const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
  6996. if (instance.type.__hmrId) {
  6997. registerHMR(instance);
  6998. }
  6999. {
  7000. pushWarningContext(initialVNode);
  7001. startMeasure(instance, `mount`);
  7002. }
  7003. // inject renderer internals for keepAlive
  7004. if (isKeepAlive(initialVNode)) {
  7005. instance.ctx.renderer = internals;
  7006. }
  7007. // resolve props and slots for setup context
  7008. {
  7009. {
  7010. startMeasure(instance, `init`);
  7011. }
  7012. setupComponent(instance);
  7013. {
  7014. endMeasure(instance, `init`);
  7015. }
  7016. }
  7017. // setup() is async. This component relies on async logic to be resolved
  7018. // before proceeding
  7019. if (instance.asyncDep) {
  7020. parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
  7021. // Give it a placeholder if this is not hydration
  7022. // TODO handle self-defined fallback
  7023. if (!initialVNode.el) {
  7024. const placeholder = (instance.subTree = createVNode(Comment));
  7025. processCommentNode(null, placeholder, container, anchor);
  7026. }
  7027. return;
  7028. }
  7029. setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
  7030. {
  7031. popWarningContext();
  7032. endMeasure(instance, `mount`);
  7033. }
  7034. };
  7035. const updateComponent = (n1, n2, optimized) => {
  7036. const instance = (n2.component = n1.component);
  7037. if (shouldUpdateComponent(n1, n2, optimized)) {
  7038. if (instance.asyncDep &&
  7039. !instance.asyncResolved) {
  7040. // async & still pending - just update props and slots
  7041. // since the component's reactive effect for render isn't set-up yet
  7042. {
  7043. pushWarningContext(n2);
  7044. }
  7045. updateComponentPreRender(instance, n2, optimized);
  7046. {
  7047. popWarningContext();
  7048. }
  7049. return;
  7050. }
  7051. else {
  7052. // normal update
  7053. instance.next = n2;
  7054. // in case the child component is also queued, remove it to avoid
  7055. // double updating the same child component in the same flush.
  7056. invalidateJob(instance.update);
  7057. // instance.update is the reactive effect.
  7058. instance.update();
  7059. }
  7060. }
  7061. else {
  7062. // no update needed. just copy over properties
  7063. n2.el = n1.el;
  7064. instance.vnode = n2;
  7065. }
  7066. };
  7067. const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
  7068. const componentUpdateFn = () => {
  7069. if (!instance.isMounted) {
  7070. let vnodeHook;
  7071. const { el, props } = initialVNode;
  7072. const { bm, m, parent } = instance;
  7073. const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
  7074. toggleRecurse(instance, false);
  7075. // beforeMount hook
  7076. if (bm) {
  7077. invokeArrayFns(bm);
  7078. }
  7079. // onVnodeBeforeMount
  7080. if (!isAsyncWrapperVNode &&
  7081. (vnodeHook = props && props.onVnodeBeforeMount)) {
  7082. invokeVNodeHook(vnodeHook, parent, initialVNode);
  7083. }
  7084. toggleRecurse(instance, true);
  7085. if (el && hydrateNode) {
  7086. // vnode has adopted host node - perform hydration instead of mount.
  7087. const hydrateSubTree = () => {
  7088. {
  7089. startMeasure(instance, `render`);
  7090. }
  7091. instance.subTree = renderComponentRoot(instance);
  7092. {
  7093. endMeasure(instance, `render`);
  7094. }
  7095. {
  7096. startMeasure(instance, `hydrate`);
  7097. }
  7098. hydrateNode(el, instance.subTree, instance, parentSuspense, null);
  7099. {
  7100. endMeasure(instance, `hydrate`);
  7101. }
  7102. };
  7103. if (isAsyncWrapperVNode) {
  7104. initialVNode.type.__asyncLoader().then(
  7105. // note: we are moving the render call into an async callback,
  7106. // which means it won't track dependencies - but it's ok because
  7107. // a server-rendered async wrapper is already in resolved state
  7108. // and it will never need to change.
  7109. () => !instance.isUnmounted && hydrateSubTree());
  7110. }
  7111. else {
  7112. hydrateSubTree();
  7113. }
  7114. }
  7115. else {
  7116. {
  7117. startMeasure(instance, `render`);
  7118. }
  7119. const subTree = (instance.subTree = renderComponentRoot(instance));
  7120. {
  7121. endMeasure(instance, `render`);
  7122. }
  7123. {
  7124. startMeasure(instance, `patch`);
  7125. }
  7126. patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
  7127. {
  7128. endMeasure(instance, `patch`);
  7129. }
  7130. initialVNode.el = subTree.el;
  7131. }
  7132. // mounted hook
  7133. if (m) {
  7134. queuePostRenderEffect(m, parentSuspense);
  7135. }
  7136. // onVnodeMounted
  7137. if (!isAsyncWrapperVNode &&
  7138. (vnodeHook = props && props.onVnodeMounted)) {
  7139. const scopedInitialVNode = initialVNode;
  7140. queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
  7141. }
  7142. // activated hook for keep-alive roots.
  7143. // #1742 activated hook must be accessed after first render
  7144. // since the hook may be injected by a child keep-alive
  7145. if (initialVNode.shapeFlag & 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */ ||
  7146. (parent &&
  7147. isAsyncWrapper(parent.vnode) &&
  7148. parent.vnode.shapeFlag & 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */)) {
  7149. instance.a && queuePostRenderEffect(instance.a, parentSuspense);
  7150. }
  7151. instance.isMounted = true;
  7152. {
  7153. devtoolsComponentAdded(instance);
  7154. }
  7155. // #2458: deference mount-only object parameters to prevent memleaks
  7156. initialVNode = container = anchor = null;
  7157. }
  7158. else {
  7159. // updateComponent
  7160. // This is triggered by mutation of component's own state (next: null)
  7161. // OR parent calling processComponent (next: VNode)
  7162. let { next, bu, u, parent, vnode } = instance;
  7163. let originNext = next;
  7164. let vnodeHook;
  7165. {
  7166. pushWarningContext(next || instance.vnode);
  7167. }
  7168. // Disallow component effect recursion during pre-lifecycle hooks.
  7169. toggleRecurse(instance, false);
  7170. if (next) {
  7171. next.el = vnode.el;
  7172. updateComponentPreRender(instance, next, optimized);
  7173. }
  7174. else {
  7175. next = vnode;
  7176. }
  7177. // beforeUpdate hook
  7178. if (bu) {
  7179. invokeArrayFns(bu);
  7180. }
  7181. // onVnodeBeforeUpdate
  7182. if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
  7183. invokeVNodeHook(vnodeHook, parent, next, vnode);
  7184. }
  7185. toggleRecurse(instance, true);
  7186. // render
  7187. {
  7188. startMeasure(instance, `render`);
  7189. }
  7190. const nextTree = renderComponentRoot(instance);
  7191. {
  7192. endMeasure(instance, `render`);
  7193. }
  7194. const prevTree = instance.subTree;
  7195. instance.subTree = nextTree;
  7196. {
  7197. startMeasure(instance, `patch`);
  7198. }
  7199. patch(prevTree, nextTree,
  7200. // parent may have changed if it's in a teleport
  7201. hostParentNode(prevTree.el),
  7202. // anchor may have changed if it's in a fragment
  7203. getNextHostNode(prevTree), instance, parentSuspense, isSVG);
  7204. {
  7205. endMeasure(instance, `patch`);
  7206. }
  7207. next.el = nextTree.el;
  7208. if (originNext === null) {
  7209. // self-triggered update. In case of HOC, update parent component
  7210. // vnode el. HOC is indicated by parent instance's subTree pointing
  7211. // to child component's vnode
  7212. updateHOCHostEl(instance, nextTree.el);
  7213. }
  7214. // updated hook
  7215. if (u) {
  7216. queuePostRenderEffect(u, parentSuspense);
  7217. }
  7218. // onVnodeUpdated
  7219. if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
  7220. queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
  7221. }
  7222. {
  7223. devtoolsComponentUpdated(instance);
  7224. }
  7225. {
  7226. popWarningContext();
  7227. }
  7228. }
  7229. };
  7230. // create reactive effect for rendering
  7231. const effect = (instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(update), instance.scope // track it in component's effect scope
  7232. ));
  7233. const update = (instance.update = () => effect.run());
  7234. update.id = instance.uid;
  7235. // allowRecurse
  7236. // #1801, #2043 component render effects should allow recursive updates
  7237. toggleRecurse(instance, true);
  7238. {
  7239. effect.onTrack = instance.rtc
  7240. ? e => invokeArrayFns(instance.rtc, e)
  7241. : void 0;
  7242. effect.onTrigger = instance.rtg
  7243. ? e => invokeArrayFns(instance.rtg, e)
  7244. : void 0;
  7245. update.ownerInstance = instance;
  7246. }
  7247. update();
  7248. };
  7249. const updateComponentPreRender = (instance, nextVNode, optimized) => {
  7250. nextVNode.component = instance;
  7251. const prevProps = instance.vnode.props;
  7252. instance.vnode = nextVNode;
  7253. instance.next = null;
  7254. updateProps(instance, nextVNode.props, prevProps, optimized);
  7255. updateSlots(instance, nextVNode.children, optimized);
  7256. pauseTracking();
  7257. // props update may have triggered pre-flush watchers.
  7258. // flush them before the render update.
  7259. flushPreFlushCbs();
  7260. resetTracking();
  7261. };
  7262. const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
  7263. const c1 = n1 && n1.children;
  7264. const prevShapeFlag = n1 ? n1.shapeFlag : 0;
  7265. const c2 = n2.children;
  7266. const { patchFlag, shapeFlag } = n2;
  7267. // fast path
  7268. if (patchFlag > 0) {
  7269. if (patchFlag & 128 /* PatchFlags.KEYED_FRAGMENT */) {
  7270. // this could be either fully-keyed or mixed (some keyed some not)
  7271. // presence of patchFlag means children are guaranteed to be arrays
  7272. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7273. return;
  7274. }
  7275. else if (patchFlag & 256 /* PatchFlags.UNKEYED_FRAGMENT */) {
  7276. // unkeyed
  7277. patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7278. return;
  7279. }
  7280. }
  7281. // children has 3 possibilities: text, array or no children.
  7282. if (shapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
  7283. // text children fast path
  7284. if (prevShapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7285. unmountChildren(c1, parentComponent, parentSuspense);
  7286. }
  7287. if (c2 !== c1) {
  7288. hostSetElementText(container, c2);
  7289. }
  7290. }
  7291. else {
  7292. if (prevShapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7293. // prev children was array
  7294. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7295. // two arrays, cannot assume anything, do full diff
  7296. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7297. }
  7298. else {
  7299. // no new children, just unmount old
  7300. unmountChildren(c1, parentComponent, parentSuspense, true);
  7301. }
  7302. }
  7303. else {
  7304. // prev children was text OR null
  7305. // new children is array OR null
  7306. if (prevShapeFlag & 8 /* ShapeFlags.TEXT_CHILDREN */) {
  7307. hostSetElementText(container, '');
  7308. }
  7309. // mount new if array
  7310. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7311. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7312. }
  7313. }
  7314. }
  7315. };
  7316. const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  7317. c1 = c1 || EMPTY_ARR;
  7318. c2 = c2 || EMPTY_ARR;
  7319. const oldLength = c1.length;
  7320. const newLength = c2.length;
  7321. const commonLength = Math.min(oldLength, newLength);
  7322. let i;
  7323. for (i = 0; i < commonLength; i++) {
  7324. const nextChild = (c2[i] = optimized
  7325. ? cloneIfMounted(c2[i])
  7326. : normalizeVNode(c2[i]));
  7327. patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7328. }
  7329. if (oldLength > newLength) {
  7330. // remove old
  7331. unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
  7332. }
  7333. else {
  7334. // mount new
  7335. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
  7336. }
  7337. };
  7338. // can be all-keyed or mixed
  7339. const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  7340. let i = 0;
  7341. const l2 = c2.length;
  7342. let e1 = c1.length - 1; // prev ending index
  7343. let e2 = l2 - 1; // next ending index
  7344. // 1. sync from start
  7345. // (a b) c
  7346. // (a b) d e
  7347. while (i <= e1 && i <= e2) {
  7348. const n1 = c1[i];
  7349. const n2 = (c2[i] = optimized
  7350. ? cloneIfMounted(c2[i])
  7351. : normalizeVNode(c2[i]));
  7352. if (isSameVNodeType(n1, n2)) {
  7353. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7354. }
  7355. else {
  7356. break;
  7357. }
  7358. i++;
  7359. }
  7360. // 2. sync from end
  7361. // a (b c)
  7362. // d e (b c)
  7363. while (i <= e1 && i <= e2) {
  7364. const n1 = c1[e1];
  7365. const n2 = (c2[e2] = optimized
  7366. ? cloneIfMounted(c2[e2])
  7367. : normalizeVNode(c2[e2]));
  7368. if (isSameVNodeType(n1, n2)) {
  7369. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7370. }
  7371. else {
  7372. break;
  7373. }
  7374. e1--;
  7375. e2--;
  7376. }
  7377. // 3. common sequence + mount
  7378. // (a b)
  7379. // (a b) c
  7380. // i = 2, e1 = 1, e2 = 2
  7381. // (a b)
  7382. // c (a b)
  7383. // i = 0, e1 = -1, e2 = 0
  7384. if (i > e1) {
  7385. if (i <= e2) {
  7386. const nextPos = e2 + 1;
  7387. const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
  7388. while (i <= e2) {
  7389. patch(null, (c2[i] = optimized
  7390. ? cloneIfMounted(c2[i])
  7391. : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7392. i++;
  7393. }
  7394. }
  7395. }
  7396. // 4. common sequence + unmount
  7397. // (a b) c
  7398. // (a b)
  7399. // i = 2, e1 = 2, e2 = 1
  7400. // a (b c)
  7401. // (b c)
  7402. // i = 0, e1 = 0, e2 = -1
  7403. else if (i > e2) {
  7404. while (i <= e1) {
  7405. unmount(c1[i], parentComponent, parentSuspense, true);
  7406. i++;
  7407. }
  7408. }
  7409. // 5. unknown sequence
  7410. // [i ... e1 + 1]: a b [c d e] f g
  7411. // [i ... e2 + 1]: a b [e d c h] f g
  7412. // i = 2, e1 = 4, e2 = 5
  7413. else {
  7414. const s1 = i; // prev starting index
  7415. const s2 = i; // next starting index
  7416. // 5.1 build key:index map for newChildren
  7417. const keyToNewIndexMap = new Map();
  7418. for (i = s2; i <= e2; i++) {
  7419. const nextChild = (c2[i] = optimized
  7420. ? cloneIfMounted(c2[i])
  7421. : normalizeVNode(c2[i]));
  7422. if (nextChild.key != null) {
  7423. if (keyToNewIndexMap.has(nextChild.key)) {
  7424. warn(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
  7425. }
  7426. keyToNewIndexMap.set(nextChild.key, i);
  7427. }
  7428. }
  7429. // 5.2 loop through old children left to be patched and try to patch
  7430. // matching nodes & remove nodes that are no longer present
  7431. let j;
  7432. let patched = 0;
  7433. const toBePatched = e2 - s2 + 1;
  7434. let moved = false;
  7435. // used to track whether any node has moved
  7436. let maxNewIndexSoFar = 0;
  7437. // works as Map<newIndex, oldIndex>
  7438. // Note that oldIndex is offset by +1
  7439. // and oldIndex = 0 is a special value indicating the new node has
  7440. // no corresponding old node.
  7441. // used for determining longest stable subsequence
  7442. const newIndexToOldIndexMap = new Array(toBePatched);
  7443. for (i = 0; i < toBePatched; i++)
  7444. newIndexToOldIndexMap[i] = 0;
  7445. for (i = s1; i <= e1; i++) {
  7446. const prevChild = c1[i];
  7447. if (patched >= toBePatched) {
  7448. // all new children have been patched so this can only be a removal
  7449. unmount(prevChild, parentComponent, parentSuspense, true);
  7450. continue;
  7451. }
  7452. let newIndex;
  7453. if (prevChild.key != null) {
  7454. newIndex = keyToNewIndexMap.get(prevChild.key);
  7455. }
  7456. else {
  7457. // key-less node, try to locate a key-less node of the same type
  7458. for (j = s2; j <= e2; j++) {
  7459. if (newIndexToOldIndexMap[j - s2] === 0 &&
  7460. isSameVNodeType(prevChild, c2[j])) {
  7461. newIndex = j;
  7462. break;
  7463. }
  7464. }
  7465. }
  7466. if (newIndex === undefined) {
  7467. unmount(prevChild, parentComponent, parentSuspense, true);
  7468. }
  7469. else {
  7470. newIndexToOldIndexMap[newIndex - s2] = i + 1;
  7471. if (newIndex >= maxNewIndexSoFar) {
  7472. maxNewIndexSoFar = newIndex;
  7473. }
  7474. else {
  7475. moved = true;
  7476. }
  7477. patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7478. patched++;
  7479. }
  7480. }
  7481. // 5.3 move and mount
  7482. // generate longest stable subsequence only when nodes have moved
  7483. const increasingNewIndexSequence = moved
  7484. ? getSequence(newIndexToOldIndexMap)
  7485. : EMPTY_ARR;
  7486. j = increasingNewIndexSequence.length - 1;
  7487. // looping backwards so that we can use last patched node as anchor
  7488. for (i = toBePatched - 1; i >= 0; i--) {
  7489. const nextIndex = s2 + i;
  7490. const nextChild = c2[nextIndex];
  7491. const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
  7492. if (newIndexToOldIndexMap[i] === 0) {
  7493. // mount new
  7494. patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7495. }
  7496. else if (moved) {
  7497. // move if:
  7498. // There is no stable subsequence (e.g. a reverse)
  7499. // OR current node is not among the stable sequence
  7500. if (j < 0 || i !== increasingNewIndexSequence[j]) {
  7501. move(nextChild, container, anchor, 2 /* MoveType.REORDER */);
  7502. }
  7503. else {
  7504. j--;
  7505. }
  7506. }
  7507. }
  7508. }
  7509. };
  7510. const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
  7511. const { el, type, transition, children, shapeFlag } = vnode;
  7512. if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  7513. move(vnode.component.subTree, container, anchor, moveType);
  7514. return;
  7515. }
  7516. if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  7517. vnode.suspense.move(container, anchor, moveType);
  7518. return;
  7519. }
  7520. if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
  7521. type.move(vnode, container, anchor, internals);
  7522. return;
  7523. }
  7524. if (type === Fragment) {
  7525. hostInsert(el, container, anchor);
  7526. for (let i = 0; i < children.length; i++) {
  7527. move(children[i], container, anchor, moveType);
  7528. }
  7529. hostInsert(vnode.anchor, container, anchor);
  7530. return;
  7531. }
  7532. if (type === Static) {
  7533. moveStaticNode(vnode, container, anchor);
  7534. return;
  7535. }
  7536. // single nodes
  7537. const needTransition = moveType !== 2 /* MoveType.REORDER */ &&
  7538. shapeFlag & 1 /* ShapeFlags.ELEMENT */ &&
  7539. transition;
  7540. if (needTransition) {
  7541. if (moveType === 0 /* MoveType.ENTER */) {
  7542. transition.beforeEnter(el);
  7543. hostInsert(el, container, anchor);
  7544. queuePostRenderEffect(() => transition.enter(el), parentSuspense);
  7545. }
  7546. else {
  7547. const { leave, delayLeave, afterLeave } = transition;
  7548. const remove = () => hostInsert(el, container, anchor);
  7549. const performLeave = () => {
  7550. leave(el, () => {
  7551. remove();
  7552. afterLeave && afterLeave();
  7553. });
  7554. };
  7555. if (delayLeave) {
  7556. delayLeave(el, remove, performLeave);
  7557. }
  7558. else {
  7559. performLeave();
  7560. }
  7561. }
  7562. }
  7563. else {
  7564. hostInsert(el, container, anchor);
  7565. }
  7566. };
  7567. const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
  7568. const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
  7569. // unset ref
  7570. if (ref != null) {
  7571. setRef(ref, null, parentSuspense, vnode, true);
  7572. }
  7573. if (shapeFlag & 256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */) {
  7574. parentComponent.ctx.deactivate(vnode);
  7575. return;
  7576. }
  7577. const shouldInvokeDirs = shapeFlag & 1 /* ShapeFlags.ELEMENT */ && dirs;
  7578. const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
  7579. let vnodeHook;
  7580. if (shouldInvokeVnodeHook &&
  7581. (vnodeHook = props && props.onVnodeBeforeUnmount)) {
  7582. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  7583. }
  7584. if (shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  7585. unmountComponent(vnode.component, parentSuspense, doRemove);
  7586. }
  7587. else {
  7588. if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  7589. vnode.suspense.unmount(parentSuspense, doRemove);
  7590. return;
  7591. }
  7592. if (shouldInvokeDirs) {
  7593. invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
  7594. }
  7595. if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
  7596. vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
  7597. }
  7598. else if (dynamicChildren &&
  7599. // #1153: fast path should not be taken for non-stable (v-for) fragments
  7600. (type !== Fragment ||
  7601. (patchFlag > 0 && patchFlag & 64 /* PatchFlags.STABLE_FRAGMENT */))) {
  7602. // fast path for block nodes: only need to unmount dynamic children.
  7603. unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
  7604. }
  7605. else if ((type === Fragment &&
  7606. patchFlag &
  7607. (128 /* PatchFlags.KEYED_FRAGMENT */ | 256 /* PatchFlags.UNKEYED_FRAGMENT */)) ||
  7608. (!optimized && shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */)) {
  7609. unmountChildren(children, parentComponent, parentSuspense);
  7610. }
  7611. if (doRemove) {
  7612. remove(vnode);
  7613. }
  7614. }
  7615. if ((shouldInvokeVnodeHook &&
  7616. (vnodeHook = props && props.onVnodeUnmounted)) ||
  7617. shouldInvokeDirs) {
  7618. queuePostRenderEffect(() => {
  7619. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  7620. shouldInvokeDirs &&
  7621. invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
  7622. }, parentSuspense);
  7623. }
  7624. };
  7625. const remove = vnode => {
  7626. const { type, el, anchor, transition } = vnode;
  7627. if (type === Fragment) {
  7628. if (vnode.patchFlag > 0 &&
  7629. vnode.patchFlag & 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */ &&
  7630. transition &&
  7631. !transition.persisted) {
  7632. vnode.children.forEach(child => {
  7633. if (child.type === Comment) {
  7634. hostRemove(child.el);
  7635. }
  7636. else {
  7637. remove(child);
  7638. }
  7639. });
  7640. }
  7641. else {
  7642. removeFragment(el, anchor);
  7643. }
  7644. return;
  7645. }
  7646. if (type === Static) {
  7647. removeStaticNode(vnode);
  7648. return;
  7649. }
  7650. const performRemove = () => {
  7651. hostRemove(el);
  7652. if (transition && !transition.persisted && transition.afterLeave) {
  7653. transition.afterLeave();
  7654. }
  7655. };
  7656. if (vnode.shapeFlag & 1 /* ShapeFlags.ELEMENT */ &&
  7657. transition &&
  7658. !transition.persisted) {
  7659. const { leave, delayLeave } = transition;
  7660. const performLeave = () => leave(el, performRemove);
  7661. if (delayLeave) {
  7662. delayLeave(vnode.el, performRemove, performLeave);
  7663. }
  7664. else {
  7665. performLeave();
  7666. }
  7667. }
  7668. else {
  7669. performRemove();
  7670. }
  7671. };
  7672. const removeFragment = (cur, end) => {
  7673. // For fragments, directly remove all contained DOM nodes.
  7674. // (fragment child nodes cannot have transition)
  7675. let next;
  7676. while (cur !== end) {
  7677. next = hostNextSibling(cur);
  7678. hostRemove(cur);
  7679. cur = next;
  7680. }
  7681. hostRemove(end);
  7682. };
  7683. const unmountComponent = (instance, parentSuspense, doRemove) => {
  7684. if (instance.type.__hmrId) {
  7685. unregisterHMR(instance);
  7686. }
  7687. const { bum, scope, update, subTree, um } = instance;
  7688. // beforeUnmount hook
  7689. if (bum) {
  7690. invokeArrayFns(bum);
  7691. }
  7692. // stop effects in component scope
  7693. scope.stop();
  7694. // update may be null if a component is unmounted before its async
  7695. // setup has resolved.
  7696. if (update) {
  7697. // so that scheduler will no longer invoke it
  7698. update.active = false;
  7699. unmount(subTree, instance, parentSuspense, doRemove);
  7700. }
  7701. // unmounted hook
  7702. if (um) {
  7703. queuePostRenderEffect(um, parentSuspense);
  7704. }
  7705. queuePostRenderEffect(() => {
  7706. instance.isUnmounted = true;
  7707. }, parentSuspense);
  7708. // A component with async dep inside a pending suspense is unmounted before
  7709. // its async dep resolves. This should remove the dep from the suspense, and
  7710. // cause the suspense to resolve immediately if that was the last dep.
  7711. if (parentSuspense &&
  7712. parentSuspense.pendingBranch &&
  7713. !parentSuspense.isUnmounted &&
  7714. instance.asyncDep &&
  7715. !instance.asyncResolved &&
  7716. instance.suspenseId === parentSuspense.pendingId) {
  7717. parentSuspense.deps--;
  7718. if (parentSuspense.deps === 0) {
  7719. parentSuspense.resolve();
  7720. }
  7721. }
  7722. {
  7723. devtoolsComponentRemoved(instance);
  7724. }
  7725. };
  7726. const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
  7727. for (let i = start; i < children.length; i++) {
  7728. unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
  7729. }
  7730. };
  7731. const getNextHostNode = vnode => {
  7732. if (vnode.shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  7733. return getNextHostNode(vnode.component.subTree);
  7734. }
  7735. if (vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  7736. return vnode.suspense.next();
  7737. }
  7738. return hostNextSibling((vnode.anchor || vnode.el));
  7739. };
  7740. const render = (vnode, container, isSVG) => {
  7741. if (vnode == null) {
  7742. if (container._vnode) {
  7743. unmount(container._vnode, null, null, true);
  7744. }
  7745. }
  7746. else {
  7747. patch(container._vnode || null, vnode, container, null, null, null, isSVG);
  7748. }
  7749. flushPreFlushCbs();
  7750. flushPostFlushCbs();
  7751. container._vnode = vnode;
  7752. };
  7753. const internals = {
  7754. p: patch,
  7755. um: unmount,
  7756. m: move,
  7757. r: remove,
  7758. mt: mountComponent,
  7759. mc: mountChildren,
  7760. pc: patchChildren,
  7761. pbc: patchBlockChildren,
  7762. n: getNextHostNode,
  7763. o: options
  7764. };
  7765. let hydrate;
  7766. let hydrateNode;
  7767. if (createHydrationFns) {
  7768. [hydrate, hydrateNode] = createHydrationFns(internals);
  7769. }
  7770. return {
  7771. render,
  7772. hydrate,
  7773. createApp: createAppAPI(render, hydrate)
  7774. };
  7775. }
  7776. function toggleRecurse({ effect, update }, allowed) {
  7777. effect.allowRecurse = update.allowRecurse = allowed;
  7778. }
  7779. /**
  7780. * #1156
  7781. * When a component is HMR-enabled, we need to make sure that all static nodes
  7782. * inside a block also inherit the DOM element from the previous tree so that
  7783. * HMR updates (which are full updates) can retrieve the element for patching.
  7784. *
  7785. * #2080
  7786. * Inside keyed `template` fragment static children, if a fragment is moved,
  7787. * the children will always be moved. Therefore, in order to ensure correct move
  7788. * position, el should be inherited from previous nodes.
  7789. */
  7790. function traverseStaticChildren(n1, n2, shallow = false) {
  7791. const ch1 = n1.children;
  7792. const ch2 = n2.children;
  7793. if (isArray(ch1) && isArray(ch2)) {
  7794. for (let i = 0; i < ch1.length; i++) {
  7795. // this is only called in the optimized path so array children are
  7796. // guaranteed to be vnodes
  7797. const c1 = ch1[i];
  7798. let c2 = ch2[i];
  7799. if (c2.shapeFlag & 1 /* ShapeFlags.ELEMENT */ && !c2.dynamicChildren) {
  7800. if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) {
  7801. c2 = ch2[i] = cloneIfMounted(ch2[i]);
  7802. c2.el = c1.el;
  7803. }
  7804. if (!shallow)
  7805. traverseStaticChildren(c1, c2);
  7806. }
  7807. // #6852 also inherit for text nodes
  7808. if (c2.type === Text) {
  7809. c2.el = c1.el;
  7810. }
  7811. // also inherit for comment nodes, but not placeholders (e.g. v-if which
  7812. // would have received .el during block patch)
  7813. if (c2.type === Comment && !c2.el) {
  7814. c2.el = c1.el;
  7815. }
  7816. }
  7817. }
  7818. }
  7819. // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
  7820. function getSequence(arr) {
  7821. const p = arr.slice();
  7822. const result = [0];
  7823. let i, j, u, v, c;
  7824. const len = arr.length;
  7825. for (i = 0; i < len; i++) {
  7826. const arrI = arr[i];
  7827. if (arrI !== 0) {
  7828. j = result[result.length - 1];
  7829. if (arr[j] < arrI) {
  7830. p[i] = j;
  7831. result.push(i);
  7832. continue;
  7833. }
  7834. u = 0;
  7835. v = result.length - 1;
  7836. while (u < v) {
  7837. c = (u + v) >> 1;
  7838. if (arr[result[c]] < arrI) {
  7839. u = c + 1;
  7840. }
  7841. else {
  7842. v = c;
  7843. }
  7844. }
  7845. if (arrI < arr[result[u]]) {
  7846. if (u > 0) {
  7847. p[i] = result[u - 1];
  7848. }
  7849. result[u] = i;
  7850. }
  7851. }
  7852. }
  7853. u = result.length;
  7854. v = result[u - 1];
  7855. while (u-- > 0) {
  7856. result[u] = v;
  7857. v = p[v];
  7858. }
  7859. return result;
  7860. }
  7861. const isTeleport = (type) => type.__isTeleport;
  7862. const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
  7863. const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
  7864. const resolveTarget = (props, select) => {
  7865. const targetSelector = props && props.to;
  7866. if (isString(targetSelector)) {
  7867. if (!select) {
  7868. warn(`Current renderer does not support string target for Teleports. ` +
  7869. `(missing querySelector renderer option)`);
  7870. return null;
  7871. }
  7872. else {
  7873. const target = select(targetSelector);
  7874. if (!target) {
  7875. warn(`Failed to locate Teleport target with selector "${targetSelector}". ` +
  7876. `Note the target element must exist before the component is mounted - ` +
  7877. `i.e. the target cannot be rendered by the component itself, and ` +
  7878. `ideally should be outside of the entire Vue component tree.`);
  7879. }
  7880. return target;
  7881. }
  7882. }
  7883. else {
  7884. if (!targetSelector && !isTeleportDisabled(props)) {
  7885. warn(`Invalid Teleport target: ${targetSelector}`);
  7886. }
  7887. return targetSelector;
  7888. }
  7889. };
  7890. const TeleportImpl = {
  7891. __isTeleport: true,
  7892. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
  7893. const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
  7894. const disabled = isTeleportDisabled(n2.props);
  7895. let { shapeFlag, children, dynamicChildren } = n2;
  7896. // #3302
  7897. // HMR updated, force full diff
  7898. if (isHmrUpdating) {
  7899. optimized = false;
  7900. dynamicChildren = null;
  7901. }
  7902. if (n1 == null) {
  7903. // insert anchors in the main view
  7904. const placeholder = (n2.el = createComment('teleport start')
  7905. );
  7906. const mainAnchor = (n2.anchor = createComment('teleport end')
  7907. );
  7908. insert(placeholder, container, anchor);
  7909. insert(mainAnchor, container, anchor);
  7910. const target = (n2.target = resolveTarget(n2.props, querySelector));
  7911. const targetAnchor = (n2.targetAnchor = createText(''));
  7912. if (target) {
  7913. insert(targetAnchor, target);
  7914. // #2652 we could be teleporting from a non-SVG tree into an SVG tree
  7915. isSVG = isSVG || isTargetSVG(target);
  7916. }
  7917. else if (!disabled) {
  7918. warn('Invalid Teleport target on mount:', target, `(${typeof target})`);
  7919. }
  7920. const mount = (container, anchor) => {
  7921. // Teleport *always* has Array children. This is enforced in both the
  7922. // compiler and vnode children normalization.
  7923. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7924. mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7925. }
  7926. };
  7927. if (disabled) {
  7928. mount(container, mainAnchor);
  7929. }
  7930. else if (target) {
  7931. mount(target, targetAnchor);
  7932. }
  7933. }
  7934. else {
  7935. // update content
  7936. n2.el = n1.el;
  7937. const mainAnchor = (n2.anchor = n1.anchor);
  7938. const target = (n2.target = n1.target);
  7939. const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
  7940. const wasDisabled = isTeleportDisabled(n1.props);
  7941. const currentContainer = wasDisabled ? container : target;
  7942. const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
  7943. isSVG = isSVG || isTargetSVG(target);
  7944. if (dynamicChildren) {
  7945. // fast path when the teleport happens to be a block root
  7946. patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
  7947. // even in block tree mode we need to make sure all root-level nodes
  7948. // in the teleport inherit previous DOM references so that they can
  7949. // be moved in future patches.
  7950. traverseStaticChildren(n1, n2, true);
  7951. }
  7952. else if (!optimized) {
  7953. patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
  7954. }
  7955. if (disabled) {
  7956. if (!wasDisabled) {
  7957. // enabled -> disabled
  7958. // move into main container
  7959. moveTeleport(n2, container, mainAnchor, internals, 1 /* TeleportMoveTypes.TOGGLE */);
  7960. }
  7961. }
  7962. else {
  7963. // target changed
  7964. if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
  7965. const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
  7966. if (nextTarget) {
  7967. moveTeleport(n2, nextTarget, null, internals, 0 /* TeleportMoveTypes.TARGET_CHANGE */);
  7968. }
  7969. else {
  7970. warn('Invalid Teleport target on update:', target, `(${typeof target})`);
  7971. }
  7972. }
  7973. else if (wasDisabled) {
  7974. // disabled -> enabled
  7975. // move into teleport target
  7976. moveTeleport(n2, target, targetAnchor, internals, 1 /* TeleportMoveTypes.TOGGLE */);
  7977. }
  7978. }
  7979. }
  7980. updateCssVars(n2);
  7981. },
  7982. remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
  7983. const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
  7984. if (target) {
  7985. hostRemove(targetAnchor);
  7986. }
  7987. // an unmounted teleport should always remove its children if not disabled
  7988. if (doRemove || !isTeleportDisabled(props)) {
  7989. hostRemove(anchor);
  7990. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  7991. for (let i = 0; i < children.length; i++) {
  7992. const child = children[i];
  7993. unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
  7994. }
  7995. }
  7996. }
  7997. },
  7998. move: moveTeleport,
  7999. hydrate: hydrateTeleport
  8000. };
  8001. function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* TeleportMoveTypes.REORDER */) {
  8002. // move target anchor if this is a target change.
  8003. if (moveType === 0 /* TeleportMoveTypes.TARGET_CHANGE */) {
  8004. insert(vnode.targetAnchor, container, parentAnchor);
  8005. }
  8006. const { el, anchor, shapeFlag, children, props } = vnode;
  8007. const isReorder = moveType === 2 /* TeleportMoveTypes.REORDER */;
  8008. // move main view anchor if this is a re-order.
  8009. if (isReorder) {
  8010. insert(el, container, parentAnchor);
  8011. }
  8012. // if this is a re-order and teleport is enabled (content is in target)
  8013. // do not move children. So the opposite is: only move children if this
  8014. // is not a reorder, or the teleport is disabled
  8015. if (!isReorder || isTeleportDisabled(props)) {
  8016. // Teleport has either Array children or no children.
  8017. if (shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  8018. for (let i = 0; i < children.length; i++) {
  8019. move(children[i], container, parentAnchor, 2 /* MoveType.REORDER */);
  8020. }
  8021. }
  8022. }
  8023. // move main view anchor if this is a re-order.
  8024. if (isReorder) {
  8025. insert(anchor, container, parentAnchor);
  8026. }
  8027. }
  8028. function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
  8029. const target = (vnode.target = resolveTarget(vnode.props, querySelector));
  8030. if (target) {
  8031. // if multiple teleports rendered to the same target element, we need to
  8032. // pick up from where the last teleport finished instead of the first node
  8033. const targetNode = target._lpa || target.firstChild;
  8034. if (vnode.shapeFlag & 16 /* ShapeFlags.ARRAY_CHILDREN */) {
  8035. if (isTeleportDisabled(vnode.props)) {
  8036. vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
  8037. vnode.targetAnchor = targetNode;
  8038. }
  8039. else {
  8040. vnode.anchor = nextSibling(node);
  8041. // lookahead until we find the target anchor
  8042. // we cannot rely on return value of hydrateChildren() because there
  8043. // could be nested teleports
  8044. let targetAnchor = targetNode;
  8045. while (targetAnchor) {
  8046. targetAnchor = nextSibling(targetAnchor);
  8047. if (targetAnchor &&
  8048. targetAnchor.nodeType === 8 &&
  8049. targetAnchor.data === 'teleport anchor') {
  8050. vnode.targetAnchor = targetAnchor;
  8051. target._lpa =
  8052. vnode.targetAnchor && nextSibling(vnode.targetAnchor);
  8053. break;
  8054. }
  8055. }
  8056. hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
  8057. }
  8058. }
  8059. updateCssVars(vnode);
  8060. }
  8061. return vnode.anchor && nextSibling(vnode.anchor);
  8062. }
  8063. // Force-casted public typing for h and TSX props inference
  8064. const Teleport = TeleportImpl;
  8065. function updateCssVars(vnode) {
  8066. // presence of .ut method indicates owner component uses css vars.
  8067. // code path here can assume browser environment.
  8068. const ctx = vnode.ctx;
  8069. if (ctx && ctx.ut) {
  8070. let node = vnode.children[0].el;
  8071. while (node !== vnode.targetAnchor) {
  8072. if (node.nodeType === 1)
  8073. node.setAttribute('data-v-owner', ctx.uid);
  8074. node = node.nextSibling;
  8075. }
  8076. ctx.ut();
  8077. }
  8078. }
  8079. const Fragment = Symbol('Fragment' );
  8080. const Text = Symbol('Text' );
  8081. const Comment = Symbol('Comment' );
  8082. const Static = Symbol('Static' );
  8083. // Since v-if and v-for are the two possible ways node structure can dynamically
  8084. // change, once we consider v-if branches and each v-for fragment a block, we
  8085. // can divide a template into nested blocks, and within each block the node
  8086. // structure would be stable. This allows us to skip most children diffing
  8087. // and only worry about the dynamic nodes (indicated by patch flags).
  8088. const blockStack = [];
  8089. let currentBlock = null;
  8090. /**
  8091. * Open a block.
  8092. * This must be called before `createBlock`. It cannot be part of `createBlock`
  8093. * because the children of the block are evaluated before `createBlock` itself
  8094. * is called. The generated code typically looks like this:
  8095. *
  8096. * ```js
  8097. * function render() {
  8098. * return (openBlock(),createBlock('div', null, [...]))
  8099. * }
  8100. * ```
  8101. * disableTracking is true when creating a v-for fragment block, since a v-for
  8102. * fragment always diffs its children.
  8103. *
  8104. * @private
  8105. */
  8106. function openBlock(disableTracking = false) {
  8107. blockStack.push((currentBlock = disableTracking ? null : []));
  8108. }
  8109. function closeBlock() {
  8110. blockStack.pop();
  8111. currentBlock = blockStack[blockStack.length - 1] || null;
  8112. }
  8113. // Whether we should be tracking dynamic child nodes inside a block.
  8114. // Only tracks when this value is > 0
  8115. // We are not using a simple boolean because this value may need to be
  8116. // incremented/decremented by nested usage of v-once (see below)
  8117. let isBlockTreeEnabled = 1;
  8118. /**
  8119. * Block tracking sometimes needs to be disabled, for example during the
  8120. * creation of a tree that needs to be cached by v-once. The compiler generates
  8121. * code like this:
  8122. *
  8123. * ``` js
  8124. * _cache[1] || (
  8125. * setBlockTracking(-1),
  8126. * _cache[1] = createVNode(...),
  8127. * setBlockTracking(1),
  8128. * _cache[1]
  8129. * )
  8130. * ```
  8131. *
  8132. * @private
  8133. */
  8134. function setBlockTracking(value) {
  8135. isBlockTreeEnabled += value;
  8136. }
  8137. function setupBlock(vnode) {
  8138. // save current block children on the block vnode
  8139. vnode.dynamicChildren =
  8140. isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
  8141. // close block
  8142. closeBlock();
  8143. // a block is always going to be patched, so track it as a child of its
  8144. // parent block
  8145. if (isBlockTreeEnabled > 0 && currentBlock) {
  8146. currentBlock.push(vnode);
  8147. }
  8148. return vnode;
  8149. }
  8150. /**
  8151. * @private
  8152. */
  8153. function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
  8154. return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
  8155. }
  8156. /**
  8157. * Create a block root vnode. Takes the same exact arguments as `createVNode`.
  8158. * A block root keeps track of dynamic nodes within the block in the
  8159. * `dynamicChildren` array.
  8160. *
  8161. * @private
  8162. */
  8163. function createBlock(type, props, children, patchFlag, dynamicProps) {
  8164. return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
  8165. }
  8166. function isVNode(value) {
  8167. return value ? value.__v_isVNode === true : false;
  8168. }
  8169. function isSameVNodeType(n1, n2) {
  8170. if (n2.shapeFlag & 6 /* ShapeFlags.COMPONENT */ &&
  8171. hmrDirtyComponents.has(n2.type)) {
  8172. // #7042, ensure the vnode being unmounted during HMR
  8173. // bitwise operations to remove keep alive flags
  8174. n1.shapeFlag &= ~256 /* ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE */;
  8175. n2.shapeFlag &= ~512 /* ShapeFlags.COMPONENT_KEPT_ALIVE */;
  8176. // HMR only: if the component has been hot-updated, force a reload.
  8177. return false;
  8178. }
  8179. return n1.type === n2.type && n1.key === n2.key;
  8180. }
  8181. let vnodeArgsTransformer;
  8182. /**
  8183. * Internal API for registering an arguments transform for createVNode
  8184. * used for creating stubs in the test-utils
  8185. * It is *internal* but needs to be exposed for test-utils to pick up proper
  8186. * typings
  8187. */
  8188. function transformVNodeArgs(transformer) {
  8189. vnodeArgsTransformer = transformer;
  8190. }
  8191. const createVNodeWithArgsTransform = (...args) => {
  8192. return _createVNode(...(vnodeArgsTransformer
  8193. ? vnodeArgsTransformer(args, currentRenderingInstance)
  8194. : args));
  8195. };
  8196. const InternalObjectKey = `__vInternal`;
  8197. const normalizeKey = ({ key }) => key != null ? key : null;
  8198. const normalizeRef = ({ ref, ref_key, ref_for }) => {
  8199. return (ref != null
  8200. ? isString(ref) || isRef(ref) || isFunction(ref)
  8201. ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
  8202. : ref
  8203. : null);
  8204. };
  8205. function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ShapeFlags.ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
  8206. const vnode = {
  8207. __v_isVNode: true,
  8208. __v_skip: true,
  8209. type,
  8210. props,
  8211. key: props && normalizeKey(props),
  8212. ref: props && normalizeRef(props),
  8213. scopeId: currentScopeId,
  8214. slotScopeIds: null,
  8215. children,
  8216. component: null,
  8217. suspense: null,
  8218. ssContent: null,
  8219. ssFallback: null,
  8220. dirs: null,
  8221. transition: null,
  8222. el: null,
  8223. anchor: null,
  8224. target: null,
  8225. targetAnchor: null,
  8226. staticCount: 0,
  8227. shapeFlag,
  8228. patchFlag,
  8229. dynamicProps,
  8230. dynamicChildren: null,
  8231. appContext: null,
  8232. ctx: currentRenderingInstance
  8233. };
  8234. if (needFullChildrenNormalization) {
  8235. normalizeChildren(vnode, children);
  8236. // normalize suspense children
  8237. if (shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  8238. type.normalize(vnode);
  8239. }
  8240. }
  8241. else if (children) {
  8242. // compiled element vnode - if children is passed, only possible types are
  8243. // string or Array.
  8244. vnode.shapeFlag |= isString(children)
  8245. ? 8 /* ShapeFlags.TEXT_CHILDREN */
  8246. : 16 /* ShapeFlags.ARRAY_CHILDREN */;
  8247. }
  8248. // validate key
  8249. if (vnode.key !== vnode.key) {
  8250. warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
  8251. }
  8252. // track vnode for block tree
  8253. if (isBlockTreeEnabled > 0 &&
  8254. // avoid a block node from tracking itself
  8255. !isBlockNode &&
  8256. // has current parent block
  8257. currentBlock &&
  8258. // presence of a patch flag indicates this node needs patching on updates.
  8259. // component nodes also should always be patched, because even if the
  8260. // component doesn't need to update, it needs to persist the instance on to
  8261. // the next vnode so that it can be properly unmounted later.
  8262. (vnode.patchFlag > 0 || shapeFlag & 6 /* ShapeFlags.COMPONENT */) &&
  8263. // the EVENTS flag is only for hydration and if it is the only flag, the
  8264. // vnode should not be considered dynamic due to handler caching.
  8265. vnode.patchFlag !== 32 /* PatchFlags.HYDRATE_EVENTS */) {
  8266. currentBlock.push(vnode);
  8267. }
  8268. return vnode;
  8269. }
  8270. const createVNode = (createVNodeWithArgsTransform );
  8271. function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
  8272. if (!type || type === NULL_DYNAMIC_COMPONENT) {
  8273. if (!type) {
  8274. warn(`Invalid vnode type when creating vnode: ${type}.`);
  8275. }
  8276. type = Comment;
  8277. }
  8278. if (isVNode(type)) {
  8279. // createVNode receiving an existing vnode. This happens in cases like
  8280. // <component :is="vnode"/>
  8281. // #2078 make sure to merge refs during the clone instead of overwriting it
  8282. const cloned = cloneVNode(type, props, true /* mergeRef: true */);
  8283. if (children) {
  8284. normalizeChildren(cloned, children);
  8285. }
  8286. if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) {
  8287. if (cloned.shapeFlag & 6 /* ShapeFlags.COMPONENT */) {
  8288. currentBlock[currentBlock.indexOf(type)] = cloned;
  8289. }
  8290. else {
  8291. currentBlock.push(cloned);
  8292. }
  8293. }
  8294. cloned.patchFlag |= -2 /* PatchFlags.BAIL */;
  8295. return cloned;
  8296. }
  8297. // class component normalization.
  8298. if (isClassComponent(type)) {
  8299. type = type.__vccOpts;
  8300. }
  8301. // class & style normalization.
  8302. if (props) {
  8303. // for reactive or proxy objects, we need to clone it to enable mutation.
  8304. props = guardReactiveProps(props);
  8305. let { class: klass, style } = props;
  8306. if (klass && !isString(klass)) {
  8307. props.class = normalizeClass(klass);
  8308. }
  8309. if (isObject(style)) {
  8310. // reactive state objects need to be cloned since they are likely to be
  8311. // mutated
  8312. if (isProxy(style) && !isArray(style)) {
  8313. style = extend({}, style);
  8314. }
  8315. props.style = normalizeStyle(style);
  8316. }
  8317. }
  8318. // encode the vnode type information into a bitmap
  8319. const shapeFlag = isString(type)
  8320. ? 1 /* ShapeFlags.ELEMENT */
  8321. : isSuspense(type)
  8322. ? 128 /* ShapeFlags.SUSPENSE */
  8323. : isTeleport(type)
  8324. ? 64 /* ShapeFlags.TELEPORT */
  8325. : isObject(type)
  8326. ? 4 /* ShapeFlags.STATEFUL_COMPONENT */
  8327. : isFunction(type)
  8328. ? 2 /* ShapeFlags.FUNCTIONAL_COMPONENT */
  8329. : 0;
  8330. if (shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */ && isProxy(type)) {
  8331. type = toRaw(type);
  8332. warn(`Vue received a Component which was made a reactive object. This can ` +
  8333. `lead to unnecessary performance overhead, and should be avoided by ` +
  8334. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  8335. `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
  8336. }
  8337. return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
  8338. }
  8339. function guardReactiveProps(props) {
  8340. if (!props)
  8341. return null;
  8342. return isProxy(props) || InternalObjectKey in props
  8343. ? extend({}, props)
  8344. : props;
  8345. }
  8346. function cloneVNode(vnode, extraProps, mergeRef = false) {
  8347. // This is intentionally NOT using spread or extend to avoid the runtime
  8348. // key enumeration cost.
  8349. const { props, ref, patchFlag, children } = vnode;
  8350. const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
  8351. const cloned = {
  8352. __v_isVNode: true,
  8353. __v_skip: true,
  8354. type: vnode.type,
  8355. props: mergedProps,
  8356. key: mergedProps && normalizeKey(mergedProps),
  8357. ref: extraProps && extraProps.ref
  8358. ? // #2078 in the case of <component :is="vnode" ref="extra"/>
  8359. // if the vnode itself already has a ref, cloneVNode will need to merge
  8360. // the refs so the single vnode can be set on multiple refs
  8361. mergeRef && ref
  8362. ? isArray(ref)
  8363. ? ref.concat(normalizeRef(extraProps))
  8364. : [ref, normalizeRef(extraProps)]
  8365. : normalizeRef(extraProps)
  8366. : ref,
  8367. scopeId: vnode.scopeId,
  8368. slotScopeIds: vnode.slotScopeIds,
  8369. children: patchFlag === -1 /* PatchFlags.HOISTED */ && isArray(children)
  8370. ? children.map(deepCloneVNode)
  8371. : children,
  8372. target: vnode.target,
  8373. targetAnchor: vnode.targetAnchor,
  8374. staticCount: vnode.staticCount,
  8375. shapeFlag: vnode.shapeFlag,
  8376. // if the vnode is cloned with extra props, we can no longer assume its
  8377. // existing patch flag to be reliable and need to add the FULL_PROPS flag.
  8378. // note: preserve flag for fragments since they use the flag for children
  8379. // fast paths only.
  8380. patchFlag: extraProps && vnode.type !== Fragment
  8381. ? patchFlag === -1 // hoisted node
  8382. ? 16 /* PatchFlags.FULL_PROPS */
  8383. : patchFlag | 16 /* PatchFlags.FULL_PROPS */
  8384. : patchFlag,
  8385. dynamicProps: vnode.dynamicProps,
  8386. dynamicChildren: vnode.dynamicChildren,
  8387. appContext: vnode.appContext,
  8388. dirs: vnode.dirs,
  8389. transition: vnode.transition,
  8390. // These should technically only be non-null on mounted VNodes. However,
  8391. // they *should* be copied for kept-alive vnodes. So we just always copy
  8392. // them since them being non-null during a mount doesn't affect the logic as
  8393. // they will simply be overwritten.
  8394. component: vnode.component,
  8395. suspense: vnode.suspense,
  8396. ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
  8397. ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
  8398. el: vnode.el,
  8399. anchor: vnode.anchor,
  8400. ctx: vnode.ctx,
  8401. ce: vnode.ce
  8402. };
  8403. return cloned;
  8404. }
  8405. /**
  8406. * Dev only, for HMR of hoisted vnodes reused in v-for
  8407. * https://github.com/vitejs/vite/issues/2022
  8408. */
  8409. function deepCloneVNode(vnode) {
  8410. const cloned = cloneVNode(vnode);
  8411. if (isArray(vnode.children)) {
  8412. cloned.children = vnode.children.map(deepCloneVNode);
  8413. }
  8414. return cloned;
  8415. }
  8416. /**
  8417. * @private
  8418. */
  8419. function createTextVNode(text = ' ', flag = 0) {
  8420. return createVNode(Text, null, text, flag);
  8421. }
  8422. /**
  8423. * @private
  8424. */
  8425. function createStaticVNode(content, numberOfNodes) {
  8426. // A static vnode can contain multiple stringified elements, and the number
  8427. // of elements is necessary for hydration.
  8428. const vnode = createVNode(Static, null, content);
  8429. vnode.staticCount = numberOfNodes;
  8430. return vnode;
  8431. }
  8432. /**
  8433. * @private
  8434. */
  8435. function createCommentVNode(text = '',
  8436. // when used as the v-else branch, the comment node must be created as a
  8437. // block to ensure correct updates.
  8438. asBlock = false) {
  8439. return asBlock
  8440. ? (openBlock(), createBlock(Comment, null, text))
  8441. : createVNode(Comment, null, text);
  8442. }
  8443. function normalizeVNode(child) {
  8444. if (child == null || typeof child === 'boolean') {
  8445. // empty placeholder
  8446. return createVNode(Comment);
  8447. }
  8448. else if (isArray(child)) {
  8449. // fragment
  8450. return createVNode(Fragment, null,
  8451. // #3666, avoid reference pollution when reusing vnode
  8452. child.slice());
  8453. }
  8454. else if (typeof child === 'object') {
  8455. // already vnode, this should be the most common since compiled templates
  8456. // always produce all-vnode children arrays
  8457. return cloneIfMounted(child);
  8458. }
  8459. else {
  8460. // strings and numbers
  8461. return createVNode(Text, null, String(child));
  8462. }
  8463. }
  8464. // optimized normalization for template-compiled render fns
  8465. function cloneIfMounted(child) {
  8466. return (child.el === null && child.patchFlag !== -1 /* PatchFlags.HOISTED */) ||
  8467. child.memo
  8468. ? child
  8469. : cloneVNode(child);
  8470. }
  8471. function normalizeChildren(vnode, children) {
  8472. let type = 0;
  8473. const { shapeFlag } = vnode;
  8474. if (children == null) {
  8475. children = null;
  8476. }
  8477. else if (isArray(children)) {
  8478. type = 16 /* ShapeFlags.ARRAY_CHILDREN */;
  8479. }
  8480. else if (typeof children === 'object') {
  8481. if (shapeFlag & (1 /* ShapeFlags.ELEMENT */ | 64 /* ShapeFlags.TELEPORT */)) {
  8482. // Normalize slot to plain children for plain element and Teleport
  8483. const slot = children.default;
  8484. if (slot) {
  8485. // _c marker is added by withCtx() indicating this is a compiled slot
  8486. slot._c && (slot._d = false);
  8487. normalizeChildren(vnode, slot());
  8488. slot._c && (slot._d = true);
  8489. }
  8490. return;
  8491. }
  8492. else {
  8493. type = 32 /* ShapeFlags.SLOTS_CHILDREN */;
  8494. const slotFlag = children._;
  8495. if (!slotFlag && !(InternalObjectKey in children)) {
  8496. children._ctx = currentRenderingInstance;
  8497. }
  8498. else if (slotFlag === 3 /* SlotFlags.FORWARDED */ && currentRenderingInstance) {
  8499. // a child component receives forwarded slots from the parent.
  8500. // its slot type is determined by its parent's slot type.
  8501. if (currentRenderingInstance.slots._ === 1 /* SlotFlags.STABLE */) {
  8502. children._ = 1 /* SlotFlags.STABLE */;
  8503. }
  8504. else {
  8505. children._ = 2 /* SlotFlags.DYNAMIC */;
  8506. vnode.patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  8507. }
  8508. }
  8509. }
  8510. }
  8511. else if (isFunction(children)) {
  8512. children = { default: children, _ctx: currentRenderingInstance };
  8513. type = 32 /* ShapeFlags.SLOTS_CHILDREN */;
  8514. }
  8515. else {
  8516. children = String(children);
  8517. // force teleport children to array so it can be moved around
  8518. if (shapeFlag & 64 /* ShapeFlags.TELEPORT */) {
  8519. type = 16 /* ShapeFlags.ARRAY_CHILDREN */;
  8520. children = [createTextVNode(children)];
  8521. }
  8522. else {
  8523. type = 8 /* ShapeFlags.TEXT_CHILDREN */;
  8524. }
  8525. }
  8526. vnode.children = children;
  8527. vnode.shapeFlag |= type;
  8528. }
  8529. function mergeProps(...args) {
  8530. const ret = {};
  8531. for (let i = 0; i < args.length; i++) {
  8532. const toMerge = args[i];
  8533. for (const key in toMerge) {
  8534. if (key === 'class') {
  8535. if (ret.class !== toMerge.class) {
  8536. ret.class = normalizeClass([ret.class, toMerge.class]);
  8537. }
  8538. }
  8539. else if (key === 'style') {
  8540. ret.style = normalizeStyle([ret.style, toMerge.style]);
  8541. }
  8542. else if (isOn(key)) {
  8543. const existing = ret[key];
  8544. const incoming = toMerge[key];
  8545. if (incoming &&
  8546. existing !== incoming &&
  8547. !(isArray(existing) && existing.includes(incoming))) {
  8548. ret[key] = existing
  8549. ? [].concat(existing, incoming)
  8550. : incoming;
  8551. }
  8552. }
  8553. else if (key !== '') {
  8554. ret[key] = toMerge[key];
  8555. }
  8556. }
  8557. }
  8558. return ret;
  8559. }
  8560. function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
  8561. callWithAsyncErrorHandling(hook, instance, 7 /* ErrorCodes.VNODE_HOOK */, [
  8562. vnode,
  8563. prevVNode
  8564. ]);
  8565. }
  8566. const emptyAppContext = createAppContext();
  8567. let uid = 0;
  8568. function createComponentInstance(vnode, parent, suspense) {
  8569. const type = vnode.type;
  8570. // inherit parent app context - or - if root, adopt from root vnode
  8571. const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
  8572. const instance = {
  8573. uid: uid++,
  8574. vnode,
  8575. type,
  8576. parent,
  8577. appContext,
  8578. root: null,
  8579. next: null,
  8580. subTree: null,
  8581. effect: null,
  8582. update: null,
  8583. scope: new EffectScope(true /* detached */),
  8584. render: null,
  8585. proxy: null,
  8586. exposed: null,
  8587. exposeProxy: null,
  8588. withProxy: null,
  8589. provides: parent ? parent.provides : Object.create(appContext.provides),
  8590. accessCache: null,
  8591. renderCache: [],
  8592. // local resolved assets
  8593. components: null,
  8594. directives: null,
  8595. // resolved props and emits options
  8596. propsOptions: normalizePropsOptions(type, appContext),
  8597. emitsOptions: normalizeEmitsOptions(type, appContext),
  8598. // emit
  8599. emit: null,
  8600. emitted: null,
  8601. // props default value
  8602. propsDefaults: EMPTY_OBJ,
  8603. // inheritAttrs
  8604. inheritAttrs: type.inheritAttrs,
  8605. // state
  8606. ctx: EMPTY_OBJ,
  8607. data: EMPTY_OBJ,
  8608. props: EMPTY_OBJ,
  8609. attrs: EMPTY_OBJ,
  8610. slots: EMPTY_OBJ,
  8611. refs: EMPTY_OBJ,
  8612. setupState: EMPTY_OBJ,
  8613. setupContext: null,
  8614. // suspense related
  8615. suspense,
  8616. suspenseId: suspense ? suspense.pendingId : 0,
  8617. asyncDep: null,
  8618. asyncResolved: false,
  8619. // lifecycle hooks
  8620. // not using enums here because it results in computed properties
  8621. isMounted: false,
  8622. isUnmounted: false,
  8623. isDeactivated: false,
  8624. bc: null,
  8625. c: null,
  8626. bm: null,
  8627. m: null,
  8628. bu: null,
  8629. u: null,
  8630. um: null,
  8631. bum: null,
  8632. da: null,
  8633. a: null,
  8634. rtg: null,
  8635. rtc: null,
  8636. ec: null,
  8637. sp: null
  8638. };
  8639. {
  8640. instance.ctx = createDevRenderContext(instance);
  8641. }
  8642. instance.root = parent ? parent.root : instance;
  8643. instance.emit = emit.bind(null, instance);
  8644. // apply custom element special handling
  8645. if (vnode.ce) {
  8646. vnode.ce(instance);
  8647. }
  8648. return instance;
  8649. }
  8650. let currentInstance = null;
  8651. const getCurrentInstance = () => currentInstance || currentRenderingInstance;
  8652. const setCurrentInstance = (instance) => {
  8653. currentInstance = instance;
  8654. instance.scope.on();
  8655. };
  8656. const unsetCurrentInstance = () => {
  8657. currentInstance && currentInstance.scope.off();
  8658. currentInstance = null;
  8659. };
  8660. const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
  8661. function validateComponentName(name, config) {
  8662. const appIsNativeTag = config.isNativeTag || NO;
  8663. if (isBuiltInTag(name) || appIsNativeTag(name)) {
  8664. warn('Do not use built-in or reserved HTML elements as component id: ' + name);
  8665. }
  8666. }
  8667. function isStatefulComponent(instance) {
  8668. return instance.vnode.shapeFlag & 4 /* ShapeFlags.STATEFUL_COMPONENT */;
  8669. }
  8670. let isInSSRComponentSetup = false;
  8671. function setupComponent(instance, isSSR = false) {
  8672. isInSSRComponentSetup = isSSR;
  8673. const { props, children } = instance.vnode;
  8674. const isStateful = isStatefulComponent(instance);
  8675. initProps(instance, props, isStateful, isSSR);
  8676. initSlots(instance, children);
  8677. const setupResult = isStateful
  8678. ? setupStatefulComponent(instance, isSSR)
  8679. : undefined;
  8680. isInSSRComponentSetup = false;
  8681. return setupResult;
  8682. }
  8683. function setupStatefulComponent(instance, isSSR) {
  8684. var _a;
  8685. const Component = instance.type;
  8686. {
  8687. if (Component.name) {
  8688. validateComponentName(Component.name, instance.appContext.config);
  8689. }
  8690. if (Component.components) {
  8691. const names = Object.keys(Component.components);
  8692. for (let i = 0; i < names.length; i++) {
  8693. validateComponentName(names[i], instance.appContext.config);
  8694. }
  8695. }
  8696. if (Component.directives) {
  8697. const names = Object.keys(Component.directives);
  8698. for (let i = 0; i < names.length; i++) {
  8699. validateDirectiveName(names[i]);
  8700. }
  8701. }
  8702. if (Component.compilerOptions && isRuntimeOnly()) {
  8703. warn(`"compilerOptions" is only supported when using a build of Vue that ` +
  8704. `includes the runtime compiler. Since you are using a runtime-only ` +
  8705. `build, the options should be passed via your build tool config instead.`);
  8706. }
  8707. }
  8708. // 0. create render proxy property access cache
  8709. instance.accessCache = Object.create(null);
  8710. // 1. create public instance / render proxy
  8711. // also mark it raw so it's never observed
  8712. instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
  8713. {
  8714. exposePropsOnRenderContext(instance);
  8715. }
  8716. // 2. call setup()
  8717. const { setup } = Component;
  8718. if (setup) {
  8719. const setupContext = (instance.setupContext =
  8720. setup.length > 1 ? createSetupContext(instance) : null);
  8721. setCurrentInstance(instance);
  8722. pauseTracking();
  8723. const setupResult = callWithErrorHandling(setup, instance, 0 /* ErrorCodes.SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
  8724. resetTracking();
  8725. unsetCurrentInstance();
  8726. if (isPromise(setupResult)) {
  8727. setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
  8728. if (isSSR) {
  8729. // return the promise so server-renderer can wait on it
  8730. return setupResult
  8731. .then((resolvedResult) => {
  8732. handleSetupResult(instance, resolvedResult, isSSR);
  8733. })
  8734. .catch(e => {
  8735. handleError(e, instance, 0 /* ErrorCodes.SETUP_FUNCTION */);
  8736. });
  8737. }
  8738. else {
  8739. // async setup returned Promise.
  8740. // bail here and wait for re-entry.
  8741. instance.asyncDep = setupResult;
  8742. if (!instance.suspense) {
  8743. const name = (_a = Component.name) !== null && _a !== void 0 ? _a : 'Anonymous';
  8744. warn(`Component <${name}>: setup function returned a promise, but no ` +
  8745. `<Suspense> boundary was found in the parent component tree. ` +
  8746. `A component with async setup() must be nested in a <Suspense> ` +
  8747. `in order to be rendered.`);
  8748. }
  8749. }
  8750. }
  8751. else {
  8752. handleSetupResult(instance, setupResult, isSSR);
  8753. }
  8754. }
  8755. else {
  8756. finishComponentSetup(instance, isSSR);
  8757. }
  8758. }
  8759. function handleSetupResult(instance, setupResult, isSSR) {
  8760. if (isFunction(setupResult)) {
  8761. // setup returned an inline render function
  8762. {
  8763. instance.render = setupResult;
  8764. }
  8765. }
  8766. else if (isObject(setupResult)) {
  8767. if (isVNode(setupResult)) {
  8768. warn(`setup() should not return VNodes directly - ` +
  8769. `return a render function instead.`);
  8770. }
  8771. // setup returned bindings.
  8772. // assuming a render function compiled from template is present.
  8773. {
  8774. instance.devtoolsRawSetupState = setupResult;
  8775. }
  8776. instance.setupState = proxyRefs(setupResult);
  8777. {
  8778. exposeSetupStateOnRenderContext(instance);
  8779. }
  8780. }
  8781. else if (setupResult !== undefined) {
  8782. warn(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
  8783. }
  8784. finishComponentSetup(instance, isSSR);
  8785. }
  8786. let compile$1;
  8787. let installWithProxy;
  8788. /**
  8789. * For runtime-dom to register the compiler.
  8790. * Note the exported method uses any to avoid d.ts relying on the compiler types.
  8791. */
  8792. function registerRuntimeCompiler(_compile) {
  8793. compile$1 = _compile;
  8794. installWithProxy = i => {
  8795. if (i.render._rc) {
  8796. i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
  8797. }
  8798. };
  8799. }
  8800. // dev only
  8801. const isRuntimeOnly = () => !compile$1;
  8802. function finishComponentSetup(instance, isSSR, skipOptions) {
  8803. const Component = instance.type;
  8804. // template / render function normalization
  8805. // could be already set when returned from setup()
  8806. if (!instance.render) {
  8807. // only do on-the-fly compile if not in SSR - SSR on-the-fly compilation
  8808. // is done by server-renderer
  8809. if (!isSSR && compile$1 && !Component.render) {
  8810. const template = Component.template ||
  8811. resolveMergedOptions(instance).template;
  8812. if (template) {
  8813. {
  8814. startMeasure(instance, `compile`);
  8815. }
  8816. const { isCustomElement, compilerOptions } = instance.appContext.config;
  8817. const { delimiters, compilerOptions: componentCompilerOptions } = Component;
  8818. const finalCompilerOptions = extend(extend({
  8819. isCustomElement,
  8820. delimiters
  8821. }, compilerOptions), componentCompilerOptions);
  8822. Component.render = compile$1(template, finalCompilerOptions);
  8823. {
  8824. endMeasure(instance, `compile`);
  8825. }
  8826. }
  8827. }
  8828. instance.render = (Component.render || NOOP);
  8829. // for runtime-compiled render functions using `with` blocks, the render
  8830. // proxy used needs a different `has` handler which is more performant and
  8831. // also only allows a whitelist of globals to fallthrough.
  8832. if (installWithProxy) {
  8833. installWithProxy(instance);
  8834. }
  8835. }
  8836. // support for 2.x options
  8837. {
  8838. setCurrentInstance(instance);
  8839. pauseTracking();
  8840. applyOptions(instance);
  8841. resetTracking();
  8842. unsetCurrentInstance();
  8843. }
  8844. // warn missing template/render
  8845. // the runtime compilation of template in SSR is done by server-render
  8846. if (!Component.render && instance.render === NOOP && !isSSR) {
  8847. /* istanbul ignore if */
  8848. if (!compile$1 && Component.template) {
  8849. warn(`Component provided template option but ` +
  8850. `runtime compilation is not supported in this build of Vue.` +
  8851. (` Use "vue.esm-browser.js" instead.`
  8852. ) /* should not happen */);
  8853. }
  8854. else {
  8855. warn(`Component is missing template or render function.`);
  8856. }
  8857. }
  8858. }
  8859. function createAttrsProxy(instance) {
  8860. return new Proxy(instance.attrs, {
  8861. get(target, key) {
  8862. markAttrsAccessed();
  8863. track(instance, "get" /* TrackOpTypes.GET */, '$attrs');
  8864. return target[key];
  8865. },
  8866. set() {
  8867. warn(`setupContext.attrs is readonly.`);
  8868. return false;
  8869. },
  8870. deleteProperty() {
  8871. warn(`setupContext.attrs is readonly.`);
  8872. return false;
  8873. }
  8874. }
  8875. );
  8876. }
  8877. function createSetupContext(instance) {
  8878. const expose = exposed => {
  8879. {
  8880. if (instance.exposed) {
  8881. warn(`expose() should be called only once per setup().`);
  8882. }
  8883. if (exposed != null) {
  8884. let exposedType = typeof exposed;
  8885. if (exposedType === 'object') {
  8886. if (isArray(exposed)) {
  8887. exposedType = 'array';
  8888. }
  8889. else if (isRef(exposed)) {
  8890. exposedType = 'ref';
  8891. }
  8892. }
  8893. if (exposedType !== 'object') {
  8894. warn(`expose() should be passed a plain object, received ${exposedType}.`);
  8895. }
  8896. }
  8897. }
  8898. instance.exposed = exposed || {};
  8899. };
  8900. let attrs;
  8901. {
  8902. // We use getters in dev in case libs like test-utils overwrite instance
  8903. // properties (overwrites should not be done in prod)
  8904. return Object.freeze({
  8905. get attrs() {
  8906. return attrs || (attrs = createAttrsProxy(instance));
  8907. },
  8908. get slots() {
  8909. return shallowReadonly(instance.slots);
  8910. },
  8911. get emit() {
  8912. return (event, ...args) => instance.emit(event, ...args);
  8913. },
  8914. expose
  8915. });
  8916. }
  8917. }
  8918. function getExposeProxy(instance) {
  8919. if (instance.exposed) {
  8920. return (instance.exposeProxy ||
  8921. (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
  8922. get(target, key) {
  8923. if (key in target) {
  8924. return target[key];
  8925. }
  8926. else if (key in publicPropertiesMap) {
  8927. return publicPropertiesMap[key](instance);
  8928. }
  8929. },
  8930. has(target, key) {
  8931. return key in target || key in publicPropertiesMap;
  8932. }
  8933. })));
  8934. }
  8935. }
  8936. const classifyRE = /(?:^|[-_])(\w)/g;
  8937. const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
  8938. function getComponentName(Component, includeInferred = true) {
  8939. return isFunction(Component)
  8940. ? Component.displayName || Component.name
  8941. : Component.name || (includeInferred && Component.__name);
  8942. }
  8943. /* istanbul ignore next */
  8944. function formatComponentName(instance, Component, isRoot = false) {
  8945. let name = getComponentName(Component);
  8946. if (!name && Component.__file) {
  8947. const match = Component.__file.match(/([^/\\]+)\.\w+$/);
  8948. if (match) {
  8949. name = match[1];
  8950. }
  8951. }
  8952. if (!name && instance && instance.parent) {
  8953. // try to infer the name based on reverse resolution
  8954. const inferFromRegistry = (registry) => {
  8955. for (const key in registry) {
  8956. if (registry[key] === Component) {
  8957. return key;
  8958. }
  8959. }
  8960. };
  8961. name =
  8962. inferFromRegistry(instance.components ||
  8963. instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
  8964. }
  8965. return name ? classify(name) : isRoot ? `App` : `Anonymous`;
  8966. }
  8967. function isClassComponent(value) {
  8968. return isFunction(value) && '__vccOpts' in value;
  8969. }
  8970. const computed = ((getterOrOptions, debugOptions) => {
  8971. // @ts-ignore
  8972. return computed$1(getterOrOptions, debugOptions, isInSSRComponentSetup);
  8973. });
  8974. // dev only
  8975. const warnRuntimeUsage = (method) => warn(`${method}() is a compiler-hint helper that is only usable inside ` +
  8976. `<script setup> of a single file component. Its arguments should be ` +
  8977. `compiled away and passing it at runtime has no effect.`);
  8978. // implementation
  8979. function defineProps() {
  8980. {
  8981. warnRuntimeUsage(`defineProps`);
  8982. }
  8983. return null;
  8984. }
  8985. // implementation
  8986. function defineEmits() {
  8987. {
  8988. warnRuntimeUsage(`defineEmits`);
  8989. }
  8990. return null;
  8991. }
  8992. /**
  8993. * Vue `<script setup>` compiler macro for declaring a component's exposed
  8994. * instance properties when it is accessed by a parent component via template
  8995. * refs.
  8996. *
  8997. * `<script setup>` components are closed by default - i.e. variables inside
  8998. * the `<script setup>` scope is not exposed to parent unless explicitly exposed
  8999. * via `defineExpose`.
  9000. *
  9001. * This is only usable inside `<script setup>`, is compiled away in the
  9002. * output and should **not** be actually called at runtime.
  9003. */
  9004. function defineExpose(exposed) {
  9005. {
  9006. warnRuntimeUsage(`defineExpose`);
  9007. }
  9008. }
  9009. /**
  9010. * Vue `<script setup>` compiler macro for providing props default values when
  9011. * using type-based `defineProps` declaration.
  9012. *
  9013. * Example usage:
  9014. * ```ts
  9015. * withDefaults(defineProps<{
  9016. * size?: number
  9017. * labels?: string[]
  9018. * }>(), {
  9019. * size: 3,
  9020. * labels: () => ['default label']
  9021. * })
  9022. * ```
  9023. *
  9024. * This is only usable inside `<script setup>`, is compiled away in the output
  9025. * and should **not** be actually called at runtime.
  9026. */
  9027. function withDefaults(props, defaults) {
  9028. {
  9029. warnRuntimeUsage(`withDefaults`);
  9030. }
  9031. return null;
  9032. }
  9033. function useSlots() {
  9034. return getContext().slots;
  9035. }
  9036. function useAttrs() {
  9037. return getContext().attrs;
  9038. }
  9039. function getContext() {
  9040. const i = getCurrentInstance();
  9041. if (!i) {
  9042. warn(`useContext() called without active instance.`);
  9043. }
  9044. return i.setupContext || (i.setupContext = createSetupContext(i));
  9045. }
  9046. /**
  9047. * Runtime helper for merging default declarations. Imported by compiled code
  9048. * only.
  9049. * @internal
  9050. */
  9051. function mergeDefaults(raw, defaults) {
  9052. const props = isArray(raw)
  9053. ? raw.reduce((normalized, p) => ((normalized[p] = {}), normalized), {})
  9054. : raw;
  9055. for (const key in defaults) {
  9056. const opt = props[key];
  9057. if (opt) {
  9058. if (isArray(opt) || isFunction(opt)) {
  9059. props[key] = { type: opt, default: defaults[key] };
  9060. }
  9061. else {
  9062. opt.default = defaults[key];
  9063. }
  9064. }
  9065. else if (opt === null) {
  9066. props[key] = { default: defaults[key] };
  9067. }
  9068. else {
  9069. warn(`props default key "${key}" has no corresponding declaration.`);
  9070. }
  9071. }
  9072. return props;
  9073. }
  9074. /**
  9075. * Used to create a proxy for the rest element when destructuring props with
  9076. * defineProps().
  9077. * @internal
  9078. */
  9079. function createPropsRestProxy(props, excludedKeys) {
  9080. const ret = {};
  9081. for (const key in props) {
  9082. if (!excludedKeys.includes(key)) {
  9083. Object.defineProperty(ret, key, {
  9084. enumerable: true,
  9085. get: () => props[key]
  9086. });
  9087. }
  9088. }
  9089. return ret;
  9090. }
  9091. /**
  9092. * `<script setup>` helper for persisting the current instance context over
  9093. * async/await flows.
  9094. *
  9095. * `@vue/compiler-sfc` converts the following:
  9096. *
  9097. * ```ts
  9098. * const x = await foo()
  9099. * ```
  9100. *
  9101. * into:
  9102. *
  9103. * ```ts
  9104. * let __temp, __restore
  9105. * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
  9106. * ```
  9107. * @internal
  9108. */
  9109. function withAsyncContext(getAwaitable) {
  9110. const ctx = getCurrentInstance();
  9111. if (!ctx) {
  9112. warn(`withAsyncContext called without active current instance. ` +
  9113. `This is likely a bug.`);
  9114. }
  9115. let awaitable = getAwaitable();
  9116. unsetCurrentInstance();
  9117. if (isPromise(awaitable)) {
  9118. awaitable = awaitable.catch(e => {
  9119. setCurrentInstance(ctx);
  9120. throw e;
  9121. });
  9122. }
  9123. return [awaitable, () => setCurrentInstance(ctx)];
  9124. }
  9125. // Actual implementation
  9126. function h(type, propsOrChildren, children) {
  9127. const l = arguments.length;
  9128. if (l === 2) {
  9129. if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
  9130. // single vnode without props
  9131. if (isVNode(propsOrChildren)) {
  9132. return createVNode(type, null, [propsOrChildren]);
  9133. }
  9134. // props without children
  9135. return createVNode(type, propsOrChildren);
  9136. }
  9137. else {
  9138. // omit props
  9139. return createVNode(type, null, propsOrChildren);
  9140. }
  9141. }
  9142. else {
  9143. if (l > 3) {
  9144. children = Array.prototype.slice.call(arguments, 2);
  9145. }
  9146. else if (l === 3 && isVNode(children)) {
  9147. children = [children];
  9148. }
  9149. return createVNode(type, propsOrChildren, children);
  9150. }
  9151. }
  9152. const ssrContextKey = Symbol(`ssrContext` );
  9153. const useSSRContext = () => {
  9154. {
  9155. const ctx = inject(ssrContextKey);
  9156. if (!ctx) {
  9157. warn(`Server rendering context not provided. Make sure to only call ` +
  9158. `useSSRContext() conditionally in the server build.`);
  9159. }
  9160. return ctx;
  9161. }
  9162. };
  9163. function initCustomFormatter() {
  9164. /* eslint-disable no-restricted-globals */
  9165. if (typeof window === 'undefined') {
  9166. return;
  9167. }
  9168. const vueStyle = { style: 'color:#3ba776' };
  9169. const numberStyle = { style: 'color:#0b1bc9' };
  9170. const stringStyle = { style: 'color:#b62e24' };
  9171. const keywordStyle = { style: 'color:#9d288c' };
  9172. // custom formatter for Chrome
  9173. // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
  9174. const formatter = {
  9175. header(obj) {
  9176. // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
  9177. if (!isObject(obj)) {
  9178. return null;
  9179. }
  9180. if (obj.__isVue) {
  9181. return ['div', vueStyle, `VueInstance`];
  9182. }
  9183. else if (isRef(obj)) {
  9184. return [
  9185. 'div',
  9186. {},
  9187. ['span', vueStyle, genRefFlag(obj)],
  9188. '<',
  9189. formatValue(obj.value),
  9190. `>`
  9191. ];
  9192. }
  9193. else if (isReactive(obj)) {
  9194. return [
  9195. 'div',
  9196. {},
  9197. ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'],
  9198. '<',
  9199. formatValue(obj),
  9200. `>${isReadonly(obj) ? ` (readonly)` : ``}`
  9201. ];
  9202. }
  9203. else if (isReadonly(obj)) {
  9204. return [
  9205. 'div',
  9206. {},
  9207. ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'],
  9208. '<',
  9209. formatValue(obj),
  9210. '>'
  9211. ];
  9212. }
  9213. return null;
  9214. },
  9215. hasBody(obj) {
  9216. return obj && obj.__isVue;
  9217. },
  9218. body(obj) {
  9219. if (obj && obj.__isVue) {
  9220. return [
  9221. 'div',
  9222. {},
  9223. ...formatInstance(obj.$)
  9224. ];
  9225. }
  9226. }
  9227. };
  9228. function formatInstance(instance) {
  9229. const blocks = [];
  9230. if (instance.type.props && instance.props) {
  9231. blocks.push(createInstanceBlock('props', toRaw(instance.props)));
  9232. }
  9233. if (instance.setupState !== EMPTY_OBJ) {
  9234. blocks.push(createInstanceBlock('setup', instance.setupState));
  9235. }
  9236. if (instance.data !== EMPTY_OBJ) {
  9237. blocks.push(createInstanceBlock('data', toRaw(instance.data)));
  9238. }
  9239. const computed = extractKeys(instance, 'computed');
  9240. if (computed) {
  9241. blocks.push(createInstanceBlock('computed', computed));
  9242. }
  9243. const injected = extractKeys(instance, 'inject');
  9244. if (injected) {
  9245. blocks.push(createInstanceBlock('injected', injected));
  9246. }
  9247. blocks.push([
  9248. 'div',
  9249. {},
  9250. [
  9251. 'span',
  9252. {
  9253. style: keywordStyle.style + ';opacity:0.66'
  9254. },
  9255. '$ (internal): '
  9256. ],
  9257. ['object', { object: instance }]
  9258. ]);
  9259. return blocks;
  9260. }
  9261. function createInstanceBlock(type, target) {
  9262. target = extend({}, target);
  9263. if (!Object.keys(target).length) {
  9264. return ['span', {}];
  9265. }
  9266. return [
  9267. 'div',
  9268. { style: 'line-height:1.25em;margin-bottom:0.6em' },
  9269. [
  9270. 'div',
  9271. {
  9272. style: 'color:#476582'
  9273. },
  9274. type
  9275. ],
  9276. [
  9277. 'div',
  9278. {
  9279. style: 'padding-left:1.25em'
  9280. },
  9281. ...Object.keys(target).map(key => {
  9282. return [
  9283. 'div',
  9284. {},
  9285. ['span', keywordStyle, key + ': '],
  9286. formatValue(target[key], false)
  9287. ];
  9288. })
  9289. ]
  9290. ];
  9291. }
  9292. function formatValue(v, asRaw = true) {
  9293. if (typeof v === 'number') {
  9294. return ['span', numberStyle, v];
  9295. }
  9296. else if (typeof v === 'string') {
  9297. return ['span', stringStyle, JSON.stringify(v)];
  9298. }
  9299. else if (typeof v === 'boolean') {
  9300. return ['span', keywordStyle, v];
  9301. }
  9302. else if (isObject(v)) {
  9303. return ['object', { object: asRaw ? toRaw(v) : v }];
  9304. }
  9305. else {
  9306. return ['span', stringStyle, String(v)];
  9307. }
  9308. }
  9309. function extractKeys(instance, type) {
  9310. const Comp = instance.type;
  9311. if (isFunction(Comp)) {
  9312. return;
  9313. }
  9314. const extracted = {};
  9315. for (const key in instance.ctx) {
  9316. if (isKeyOfType(Comp, key, type)) {
  9317. extracted[key] = instance.ctx[key];
  9318. }
  9319. }
  9320. return extracted;
  9321. }
  9322. function isKeyOfType(Comp, key, type) {
  9323. const opts = Comp[type];
  9324. if ((isArray(opts) && opts.includes(key)) ||
  9325. (isObject(opts) && key in opts)) {
  9326. return true;
  9327. }
  9328. if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
  9329. return true;
  9330. }
  9331. if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
  9332. return true;
  9333. }
  9334. }
  9335. function genRefFlag(v) {
  9336. if (isShallow(v)) {
  9337. return `ShallowRef`;
  9338. }
  9339. if (v.effect) {
  9340. return `ComputedRef`;
  9341. }
  9342. return `Ref`;
  9343. }
  9344. if (window.devtoolsFormatters) {
  9345. window.devtoolsFormatters.push(formatter);
  9346. }
  9347. else {
  9348. window.devtoolsFormatters = [formatter];
  9349. }
  9350. }
  9351. function withMemo(memo, render, cache, index) {
  9352. const cached = cache[index];
  9353. if (cached && isMemoSame(cached, memo)) {
  9354. return cached;
  9355. }
  9356. const ret = render();
  9357. // shallow clone
  9358. ret.memo = memo.slice();
  9359. return (cache[index] = ret);
  9360. }
  9361. function isMemoSame(cached, memo) {
  9362. const prev = cached.memo;
  9363. if (prev.length != memo.length) {
  9364. return false;
  9365. }
  9366. for (let i = 0; i < prev.length; i++) {
  9367. if (hasChanged(prev[i], memo[i])) {
  9368. return false;
  9369. }
  9370. }
  9371. // make sure to let parent block track it when returning cached
  9372. if (isBlockTreeEnabled > 0 && currentBlock) {
  9373. currentBlock.push(cached);
  9374. }
  9375. return true;
  9376. }
  9377. // Core API ------------------------------------------------------------------
  9378. const version = "3.2.47";
  9379. /**
  9380. * SSR utils for \@vue/server-renderer. Only exposed in ssr-possible builds.
  9381. * @internal
  9382. */
  9383. const ssrUtils = (null);
  9384. /**
  9385. * @internal only exposed in compat builds
  9386. */
  9387. const resolveFilter = null;
  9388. /**
  9389. * @internal only exposed in compat builds.
  9390. */
  9391. const compatUtils = (null);
  9392. const svgNS = 'http://www.w3.org/2000/svg';
  9393. const doc = (typeof document !== 'undefined' ? document : null);
  9394. const templateContainer = doc && /*#__PURE__*/ doc.createElement('template');
  9395. const nodeOps = {
  9396. insert: (child, parent, anchor) => {
  9397. parent.insertBefore(child, anchor || null);
  9398. },
  9399. remove: child => {
  9400. const parent = child.parentNode;
  9401. if (parent) {
  9402. parent.removeChild(child);
  9403. }
  9404. },
  9405. createElement: (tag, isSVG, is, props) => {
  9406. const el = isSVG
  9407. ? doc.createElementNS(svgNS, tag)
  9408. : doc.createElement(tag, is ? { is } : undefined);
  9409. if (tag === 'select' && props && props.multiple != null) {
  9410. el.setAttribute('multiple', props.multiple);
  9411. }
  9412. return el;
  9413. },
  9414. createText: text => doc.createTextNode(text),
  9415. createComment: text => doc.createComment(text),
  9416. setText: (node, text) => {
  9417. node.nodeValue = text;
  9418. },
  9419. setElementText: (el, text) => {
  9420. el.textContent = text;
  9421. },
  9422. parentNode: node => node.parentNode,
  9423. nextSibling: node => node.nextSibling,
  9424. querySelector: selector => doc.querySelector(selector),
  9425. setScopeId(el, id) {
  9426. el.setAttribute(id, '');
  9427. },
  9428. // __UNSAFE__
  9429. // Reason: innerHTML.
  9430. // Static content here can only come from compiled templates.
  9431. // As long as the user only uses trusted templates, this is safe.
  9432. insertStaticContent(content, parent, anchor, isSVG, start, end) {
  9433. // <parent> before | first ... last | anchor </parent>
  9434. const before = anchor ? anchor.previousSibling : parent.lastChild;
  9435. // #5308 can only take cached path if:
  9436. // - has a single root node
  9437. // - nextSibling info is still available
  9438. if (start && (start === end || start.nextSibling)) {
  9439. // cached
  9440. while (true) {
  9441. parent.insertBefore(start.cloneNode(true), anchor);
  9442. if (start === end || !(start = start.nextSibling))
  9443. break;
  9444. }
  9445. }
  9446. else {
  9447. // fresh insert
  9448. templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
  9449. const template = templateContainer.content;
  9450. if (isSVG) {
  9451. // remove outer svg wrapper
  9452. const wrapper = template.firstChild;
  9453. while (wrapper.firstChild) {
  9454. template.appendChild(wrapper.firstChild);
  9455. }
  9456. template.removeChild(wrapper);
  9457. }
  9458. parent.insertBefore(template, anchor);
  9459. }
  9460. return [
  9461. // first
  9462. before ? before.nextSibling : parent.firstChild,
  9463. // last
  9464. anchor ? anchor.previousSibling : parent.lastChild
  9465. ];
  9466. }
  9467. };
  9468. // compiler should normalize class + :class bindings on the same element
  9469. // into a single binding ['staticClass', dynamic]
  9470. function patchClass(el, value, isSVG) {
  9471. // directly setting className should be faster than setAttribute in theory
  9472. // if this is an element during a transition, take the temporary transition
  9473. // classes into account.
  9474. const transitionClasses = el._vtc;
  9475. if (transitionClasses) {
  9476. value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
  9477. }
  9478. if (value == null) {
  9479. el.removeAttribute('class');
  9480. }
  9481. else if (isSVG) {
  9482. el.setAttribute('class', value);
  9483. }
  9484. else {
  9485. el.className = value;
  9486. }
  9487. }
  9488. function patchStyle(el, prev, next) {
  9489. const style = el.style;
  9490. const isCssString = isString(next);
  9491. if (next && !isCssString) {
  9492. if (prev && !isString(prev)) {
  9493. for (const key in prev) {
  9494. if (next[key] == null) {
  9495. setStyle(style, key, '');
  9496. }
  9497. }
  9498. }
  9499. for (const key in next) {
  9500. setStyle(style, key, next[key]);
  9501. }
  9502. }
  9503. else {
  9504. const currentDisplay = style.display;
  9505. if (isCssString) {
  9506. if (prev !== next) {
  9507. style.cssText = next;
  9508. }
  9509. }
  9510. else if (prev) {
  9511. el.removeAttribute('style');
  9512. }
  9513. // indicates that the `display` of the element is controlled by `v-show`,
  9514. // so we always keep the current `display` value regardless of the `style`
  9515. // value, thus handing over control to `v-show`.
  9516. if ('_vod' in el) {
  9517. style.display = currentDisplay;
  9518. }
  9519. }
  9520. }
  9521. const semicolonRE = /[^\\];\s*$/;
  9522. const importantRE = /\s*!important$/;
  9523. function setStyle(style, name, val) {
  9524. if (isArray(val)) {
  9525. val.forEach(v => setStyle(style, name, v));
  9526. }
  9527. else {
  9528. if (val == null)
  9529. val = '';
  9530. {
  9531. if (semicolonRE.test(val)) {
  9532. warn(`Unexpected semicolon at the end of '${name}' style value: '${val}'`);
  9533. }
  9534. }
  9535. if (name.startsWith('--')) {
  9536. // custom property definition
  9537. style.setProperty(name, val);
  9538. }
  9539. else {
  9540. const prefixed = autoPrefix(style, name);
  9541. if (importantRE.test(val)) {
  9542. // !important
  9543. style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
  9544. }
  9545. else {
  9546. style[prefixed] = val;
  9547. }
  9548. }
  9549. }
  9550. }
  9551. const prefixes = ['Webkit', 'Moz', 'ms'];
  9552. const prefixCache = {};
  9553. function autoPrefix(style, rawName) {
  9554. const cached = prefixCache[rawName];
  9555. if (cached) {
  9556. return cached;
  9557. }
  9558. let name = camelize(rawName);
  9559. if (name !== 'filter' && name in style) {
  9560. return (prefixCache[rawName] = name);
  9561. }
  9562. name = capitalize(name);
  9563. for (let i = 0; i < prefixes.length; i++) {
  9564. const prefixed = prefixes[i] + name;
  9565. if (prefixed in style) {
  9566. return (prefixCache[rawName] = prefixed);
  9567. }
  9568. }
  9569. return rawName;
  9570. }
  9571. const xlinkNS = 'http://www.w3.org/1999/xlink';
  9572. function patchAttr(el, key, value, isSVG, instance) {
  9573. if (isSVG && key.startsWith('xlink:')) {
  9574. if (value == null) {
  9575. el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
  9576. }
  9577. else {
  9578. el.setAttributeNS(xlinkNS, key, value);
  9579. }
  9580. }
  9581. else {
  9582. // note we are only checking boolean attributes that don't have a
  9583. // corresponding dom prop of the same name here.
  9584. const isBoolean = isSpecialBooleanAttr(key);
  9585. if (value == null || (isBoolean && !includeBooleanAttr(value))) {
  9586. el.removeAttribute(key);
  9587. }
  9588. else {
  9589. el.setAttribute(key, isBoolean ? '' : value);
  9590. }
  9591. }
  9592. }
  9593. // __UNSAFE__
  9594. // functions. The user is responsible for using them with only trusted content.
  9595. function patchDOMProp(el, key, value,
  9596. // the following args are passed only due to potential innerHTML/textContent
  9597. // overriding existing VNodes, in which case the old tree must be properly
  9598. // unmounted.
  9599. prevChildren, parentComponent, parentSuspense, unmountChildren) {
  9600. if (key === 'innerHTML' || key === 'textContent') {
  9601. if (prevChildren) {
  9602. unmountChildren(prevChildren, parentComponent, parentSuspense);
  9603. }
  9604. el[key] = value == null ? '' : value;
  9605. return;
  9606. }
  9607. if (key === 'value' &&
  9608. el.tagName !== 'PROGRESS' &&
  9609. // custom elements may use _value internally
  9610. !el.tagName.includes('-')) {
  9611. // store value as _value as well since
  9612. // non-string values will be stringified.
  9613. el._value = value;
  9614. const newValue = value == null ? '' : value;
  9615. if (el.value !== newValue ||
  9616. // #4956: always set for OPTION elements because its value falls back to
  9617. // textContent if no value attribute is present. And setting .value for
  9618. // OPTION has no side effect
  9619. el.tagName === 'OPTION') {
  9620. el.value = newValue;
  9621. }
  9622. if (value == null) {
  9623. el.removeAttribute(key);
  9624. }
  9625. return;
  9626. }
  9627. let needRemove = false;
  9628. if (value === '' || value == null) {
  9629. const type = typeof el[key];
  9630. if (type === 'boolean') {
  9631. // e.g. <select multiple> compiles to { multiple: '' }
  9632. value = includeBooleanAttr(value);
  9633. }
  9634. else if (value == null && type === 'string') {
  9635. // e.g. <div :id="null">
  9636. value = '';
  9637. needRemove = true;
  9638. }
  9639. else if (type === 'number') {
  9640. // e.g. <img :width="null">
  9641. value = 0;
  9642. needRemove = true;
  9643. }
  9644. }
  9645. // some properties perform value validation and throw,
  9646. // some properties has getter, no setter, will error in 'use strict'
  9647. // eg. <select :type="null"></select> <select :willValidate="null"></select>
  9648. try {
  9649. el[key] = value;
  9650. }
  9651. catch (e) {
  9652. // do not warn if value is auto-coerced from nullish values
  9653. if (!needRemove) {
  9654. warn(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
  9655. `value ${value} is invalid.`, e);
  9656. }
  9657. }
  9658. needRemove && el.removeAttribute(key);
  9659. }
  9660. function addEventListener(el, event, handler, options) {
  9661. el.addEventListener(event, handler, options);
  9662. }
  9663. function removeEventListener(el, event, handler, options) {
  9664. el.removeEventListener(event, handler, options);
  9665. }
  9666. function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  9667. // vei = vue event invokers
  9668. const invokers = el._vei || (el._vei = {});
  9669. const existingInvoker = invokers[rawName];
  9670. if (nextValue && existingInvoker) {
  9671. // patch
  9672. existingInvoker.value = nextValue;
  9673. }
  9674. else {
  9675. const [name, options] = parseName(rawName);
  9676. if (nextValue) {
  9677. // add
  9678. const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
  9679. addEventListener(el, name, invoker, options);
  9680. }
  9681. else if (existingInvoker) {
  9682. // remove
  9683. removeEventListener(el, name, existingInvoker, options);
  9684. invokers[rawName] = undefined;
  9685. }
  9686. }
  9687. }
  9688. const optionsModifierRE = /(?:Once|Passive|Capture)$/;
  9689. function parseName(name) {
  9690. let options;
  9691. if (optionsModifierRE.test(name)) {
  9692. options = {};
  9693. let m;
  9694. while ((m = name.match(optionsModifierRE))) {
  9695. name = name.slice(0, name.length - m[0].length);
  9696. options[m[0].toLowerCase()] = true;
  9697. }
  9698. }
  9699. const event = name[2] === ':' ? name.slice(3) : hyphenate(name.slice(2));
  9700. return [event, options];
  9701. }
  9702. // To avoid the overhead of repeatedly calling Date.now(), we cache
  9703. // and use the same timestamp for all event listeners attached in the same tick.
  9704. let cachedNow = 0;
  9705. const p = /*#__PURE__*/ Promise.resolve();
  9706. const getNow = () => cachedNow || (p.then(() => (cachedNow = 0)), (cachedNow = Date.now()));
  9707. function createInvoker(initialValue, instance) {
  9708. const invoker = (e) => {
  9709. // async edge case vuejs/vue#6566
  9710. // inner click event triggers patch, event handler
  9711. // attached to outer element during patch, and triggered again. This
  9712. // happens because browsers fire microtask ticks between event propagation.
  9713. // this no longer happens for templates in Vue 3, but could still be
  9714. // theoretically possible for hand-written render functions.
  9715. // the solution: we save the timestamp when a handler is attached,
  9716. // and also attach the timestamp to any event that was handled by vue
  9717. // for the first time (to avoid inconsistent event timestamp implementations
  9718. // or events fired from iframes, e.g. #2513)
  9719. // The handler would only fire if the event passed to it was fired
  9720. // AFTER it was attached.
  9721. if (!e._vts) {
  9722. e._vts = Date.now();
  9723. }
  9724. else if (e._vts <= invoker.attached) {
  9725. return;
  9726. }
  9727. callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* ErrorCodes.NATIVE_EVENT_HANDLER */, [e]);
  9728. };
  9729. invoker.value = initialValue;
  9730. invoker.attached = getNow();
  9731. return invoker;
  9732. }
  9733. function patchStopImmediatePropagation(e, value) {
  9734. if (isArray(value)) {
  9735. const originalStop = e.stopImmediatePropagation;
  9736. e.stopImmediatePropagation = () => {
  9737. originalStop.call(e);
  9738. e._stopped = true;
  9739. };
  9740. return value.map(fn => (e) => !e._stopped && fn && fn(e));
  9741. }
  9742. else {
  9743. return value;
  9744. }
  9745. }
  9746. const nativeOnRE = /^on[a-z]/;
  9747. const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
  9748. if (key === 'class') {
  9749. patchClass(el, nextValue, isSVG);
  9750. }
  9751. else if (key === 'style') {
  9752. patchStyle(el, prevValue, nextValue);
  9753. }
  9754. else if (isOn(key)) {
  9755. // ignore v-model listeners
  9756. if (!isModelListener(key)) {
  9757. patchEvent(el, key, prevValue, nextValue, parentComponent);
  9758. }
  9759. }
  9760. else if (key[0] === '.'
  9761. ? ((key = key.slice(1)), true)
  9762. : key[0] === '^'
  9763. ? ((key = key.slice(1)), false)
  9764. : shouldSetAsProp(el, key, nextValue, isSVG)) {
  9765. patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
  9766. }
  9767. else {
  9768. // special case for <input v-model type="checkbox"> with
  9769. // :true-value & :false-value
  9770. // store value as dom properties since non-string values will be
  9771. // stringified.
  9772. if (key === 'true-value') {
  9773. el._trueValue = nextValue;
  9774. }
  9775. else if (key === 'false-value') {
  9776. el._falseValue = nextValue;
  9777. }
  9778. patchAttr(el, key, nextValue, isSVG);
  9779. }
  9780. };
  9781. function shouldSetAsProp(el, key, value, isSVG) {
  9782. if (isSVG) {
  9783. // most keys must be set as attribute on svg elements to work
  9784. // ...except innerHTML & textContent
  9785. if (key === 'innerHTML' || key === 'textContent') {
  9786. return true;
  9787. }
  9788. // or native onclick with function values
  9789. if (key in el && nativeOnRE.test(key) && isFunction(value)) {
  9790. return true;
  9791. }
  9792. return false;
  9793. }
  9794. // these are enumerated attrs, however their corresponding DOM properties
  9795. // are actually booleans - this leads to setting it with a string "false"
  9796. // value leading it to be coerced to `true`, so we need to always treat
  9797. // them as attributes.
  9798. // Note that `contentEditable` doesn't have this problem: its DOM
  9799. // property is also enumerated string values.
  9800. if (key === 'spellcheck' || key === 'draggable' || key === 'translate') {
  9801. return false;
  9802. }
  9803. // #1787, #2840 form property on form elements is readonly and must be set as
  9804. // attribute.
  9805. if (key === 'form') {
  9806. return false;
  9807. }
  9808. // #1526 <input list> must be set as attribute
  9809. if (key === 'list' && el.tagName === 'INPUT') {
  9810. return false;
  9811. }
  9812. // #2766 <textarea type> must be set as attribute
  9813. if (key === 'type' && el.tagName === 'TEXTAREA') {
  9814. return false;
  9815. }
  9816. // native onclick with string value, must be set as attribute
  9817. if (nativeOnRE.test(key) && isString(value)) {
  9818. return false;
  9819. }
  9820. return key in el;
  9821. }
  9822. function defineCustomElement(options, hydrate) {
  9823. const Comp = defineComponent(options);
  9824. class VueCustomElement extends VueElement {
  9825. constructor(initialProps) {
  9826. super(Comp, initialProps, hydrate);
  9827. }
  9828. }
  9829. VueCustomElement.def = Comp;
  9830. return VueCustomElement;
  9831. }
  9832. const defineSSRCustomElement = ((options) => {
  9833. // @ts-ignore
  9834. return defineCustomElement(options, hydrate);
  9835. });
  9836. const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
  9837. });
  9838. class VueElement extends BaseClass {
  9839. constructor(_def, _props = {}, hydrate) {
  9840. super();
  9841. this._def = _def;
  9842. this._props = _props;
  9843. /**
  9844. * @internal
  9845. */
  9846. this._instance = null;
  9847. this._connected = false;
  9848. this._resolved = false;
  9849. this._numberProps = null;
  9850. if (this.shadowRoot && hydrate) {
  9851. hydrate(this._createVNode(), this.shadowRoot);
  9852. }
  9853. else {
  9854. if (this.shadowRoot) {
  9855. warn(`Custom element has pre-rendered declarative shadow root but is not ` +
  9856. `defined as hydratable. Use \`defineSSRCustomElement\`.`);
  9857. }
  9858. this.attachShadow({ mode: 'open' });
  9859. if (!this._def.__asyncLoader) {
  9860. // for sync component defs we can immediately resolve props
  9861. this._resolveProps(this._def);
  9862. }
  9863. }
  9864. }
  9865. connectedCallback() {
  9866. this._connected = true;
  9867. if (!this._instance) {
  9868. if (this._resolved) {
  9869. this._update();
  9870. }
  9871. else {
  9872. this._resolveDef();
  9873. }
  9874. }
  9875. }
  9876. disconnectedCallback() {
  9877. this._connected = false;
  9878. nextTick(() => {
  9879. if (!this._connected) {
  9880. render(null, this.shadowRoot);
  9881. this._instance = null;
  9882. }
  9883. });
  9884. }
  9885. /**
  9886. * resolve inner component definition (handle possible async component)
  9887. */
  9888. _resolveDef() {
  9889. this._resolved = true;
  9890. // set initial attrs
  9891. for (let i = 0; i < this.attributes.length; i++) {
  9892. this._setAttr(this.attributes[i].name);
  9893. }
  9894. // watch future attr changes
  9895. new MutationObserver(mutations => {
  9896. for (const m of mutations) {
  9897. this._setAttr(m.attributeName);
  9898. }
  9899. }).observe(this, { attributes: true });
  9900. const resolve = (def, isAsync = false) => {
  9901. const { props, styles } = def;
  9902. // cast Number-type props set before resolve
  9903. let numberProps;
  9904. if (props && !isArray(props)) {
  9905. for (const key in props) {
  9906. const opt = props[key];
  9907. if (opt === Number || (opt && opt.type === Number)) {
  9908. if (key in this._props) {
  9909. this._props[key] = toNumber(this._props[key]);
  9910. }
  9911. (numberProps || (numberProps = Object.create(null)))[camelize(key)] = true;
  9912. }
  9913. }
  9914. }
  9915. this._numberProps = numberProps;
  9916. if (isAsync) {
  9917. // defining getter/setters on prototype
  9918. // for sync defs, this already happened in the constructor
  9919. this._resolveProps(def);
  9920. }
  9921. // apply CSS
  9922. this._applyStyles(styles);
  9923. // initial render
  9924. this._update();
  9925. };
  9926. const asyncDef = this._def.__asyncLoader;
  9927. if (asyncDef) {
  9928. asyncDef().then(def => resolve(def, true));
  9929. }
  9930. else {
  9931. resolve(this._def);
  9932. }
  9933. }
  9934. _resolveProps(def) {
  9935. const { props } = def;
  9936. const declaredPropKeys = isArray(props) ? props : Object.keys(props || {});
  9937. // check if there are props set pre-upgrade or connect
  9938. for (const key of Object.keys(this)) {
  9939. if (key[0] !== '_' && declaredPropKeys.includes(key)) {
  9940. this._setProp(key, this[key], true, false);
  9941. }
  9942. }
  9943. // defining getter/setters on prototype
  9944. for (const key of declaredPropKeys.map(camelize)) {
  9945. Object.defineProperty(this, key, {
  9946. get() {
  9947. return this._getProp(key);
  9948. },
  9949. set(val) {
  9950. this._setProp(key, val);
  9951. }
  9952. });
  9953. }
  9954. }
  9955. _setAttr(key) {
  9956. let value = this.getAttribute(key);
  9957. const camelKey = camelize(key);
  9958. if (this._numberProps && this._numberProps[camelKey]) {
  9959. value = toNumber(value);
  9960. }
  9961. this._setProp(camelKey, value, false);
  9962. }
  9963. /**
  9964. * @internal
  9965. */
  9966. _getProp(key) {
  9967. return this._props[key];
  9968. }
  9969. /**
  9970. * @internal
  9971. */
  9972. _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
  9973. if (val !== this._props[key]) {
  9974. this._props[key] = val;
  9975. if (shouldUpdate && this._instance) {
  9976. this._update();
  9977. }
  9978. // reflect
  9979. if (shouldReflect) {
  9980. if (val === true) {
  9981. this.setAttribute(hyphenate(key), '');
  9982. }
  9983. else if (typeof val === 'string' || typeof val === 'number') {
  9984. this.setAttribute(hyphenate(key), val + '');
  9985. }
  9986. else if (!val) {
  9987. this.removeAttribute(hyphenate(key));
  9988. }
  9989. }
  9990. }
  9991. }
  9992. _update() {
  9993. render(this._createVNode(), this.shadowRoot);
  9994. }
  9995. _createVNode() {
  9996. const vnode = createVNode(this._def, extend({}, this._props));
  9997. if (!this._instance) {
  9998. vnode.ce = instance => {
  9999. this._instance = instance;
  10000. instance.isCE = true;
  10001. // HMR
  10002. {
  10003. instance.ceReload = newStyles => {
  10004. // always reset styles
  10005. if (this._styles) {
  10006. this._styles.forEach(s => this.shadowRoot.removeChild(s));
  10007. this._styles.length = 0;
  10008. }
  10009. this._applyStyles(newStyles);
  10010. this._instance = null;
  10011. this._update();
  10012. };
  10013. }
  10014. const dispatch = (event, args) => {
  10015. this.dispatchEvent(new CustomEvent(event, {
  10016. detail: args
  10017. }));
  10018. };
  10019. // intercept emit
  10020. instance.emit = (event, ...args) => {
  10021. // dispatch both the raw and hyphenated versions of an event
  10022. // to match Vue behavior
  10023. dispatch(event, args);
  10024. if (hyphenate(event) !== event) {
  10025. dispatch(hyphenate(event), args);
  10026. }
  10027. };
  10028. // locate nearest Vue custom element parent for provide/inject
  10029. let parent = this;
  10030. while ((parent =
  10031. parent && (parent.parentNode || parent.host))) {
  10032. if (parent instanceof VueElement) {
  10033. instance.parent = parent._instance;
  10034. instance.provides = parent._instance.provides;
  10035. break;
  10036. }
  10037. }
  10038. };
  10039. }
  10040. return vnode;
  10041. }
  10042. _applyStyles(styles) {
  10043. if (styles) {
  10044. styles.forEach(css => {
  10045. const s = document.createElement('style');
  10046. s.textContent = css;
  10047. this.shadowRoot.appendChild(s);
  10048. // record for HMR
  10049. {
  10050. (this._styles || (this._styles = [])).push(s);
  10051. }
  10052. });
  10053. }
  10054. }
  10055. }
  10056. function useCssModule(name = '$style') {
  10057. /* istanbul ignore else */
  10058. {
  10059. const instance = getCurrentInstance();
  10060. if (!instance) {
  10061. warn(`useCssModule must be called inside setup()`);
  10062. return EMPTY_OBJ;
  10063. }
  10064. const modules = instance.type.__cssModules;
  10065. if (!modules) {
  10066. warn(`Current instance does not have CSS modules injected.`);
  10067. return EMPTY_OBJ;
  10068. }
  10069. const mod = modules[name];
  10070. if (!mod) {
  10071. warn(`Current instance does not have CSS module named "${name}".`);
  10072. return EMPTY_OBJ;
  10073. }
  10074. return mod;
  10075. }
  10076. }
  10077. /**
  10078. * Runtime helper for SFC's CSS variable injection feature.
  10079. * @private
  10080. */
  10081. function useCssVars(getter) {
  10082. const instance = getCurrentInstance();
  10083. /* istanbul ignore next */
  10084. if (!instance) {
  10085. warn(`useCssVars is called without current active component instance.`);
  10086. return;
  10087. }
  10088. const updateTeleports = (instance.ut = (vars = getter(instance.proxy)) => {
  10089. Array.from(document.querySelectorAll(`[data-v-owner="${instance.uid}"]`)).forEach(node => setVarsOnNode(node, vars));
  10090. });
  10091. const setVars = () => {
  10092. const vars = getter(instance.proxy);
  10093. setVarsOnVNode(instance.subTree, vars);
  10094. updateTeleports(vars);
  10095. };
  10096. watchPostEffect(setVars);
  10097. onMounted(() => {
  10098. const ob = new MutationObserver(setVars);
  10099. ob.observe(instance.subTree.el.parentNode, { childList: true });
  10100. onUnmounted(() => ob.disconnect());
  10101. });
  10102. }
  10103. function setVarsOnVNode(vnode, vars) {
  10104. if (vnode.shapeFlag & 128 /* ShapeFlags.SUSPENSE */) {
  10105. const suspense = vnode.suspense;
  10106. vnode = suspense.activeBranch;
  10107. if (suspense.pendingBranch && !suspense.isHydrating) {
  10108. suspense.effects.push(() => {
  10109. setVarsOnVNode(suspense.activeBranch, vars);
  10110. });
  10111. }
  10112. }
  10113. // drill down HOCs until it's a non-component vnode
  10114. while (vnode.component) {
  10115. vnode = vnode.component.subTree;
  10116. }
  10117. if (vnode.shapeFlag & 1 /* ShapeFlags.ELEMENT */ && vnode.el) {
  10118. setVarsOnNode(vnode.el, vars);
  10119. }
  10120. else if (vnode.type === Fragment) {
  10121. vnode.children.forEach(c => setVarsOnVNode(c, vars));
  10122. }
  10123. else if (vnode.type === Static) {
  10124. let { el, anchor } = vnode;
  10125. while (el) {
  10126. setVarsOnNode(el, vars);
  10127. if (el === anchor)
  10128. break;
  10129. el = el.nextSibling;
  10130. }
  10131. }
  10132. }
  10133. function setVarsOnNode(el, vars) {
  10134. if (el.nodeType === 1) {
  10135. const style = el.style;
  10136. for (const key in vars) {
  10137. style.setProperty(`--${key}`, vars[key]);
  10138. }
  10139. }
  10140. }
  10141. const TRANSITION$1 = 'transition';
  10142. const ANIMATION = 'animation';
  10143. // DOM Transition is a higher-order-component based on the platform-agnostic
  10144. // base Transition component, with DOM-specific logic.
  10145. const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
  10146. Transition.displayName = 'Transition';
  10147. const DOMTransitionPropsValidators = {
  10148. name: String,
  10149. type: String,
  10150. css: {
  10151. type: Boolean,
  10152. default: true
  10153. },
  10154. duration: [String, Number, Object],
  10155. enterFromClass: String,
  10156. enterActiveClass: String,
  10157. enterToClass: String,
  10158. appearFromClass: String,
  10159. appearActiveClass: String,
  10160. appearToClass: String,
  10161. leaveFromClass: String,
  10162. leaveActiveClass: String,
  10163. leaveToClass: String
  10164. };
  10165. const TransitionPropsValidators = (Transition.props =
  10166. /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
  10167. /**
  10168. * #3227 Incoming hooks may be merged into arrays when wrapping Transition
  10169. * with custom HOCs.
  10170. */
  10171. const callHook = (hook, args = []) => {
  10172. if (isArray(hook)) {
  10173. hook.forEach(h => h(...args));
  10174. }
  10175. else if (hook) {
  10176. hook(...args);
  10177. }
  10178. };
  10179. /**
  10180. * Check if a hook expects a callback (2nd arg), which means the user
  10181. * intends to explicitly control the end of the transition.
  10182. */
  10183. const hasExplicitCallback = (hook) => {
  10184. return hook
  10185. ? isArray(hook)
  10186. ? hook.some(h => h.length > 1)
  10187. : hook.length > 1
  10188. : false;
  10189. };
  10190. function resolveTransitionProps(rawProps) {
  10191. const baseProps = {};
  10192. for (const key in rawProps) {
  10193. if (!(key in DOMTransitionPropsValidators)) {
  10194. baseProps[key] = rawProps[key];
  10195. }
  10196. }
  10197. if (rawProps.css === false) {
  10198. return baseProps;
  10199. }
  10200. const { name = 'v', type, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps;
  10201. const durations = normalizeDuration(duration);
  10202. const enterDuration = durations && durations[0];
  10203. const leaveDuration = durations && durations[1];
  10204. const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
  10205. const finishEnter = (el, isAppear, done) => {
  10206. removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
  10207. removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
  10208. done && done();
  10209. };
  10210. const finishLeave = (el, done) => {
  10211. el._isLeaving = false;
  10212. removeTransitionClass(el, leaveFromClass);
  10213. removeTransitionClass(el, leaveToClass);
  10214. removeTransitionClass(el, leaveActiveClass);
  10215. done && done();
  10216. };
  10217. const makeEnterHook = (isAppear) => {
  10218. return (el, done) => {
  10219. const hook = isAppear ? onAppear : onEnter;
  10220. const resolve = () => finishEnter(el, isAppear, done);
  10221. callHook(hook, [el, resolve]);
  10222. nextFrame(() => {
  10223. removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
  10224. addTransitionClass(el, isAppear ? appearToClass : enterToClass);
  10225. if (!hasExplicitCallback(hook)) {
  10226. whenTransitionEnds(el, type, enterDuration, resolve);
  10227. }
  10228. });
  10229. };
  10230. };
  10231. return extend(baseProps, {
  10232. onBeforeEnter(el) {
  10233. callHook(onBeforeEnter, [el]);
  10234. addTransitionClass(el, enterFromClass);
  10235. addTransitionClass(el, enterActiveClass);
  10236. },
  10237. onBeforeAppear(el) {
  10238. callHook(onBeforeAppear, [el]);
  10239. addTransitionClass(el, appearFromClass);
  10240. addTransitionClass(el, appearActiveClass);
  10241. },
  10242. onEnter: makeEnterHook(false),
  10243. onAppear: makeEnterHook(true),
  10244. onLeave(el, done) {
  10245. el._isLeaving = true;
  10246. const resolve = () => finishLeave(el, done);
  10247. addTransitionClass(el, leaveFromClass);
  10248. // force reflow so *-leave-from classes immediately take effect (#2593)
  10249. forceReflow();
  10250. addTransitionClass(el, leaveActiveClass);
  10251. nextFrame(() => {
  10252. if (!el._isLeaving) {
  10253. // cancelled
  10254. return;
  10255. }
  10256. removeTransitionClass(el, leaveFromClass);
  10257. addTransitionClass(el, leaveToClass);
  10258. if (!hasExplicitCallback(onLeave)) {
  10259. whenTransitionEnds(el, type, leaveDuration, resolve);
  10260. }
  10261. });
  10262. callHook(onLeave, [el, resolve]);
  10263. },
  10264. onEnterCancelled(el) {
  10265. finishEnter(el, false);
  10266. callHook(onEnterCancelled, [el]);
  10267. },
  10268. onAppearCancelled(el) {
  10269. finishEnter(el, true);
  10270. callHook(onAppearCancelled, [el]);
  10271. },
  10272. onLeaveCancelled(el) {
  10273. finishLeave(el);
  10274. callHook(onLeaveCancelled, [el]);
  10275. }
  10276. });
  10277. }
  10278. function normalizeDuration(duration) {
  10279. if (duration == null) {
  10280. return null;
  10281. }
  10282. else if (isObject(duration)) {
  10283. return [NumberOf(duration.enter), NumberOf(duration.leave)];
  10284. }
  10285. else {
  10286. const n = NumberOf(duration);
  10287. return [n, n];
  10288. }
  10289. }
  10290. function NumberOf(val) {
  10291. const res = toNumber(val);
  10292. {
  10293. assertNumber(res, '<transition> explicit duration');
  10294. }
  10295. return res;
  10296. }
  10297. function addTransitionClass(el, cls) {
  10298. cls.split(/\s+/).forEach(c => c && el.classList.add(c));
  10299. (el._vtc ||
  10300. (el._vtc = new Set())).add(cls);
  10301. }
  10302. function removeTransitionClass(el, cls) {
  10303. cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
  10304. const { _vtc } = el;
  10305. if (_vtc) {
  10306. _vtc.delete(cls);
  10307. if (!_vtc.size) {
  10308. el._vtc = undefined;
  10309. }
  10310. }
  10311. }
  10312. function nextFrame(cb) {
  10313. requestAnimationFrame(() => {
  10314. requestAnimationFrame(cb);
  10315. });
  10316. }
  10317. let endId = 0;
  10318. function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
  10319. const id = (el._endId = ++endId);
  10320. const resolveIfNotStale = () => {
  10321. if (id === el._endId) {
  10322. resolve();
  10323. }
  10324. };
  10325. if (explicitTimeout) {
  10326. return setTimeout(resolveIfNotStale, explicitTimeout);
  10327. }
  10328. const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
  10329. if (!type) {
  10330. return resolve();
  10331. }
  10332. const endEvent = type + 'end';
  10333. let ended = 0;
  10334. const end = () => {
  10335. el.removeEventListener(endEvent, onEnd);
  10336. resolveIfNotStale();
  10337. };
  10338. const onEnd = (e) => {
  10339. if (e.target === el && ++ended >= propCount) {
  10340. end();
  10341. }
  10342. };
  10343. setTimeout(() => {
  10344. if (ended < propCount) {
  10345. end();
  10346. }
  10347. }, timeout + 1);
  10348. el.addEventListener(endEvent, onEnd);
  10349. }
  10350. function getTransitionInfo(el, expectedType) {
  10351. const styles = window.getComputedStyle(el);
  10352. // JSDOM may return undefined for transition properties
  10353. const getStyleProperties = (key) => (styles[key] || '').split(', ');
  10354. const transitionDelays = getStyleProperties(`${TRANSITION$1}Delay`);
  10355. const transitionDurations = getStyleProperties(`${TRANSITION$1}Duration`);
  10356. const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
  10357. const animationDelays = getStyleProperties(`${ANIMATION}Delay`);
  10358. const animationDurations = getStyleProperties(`${ANIMATION}Duration`);
  10359. const animationTimeout = getTimeout(animationDelays, animationDurations);
  10360. let type = null;
  10361. let timeout = 0;
  10362. let propCount = 0;
  10363. /* istanbul ignore if */
  10364. if (expectedType === TRANSITION$1) {
  10365. if (transitionTimeout > 0) {
  10366. type = TRANSITION$1;
  10367. timeout = transitionTimeout;
  10368. propCount = transitionDurations.length;
  10369. }
  10370. }
  10371. else if (expectedType === ANIMATION) {
  10372. if (animationTimeout > 0) {
  10373. type = ANIMATION;
  10374. timeout = animationTimeout;
  10375. propCount = animationDurations.length;
  10376. }
  10377. }
  10378. else {
  10379. timeout = Math.max(transitionTimeout, animationTimeout);
  10380. type =
  10381. timeout > 0
  10382. ? transitionTimeout > animationTimeout
  10383. ? TRANSITION$1
  10384. : ANIMATION
  10385. : null;
  10386. propCount = type
  10387. ? type === TRANSITION$1
  10388. ? transitionDurations.length
  10389. : animationDurations.length
  10390. : 0;
  10391. }
  10392. const hasTransform = type === TRANSITION$1 &&
  10393. /\b(transform|all)(,|$)/.test(getStyleProperties(`${TRANSITION$1}Property`).toString());
  10394. return {
  10395. type,
  10396. timeout,
  10397. propCount,
  10398. hasTransform
  10399. };
  10400. }
  10401. function getTimeout(delays, durations) {
  10402. while (delays.length < durations.length) {
  10403. delays = delays.concat(delays);
  10404. }
  10405. return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
  10406. }
  10407. // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
  10408. // numbers in a locale-dependent way, using a comma instead of a dot.
  10409. // If comma is not replaced with a dot, the input will be rounded down
  10410. // (i.e. acting as a floor function) causing unexpected behaviors
  10411. function toMs(s) {
  10412. return Number(s.slice(0, -1).replace(',', '.')) * 1000;
  10413. }
  10414. // synchronously force layout to put elements into a certain state
  10415. function forceReflow() {
  10416. return document.body.offsetHeight;
  10417. }
  10418. const positionMap = new WeakMap();
  10419. const newPositionMap = new WeakMap();
  10420. const TransitionGroupImpl = {
  10421. name: 'TransitionGroup',
  10422. props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
  10423. tag: String,
  10424. moveClass: String
  10425. }),
  10426. setup(props, { slots }) {
  10427. const instance = getCurrentInstance();
  10428. const state = useTransitionState();
  10429. let prevChildren;
  10430. let children;
  10431. onUpdated(() => {
  10432. // children is guaranteed to exist after initial render
  10433. if (!prevChildren.length) {
  10434. return;
  10435. }
  10436. const moveClass = props.moveClass || `${props.name || 'v'}-move`;
  10437. if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
  10438. return;
  10439. }
  10440. // we divide the work into three loops to avoid mixing DOM reads and writes
  10441. // in each iteration - which helps prevent layout thrashing.
  10442. prevChildren.forEach(callPendingCbs);
  10443. prevChildren.forEach(recordPosition);
  10444. const movedChildren = prevChildren.filter(applyTranslation);
  10445. // force reflow to put everything in position
  10446. forceReflow();
  10447. movedChildren.forEach(c => {
  10448. const el = c.el;
  10449. const style = el.style;
  10450. addTransitionClass(el, moveClass);
  10451. style.transform = style.webkitTransform = style.transitionDuration = '';
  10452. const cb = (el._moveCb = (e) => {
  10453. if (e && e.target !== el) {
  10454. return;
  10455. }
  10456. if (!e || /transform$/.test(e.propertyName)) {
  10457. el.removeEventListener('transitionend', cb);
  10458. el._moveCb = null;
  10459. removeTransitionClass(el, moveClass);
  10460. }
  10461. });
  10462. el.addEventListener('transitionend', cb);
  10463. });
  10464. });
  10465. return () => {
  10466. const rawProps = toRaw(props);
  10467. const cssTransitionProps = resolveTransitionProps(rawProps);
  10468. let tag = rawProps.tag || Fragment;
  10469. prevChildren = children;
  10470. children = slots.default ? getTransitionRawChildren(slots.default()) : [];
  10471. for (let i = 0; i < children.length; i++) {
  10472. const child = children[i];
  10473. if (child.key != null) {
  10474. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  10475. }
  10476. else {
  10477. warn(`<TransitionGroup> children must be keyed.`);
  10478. }
  10479. }
  10480. if (prevChildren) {
  10481. for (let i = 0; i < prevChildren.length; i++) {
  10482. const child = prevChildren[i];
  10483. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  10484. positionMap.set(child, child.el.getBoundingClientRect());
  10485. }
  10486. }
  10487. return createVNode(tag, null, children);
  10488. };
  10489. }
  10490. };
  10491. /**
  10492. * TransitionGroup does not support "mode" so we need to remove it from the
  10493. * props declarations, but direct delete operation is considered a side effect
  10494. * and will make the entire transition feature non-tree-shakeable, so we do it
  10495. * in a function and mark the function's invocation as pure.
  10496. */
  10497. const removeMode = (props) => delete props.mode;
  10498. /*#__PURE__*/ removeMode(TransitionGroupImpl.props);
  10499. const TransitionGroup = TransitionGroupImpl;
  10500. function callPendingCbs(c) {
  10501. const el = c.el;
  10502. if (el._moveCb) {
  10503. el._moveCb();
  10504. }
  10505. if (el._enterCb) {
  10506. el._enterCb();
  10507. }
  10508. }
  10509. function recordPosition(c) {
  10510. newPositionMap.set(c, c.el.getBoundingClientRect());
  10511. }
  10512. function applyTranslation(c) {
  10513. const oldPos = positionMap.get(c);
  10514. const newPos = newPositionMap.get(c);
  10515. const dx = oldPos.left - newPos.left;
  10516. const dy = oldPos.top - newPos.top;
  10517. if (dx || dy) {
  10518. const s = c.el.style;
  10519. s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
  10520. s.transitionDuration = '0s';
  10521. return c;
  10522. }
  10523. }
  10524. function hasCSSTransform(el, root, moveClass) {
  10525. // Detect whether an element with the move class applied has
  10526. // CSS transitions. Since the element may be inside an entering
  10527. // transition at this very moment, we make a clone of it and remove
  10528. // all other transition classes applied to ensure only the move class
  10529. // is applied.
  10530. const clone = el.cloneNode();
  10531. if (el._vtc) {
  10532. el._vtc.forEach(cls => {
  10533. cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
  10534. });
  10535. }
  10536. moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
  10537. clone.style.display = 'none';
  10538. const container = (root.nodeType === 1 ? root : root.parentNode);
  10539. container.appendChild(clone);
  10540. const { hasTransform } = getTransitionInfo(clone);
  10541. container.removeChild(clone);
  10542. return hasTransform;
  10543. }
  10544. const getModelAssigner = (vnode) => {
  10545. const fn = vnode.props['onUpdate:modelValue'] ||
  10546. (false );
  10547. return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
  10548. };
  10549. function onCompositionStart(e) {
  10550. e.target.composing = true;
  10551. }
  10552. function onCompositionEnd(e) {
  10553. const target = e.target;
  10554. if (target.composing) {
  10555. target.composing = false;
  10556. target.dispatchEvent(new Event('input'));
  10557. }
  10558. }
  10559. // We are exporting the v-model runtime directly as vnode hooks so that it can
  10560. // be tree-shaken in case v-model is never used.
  10561. const vModelText = {
  10562. created(el, { modifiers: { lazy, trim, number } }, vnode) {
  10563. el._assign = getModelAssigner(vnode);
  10564. const castToNumber = number || (vnode.props && vnode.props.type === 'number');
  10565. addEventListener(el, lazy ? 'change' : 'input', e => {
  10566. if (e.target.composing)
  10567. return;
  10568. let domValue = el.value;
  10569. if (trim) {
  10570. domValue = domValue.trim();
  10571. }
  10572. if (castToNumber) {
  10573. domValue = looseToNumber(domValue);
  10574. }
  10575. el._assign(domValue);
  10576. });
  10577. if (trim) {
  10578. addEventListener(el, 'change', () => {
  10579. el.value = el.value.trim();
  10580. });
  10581. }
  10582. if (!lazy) {
  10583. addEventListener(el, 'compositionstart', onCompositionStart);
  10584. addEventListener(el, 'compositionend', onCompositionEnd);
  10585. // Safari < 10.2 & UIWebView doesn't fire compositionend when
  10586. // switching focus before confirming composition choice
  10587. // this also fixes the issue where some browsers e.g. iOS Chrome
  10588. // fires "change" instead of "input" on autocomplete.
  10589. addEventListener(el, 'change', onCompositionEnd);
  10590. }
  10591. },
  10592. // set value on mounted so it's after min/max for type="range"
  10593. mounted(el, { value }) {
  10594. el.value = value == null ? '' : value;
  10595. },
  10596. beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
  10597. el._assign = getModelAssigner(vnode);
  10598. // avoid clearing unresolved text. #2302
  10599. if (el.composing)
  10600. return;
  10601. if (document.activeElement === el && el.type !== 'range') {
  10602. if (lazy) {
  10603. return;
  10604. }
  10605. if (trim && el.value.trim() === value) {
  10606. return;
  10607. }
  10608. if ((number || el.type === 'number') &&
  10609. looseToNumber(el.value) === value) {
  10610. return;
  10611. }
  10612. }
  10613. const newValue = value == null ? '' : value;
  10614. if (el.value !== newValue) {
  10615. el.value = newValue;
  10616. }
  10617. }
  10618. };
  10619. const vModelCheckbox = {
  10620. // #4096 array checkboxes need to be deep traversed
  10621. deep: true,
  10622. created(el, _, vnode) {
  10623. el._assign = getModelAssigner(vnode);
  10624. addEventListener(el, 'change', () => {
  10625. const modelValue = el._modelValue;
  10626. const elementValue = getValue(el);
  10627. const checked = el.checked;
  10628. const assign = el._assign;
  10629. if (isArray(modelValue)) {
  10630. const index = looseIndexOf(modelValue, elementValue);
  10631. const found = index !== -1;
  10632. if (checked && !found) {
  10633. assign(modelValue.concat(elementValue));
  10634. }
  10635. else if (!checked && found) {
  10636. const filtered = [...modelValue];
  10637. filtered.splice(index, 1);
  10638. assign(filtered);
  10639. }
  10640. }
  10641. else if (isSet(modelValue)) {
  10642. const cloned = new Set(modelValue);
  10643. if (checked) {
  10644. cloned.add(elementValue);
  10645. }
  10646. else {
  10647. cloned.delete(elementValue);
  10648. }
  10649. assign(cloned);
  10650. }
  10651. else {
  10652. assign(getCheckboxValue(el, checked));
  10653. }
  10654. });
  10655. },
  10656. // set initial checked on mount to wait for true-value/false-value
  10657. mounted: setChecked,
  10658. beforeUpdate(el, binding, vnode) {
  10659. el._assign = getModelAssigner(vnode);
  10660. setChecked(el, binding, vnode);
  10661. }
  10662. };
  10663. function setChecked(el, { value, oldValue }, vnode) {
  10664. el._modelValue = value;
  10665. if (isArray(value)) {
  10666. el.checked = looseIndexOf(value, vnode.props.value) > -1;
  10667. }
  10668. else if (isSet(value)) {
  10669. el.checked = value.has(vnode.props.value);
  10670. }
  10671. else if (value !== oldValue) {
  10672. el.checked = looseEqual(value, getCheckboxValue(el, true));
  10673. }
  10674. }
  10675. const vModelRadio = {
  10676. created(el, { value }, vnode) {
  10677. el.checked = looseEqual(value, vnode.props.value);
  10678. el._assign = getModelAssigner(vnode);
  10679. addEventListener(el, 'change', () => {
  10680. el._assign(getValue(el));
  10681. });
  10682. },
  10683. beforeUpdate(el, { value, oldValue }, vnode) {
  10684. el._assign = getModelAssigner(vnode);
  10685. if (value !== oldValue) {
  10686. el.checked = looseEqual(value, vnode.props.value);
  10687. }
  10688. }
  10689. };
  10690. const vModelSelect = {
  10691. // <select multiple> value need to be deep traversed
  10692. deep: true,
  10693. created(el, { value, modifiers: { number } }, vnode) {
  10694. const isSetModel = isSet(value);
  10695. addEventListener(el, 'change', () => {
  10696. const selectedVal = Array.prototype.filter
  10697. .call(el.options, (o) => o.selected)
  10698. .map((o) => number ? looseToNumber(getValue(o)) : getValue(o));
  10699. el._assign(el.multiple
  10700. ? isSetModel
  10701. ? new Set(selectedVal)
  10702. : selectedVal
  10703. : selectedVal[0]);
  10704. });
  10705. el._assign = getModelAssigner(vnode);
  10706. },
  10707. // set value in mounted & updated because <select> relies on its children
  10708. // <option>s.
  10709. mounted(el, { value }) {
  10710. setSelected(el, value);
  10711. },
  10712. beforeUpdate(el, _binding, vnode) {
  10713. el._assign = getModelAssigner(vnode);
  10714. },
  10715. updated(el, { value }) {
  10716. setSelected(el, value);
  10717. }
  10718. };
  10719. function setSelected(el, value) {
  10720. const isMultiple = el.multiple;
  10721. if (isMultiple && !isArray(value) && !isSet(value)) {
  10722. warn(`<select multiple v-model> expects an Array or Set value for its binding, ` +
  10723. `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
  10724. return;
  10725. }
  10726. for (let i = 0, l = el.options.length; i < l; i++) {
  10727. const option = el.options[i];
  10728. const optionValue = getValue(option);
  10729. if (isMultiple) {
  10730. if (isArray(value)) {
  10731. option.selected = looseIndexOf(value, optionValue) > -1;
  10732. }
  10733. else {
  10734. option.selected = value.has(optionValue);
  10735. }
  10736. }
  10737. else {
  10738. if (looseEqual(getValue(option), value)) {
  10739. if (el.selectedIndex !== i)
  10740. el.selectedIndex = i;
  10741. return;
  10742. }
  10743. }
  10744. }
  10745. if (!isMultiple && el.selectedIndex !== -1) {
  10746. el.selectedIndex = -1;
  10747. }
  10748. }
  10749. // retrieve raw value set via :value bindings
  10750. function getValue(el) {
  10751. return '_value' in el ? el._value : el.value;
  10752. }
  10753. // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
  10754. function getCheckboxValue(el, checked) {
  10755. const key = checked ? '_trueValue' : '_falseValue';
  10756. return key in el ? el[key] : checked;
  10757. }
  10758. const vModelDynamic = {
  10759. created(el, binding, vnode) {
  10760. callModelHook(el, binding, vnode, null, 'created');
  10761. },
  10762. mounted(el, binding, vnode) {
  10763. callModelHook(el, binding, vnode, null, 'mounted');
  10764. },
  10765. beforeUpdate(el, binding, vnode, prevVNode) {
  10766. callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
  10767. },
  10768. updated(el, binding, vnode, prevVNode) {
  10769. callModelHook(el, binding, vnode, prevVNode, 'updated');
  10770. }
  10771. };
  10772. function resolveDynamicModel(tagName, type) {
  10773. switch (tagName) {
  10774. case 'SELECT':
  10775. return vModelSelect;
  10776. case 'TEXTAREA':
  10777. return vModelText;
  10778. default:
  10779. switch (type) {
  10780. case 'checkbox':
  10781. return vModelCheckbox;
  10782. case 'radio':
  10783. return vModelRadio;
  10784. default:
  10785. return vModelText;
  10786. }
  10787. }
  10788. }
  10789. function callModelHook(el, binding, vnode, prevVNode, hook) {
  10790. const modelToUse = resolveDynamicModel(el.tagName, vnode.props && vnode.props.type);
  10791. const fn = modelToUse[hook];
  10792. fn && fn(el, binding, vnode, prevVNode);
  10793. }
  10794. const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
  10795. const modifierGuards = {
  10796. stop: e => e.stopPropagation(),
  10797. prevent: e => e.preventDefault(),
  10798. self: e => e.target !== e.currentTarget,
  10799. ctrl: e => !e.ctrlKey,
  10800. shift: e => !e.shiftKey,
  10801. alt: e => !e.altKey,
  10802. meta: e => !e.metaKey,
  10803. left: e => 'button' in e && e.button !== 0,
  10804. middle: e => 'button' in e && e.button !== 1,
  10805. right: e => 'button' in e && e.button !== 2,
  10806. exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
  10807. };
  10808. /**
  10809. * @private
  10810. */
  10811. const withModifiers = (fn, modifiers) => {
  10812. return (event, ...args) => {
  10813. for (let i = 0; i < modifiers.length; i++) {
  10814. const guard = modifierGuards[modifiers[i]];
  10815. if (guard && guard(event, modifiers))
  10816. return;
  10817. }
  10818. return fn(event, ...args);
  10819. };
  10820. };
  10821. // Kept for 2.x compat.
  10822. // Note: IE11 compat for `spacebar` and `del` is removed for now.
  10823. const keyNames = {
  10824. esc: 'escape',
  10825. space: ' ',
  10826. up: 'arrow-up',
  10827. left: 'arrow-left',
  10828. right: 'arrow-right',
  10829. down: 'arrow-down',
  10830. delete: 'backspace'
  10831. };
  10832. /**
  10833. * @private
  10834. */
  10835. const withKeys = (fn, modifiers) => {
  10836. return (event) => {
  10837. if (!('key' in event)) {
  10838. return;
  10839. }
  10840. const eventKey = hyphenate(event.key);
  10841. if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
  10842. return fn(event);
  10843. }
  10844. };
  10845. };
  10846. const vShow = {
  10847. beforeMount(el, { value }, { transition }) {
  10848. el._vod = el.style.display === 'none' ? '' : el.style.display;
  10849. if (transition && value) {
  10850. transition.beforeEnter(el);
  10851. }
  10852. else {
  10853. setDisplay(el, value);
  10854. }
  10855. },
  10856. mounted(el, { value }, { transition }) {
  10857. if (transition && value) {
  10858. transition.enter(el);
  10859. }
  10860. },
  10861. updated(el, { value, oldValue }, { transition }) {
  10862. if (!value === !oldValue)
  10863. return;
  10864. if (transition) {
  10865. if (value) {
  10866. transition.beforeEnter(el);
  10867. setDisplay(el, true);
  10868. transition.enter(el);
  10869. }
  10870. else {
  10871. transition.leave(el, () => {
  10872. setDisplay(el, false);
  10873. });
  10874. }
  10875. }
  10876. else {
  10877. setDisplay(el, value);
  10878. }
  10879. },
  10880. beforeUnmount(el, { value }) {
  10881. setDisplay(el, value);
  10882. }
  10883. };
  10884. function setDisplay(el, value) {
  10885. el.style.display = value ? el._vod : 'none';
  10886. }
  10887. const rendererOptions = /*#__PURE__*/ extend({ patchProp }, nodeOps);
  10888. // lazy create the renderer - this makes core renderer logic tree-shakable
  10889. // in case the user only imports reactivity utilities from Vue.
  10890. let renderer;
  10891. let enabledHydration = false;
  10892. function ensureRenderer() {
  10893. return (renderer ||
  10894. (renderer = createRenderer(rendererOptions)));
  10895. }
  10896. function ensureHydrationRenderer() {
  10897. renderer = enabledHydration
  10898. ? renderer
  10899. : createHydrationRenderer(rendererOptions);
  10900. enabledHydration = true;
  10901. return renderer;
  10902. }
  10903. // use explicit type casts here to avoid import() calls in rolled-up d.ts
  10904. const render = ((...args) => {
  10905. ensureRenderer().render(...args);
  10906. });
  10907. const hydrate = ((...args) => {
  10908. ensureHydrationRenderer().hydrate(...args);
  10909. });
  10910. const createApp = ((...args) => {
  10911. const app = ensureRenderer().createApp(...args);
  10912. {
  10913. injectNativeTagCheck(app);
  10914. injectCompilerOptionsCheck(app);
  10915. }
  10916. const { mount } = app;
  10917. app.mount = (containerOrSelector) => {
  10918. const container = normalizeContainer(containerOrSelector);
  10919. if (!container)
  10920. return;
  10921. const component = app._component;
  10922. if (!isFunction(component) && !component.render && !component.template) {
  10923. // __UNSAFE__
  10924. // Reason: potential execution of JS expressions in in-DOM template.
  10925. // The user must make sure the in-DOM template is trusted. If it's
  10926. // rendered by the server, the template should not contain any user data.
  10927. component.template = container.innerHTML;
  10928. }
  10929. // clear content before mounting
  10930. container.innerHTML = '';
  10931. const proxy = mount(container, false, container instanceof SVGElement);
  10932. if (container instanceof Element) {
  10933. container.removeAttribute('v-cloak');
  10934. container.setAttribute('data-v-app', '');
  10935. }
  10936. return proxy;
  10937. };
  10938. return app;
  10939. });
  10940. const createSSRApp = ((...args) => {
  10941. const app = ensureHydrationRenderer().createApp(...args);
  10942. {
  10943. injectNativeTagCheck(app);
  10944. injectCompilerOptionsCheck(app);
  10945. }
  10946. const { mount } = app;
  10947. app.mount = (containerOrSelector) => {
  10948. const container = normalizeContainer(containerOrSelector);
  10949. if (container) {
  10950. return mount(container, true, container instanceof SVGElement);
  10951. }
  10952. };
  10953. return app;
  10954. });
  10955. function injectNativeTagCheck(app) {
  10956. // Inject `isNativeTag`
  10957. // this is used for component name validation (dev only)
  10958. Object.defineProperty(app.config, 'isNativeTag', {
  10959. value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
  10960. writable: false
  10961. });
  10962. }
  10963. // dev only
  10964. function injectCompilerOptionsCheck(app) {
  10965. if (isRuntimeOnly()) {
  10966. const isCustomElement = app.config.isCustomElement;
  10967. Object.defineProperty(app.config, 'isCustomElement', {
  10968. get() {
  10969. return isCustomElement;
  10970. },
  10971. set() {
  10972. warn(`The \`isCustomElement\` config option is deprecated. Use ` +
  10973. `\`compilerOptions.isCustomElement\` instead.`);
  10974. }
  10975. });
  10976. const compilerOptions = app.config.compilerOptions;
  10977. const msg = `The \`compilerOptions\` config option is only respected when using ` +
  10978. `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
  10979. `Since you are using the runtime-only build, \`compilerOptions\` ` +
  10980. `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
  10981. `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
  10982. `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
  10983. `- For vite: pass it via @vitejs/plugin-vue options. See https://github.com/vitejs/vite/tree/main/packages/plugin-vue#example-for-passing-options-to-vuecompiler-dom`;
  10984. Object.defineProperty(app.config, 'compilerOptions', {
  10985. get() {
  10986. warn(msg);
  10987. return compilerOptions;
  10988. },
  10989. set() {
  10990. warn(msg);
  10991. }
  10992. });
  10993. }
  10994. }
  10995. function normalizeContainer(container) {
  10996. if (isString(container)) {
  10997. const res = document.querySelector(container);
  10998. if (!res) {
  10999. warn(`Failed to mount app: mount target selector "${container}" returned null.`);
  11000. }
  11001. return res;
  11002. }
  11003. if (window.ShadowRoot &&
  11004. container instanceof window.ShadowRoot &&
  11005. container.mode === 'closed') {
  11006. warn(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
  11007. }
  11008. return container;
  11009. }
  11010. /**
  11011. * @internal
  11012. */
  11013. const initDirectivesForSSR = NOOP;
  11014. var runtimeDom = /*#__PURE__*/Object.freeze({
  11015. __proto__: null,
  11016. BaseTransition: BaseTransition,
  11017. Comment: Comment,
  11018. EffectScope: EffectScope,
  11019. Fragment: Fragment,
  11020. KeepAlive: KeepAlive,
  11021. ReactiveEffect: ReactiveEffect,
  11022. Static: Static,
  11023. Suspense: Suspense,
  11024. Teleport: Teleport,
  11025. Text: Text,
  11026. Transition: Transition,
  11027. TransitionGroup: TransitionGroup,
  11028. VueElement: VueElement,
  11029. assertNumber: assertNumber,
  11030. callWithAsyncErrorHandling: callWithAsyncErrorHandling,
  11031. callWithErrorHandling: callWithErrorHandling,
  11032. camelize: camelize,
  11033. capitalize: capitalize,
  11034. cloneVNode: cloneVNode,
  11035. compatUtils: compatUtils,
  11036. computed: computed,
  11037. createApp: createApp,
  11038. createBlock: createBlock,
  11039. createCommentVNode: createCommentVNode,
  11040. createElementBlock: createElementBlock,
  11041. createElementVNode: createBaseVNode,
  11042. createHydrationRenderer: createHydrationRenderer,
  11043. createPropsRestProxy: createPropsRestProxy,
  11044. createRenderer: createRenderer,
  11045. createSSRApp: createSSRApp,
  11046. createSlots: createSlots,
  11047. createStaticVNode: createStaticVNode,
  11048. createTextVNode: createTextVNode,
  11049. createVNode: createVNode,
  11050. customRef: customRef,
  11051. defineAsyncComponent: defineAsyncComponent,
  11052. defineComponent: defineComponent,
  11053. defineCustomElement: defineCustomElement,
  11054. defineEmits: defineEmits,
  11055. defineExpose: defineExpose,
  11056. defineProps: defineProps,
  11057. defineSSRCustomElement: defineSSRCustomElement,
  11058. get devtools () { return devtools; },
  11059. effect: effect,
  11060. effectScope: effectScope,
  11061. getCurrentInstance: getCurrentInstance,
  11062. getCurrentScope: getCurrentScope,
  11063. getTransitionRawChildren: getTransitionRawChildren,
  11064. guardReactiveProps: guardReactiveProps,
  11065. h: h,
  11066. handleError: handleError,
  11067. hydrate: hydrate,
  11068. initCustomFormatter: initCustomFormatter,
  11069. initDirectivesForSSR: initDirectivesForSSR,
  11070. inject: inject,
  11071. isMemoSame: isMemoSame,
  11072. isProxy: isProxy,
  11073. isReactive: isReactive,
  11074. isReadonly: isReadonly,
  11075. isRef: isRef,
  11076. isRuntimeOnly: isRuntimeOnly,
  11077. isShallow: isShallow,
  11078. isVNode: isVNode,
  11079. markRaw: markRaw,
  11080. mergeDefaults: mergeDefaults,
  11081. mergeProps: mergeProps,
  11082. nextTick: nextTick,
  11083. normalizeClass: normalizeClass,
  11084. normalizeProps: normalizeProps,
  11085. normalizeStyle: normalizeStyle,
  11086. onActivated: onActivated,
  11087. onBeforeMount: onBeforeMount,
  11088. onBeforeUnmount: onBeforeUnmount,
  11089. onBeforeUpdate: onBeforeUpdate,
  11090. onDeactivated: onDeactivated,
  11091. onErrorCaptured: onErrorCaptured,
  11092. onMounted: onMounted,
  11093. onRenderTracked: onRenderTracked,
  11094. onRenderTriggered: onRenderTriggered,
  11095. onScopeDispose: onScopeDispose,
  11096. onServerPrefetch: onServerPrefetch,
  11097. onUnmounted: onUnmounted,
  11098. onUpdated: onUpdated,
  11099. openBlock: openBlock,
  11100. popScopeId: popScopeId,
  11101. provide: provide,
  11102. proxyRefs: proxyRefs,
  11103. pushScopeId: pushScopeId,
  11104. queuePostFlushCb: queuePostFlushCb,
  11105. reactive: reactive,
  11106. readonly: readonly,
  11107. ref: ref,
  11108. registerRuntimeCompiler: registerRuntimeCompiler,
  11109. render: render,
  11110. renderList: renderList,
  11111. renderSlot: renderSlot,
  11112. resolveComponent: resolveComponent,
  11113. resolveDirective: resolveDirective,
  11114. resolveDynamicComponent: resolveDynamicComponent,
  11115. resolveFilter: resolveFilter,
  11116. resolveTransitionHooks: resolveTransitionHooks,
  11117. setBlockTracking: setBlockTracking,
  11118. setDevtoolsHook: setDevtoolsHook,
  11119. setTransitionHooks: setTransitionHooks,
  11120. shallowReactive: shallowReactive,
  11121. shallowReadonly: shallowReadonly,
  11122. shallowRef: shallowRef,
  11123. ssrContextKey: ssrContextKey,
  11124. ssrUtils: ssrUtils,
  11125. stop: stop,
  11126. toDisplayString: toDisplayString,
  11127. toHandlerKey: toHandlerKey,
  11128. toHandlers: toHandlers,
  11129. toRaw: toRaw,
  11130. toRef: toRef,
  11131. toRefs: toRefs,
  11132. transformVNodeArgs: transformVNodeArgs,
  11133. triggerRef: triggerRef,
  11134. unref: unref,
  11135. useAttrs: useAttrs,
  11136. useCssModule: useCssModule,
  11137. useCssVars: useCssVars,
  11138. useSSRContext: useSSRContext,
  11139. useSlots: useSlots,
  11140. useTransitionState: useTransitionState,
  11141. vModelCheckbox: vModelCheckbox,
  11142. vModelDynamic: vModelDynamic,
  11143. vModelRadio: vModelRadio,
  11144. vModelSelect: vModelSelect,
  11145. vModelText: vModelText,
  11146. vShow: vShow,
  11147. version: version,
  11148. warn: warn,
  11149. watch: watch,
  11150. watchEffect: watchEffect,
  11151. watchPostEffect: watchPostEffect,
  11152. watchSyncEffect: watchSyncEffect,
  11153. withAsyncContext: withAsyncContext,
  11154. withCtx: withCtx,
  11155. withDefaults: withDefaults,
  11156. withDirectives: withDirectives,
  11157. withKeys: withKeys,
  11158. withMemo: withMemo,
  11159. withModifiers: withModifiers,
  11160. withScopeId: withScopeId
  11161. });
  11162. function initDev() {
  11163. {
  11164. /* istanbul ignore if */
  11165. {
  11166. console.info(`You are running a development build of Vue.\n` +
  11167. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  11168. }
  11169. initCustomFormatter();
  11170. }
  11171. }
  11172. function defaultOnError(error) {
  11173. throw error;
  11174. }
  11175. function defaultOnWarn(msg) {
  11176. console.warn(`[Vue warn] ${msg.message}`);
  11177. }
  11178. function createCompilerError(code, loc, messages, additionalMessage) {
  11179. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  11180. ;
  11181. const error = new SyntaxError(String(msg));
  11182. error.code = code;
  11183. error.loc = loc;
  11184. return error;
  11185. }
  11186. const errorMessages = {
  11187. // parse errors
  11188. [0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  11189. [1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  11190. [2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  11191. [3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  11192. [4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  11193. [5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  11194. [6 /* ErrorCodes.EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  11195. [7 /* ErrorCodes.EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  11196. [8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  11197. [9 /* ErrorCodes.EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  11198. [10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  11199. [11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  11200. [12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  11201. [13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  11202. [14 /* ErrorCodes.MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  11203. [15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  11204. [16 /* ErrorCodes.NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  11205. [17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  11206. [18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  11207. [19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  11208. [21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  11209. [20 /* ErrorCodes.UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  11210. [22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  11211. // Vue-specific parse errors
  11212. [23 /* ErrorCodes.X_INVALID_END_TAG */]: 'Invalid end tag.',
  11213. [24 /* ErrorCodes.X_MISSING_END_TAG */]: 'Element is missing end tag.',
  11214. [25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  11215. [27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  11216. 'Note that dynamic directive argument cannot contain spaces.',
  11217. [26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  11218. // transform errors
  11219. [28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  11220. [29 /* ErrorCodes.X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  11221. [30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  11222. [31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  11223. [32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  11224. [33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  11225. [34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  11226. [35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  11227. [36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  11228. [37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>. ` +
  11229. `When there are multiple named slots, all slots should use <template> ` +
  11230. `syntax to avoid scope ambiguity.`,
  11231. [38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  11232. [39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  11233. `default slot. These children will be ignored.`,
  11234. [40 /* ErrorCodes.X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  11235. [41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  11236. [42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  11237. [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.`,
  11238. [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.`,
  11239. [45 /* ErrorCodes.X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  11240. [46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  11241. // generic errors
  11242. [47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  11243. [48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  11244. [49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  11245. [50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  11246. // just to fulfill types
  11247. [51 /* ErrorCodes.__EXTEND_POINT__ */]: ``
  11248. };
  11249. const FRAGMENT = Symbol(`Fragment` );
  11250. const TELEPORT = Symbol(`Teleport` );
  11251. const SUSPENSE = Symbol(`Suspense` );
  11252. const KEEP_ALIVE = Symbol(`KeepAlive` );
  11253. const BASE_TRANSITION = Symbol(`BaseTransition` );
  11254. const OPEN_BLOCK = Symbol(`openBlock` );
  11255. const CREATE_BLOCK = Symbol(`createBlock` );
  11256. const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
  11257. const CREATE_VNODE = Symbol(`createVNode` );
  11258. const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
  11259. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  11260. const CREATE_TEXT = Symbol(`createTextVNode` );
  11261. const CREATE_STATIC = Symbol(`createStaticVNode` );
  11262. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  11263. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  11264. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  11265. const RESOLVE_FILTER = Symbol(`resolveFilter` );
  11266. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  11267. const RENDER_LIST = Symbol(`renderList` );
  11268. const RENDER_SLOT = Symbol(`renderSlot` );
  11269. const CREATE_SLOTS = Symbol(`createSlots` );
  11270. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  11271. const MERGE_PROPS = Symbol(`mergeProps` );
  11272. const NORMALIZE_CLASS = Symbol(`normalizeClass` );
  11273. const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
  11274. const NORMALIZE_PROPS = Symbol(`normalizeProps` );
  11275. const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
  11276. const TO_HANDLERS = Symbol(`toHandlers` );
  11277. const CAMELIZE = Symbol(`camelize` );
  11278. const CAPITALIZE = Symbol(`capitalize` );
  11279. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  11280. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  11281. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  11282. const POP_SCOPE_ID = Symbol(`popScopeId` );
  11283. const WITH_CTX = Symbol(`withCtx` );
  11284. const UNREF = Symbol(`unref` );
  11285. const IS_REF = Symbol(`isRef` );
  11286. const WITH_MEMO = Symbol(`withMemo` );
  11287. const IS_MEMO_SAME = Symbol(`isMemoSame` );
  11288. // Name mapping for runtime helpers that need to be imported from 'vue' in
  11289. // generated code. Make sure these are correctly exported in the runtime!
  11290. const helperNameMap = {
  11291. [FRAGMENT]: `Fragment`,
  11292. [TELEPORT]: `Teleport`,
  11293. [SUSPENSE]: `Suspense`,
  11294. [KEEP_ALIVE]: `KeepAlive`,
  11295. [BASE_TRANSITION]: `BaseTransition`,
  11296. [OPEN_BLOCK]: `openBlock`,
  11297. [CREATE_BLOCK]: `createBlock`,
  11298. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  11299. [CREATE_VNODE]: `createVNode`,
  11300. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  11301. [CREATE_COMMENT]: `createCommentVNode`,
  11302. [CREATE_TEXT]: `createTextVNode`,
  11303. [CREATE_STATIC]: `createStaticVNode`,
  11304. [RESOLVE_COMPONENT]: `resolveComponent`,
  11305. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  11306. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  11307. [RESOLVE_FILTER]: `resolveFilter`,
  11308. [WITH_DIRECTIVES]: `withDirectives`,
  11309. [RENDER_LIST]: `renderList`,
  11310. [RENDER_SLOT]: `renderSlot`,
  11311. [CREATE_SLOTS]: `createSlots`,
  11312. [TO_DISPLAY_STRING]: `toDisplayString`,
  11313. [MERGE_PROPS]: `mergeProps`,
  11314. [NORMALIZE_CLASS]: `normalizeClass`,
  11315. [NORMALIZE_STYLE]: `normalizeStyle`,
  11316. [NORMALIZE_PROPS]: `normalizeProps`,
  11317. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  11318. [TO_HANDLERS]: `toHandlers`,
  11319. [CAMELIZE]: `camelize`,
  11320. [CAPITALIZE]: `capitalize`,
  11321. [TO_HANDLER_KEY]: `toHandlerKey`,
  11322. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  11323. [PUSH_SCOPE_ID]: `pushScopeId`,
  11324. [POP_SCOPE_ID]: `popScopeId`,
  11325. [WITH_CTX]: `withCtx`,
  11326. [UNREF]: `unref`,
  11327. [IS_REF]: `isRef`,
  11328. [WITH_MEMO]: `withMemo`,
  11329. [IS_MEMO_SAME]: `isMemoSame`
  11330. };
  11331. function registerRuntimeHelpers(helpers) {
  11332. Object.getOwnPropertySymbols(helpers).forEach(s => {
  11333. helperNameMap[s] = helpers[s];
  11334. });
  11335. }
  11336. // AST Utilities ---------------------------------------------------------------
  11337. // Some expressions, e.g. sequence and conditional expressions, are never
  11338. // associated with template nodes, so their source locations are just a stub.
  11339. // Container types like CompoundExpression also don't need a real location.
  11340. const locStub = {
  11341. source: '',
  11342. start: { line: 1, column: 1, offset: 0 },
  11343. end: { line: 1, column: 1, offset: 0 }
  11344. };
  11345. function createRoot(children, loc = locStub) {
  11346. return {
  11347. type: 0 /* NodeTypes.ROOT */,
  11348. children,
  11349. helpers: new Set(),
  11350. components: [],
  11351. directives: [],
  11352. hoists: [],
  11353. imports: [],
  11354. cached: 0,
  11355. temps: 0,
  11356. codegenNode: undefined,
  11357. loc
  11358. };
  11359. }
  11360. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  11361. if (context) {
  11362. if (isBlock) {
  11363. context.helper(OPEN_BLOCK);
  11364. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  11365. }
  11366. else {
  11367. context.helper(getVNodeHelper(context.inSSR, isComponent));
  11368. }
  11369. if (directives) {
  11370. context.helper(WITH_DIRECTIVES);
  11371. }
  11372. }
  11373. return {
  11374. type: 13 /* NodeTypes.VNODE_CALL */,
  11375. tag,
  11376. props,
  11377. children,
  11378. patchFlag,
  11379. dynamicProps,
  11380. directives,
  11381. isBlock,
  11382. disableTracking,
  11383. isComponent,
  11384. loc
  11385. };
  11386. }
  11387. function createArrayExpression(elements, loc = locStub) {
  11388. return {
  11389. type: 17 /* NodeTypes.JS_ARRAY_EXPRESSION */,
  11390. loc,
  11391. elements
  11392. };
  11393. }
  11394. function createObjectExpression(properties, loc = locStub) {
  11395. return {
  11396. type: 15 /* NodeTypes.JS_OBJECT_EXPRESSION */,
  11397. loc,
  11398. properties
  11399. };
  11400. }
  11401. function createObjectProperty(key, value) {
  11402. return {
  11403. type: 16 /* NodeTypes.JS_PROPERTY */,
  11404. loc: locStub,
  11405. key: isString(key) ? createSimpleExpression(key, true) : key,
  11406. value
  11407. };
  11408. }
  11409. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* ConstantTypes.NOT_CONSTANT */) {
  11410. return {
  11411. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  11412. loc,
  11413. content,
  11414. isStatic,
  11415. constType: isStatic ? 3 /* ConstantTypes.CAN_STRINGIFY */ : constType
  11416. };
  11417. }
  11418. function createCompoundExpression(children, loc = locStub) {
  11419. return {
  11420. type: 8 /* NodeTypes.COMPOUND_EXPRESSION */,
  11421. loc,
  11422. children
  11423. };
  11424. }
  11425. function createCallExpression(callee, args = [], loc = locStub) {
  11426. return {
  11427. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  11428. loc,
  11429. callee,
  11430. arguments: args
  11431. };
  11432. }
  11433. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  11434. return {
  11435. type: 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */,
  11436. params,
  11437. returns,
  11438. newline,
  11439. isSlot,
  11440. loc
  11441. };
  11442. }
  11443. function createConditionalExpression(test, consequent, alternate, newline = true) {
  11444. return {
  11445. type: 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */,
  11446. test,
  11447. consequent,
  11448. alternate,
  11449. newline,
  11450. loc: locStub
  11451. };
  11452. }
  11453. function createCacheExpression(index, value, isVNode = false) {
  11454. return {
  11455. type: 20 /* NodeTypes.JS_CACHE_EXPRESSION */,
  11456. index,
  11457. value,
  11458. isVNode,
  11459. loc: locStub
  11460. };
  11461. }
  11462. function createBlockStatement(body) {
  11463. return {
  11464. type: 21 /* NodeTypes.JS_BLOCK_STATEMENT */,
  11465. body,
  11466. loc: locStub
  11467. };
  11468. }
  11469. const isStaticExp = (p) => p.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && p.isStatic;
  11470. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  11471. function isCoreComponent(tag) {
  11472. if (isBuiltInType(tag, 'Teleport')) {
  11473. return TELEPORT;
  11474. }
  11475. else if (isBuiltInType(tag, 'Suspense')) {
  11476. return SUSPENSE;
  11477. }
  11478. else if (isBuiltInType(tag, 'KeepAlive')) {
  11479. return KEEP_ALIVE;
  11480. }
  11481. else if (isBuiltInType(tag, 'BaseTransition')) {
  11482. return BASE_TRANSITION;
  11483. }
  11484. }
  11485. const nonIdentifierRE = /^\d|[^\$\w]/;
  11486. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  11487. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  11488. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  11489. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  11490. /**
  11491. * Simple lexer to check if an expression is a member expression. This is
  11492. * lax and only checks validity at the root level (i.e. does not validate exps
  11493. * inside square brackets), but it's ok since these are only used on template
  11494. * expressions and false positives are invalid expressions in the first place.
  11495. */
  11496. const isMemberExpressionBrowser = (path) => {
  11497. // remove whitespaces around . or [ first
  11498. path = path.trim().replace(whitespaceRE, s => s.trim());
  11499. let state = 0 /* MemberExpLexState.inMemberExp */;
  11500. let stateStack = [];
  11501. let currentOpenBracketCount = 0;
  11502. let currentOpenParensCount = 0;
  11503. let currentStringType = null;
  11504. for (let i = 0; i < path.length; i++) {
  11505. const char = path.charAt(i);
  11506. switch (state) {
  11507. case 0 /* MemberExpLexState.inMemberExp */:
  11508. if (char === '[') {
  11509. stateStack.push(state);
  11510. state = 1 /* MemberExpLexState.inBrackets */;
  11511. currentOpenBracketCount++;
  11512. }
  11513. else if (char === '(') {
  11514. stateStack.push(state);
  11515. state = 2 /* MemberExpLexState.inParens */;
  11516. currentOpenParensCount++;
  11517. }
  11518. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  11519. return false;
  11520. }
  11521. break;
  11522. case 1 /* MemberExpLexState.inBrackets */:
  11523. if (char === `'` || char === `"` || char === '`') {
  11524. stateStack.push(state);
  11525. state = 3 /* MemberExpLexState.inString */;
  11526. currentStringType = char;
  11527. }
  11528. else if (char === `[`) {
  11529. currentOpenBracketCount++;
  11530. }
  11531. else if (char === `]`) {
  11532. if (!--currentOpenBracketCount) {
  11533. state = stateStack.pop();
  11534. }
  11535. }
  11536. break;
  11537. case 2 /* MemberExpLexState.inParens */:
  11538. if (char === `'` || char === `"` || char === '`') {
  11539. stateStack.push(state);
  11540. state = 3 /* MemberExpLexState.inString */;
  11541. currentStringType = char;
  11542. }
  11543. else if (char === `(`) {
  11544. currentOpenParensCount++;
  11545. }
  11546. else if (char === `)`) {
  11547. // if the exp ends as a call then it should not be considered valid
  11548. if (i === path.length - 1) {
  11549. return false;
  11550. }
  11551. if (!--currentOpenParensCount) {
  11552. state = stateStack.pop();
  11553. }
  11554. }
  11555. break;
  11556. case 3 /* MemberExpLexState.inString */:
  11557. if (char === currentStringType) {
  11558. state = stateStack.pop();
  11559. currentStringType = null;
  11560. }
  11561. break;
  11562. }
  11563. }
  11564. return !currentOpenBracketCount && !currentOpenParensCount;
  11565. };
  11566. const isMemberExpression = isMemberExpressionBrowser
  11567. ;
  11568. function getInnerRange(loc, offset, length) {
  11569. const source = loc.source.slice(offset, offset + length);
  11570. const newLoc = {
  11571. source,
  11572. start: advancePositionWithClone(loc.start, loc.source, offset),
  11573. end: loc.end
  11574. };
  11575. if (length != null) {
  11576. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  11577. }
  11578. return newLoc;
  11579. }
  11580. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  11581. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  11582. }
  11583. // advance by mutation without cloning (for performance reasons), since this
  11584. // gets called a lot in the parser
  11585. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  11586. let linesCount = 0;
  11587. let lastNewLinePos = -1;
  11588. for (let i = 0; i < numberOfCharacters; i++) {
  11589. if (source.charCodeAt(i) === 10 /* newline char code */) {
  11590. linesCount++;
  11591. lastNewLinePos = i;
  11592. }
  11593. }
  11594. pos.offset += numberOfCharacters;
  11595. pos.line += linesCount;
  11596. pos.column =
  11597. lastNewLinePos === -1
  11598. ? pos.column + numberOfCharacters
  11599. : numberOfCharacters - lastNewLinePos;
  11600. return pos;
  11601. }
  11602. function assert(condition, msg) {
  11603. /* istanbul ignore if */
  11604. if (!condition) {
  11605. throw new Error(msg || `unexpected compiler condition`);
  11606. }
  11607. }
  11608. function findDir(node, name, allowEmpty = false) {
  11609. for (let i = 0; i < node.props.length; i++) {
  11610. const p = node.props[i];
  11611. if (p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  11612. (allowEmpty || p.exp) &&
  11613. (isString(name) ? p.name === name : name.test(p.name))) {
  11614. return p;
  11615. }
  11616. }
  11617. }
  11618. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  11619. for (let i = 0; i < node.props.length; i++) {
  11620. const p = node.props[i];
  11621. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  11622. if (dynamicOnly)
  11623. continue;
  11624. if (p.name === name && (p.value || allowEmpty)) {
  11625. return p;
  11626. }
  11627. }
  11628. else if (p.name === 'bind' &&
  11629. (p.exp || allowEmpty) &&
  11630. isStaticArgOf(p.arg, name)) {
  11631. return p;
  11632. }
  11633. }
  11634. }
  11635. function isStaticArgOf(arg, name) {
  11636. return !!(arg && isStaticExp(arg) && arg.content === name);
  11637. }
  11638. function hasDynamicKeyVBind(node) {
  11639. return node.props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  11640. p.name === 'bind' &&
  11641. (!p.arg || // v-bind="obj"
  11642. p.arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  11643. !p.arg.isStatic) // v-bind:[foo]
  11644. );
  11645. }
  11646. function isText$1(node) {
  11647. return node.type === 5 /* NodeTypes.INTERPOLATION */ || node.type === 2 /* NodeTypes.TEXT */;
  11648. }
  11649. function isVSlot(p) {
  11650. return p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'slot';
  11651. }
  11652. function isTemplateNode(node) {
  11653. return (node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 3 /* ElementTypes.TEMPLATE */);
  11654. }
  11655. function isSlotOutlet(node) {
  11656. return node.type === 1 /* NodeTypes.ELEMENT */ && node.tagType === 2 /* ElementTypes.SLOT */;
  11657. }
  11658. function getVNodeHelper(ssr, isComponent) {
  11659. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  11660. }
  11661. function getVNodeBlockHelper(ssr, isComponent) {
  11662. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  11663. }
  11664. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  11665. function getUnnormalizedProps(props, callPath = []) {
  11666. if (props &&
  11667. !isString(props) &&
  11668. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  11669. const callee = props.callee;
  11670. if (!isString(callee) && propsHelperSet.has(callee)) {
  11671. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  11672. }
  11673. }
  11674. return [props, callPath];
  11675. }
  11676. function injectProp(node, prop, context) {
  11677. let propsWithInjection;
  11678. /**
  11679. * 1. mergeProps(...)
  11680. * 2. toHandlers(...)
  11681. * 3. normalizeProps(...)
  11682. * 4. normalizeProps(guardReactiveProps(...))
  11683. *
  11684. * we need to get the real props before normalization
  11685. */
  11686. let props = node.type === 13 /* NodeTypes.VNODE_CALL */ ? node.props : node.arguments[2];
  11687. let callPath = [];
  11688. let parentCall;
  11689. if (props &&
  11690. !isString(props) &&
  11691. props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  11692. const ret = getUnnormalizedProps(props);
  11693. props = ret[0];
  11694. callPath = ret[1];
  11695. parentCall = callPath[callPath.length - 1];
  11696. }
  11697. if (props == null || isString(props)) {
  11698. propsWithInjection = createObjectExpression([prop]);
  11699. }
  11700. else if (props.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  11701. // merged props... add ours
  11702. // only inject key to object literal if it's the first argument so that
  11703. // if doesn't override user provided keys
  11704. const first = props.arguments[0];
  11705. if (!isString(first) && first.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  11706. // #6631
  11707. if (!hasProp(prop, first)) {
  11708. first.properties.unshift(prop);
  11709. }
  11710. }
  11711. else {
  11712. if (props.callee === TO_HANDLERS) {
  11713. // #2366
  11714. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  11715. createObjectExpression([prop]),
  11716. props
  11717. ]);
  11718. }
  11719. else {
  11720. props.arguments.unshift(createObjectExpression([prop]));
  11721. }
  11722. }
  11723. !propsWithInjection && (propsWithInjection = props);
  11724. }
  11725. else if (props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  11726. if (!hasProp(prop, props)) {
  11727. props.properties.unshift(prop);
  11728. }
  11729. propsWithInjection = props;
  11730. }
  11731. else {
  11732. // single v-bind with expression, return a merged replacement
  11733. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  11734. createObjectExpression([prop]),
  11735. props
  11736. ]);
  11737. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  11738. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  11739. // the `guardReactiveProps` will no longer be needed
  11740. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  11741. parentCall = callPath[callPath.length - 2];
  11742. }
  11743. }
  11744. if (node.type === 13 /* NodeTypes.VNODE_CALL */) {
  11745. if (parentCall) {
  11746. parentCall.arguments[0] = propsWithInjection;
  11747. }
  11748. else {
  11749. node.props = propsWithInjection;
  11750. }
  11751. }
  11752. else {
  11753. if (parentCall) {
  11754. parentCall.arguments[0] = propsWithInjection;
  11755. }
  11756. else {
  11757. node.arguments[2] = propsWithInjection;
  11758. }
  11759. }
  11760. }
  11761. // check existing key to avoid overriding user provided keys
  11762. function hasProp(prop, props) {
  11763. let result = false;
  11764. if (prop.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  11765. const propKeyName = prop.key.content;
  11766. result = props.properties.some(p => p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  11767. p.key.content === propKeyName);
  11768. }
  11769. return result;
  11770. }
  11771. function toValidAssetId(name, type) {
  11772. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  11773. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  11774. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  11775. })}`;
  11776. }
  11777. function getMemoedVNodeCall(node) {
  11778. if (node.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  11779. return node.arguments[1].returns;
  11780. }
  11781. else {
  11782. return node;
  11783. }
  11784. }
  11785. function makeBlock(node, { helper, removeHelper, inSSR }) {
  11786. if (!node.isBlock) {
  11787. node.isBlock = true;
  11788. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  11789. helper(OPEN_BLOCK);
  11790. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  11791. }
  11792. }
  11793. const deprecationData = {
  11794. ["COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */]: {
  11795. message: `Platform-native elements with "is" prop will no longer be ` +
  11796. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  11797. `prefixed with "vue:".`,
  11798. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  11799. },
  11800. ["COMPILER_V_BIND_SYNC" /* CompilerDeprecationTypes.COMPILER_V_BIND_SYNC */]: {
  11801. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  11802. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  11803. `\`v-model:${key}\`.`,
  11804. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  11805. },
  11806. ["COMPILER_V_BIND_PROP" /* CompilerDeprecationTypes.COMPILER_V_BIND_PROP */]: {
  11807. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  11808. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  11809. },
  11810. ["COMPILER_V_BIND_OBJECT_ORDER" /* CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER */]: {
  11811. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  11812. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  11813. `that appears before v-bind in the case of conflict. ` +
  11814. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  11815. `You can also suppress this warning if the usage is intended.`,
  11816. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  11817. },
  11818. ["COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */]: {
  11819. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  11820. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  11821. },
  11822. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* CompilerDeprecationTypes.COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  11823. message: `v-if / v-for precedence when used on the same element has changed ` +
  11824. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  11825. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  11826. `with <template> tags or use a computed property that filters v-for ` +
  11827. `data source.`,
  11828. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  11829. },
  11830. ["COMPILER_NATIVE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_NATIVE_TEMPLATE */]: {
  11831. message: `<template> with no special directives will render as a native template ` +
  11832. `element instead of its inner content in Vue 3.`
  11833. },
  11834. ["COMPILER_INLINE_TEMPLATE" /* CompilerDeprecationTypes.COMPILER_INLINE_TEMPLATE */]: {
  11835. message: `"inline-template" has been removed in Vue 3.`,
  11836. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  11837. },
  11838. ["COMPILER_FILTER" /* CompilerDeprecationTypes.COMPILER_FILTERS */]: {
  11839. message: `filters have been removed in Vue 3. ` +
  11840. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  11841. `Use method calls or computed properties instead.`,
  11842. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  11843. }
  11844. };
  11845. function getCompatValue(key, context) {
  11846. const config = context.options
  11847. ? context.options.compatConfig
  11848. : context.compatConfig;
  11849. const value = config && config[key];
  11850. if (key === 'MODE') {
  11851. return value || 3; // compiler defaults to v3 behavior
  11852. }
  11853. else {
  11854. return value;
  11855. }
  11856. }
  11857. function isCompatEnabled(key, context) {
  11858. const mode = getCompatValue('MODE', context);
  11859. const value = getCompatValue(key, context);
  11860. // in v3 mode, only enable if explicitly set to true
  11861. // otherwise enable for any non-false value
  11862. return mode === 3 ? value === true : value !== false;
  11863. }
  11864. function checkCompatEnabled(key, context, loc, ...args) {
  11865. const enabled = isCompatEnabled(key, context);
  11866. if (enabled) {
  11867. warnDeprecation(key, context, loc, ...args);
  11868. }
  11869. return enabled;
  11870. }
  11871. function warnDeprecation(key, context, loc, ...args) {
  11872. const val = getCompatValue(key, context);
  11873. if (val === 'suppress-warning') {
  11874. return;
  11875. }
  11876. const { message, link } = deprecationData[key];
  11877. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  11878. const err = new SyntaxError(msg);
  11879. err.code = key;
  11880. if (loc)
  11881. err.loc = loc;
  11882. context.onWarn(err);
  11883. }
  11884. // The default decoder only provides escapes for characters reserved as part of
  11885. // the template syntax, and is only used if the custom renderer did not provide
  11886. // a platform-specific decoder.
  11887. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  11888. const decodeMap = {
  11889. gt: '>',
  11890. lt: '<',
  11891. amp: '&',
  11892. apos: "'",
  11893. quot: '"'
  11894. };
  11895. const defaultParserOptions = {
  11896. delimiters: [`{{`, `}}`],
  11897. getNamespace: () => 0 /* Namespaces.HTML */,
  11898. getTextMode: () => 0 /* TextModes.DATA */,
  11899. isVoidTag: NO,
  11900. isPreTag: NO,
  11901. isCustomElement: NO,
  11902. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  11903. onError: defaultOnError,
  11904. onWarn: defaultOnWarn,
  11905. comments: true
  11906. };
  11907. function baseParse(content, options = {}) {
  11908. const context = createParserContext(content, options);
  11909. const start = getCursor(context);
  11910. return createRoot(parseChildren(context, 0 /* TextModes.DATA */, []), getSelection(context, start));
  11911. }
  11912. function createParserContext(content, rawOptions) {
  11913. const options = extend({}, defaultParserOptions);
  11914. let key;
  11915. for (key in rawOptions) {
  11916. // @ts-ignore
  11917. options[key] =
  11918. rawOptions[key] === undefined
  11919. ? defaultParserOptions[key]
  11920. : rawOptions[key];
  11921. }
  11922. return {
  11923. options,
  11924. column: 1,
  11925. line: 1,
  11926. offset: 0,
  11927. originalSource: content,
  11928. source: content,
  11929. inPre: false,
  11930. inVPre: false,
  11931. onWarn: options.onWarn
  11932. };
  11933. }
  11934. function parseChildren(context, mode, ancestors) {
  11935. const parent = last(ancestors);
  11936. const ns = parent ? parent.ns : 0 /* Namespaces.HTML */;
  11937. const nodes = [];
  11938. while (!isEnd(context, mode, ancestors)) {
  11939. const s = context.source;
  11940. let node = undefined;
  11941. if (mode === 0 /* TextModes.DATA */ || mode === 1 /* TextModes.RCDATA */) {
  11942. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  11943. // '{{'
  11944. node = parseInterpolation(context, mode);
  11945. }
  11946. else if (mode === 0 /* TextModes.DATA */ && s[0] === '<') {
  11947. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  11948. if (s.length === 1) {
  11949. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 1);
  11950. }
  11951. else if (s[1] === '!') {
  11952. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  11953. if (startsWith(s, '<!--')) {
  11954. node = parseComment(context);
  11955. }
  11956. else if (startsWith(s, '<!DOCTYPE')) {
  11957. // Ignore DOCTYPE by a limitation.
  11958. node = parseBogusComment(context);
  11959. }
  11960. else if (startsWith(s, '<![CDATA[')) {
  11961. if (ns !== 0 /* Namespaces.HTML */) {
  11962. node = parseCDATA(context, ancestors);
  11963. }
  11964. else {
  11965. emitError(context, 1 /* ErrorCodes.CDATA_IN_HTML_CONTENT */);
  11966. node = parseBogusComment(context);
  11967. }
  11968. }
  11969. else {
  11970. emitError(context, 11 /* ErrorCodes.INCORRECTLY_OPENED_COMMENT */);
  11971. node = parseBogusComment(context);
  11972. }
  11973. }
  11974. else if (s[1] === '/') {
  11975. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  11976. if (s.length === 2) {
  11977. emitError(context, 5 /* ErrorCodes.EOF_BEFORE_TAG_NAME */, 2);
  11978. }
  11979. else if (s[2] === '>') {
  11980. emitError(context, 14 /* ErrorCodes.MISSING_END_TAG_NAME */, 2);
  11981. advanceBy(context, 3);
  11982. continue;
  11983. }
  11984. else if (/[a-z]/i.test(s[2])) {
  11985. emitError(context, 23 /* ErrorCodes.X_INVALID_END_TAG */);
  11986. parseTag(context, 1 /* TagType.End */, parent);
  11987. continue;
  11988. }
  11989. else {
  11990. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  11991. node = parseBogusComment(context);
  11992. }
  11993. }
  11994. else if (/[a-z]/i.test(s[1])) {
  11995. node = parseElement(context, ancestors);
  11996. }
  11997. else if (s[1] === '?') {
  11998. emitError(context, 21 /* ErrorCodes.UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  11999. node = parseBogusComment(context);
  12000. }
  12001. else {
  12002. emitError(context, 12 /* ErrorCodes.INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  12003. }
  12004. }
  12005. }
  12006. if (!node) {
  12007. node = parseText(context, mode);
  12008. }
  12009. if (isArray(node)) {
  12010. for (let i = 0; i < node.length; i++) {
  12011. pushNode(nodes, node[i]);
  12012. }
  12013. }
  12014. else {
  12015. pushNode(nodes, node);
  12016. }
  12017. }
  12018. // Whitespace handling strategy like v2
  12019. let removedWhitespace = false;
  12020. if (mode !== 2 /* TextModes.RAWTEXT */ && mode !== 1 /* TextModes.RCDATA */) {
  12021. const shouldCondense = context.options.whitespace !== 'preserve';
  12022. for (let i = 0; i < nodes.length; i++) {
  12023. const node = nodes[i];
  12024. if (node.type === 2 /* NodeTypes.TEXT */) {
  12025. if (!context.inPre) {
  12026. if (!/[^\t\r\n\f ]/.test(node.content)) {
  12027. const prev = nodes[i - 1];
  12028. const next = nodes[i + 1];
  12029. // Remove if:
  12030. // - the whitespace is the first or last node, or:
  12031. // - (condense mode) the whitespace is between twos comments, or:
  12032. // - (condense mode) the whitespace is between comment and element, or:
  12033. // - (condense mode) the whitespace is between two elements AND contains newline
  12034. if (!prev ||
  12035. !next ||
  12036. (shouldCondense &&
  12037. ((prev.type === 3 /* NodeTypes.COMMENT */ &&
  12038. next.type === 3 /* NodeTypes.COMMENT */) ||
  12039. (prev.type === 3 /* NodeTypes.COMMENT */ &&
  12040. next.type === 1 /* NodeTypes.ELEMENT */) ||
  12041. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  12042. next.type === 3 /* NodeTypes.COMMENT */) ||
  12043. (prev.type === 1 /* NodeTypes.ELEMENT */ &&
  12044. next.type === 1 /* NodeTypes.ELEMENT */ &&
  12045. /[\r\n]/.test(node.content))))) {
  12046. removedWhitespace = true;
  12047. nodes[i] = null;
  12048. }
  12049. else {
  12050. // Otherwise, the whitespace is condensed into a single space
  12051. node.content = ' ';
  12052. }
  12053. }
  12054. else if (shouldCondense) {
  12055. // in condense mode, consecutive whitespaces in text are condensed
  12056. // down to a single space.
  12057. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  12058. }
  12059. }
  12060. else {
  12061. // #6410 normalize windows newlines in <pre>:
  12062. // in SSR, browsers normalize server-rendered \r\n into a single \n
  12063. // in the DOM
  12064. node.content = node.content.replace(/\r\n/g, '\n');
  12065. }
  12066. }
  12067. // Remove comment nodes if desired by configuration.
  12068. else if (node.type === 3 /* NodeTypes.COMMENT */ && !context.options.comments) {
  12069. removedWhitespace = true;
  12070. nodes[i] = null;
  12071. }
  12072. }
  12073. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  12074. // remove leading newline per html spec
  12075. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  12076. const first = nodes[0];
  12077. if (first && first.type === 2 /* NodeTypes.TEXT */) {
  12078. first.content = first.content.replace(/^\r?\n/, '');
  12079. }
  12080. }
  12081. }
  12082. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  12083. }
  12084. function pushNode(nodes, node) {
  12085. if (node.type === 2 /* NodeTypes.TEXT */) {
  12086. const prev = last(nodes);
  12087. // Merge if both this and the previous node are text and those are
  12088. // consecutive. This happens for cases like "a < b".
  12089. if (prev &&
  12090. prev.type === 2 /* NodeTypes.TEXT */ &&
  12091. prev.loc.end.offset === node.loc.start.offset) {
  12092. prev.content += node.content;
  12093. prev.loc.end = node.loc.end;
  12094. prev.loc.source += node.loc.source;
  12095. return;
  12096. }
  12097. }
  12098. nodes.push(node);
  12099. }
  12100. function parseCDATA(context, ancestors) {
  12101. advanceBy(context, 9);
  12102. const nodes = parseChildren(context, 3 /* TextModes.CDATA */, ancestors);
  12103. if (context.source.length === 0) {
  12104. emitError(context, 6 /* ErrorCodes.EOF_IN_CDATA */);
  12105. }
  12106. else {
  12107. advanceBy(context, 3);
  12108. }
  12109. return nodes;
  12110. }
  12111. function parseComment(context) {
  12112. const start = getCursor(context);
  12113. let content;
  12114. // Regular comment.
  12115. const match = /--(\!)?>/.exec(context.source);
  12116. if (!match) {
  12117. content = context.source.slice(4);
  12118. advanceBy(context, context.source.length);
  12119. emitError(context, 7 /* ErrorCodes.EOF_IN_COMMENT */);
  12120. }
  12121. else {
  12122. if (match.index <= 3) {
  12123. emitError(context, 0 /* ErrorCodes.ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  12124. }
  12125. if (match[1]) {
  12126. emitError(context, 10 /* ErrorCodes.INCORRECTLY_CLOSED_COMMENT */);
  12127. }
  12128. content = context.source.slice(4, match.index);
  12129. // Advancing with reporting nested comments.
  12130. const s = context.source.slice(0, match.index);
  12131. let prevIndex = 1, nestedIndex = 0;
  12132. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  12133. advanceBy(context, nestedIndex - prevIndex + 1);
  12134. if (nestedIndex + 4 < s.length) {
  12135. emitError(context, 16 /* ErrorCodes.NESTED_COMMENT */);
  12136. }
  12137. prevIndex = nestedIndex + 1;
  12138. }
  12139. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  12140. }
  12141. return {
  12142. type: 3 /* NodeTypes.COMMENT */,
  12143. content,
  12144. loc: getSelection(context, start)
  12145. };
  12146. }
  12147. function parseBogusComment(context) {
  12148. const start = getCursor(context);
  12149. const contentStart = context.source[1] === '?' ? 1 : 2;
  12150. let content;
  12151. const closeIndex = context.source.indexOf('>');
  12152. if (closeIndex === -1) {
  12153. content = context.source.slice(contentStart);
  12154. advanceBy(context, context.source.length);
  12155. }
  12156. else {
  12157. content = context.source.slice(contentStart, closeIndex);
  12158. advanceBy(context, closeIndex + 1);
  12159. }
  12160. return {
  12161. type: 3 /* NodeTypes.COMMENT */,
  12162. content,
  12163. loc: getSelection(context, start)
  12164. };
  12165. }
  12166. function parseElement(context, ancestors) {
  12167. // Start tag.
  12168. const wasInPre = context.inPre;
  12169. const wasInVPre = context.inVPre;
  12170. const parent = last(ancestors);
  12171. const element = parseTag(context, 0 /* TagType.Start */, parent);
  12172. const isPreBoundary = context.inPre && !wasInPre;
  12173. const isVPreBoundary = context.inVPre && !wasInVPre;
  12174. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  12175. // #4030 self-closing <pre> tag
  12176. if (isPreBoundary) {
  12177. context.inPre = false;
  12178. }
  12179. if (isVPreBoundary) {
  12180. context.inVPre = false;
  12181. }
  12182. return element;
  12183. }
  12184. // Children.
  12185. ancestors.push(element);
  12186. const mode = context.options.getTextMode(element, parent);
  12187. const children = parseChildren(context, mode, ancestors);
  12188. ancestors.pop();
  12189. element.children = children;
  12190. // End tag.
  12191. if (startsWithEndTagOpen(context.source, element.tag)) {
  12192. parseTag(context, 1 /* TagType.End */, parent);
  12193. }
  12194. else {
  12195. emitError(context, 24 /* ErrorCodes.X_MISSING_END_TAG */, 0, element.loc.start);
  12196. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  12197. const first = children[0];
  12198. if (first && startsWith(first.loc.source, '<!--')) {
  12199. emitError(context, 8 /* ErrorCodes.EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  12200. }
  12201. }
  12202. }
  12203. element.loc = getSelection(context, element.loc.start);
  12204. if (isPreBoundary) {
  12205. context.inPre = false;
  12206. }
  12207. if (isVPreBoundary) {
  12208. context.inVPre = false;
  12209. }
  12210. return element;
  12211. }
  12212. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  12213. function parseTag(context, type, parent) {
  12214. // Tag open.
  12215. const start = getCursor(context);
  12216. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  12217. const tag = match[1];
  12218. const ns = context.options.getNamespace(tag, parent);
  12219. advanceBy(context, match[0].length);
  12220. advanceSpaces(context);
  12221. // save current state in case we need to re-parse attributes with v-pre
  12222. const cursor = getCursor(context);
  12223. const currentSource = context.source;
  12224. // check <pre> tag
  12225. if (context.options.isPreTag(tag)) {
  12226. context.inPre = true;
  12227. }
  12228. // Attributes.
  12229. let props = parseAttributes(context, type);
  12230. // check v-pre
  12231. if (type === 0 /* TagType.Start */ &&
  12232. !context.inVPre &&
  12233. props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'pre')) {
  12234. context.inVPre = true;
  12235. // reset context
  12236. extend(context, cursor);
  12237. context.source = currentSource;
  12238. // re-parse attrs and filter out v-pre itself
  12239. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  12240. }
  12241. // Tag close.
  12242. let isSelfClosing = false;
  12243. if (context.source.length === 0) {
  12244. emitError(context, 9 /* ErrorCodes.EOF_IN_TAG */);
  12245. }
  12246. else {
  12247. isSelfClosing = startsWith(context.source, '/>');
  12248. if (type === 1 /* TagType.End */ && isSelfClosing) {
  12249. emitError(context, 4 /* ErrorCodes.END_TAG_WITH_TRAILING_SOLIDUS */);
  12250. }
  12251. advanceBy(context, isSelfClosing ? 2 : 1);
  12252. }
  12253. if (type === 1 /* TagType.End */) {
  12254. return;
  12255. }
  12256. let tagType = 0 /* ElementTypes.ELEMENT */;
  12257. if (!context.inVPre) {
  12258. if (tag === 'slot') {
  12259. tagType = 2 /* ElementTypes.SLOT */;
  12260. }
  12261. else if (tag === 'template') {
  12262. if (props.some(p => p.type === 7 /* NodeTypes.DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  12263. tagType = 3 /* ElementTypes.TEMPLATE */;
  12264. }
  12265. }
  12266. else if (isComponent(tag, props, context)) {
  12267. tagType = 1 /* ElementTypes.COMPONENT */;
  12268. }
  12269. }
  12270. return {
  12271. type: 1 /* NodeTypes.ELEMENT */,
  12272. ns,
  12273. tag,
  12274. tagType,
  12275. props,
  12276. isSelfClosing,
  12277. children: [],
  12278. loc: getSelection(context, start),
  12279. codegenNode: undefined // to be created during transform phase
  12280. };
  12281. }
  12282. function isComponent(tag, props, context) {
  12283. const options = context.options;
  12284. if (options.isCustomElement(tag)) {
  12285. return false;
  12286. }
  12287. if (tag === 'component' ||
  12288. /^[A-Z]/.test(tag) ||
  12289. isCoreComponent(tag) ||
  12290. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  12291. (options.isNativeTag && !options.isNativeTag(tag))) {
  12292. return true;
  12293. }
  12294. // at this point the tag should be a native tag, but check for potential "is"
  12295. // casting
  12296. for (let i = 0; i < props.length; i++) {
  12297. const p = props[i];
  12298. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  12299. if (p.name === 'is' && p.value) {
  12300. if (p.value.content.startsWith('vue:')) {
  12301. return true;
  12302. }
  12303. }
  12304. }
  12305. else {
  12306. // directive
  12307. // v-is (TODO Deprecate)
  12308. if (p.name === 'is') {
  12309. return true;
  12310. }
  12311. else if (
  12312. // :is on plain element - only treat as component in compat mode
  12313. p.name === 'bind' &&
  12314. isStaticArgOf(p.arg, 'is') &&
  12315. false &&
  12316. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  12317. return true;
  12318. }
  12319. }
  12320. }
  12321. }
  12322. function parseAttributes(context, type) {
  12323. const props = [];
  12324. const attributeNames = new Set();
  12325. while (context.source.length > 0 &&
  12326. !startsWith(context.source, '>') &&
  12327. !startsWith(context.source, '/>')) {
  12328. if (startsWith(context.source, '/')) {
  12329. emitError(context, 22 /* ErrorCodes.UNEXPECTED_SOLIDUS_IN_TAG */);
  12330. advanceBy(context, 1);
  12331. advanceSpaces(context);
  12332. continue;
  12333. }
  12334. if (type === 1 /* TagType.End */) {
  12335. emitError(context, 3 /* ErrorCodes.END_TAG_WITH_ATTRIBUTES */);
  12336. }
  12337. const attr = parseAttribute(context, attributeNames);
  12338. // Trim whitespace between class
  12339. // https://github.com/vuejs/core/issues/4251
  12340. if (attr.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  12341. attr.value &&
  12342. attr.name === 'class') {
  12343. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  12344. }
  12345. if (type === 0 /* TagType.Start */) {
  12346. props.push(attr);
  12347. }
  12348. if (/^[^\t\r\n\f />]/.test(context.source)) {
  12349. emitError(context, 15 /* ErrorCodes.MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  12350. }
  12351. advanceSpaces(context);
  12352. }
  12353. return props;
  12354. }
  12355. function parseAttribute(context, nameSet) {
  12356. // Name.
  12357. const start = getCursor(context);
  12358. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  12359. const name = match[0];
  12360. if (nameSet.has(name)) {
  12361. emitError(context, 2 /* ErrorCodes.DUPLICATE_ATTRIBUTE */);
  12362. }
  12363. nameSet.add(name);
  12364. if (name[0] === '=') {
  12365. emitError(context, 19 /* ErrorCodes.UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  12366. }
  12367. {
  12368. const pattern = /["'<]/g;
  12369. let m;
  12370. while ((m = pattern.exec(name))) {
  12371. emitError(context, 17 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  12372. }
  12373. }
  12374. advanceBy(context, name.length);
  12375. // Value
  12376. let value = undefined;
  12377. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  12378. advanceSpaces(context);
  12379. advanceBy(context, 1);
  12380. advanceSpaces(context);
  12381. value = parseAttributeValue(context);
  12382. if (!value) {
  12383. emitError(context, 13 /* ErrorCodes.MISSING_ATTRIBUTE_VALUE */);
  12384. }
  12385. }
  12386. const loc = getSelection(context, start);
  12387. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  12388. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  12389. let isPropShorthand = startsWith(name, '.');
  12390. let dirName = match[1] ||
  12391. (isPropShorthand || startsWith(name, ':')
  12392. ? 'bind'
  12393. : startsWith(name, '@')
  12394. ? 'on'
  12395. : 'slot');
  12396. let arg;
  12397. if (match[2]) {
  12398. const isSlot = dirName === 'slot';
  12399. const startOffset = name.lastIndexOf(match[2]);
  12400. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  12401. let content = match[2];
  12402. let isStatic = true;
  12403. if (content.startsWith('[')) {
  12404. isStatic = false;
  12405. if (!content.endsWith(']')) {
  12406. emitError(context, 27 /* ErrorCodes.X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  12407. content = content.slice(1);
  12408. }
  12409. else {
  12410. content = content.slice(1, content.length - 1);
  12411. }
  12412. }
  12413. else if (isSlot) {
  12414. // #1241 special case for v-slot: vuetify relies extensively on slot
  12415. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  12416. // supports such usage so we are keeping it consistent with 2.x.
  12417. content += match[3] || '';
  12418. }
  12419. arg = {
  12420. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  12421. content,
  12422. isStatic,
  12423. constType: isStatic
  12424. ? 3 /* ConstantTypes.CAN_STRINGIFY */
  12425. : 0 /* ConstantTypes.NOT_CONSTANT */,
  12426. loc
  12427. };
  12428. }
  12429. if (value && value.isQuoted) {
  12430. const valueLoc = value.loc;
  12431. valueLoc.start.offset++;
  12432. valueLoc.start.column++;
  12433. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  12434. valueLoc.source = valueLoc.source.slice(1, -1);
  12435. }
  12436. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  12437. if (isPropShorthand)
  12438. modifiers.push('prop');
  12439. return {
  12440. type: 7 /* NodeTypes.DIRECTIVE */,
  12441. name: dirName,
  12442. exp: value && {
  12443. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  12444. content: value.content,
  12445. isStatic: false,
  12446. // Treat as non-constant by default. This can be potentially set to
  12447. // other values by `transformExpression` to make it eligible for hoisting.
  12448. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  12449. loc: value.loc
  12450. },
  12451. arg,
  12452. modifiers,
  12453. loc
  12454. };
  12455. }
  12456. // missing directive name or illegal directive name
  12457. if (!context.inVPre && startsWith(name, 'v-')) {
  12458. emitError(context, 26 /* ErrorCodes.X_MISSING_DIRECTIVE_NAME */);
  12459. }
  12460. return {
  12461. type: 6 /* NodeTypes.ATTRIBUTE */,
  12462. name,
  12463. value: value && {
  12464. type: 2 /* NodeTypes.TEXT */,
  12465. content: value.content,
  12466. loc: value.loc
  12467. },
  12468. loc
  12469. };
  12470. }
  12471. function parseAttributeValue(context) {
  12472. const start = getCursor(context);
  12473. let content;
  12474. const quote = context.source[0];
  12475. const isQuoted = quote === `"` || quote === `'`;
  12476. if (isQuoted) {
  12477. // Quoted value.
  12478. advanceBy(context, 1);
  12479. const endIndex = context.source.indexOf(quote);
  12480. if (endIndex === -1) {
  12481. content = parseTextData(context, context.source.length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  12482. }
  12483. else {
  12484. content = parseTextData(context, endIndex, 4 /* TextModes.ATTRIBUTE_VALUE */);
  12485. advanceBy(context, 1);
  12486. }
  12487. }
  12488. else {
  12489. // Unquoted
  12490. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  12491. if (!match) {
  12492. return undefined;
  12493. }
  12494. const unexpectedChars = /["'<=`]/g;
  12495. let m;
  12496. while ((m = unexpectedChars.exec(match[0]))) {
  12497. emitError(context, 18 /* ErrorCodes.UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  12498. }
  12499. content = parseTextData(context, match[0].length, 4 /* TextModes.ATTRIBUTE_VALUE */);
  12500. }
  12501. return { content, isQuoted, loc: getSelection(context, start) };
  12502. }
  12503. function parseInterpolation(context, mode) {
  12504. const [open, close] = context.options.delimiters;
  12505. const closeIndex = context.source.indexOf(close, open.length);
  12506. if (closeIndex === -1) {
  12507. emitError(context, 25 /* ErrorCodes.X_MISSING_INTERPOLATION_END */);
  12508. return undefined;
  12509. }
  12510. const start = getCursor(context);
  12511. advanceBy(context, open.length);
  12512. const innerStart = getCursor(context);
  12513. const innerEnd = getCursor(context);
  12514. const rawContentLength = closeIndex - open.length;
  12515. const rawContent = context.source.slice(0, rawContentLength);
  12516. const preTrimContent = parseTextData(context, rawContentLength, mode);
  12517. const content = preTrimContent.trim();
  12518. const startOffset = preTrimContent.indexOf(content);
  12519. if (startOffset > 0) {
  12520. advancePositionWithMutation(innerStart, rawContent, startOffset);
  12521. }
  12522. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  12523. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  12524. advanceBy(context, close.length);
  12525. return {
  12526. type: 5 /* NodeTypes.INTERPOLATION */,
  12527. content: {
  12528. type: 4 /* NodeTypes.SIMPLE_EXPRESSION */,
  12529. isStatic: false,
  12530. // Set `isConstant` to false by default and will decide in transformExpression
  12531. constType: 0 /* ConstantTypes.NOT_CONSTANT */,
  12532. content,
  12533. loc: getSelection(context, innerStart, innerEnd)
  12534. },
  12535. loc: getSelection(context, start)
  12536. };
  12537. }
  12538. function parseText(context, mode) {
  12539. const endTokens = mode === 3 /* TextModes.CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  12540. let endIndex = context.source.length;
  12541. for (let i = 0; i < endTokens.length; i++) {
  12542. const index = context.source.indexOf(endTokens[i], 1);
  12543. if (index !== -1 && endIndex > index) {
  12544. endIndex = index;
  12545. }
  12546. }
  12547. const start = getCursor(context);
  12548. const content = parseTextData(context, endIndex, mode);
  12549. return {
  12550. type: 2 /* NodeTypes.TEXT */,
  12551. content,
  12552. loc: getSelection(context, start)
  12553. };
  12554. }
  12555. /**
  12556. * Get text data with a given length from the current location.
  12557. * This translates HTML entities in the text data.
  12558. */
  12559. function parseTextData(context, length, mode) {
  12560. const rawText = context.source.slice(0, length);
  12561. advanceBy(context, length);
  12562. if (mode === 2 /* TextModes.RAWTEXT */ ||
  12563. mode === 3 /* TextModes.CDATA */ ||
  12564. !rawText.includes('&')) {
  12565. return rawText;
  12566. }
  12567. else {
  12568. // DATA or RCDATA containing "&"". Entity decoding required.
  12569. return context.options.decodeEntities(rawText, mode === 4 /* TextModes.ATTRIBUTE_VALUE */);
  12570. }
  12571. }
  12572. function getCursor(context) {
  12573. const { column, line, offset } = context;
  12574. return { column, line, offset };
  12575. }
  12576. function getSelection(context, start, end) {
  12577. end = end || getCursor(context);
  12578. return {
  12579. start,
  12580. end,
  12581. source: context.originalSource.slice(start.offset, end.offset)
  12582. };
  12583. }
  12584. function last(xs) {
  12585. return xs[xs.length - 1];
  12586. }
  12587. function startsWith(source, searchString) {
  12588. return source.startsWith(searchString);
  12589. }
  12590. function advanceBy(context, numberOfCharacters) {
  12591. const { source } = context;
  12592. advancePositionWithMutation(context, source, numberOfCharacters);
  12593. context.source = source.slice(numberOfCharacters);
  12594. }
  12595. function advanceSpaces(context) {
  12596. const match = /^[\t\r\n\f ]+/.exec(context.source);
  12597. if (match) {
  12598. advanceBy(context, match[0].length);
  12599. }
  12600. }
  12601. function getNewPosition(context, start, numberOfCharacters) {
  12602. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  12603. }
  12604. function emitError(context, code, offset, loc = getCursor(context)) {
  12605. if (offset) {
  12606. loc.offset += offset;
  12607. loc.column += offset;
  12608. }
  12609. context.options.onError(createCompilerError(code, {
  12610. start: loc,
  12611. end: loc,
  12612. source: ''
  12613. }));
  12614. }
  12615. function isEnd(context, mode, ancestors) {
  12616. const s = context.source;
  12617. switch (mode) {
  12618. case 0 /* TextModes.DATA */:
  12619. if (startsWith(s, '</')) {
  12620. // TODO: probably bad performance
  12621. for (let i = ancestors.length - 1; i >= 0; --i) {
  12622. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  12623. return true;
  12624. }
  12625. }
  12626. }
  12627. break;
  12628. case 1 /* TextModes.RCDATA */:
  12629. case 2 /* TextModes.RAWTEXT */: {
  12630. const parent = last(ancestors);
  12631. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  12632. return true;
  12633. }
  12634. break;
  12635. }
  12636. case 3 /* TextModes.CDATA */:
  12637. if (startsWith(s, ']]>')) {
  12638. return true;
  12639. }
  12640. break;
  12641. }
  12642. return !s;
  12643. }
  12644. function startsWithEndTagOpen(source, tag) {
  12645. return (startsWith(source, '</') &&
  12646. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  12647. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  12648. }
  12649. function hoistStatic(root, context) {
  12650. walk(root, context,
  12651. // Root node is unfortunately non-hoistable due to potential parent
  12652. // fallthrough attributes.
  12653. isSingleElementRoot(root, root.children[0]));
  12654. }
  12655. function isSingleElementRoot(root, child) {
  12656. const { children } = root;
  12657. return (children.length === 1 &&
  12658. child.type === 1 /* NodeTypes.ELEMENT */ &&
  12659. !isSlotOutlet(child));
  12660. }
  12661. function walk(node, context, doNotHoistNode = false) {
  12662. const { children } = node;
  12663. const originalCount = children.length;
  12664. let hoistedCount = 0;
  12665. for (let i = 0; i < children.length; i++) {
  12666. const child = children[i];
  12667. // only plain elements & text calls are eligible for hoisting.
  12668. if (child.type === 1 /* NodeTypes.ELEMENT */ &&
  12669. child.tagType === 0 /* ElementTypes.ELEMENT */) {
  12670. const constantType = doNotHoistNode
  12671. ? 0 /* ConstantTypes.NOT_CONSTANT */
  12672. : getConstantType(child, context);
  12673. if (constantType > 0 /* ConstantTypes.NOT_CONSTANT */) {
  12674. if (constantType >= 2 /* ConstantTypes.CAN_HOIST */) {
  12675. child.codegenNode.patchFlag =
  12676. -1 /* PatchFlags.HOISTED */ + (` /* HOISTED */` );
  12677. child.codegenNode = context.hoist(child.codegenNode);
  12678. hoistedCount++;
  12679. continue;
  12680. }
  12681. }
  12682. else {
  12683. // node may contain dynamic children, but its props may be eligible for
  12684. // hoisting.
  12685. const codegenNode = child.codegenNode;
  12686. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  12687. const flag = getPatchFlag(codegenNode);
  12688. if ((!flag ||
  12689. flag === 512 /* PatchFlags.NEED_PATCH */ ||
  12690. flag === 1 /* PatchFlags.TEXT */) &&
  12691. getGeneratedPropsConstantType(child, context) >=
  12692. 2 /* ConstantTypes.CAN_HOIST */) {
  12693. const props = getNodeProps(child);
  12694. if (props) {
  12695. codegenNode.props = context.hoist(props);
  12696. }
  12697. }
  12698. if (codegenNode.dynamicProps) {
  12699. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  12700. }
  12701. }
  12702. }
  12703. }
  12704. // walk further
  12705. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  12706. const isComponent = child.tagType === 1 /* ElementTypes.COMPONENT */;
  12707. if (isComponent) {
  12708. context.scopes.vSlot++;
  12709. }
  12710. walk(child, context);
  12711. if (isComponent) {
  12712. context.scopes.vSlot--;
  12713. }
  12714. }
  12715. else if (child.type === 11 /* NodeTypes.FOR */) {
  12716. // Do not hoist v-for single child because it has to be a block
  12717. walk(child, context, child.children.length === 1);
  12718. }
  12719. else if (child.type === 9 /* NodeTypes.IF */) {
  12720. for (let i = 0; i < child.branches.length; i++) {
  12721. // Do not hoist v-if single child because it has to be a block
  12722. walk(child.branches[i], context, child.branches[i].children.length === 1);
  12723. }
  12724. }
  12725. }
  12726. if (hoistedCount && context.transformHoist) {
  12727. context.transformHoist(children, context, node);
  12728. }
  12729. // all children were hoisted - the entire children array is hoistable.
  12730. if (hoistedCount &&
  12731. hoistedCount === originalCount &&
  12732. node.type === 1 /* NodeTypes.ELEMENT */ &&
  12733. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  12734. node.codegenNode &&
  12735. node.codegenNode.type === 13 /* NodeTypes.VNODE_CALL */ &&
  12736. isArray(node.codegenNode.children)) {
  12737. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  12738. }
  12739. }
  12740. function getConstantType(node, context) {
  12741. const { constantCache } = context;
  12742. switch (node.type) {
  12743. case 1 /* NodeTypes.ELEMENT */:
  12744. if (node.tagType !== 0 /* ElementTypes.ELEMENT */) {
  12745. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12746. }
  12747. const cached = constantCache.get(node);
  12748. if (cached !== undefined) {
  12749. return cached;
  12750. }
  12751. const codegenNode = node.codegenNode;
  12752. if (codegenNode.type !== 13 /* NodeTypes.VNODE_CALL */) {
  12753. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12754. }
  12755. if (codegenNode.isBlock &&
  12756. node.tag !== 'svg' &&
  12757. node.tag !== 'foreignObject') {
  12758. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12759. }
  12760. const flag = getPatchFlag(codegenNode);
  12761. if (!flag) {
  12762. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  12763. // Element itself has no patch flag. However we still need to check:
  12764. // 1. Even for a node with no patch flag, it is possible for it to contain
  12765. // non-hoistable expressions that refers to scope variables, e.g. compiler
  12766. // injected keys or cached event handlers. Therefore we need to always
  12767. // check the codegenNode's props to be sure.
  12768. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  12769. if (generatedPropsType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12770. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  12771. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12772. }
  12773. if (generatedPropsType < returnType) {
  12774. returnType = generatedPropsType;
  12775. }
  12776. // 2. its children.
  12777. for (let i = 0; i < node.children.length; i++) {
  12778. const childType = getConstantType(node.children[i], context);
  12779. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12780. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  12781. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12782. }
  12783. if (childType < returnType) {
  12784. returnType = childType;
  12785. }
  12786. }
  12787. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  12788. // type, check if any of the props can cause the type to be lowered
  12789. // we can skip can_patch because it's guaranteed by the absence of a
  12790. // patchFlag.
  12791. if (returnType > 1 /* ConstantTypes.CAN_SKIP_PATCH */) {
  12792. for (let i = 0; i < node.props.length; i++) {
  12793. const p = node.props[i];
  12794. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'bind' && p.exp) {
  12795. const expType = getConstantType(p.exp, context);
  12796. if (expType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12797. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  12798. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12799. }
  12800. if (expType < returnType) {
  12801. returnType = expType;
  12802. }
  12803. }
  12804. }
  12805. }
  12806. // only svg/foreignObject could be block here, however if they are
  12807. // static then they don't need to be blocks since there will be no
  12808. // nested updates.
  12809. if (codegenNode.isBlock) {
  12810. // except set custom directives.
  12811. for (let i = 0; i < node.props.length; i++) {
  12812. const p = node.props[i];
  12813. if (p.type === 7 /* NodeTypes.DIRECTIVE */) {
  12814. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  12815. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12816. }
  12817. }
  12818. context.removeHelper(OPEN_BLOCK);
  12819. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  12820. codegenNode.isBlock = false;
  12821. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  12822. }
  12823. constantCache.set(node, returnType);
  12824. return returnType;
  12825. }
  12826. else {
  12827. constantCache.set(node, 0 /* ConstantTypes.NOT_CONSTANT */);
  12828. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12829. }
  12830. case 2 /* NodeTypes.TEXT */:
  12831. case 3 /* NodeTypes.COMMENT */:
  12832. return 3 /* ConstantTypes.CAN_STRINGIFY */;
  12833. case 9 /* NodeTypes.IF */:
  12834. case 11 /* NodeTypes.FOR */:
  12835. case 10 /* NodeTypes.IF_BRANCH */:
  12836. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12837. case 5 /* NodeTypes.INTERPOLATION */:
  12838. case 12 /* NodeTypes.TEXT_CALL */:
  12839. return getConstantType(node.content, context);
  12840. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  12841. return node.constType;
  12842. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  12843. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  12844. for (let i = 0; i < node.children.length; i++) {
  12845. const child = node.children[i];
  12846. if (isString(child) || isSymbol(child)) {
  12847. continue;
  12848. }
  12849. const childType = getConstantType(child, context);
  12850. if (childType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12851. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12852. }
  12853. else if (childType < returnType) {
  12854. returnType = childType;
  12855. }
  12856. }
  12857. return returnType;
  12858. default:
  12859. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12860. }
  12861. }
  12862. const allowHoistedHelperSet = new Set([
  12863. NORMALIZE_CLASS,
  12864. NORMALIZE_STYLE,
  12865. NORMALIZE_PROPS,
  12866. GUARD_REACTIVE_PROPS
  12867. ]);
  12868. function getConstantTypeOfHelperCall(value, context) {
  12869. if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */ &&
  12870. !isString(value.callee) &&
  12871. allowHoistedHelperSet.has(value.callee)) {
  12872. const arg = value.arguments[0];
  12873. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  12874. return getConstantType(arg, context);
  12875. }
  12876. else if (arg.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  12877. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  12878. return getConstantTypeOfHelperCall(arg, context);
  12879. }
  12880. }
  12881. return 0 /* ConstantTypes.NOT_CONSTANT */;
  12882. }
  12883. function getGeneratedPropsConstantType(node, context) {
  12884. let returnType = 3 /* ConstantTypes.CAN_STRINGIFY */;
  12885. const props = getNodeProps(node);
  12886. if (props && props.type === 15 /* NodeTypes.JS_OBJECT_EXPRESSION */) {
  12887. const { properties } = props;
  12888. for (let i = 0; i < properties.length; i++) {
  12889. const { key, value } = properties[i];
  12890. const keyType = getConstantType(key, context);
  12891. if (keyType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12892. return keyType;
  12893. }
  12894. if (keyType < returnType) {
  12895. returnType = keyType;
  12896. }
  12897. let valueType;
  12898. if (value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  12899. valueType = getConstantType(value, context);
  12900. }
  12901. else if (value.type === 14 /* NodeTypes.JS_CALL_EXPRESSION */) {
  12902. // some helper calls can be hoisted,
  12903. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  12904. // in this case we need to respect the ConstantType of the helper's arguments
  12905. valueType = getConstantTypeOfHelperCall(value, context);
  12906. }
  12907. else {
  12908. valueType = 0 /* ConstantTypes.NOT_CONSTANT */;
  12909. }
  12910. if (valueType === 0 /* ConstantTypes.NOT_CONSTANT */) {
  12911. return valueType;
  12912. }
  12913. if (valueType < returnType) {
  12914. returnType = valueType;
  12915. }
  12916. }
  12917. }
  12918. return returnType;
  12919. }
  12920. function getNodeProps(node) {
  12921. const codegenNode = node.codegenNode;
  12922. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  12923. return codegenNode.props;
  12924. }
  12925. }
  12926. function getPatchFlag(node) {
  12927. const flag = node.patchFlag;
  12928. return flag ? parseInt(flag, 10) : undefined;
  12929. }
  12930. 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 }) {
  12931. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  12932. const context = {
  12933. // options
  12934. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  12935. prefixIdentifiers,
  12936. hoistStatic,
  12937. cacheHandlers,
  12938. nodeTransforms,
  12939. directiveTransforms,
  12940. transformHoist,
  12941. isBuiltInComponent,
  12942. isCustomElement,
  12943. expressionPlugins,
  12944. scopeId,
  12945. slotted,
  12946. ssr,
  12947. inSSR,
  12948. ssrCssVars,
  12949. bindingMetadata,
  12950. inline,
  12951. isTS,
  12952. onError,
  12953. onWarn,
  12954. compatConfig,
  12955. // state
  12956. root,
  12957. helpers: new Map(),
  12958. components: new Set(),
  12959. directives: new Set(),
  12960. hoists: [],
  12961. imports: [],
  12962. constantCache: new Map(),
  12963. temps: 0,
  12964. cached: 0,
  12965. identifiers: Object.create(null),
  12966. scopes: {
  12967. vFor: 0,
  12968. vSlot: 0,
  12969. vPre: 0,
  12970. vOnce: 0
  12971. },
  12972. parent: null,
  12973. currentNode: root,
  12974. childIndex: 0,
  12975. inVOnce: false,
  12976. // methods
  12977. helper(name) {
  12978. const count = context.helpers.get(name) || 0;
  12979. context.helpers.set(name, count + 1);
  12980. return name;
  12981. },
  12982. removeHelper(name) {
  12983. const count = context.helpers.get(name);
  12984. if (count) {
  12985. const currentCount = count - 1;
  12986. if (!currentCount) {
  12987. context.helpers.delete(name);
  12988. }
  12989. else {
  12990. context.helpers.set(name, currentCount);
  12991. }
  12992. }
  12993. },
  12994. helperString(name) {
  12995. return `_${helperNameMap[context.helper(name)]}`;
  12996. },
  12997. replaceNode(node) {
  12998. /* istanbul ignore if */
  12999. {
  13000. if (!context.currentNode) {
  13001. throw new Error(`Node being replaced is already removed.`);
  13002. }
  13003. if (!context.parent) {
  13004. throw new Error(`Cannot replace root node.`);
  13005. }
  13006. }
  13007. context.parent.children[context.childIndex] = context.currentNode = node;
  13008. },
  13009. removeNode(node) {
  13010. if (!context.parent) {
  13011. throw new Error(`Cannot remove root node.`);
  13012. }
  13013. const list = context.parent.children;
  13014. const removalIndex = node
  13015. ? list.indexOf(node)
  13016. : context.currentNode
  13017. ? context.childIndex
  13018. : -1;
  13019. /* istanbul ignore if */
  13020. if (removalIndex < 0) {
  13021. throw new Error(`node being removed is not a child of current parent`);
  13022. }
  13023. if (!node || node === context.currentNode) {
  13024. // current node removed
  13025. context.currentNode = null;
  13026. context.onNodeRemoved();
  13027. }
  13028. else {
  13029. // sibling node removed
  13030. if (context.childIndex > removalIndex) {
  13031. context.childIndex--;
  13032. context.onNodeRemoved();
  13033. }
  13034. }
  13035. context.parent.children.splice(removalIndex, 1);
  13036. },
  13037. onNodeRemoved: () => { },
  13038. addIdentifiers(exp) {
  13039. },
  13040. removeIdentifiers(exp) {
  13041. },
  13042. hoist(exp) {
  13043. if (isString(exp))
  13044. exp = createSimpleExpression(exp);
  13045. context.hoists.push(exp);
  13046. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* ConstantTypes.CAN_HOIST */);
  13047. identifier.hoisted = exp;
  13048. return identifier;
  13049. },
  13050. cache(exp, isVNode = false) {
  13051. return createCacheExpression(context.cached++, exp, isVNode);
  13052. }
  13053. };
  13054. return context;
  13055. }
  13056. function transform(root, options) {
  13057. const context = createTransformContext(root, options);
  13058. traverseNode(root, context);
  13059. if (options.hoistStatic) {
  13060. hoistStatic(root, context);
  13061. }
  13062. if (!options.ssr) {
  13063. createRootCodegen(root, context);
  13064. }
  13065. // finalize meta information
  13066. root.helpers = new Set([...context.helpers.keys()]);
  13067. root.components = [...context.components];
  13068. root.directives = [...context.directives];
  13069. root.imports = context.imports;
  13070. root.hoists = context.hoists;
  13071. root.temps = context.temps;
  13072. root.cached = context.cached;
  13073. }
  13074. function createRootCodegen(root, context) {
  13075. const { helper } = context;
  13076. const { children } = root;
  13077. if (children.length === 1) {
  13078. const child = children[0];
  13079. // if the single child is an element, turn it into a block.
  13080. if (isSingleElementRoot(root, child) && child.codegenNode) {
  13081. // single element root is never hoisted so codegenNode will never be
  13082. // SimpleExpressionNode
  13083. const codegenNode = child.codegenNode;
  13084. if (codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  13085. makeBlock(codegenNode, context);
  13086. }
  13087. root.codegenNode = codegenNode;
  13088. }
  13089. else {
  13090. // - single <slot/>, IfNode, ForNode: already blocks.
  13091. // - single text node: always patched.
  13092. // root codegen falls through via genNode()
  13093. root.codegenNode = child;
  13094. }
  13095. }
  13096. else if (children.length > 1) {
  13097. // root has multiple nodes - return a fragment block.
  13098. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  13099. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  13100. // check if the fragment actually contains a single valid child with
  13101. // the rest being comments
  13102. if (children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  13103. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  13104. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  13105. }
  13106. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
  13107. }
  13108. else ;
  13109. }
  13110. function traverseChildren(parent, context) {
  13111. let i = 0;
  13112. const nodeRemoved = () => {
  13113. i--;
  13114. };
  13115. for (; i < parent.children.length; i++) {
  13116. const child = parent.children[i];
  13117. if (isString(child))
  13118. continue;
  13119. context.parent = parent;
  13120. context.childIndex = i;
  13121. context.onNodeRemoved = nodeRemoved;
  13122. traverseNode(child, context);
  13123. }
  13124. }
  13125. function traverseNode(node, context) {
  13126. context.currentNode = node;
  13127. // apply transform plugins
  13128. const { nodeTransforms } = context;
  13129. const exitFns = [];
  13130. for (let i = 0; i < nodeTransforms.length; i++) {
  13131. const onExit = nodeTransforms[i](node, context);
  13132. if (onExit) {
  13133. if (isArray(onExit)) {
  13134. exitFns.push(...onExit);
  13135. }
  13136. else {
  13137. exitFns.push(onExit);
  13138. }
  13139. }
  13140. if (!context.currentNode) {
  13141. // node was removed
  13142. return;
  13143. }
  13144. else {
  13145. // node may have been replaced
  13146. node = context.currentNode;
  13147. }
  13148. }
  13149. switch (node.type) {
  13150. case 3 /* NodeTypes.COMMENT */:
  13151. if (!context.ssr) {
  13152. // inject import for the Comment symbol, which is needed for creating
  13153. // comment nodes with `createVNode`
  13154. context.helper(CREATE_COMMENT);
  13155. }
  13156. break;
  13157. case 5 /* NodeTypes.INTERPOLATION */:
  13158. // no need to traverse, but we need to inject toString helper
  13159. if (!context.ssr) {
  13160. context.helper(TO_DISPLAY_STRING);
  13161. }
  13162. break;
  13163. // for container types, further traverse downwards
  13164. case 9 /* NodeTypes.IF */:
  13165. for (let i = 0; i < node.branches.length; i++) {
  13166. traverseNode(node.branches[i], context);
  13167. }
  13168. break;
  13169. case 10 /* NodeTypes.IF_BRANCH */:
  13170. case 11 /* NodeTypes.FOR */:
  13171. case 1 /* NodeTypes.ELEMENT */:
  13172. case 0 /* NodeTypes.ROOT */:
  13173. traverseChildren(node, context);
  13174. break;
  13175. }
  13176. // exit transforms
  13177. context.currentNode = node;
  13178. let i = exitFns.length;
  13179. while (i--) {
  13180. exitFns[i]();
  13181. }
  13182. }
  13183. function createStructuralDirectiveTransform(name, fn) {
  13184. const matches = isString(name)
  13185. ? (n) => n === name
  13186. : (n) => name.test(n);
  13187. return (node, context) => {
  13188. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  13189. const { props } = node;
  13190. // structural directive transforms are not concerned with slots
  13191. // as they are handled separately in vSlot.ts
  13192. if (node.tagType === 3 /* ElementTypes.TEMPLATE */ && props.some(isVSlot)) {
  13193. return;
  13194. }
  13195. const exitFns = [];
  13196. for (let i = 0; i < props.length; i++) {
  13197. const prop = props[i];
  13198. if (prop.type === 7 /* NodeTypes.DIRECTIVE */ && matches(prop.name)) {
  13199. // structural directives are removed to avoid infinite recursion
  13200. // also we remove them *before* applying so that it can further
  13201. // traverse itself in case it moves the node around
  13202. props.splice(i, 1);
  13203. i--;
  13204. const onExit = fn(node, prop, context);
  13205. if (onExit)
  13206. exitFns.push(onExit);
  13207. }
  13208. }
  13209. return exitFns;
  13210. }
  13211. };
  13212. }
  13213. const PURE_ANNOTATION = `/*#__PURE__*/`;
  13214. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  13215. 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 }) {
  13216. const context = {
  13217. mode,
  13218. prefixIdentifiers,
  13219. sourceMap,
  13220. filename,
  13221. scopeId,
  13222. optimizeImports,
  13223. runtimeGlobalName,
  13224. runtimeModuleName,
  13225. ssrRuntimeModuleName,
  13226. ssr,
  13227. isTS,
  13228. inSSR,
  13229. source: ast.loc.source,
  13230. code: ``,
  13231. column: 1,
  13232. line: 1,
  13233. offset: 0,
  13234. indentLevel: 0,
  13235. pure: false,
  13236. map: undefined,
  13237. helper(key) {
  13238. return `_${helperNameMap[key]}`;
  13239. },
  13240. push(code, node) {
  13241. context.code += code;
  13242. },
  13243. indent() {
  13244. newline(++context.indentLevel);
  13245. },
  13246. deindent(withoutNewLine = false) {
  13247. if (withoutNewLine) {
  13248. --context.indentLevel;
  13249. }
  13250. else {
  13251. newline(--context.indentLevel);
  13252. }
  13253. },
  13254. newline() {
  13255. newline(context.indentLevel);
  13256. }
  13257. };
  13258. function newline(n) {
  13259. context.push('\n' + ` `.repeat(n));
  13260. }
  13261. return context;
  13262. }
  13263. function generate(ast, options = {}) {
  13264. const context = createCodegenContext(ast, options);
  13265. if (options.onContextCreated)
  13266. options.onContextCreated(context);
  13267. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  13268. const helpers = Array.from(ast.helpers);
  13269. const hasHelpers = helpers.length > 0;
  13270. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  13271. const isSetupInlined = !true ;
  13272. // preambles
  13273. // in setup() inline mode, the preamble is generated in a sub context
  13274. // and returned separately.
  13275. const preambleContext = isSetupInlined
  13276. ? createCodegenContext(ast, options)
  13277. : context;
  13278. {
  13279. genFunctionPreamble(ast, preambleContext);
  13280. }
  13281. // enter render function
  13282. const functionName = ssr ? `ssrRender` : `render`;
  13283. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  13284. const signature = args.join(', ');
  13285. {
  13286. push(`function ${functionName}(${signature}) {`);
  13287. }
  13288. indent();
  13289. if (useWithBlock) {
  13290. push(`with (_ctx) {`);
  13291. indent();
  13292. // function mode const declarations should be inside with block
  13293. // also they should be renamed to avoid collision with user properties
  13294. if (hasHelpers) {
  13295. push(`const { ${helpers.map(aliasHelper).join(', ')} } = _Vue`);
  13296. push(`\n`);
  13297. newline();
  13298. }
  13299. }
  13300. // generate asset resolution statements
  13301. if (ast.components.length) {
  13302. genAssets(ast.components, 'component', context);
  13303. if (ast.directives.length || ast.temps > 0) {
  13304. newline();
  13305. }
  13306. }
  13307. if (ast.directives.length) {
  13308. genAssets(ast.directives, 'directive', context);
  13309. if (ast.temps > 0) {
  13310. newline();
  13311. }
  13312. }
  13313. if (ast.temps > 0) {
  13314. push(`let `);
  13315. for (let i = 0; i < ast.temps; i++) {
  13316. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  13317. }
  13318. }
  13319. if (ast.components.length || ast.directives.length || ast.temps) {
  13320. push(`\n`);
  13321. newline();
  13322. }
  13323. // generate the VNode tree expression
  13324. if (!ssr) {
  13325. push(`return `);
  13326. }
  13327. if (ast.codegenNode) {
  13328. genNode(ast.codegenNode, context);
  13329. }
  13330. else {
  13331. push(`null`);
  13332. }
  13333. if (useWithBlock) {
  13334. deindent();
  13335. push(`}`);
  13336. }
  13337. deindent();
  13338. push(`}`);
  13339. return {
  13340. ast,
  13341. code: context.code,
  13342. preamble: isSetupInlined ? preambleContext.code : ``,
  13343. // SourceMapGenerator does have toJSON() method but it's not in the types
  13344. map: context.map ? context.map.toJSON() : undefined
  13345. };
  13346. }
  13347. function genFunctionPreamble(ast, context) {
  13348. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  13349. const VueBinding = runtimeGlobalName;
  13350. // Generate const declaration for helpers
  13351. // In prefix mode, we place the const declaration at top so it's done
  13352. // only once; But if we not prefixing, we place the declaration inside the
  13353. // with block so it doesn't incur the `in` check cost for every helper access.
  13354. const helpers = Array.from(ast.helpers);
  13355. if (helpers.length > 0) {
  13356. {
  13357. // "with" mode.
  13358. // save Vue in a separate variable to avoid collision
  13359. push(`const _Vue = ${VueBinding}\n`);
  13360. // in "with" mode, helpers are declared inside the with block to avoid
  13361. // has check cost, but hoists are lifted out of the function - we need
  13362. // to provide the helper here.
  13363. if (ast.hoists.length) {
  13364. const staticHelpers = [
  13365. CREATE_VNODE,
  13366. CREATE_ELEMENT_VNODE,
  13367. CREATE_COMMENT,
  13368. CREATE_TEXT,
  13369. CREATE_STATIC
  13370. ]
  13371. .filter(helper => helpers.includes(helper))
  13372. .map(aliasHelper)
  13373. .join(', ');
  13374. push(`const { ${staticHelpers} } = _Vue\n`);
  13375. }
  13376. }
  13377. }
  13378. genHoists(ast.hoists, context);
  13379. newline();
  13380. push(`return `);
  13381. }
  13382. function genAssets(assets, type, { helper, push, newline, isTS }) {
  13383. const resolver = helper(type === 'component'
  13384. ? RESOLVE_COMPONENT
  13385. : RESOLVE_DIRECTIVE);
  13386. for (let i = 0; i < assets.length; i++) {
  13387. let id = assets[i];
  13388. // potential component implicit self-reference inferred from SFC filename
  13389. const maybeSelfReference = id.endsWith('__self');
  13390. if (maybeSelfReference) {
  13391. id = id.slice(0, -6);
  13392. }
  13393. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  13394. if (i < assets.length - 1) {
  13395. newline();
  13396. }
  13397. }
  13398. }
  13399. function genHoists(hoists, context) {
  13400. if (!hoists.length) {
  13401. return;
  13402. }
  13403. context.pure = true;
  13404. const { push, newline, helper, scopeId, mode } = context;
  13405. newline();
  13406. for (let i = 0; i < hoists.length; i++) {
  13407. const exp = hoists[i];
  13408. if (exp) {
  13409. push(`const _hoisted_${i + 1} = ${``}`);
  13410. genNode(exp, context);
  13411. newline();
  13412. }
  13413. }
  13414. context.pure = false;
  13415. }
  13416. function isText(n) {
  13417. return (isString(n) ||
  13418. n.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  13419. n.type === 2 /* NodeTypes.TEXT */ ||
  13420. n.type === 5 /* NodeTypes.INTERPOLATION */ ||
  13421. n.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */);
  13422. }
  13423. function genNodeListAsArray(nodes, context) {
  13424. const multilines = nodes.length > 3 ||
  13425. (nodes.some(n => isArray(n) || !isText(n)));
  13426. context.push(`[`);
  13427. multilines && context.indent();
  13428. genNodeList(nodes, context, multilines);
  13429. multilines && context.deindent();
  13430. context.push(`]`);
  13431. }
  13432. function genNodeList(nodes, context, multilines = false, comma = true) {
  13433. const { push, newline } = context;
  13434. for (let i = 0; i < nodes.length; i++) {
  13435. const node = nodes[i];
  13436. if (isString(node)) {
  13437. push(node);
  13438. }
  13439. else if (isArray(node)) {
  13440. genNodeListAsArray(node, context);
  13441. }
  13442. else {
  13443. genNode(node, context);
  13444. }
  13445. if (i < nodes.length - 1) {
  13446. if (multilines) {
  13447. comma && push(',');
  13448. newline();
  13449. }
  13450. else {
  13451. comma && push(', ');
  13452. }
  13453. }
  13454. }
  13455. }
  13456. function genNode(node, context) {
  13457. if (isString(node)) {
  13458. context.push(node);
  13459. return;
  13460. }
  13461. if (isSymbol(node)) {
  13462. context.push(context.helper(node));
  13463. return;
  13464. }
  13465. switch (node.type) {
  13466. case 1 /* NodeTypes.ELEMENT */:
  13467. case 9 /* NodeTypes.IF */:
  13468. case 11 /* NodeTypes.FOR */:
  13469. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  13470. `Apply appropriate transforms first.`);
  13471. genNode(node.codegenNode, context);
  13472. break;
  13473. case 2 /* NodeTypes.TEXT */:
  13474. genText(node, context);
  13475. break;
  13476. case 4 /* NodeTypes.SIMPLE_EXPRESSION */:
  13477. genExpression(node, context);
  13478. break;
  13479. case 5 /* NodeTypes.INTERPOLATION */:
  13480. genInterpolation(node, context);
  13481. break;
  13482. case 12 /* NodeTypes.TEXT_CALL */:
  13483. genNode(node.codegenNode, context);
  13484. break;
  13485. case 8 /* NodeTypes.COMPOUND_EXPRESSION */:
  13486. genCompoundExpression(node, context);
  13487. break;
  13488. case 3 /* NodeTypes.COMMENT */:
  13489. genComment(node, context);
  13490. break;
  13491. case 13 /* NodeTypes.VNODE_CALL */:
  13492. genVNodeCall(node, context);
  13493. break;
  13494. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  13495. genCallExpression(node, context);
  13496. break;
  13497. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  13498. genObjectExpression(node, context);
  13499. break;
  13500. case 17 /* NodeTypes.JS_ARRAY_EXPRESSION */:
  13501. genArrayExpression(node, context);
  13502. break;
  13503. case 18 /* NodeTypes.JS_FUNCTION_EXPRESSION */:
  13504. genFunctionExpression(node, context);
  13505. break;
  13506. case 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */:
  13507. genConditionalExpression(node, context);
  13508. break;
  13509. case 20 /* NodeTypes.JS_CACHE_EXPRESSION */:
  13510. genCacheExpression(node, context);
  13511. break;
  13512. case 21 /* NodeTypes.JS_BLOCK_STATEMENT */:
  13513. genNodeList(node.body, context, true, false);
  13514. break;
  13515. // SSR only types
  13516. case 22 /* NodeTypes.JS_TEMPLATE_LITERAL */:
  13517. break;
  13518. case 23 /* NodeTypes.JS_IF_STATEMENT */:
  13519. break;
  13520. case 24 /* NodeTypes.JS_ASSIGNMENT_EXPRESSION */:
  13521. break;
  13522. case 25 /* NodeTypes.JS_SEQUENCE_EXPRESSION */:
  13523. break;
  13524. case 26 /* NodeTypes.JS_RETURN_STATEMENT */:
  13525. break;
  13526. /* istanbul ignore next */
  13527. case 10 /* NodeTypes.IF_BRANCH */:
  13528. // noop
  13529. break;
  13530. default:
  13531. {
  13532. assert(false, `unhandled codegen node type: ${node.type}`);
  13533. // make sure we exhaust all possible types
  13534. const exhaustiveCheck = node;
  13535. return exhaustiveCheck;
  13536. }
  13537. }
  13538. }
  13539. function genText(node, context) {
  13540. context.push(JSON.stringify(node.content), node);
  13541. }
  13542. function genExpression(node, context) {
  13543. const { content, isStatic } = node;
  13544. context.push(isStatic ? JSON.stringify(content) : content, node);
  13545. }
  13546. function genInterpolation(node, context) {
  13547. const { push, helper, pure } = context;
  13548. if (pure)
  13549. push(PURE_ANNOTATION);
  13550. push(`${helper(TO_DISPLAY_STRING)}(`);
  13551. genNode(node.content, context);
  13552. push(`)`);
  13553. }
  13554. function genCompoundExpression(node, context) {
  13555. for (let i = 0; i < node.children.length; i++) {
  13556. const child = node.children[i];
  13557. if (isString(child)) {
  13558. context.push(child);
  13559. }
  13560. else {
  13561. genNode(child, context);
  13562. }
  13563. }
  13564. }
  13565. function genExpressionAsPropertyKey(node, context) {
  13566. const { push } = context;
  13567. if (node.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  13568. push(`[`);
  13569. genCompoundExpression(node, context);
  13570. push(`]`);
  13571. }
  13572. else if (node.isStatic) {
  13573. // only quote keys if necessary
  13574. const text = isSimpleIdentifier(node.content)
  13575. ? node.content
  13576. : JSON.stringify(node.content);
  13577. push(text, node);
  13578. }
  13579. else {
  13580. push(`[${node.content}]`, node);
  13581. }
  13582. }
  13583. function genComment(node, context) {
  13584. const { push, helper, pure } = context;
  13585. if (pure) {
  13586. push(PURE_ANNOTATION);
  13587. }
  13588. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  13589. }
  13590. function genVNodeCall(node, context) {
  13591. const { push, helper, pure } = context;
  13592. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  13593. if (directives) {
  13594. push(helper(WITH_DIRECTIVES) + `(`);
  13595. }
  13596. if (isBlock) {
  13597. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  13598. }
  13599. if (pure) {
  13600. push(PURE_ANNOTATION);
  13601. }
  13602. const callHelper = isBlock
  13603. ? getVNodeBlockHelper(context.inSSR, isComponent)
  13604. : getVNodeHelper(context.inSSR, isComponent);
  13605. push(helper(callHelper) + `(`, node);
  13606. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  13607. push(`)`);
  13608. if (isBlock) {
  13609. push(`)`);
  13610. }
  13611. if (directives) {
  13612. push(`, `);
  13613. genNode(directives, context);
  13614. push(`)`);
  13615. }
  13616. }
  13617. function genNullableArgs(args) {
  13618. let i = args.length;
  13619. while (i--) {
  13620. if (args[i] != null)
  13621. break;
  13622. }
  13623. return args.slice(0, i + 1).map(arg => arg || `null`);
  13624. }
  13625. // JavaScript
  13626. function genCallExpression(node, context) {
  13627. const { push, helper, pure } = context;
  13628. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  13629. if (pure) {
  13630. push(PURE_ANNOTATION);
  13631. }
  13632. push(callee + `(`, node);
  13633. genNodeList(node.arguments, context);
  13634. push(`)`);
  13635. }
  13636. function genObjectExpression(node, context) {
  13637. const { push, indent, deindent, newline } = context;
  13638. const { properties } = node;
  13639. if (!properties.length) {
  13640. push(`{}`, node);
  13641. return;
  13642. }
  13643. const multilines = properties.length > 1 ||
  13644. (properties.some(p => p.value.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */));
  13645. push(multilines ? `{` : `{ `);
  13646. multilines && indent();
  13647. for (let i = 0; i < properties.length; i++) {
  13648. const { key, value } = properties[i];
  13649. // key
  13650. genExpressionAsPropertyKey(key, context);
  13651. push(`: `);
  13652. // value
  13653. genNode(value, context);
  13654. if (i < properties.length - 1) {
  13655. // will only reach this if it's multilines
  13656. push(`,`);
  13657. newline();
  13658. }
  13659. }
  13660. multilines && deindent();
  13661. push(multilines ? `}` : ` }`);
  13662. }
  13663. function genArrayExpression(node, context) {
  13664. genNodeListAsArray(node.elements, context);
  13665. }
  13666. function genFunctionExpression(node, context) {
  13667. const { push, indent, deindent } = context;
  13668. const { params, returns, body, newline, isSlot } = node;
  13669. if (isSlot) {
  13670. // wrap slot functions with owner context
  13671. push(`_${helperNameMap[WITH_CTX]}(`);
  13672. }
  13673. push(`(`, node);
  13674. if (isArray(params)) {
  13675. genNodeList(params, context);
  13676. }
  13677. else if (params) {
  13678. genNode(params, context);
  13679. }
  13680. push(`) => `);
  13681. if (newline || body) {
  13682. push(`{`);
  13683. indent();
  13684. }
  13685. if (returns) {
  13686. if (newline) {
  13687. push(`return `);
  13688. }
  13689. if (isArray(returns)) {
  13690. genNodeListAsArray(returns, context);
  13691. }
  13692. else {
  13693. genNode(returns, context);
  13694. }
  13695. }
  13696. else if (body) {
  13697. genNode(body, context);
  13698. }
  13699. if (newline || body) {
  13700. deindent();
  13701. push(`}`);
  13702. }
  13703. if (isSlot) {
  13704. push(`)`);
  13705. }
  13706. }
  13707. function genConditionalExpression(node, context) {
  13708. const { test, consequent, alternate, newline: needNewline } = node;
  13709. const { push, indent, deindent, newline } = context;
  13710. if (test.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  13711. const needsParens = !isSimpleIdentifier(test.content);
  13712. needsParens && push(`(`);
  13713. genExpression(test, context);
  13714. needsParens && push(`)`);
  13715. }
  13716. else {
  13717. push(`(`);
  13718. genNode(test, context);
  13719. push(`)`);
  13720. }
  13721. needNewline && indent();
  13722. context.indentLevel++;
  13723. needNewline || push(` `);
  13724. push(`? `);
  13725. genNode(consequent, context);
  13726. context.indentLevel--;
  13727. needNewline && newline();
  13728. needNewline || push(` `);
  13729. push(`: `);
  13730. const isNested = alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */;
  13731. if (!isNested) {
  13732. context.indentLevel++;
  13733. }
  13734. genNode(alternate, context);
  13735. if (!isNested) {
  13736. context.indentLevel--;
  13737. }
  13738. needNewline && deindent(true /* without newline */);
  13739. }
  13740. function genCacheExpression(node, context) {
  13741. const { push, helper, indent, deindent, newline } = context;
  13742. push(`_cache[${node.index}] || (`);
  13743. if (node.isVNode) {
  13744. indent();
  13745. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  13746. newline();
  13747. }
  13748. push(`_cache[${node.index}] = `);
  13749. genNode(node.value, context);
  13750. if (node.isVNode) {
  13751. push(`,`);
  13752. newline();
  13753. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  13754. newline();
  13755. push(`_cache[${node.index}]`);
  13756. deindent();
  13757. }
  13758. push(`)`);
  13759. }
  13760. // these keywords should not appear inside expressions, but operators like
  13761. // 'typeof', 'instanceof', and 'in' are allowed
  13762. const prohibitedKeywordRE = new RegExp('\\b' +
  13763. ('arguments,await,break,case,catch,class,const,continue,debugger,default,' +
  13764. 'delete,do,else,export,extends,finally,for,function,if,import,let,new,' +
  13765. 'return,super,switch,throw,try,var,void,while,with,yield')
  13766. .split(',')
  13767. .join('\\b|\\b') +
  13768. '\\b');
  13769. // strip strings in expressions
  13770. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  13771. /**
  13772. * Validate a non-prefixed expression.
  13773. * This is only called when using the in-browser runtime compiler since it
  13774. * doesn't prefix expressions.
  13775. */
  13776. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  13777. const exp = node.content;
  13778. // empty expressions are validated per-directive since some directives
  13779. // do allow empty expressions.
  13780. if (!exp.trim()) {
  13781. return;
  13782. }
  13783. try {
  13784. new Function(asRawStatements
  13785. ? ` ${exp} `
  13786. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  13787. }
  13788. catch (e) {
  13789. let message = e.message;
  13790. const keywordMatch = exp
  13791. .replace(stripStringRE, '')
  13792. .match(prohibitedKeywordRE);
  13793. if (keywordMatch) {
  13794. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  13795. }
  13796. context.onError(createCompilerError(45 /* ErrorCodes.X_INVALID_EXPRESSION */, node.loc, undefined, message));
  13797. }
  13798. }
  13799. const transformExpression = (node, context) => {
  13800. if (node.type === 5 /* NodeTypes.INTERPOLATION */) {
  13801. node.content = processExpression(node.content, context);
  13802. }
  13803. else if (node.type === 1 /* NodeTypes.ELEMENT */) {
  13804. // handle directives on element
  13805. for (let i = 0; i < node.props.length; i++) {
  13806. const dir = node.props[i];
  13807. // do not process for v-on & v-for since they are special handled
  13808. if (dir.type === 7 /* NodeTypes.DIRECTIVE */ && dir.name !== 'for') {
  13809. const exp = dir.exp;
  13810. const arg = dir.arg;
  13811. // do not process exp if this is v-on:arg - we need special handling
  13812. // for wrapping inline statements.
  13813. if (exp &&
  13814. exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  13815. !(dir.name === 'on' && arg)) {
  13816. dir.exp = processExpression(exp, context,
  13817. // slot args must be processed as function params
  13818. dir.name === 'slot');
  13819. }
  13820. if (arg && arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !arg.isStatic) {
  13821. dir.arg = processExpression(arg, context);
  13822. }
  13823. }
  13824. }
  13825. }
  13826. };
  13827. // Important: since this function uses Node.js only dependencies, it should
  13828. // always be used with a leading !true check so that it can be
  13829. // tree-shaken from the browser build.
  13830. function processExpression(node, context,
  13831. // some expressions like v-slot props & v-for aliases should be parsed as
  13832. // function params
  13833. asParams = false,
  13834. // v-on handler values may contain multiple statements
  13835. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  13836. {
  13837. {
  13838. // simple in-browser validation (same logic in 2.x)
  13839. validateBrowserExpression(node, context, asParams, asRawStatements);
  13840. }
  13841. return node;
  13842. }
  13843. }
  13844. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  13845. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  13846. // #1587: We need to dynamically increment the key based on the current
  13847. // node's sibling nodes, since chained v-if/else branches are
  13848. // rendered at the same depth
  13849. const siblings = context.parent.children;
  13850. let i = siblings.indexOf(ifNode);
  13851. let key = 0;
  13852. while (i-- >= 0) {
  13853. const sibling = siblings[i];
  13854. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  13855. key += sibling.branches.length;
  13856. }
  13857. }
  13858. // Exit callback. Complete the codegenNode when all children have been
  13859. // transformed.
  13860. return () => {
  13861. if (isRoot) {
  13862. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  13863. }
  13864. else {
  13865. // attach this branch's codegen node to the v-if root.
  13866. const parentCondition = getParentCondition(ifNode.codegenNode);
  13867. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  13868. }
  13869. };
  13870. });
  13871. });
  13872. // target-agnostic transform used for both Client and SSR
  13873. function processIf(node, dir, context, processCodegen) {
  13874. if (dir.name !== 'else' &&
  13875. (!dir.exp || !dir.exp.content.trim())) {
  13876. const loc = dir.exp ? dir.exp.loc : node.loc;
  13877. context.onError(createCompilerError(28 /* ErrorCodes.X_V_IF_NO_EXPRESSION */, dir.loc));
  13878. dir.exp = createSimpleExpression(`true`, false, loc);
  13879. }
  13880. if (dir.exp) {
  13881. validateBrowserExpression(dir.exp, context);
  13882. }
  13883. if (dir.name === 'if') {
  13884. const branch = createIfBranch(node, dir);
  13885. const ifNode = {
  13886. type: 9 /* NodeTypes.IF */,
  13887. loc: node.loc,
  13888. branches: [branch]
  13889. };
  13890. context.replaceNode(ifNode);
  13891. if (processCodegen) {
  13892. return processCodegen(ifNode, branch, true);
  13893. }
  13894. }
  13895. else {
  13896. // locate the adjacent v-if
  13897. const siblings = context.parent.children;
  13898. const comments = [];
  13899. let i = siblings.indexOf(node);
  13900. while (i-- >= -1) {
  13901. const sibling = siblings[i];
  13902. if (sibling && sibling.type === 3 /* NodeTypes.COMMENT */) {
  13903. context.removeNode(sibling);
  13904. comments.unshift(sibling);
  13905. continue;
  13906. }
  13907. if (sibling &&
  13908. sibling.type === 2 /* NodeTypes.TEXT */ &&
  13909. !sibling.content.trim().length) {
  13910. context.removeNode(sibling);
  13911. continue;
  13912. }
  13913. if (sibling && sibling.type === 9 /* NodeTypes.IF */) {
  13914. // Check if v-else was followed by v-else-if
  13915. if (dir.name === 'else-if' &&
  13916. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  13917. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  13918. }
  13919. // move the node to the if node's branches
  13920. context.removeNode();
  13921. const branch = createIfBranch(node, dir);
  13922. if (comments.length &&
  13923. // #3619 ignore comments if the v-if is direct child of <transition>
  13924. !(context.parent &&
  13925. context.parent.type === 1 /* NodeTypes.ELEMENT */ &&
  13926. isBuiltInType(context.parent.tag, 'transition'))) {
  13927. branch.children = [...comments, ...branch.children];
  13928. }
  13929. // check if user is forcing same key on different branches
  13930. {
  13931. const key = branch.userKey;
  13932. if (key) {
  13933. sibling.branches.forEach(({ userKey }) => {
  13934. if (isSameKey(userKey, key)) {
  13935. context.onError(createCompilerError(29 /* ErrorCodes.X_V_IF_SAME_KEY */, branch.userKey.loc));
  13936. }
  13937. });
  13938. }
  13939. }
  13940. sibling.branches.push(branch);
  13941. const onExit = processCodegen && processCodegen(sibling, branch, false);
  13942. // since the branch was removed, it will not be traversed.
  13943. // make sure to traverse here.
  13944. traverseNode(branch, context);
  13945. // call on exit
  13946. if (onExit)
  13947. onExit();
  13948. // make sure to reset currentNode after traversal to indicate this
  13949. // node has been removed.
  13950. context.currentNode = null;
  13951. }
  13952. else {
  13953. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  13954. }
  13955. break;
  13956. }
  13957. }
  13958. }
  13959. function createIfBranch(node, dir) {
  13960. const isTemplateIf = node.tagType === 3 /* ElementTypes.TEMPLATE */;
  13961. return {
  13962. type: 10 /* NodeTypes.IF_BRANCH */,
  13963. loc: node.loc,
  13964. condition: dir.name === 'else' ? undefined : dir.exp,
  13965. children: isTemplateIf && !findDir(node, 'for') ? node.children : [node],
  13966. userKey: findProp(node, `key`),
  13967. isTemplateIf
  13968. };
  13969. }
  13970. function createCodegenNodeForBranch(branch, keyIndex, context) {
  13971. if (branch.condition) {
  13972. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  13973. // make sure to pass in asBlock: true so that the comment node call
  13974. // closes the current block.
  13975. createCallExpression(context.helper(CREATE_COMMENT), [
  13976. '"v-if"' ,
  13977. 'true'
  13978. ]));
  13979. }
  13980. else {
  13981. return createChildrenCodegenNode(branch, keyIndex, context);
  13982. }
  13983. }
  13984. function createChildrenCodegenNode(branch, keyIndex, context) {
  13985. const { helper } = context;
  13986. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* ConstantTypes.CAN_HOIST */));
  13987. const { children } = branch;
  13988. const firstChild = children[0];
  13989. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* NodeTypes.ELEMENT */;
  13990. if (needFragmentWrapper) {
  13991. if (children.length === 1 && firstChild.type === 11 /* NodeTypes.FOR */) {
  13992. // optimize away nested fragments when child is a ForNode
  13993. const vnodeCall = firstChild.codegenNode;
  13994. injectProp(vnodeCall, keyProperty, context);
  13995. return vnodeCall;
  13996. }
  13997. else {
  13998. let patchFlag = 64 /* PatchFlags.STABLE_FRAGMENT */;
  13999. let patchFlagText = PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */];
  14000. // check if the fragment actually contains a single valid child with
  14001. // the rest being comments
  14002. if (!branch.isTemplateIf &&
  14003. children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */).length === 1) {
  14004. patchFlag |= 2048 /* PatchFlags.DEV_ROOT_FRAGMENT */;
  14005. patchFlagText += `, ${PatchFlagNames[2048 /* PatchFlags.DEV_ROOT_FRAGMENT */]}`;
  14006. }
  14007. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  14008. }
  14009. }
  14010. else {
  14011. const ret = firstChild.codegenNode;
  14012. const vnodeCall = getMemoedVNodeCall(ret);
  14013. // Change createVNode to createBlock.
  14014. if (vnodeCall.type === 13 /* NodeTypes.VNODE_CALL */) {
  14015. makeBlock(vnodeCall, context);
  14016. }
  14017. // inject branch key
  14018. injectProp(vnodeCall, keyProperty, context);
  14019. return ret;
  14020. }
  14021. }
  14022. function isSameKey(a, b) {
  14023. if (!a || a.type !== b.type) {
  14024. return false;
  14025. }
  14026. if (a.type === 6 /* NodeTypes.ATTRIBUTE */) {
  14027. if (a.value.content !== b.value.content) {
  14028. return false;
  14029. }
  14030. }
  14031. else {
  14032. // directive
  14033. const exp = a.exp;
  14034. const branchExp = b.exp;
  14035. if (exp.type !== branchExp.type) {
  14036. return false;
  14037. }
  14038. if (exp.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  14039. exp.isStatic !== branchExp.isStatic ||
  14040. exp.content !== branchExp.content) {
  14041. return false;
  14042. }
  14043. }
  14044. return true;
  14045. }
  14046. function getParentCondition(node) {
  14047. while (true) {
  14048. if (node.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  14049. if (node.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  14050. node = node.alternate;
  14051. }
  14052. else {
  14053. return node;
  14054. }
  14055. }
  14056. else if (node.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */) {
  14057. node = node.value;
  14058. }
  14059. }
  14060. }
  14061. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  14062. const { helper, removeHelper } = context;
  14063. return processFor(node, dir, context, forNode => {
  14064. // create the loop render function expression now, and add the
  14065. // iterator on exit after all children have been traversed
  14066. const renderExp = createCallExpression(helper(RENDER_LIST), [
  14067. forNode.source
  14068. ]);
  14069. const isTemplate = isTemplateNode(node);
  14070. const memo = findDir(node, 'memo');
  14071. const keyProp = findProp(node, `key`);
  14072. const keyExp = keyProp &&
  14073. (keyProp.type === 6 /* NodeTypes.ATTRIBUTE */
  14074. ? createSimpleExpression(keyProp.value.content, true)
  14075. : keyProp.exp);
  14076. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  14077. const isStableFragment = forNode.source.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  14078. forNode.source.constType > 0 /* ConstantTypes.NOT_CONSTANT */;
  14079. const fragmentFlag = isStableFragment
  14080. ? 64 /* PatchFlags.STABLE_FRAGMENT */
  14081. : keyProp
  14082. ? 128 /* PatchFlags.KEYED_FRAGMENT */
  14083. : 256 /* PatchFlags.UNKEYED_FRAGMENT */;
  14084. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  14085. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  14086. return () => {
  14087. // finish the codegen now that all children have been traversed
  14088. let childBlock;
  14089. const { children } = forNode;
  14090. // check <template v-for> key placement
  14091. if (isTemplate) {
  14092. node.children.some(c => {
  14093. if (c.type === 1 /* NodeTypes.ELEMENT */) {
  14094. const key = findProp(c, 'key');
  14095. if (key) {
  14096. context.onError(createCompilerError(33 /* ErrorCodes.X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  14097. return true;
  14098. }
  14099. }
  14100. });
  14101. }
  14102. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* NodeTypes.ELEMENT */;
  14103. const slotOutlet = isSlotOutlet(node)
  14104. ? node
  14105. : isTemplate &&
  14106. node.children.length === 1 &&
  14107. isSlotOutlet(node.children[0])
  14108. ? node.children[0] // api-extractor somehow fails to infer this
  14109. : null;
  14110. if (slotOutlet) {
  14111. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  14112. childBlock = slotOutlet.codegenNode;
  14113. if (isTemplate && keyProperty) {
  14114. // <template v-for="..." :key="..."><slot/></template>
  14115. // we need to inject the key to the renderSlot() call.
  14116. // the props for renderSlot is passed as the 3rd argument.
  14117. injectProp(childBlock, keyProperty, context);
  14118. }
  14119. }
  14120. else if (needFragmentWrapper) {
  14121. // <template v-for="..."> with text or multi-elements
  14122. // should generate a fragment block for each loop
  14123. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* PatchFlags.STABLE_FRAGMENT */ +
  14124. (` /* ${PatchFlagNames[64 /* PatchFlags.STABLE_FRAGMENT */]} */`
  14125. ), undefined, undefined, true, undefined, false /* isComponent */);
  14126. }
  14127. else {
  14128. // Normal element v-for. Directly use the child's codegenNode
  14129. // but mark it as a block.
  14130. childBlock = children[0]
  14131. .codegenNode;
  14132. if (isTemplate && keyProperty) {
  14133. injectProp(childBlock, keyProperty, context);
  14134. }
  14135. if (childBlock.isBlock !== !isStableFragment) {
  14136. if (childBlock.isBlock) {
  14137. // switch from block to vnode
  14138. removeHelper(OPEN_BLOCK);
  14139. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  14140. }
  14141. else {
  14142. // switch from vnode to block
  14143. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  14144. }
  14145. }
  14146. childBlock.isBlock = !isStableFragment;
  14147. if (childBlock.isBlock) {
  14148. helper(OPEN_BLOCK);
  14149. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  14150. }
  14151. else {
  14152. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  14153. }
  14154. }
  14155. if (memo) {
  14156. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  14157. createSimpleExpression(`_cached`)
  14158. ]));
  14159. loop.body = createBlockStatement([
  14160. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  14161. createCompoundExpression([
  14162. `if (_cached`,
  14163. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  14164. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  14165. ]),
  14166. createCompoundExpression([`const _item = `, childBlock]),
  14167. createSimpleExpression(`_item.memo = _memo`),
  14168. createSimpleExpression(`return _item`)
  14169. ]);
  14170. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  14171. }
  14172. else {
  14173. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  14174. }
  14175. };
  14176. });
  14177. });
  14178. // target-agnostic transform used for both Client and SSR
  14179. function processFor(node, dir, context, processCodegen) {
  14180. if (!dir.exp) {
  14181. context.onError(createCompilerError(31 /* ErrorCodes.X_V_FOR_NO_EXPRESSION */, dir.loc));
  14182. return;
  14183. }
  14184. const parseResult = parseForExpression(
  14185. // can only be simple expression because vFor transform is applied
  14186. // before expression transform.
  14187. dir.exp, context);
  14188. if (!parseResult) {
  14189. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  14190. return;
  14191. }
  14192. const { addIdentifiers, removeIdentifiers, scopes } = context;
  14193. const { source, value, key, index } = parseResult;
  14194. const forNode = {
  14195. type: 11 /* NodeTypes.FOR */,
  14196. loc: dir.loc,
  14197. source,
  14198. valueAlias: value,
  14199. keyAlias: key,
  14200. objectIndexAlias: index,
  14201. parseResult,
  14202. children: isTemplateNode(node) ? node.children : [node]
  14203. };
  14204. context.replaceNode(forNode);
  14205. // bookkeeping
  14206. scopes.vFor++;
  14207. const onExit = processCodegen && processCodegen(forNode);
  14208. return () => {
  14209. scopes.vFor--;
  14210. if (onExit)
  14211. onExit();
  14212. };
  14213. }
  14214. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  14215. // This regex doesn't cover the case if key or index aliases have destructuring,
  14216. // but those do not make sense in the first place, so this works in practice.
  14217. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  14218. const stripParensRE = /^\(|\)$/g;
  14219. function parseForExpression(input, context) {
  14220. const loc = input.loc;
  14221. const exp = input.content;
  14222. const inMatch = exp.match(forAliasRE);
  14223. if (!inMatch)
  14224. return;
  14225. const [, LHS, RHS] = inMatch;
  14226. const result = {
  14227. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  14228. value: undefined,
  14229. key: undefined,
  14230. index: undefined
  14231. };
  14232. {
  14233. validateBrowserExpression(result.source, context);
  14234. }
  14235. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  14236. const trimmedOffset = LHS.indexOf(valueContent);
  14237. const iteratorMatch = valueContent.match(forIteratorRE);
  14238. if (iteratorMatch) {
  14239. valueContent = valueContent.replace(forIteratorRE, '').trim();
  14240. const keyContent = iteratorMatch[1].trim();
  14241. let keyOffset;
  14242. if (keyContent) {
  14243. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  14244. result.key = createAliasExpression(loc, keyContent, keyOffset);
  14245. {
  14246. validateBrowserExpression(result.key, context, true);
  14247. }
  14248. }
  14249. if (iteratorMatch[2]) {
  14250. const indexContent = iteratorMatch[2].trim();
  14251. if (indexContent) {
  14252. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  14253. ? keyOffset + keyContent.length
  14254. : trimmedOffset + valueContent.length));
  14255. {
  14256. validateBrowserExpression(result.index, context, true);
  14257. }
  14258. }
  14259. }
  14260. }
  14261. if (valueContent) {
  14262. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  14263. {
  14264. validateBrowserExpression(result.value, context, true);
  14265. }
  14266. }
  14267. return result;
  14268. }
  14269. function createAliasExpression(range, content, offset) {
  14270. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  14271. }
  14272. function createForLoopParams({ value, key, index }, memoArgs = []) {
  14273. return createParamsList([value, key, index, ...memoArgs]);
  14274. }
  14275. function createParamsList(args) {
  14276. let i = args.length;
  14277. while (i--) {
  14278. if (args[i])
  14279. break;
  14280. }
  14281. return args
  14282. .slice(0, i + 1)
  14283. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  14284. }
  14285. const defaultFallback = createSimpleExpression(`undefined`, false);
  14286. // A NodeTransform that:
  14287. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  14288. // by transformExpression. This is only applied in non-browser builds with
  14289. // { prefixIdentifiers: true }.
  14290. // 2. Track v-slot depths so that we know a slot is inside another slot.
  14291. // Note the exit callback is executed before buildSlots() on the same node,
  14292. // so only nested slots see positive numbers.
  14293. const trackSlotScopes = (node, context) => {
  14294. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  14295. (node.tagType === 1 /* ElementTypes.COMPONENT */ ||
  14296. node.tagType === 3 /* ElementTypes.TEMPLATE */)) {
  14297. // We are only checking non-empty v-slot here
  14298. // since we only care about slots that introduce scope variables.
  14299. const vSlot = findDir(node, 'slot');
  14300. if (vSlot) {
  14301. vSlot.exp;
  14302. context.scopes.vSlot++;
  14303. return () => {
  14304. context.scopes.vSlot--;
  14305. };
  14306. }
  14307. }
  14308. };
  14309. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  14310. // Instead of being a DirectiveTransform, v-slot processing is called during
  14311. // transformElement to build the slots object for a component.
  14312. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  14313. context.helper(WITH_CTX);
  14314. const { children, loc } = node;
  14315. const slotsProperties = [];
  14316. const dynamicSlots = [];
  14317. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  14318. // since it likely uses a scope variable.
  14319. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  14320. // 1. Check for slot with slotProps on component itself.
  14321. // <Comp v-slot="{ prop }"/>
  14322. const onComponentSlot = findDir(node, 'slot', true);
  14323. if (onComponentSlot) {
  14324. const { arg, exp } = onComponentSlot;
  14325. if (arg && !isStaticExp(arg)) {
  14326. hasDynamicSlots = true;
  14327. }
  14328. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  14329. }
  14330. // 2. Iterate through children and check for template slots
  14331. // <template v-slot:foo="{ prop }">
  14332. let hasTemplateSlots = false;
  14333. let hasNamedDefaultSlot = false;
  14334. const implicitDefaultChildren = [];
  14335. const seenSlotNames = new Set();
  14336. let conditionalBranchIndex = 0;
  14337. for (let i = 0; i < children.length; i++) {
  14338. const slotElement = children[i];
  14339. let slotDir;
  14340. if (!isTemplateNode(slotElement) ||
  14341. !(slotDir = findDir(slotElement, 'slot', true))) {
  14342. // not a <template v-slot>, skip.
  14343. if (slotElement.type !== 3 /* NodeTypes.COMMENT */) {
  14344. implicitDefaultChildren.push(slotElement);
  14345. }
  14346. continue;
  14347. }
  14348. if (onComponentSlot) {
  14349. // already has on-component slot - this is incorrect usage.
  14350. context.onError(createCompilerError(37 /* ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  14351. break;
  14352. }
  14353. hasTemplateSlots = true;
  14354. const { children: slotChildren, loc: slotLoc } = slotElement;
  14355. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  14356. // check if name is dynamic.
  14357. let staticSlotName;
  14358. if (isStaticExp(slotName)) {
  14359. staticSlotName = slotName ? slotName.content : `default`;
  14360. }
  14361. else {
  14362. hasDynamicSlots = true;
  14363. }
  14364. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  14365. // check if this slot is conditional (v-if/v-for)
  14366. let vIf;
  14367. let vElse;
  14368. let vFor;
  14369. if ((vIf = findDir(slotElement, 'if'))) {
  14370. hasDynamicSlots = true;
  14371. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback));
  14372. }
  14373. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  14374. // find adjacent v-if
  14375. let j = i;
  14376. let prev;
  14377. while (j--) {
  14378. prev = children[j];
  14379. if (prev.type !== 3 /* NodeTypes.COMMENT */) {
  14380. break;
  14381. }
  14382. }
  14383. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  14384. // remove node
  14385. children.splice(i, 1);
  14386. i--;
  14387. // attach this slot to previous conditional
  14388. let conditional = dynamicSlots[dynamicSlots.length - 1];
  14389. while (conditional.alternate.type === 19 /* NodeTypes.JS_CONDITIONAL_EXPRESSION */) {
  14390. conditional = conditional.alternate;
  14391. }
  14392. conditional.alternate = vElse.exp
  14393. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++), defaultFallback)
  14394. : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
  14395. }
  14396. else {
  14397. context.onError(createCompilerError(30 /* ErrorCodes.X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  14398. }
  14399. }
  14400. else if ((vFor = findDir(slotElement, 'for'))) {
  14401. hasDynamicSlots = true;
  14402. const parseResult = vFor.parseResult ||
  14403. parseForExpression(vFor.exp, context);
  14404. if (parseResult) {
  14405. // Render the dynamic slots as an array and add it to the createSlot()
  14406. // args. The runtime knows how to handle it appropriately.
  14407. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  14408. parseResult.source,
  14409. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  14410. ]));
  14411. }
  14412. else {
  14413. context.onError(createCompilerError(32 /* ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  14414. }
  14415. }
  14416. else {
  14417. // check duplicate static names
  14418. if (staticSlotName) {
  14419. if (seenSlotNames.has(staticSlotName)) {
  14420. context.onError(createCompilerError(38 /* ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  14421. continue;
  14422. }
  14423. seenSlotNames.add(staticSlotName);
  14424. if (staticSlotName === 'default') {
  14425. hasNamedDefaultSlot = true;
  14426. }
  14427. }
  14428. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  14429. }
  14430. }
  14431. if (!onComponentSlot) {
  14432. const buildDefaultSlotProperty = (props, children) => {
  14433. const fn = buildSlotFn(props, children, loc);
  14434. return createObjectProperty(`default`, fn);
  14435. };
  14436. if (!hasTemplateSlots) {
  14437. // implicit default slot (on component)
  14438. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  14439. }
  14440. else if (implicitDefaultChildren.length &&
  14441. // #3766
  14442. // with whitespace: 'preserve', whitespaces between slots will end up in
  14443. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  14444. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  14445. // implicit default slot (mixed with named slots)
  14446. if (hasNamedDefaultSlot) {
  14447. context.onError(createCompilerError(39 /* ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  14448. }
  14449. else {
  14450. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  14451. }
  14452. }
  14453. }
  14454. const slotFlag = hasDynamicSlots
  14455. ? 2 /* SlotFlags.DYNAMIC */
  14456. : hasForwardedSlots(node.children)
  14457. ? 3 /* SlotFlags.FORWARDED */
  14458. : 1 /* SlotFlags.STABLE */;
  14459. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  14460. // 2 = compiled but dynamic = can skip normalization, but must run diff
  14461. // 1 = compiled and static = can skip normalization AND diff as optimized
  14462. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  14463. if (dynamicSlots.length) {
  14464. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  14465. slots,
  14466. createArrayExpression(dynamicSlots)
  14467. ]);
  14468. }
  14469. return {
  14470. slots,
  14471. hasDynamicSlots
  14472. };
  14473. }
  14474. function buildDynamicSlot(name, fn, index) {
  14475. const props = [
  14476. createObjectProperty(`name`, name),
  14477. createObjectProperty(`fn`, fn)
  14478. ];
  14479. if (index != null) {
  14480. props.push(createObjectProperty(`key`, createSimpleExpression(String(index), true)));
  14481. }
  14482. return createObjectExpression(props);
  14483. }
  14484. function hasForwardedSlots(children) {
  14485. for (let i = 0; i < children.length; i++) {
  14486. const child = children[i];
  14487. switch (child.type) {
  14488. case 1 /* NodeTypes.ELEMENT */:
  14489. if (child.tagType === 2 /* ElementTypes.SLOT */ ||
  14490. hasForwardedSlots(child.children)) {
  14491. return true;
  14492. }
  14493. break;
  14494. case 9 /* NodeTypes.IF */:
  14495. if (hasForwardedSlots(child.branches))
  14496. return true;
  14497. break;
  14498. case 10 /* NodeTypes.IF_BRANCH */:
  14499. case 11 /* NodeTypes.FOR */:
  14500. if (hasForwardedSlots(child.children))
  14501. return true;
  14502. break;
  14503. }
  14504. }
  14505. return false;
  14506. }
  14507. function isNonWhitespaceContent(node) {
  14508. if (node.type !== 2 /* NodeTypes.TEXT */ && node.type !== 12 /* NodeTypes.TEXT_CALL */)
  14509. return true;
  14510. return node.type === 2 /* NodeTypes.TEXT */
  14511. ? !!node.content.trim()
  14512. : isNonWhitespaceContent(node.content);
  14513. }
  14514. // some directive transforms (e.g. v-model) may return a symbol for runtime
  14515. // import, which should be used instead of a resolveDirective call.
  14516. const directiveImportMap = new WeakMap();
  14517. // generate a JavaScript AST for this element's codegen
  14518. const transformElement = (node, context) => {
  14519. // perform the work on exit, after all child expressions have been
  14520. // processed and merged.
  14521. return function postTransformElement() {
  14522. node = context.currentNode;
  14523. if (!(node.type === 1 /* NodeTypes.ELEMENT */ &&
  14524. (node.tagType === 0 /* ElementTypes.ELEMENT */ ||
  14525. node.tagType === 1 /* ElementTypes.COMPONENT */))) {
  14526. return;
  14527. }
  14528. const { tag, props } = node;
  14529. const isComponent = node.tagType === 1 /* ElementTypes.COMPONENT */;
  14530. // The goal of the transform is to create a codegenNode implementing the
  14531. // VNodeCall interface.
  14532. let vnodeTag = isComponent
  14533. ? resolveComponentType(node, context)
  14534. : `"${tag}"`;
  14535. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  14536. let vnodeProps;
  14537. let vnodeChildren;
  14538. let vnodePatchFlag;
  14539. let patchFlag = 0;
  14540. let vnodeDynamicProps;
  14541. let dynamicPropNames;
  14542. let vnodeDirectives;
  14543. let shouldUseBlock =
  14544. // dynamic component may resolve to plain elements
  14545. isDynamicComponent ||
  14546. vnodeTag === TELEPORT ||
  14547. vnodeTag === SUSPENSE ||
  14548. (!isComponent &&
  14549. // <svg> and <foreignObject> must be forced into blocks so that block
  14550. // updates inside get proper isSVG flag at runtime. (#639, #643)
  14551. // This is technically web-specific, but splitting the logic out of core
  14552. // leads to too much unnecessary complexity.
  14553. (tag === 'svg' || tag === 'foreignObject'));
  14554. // props
  14555. if (props.length > 0) {
  14556. const propsBuildResult = buildProps(node, context, undefined, isComponent, isDynamicComponent);
  14557. vnodeProps = propsBuildResult.props;
  14558. patchFlag = propsBuildResult.patchFlag;
  14559. dynamicPropNames = propsBuildResult.dynamicPropNames;
  14560. const directives = propsBuildResult.directives;
  14561. vnodeDirectives =
  14562. directives && directives.length
  14563. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  14564. : undefined;
  14565. if (propsBuildResult.shouldUseBlock) {
  14566. shouldUseBlock = true;
  14567. }
  14568. }
  14569. // children
  14570. if (node.children.length > 0) {
  14571. if (vnodeTag === KEEP_ALIVE) {
  14572. // Although a built-in component, we compile KeepAlive with raw children
  14573. // instead of slot functions so that it can be used inside Transition
  14574. // or other Transition-wrapping HOCs.
  14575. // To ensure correct updates with block optimizations, we need to:
  14576. // 1. Force keep-alive into a block. This avoids its children being
  14577. // collected by a parent block.
  14578. shouldUseBlock = true;
  14579. // 2. Force keep-alive to always be updated, since it uses raw children.
  14580. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  14581. if (node.children.length > 1) {
  14582. context.onError(createCompilerError(46 /* ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN */, {
  14583. start: node.children[0].loc.start,
  14584. end: node.children[node.children.length - 1].loc.end,
  14585. source: ''
  14586. }));
  14587. }
  14588. }
  14589. const shouldBuildAsSlots = isComponent &&
  14590. // Teleport is not a real component and has dedicated runtime handling
  14591. vnodeTag !== TELEPORT &&
  14592. // explained above.
  14593. vnodeTag !== KEEP_ALIVE;
  14594. if (shouldBuildAsSlots) {
  14595. const { slots, hasDynamicSlots } = buildSlots(node, context);
  14596. vnodeChildren = slots;
  14597. if (hasDynamicSlots) {
  14598. patchFlag |= 1024 /* PatchFlags.DYNAMIC_SLOTS */;
  14599. }
  14600. }
  14601. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  14602. const child = node.children[0];
  14603. const type = child.type;
  14604. // check for dynamic text children
  14605. const hasDynamicTextChild = type === 5 /* NodeTypes.INTERPOLATION */ ||
  14606. type === 8 /* NodeTypes.COMPOUND_EXPRESSION */;
  14607. if (hasDynamicTextChild &&
  14608. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  14609. patchFlag |= 1 /* PatchFlags.TEXT */;
  14610. }
  14611. // pass directly if the only child is a text node
  14612. // (plain / interpolation / expression)
  14613. if (hasDynamicTextChild || type === 2 /* NodeTypes.TEXT */) {
  14614. vnodeChildren = child;
  14615. }
  14616. else {
  14617. vnodeChildren = node.children;
  14618. }
  14619. }
  14620. else {
  14621. vnodeChildren = node.children;
  14622. }
  14623. }
  14624. // patchFlag & dynamicPropNames
  14625. if (patchFlag !== 0) {
  14626. {
  14627. if (patchFlag < 0) {
  14628. // special flags (negative and mutually exclusive)
  14629. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  14630. }
  14631. else {
  14632. // bitwise flags
  14633. const flagNames = Object.keys(PatchFlagNames)
  14634. .map(Number)
  14635. .filter(n => n > 0 && patchFlag & n)
  14636. .map(n => PatchFlagNames[n])
  14637. .join(`, `);
  14638. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  14639. }
  14640. }
  14641. if (dynamicPropNames && dynamicPropNames.length) {
  14642. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  14643. }
  14644. }
  14645. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  14646. };
  14647. };
  14648. function resolveComponentType(node, context, ssr = false) {
  14649. let { tag } = node;
  14650. // 1. dynamic component
  14651. const isExplicitDynamic = isComponentTag(tag);
  14652. const isProp = findProp(node, 'is');
  14653. if (isProp) {
  14654. if (isExplicitDynamic ||
  14655. (false )) {
  14656. const exp = isProp.type === 6 /* NodeTypes.ATTRIBUTE */
  14657. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  14658. : isProp.exp;
  14659. if (exp) {
  14660. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  14661. exp
  14662. ]);
  14663. }
  14664. }
  14665. else if (isProp.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  14666. isProp.value.content.startsWith('vue:')) {
  14667. // <button is="vue:xxx">
  14668. // if not <component>, only is value that starts with "vue:" will be
  14669. // treated as component by the parse phase and reach here, unless it's
  14670. // compat mode where all is values are considered components
  14671. tag = isProp.value.content.slice(4);
  14672. }
  14673. }
  14674. // 1.5 v-is (TODO: Deprecate)
  14675. const isDir = !isExplicitDynamic && findDir(node, 'is');
  14676. if (isDir && isDir.exp) {
  14677. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  14678. isDir.exp
  14679. ]);
  14680. }
  14681. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  14682. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  14683. if (builtIn) {
  14684. // built-ins are simply fallthroughs / have special handling during ssr
  14685. // so we don't need to import their runtime equivalents
  14686. if (!ssr)
  14687. context.helper(builtIn);
  14688. return builtIn;
  14689. }
  14690. // 5. user component (resolve)
  14691. context.helper(RESOLVE_COMPONENT);
  14692. context.components.add(tag);
  14693. return toValidAssetId(tag, `component`);
  14694. }
  14695. function buildProps(node, context, props = node.props, isComponent, isDynamicComponent, ssr = false) {
  14696. const { tag, loc: elementLoc, children } = node;
  14697. let properties = [];
  14698. const mergeArgs = [];
  14699. const runtimeDirectives = [];
  14700. const hasChildren = children.length > 0;
  14701. let shouldUseBlock = false;
  14702. // patchFlag analysis
  14703. let patchFlag = 0;
  14704. let hasRef = false;
  14705. let hasClassBinding = false;
  14706. let hasStyleBinding = false;
  14707. let hasHydrationEventBinding = false;
  14708. let hasDynamicKeys = false;
  14709. let hasVnodeHook = false;
  14710. const dynamicPropNames = [];
  14711. const pushMergeArg = (arg) => {
  14712. if (properties.length) {
  14713. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  14714. properties = [];
  14715. }
  14716. if (arg)
  14717. mergeArgs.push(arg);
  14718. };
  14719. const analyzePatchFlag = ({ key, value }) => {
  14720. if (isStaticExp(key)) {
  14721. const name = key.content;
  14722. const isEventHandler = isOn(name);
  14723. if (isEventHandler &&
  14724. (!isComponent || isDynamicComponent) &&
  14725. // omit the flag for click handlers because hydration gives click
  14726. // dedicated fast path.
  14727. name.toLowerCase() !== 'onclick' &&
  14728. // omit v-model handlers
  14729. name !== 'onUpdate:modelValue' &&
  14730. // omit onVnodeXXX hooks
  14731. !isReservedProp(name)) {
  14732. hasHydrationEventBinding = true;
  14733. }
  14734. if (isEventHandler && isReservedProp(name)) {
  14735. hasVnodeHook = true;
  14736. }
  14737. if (value.type === 20 /* NodeTypes.JS_CACHE_EXPRESSION */ ||
  14738. ((value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ||
  14739. value.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) &&
  14740. getConstantType(value, context) > 0)) {
  14741. // skip if the prop is a cached handler or has constant value
  14742. return;
  14743. }
  14744. if (name === 'ref') {
  14745. hasRef = true;
  14746. }
  14747. else if (name === 'class') {
  14748. hasClassBinding = true;
  14749. }
  14750. else if (name === 'style') {
  14751. hasStyleBinding = true;
  14752. }
  14753. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  14754. dynamicPropNames.push(name);
  14755. }
  14756. // treat the dynamic class and style binding of the component as dynamic props
  14757. if (isComponent &&
  14758. (name === 'class' || name === 'style') &&
  14759. !dynamicPropNames.includes(name)) {
  14760. dynamicPropNames.push(name);
  14761. }
  14762. }
  14763. else {
  14764. hasDynamicKeys = true;
  14765. }
  14766. };
  14767. for (let i = 0; i < props.length; i++) {
  14768. // static attribute
  14769. const prop = props[i];
  14770. if (prop.type === 6 /* NodeTypes.ATTRIBUTE */) {
  14771. const { loc, name, value } = prop;
  14772. let isStatic = true;
  14773. if (name === 'ref') {
  14774. hasRef = true;
  14775. if (context.scopes.vFor > 0) {
  14776. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  14777. }
  14778. }
  14779. // skip is on <component>, or is="vue:xxx"
  14780. if (name === 'is' &&
  14781. (isComponentTag(tag) ||
  14782. (value && value.content.startsWith('vue:')) ||
  14783. (false ))) {
  14784. continue;
  14785. }
  14786. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  14787. }
  14788. else {
  14789. // directives
  14790. const { name, arg, exp, loc } = prop;
  14791. const isVBind = name === 'bind';
  14792. const isVOn = name === 'on';
  14793. // skip v-slot - it is handled by its dedicated transform.
  14794. if (name === 'slot') {
  14795. if (!isComponent) {
  14796. context.onError(createCompilerError(40 /* ErrorCodes.X_V_SLOT_MISPLACED */, loc));
  14797. }
  14798. continue;
  14799. }
  14800. // skip v-once/v-memo - they are handled by dedicated transforms.
  14801. if (name === 'once' || name === 'memo') {
  14802. continue;
  14803. }
  14804. // skip v-is and :is on <component>
  14805. if (name === 'is' ||
  14806. (isVBind &&
  14807. isStaticArgOf(arg, 'is') &&
  14808. (isComponentTag(tag) ||
  14809. (false )))) {
  14810. continue;
  14811. }
  14812. // skip v-on in SSR compilation
  14813. if (isVOn && ssr) {
  14814. continue;
  14815. }
  14816. if (
  14817. // #938: elements with dynamic keys should be forced into blocks
  14818. (isVBind && isStaticArgOf(arg, 'key')) ||
  14819. // inline before-update hooks need to force block so that it is invoked
  14820. // before children
  14821. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  14822. shouldUseBlock = true;
  14823. }
  14824. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  14825. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  14826. }
  14827. // special case for v-bind and v-on with no argument
  14828. if (!arg && (isVBind || isVOn)) {
  14829. hasDynamicKeys = true;
  14830. if (exp) {
  14831. if (isVBind) {
  14832. // have to merge early for compat build check
  14833. pushMergeArg();
  14834. mergeArgs.push(exp);
  14835. }
  14836. else {
  14837. // v-on="obj" -> toHandlers(obj)
  14838. pushMergeArg({
  14839. type: 14 /* NodeTypes.JS_CALL_EXPRESSION */,
  14840. loc,
  14841. callee: context.helper(TO_HANDLERS),
  14842. arguments: isComponent ? [exp] : [exp, `true`]
  14843. });
  14844. }
  14845. }
  14846. else {
  14847. context.onError(createCompilerError(isVBind
  14848. ? 34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */
  14849. : 35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  14850. }
  14851. continue;
  14852. }
  14853. const directiveTransform = context.directiveTransforms[name];
  14854. if (directiveTransform) {
  14855. // has built-in directive transform.
  14856. const { props, needRuntime } = directiveTransform(prop, node, context);
  14857. !ssr && props.forEach(analyzePatchFlag);
  14858. if (isVOn && arg && !isStaticExp(arg)) {
  14859. pushMergeArg(createObjectExpression(props, elementLoc));
  14860. }
  14861. else {
  14862. properties.push(...props);
  14863. }
  14864. if (needRuntime) {
  14865. runtimeDirectives.push(prop);
  14866. if (isSymbol(needRuntime)) {
  14867. directiveImportMap.set(prop, needRuntime);
  14868. }
  14869. }
  14870. }
  14871. else if (!isBuiltInDirective(name)) {
  14872. // no built-in transform, this is a user custom directive.
  14873. runtimeDirectives.push(prop);
  14874. // custom dirs may use beforeUpdate so they need to force blocks
  14875. // to ensure before-update gets called before children update
  14876. if (hasChildren) {
  14877. shouldUseBlock = true;
  14878. }
  14879. }
  14880. }
  14881. }
  14882. let propsExpression = undefined;
  14883. // has v-bind="object" or v-on="object", wrap with mergeProps
  14884. if (mergeArgs.length) {
  14885. // close up any not-yet-merged props
  14886. pushMergeArg();
  14887. if (mergeArgs.length > 1) {
  14888. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  14889. }
  14890. else {
  14891. // single v-bind with nothing else - no need for a mergeProps call
  14892. propsExpression = mergeArgs[0];
  14893. }
  14894. }
  14895. else if (properties.length) {
  14896. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  14897. }
  14898. // patchFlag analysis
  14899. if (hasDynamicKeys) {
  14900. patchFlag |= 16 /* PatchFlags.FULL_PROPS */;
  14901. }
  14902. else {
  14903. if (hasClassBinding && !isComponent) {
  14904. patchFlag |= 2 /* PatchFlags.CLASS */;
  14905. }
  14906. if (hasStyleBinding && !isComponent) {
  14907. patchFlag |= 4 /* PatchFlags.STYLE */;
  14908. }
  14909. if (dynamicPropNames.length) {
  14910. patchFlag |= 8 /* PatchFlags.PROPS */;
  14911. }
  14912. if (hasHydrationEventBinding) {
  14913. patchFlag |= 32 /* PatchFlags.HYDRATE_EVENTS */;
  14914. }
  14915. }
  14916. if (!shouldUseBlock &&
  14917. (patchFlag === 0 || patchFlag === 32 /* PatchFlags.HYDRATE_EVENTS */) &&
  14918. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  14919. patchFlag |= 512 /* PatchFlags.NEED_PATCH */;
  14920. }
  14921. // pre-normalize props, SSR is skipped for now
  14922. if (!context.inSSR && propsExpression) {
  14923. switch (propsExpression.type) {
  14924. case 15 /* NodeTypes.JS_OBJECT_EXPRESSION */:
  14925. // means that there is no v-bind,
  14926. // but still need to deal with dynamic key binding
  14927. let classKeyIndex = -1;
  14928. let styleKeyIndex = -1;
  14929. let hasDynamicKey = false;
  14930. for (let i = 0; i < propsExpression.properties.length; i++) {
  14931. const key = propsExpression.properties[i].key;
  14932. if (isStaticExp(key)) {
  14933. if (key.content === 'class') {
  14934. classKeyIndex = i;
  14935. }
  14936. else if (key.content === 'style') {
  14937. styleKeyIndex = i;
  14938. }
  14939. }
  14940. else if (!key.isHandlerKey) {
  14941. hasDynamicKey = true;
  14942. }
  14943. }
  14944. const classProp = propsExpression.properties[classKeyIndex];
  14945. const styleProp = propsExpression.properties[styleKeyIndex];
  14946. // no dynamic key
  14947. if (!hasDynamicKey) {
  14948. if (classProp && !isStaticExp(classProp.value)) {
  14949. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  14950. }
  14951. if (styleProp &&
  14952. // the static style is compiled into an object,
  14953. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  14954. (hasStyleBinding ||
  14955. (styleProp.value.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  14956. styleProp.value.content.trim()[0] === `[`) ||
  14957. // v-bind:style and style both exist,
  14958. // v-bind:style with static literal object
  14959. styleProp.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */)) {
  14960. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  14961. }
  14962. }
  14963. else {
  14964. // dynamic key binding, wrap with `normalizeProps`
  14965. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  14966. }
  14967. break;
  14968. case 14 /* NodeTypes.JS_CALL_EXPRESSION */:
  14969. // mergeProps call, do nothing
  14970. break;
  14971. default:
  14972. // single v-bind
  14973. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  14974. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  14975. propsExpression
  14976. ])
  14977. ]);
  14978. break;
  14979. }
  14980. }
  14981. return {
  14982. props: propsExpression,
  14983. directives: runtimeDirectives,
  14984. patchFlag,
  14985. dynamicPropNames,
  14986. shouldUseBlock
  14987. };
  14988. }
  14989. // Dedupe props in an object literal.
  14990. // Literal duplicated attributes would have been warned during the parse phase,
  14991. // however, it's possible to encounter duplicated `onXXX` handlers with different
  14992. // modifiers. We also need to merge static and dynamic class / style attributes.
  14993. // - onXXX handlers / style: merge into array
  14994. // - class: merge into single expression with concatenation
  14995. function dedupeProperties(properties) {
  14996. const knownProps = new Map();
  14997. const deduped = [];
  14998. for (let i = 0; i < properties.length; i++) {
  14999. const prop = properties[i];
  15000. // dynamic keys are always allowed
  15001. if (prop.key.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  15002. deduped.push(prop);
  15003. continue;
  15004. }
  15005. const name = prop.key.content;
  15006. const existing = knownProps.get(name);
  15007. if (existing) {
  15008. if (name === 'style' || name === 'class' || isOn(name)) {
  15009. mergeAsArray(existing, prop);
  15010. }
  15011. // unexpected duplicate, should have emitted error during parse
  15012. }
  15013. else {
  15014. knownProps.set(name, prop);
  15015. deduped.push(prop);
  15016. }
  15017. }
  15018. return deduped;
  15019. }
  15020. function mergeAsArray(existing, incoming) {
  15021. if (existing.value.type === 17 /* NodeTypes.JS_ARRAY_EXPRESSION */) {
  15022. existing.value.elements.push(incoming.value);
  15023. }
  15024. else {
  15025. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  15026. }
  15027. }
  15028. function buildDirectiveArgs(dir, context) {
  15029. const dirArgs = [];
  15030. const runtime = directiveImportMap.get(dir);
  15031. if (runtime) {
  15032. // built-in directive with runtime
  15033. dirArgs.push(context.helperString(runtime));
  15034. }
  15035. else {
  15036. {
  15037. // inject statement for resolving directive
  15038. context.helper(RESOLVE_DIRECTIVE);
  15039. context.directives.add(dir.name);
  15040. dirArgs.push(toValidAssetId(dir.name, `directive`));
  15041. }
  15042. }
  15043. const { loc } = dir;
  15044. if (dir.exp)
  15045. dirArgs.push(dir.exp);
  15046. if (dir.arg) {
  15047. if (!dir.exp) {
  15048. dirArgs.push(`void 0`);
  15049. }
  15050. dirArgs.push(dir.arg);
  15051. }
  15052. if (Object.keys(dir.modifiers).length) {
  15053. if (!dir.arg) {
  15054. if (!dir.exp) {
  15055. dirArgs.push(`void 0`);
  15056. }
  15057. dirArgs.push(`void 0`);
  15058. }
  15059. const trueExpression = createSimpleExpression(`true`, false, loc);
  15060. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  15061. }
  15062. return createArrayExpression(dirArgs, dir.loc);
  15063. }
  15064. function stringifyDynamicPropNames(props) {
  15065. let propsNamesString = `[`;
  15066. for (let i = 0, l = props.length; i < l; i++) {
  15067. propsNamesString += JSON.stringify(props[i]);
  15068. if (i < l - 1)
  15069. propsNamesString += ', ';
  15070. }
  15071. return propsNamesString + `]`;
  15072. }
  15073. function isComponentTag(tag) {
  15074. return tag === 'component' || tag === 'Component';
  15075. }
  15076. const transformSlotOutlet = (node, context) => {
  15077. if (isSlotOutlet(node)) {
  15078. const { children, loc } = node;
  15079. const { slotName, slotProps } = processSlotOutlet(node, context);
  15080. const slotArgs = [
  15081. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  15082. slotName,
  15083. '{}',
  15084. 'undefined',
  15085. 'true'
  15086. ];
  15087. let expectedLen = 2;
  15088. if (slotProps) {
  15089. slotArgs[2] = slotProps;
  15090. expectedLen = 3;
  15091. }
  15092. if (children.length) {
  15093. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  15094. expectedLen = 4;
  15095. }
  15096. if (context.scopeId && !context.slotted) {
  15097. expectedLen = 5;
  15098. }
  15099. slotArgs.splice(expectedLen); // remove unused arguments
  15100. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  15101. }
  15102. };
  15103. function processSlotOutlet(node, context) {
  15104. let slotName = `"default"`;
  15105. let slotProps = undefined;
  15106. const nonNameProps = [];
  15107. for (let i = 0; i < node.props.length; i++) {
  15108. const p = node.props[i];
  15109. if (p.type === 6 /* NodeTypes.ATTRIBUTE */) {
  15110. if (p.value) {
  15111. if (p.name === 'name') {
  15112. slotName = JSON.stringify(p.value.content);
  15113. }
  15114. else {
  15115. p.name = camelize(p.name);
  15116. nonNameProps.push(p);
  15117. }
  15118. }
  15119. }
  15120. else {
  15121. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  15122. if (p.exp)
  15123. slotName = p.exp;
  15124. }
  15125. else {
  15126. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  15127. p.arg.content = camelize(p.arg.content);
  15128. }
  15129. nonNameProps.push(p);
  15130. }
  15131. }
  15132. }
  15133. if (nonNameProps.length > 0) {
  15134. const { props, directives } = buildProps(node, context, nonNameProps, false, false);
  15135. slotProps = props;
  15136. if (directives.length) {
  15137. context.onError(createCompilerError(36 /* ErrorCodes.X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  15138. }
  15139. }
  15140. return {
  15141. slotName,
  15142. slotProps
  15143. };
  15144. }
  15145. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  15146. const transformOn$1 = (dir, node, context, augmentor) => {
  15147. const { loc, modifiers, arg } = dir;
  15148. if (!dir.exp && !modifiers.length) {
  15149. context.onError(createCompilerError(35 /* ErrorCodes.X_V_ON_NO_EXPRESSION */, loc));
  15150. }
  15151. let eventName;
  15152. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  15153. if (arg.isStatic) {
  15154. let rawName = arg.content;
  15155. // TODO deprecate @vnodeXXX usage
  15156. if (rawName.startsWith('vue:')) {
  15157. rawName = `vnode-${rawName.slice(4)}`;
  15158. }
  15159. const eventString = node.tagType !== 0 /* ElementTypes.ELEMENT */ ||
  15160. rawName.startsWith('vnode') ||
  15161. !/[A-Z]/.test(rawName)
  15162. ? // for non-element and vnode lifecycle event listeners, auto convert
  15163. // it to camelCase. See issue #2249
  15164. toHandlerKey(camelize(rawName))
  15165. : // preserve case for plain element listeners that have uppercase
  15166. // letters, as these may be custom elements' custom events
  15167. `on:${rawName}`;
  15168. eventName = createSimpleExpression(eventString, true, arg.loc);
  15169. }
  15170. else {
  15171. // #2388
  15172. eventName = createCompoundExpression([
  15173. `${context.helperString(TO_HANDLER_KEY)}(`,
  15174. arg,
  15175. `)`
  15176. ]);
  15177. }
  15178. }
  15179. else {
  15180. // already a compound expression.
  15181. eventName = arg;
  15182. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  15183. eventName.children.push(`)`);
  15184. }
  15185. // handler processing
  15186. let exp = dir.exp;
  15187. if (exp && !exp.content.trim()) {
  15188. exp = undefined;
  15189. }
  15190. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  15191. if (exp) {
  15192. const isMemberExp = isMemberExpression(exp.content);
  15193. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  15194. const hasMultipleStatements = exp.content.includes(`;`);
  15195. {
  15196. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  15197. }
  15198. if (isInlineStatement || (shouldCache && isMemberExp)) {
  15199. // wrap inline statement in a function expression
  15200. exp = createCompoundExpression([
  15201. `${isInlineStatement
  15202. ? `$event`
  15203. : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  15204. exp,
  15205. hasMultipleStatements ? `}` : `)`
  15206. ]);
  15207. }
  15208. }
  15209. let ret = {
  15210. props: [
  15211. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  15212. ]
  15213. };
  15214. // apply extended compiler augmentor
  15215. if (augmentor) {
  15216. ret = augmentor(ret);
  15217. }
  15218. if (shouldCache) {
  15219. // cache handlers so that it's always the same handler being passed down.
  15220. // this avoids unnecessary re-renders when users use inline handlers on
  15221. // components.
  15222. ret.props[0].value = context.cache(ret.props[0].value);
  15223. }
  15224. // mark the key as handler for props normalization check
  15225. ret.props.forEach(p => (p.key.isHandlerKey = true));
  15226. return ret;
  15227. };
  15228. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  15229. // codegen for the entire props object. This transform here is only for v-bind
  15230. // *with* args.
  15231. const transformBind = (dir, _node, context) => {
  15232. const { exp, modifiers, loc } = dir;
  15233. const arg = dir.arg;
  15234. if (arg.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  15235. arg.children.unshift(`(`);
  15236. arg.children.push(`) || ""`);
  15237. }
  15238. else if (!arg.isStatic) {
  15239. arg.content = `${arg.content} || ""`;
  15240. }
  15241. // .sync is replaced by v-model:arg
  15242. if (modifiers.includes('camel')) {
  15243. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  15244. if (arg.isStatic) {
  15245. arg.content = camelize(arg.content);
  15246. }
  15247. else {
  15248. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  15249. }
  15250. }
  15251. else {
  15252. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  15253. arg.children.push(`)`);
  15254. }
  15255. }
  15256. if (!context.inSSR) {
  15257. if (modifiers.includes('prop')) {
  15258. injectPrefix(arg, '.');
  15259. }
  15260. if (modifiers.includes('attr')) {
  15261. injectPrefix(arg, '^');
  15262. }
  15263. }
  15264. if (!exp ||
  15265. (exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  15266. context.onError(createCompilerError(34 /* ErrorCodes.X_V_BIND_NO_EXPRESSION */, loc));
  15267. return {
  15268. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  15269. };
  15270. }
  15271. return {
  15272. props: [createObjectProperty(arg, exp)]
  15273. };
  15274. };
  15275. const injectPrefix = (arg, prefix) => {
  15276. if (arg.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */) {
  15277. if (arg.isStatic) {
  15278. arg.content = prefix + arg.content;
  15279. }
  15280. else {
  15281. arg.content = `\`${prefix}\${${arg.content}}\``;
  15282. }
  15283. }
  15284. else {
  15285. arg.children.unshift(`'${prefix}' + (`);
  15286. arg.children.push(`)`);
  15287. }
  15288. };
  15289. // Merge adjacent text nodes and expressions into a single expression
  15290. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  15291. const transformText = (node, context) => {
  15292. if (node.type === 0 /* NodeTypes.ROOT */ ||
  15293. node.type === 1 /* NodeTypes.ELEMENT */ ||
  15294. node.type === 11 /* NodeTypes.FOR */ ||
  15295. node.type === 10 /* NodeTypes.IF_BRANCH */) {
  15296. // perform the transform on node exit so that all expressions have already
  15297. // been processed.
  15298. return () => {
  15299. const children = node.children;
  15300. let currentContainer = undefined;
  15301. let hasText = false;
  15302. for (let i = 0; i < children.length; i++) {
  15303. const child = children[i];
  15304. if (isText$1(child)) {
  15305. hasText = true;
  15306. for (let j = i + 1; j < children.length; j++) {
  15307. const next = children[j];
  15308. if (isText$1(next)) {
  15309. if (!currentContainer) {
  15310. currentContainer = children[i] = createCompoundExpression([child], child.loc);
  15311. }
  15312. // merge adjacent text node into current
  15313. currentContainer.children.push(` + `, next);
  15314. children.splice(j, 1);
  15315. j--;
  15316. }
  15317. else {
  15318. currentContainer = undefined;
  15319. break;
  15320. }
  15321. }
  15322. }
  15323. }
  15324. if (!hasText ||
  15325. // if this is a plain element with a single text child, leave it
  15326. // as-is since the runtime has dedicated fast path for this by directly
  15327. // setting textContent of the element.
  15328. // for component root it's always normalized anyway.
  15329. (children.length === 1 &&
  15330. (node.type === 0 /* NodeTypes.ROOT */ ||
  15331. (node.type === 1 /* NodeTypes.ELEMENT */ &&
  15332. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  15333. // #3756
  15334. // custom directives can potentially add DOM elements arbitrarily,
  15335. // we need to avoid setting textContent of the element at runtime
  15336. // to avoid accidentally overwriting the DOM elements added
  15337. // by the user through custom directives.
  15338. !node.props.find(p => p.type === 7 /* NodeTypes.DIRECTIVE */ &&
  15339. !context.directiveTransforms[p.name]) &&
  15340. // in compat mode, <template> tags with no special directives
  15341. // will be rendered as a fragment so its children must be
  15342. // converted into vnodes.
  15343. !(false ))))) {
  15344. return;
  15345. }
  15346. // pre-convert text nodes into createTextVNode(text) calls to avoid
  15347. // runtime normalization.
  15348. for (let i = 0; i < children.length; i++) {
  15349. const child = children[i];
  15350. if (isText$1(child) || child.type === 8 /* NodeTypes.COMPOUND_EXPRESSION */) {
  15351. const callArgs = [];
  15352. // createTextVNode defaults to single whitespace, so if it is a
  15353. // single space the code could be an empty call to save bytes.
  15354. if (child.type !== 2 /* NodeTypes.TEXT */ || child.content !== ' ') {
  15355. callArgs.push(child);
  15356. }
  15357. // mark dynamic text with flag so it gets patched inside a block
  15358. if (!context.ssr &&
  15359. getConstantType(child, context) === 0 /* ConstantTypes.NOT_CONSTANT */) {
  15360. callArgs.push(1 /* PatchFlags.TEXT */ +
  15361. (` /* ${PatchFlagNames[1 /* PatchFlags.TEXT */]} */` ));
  15362. }
  15363. children[i] = {
  15364. type: 12 /* NodeTypes.TEXT_CALL */,
  15365. content: child,
  15366. loc: child.loc,
  15367. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  15368. };
  15369. }
  15370. }
  15371. };
  15372. }
  15373. };
  15374. const seen$1 = new WeakSet();
  15375. const transformOnce = (node, context) => {
  15376. if (node.type === 1 /* NodeTypes.ELEMENT */ && findDir(node, 'once', true)) {
  15377. if (seen$1.has(node) || context.inVOnce) {
  15378. return;
  15379. }
  15380. seen$1.add(node);
  15381. context.inVOnce = true;
  15382. context.helper(SET_BLOCK_TRACKING);
  15383. return () => {
  15384. context.inVOnce = false;
  15385. const cur = context.currentNode;
  15386. if (cur.codegenNode) {
  15387. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  15388. }
  15389. };
  15390. }
  15391. };
  15392. const transformModel$1 = (dir, node, context) => {
  15393. const { exp, arg } = dir;
  15394. if (!exp) {
  15395. context.onError(createCompilerError(41 /* ErrorCodes.X_V_MODEL_NO_EXPRESSION */, dir.loc));
  15396. return createTransformProps();
  15397. }
  15398. const rawExp = exp.loc.source;
  15399. const expString = exp.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  15400. // im SFC <script setup> inline mode, the exp may have been transformed into
  15401. // _unref(exp)
  15402. const bindingType = context.bindingMetadata[rawExp];
  15403. // check props
  15404. if (bindingType === "props" /* BindingTypes.PROPS */ ||
  15405. bindingType === "props-aliased" /* BindingTypes.PROPS_ALIASED */) {
  15406. context.onError(createCompilerError(44 /* ErrorCodes.X_V_MODEL_ON_PROPS */, exp.loc));
  15407. return createTransformProps();
  15408. }
  15409. const maybeRef = !true ;
  15410. if (!expString.trim() ||
  15411. (!isMemberExpression(expString) && !maybeRef)) {
  15412. context.onError(createCompilerError(42 /* ErrorCodes.X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  15413. return createTransformProps();
  15414. }
  15415. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  15416. const eventName = arg
  15417. ? isStaticExp(arg)
  15418. ? `onUpdate:${camelize(arg.content)}`
  15419. : createCompoundExpression(['"onUpdate:" + ', arg])
  15420. : `onUpdate:modelValue`;
  15421. let assignmentExp;
  15422. const eventArg = context.isTS ? `($event: any)` : `$event`;
  15423. {
  15424. assignmentExp = createCompoundExpression([
  15425. `${eventArg} => ((`,
  15426. exp,
  15427. `) = $event)`
  15428. ]);
  15429. }
  15430. const props = [
  15431. // modelValue: foo
  15432. createObjectProperty(propName, dir.exp),
  15433. // "onUpdate:modelValue": $event => (foo = $event)
  15434. createObjectProperty(eventName, assignmentExp)
  15435. ];
  15436. // modelModifiers: { foo: true, "bar-baz": true }
  15437. if (dir.modifiers.length && node.tagType === 1 /* ElementTypes.COMPONENT */) {
  15438. const modifiers = dir.modifiers
  15439. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  15440. .join(`, `);
  15441. const modifiersKey = arg
  15442. ? isStaticExp(arg)
  15443. ? `${arg.content}Modifiers`
  15444. : createCompoundExpression([arg, ' + "Modifiers"'])
  15445. : `modelModifiers`;
  15446. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* ConstantTypes.CAN_HOIST */)));
  15447. }
  15448. return createTransformProps(props);
  15449. };
  15450. function createTransformProps(props = []) {
  15451. return { props };
  15452. }
  15453. const seen = new WeakSet();
  15454. const transformMemo = (node, context) => {
  15455. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  15456. const dir = findDir(node, 'memo');
  15457. if (!dir || seen.has(node)) {
  15458. return;
  15459. }
  15460. seen.add(node);
  15461. return () => {
  15462. const codegenNode = node.codegenNode ||
  15463. context.currentNode.codegenNode;
  15464. if (codegenNode && codegenNode.type === 13 /* NodeTypes.VNODE_CALL */) {
  15465. // non-component sub tree should be turned into a block
  15466. if (node.tagType !== 1 /* ElementTypes.COMPONENT */) {
  15467. makeBlock(codegenNode, context);
  15468. }
  15469. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  15470. dir.exp,
  15471. createFunctionExpression(undefined, codegenNode),
  15472. `_cache`,
  15473. String(context.cached++)
  15474. ]);
  15475. }
  15476. };
  15477. }
  15478. };
  15479. function getBaseTransformPreset(prefixIdentifiers) {
  15480. return [
  15481. [
  15482. transformOnce,
  15483. transformIf,
  15484. transformMemo,
  15485. transformFor,
  15486. ...([]),
  15487. ...([transformExpression]
  15488. ),
  15489. transformSlotOutlet,
  15490. transformElement,
  15491. trackSlotScopes,
  15492. transformText
  15493. ],
  15494. {
  15495. on: transformOn$1,
  15496. bind: transformBind,
  15497. model: transformModel$1
  15498. }
  15499. ];
  15500. }
  15501. // we name it `baseCompile` so that higher order compilers like
  15502. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  15503. function baseCompile(template, options = {}) {
  15504. const onError = options.onError || defaultOnError;
  15505. const isModuleMode = options.mode === 'module';
  15506. /* istanbul ignore if */
  15507. {
  15508. if (options.prefixIdentifiers === true) {
  15509. onError(createCompilerError(47 /* ErrorCodes.X_PREFIX_ID_NOT_SUPPORTED */));
  15510. }
  15511. else if (isModuleMode) {
  15512. onError(createCompilerError(48 /* ErrorCodes.X_MODULE_MODE_NOT_SUPPORTED */));
  15513. }
  15514. }
  15515. const prefixIdentifiers = !true ;
  15516. if (options.cacheHandlers) {
  15517. onError(createCompilerError(49 /* ErrorCodes.X_CACHE_HANDLER_NOT_SUPPORTED */));
  15518. }
  15519. if (options.scopeId && !isModuleMode) {
  15520. onError(createCompilerError(50 /* ErrorCodes.X_SCOPE_ID_NOT_SUPPORTED */));
  15521. }
  15522. const ast = isString(template) ? baseParse(template, options) : template;
  15523. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  15524. transform(ast, extend({}, options, {
  15525. prefixIdentifiers,
  15526. nodeTransforms: [
  15527. ...nodeTransforms,
  15528. ...(options.nodeTransforms || []) // user transforms
  15529. ],
  15530. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  15531. )
  15532. }));
  15533. return generate(ast, extend({}, options, {
  15534. prefixIdentifiers
  15535. }));
  15536. }
  15537. const noopDirectiveTransform = () => ({ props: [] });
  15538. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  15539. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  15540. const V_MODEL_TEXT = Symbol(`vModelText` );
  15541. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  15542. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  15543. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  15544. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  15545. const V_SHOW = Symbol(`vShow` );
  15546. const TRANSITION = Symbol(`Transition` );
  15547. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  15548. registerRuntimeHelpers({
  15549. [V_MODEL_RADIO]: `vModelRadio`,
  15550. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  15551. [V_MODEL_TEXT]: `vModelText`,
  15552. [V_MODEL_SELECT]: `vModelSelect`,
  15553. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  15554. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  15555. [V_ON_WITH_KEYS]: `withKeys`,
  15556. [V_SHOW]: `vShow`,
  15557. [TRANSITION]: `Transition`,
  15558. [TRANSITION_GROUP]: `TransitionGroup`
  15559. });
  15560. /* eslint-disable no-restricted-globals */
  15561. let decoder;
  15562. function decodeHtmlBrowser(raw, asAttr = false) {
  15563. if (!decoder) {
  15564. decoder = document.createElement('div');
  15565. }
  15566. if (asAttr) {
  15567. decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
  15568. return decoder.children[0].getAttribute('foo');
  15569. }
  15570. else {
  15571. decoder.innerHTML = raw;
  15572. return decoder.textContent;
  15573. }
  15574. }
  15575. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  15576. const parserOptions = {
  15577. isVoidTag,
  15578. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  15579. isPreTag: tag => tag === 'pre',
  15580. decodeEntities: decodeHtmlBrowser ,
  15581. isBuiltInComponent: (tag) => {
  15582. if (isBuiltInType(tag, `Transition`)) {
  15583. return TRANSITION;
  15584. }
  15585. else if (isBuiltInType(tag, `TransitionGroup`)) {
  15586. return TRANSITION_GROUP;
  15587. }
  15588. },
  15589. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  15590. getNamespace(tag, parent) {
  15591. let ns = parent ? parent.ns : 0 /* DOMNamespaces.HTML */;
  15592. if (parent && ns === 2 /* DOMNamespaces.MATH_ML */) {
  15593. if (parent.tag === 'annotation-xml') {
  15594. if (tag === 'svg') {
  15595. return 1 /* DOMNamespaces.SVG */;
  15596. }
  15597. if (parent.props.some(a => a.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  15598. a.name === 'encoding' &&
  15599. a.value != null &&
  15600. (a.value.content === 'text/html' ||
  15601. a.value.content === 'application/xhtml+xml'))) {
  15602. ns = 0 /* DOMNamespaces.HTML */;
  15603. }
  15604. }
  15605. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  15606. tag !== 'mglyph' &&
  15607. tag !== 'malignmark') {
  15608. ns = 0 /* DOMNamespaces.HTML */;
  15609. }
  15610. }
  15611. else if (parent && ns === 1 /* DOMNamespaces.SVG */) {
  15612. if (parent.tag === 'foreignObject' ||
  15613. parent.tag === 'desc' ||
  15614. parent.tag === 'title') {
  15615. ns = 0 /* DOMNamespaces.HTML */;
  15616. }
  15617. }
  15618. if (ns === 0 /* DOMNamespaces.HTML */) {
  15619. if (tag === 'svg') {
  15620. return 1 /* DOMNamespaces.SVG */;
  15621. }
  15622. if (tag === 'math') {
  15623. return 2 /* DOMNamespaces.MATH_ML */;
  15624. }
  15625. }
  15626. return ns;
  15627. },
  15628. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  15629. getTextMode({ tag, ns }) {
  15630. if (ns === 0 /* DOMNamespaces.HTML */) {
  15631. if (tag === 'textarea' || tag === 'title') {
  15632. return 1 /* TextModes.RCDATA */;
  15633. }
  15634. if (isRawTextContainer(tag)) {
  15635. return 2 /* TextModes.RAWTEXT */;
  15636. }
  15637. }
  15638. return 0 /* TextModes.DATA */;
  15639. }
  15640. };
  15641. // Parse inline CSS strings for static style attributes into an object.
  15642. // This is a NodeTransform since it works on the static `style` attribute and
  15643. // converts it into a dynamic equivalent:
  15644. // style="color: red" -> :style='{ "color": "red" }'
  15645. // It is then processed by `transformElement` and included in the generated
  15646. // props.
  15647. const transformStyle = node => {
  15648. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  15649. node.props.forEach((p, i) => {
  15650. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'style' && p.value) {
  15651. // replace p with an expression node
  15652. node.props[i] = {
  15653. type: 7 /* NodeTypes.DIRECTIVE */,
  15654. name: `bind`,
  15655. arg: createSimpleExpression(`style`, true, p.loc),
  15656. exp: parseInlineCSS(p.value.content, p.loc),
  15657. modifiers: [],
  15658. loc: p.loc
  15659. };
  15660. }
  15661. });
  15662. }
  15663. };
  15664. const parseInlineCSS = (cssText, loc) => {
  15665. const normalized = parseStringStyle(cssText);
  15666. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  15667. };
  15668. function createDOMCompilerError(code, loc) {
  15669. return createCompilerError(code, loc, DOMErrorMessages );
  15670. }
  15671. const DOMErrorMessages = {
  15672. [51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  15673. [52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  15674. [53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  15675. [54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  15676. [55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  15677. [56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  15678. [57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  15679. [58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  15680. [59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  15681. [60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  15682. [61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  15683. };
  15684. const transformVHtml = (dir, node, context) => {
  15685. const { exp, loc } = dir;
  15686. if (!exp) {
  15687. context.onError(createDOMCompilerError(51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */, loc));
  15688. }
  15689. if (node.children.length) {
  15690. context.onError(createDOMCompilerError(52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */, loc));
  15691. node.children.length = 0;
  15692. }
  15693. return {
  15694. props: [
  15695. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  15696. ]
  15697. };
  15698. };
  15699. const transformVText = (dir, node, context) => {
  15700. const { exp, loc } = dir;
  15701. if (!exp) {
  15702. context.onError(createDOMCompilerError(53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */, loc));
  15703. }
  15704. if (node.children.length) {
  15705. context.onError(createDOMCompilerError(54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */, loc));
  15706. node.children.length = 0;
  15707. }
  15708. return {
  15709. props: [
  15710. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  15711. ? getConstantType(exp, context) > 0
  15712. ? exp
  15713. : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  15714. : createSimpleExpression('', true))
  15715. ]
  15716. };
  15717. };
  15718. const transformModel = (dir, node, context) => {
  15719. const baseResult = transformModel$1(dir, node, context);
  15720. // base transform has errors OR component v-model (only need props)
  15721. if (!baseResult.props.length || node.tagType === 1 /* ElementTypes.COMPONENT */) {
  15722. return baseResult;
  15723. }
  15724. if (dir.arg) {
  15725. context.onError(createDOMCompilerError(56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  15726. }
  15727. function checkDuplicatedValue() {
  15728. const value = findProp(node, 'value');
  15729. if (value) {
  15730. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  15731. }
  15732. }
  15733. const { tag } = node;
  15734. const isCustomElement = context.isCustomElement(tag);
  15735. if (tag === 'input' ||
  15736. tag === 'textarea' ||
  15737. tag === 'select' ||
  15738. isCustomElement) {
  15739. let directiveToUse = V_MODEL_TEXT;
  15740. let isInvalidType = false;
  15741. if (tag === 'input' || isCustomElement) {
  15742. const type = findProp(node, `type`);
  15743. if (type) {
  15744. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  15745. // :type="foo"
  15746. directiveToUse = V_MODEL_DYNAMIC;
  15747. }
  15748. else if (type.value) {
  15749. switch (type.value.content) {
  15750. case 'radio':
  15751. directiveToUse = V_MODEL_RADIO;
  15752. break;
  15753. case 'checkbox':
  15754. directiveToUse = V_MODEL_CHECKBOX;
  15755. break;
  15756. case 'file':
  15757. isInvalidType = true;
  15758. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  15759. break;
  15760. default:
  15761. // text type
  15762. checkDuplicatedValue();
  15763. break;
  15764. }
  15765. }
  15766. }
  15767. else if (hasDynamicKeyVBind(node)) {
  15768. // element has bindings with dynamic keys, which can possibly contain
  15769. // "type".
  15770. directiveToUse = V_MODEL_DYNAMIC;
  15771. }
  15772. else {
  15773. // text type
  15774. checkDuplicatedValue();
  15775. }
  15776. }
  15777. else if (tag === 'select') {
  15778. directiveToUse = V_MODEL_SELECT;
  15779. }
  15780. else {
  15781. // textarea
  15782. checkDuplicatedValue();
  15783. }
  15784. // inject runtime directive
  15785. // by returning the helper symbol via needRuntime
  15786. // the import will replaced a resolveDirective call.
  15787. if (!isInvalidType) {
  15788. baseResult.needRuntime = context.helper(directiveToUse);
  15789. }
  15790. }
  15791. else {
  15792. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  15793. }
  15794. // native vmodel doesn't need the `modelValue` props since they are also
  15795. // passed to the runtime as `binding.value`. removing it reduces code size.
  15796. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  15797. p.key.content === 'modelValue'));
  15798. return baseResult;
  15799. };
  15800. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  15801. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  15802. // event propagation management
  15803. `stop,prevent,self,` +
  15804. // system modifiers + exact
  15805. `ctrl,shift,alt,meta,exact,` +
  15806. // mouse
  15807. `middle`);
  15808. // left & right could be mouse or key modifiers based on event type
  15809. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  15810. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  15811. const resolveModifiers = (key, modifiers, context, loc) => {
  15812. const keyModifiers = [];
  15813. const nonKeyModifiers = [];
  15814. const eventOptionModifiers = [];
  15815. for (let i = 0; i < modifiers.length; i++) {
  15816. const modifier = modifiers[i];
  15817. if (isEventOptionModifier(modifier)) {
  15818. // eventOptionModifiers: modifiers for addEventListener() options,
  15819. // e.g. .passive & .capture
  15820. eventOptionModifiers.push(modifier);
  15821. }
  15822. else {
  15823. // runtimeModifiers: modifiers that needs runtime guards
  15824. if (maybeKeyModifier(modifier)) {
  15825. if (isStaticExp(key)) {
  15826. if (isKeyboardEvent(key.content)) {
  15827. keyModifiers.push(modifier);
  15828. }
  15829. else {
  15830. nonKeyModifiers.push(modifier);
  15831. }
  15832. }
  15833. else {
  15834. keyModifiers.push(modifier);
  15835. nonKeyModifiers.push(modifier);
  15836. }
  15837. }
  15838. else {
  15839. if (isNonKeyModifier(modifier)) {
  15840. nonKeyModifiers.push(modifier);
  15841. }
  15842. else {
  15843. keyModifiers.push(modifier);
  15844. }
  15845. }
  15846. }
  15847. }
  15848. return {
  15849. keyModifiers,
  15850. nonKeyModifiers,
  15851. eventOptionModifiers
  15852. };
  15853. };
  15854. const transformClick = (key, event) => {
  15855. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  15856. return isStaticClick
  15857. ? createSimpleExpression(event, true)
  15858. : key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */
  15859. ? createCompoundExpression([
  15860. `(`,
  15861. key,
  15862. `) === "onClick" ? "${event}" : (`,
  15863. key,
  15864. `)`
  15865. ])
  15866. : key;
  15867. };
  15868. const transformOn = (dir, node, context) => {
  15869. return transformOn$1(dir, node, context, baseResult => {
  15870. const { modifiers } = dir;
  15871. if (!modifiers.length)
  15872. return baseResult;
  15873. let { key, value: handlerExp } = baseResult.props[0];
  15874. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  15875. // normalize click.right and click.middle since they don't actually fire
  15876. if (nonKeyModifiers.includes('right')) {
  15877. key = transformClick(key, `onContextmenu`);
  15878. }
  15879. if (nonKeyModifiers.includes('middle')) {
  15880. key = transformClick(key, `onMouseup`);
  15881. }
  15882. if (nonKeyModifiers.length) {
  15883. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  15884. handlerExp,
  15885. JSON.stringify(nonKeyModifiers)
  15886. ]);
  15887. }
  15888. if (keyModifiers.length &&
  15889. // if event name is dynamic, always wrap with keys guard
  15890. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  15891. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  15892. handlerExp,
  15893. JSON.stringify(keyModifiers)
  15894. ]);
  15895. }
  15896. if (eventOptionModifiers.length) {
  15897. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  15898. key = isStaticExp(key)
  15899. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  15900. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  15901. }
  15902. return {
  15903. props: [createObjectProperty(key, handlerExp)]
  15904. };
  15905. });
  15906. };
  15907. const transformShow = (dir, node, context) => {
  15908. const { exp, loc } = dir;
  15909. if (!exp) {
  15910. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */, loc));
  15911. }
  15912. return {
  15913. props: [],
  15914. needRuntime: context.helper(V_SHOW)
  15915. };
  15916. };
  15917. const transformTransition = (node, context) => {
  15918. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  15919. node.tagType === 1 /* ElementTypes.COMPONENT */) {
  15920. const component = context.isBuiltInComponent(node.tag);
  15921. if (component === TRANSITION) {
  15922. return () => {
  15923. if (!node.children.length) {
  15924. return;
  15925. }
  15926. // warn multiple transition children
  15927. if (hasMultipleChildren(node)) {
  15928. context.onError(createDOMCompilerError(60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */, {
  15929. start: node.children[0].loc.start,
  15930. end: node.children[node.children.length - 1].loc.end,
  15931. source: ''
  15932. }));
  15933. }
  15934. // check if it's s single child w/ v-show
  15935. // if yes, inject "persisted: true" to the transition props
  15936. const child = node.children[0];
  15937. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  15938. for (const p of child.props) {
  15939. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'show') {
  15940. node.props.push({
  15941. type: 6 /* NodeTypes.ATTRIBUTE */,
  15942. name: 'persisted',
  15943. value: undefined,
  15944. loc: node.loc
  15945. });
  15946. }
  15947. }
  15948. }
  15949. };
  15950. }
  15951. }
  15952. };
  15953. function hasMultipleChildren(node) {
  15954. // #1352 filter out potential comment nodes.
  15955. const children = (node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */ &&
  15956. !(c.type === 2 /* NodeTypes.TEXT */ && !c.content.trim())));
  15957. const child = children[0];
  15958. return (children.length !== 1 ||
  15959. child.type === 11 /* NodeTypes.FOR */ ||
  15960. (child.type === 9 /* NodeTypes.IF */ && child.branches.some(hasMultipleChildren)));
  15961. }
  15962. const ignoreSideEffectTags = (node, context) => {
  15963. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  15964. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  15965. (node.tag === 'script' || node.tag === 'style')) {
  15966. context.onError(createDOMCompilerError(61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  15967. context.removeNode();
  15968. }
  15969. };
  15970. const DOMNodeTransforms = [
  15971. transformStyle,
  15972. ...([transformTransition] )
  15973. ];
  15974. const DOMDirectiveTransforms = {
  15975. cloak: noopDirectiveTransform,
  15976. html: transformVHtml,
  15977. text: transformVText,
  15978. model: transformModel,
  15979. on: transformOn,
  15980. show: transformShow
  15981. };
  15982. function compile(template, options = {}) {
  15983. return baseCompile(template, extend({}, parserOptions, options, {
  15984. nodeTransforms: [
  15985. // ignore <script> and <tag>
  15986. // this is not put inside DOMNodeTransforms because that list is used
  15987. // by compiler-ssr to generate vnode fallback branches
  15988. ignoreSideEffectTags,
  15989. ...DOMNodeTransforms,
  15990. ...(options.nodeTransforms || [])
  15991. ],
  15992. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  15993. transformHoist: null
  15994. }));
  15995. }
  15996. // This entry is the "full-build" that includes both the runtime
  15997. {
  15998. initDev();
  15999. }
  16000. const compileCache = Object.create(null);
  16001. function compileToFunction(template, options) {
  16002. if (!isString(template)) {
  16003. if (template.nodeType) {
  16004. template = template.innerHTML;
  16005. }
  16006. else {
  16007. warn(`invalid template option: `, template);
  16008. return NOOP;
  16009. }
  16010. }
  16011. const key = template;
  16012. const cached = compileCache[key];
  16013. if (cached) {
  16014. return cached;
  16015. }
  16016. if (template[0] === '#') {
  16017. const el = document.querySelector(template);
  16018. if (!el) {
  16019. warn(`Template element not found or is empty: ${template}`);
  16020. }
  16021. // __UNSAFE__
  16022. // Reason: potential execution of JS expressions in in-DOM template.
  16023. // The user must make sure the in-DOM template is trusted. If it's rendered
  16024. // by the server, the template should not contain any user data.
  16025. template = el ? el.innerHTML : ``;
  16026. }
  16027. const opts = extend({
  16028. hoistStatic: true,
  16029. onError: onError ,
  16030. onWarn: e => onError(e, true)
  16031. }, options);
  16032. if (!opts.isCustomElement && typeof customElements !== 'undefined') {
  16033. opts.isCustomElement = tag => !!customElements.get(tag);
  16034. }
  16035. const { code } = compile(template, opts);
  16036. function onError(err, asWarning = false) {
  16037. const message = asWarning
  16038. ? err.message
  16039. : `Template compilation error: ${err.message}`;
  16040. const codeFrame = err.loc &&
  16041. generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
  16042. warn(codeFrame ? `${message}\n${codeFrame}` : message);
  16043. }
  16044. // The wildcard import results in a huge object with every export
  16045. // with keys that cannot be mangled, and can be quite heavy size-wise.
  16046. // In the global build we know `Vue` is available globally so we can avoid
  16047. // the wildcard object.
  16048. const render = (new Function('Vue', code)(runtimeDom));
  16049. render._rc = true;
  16050. return (compileCache[key] = render);
  16051. }
  16052. registerRuntimeCompiler(compileToFunction);
  16053. export { BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, assertNumber, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compileToFunction as compile, computed, createApp, createBlock, createCommentVNode, createElementBlock, createBaseVNode as createElementVNode, createHydrationRenderer, createPropsRestProxy, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineCustomElement, defineEmits, defineExpose, defineProps, defineSSRCustomElement, devtools, effect, effectScope, getCurrentInstance, getCurrentScope, getTransitionRawChildren, guardReactiveProps, h, handleError, hydrate, initCustomFormatter, initDirectivesForSSR, inject, isMemoSame, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, isShallow, isVNode, markRaw, mergeDefaults, mergeProps, nextTick, normalizeClass, normalizeProps, normalizeStyle, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onServerPrefetch, onUnmounted, onUpdated, openBlock, popScopeId, provide, proxyRefs, pushScopeId, queuePostFlushCb, reactive, readonly, ref, registerRuntimeCompiler, render, renderList, renderSlot, resolveComponent, resolveDirective, resolveDynamicComponent, resolveFilter, resolveTransitionHooks, setBlockTracking, setDevtoolsHook, setTransitionHooks, shallowReactive, shallowReadonly, shallowRef, ssrContextKey, ssrUtils, stop, toDisplayString, toHandlerKey, toHandlers, toRaw, toRef, toRefs, transformVNodeArgs, triggerRef, unref, useAttrs, useCssModule, useCssVars, useSSRContext, useSlots, useTransitionState, vModelCheckbox, vModelDynamic, vModelRadio, vModelSelect, vModelText, vShow, version, warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withKeys, withMemo, withModifiers, withScopeId };