vue.esm-browser.js 483 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424
  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. // Patch flags are optimization hints generated by the compiler.
  17. // when a block with dynamicChildren is encountered during diff, the algorithm
  18. // enters "optimized mode". In this mode, we know that the vdom is produced by
  19. // a render function generated by the compiler, so the algorithm only needs to
  20. // handle updates explicitly marked by these patch flags.
  21. // dev only flag -> name mapping
  22. const PatchFlagNames = {
  23. [1 /* TEXT */]: `TEXT`,
  24. [2 /* CLASS */]: `CLASS`,
  25. [4 /* STYLE */]: `STYLE`,
  26. [8 /* PROPS */]: `PROPS`,
  27. [16 /* FULL_PROPS */]: `FULL_PROPS`,
  28. [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  29. [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  30. [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  31. [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  32. [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  33. [512 /* NEED_PATCH */]: `NEED_PATCH`,
  34. [-1 /* HOISTED */]: `HOISTED`,
  35. [-2 /* BAIL */]: `BAIL`
  36. };
  37. const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  38. 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  39. 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl';
  40. const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
  41. const range = 2;
  42. function generateCodeFrame(source, start = 0, end = source.length) {
  43. const lines = source.split(/\r?\n/);
  44. let count = 0;
  45. const res = [];
  46. for (let i = 0; i < lines.length; i++) {
  47. count += lines[i].length + 1;
  48. if (count >= start) {
  49. for (let j = i - range; j <= i + range || end > count; j++) {
  50. if (j < 0 || j >= lines.length)
  51. continue;
  52. const line = j + 1;
  53. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  54. const lineLength = lines[j].length;
  55. if (j === i) {
  56. // push underline
  57. const pad = start - (count - lineLength) + 1;
  58. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  59. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  60. }
  61. else if (j > i) {
  62. if (end > count) {
  63. const length = Math.max(Math.min(end - count, lineLength), 1);
  64. res.push(` | ` + '^'.repeat(length));
  65. }
  66. count += lineLength + 1;
  67. }
  68. }
  69. break;
  70. }
  71. }
  72. return res.join('\n');
  73. }
  74. /**
  75. * On the client we only need to offer special cases for boolean attributes that
  76. * have different names from their corresponding dom properties:
  77. * - itemscope -> N/A
  78. * - allowfullscreen -> allowFullscreen
  79. * - formnovalidate -> formNoValidate
  80. * - ismap -> isMap
  81. * - nomodule -> noModule
  82. * - novalidate -> noValidate
  83. * - readonly -> readOnly
  84. */
  85. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  86. const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
  87. function normalizeStyle(value) {
  88. if (isArray(value)) {
  89. const res = {};
  90. for (let i = 0; i < value.length; i++) {
  91. const item = value[i];
  92. const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
  93. if (normalized) {
  94. for (const key in normalized) {
  95. res[key] = normalized[key];
  96. }
  97. }
  98. }
  99. return res;
  100. }
  101. else if (isObject(value)) {
  102. return value;
  103. }
  104. }
  105. const listDelimiterRE = /;(?![^(]*\))/g;
  106. const propertyDelimiterRE = /:(.+)/;
  107. function parseStringStyle(cssText) {
  108. const ret = {};
  109. cssText.split(listDelimiterRE).forEach(item => {
  110. if (item) {
  111. const tmp = item.split(propertyDelimiterRE);
  112. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  113. }
  114. });
  115. return ret;
  116. }
  117. function normalizeClass(value) {
  118. let res = '';
  119. if (isString(value)) {
  120. res = value;
  121. }
  122. else if (isArray(value)) {
  123. for (let i = 0; i < value.length; i++) {
  124. res += normalizeClass(value[i]) + ' ';
  125. }
  126. }
  127. else if (isObject(value)) {
  128. for (const name in value) {
  129. if (value[name]) {
  130. res += name + ' ';
  131. }
  132. }
  133. }
  134. return res.trim();
  135. }
  136. // These tag configs are shared between compiler-dom and runtime-dom, so they
  137. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  138. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  139. 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
  140. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  141. 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
  142. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  143. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  144. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  145. 'option,output,progress,select,textarea,details,dialog,menu,' +
  146. 'summary,template,blockquote,iframe,tfoot';
  147. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  148. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  149. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  150. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  151. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  152. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  153. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  154. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  155. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  156. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  157. 'text,textPath,title,tspan,unknown,use,view';
  158. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  159. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  160. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  161. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  162. function looseCompareArrays(a, b) {
  163. if (a.length !== b.length)
  164. return false;
  165. let equal = true;
  166. for (let i = 0; equal && i < a.length; i++) {
  167. equal = looseEqual(a[i], b[i]);
  168. }
  169. return equal;
  170. }
  171. function looseEqual(a, b) {
  172. if (a === b)
  173. return true;
  174. let aValidType = isDate(a);
  175. let bValidType = isDate(b);
  176. if (aValidType || bValidType) {
  177. return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  178. }
  179. aValidType = isArray(a);
  180. bValidType = isArray(b);
  181. if (aValidType || bValidType) {
  182. return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  183. }
  184. aValidType = isObject(a);
  185. bValidType = isObject(b);
  186. if (aValidType || bValidType) {
  187. /* istanbul ignore if: this if will probably never be called */
  188. if (!aValidType || !bValidType) {
  189. return false;
  190. }
  191. const aKeysCount = Object.keys(a).length;
  192. const bKeysCount = Object.keys(b).length;
  193. if (aKeysCount !== bKeysCount) {
  194. return false;
  195. }
  196. for (const key in a) {
  197. const aHasKey = a.hasOwnProperty(key);
  198. const bHasKey = b.hasOwnProperty(key);
  199. if ((aHasKey && !bHasKey) ||
  200. (!aHasKey && bHasKey) ||
  201. !looseEqual(a[key], b[key])) {
  202. return false;
  203. }
  204. }
  205. }
  206. return String(a) === String(b);
  207. }
  208. function looseIndexOf(arr, val) {
  209. return arr.findIndex(item => looseEqual(item, val));
  210. }
  211. /**
  212. * For converting {{ interpolation }} values to displayed strings.
  213. * @private
  214. */
  215. const toDisplayString = (val) => {
  216. return val == null
  217. ? ''
  218. : isObject(val)
  219. ? JSON.stringify(val, replacer, 2)
  220. : String(val);
  221. };
  222. const replacer = (_key, val) => {
  223. if (isMap(val)) {
  224. return {
  225. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  226. entries[`${key} =>`] = val;
  227. return entries;
  228. }, {})
  229. };
  230. }
  231. else if (isSet(val)) {
  232. return {
  233. [`Set(${val.size})`]: [...val.values()]
  234. };
  235. }
  236. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  237. return String(val);
  238. }
  239. return val;
  240. };
  241. const EMPTY_OBJ = Object.freeze({})
  242. ;
  243. const EMPTY_ARR = Object.freeze([]) ;
  244. const NOOP = () => { };
  245. /**
  246. * Always return false.
  247. */
  248. const NO = () => false;
  249. const onRE = /^on[^a-z]/;
  250. const isOn = (key) => onRE.test(key);
  251. const isModelListener = (key) => key.startsWith('onUpdate:');
  252. const extend = Object.assign;
  253. const remove = (arr, el) => {
  254. const i = arr.indexOf(el);
  255. if (i > -1) {
  256. arr.splice(i, 1);
  257. }
  258. };
  259. const hasOwnProperty = Object.prototype.hasOwnProperty;
  260. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  261. const isArray = Array.isArray;
  262. const isMap = (val) => toTypeString(val) === '[object Map]';
  263. const isSet = (val) => toTypeString(val) === '[object Set]';
  264. const isDate = (val) => val instanceof Date;
  265. const isFunction = (val) => typeof val === 'function';
  266. const isString = (val) => typeof val === 'string';
  267. const isSymbol = (val) => typeof val === 'symbol';
  268. const isObject = (val) => val !== null && typeof val === 'object';
  269. const isPromise = (val) => {
  270. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  271. };
  272. const objectToString = Object.prototype.toString;
  273. const toTypeString = (value) => objectToString.call(value);
  274. const toRawType = (value) => {
  275. // extract "RawType" from strings like "[object RawType]"
  276. return toTypeString(value).slice(8, -1);
  277. };
  278. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  279. const isIntegerKey = (key) => isString(key) &&
  280. key !== 'NaN' &&
  281. key[0] !== '-' &&
  282. '' + parseInt(key, 10) === key;
  283. const isReservedProp = /*#__PURE__*/ makeMap(
  284. // the leading comma is intentional so empty string "" is also included
  285. ',key,ref,' +
  286. 'onVnodeBeforeMount,onVnodeMounted,' +
  287. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  288. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  289. const cacheStringFunction = (fn) => {
  290. const cache = Object.create(null);
  291. return ((str) => {
  292. const hit = cache[str];
  293. return hit || (cache[str] = fn(str));
  294. });
  295. };
  296. const camelizeRE = /-(\w)/g;
  297. /**
  298. * @private
  299. */
  300. const camelize = cacheStringFunction((str) => {
  301. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  302. });
  303. const hyphenateRE = /\B([A-Z])/g;
  304. /**
  305. * @private
  306. */
  307. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  308. /**
  309. * @private
  310. */
  311. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  312. /**
  313. * @private
  314. */
  315. const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
  316. // compare whether a value has changed, accounting for NaN.
  317. const hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue);
  318. const invokeArrayFns = (fns, arg) => {
  319. for (let i = 0; i < fns.length; i++) {
  320. fns[i](arg);
  321. }
  322. };
  323. const def = (obj, key, value) => {
  324. Object.defineProperty(obj, key, {
  325. configurable: true,
  326. enumerable: false,
  327. value
  328. });
  329. };
  330. const toNumber = (val) => {
  331. const n = parseFloat(val);
  332. return isNaN(n) ? val : n;
  333. };
  334. let _globalThis;
  335. const getGlobalThis = () => {
  336. return (_globalThis ||
  337. (_globalThis =
  338. typeof globalThis !== 'undefined'
  339. ? globalThis
  340. : typeof self !== 'undefined'
  341. ? self
  342. : typeof window !== 'undefined'
  343. ? window
  344. : typeof global !== 'undefined'
  345. ? global
  346. : {}));
  347. };
  348. const targetMap = new WeakMap();
  349. const effectStack = [];
  350. let activeEffect;
  351. const ITERATE_KEY = Symbol( 'iterate' );
  352. const MAP_KEY_ITERATE_KEY = Symbol( 'Map key iterate' );
  353. function isEffect(fn) {
  354. return fn && fn._isEffect === true;
  355. }
  356. function effect(fn, options = EMPTY_OBJ) {
  357. if (isEffect(fn)) {
  358. fn = fn.raw;
  359. }
  360. const effect = createReactiveEffect(fn, options);
  361. if (!options.lazy) {
  362. effect();
  363. }
  364. return effect;
  365. }
  366. function stop(effect) {
  367. if (effect.active) {
  368. cleanup(effect);
  369. if (effect.options.onStop) {
  370. effect.options.onStop();
  371. }
  372. effect.active = false;
  373. }
  374. }
  375. let uid = 0;
  376. function createReactiveEffect(fn, options) {
  377. const effect = function reactiveEffect() {
  378. if (!effect.active) {
  379. return options.scheduler ? undefined : fn();
  380. }
  381. if (!effectStack.includes(effect)) {
  382. cleanup(effect);
  383. try {
  384. enableTracking();
  385. effectStack.push(effect);
  386. activeEffect = effect;
  387. return fn();
  388. }
  389. finally {
  390. effectStack.pop();
  391. resetTracking();
  392. activeEffect = effectStack[effectStack.length - 1];
  393. }
  394. }
  395. };
  396. effect.id = uid++;
  397. effect.allowRecurse = !!options.allowRecurse;
  398. effect._isEffect = true;
  399. effect.active = true;
  400. effect.raw = fn;
  401. effect.deps = [];
  402. effect.options = options;
  403. return effect;
  404. }
  405. function cleanup(effect) {
  406. const { deps } = effect;
  407. if (deps.length) {
  408. for (let i = 0; i < deps.length; i++) {
  409. deps[i].delete(effect);
  410. }
  411. deps.length = 0;
  412. }
  413. }
  414. let shouldTrack = true;
  415. const trackStack = [];
  416. function pauseTracking() {
  417. trackStack.push(shouldTrack);
  418. shouldTrack = false;
  419. }
  420. function enableTracking() {
  421. trackStack.push(shouldTrack);
  422. shouldTrack = true;
  423. }
  424. function resetTracking() {
  425. const last = trackStack.pop();
  426. shouldTrack = last === undefined ? true : last;
  427. }
  428. function track(target, type, key) {
  429. if (!shouldTrack || activeEffect === undefined) {
  430. return;
  431. }
  432. let depsMap = targetMap.get(target);
  433. if (!depsMap) {
  434. targetMap.set(target, (depsMap = new Map()));
  435. }
  436. let dep = depsMap.get(key);
  437. if (!dep) {
  438. depsMap.set(key, (dep = new Set()));
  439. }
  440. if (!dep.has(activeEffect)) {
  441. dep.add(activeEffect);
  442. activeEffect.deps.push(dep);
  443. if ( activeEffect.options.onTrack) {
  444. activeEffect.options.onTrack({
  445. effect: activeEffect,
  446. target,
  447. type,
  448. key
  449. });
  450. }
  451. }
  452. }
  453. function trigger(target, type, key, newValue, oldValue, oldTarget) {
  454. const depsMap = targetMap.get(target);
  455. if (!depsMap) {
  456. // never been tracked
  457. return;
  458. }
  459. const effects = new Set();
  460. const add = (effectsToAdd) => {
  461. if (effectsToAdd) {
  462. effectsToAdd.forEach(effect => {
  463. if (effect !== activeEffect || effect.allowRecurse) {
  464. effects.add(effect);
  465. }
  466. });
  467. }
  468. };
  469. if (type === "clear" /* CLEAR */) {
  470. // collection being cleared
  471. // trigger all effects for target
  472. depsMap.forEach(add);
  473. }
  474. else if (key === 'length' && isArray(target)) {
  475. depsMap.forEach((dep, key) => {
  476. if (key === 'length' || key >= newValue) {
  477. add(dep);
  478. }
  479. });
  480. }
  481. else {
  482. // schedule runs for SET | ADD | DELETE
  483. if (key !== void 0) {
  484. add(depsMap.get(key));
  485. }
  486. // also run for iteration key on ADD | DELETE | Map.SET
  487. switch (type) {
  488. case "add" /* ADD */:
  489. if (!isArray(target)) {
  490. add(depsMap.get(ITERATE_KEY));
  491. if (isMap(target)) {
  492. add(depsMap.get(MAP_KEY_ITERATE_KEY));
  493. }
  494. }
  495. else if (isIntegerKey(key)) {
  496. // new index added to array -> length changes
  497. add(depsMap.get('length'));
  498. }
  499. break;
  500. case "delete" /* DELETE */:
  501. if (!isArray(target)) {
  502. add(depsMap.get(ITERATE_KEY));
  503. if (isMap(target)) {
  504. add(depsMap.get(MAP_KEY_ITERATE_KEY));
  505. }
  506. }
  507. break;
  508. case "set" /* SET */:
  509. if (isMap(target)) {
  510. add(depsMap.get(ITERATE_KEY));
  511. }
  512. break;
  513. }
  514. }
  515. const run = (effect) => {
  516. if ( effect.options.onTrigger) {
  517. effect.options.onTrigger({
  518. effect,
  519. target,
  520. key,
  521. type,
  522. newValue,
  523. oldValue,
  524. oldTarget
  525. });
  526. }
  527. if (effect.options.scheduler) {
  528. effect.options.scheduler(effect);
  529. }
  530. else {
  531. effect();
  532. }
  533. };
  534. effects.forEach(run);
  535. }
  536. const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
  537. .map(key => Symbol[key])
  538. .filter(isSymbol));
  539. const get = /*#__PURE__*/ createGetter();
  540. const shallowGet = /*#__PURE__*/ createGetter(false, true);
  541. const readonlyGet = /*#__PURE__*/ createGetter(true);
  542. const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
  543. const arrayInstrumentations = {};
  544. ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
  545. const method = Array.prototype[key];
  546. arrayInstrumentations[key] = function (...args) {
  547. const arr = toRaw(this);
  548. for (let i = 0, l = this.length; i < l; i++) {
  549. track(arr, "get" /* GET */, i + '');
  550. }
  551. // we run the method using the original args first (which may be reactive)
  552. const res = method.apply(arr, args);
  553. if (res === -1 || res === false) {
  554. // if that didn't work, run it again using raw values.
  555. return method.apply(arr, args.map(toRaw));
  556. }
  557. else {
  558. return res;
  559. }
  560. };
  561. });
  562. ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
  563. const method = Array.prototype[key];
  564. arrayInstrumentations[key] = function (...args) {
  565. pauseTracking();
  566. const res = method.apply(this, args);
  567. resetTracking();
  568. return res;
  569. };
  570. });
  571. function createGetter(isReadonly = false, shallow = false) {
  572. return function get(target, key, receiver) {
  573. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  574. return !isReadonly;
  575. }
  576. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  577. return isReadonly;
  578. }
  579. else if (key === "__v_raw" /* RAW */ &&
  580. receiver === (isReadonly ? readonlyMap : reactiveMap).get(target)) {
  581. return target;
  582. }
  583. const targetIsArray = isArray(target);
  584. if (targetIsArray && hasOwn(arrayInstrumentations, key)) {
  585. return Reflect.get(arrayInstrumentations, key, receiver);
  586. }
  587. const res = Reflect.get(target, key, receiver);
  588. if (isSymbol(key)
  589. ? builtInSymbols.has(key)
  590. : key === `__proto__` || key === `__v_isRef`) {
  591. return res;
  592. }
  593. if (!isReadonly) {
  594. track(target, "get" /* GET */, key);
  595. }
  596. if (shallow) {
  597. return res;
  598. }
  599. if (isRef(res)) {
  600. // ref unwrapping - does not apply for Array + integer key.
  601. const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
  602. return shouldUnwrap ? res.value : res;
  603. }
  604. if (isObject(res)) {
  605. // Convert returned value into a proxy as well. we do the isObject check
  606. // here to avoid invalid value warning. Also need to lazy access readonly
  607. // and reactive here to avoid circular dependency.
  608. return isReadonly ? readonly(res) : reactive(res);
  609. }
  610. return res;
  611. };
  612. }
  613. const set = /*#__PURE__*/ createSetter();
  614. const shallowSet = /*#__PURE__*/ createSetter(true);
  615. function createSetter(shallow = false) {
  616. return function set(target, key, value, receiver) {
  617. const oldValue = target[key];
  618. if (!shallow) {
  619. value = toRaw(value);
  620. if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
  621. oldValue.value = value;
  622. return true;
  623. }
  624. }
  625. const hadKey = isArray(target) && isIntegerKey(key)
  626. ? Number(key) < target.length
  627. : hasOwn(target, key);
  628. const result = Reflect.set(target, key, value, receiver);
  629. // don't trigger if target is something up in the prototype chain of original
  630. if (target === toRaw(receiver)) {
  631. if (!hadKey) {
  632. trigger(target, "add" /* ADD */, key, value);
  633. }
  634. else if (hasChanged(value, oldValue)) {
  635. trigger(target, "set" /* SET */, key, value, oldValue);
  636. }
  637. }
  638. return result;
  639. };
  640. }
  641. function deleteProperty(target, key) {
  642. const hadKey = hasOwn(target, key);
  643. const oldValue = target[key];
  644. const result = Reflect.deleteProperty(target, key);
  645. if (result && hadKey) {
  646. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  647. }
  648. return result;
  649. }
  650. function has(target, key) {
  651. const result = Reflect.has(target, key);
  652. if (!isSymbol(key) || !builtInSymbols.has(key)) {
  653. track(target, "has" /* HAS */, key);
  654. }
  655. return result;
  656. }
  657. function ownKeys(target) {
  658. track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
  659. return Reflect.ownKeys(target);
  660. }
  661. const mutableHandlers = {
  662. get,
  663. set,
  664. deleteProperty,
  665. has,
  666. ownKeys
  667. };
  668. const readonlyHandlers = {
  669. get: readonlyGet,
  670. set(target, key) {
  671. {
  672. console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
  673. }
  674. return true;
  675. },
  676. deleteProperty(target, key) {
  677. {
  678. console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
  679. }
  680. return true;
  681. }
  682. };
  683. const shallowReactiveHandlers = extend({}, mutableHandlers, {
  684. get: shallowGet,
  685. set: shallowSet
  686. });
  687. // Props handlers are special in the sense that it should not unwrap top-level
  688. // refs (in order to allow refs to be explicitly passed down), but should
  689. // retain the reactivity of the normal readonly object.
  690. const shallowReadonlyHandlers = extend({}, readonlyHandlers, {
  691. get: shallowReadonlyGet
  692. });
  693. const toReactive = (value) => isObject(value) ? reactive(value) : value;
  694. const toReadonly = (value) => isObject(value) ? readonly(value) : value;
  695. const toShallow = (value) => value;
  696. const getProto = (v) => Reflect.getPrototypeOf(v);
  697. function get$1(target, key, isReadonly = false, isShallow = false) {
  698. // #1772: readonly(reactive(Map)) should return readonly + reactive version
  699. // of the value
  700. target = target["__v_raw" /* RAW */];
  701. const rawTarget = toRaw(target);
  702. const rawKey = toRaw(key);
  703. if (key !== rawKey) {
  704. !isReadonly && track(rawTarget, "get" /* GET */, key);
  705. }
  706. !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
  707. const { has } = getProto(rawTarget);
  708. const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
  709. if (has.call(rawTarget, key)) {
  710. return wrap(target.get(key));
  711. }
  712. else if (has.call(rawTarget, rawKey)) {
  713. return wrap(target.get(rawKey));
  714. }
  715. }
  716. function has$1(key, isReadonly = false) {
  717. const target = this["__v_raw" /* RAW */];
  718. const rawTarget = toRaw(target);
  719. const rawKey = toRaw(key);
  720. if (key !== rawKey) {
  721. !isReadonly && track(rawTarget, "has" /* HAS */, key);
  722. }
  723. !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
  724. return key === rawKey
  725. ? target.has(key)
  726. : target.has(key) || target.has(rawKey);
  727. }
  728. function size(target, isReadonly = false) {
  729. target = target["__v_raw" /* RAW */];
  730. !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
  731. return Reflect.get(target, 'size', target);
  732. }
  733. function add(value) {
  734. value = toRaw(value);
  735. const target = toRaw(this);
  736. const proto = getProto(target);
  737. const hadKey = proto.has.call(target, value);
  738. const result = target.add(value);
  739. if (!hadKey) {
  740. trigger(target, "add" /* ADD */, value, value);
  741. }
  742. return result;
  743. }
  744. function set$1(key, value) {
  745. value = toRaw(value);
  746. const target = toRaw(this);
  747. const { has, get } = getProto(target);
  748. let hadKey = has.call(target, key);
  749. if (!hadKey) {
  750. key = toRaw(key);
  751. hadKey = has.call(target, key);
  752. }
  753. else {
  754. checkIdentityKeys(target, has, key);
  755. }
  756. const oldValue = get.call(target, key);
  757. const result = target.set(key, value);
  758. if (!hadKey) {
  759. trigger(target, "add" /* ADD */, key, value);
  760. }
  761. else if (hasChanged(value, oldValue)) {
  762. trigger(target, "set" /* SET */, key, value, oldValue);
  763. }
  764. return result;
  765. }
  766. function deleteEntry(key) {
  767. const target = toRaw(this);
  768. const { has, get } = getProto(target);
  769. let hadKey = has.call(target, key);
  770. if (!hadKey) {
  771. key = toRaw(key);
  772. hadKey = has.call(target, key);
  773. }
  774. else {
  775. checkIdentityKeys(target, has, key);
  776. }
  777. const oldValue = get ? get.call(target, key) : undefined;
  778. // forward the operation before queueing reactions
  779. const result = target.delete(key);
  780. if (hadKey) {
  781. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  782. }
  783. return result;
  784. }
  785. function clear() {
  786. const target = toRaw(this);
  787. const hadItems = target.size !== 0;
  788. const oldTarget = isMap(target)
  789. ? new Map(target)
  790. : new Set(target)
  791. ;
  792. // forward the operation before queueing reactions
  793. const result = target.clear();
  794. if (hadItems) {
  795. trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
  796. }
  797. return result;
  798. }
  799. function createForEach(isReadonly, isShallow) {
  800. return function forEach(callback, thisArg) {
  801. const observed = this;
  802. const target = observed["__v_raw" /* RAW */];
  803. const rawTarget = toRaw(target);
  804. const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
  805. !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
  806. return target.forEach((value, key) => {
  807. // important: make sure the callback is
  808. // 1. invoked with the reactive map as `this` and 3rd arg
  809. // 2. the value received should be a corresponding reactive/readonly.
  810. return callback.call(thisArg, wrap(value), wrap(key), observed);
  811. });
  812. };
  813. }
  814. function createIterableMethod(method, isReadonly, isShallow) {
  815. return function (...args) {
  816. const target = this["__v_raw" /* RAW */];
  817. const rawTarget = toRaw(target);
  818. const targetIsMap = isMap(rawTarget);
  819. const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
  820. const isKeyOnly = method === 'keys' && targetIsMap;
  821. const innerIterator = target[method](...args);
  822. const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
  823. !isReadonly &&
  824. track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
  825. // return a wrapped iterator which returns observed versions of the
  826. // values emitted from the real iterator
  827. return {
  828. // iterator protocol
  829. next() {
  830. const { value, done } = innerIterator.next();
  831. return done
  832. ? { value, done }
  833. : {
  834. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  835. done
  836. };
  837. },
  838. // iterable protocol
  839. [Symbol.iterator]() {
  840. return this;
  841. }
  842. };
  843. };
  844. }
  845. function createReadonlyMethod(type) {
  846. return function (...args) {
  847. {
  848. const key = args[0] ? `on key "${args[0]}" ` : ``;
  849. console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
  850. }
  851. return type === "delete" /* DELETE */ ? false : this;
  852. };
  853. }
  854. const mutableInstrumentations = {
  855. get(key) {
  856. return get$1(this, key);
  857. },
  858. get size() {
  859. return size(this);
  860. },
  861. has: has$1,
  862. add,
  863. set: set$1,
  864. delete: deleteEntry,
  865. clear,
  866. forEach: createForEach(false, false)
  867. };
  868. const shallowInstrumentations = {
  869. get(key) {
  870. return get$1(this, key, false, true);
  871. },
  872. get size() {
  873. return size(this);
  874. },
  875. has: has$1,
  876. add,
  877. set: set$1,
  878. delete: deleteEntry,
  879. clear,
  880. forEach: createForEach(false, true)
  881. };
  882. const readonlyInstrumentations = {
  883. get(key) {
  884. return get$1(this, key, true);
  885. },
  886. get size() {
  887. return size(this, true);
  888. },
  889. has(key) {
  890. return has$1.call(this, key, true);
  891. },
  892. add: createReadonlyMethod("add" /* ADD */),
  893. set: createReadonlyMethod("set" /* SET */),
  894. delete: createReadonlyMethod("delete" /* DELETE */),
  895. clear: createReadonlyMethod("clear" /* CLEAR */),
  896. forEach: createForEach(true, false)
  897. };
  898. const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
  899. iteratorMethods.forEach(method => {
  900. mutableInstrumentations[method] = createIterableMethod(method, false, false);
  901. readonlyInstrumentations[method] = createIterableMethod(method, true, false);
  902. shallowInstrumentations[method] = createIterableMethod(method, false, true);
  903. });
  904. function createInstrumentationGetter(isReadonly, shallow) {
  905. const instrumentations = shallow
  906. ? shallowInstrumentations
  907. : isReadonly
  908. ? readonlyInstrumentations
  909. : mutableInstrumentations;
  910. return (target, key, receiver) => {
  911. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  912. return !isReadonly;
  913. }
  914. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  915. return isReadonly;
  916. }
  917. else if (key === "__v_raw" /* RAW */) {
  918. return target;
  919. }
  920. return Reflect.get(hasOwn(instrumentations, key) && key in target
  921. ? instrumentations
  922. : target, key, receiver);
  923. };
  924. }
  925. const mutableCollectionHandlers = {
  926. get: createInstrumentationGetter(false, false)
  927. };
  928. const shallowCollectionHandlers = {
  929. get: createInstrumentationGetter(false, true)
  930. };
  931. const readonlyCollectionHandlers = {
  932. get: createInstrumentationGetter(true, false)
  933. };
  934. function checkIdentityKeys(target, has, key) {
  935. const rawKey = toRaw(key);
  936. if (rawKey !== key && has.call(target, rawKey)) {
  937. const type = toRawType(target);
  938. console.warn(`Reactive ${type} contains both the raw and reactive ` +
  939. `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
  940. `which can lead to inconsistencies. ` +
  941. `Avoid differentiating between the raw and reactive versions ` +
  942. `of an object and only use the reactive version if possible.`);
  943. }
  944. }
  945. const reactiveMap = new WeakMap();
  946. const readonlyMap = new WeakMap();
  947. function targetTypeMap(rawType) {
  948. switch (rawType) {
  949. case 'Object':
  950. case 'Array':
  951. return 1 /* COMMON */;
  952. case 'Map':
  953. case 'Set':
  954. case 'WeakMap':
  955. case 'WeakSet':
  956. return 2 /* COLLECTION */;
  957. default:
  958. return 0 /* INVALID */;
  959. }
  960. }
  961. function getTargetType(value) {
  962. return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
  963. ? 0 /* INVALID */
  964. : targetTypeMap(toRawType(value));
  965. }
  966. function reactive(target) {
  967. // if trying to observe a readonly proxy, return the readonly version.
  968. if (target && target["__v_isReadonly" /* IS_READONLY */]) {
  969. return target;
  970. }
  971. return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers);
  972. }
  973. // Return a reactive-copy of the original object, where only the root level
  974. // properties are reactive, and does NOT unwrap refs nor recursively convert
  975. // returned properties.
  976. function shallowReactive(target) {
  977. return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers);
  978. }
  979. function readonly(target) {
  980. return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers);
  981. }
  982. // Return a reactive-copy of the original object, where only the root level
  983. // properties are readonly, and does NOT unwrap refs nor recursively convert
  984. // returned properties.
  985. // This is used for creating the props proxy object for stateful components.
  986. function shallowReadonly(target) {
  987. return createReactiveObject(target, true, shallowReadonlyHandlers, readonlyCollectionHandlers);
  988. }
  989. function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers) {
  990. if (!isObject(target)) {
  991. {
  992. console.warn(`value cannot be made reactive: ${String(target)}`);
  993. }
  994. return target;
  995. }
  996. // target is already a Proxy, return it.
  997. // exception: calling readonly() on a reactive object
  998. if (target["__v_raw" /* RAW */] &&
  999. !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
  1000. return target;
  1001. }
  1002. // target already has corresponding Proxy
  1003. const proxyMap = isReadonly ? readonlyMap : reactiveMap;
  1004. const existingProxy = proxyMap.get(target);
  1005. if (existingProxy) {
  1006. return existingProxy;
  1007. }
  1008. // only a whitelist of value types can be observed.
  1009. const targetType = getTargetType(target);
  1010. if (targetType === 0 /* INVALID */) {
  1011. return target;
  1012. }
  1013. const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
  1014. proxyMap.set(target, proxy);
  1015. return proxy;
  1016. }
  1017. function isReactive(value) {
  1018. if (isReadonly(value)) {
  1019. return isReactive(value["__v_raw" /* RAW */]);
  1020. }
  1021. return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
  1022. }
  1023. function isReadonly(value) {
  1024. return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
  1025. }
  1026. function isProxy(value) {
  1027. return isReactive(value) || isReadonly(value);
  1028. }
  1029. function toRaw(observed) {
  1030. return ((observed && toRaw(observed["__v_raw" /* RAW */])) || observed);
  1031. }
  1032. function markRaw(value) {
  1033. def(value, "__v_skip" /* SKIP */, true);
  1034. return value;
  1035. }
  1036. const convert = (val) => isObject(val) ? reactive(val) : val;
  1037. function isRef(r) {
  1038. return Boolean(r && r.__v_isRef === true);
  1039. }
  1040. function ref(value) {
  1041. return createRef(value);
  1042. }
  1043. function shallowRef(value) {
  1044. return createRef(value, true);
  1045. }
  1046. class RefImpl {
  1047. constructor(_rawValue, _shallow = false) {
  1048. this._rawValue = _rawValue;
  1049. this._shallow = _shallow;
  1050. this.__v_isRef = true;
  1051. this._value = _shallow ? _rawValue : convert(_rawValue);
  1052. }
  1053. get value() {
  1054. track(toRaw(this), "get" /* GET */, 'value');
  1055. return this._value;
  1056. }
  1057. set value(newVal) {
  1058. if (hasChanged(toRaw(newVal), this._rawValue)) {
  1059. this._rawValue = newVal;
  1060. this._value = this._shallow ? newVal : convert(newVal);
  1061. trigger(toRaw(this), "set" /* SET */, 'value', newVal);
  1062. }
  1063. }
  1064. }
  1065. function createRef(rawValue, shallow = false) {
  1066. if (isRef(rawValue)) {
  1067. return rawValue;
  1068. }
  1069. return new RefImpl(rawValue, shallow);
  1070. }
  1071. function triggerRef(ref) {
  1072. trigger(toRaw(ref), "set" /* SET */, 'value', ref.value );
  1073. }
  1074. function unref(ref) {
  1075. return isRef(ref) ? ref.value : ref;
  1076. }
  1077. const shallowUnwrapHandlers = {
  1078. get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  1079. set: (target, key, value, receiver) => {
  1080. const oldValue = target[key];
  1081. if (isRef(oldValue) && !isRef(value)) {
  1082. oldValue.value = value;
  1083. return true;
  1084. }
  1085. else {
  1086. return Reflect.set(target, key, value, receiver);
  1087. }
  1088. }
  1089. };
  1090. function proxyRefs(objectWithRefs) {
  1091. return isReactive(objectWithRefs)
  1092. ? objectWithRefs
  1093. : new Proxy(objectWithRefs, shallowUnwrapHandlers);
  1094. }
  1095. class CustomRefImpl {
  1096. constructor(factory) {
  1097. this.__v_isRef = true;
  1098. const { get, set } = factory(() => track(this, "get" /* GET */, 'value'), () => trigger(this, "set" /* SET */, 'value'));
  1099. this._get = get;
  1100. this._set = set;
  1101. }
  1102. get value() {
  1103. return this._get();
  1104. }
  1105. set value(newVal) {
  1106. this._set(newVal);
  1107. }
  1108. }
  1109. function customRef(factory) {
  1110. return new CustomRefImpl(factory);
  1111. }
  1112. function toRefs(object) {
  1113. if ( !isProxy(object)) {
  1114. console.warn(`toRefs() expects a reactive object but received a plain one.`);
  1115. }
  1116. const ret = isArray(object) ? new Array(object.length) : {};
  1117. for (const key in object) {
  1118. ret[key] = toRef(object, key);
  1119. }
  1120. return ret;
  1121. }
  1122. class ObjectRefImpl {
  1123. constructor(_object, _key) {
  1124. this._object = _object;
  1125. this._key = _key;
  1126. this.__v_isRef = true;
  1127. }
  1128. get value() {
  1129. return this._object[this._key];
  1130. }
  1131. set value(newVal) {
  1132. this._object[this._key] = newVal;
  1133. }
  1134. }
  1135. function toRef(object, key) {
  1136. return isRef(object[key])
  1137. ? object[key]
  1138. : new ObjectRefImpl(object, key);
  1139. }
  1140. class ComputedRefImpl {
  1141. constructor(getter, _setter, isReadonly) {
  1142. this._setter = _setter;
  1143. this._dirty = true;
  1144. this.__v_isRef = true;
  1145. this.effect = effect(getter, {
  1146. lazy: true,
  1147. scheduler: () => {
  1148. if (!this._dirty) {
  1149. this._dirty = true;
  1150. trigger(toRaw(this), "set" /* SET */, 'value');
  1151. }
  1152. }
  1153. });
  1154. this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
  1155. }
  1156. get value() {
  1157. if (this._dirty) {
  1158. this._value = this.effect();
  1159. this._dirty = false;
  1160. }
  1161. track(toRaw(this), "get" /* GET */, 'value');
  1162. return this._value;
  1163. }
  1164. set value(newValue) {
  1165. this._setter(newValue);
  1166. }
  1167. }
  1168. function computed(getterOrOptions) {
  1169. let getter;
  1170. let setter;
  1171. if (isFunction(getterOrOptions)) {
  1172. getter = getterOrOptions;
  1173. setter = () => {
  1174. console.warn('Write operation failed: computed value is readonly');
  1175. }
  1176. ;
  1177. }
  1178. else {
  1179. getter = getterOrOptions.get;
  1180. setter = getterOrOptions.set;
  1181. }
  1182. return new ComputedRefImpl(getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set);
  1183. }
  1184. const stack = [];
  1185. function pushWarningContext(vnode) {
  1186. stack.push(vnode);
  1187. }
  1188. function popWarningContext() {
  1189. stack.pop();
  1190. }
  1191. function warn(msg, ...args) {
  1192. // avoid props formatting or warn handler tracking deps that might be mutated
  1193. // during patch, leading to infinite recursion.
  1194. pauseTracking();
  1195. const instance = stack.length ? stack[stack.length - 1].component : null;
  1196. const appWarnHandler = instance && instance.appContext.config.warnHandler;
  1197. const trace = getComponentTrace();
  1198. if (appWarnHandler) {
  1199. callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
  1200. msg + args.join(''),
  1201. instance && instance.proxy,
  1202. trace
  1203. .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
  1204. .join('\n'),
  1205. trace
  1206. ]);
  1207. }
  1208. else {
  1209. const warnArgs = [`[Vue warn]: ${msg}`, ...args];
  1210. /* istanbul ignore if */
  1211. if (trace.length &&
  1212. // avoid spamming console during tests
  1213. !false) {
  1214. warnArgs.push(`\n`, ...formatTrace(trace));
  1215. }
  1216. console.warn(...warnArgs);
  1217. }
  1218. resetTracking();
  1219. }
  1220. function getComponentTrace() {
  1221. let currentVNode = stack[stack.length - 1];
  1222. if (!currentVNode) {
  1223. return [];
  1224. }
  1225. // we can't just use the stack because it will be incomplete during updates
  1226. // that did not start from the root. Re-construct the parent chain using
  1227. // instance parent pointers.
  1228. const normalizedStack = [];
  1229. while (currentVNode) {
  1230. const last = normalizedStack[0];
  1231. if (last && last.vnode === currentVNode) {
  1232. last.recurseCount++;
  1233. }
  1234. else {
  1235. normalizedStack.push({
  1236. vnode: currentVNode,
  1237. recurseCount: 0
  1238. });
  1239. }
  1240. const parentInstance = currentVNode.component && currentVNode.component.parent;
  1241. currentVNode = parentInstance && parentInstance.vnode;
  1242. }
  1243. return normalizedStack;
  1244. }
  1245. /* istanbul ignore next */
  1246. function formatTrace(trace) {
  1247. const logs = [];
  1248. trace.forEach((entry, i) => {
  1249. logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
  1250. });
  1251. return logs;
  1252. }
  1253. function formatTraceEntry({ vnode, recurseCount }) {
  1254. const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
  1255. const isRoot = vnode.component ? vnode.component.parent == null : false;
  1256. const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
  1257. const close = `>` + postfix;
  1258. return vnode.props
  1259. ? [open, ...formatProps(vnode.props), close]
  1260. : [open + close];
  1261. }
  1262. /* istanbul ignore next */
  1263. function formatProps(props) {
  1264. const res = [];
  1265. const keys = Object.keys(props);
  1266. keys.slice(0, 3).forEach(key => {
  1267. res.push(...formatProp(key, props[key]));
  1268. });
  1269. if (keys.length > 3) {
  1270. res.push(` ...`);
  1271. }
  1272. return res;
  1273. }
  1274. /* istanbul ignore next */
  1275. function formatProp(key, value, raw) {
  1276. if (isString(value)) {
  1277. value = JSON.stringify(value);
  1278. return raw ? value : [`${key}=${value}`];
  1279. }
  1280. else if (typeof value === 'number' ||
  1281. typeof value === 'boolean' ||
  1282. value == null) {
  1283. return raw ? value : [`${key}=${value}`];
  1284. }
  1285. else if (isRef(value)) {
  1286. value = formatProp(key, toRaw(value.value), true);
  1287. return raw ? value : [`${key}=Ref<`, value, `>`];
  1288. }
  1289. else if (isFunction(value)) {
  1290. return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
  1291. }
  1292. else {
  1293. value = toRaw(value);
  1294. return raw ? value : [`${key}=`, value];
  1295. }
  1296. }
  1297. const ErrorTypeStrings = {
  1298. ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
  1299. ["c" /* CREATED */]: 'created hook',
  1300. ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
  1301. ["m" /* MOUNTED */]: 'mounted hook',
  1302. ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
  1303. ["u" /* UPDATED */]: 'updated',
  1304. ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
  1305. ["um" /* UNMOUNTED */]: 'unmounted hook',
  1306. ["a" /* ACTIVATED */]: 'activated hook',
  1307. ["da" /* DEACTIVATED */]: 'deactivated hook',
  1308. ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
  1309. ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
  1310. ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
  1311. [0 /* SETUP_FUNCTION */]: 'setup function',
  1312. [1 /* RENDER_FUNCTION */]: 'render function',
  1313. [2 /* WATCH_GETTER */]: 'watcher getter',
  1314. [3 /* WATCH_CALLBACK */]: 'watcher callback',
  1315. [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
  1316. [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
  1317. [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
  1318. [7 /* VNODE_HOOK */]: 'vnode hook',
  1319. [8 /* DIRECTIVE_HOOK */]: 'directive hook',
  1320. [9 /* TRANSITION_HOOK */]: 'transition hook',
  1321. [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
  1322. [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
  1323. [12 /* FUNCTION_REF */]: 'ref function',
  1324. [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
  1325. [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
  1326. 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
  1327. };
  1328. function callWithErrorHandling(fn, instance, type, args) {
  1329. let res;
  1330. try {
  1331. res = args ? fn(...args) : fn();
  1332. }
  1333. catch (err) {
  1334. handleError(err, instance, type);
  1335. }
  1336. return res;
  1337. }
  1338. function callWithAsyncErrorHandling(fn, instance, type, args) {
  1339. if (isFunction(fn)) {
  1340. const res = callWithErrorHandling(fn, instance, type, args);
  1341. if (res && isPromise(res)) {
  1342. res.catch(err => {
  1343. handleError(err, instance, type);
  1344. });
  1345. }
  1346. return res;
  1347. }
  1348. const values = [];
  1349. for (let i = 0; i < fn.length; i++) {
  1350. values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
  1351. }
  1352. return values;
  1353. }
  1354. function handleError(err, instance, type, throwInDev = true) {
  1355. const contextVNode = instance ? instance.vnode : null;
  1356. if (instance) {
  1357. let cur = instance.parent;
  1358. // the exposed instance is the render proxy to keep it consistent with 2.x
  1359. const exposedInstance = instance.proxy;
  1360. // in production the hook receives only the error code
  1361. const errorInfo = ErrorTypeStrings[type] ;
  1362. while (cur) {
  1363. const errorCapturedHooks = cur.ec;
  1364. if (errorCapturedHooks) {
  1365. for (let i = 0; i < errorCapturedHooks.length; i++) {
  1366. if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
  1367. return;
  1368. }
  1369. }
  1370. }
  1371. cur = cur.parent;
  1372. }
  1373. // app-level handling
  1374. const appErrorHandler = instance.appContext.config.errorHandler;
  1375. if (appErrorHandler) {
  1376. callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
  1377. return;
  1378. }
  1379. }
  1380. logError(err, type, contextVNode, throwInDev);
  1381. }
  1382. function logError(err, type, contextVNode, throwInDev = true) {
  1383. {
  1384. const info = ErrorTypeStrings[type];
  1385. if (contextVNode) {
  1386. pushWarningContext(contextVNode);
  1387. }
  1388. warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
  1389. if (contextVNode) {
  1390. popWarningContext();
  1391. }
  1392. // crash in dev by default so it's more noticeable
  1393. if (throwInDev) {
  1394. throw err;
  1395. }
  1396. else {
  1397. console.error(err);
  1398. }
  1399. }
  1400. }
  1401. let isFlushing = false;
  1402. let isFlushPending = false;
  1403. const queue = [];
  1404. let flushIndex = 0;
  1405. const pendingPreFlushCbs = [];
  1406. let activePreFlushCbs = null;
  1407. let preFlushIndex = 0;
  1408. const pendingPostFlushCbs = [];
  1409. let activePostFlushCbs = null;
  1410. let postFlushIndex = 0;
  1411. const resolvedPromise = Promise.resolve();
  1412. let currentFlushPromise = null;
  1413. let currentPreFlushParentJob = null;
  1414. const RECURSION_LIMIT = 100;
  1415. function nextTick(fn) {
  1416. const p = currentFlushPromise || resolvedPromise;
  1417. return fn ? p.then(this ? fn.bind(this) : fn) : p;
  1418. }
  1419. function queueJob(job) {
  1420. // the dedupe search uses the startIndex argument of Array.includes()
  1421. // by default the search index includes the current job that is being run
  1422. // so it cannot recursively trigger itself again.
  1423. // if the job is a watch() callback, the search will start with a +1 index to
  1424. // allow it recursively trigger itself - it is the user's responsibility to
  1425. // ensure it doesn't end up in an infinite loop.
  1426. if ((!queue.length ||
  1427. !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
  1428. job !== currentPreFlushParentJob) {
  1429. queue.push(job);
  1430. queueFlush();
  1431. }
  1432. }
  1433. function queueFlush() {
  1434. if (!isFlushing && !isFlushPending) {
  1435. isFlushPending = true;
  1436. currentFlushPromise = resolvedPromise.then(flushJobs);
  1437. }
  1438. }
  1439. function invalidateJob(job) {
  1440. const i = queue.indexOf(job);
  1441. if (i > -1) {
  1442. queue[i] = null;
  1443. }
  1444. }
  1445. function queueCb(cb, activeQueue, pendingQueue, index) {
  1446. if (!isArray(cb)) {
  1447. if (!activeQueue ||
  1448. !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
  1449. pendingQueue.push(cb);
  1450. }
  1451. }
  1452. else {
  1453. // if cb is an array, it is a component lifecycle hook which can only be
  1454. // triggered by a job, which is already deduped in the main queue, so
  1455. // we can skip duplicate check here to improve perf
  1456. pendingQueue.push(...cb);
  1457. }
  1458. queueFlush();
  1459. }
  1460. function queuePreFlushCb(cb) {
  1461. queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
  1462. }
  1463. function queuePostFlushCb(cb) {
  1464. queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
  1465. }
  1466. function flushPreFlushCbs(seen, parentJob = null) {
  1467. if (pendingPreFlushCbs.length) {
  1468. currentPreFlushParentJob = parentJob;
  1469. activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
  1470. pendingPreFlushCbs.length = 0;
  1471. {
  1472. seen = seen || new Map();
  1473. }
  1474. for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
  1475. {
  1476. checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex]);
  1477. }
  1478. activePreFlushCbs[preFlushIndex]();
  1479. }
  1480. activePreFlushCbs = null;
  1481. preFlushIndex = 0;
  1482. currentPreFlushParentJob = null;
  1483. // recursively flush until it drains
  1484. flushPreFlushCbs(seen, parentJob);
  1485. }
  1486. }
  1487. function flushPostFlushCbs(seen) {
  1488. if (pendingPostFlushCbs.length) {
  1489. const deduped = [...new Set(pendingPostFlushCbs)];
  1490. pendingPostFlushCbs.length = 0;
  1491. // #1947 already has active queue, nested flushPostFlushCbs call
  1492. if (activePostFlushCbs) {
  1493. activePostFlushCbs.push(...deduped);
  1494. return;
  1495. }
  1496. activePostFlushCbs = deduped;
  1497. {
  1498. seen = seen || new Map();
  1499. }
  1500. activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
  1501. for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
  1502. {
  1503. checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex]);
  1504. }
  1505. activePostFlushCbs[postFlushIndex]();
  1506. }
  1507. activePostFlushCbs = null;
  1508. postFlushIndex = 0;
  1509. }
  1510. }
  1511. const getId = (job) => job.id == null ? Infinity : job.id;
  1512. function flushJobs(seen) {
  1513. isFlushPending = false;
  1514. isFlushing = true;
  1515. {
  1516. seen = seen || new Map();
  1517. }
  1518. flushPreFlushCbs(seen);
  1519. // Sort queue before flush.
  1520. // This ensures that:
  1521. // 1. Components are updated from parent to child. (because parent is always
  1522. // created before the child so its render effect will have smaller
  1523. // priority number)
  1524. // 2. If a component is unmounted during a parent component's update,
  1525. // its update can be skipped.
  1526. // Jobs can never be null before flush starts, since they are only invalidated
  1527. // during execution of another flushed job.
  1528. queue.sort((a, b) => getId(a) - getId(b));
  1529. try {
  1530. for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
  1531. const job = queue[flushIndex];
  1532. if (job) {
  1533. if (true) {
  1534. checkRecursiveUpdates(seen, job);
  1535. }
  1536. callWithErrorHandling(job, null, 14 /* SCHEDULER */);
  1537. }
  1538. }
  1539. }
  1540. finally {
  1541. flushIndex = 0;
  1542. queue.length = 0;
  1543. flushPostFlushCbs(seen);
  1544. isFlushing = false;
  1545. currentFlushPromise = null;
  1546. // some postFlushCb queued jobs!
  1547. // keep flushing until it drains.
  1548. if (queue.length || pendingPostFlushCbs.length) {
  1549. flushJobs(seen);
  1550. }
  1551. }
  1552. }
  1553. function checkRecursiveUpdates(seen, fn) {
  1554. if (!seen.has(fn)) {
  1555. seen.set(fn, 1);
  1556. }
  1557. else {
  1558. const count = seen.get(fn);
  1559. if (count > RECURSION_LIMIT) {
  1560. throw new Error(`Maximum recursive updates exceeded. ` +
  1561. `This means you have a reactive effect that is mutating its own ` +
  1562. `dependencies and thus recursively triggering itself. Possible sources ` +
  1563. `include component template, render function, updated hook or ` +
  1564. `watcher source function.`);
  1565. }
  1566. else {
  1567. seen.set(fn, count + 1);
  1568. }
  1569. }
  1570. }
  1571. /* eslint-disable no-restricted-globals */
  1572. let isHmrUpdating = false;
  1573. const hmrDirtyComponents = new Set();
  1574. // Expose the HMR runtime on the global object
  1575. // This makes it entirely tree-shakable without polluting the exports and makes
  1576. // it easier to be used in toolings like vue-loader
  1577. // Note: for a component to be eligible for HMR it also needs the __hmrId option
  1578. // to be set so that its instances can be registered / removed.
  1579. {
  1580. const globalObject = typeof global !== 'undefined'
  1581. ? global
  1582. : typeof self !== 'undefined'
  1583. ? self
  1584. : typeof window !== 'undefined'
  1585. ? window
  1586. : {};
  1587. globalObject.__VUE_HMR_RUNTIME__ = {
  1588. createRecord: tryWrap(createRecord),
  1589. rerender: tryWrap(rerender),
  1590. reload: tryWrap(reload)
  1591. };
  1592. }
  1593. const map = new Map();
  1594. function registerHMR(instance) {
  1595. const id = instance.type.__hmrId;
  1596. let record = map.get(id);
  1597. if (!record) {
  1598. createRecord(id);
  1599. record = map.get(id);
  1600. }
  1601. record.add(instance);
  1602. }
  1603. function unregisterHMR(instance) {
  1604. map.get(instance.type.__hmrId).delete(instance);
  1605. }
  1606. function createRecord(id) {
  1607. if (map.has(id)) {
  1608. return false;
  1609. }
  1610. map.set(id, new Set());
  1611. return true;
  1612. }
  1613. function rerender(id, newRender) {
  1614. const record = map.get(id);
  1615. if (!record)
  1616. return;
  1617. // Array.from creates a snapshot which avoids the set being mutated during
  1618. // updates
  1619. Array.from(record).forEach(instance => {
  1620. if (newRender) {
  1621. instance.render = newRender;
  1622. }
  1623. instance.renderCache = [];
  1624. // this flag forces child components with slot content to update
  1625. isHmrUpdating = true;
  1626. instance.update();
  1627. isHmrUpdating = false;
  1628. });
  1629. }
  1630. function reload(id, newComp) {
  1631. const record = map.get(id);
  1632. if (!record)
  1633. return;
  1634. // Array.from creates a snapshot which avoids the set being mutated during
  1635. // updates
  1636. Array.from(record).forEach(instance => {
  1637. const comp = instance.type;
  1638. if (!hmrDirtyComponents.has(comp)) {
  1639. // 1. Update existing comp definition to match new one
  1640. newComp = isClassComponent(newComp) ? newComp.__vccOpts : newComp;
  1641. extend(comp, newComp);
  1642. for (const key in comp) {
  1643. if (!(key in newComp)) {
  1644. delete comp[key];
  1645. }
  1646. }
  1647. // 2. Mark component dirty. This forces the renderer to replace the component
  1648. // on patch.
  1649. hmrDirtyComponents.add(comp);
  1650. // 3. Make sure to unmark the component after the reload.
  1651. queuePostFlushCb(() => {
  1652. hmrDirtyComponents.delete(comp);
  1653. });
  1654. }
  1655. if (instance.parent) {
  1656. // 4. Force the parent instance to re-render. This will cause all updated
  1657. // components to be unmounted and re-mounted. Queue the update so that we
  1658. // don't end up forcing the same parent to re-render multiple times.
  1659. queueJob(instance.parent.update);
  1660. }
  1661. else if (instance.appContext.reload) {
  1662. // root instance mounted via createApp() has a reload method
  1663. instance.appContext.reload();
  1664. }
  1665. else if (typeof window !== 'undefined') {
  1666. // root instance inside tree created via raw render(). Force reload.
  1667. window.location.reload();
  1668. }
  1669. else {
  1670. console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
  1671. }
  1672. });
  1673. }
  1674. function tryWrap(fn) {
  1675. return (id, arg) => {
  1676. try {
  1677. return fn(id, arg);
  1678. }
  1679. catch (e) {
  1680. console.error(e);
  1681. console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
  1682. `Full reload required.`);
  1683. }
  1684. };
  1685. }
  1686. let devtools;
  1687. function setDevtoolsHook(hook) {
  1688. devtools = hook;
  1689. }
  1690. function devtoolsInitApp(app, version) {
  1691. // TODO queue if devtools is undefined
  1692. if (!devtools)
  1693. return;
  1694. devtools.emit("app:init" /* APP_INIT */, app, version, {
  1695. Fragment,
  1696. Text,
  1697. Comment,
  1698. Static
  1699. });
  1700. }
  1701. function devtoolsUnmountApp(app) {
  1702. if (!devtools)
  1703. return;
  1704. devtools.emit("app:unmount" /* APP_UNMOUNT */, app);
  1705. }
  1706. const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
  1707. const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
  1708. const devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
  1709. function createDevtoolsComponentHook(hook) {
  1710. return (component) => {
  1711. if (!devtools)
  1712. return;
  1713. devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined);
  1714. };
  1715. }
  1716. function devtoolsComponentEmit(component, event, params) {
  1717. if (!devtools)
  1718. return;
  1719. devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
  1720. }
  1721. function emit(instance, event, ...rawArgs) {
  1722. const props = instance.vnode.props || EMPTY_OBJ;
  1723. {
  1724. const { emitsOptions, propsOptions: [propsOptions] } = instance;
  1725. if (emitsOptions) {
  1726. if (!(event in emitsOptions)) {
  1727. if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
  1728. warn(`Component emitted event "${event}" but it is neither declared in ` +
  1729. `the emits option nor as an "${toHandlerKey(event)}" prop.`);
  1730. }
  1731. }
  1732. else {
  1733. const validator = emitsOptions[event];
  1734. if (isFunction(validator)) {
  1735. const isValid = validator(...rawArgs);
  1736. if (!isValid) {
  1737. warn(`Invalid event arguments: event validation failed for event "${event}".`);
  1738. }
  1739. }
  1740. }
  1741. }
  1742. }
  1743. let args = rawArgs;
  1744. const isModelListener = event.startsWith('update:');
  1745. // for v-model update:xxx events, apply modifiers on args
  1746. const modelArg = isModelListener && event.slice(7);
  1747. if (modelArg && modelArg in props) {
  1748. const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
  1749. const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
  1750. if (trim) {
  1751. args = rawArgs.map(a => a.trim());
  1752. }
  1753. else if (number) {
  1754. args = rawArgs.map(toNumber);
  1755. }
  1756. }
  1757. {
  1758. devtoolsComponentEmit(instance, event, args);
  1759. }
  1760. {
  1761. const lowerCaseEvent = event.toLowerCase();
  1762. if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
  1763. warn(`Event "${lowerCaseEvent}" is emitted in component ` +
  1764. `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
  1765. `Note that HTML attributes are case-insensitive and you cannot use ` +
  1766. `v-on to listen to camelCase events when using in-DOM templates. ` +
  1767. `You should probably use "${hyphenate(event)}" instead of "${event}".`);
  1768. }
  1769. }
  1770. // convert handler name to camelCase. See issue #2249
  1771. let handlerName = toHandlerKey(camelize(event));
  1772. let handler = props[handlerName];
  1773. // for v-model update:xxx events, also trigger kebab-case equivalent
  1774. // for props passed via kebab-case
  1775. if (!handler && isModelListener) {
  1776. handlerName = toHandlerKey(hyphenate(event));
  1777. handler = props[handlerName];
  1778. }
  1779. if (handler) {
  1780. callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
  1781. }
  1782. const onceHandler = props[handlerName + `Once`];
  1783. if (onceHandler) {
  1784. if (!instance.emitted) {
  1785. (instance.emitted = {})[handlerName] = true;
  1786. }
  1787. else if (instance.emitted[handlerName]) {
  1788. return;
  1789. }
  1790. callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
  1791. }
  1792. }
  1793. function normalizeEmitsOptions(comp, appContext, asMixin = false) {
  1794. if (!appContext.deopt && comp.__emits !== undefined) {
  1795. return comp.__emits;
  1796. }
  1797. const raw = comp.emits;
  1798. let normalized = {};
  1799. // apply mixin/extends props
  1800. let hasExtends = false;
  1801. if ( !isFunction(comp)) {
  1802. const extendEmits = (raw) => {
  1803. hasExtends = true;
  1804. extend(normalized, normalizeEmitsOptions(raw, appContext, true));
  1805. };
  1806. if (!asMixin && appContext.mixins.length) {
  1807. appContext.mixins.forEach(extendEmits);
  1808. }
  1809. if (comp.extends) {
  1810. extendEmits(comp.extends);
  1811. }
  1812. if (comp.mixins) {
  1813. comp.mixins.forEach(extendEmits);
  1814. }
  1815. }
  1816. if (!raw && !hasExtends) {
  1817. return (comp.__emits = null);
  1818. }
  1819. if (isArray(raw)) {
  1820. raw.forEach(key => (normalized[key] = null));
  1821. }
  1822. else {
  1823. extend(normalized, raw);
  1824. }
  1825. return (comp.__emits = normalized);
  1826. }
  1827. // Check if an incoming prop key is a declared emit event listener.
  1828. // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
  1829. // both considered matched listeners.
  1830. function isEmitListener(options, key) {
  1831. if (!options || !isOn(key)) {
  1832. return false;
  1833. }
  1834. key = key.replace(/Once$/, '');
  1835. return (hasOwn(options, key[2].toLowerCase() + key.slice(3)) ||
  1836. hasOwn(options, key.slice(2)));
  1837. }
  1838. // mark the current rendering instance for asset resolution (e.g.
  1839. // resolveComponent, resolveDirective) during render
  1840. let currentRenderingInstance = null;
  1841. function setCurrentRenderingInstance(instance) {
  1842. currentRenderingInstance = instance;
  1843. }
  1844. // dev only flag to track whether $attrs was used during render.
  1845. // If $attrs was used during render then the warning for failed attrs
  1846. // fallthrough can be suppressed.
  1847. let accessedAttrs = false;
  1848. function markAttrsAccessed() {
  1849. accessedAttrs = true;
  1850. }
  1851. function renderComponentRoot(instance) {
  1852. const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx } = instance;
  1853. let result;
  1854. currentRenderingInstance = instance;
  1855. {
  1856. accessedAttrs = false;
  1857. }
  1858. try {
  1859. let fallthroughAttrs;
  1860. if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
  1861. // withProxy is a proxy with a different `has` trap only for
  1862. // runtime-compiled render functions using `with` block.
  1863. const proxyToUse = withProxy || proxy;
  1864. result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
  1865. fallthroughAttrs = attrs;
  1866. }
  1867. else {
  1868. // functional
  1869. const render = Component;
  1870. // in dev, mark attrs accessed if optional props (attrs === props)
  1871. if (true && attrs === props) {
  1872. markAttrsAccessed();
  1873. }
  1874. result = normalizeVNode(render.length > 1
  1875. ? render(props, true
  1876. ? {
  1877. get attrs() {
  1878. markAttrsAccessed();
  1879. return attrs;
  1880. },
  1881. slots,
  1882. emit
  1883. }
  1884. : { attrs, slots, emit })
  1885. : render(props, null /* we know it doesn't need it */));
  1886. fallthroughAttrs = Component.props
  1887. ? attrs
  1888. : getFunctionalFallthrough(attrs);
  1889. }
  1890. // attr merging
  1891. // in dev mode, comments are preserved, and it's possible for a template
  1892. // to have comments along side the root element which makes it a fragment
  1893. let root = result;
  1894. let setRoot = undefined;
  1895. if (true) {
  1896. ;
  1897. [root, setRoot] = getChildRoot(result);
  1898. }
  1899. if (Component.inheritAttrs !== false && fallthroughAttrs) {
  1900. const keys = Object.keys(fallthroughAttrs);
  1901. const { shapeFlag } = root;
  1902. if (keys.length) {
  1903. if (shapeFlag & 1 /* ELEMENT */ ||
  1904. shapeFlag & 6 /* COMPONENT */) {
  1905. if (propsOptions && keys.some(isModelListener)) {
  1906. // If a v-model listener (onUpdate:xxx) has a corresponding declared
  1907. // prop, it indicates this component expects to handle v-model and
  1908. // it should not fallthrough.
  1909. // related: #1543, #1643, #1989
  1910. fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
  1911. }
  1912. root = cloneVNode(root, fallthroughAttrs);
  1913. }
  1914. else if (true && !accessedAttrs && root.type !== Comment) {
  1915. const allAttrs = Object.keys(attrs);
  1916. const eventAttrs = [];
  1917. const extraAttrs = [];
  1918. for (let i = 0, l = allAttrs.length; i < l; i++) {
  1919. const key = allAttrs[i];
  1920. if (isOn(key)) {
  1921. // ignore v-model handlers when they fail to fallthrough
  1922. if (!isModelListener(key)) {
  1923. // remove `on`, lowercase first letter to reflect event casing
  1924. // accurately
  1925. eventAttrs.push(key[2].toLowerCase() + key.slice(3));
  1926. }
  1927. }
  1928. else {
  1929. extraAttrs.push(key);
  1930. }
  1931. }
  1932. if (extraAttrs.length) {
  1933. warn(`Extraneous non-props attributes (` +
  1934. `${extraAttrs.join(', ')}) ` +
  1935. `were passed to component but could not be automatically inherited ` +
  1936. `because component renders fragment or text root nodes.`);
  1937. }
  1938. if (eventAttrs.length) {
  1939. warn(`Extraneous non-emits event listeners (` +
  1940. `${eventAttrs.join(', ')}) ` +
  1941. `were passed to component but could not be automatically inherited ` +
  1942. `because component renders fragment or text root nodes. ` +
  1943. `If the listener is intended to be a component custom event listener only, ` +
  1944. `declare it using the "emits" option.`);
  1945. }
  1946. }
  1947. }
  1948. }
  1949. // inherit directives
  1950. if (vnode.dirs) {
  1951. if (true && !isElementRoot(root)) {
  1952. warn(`Runtime directive used on component with non-element root node. ` +
  1953. `The directives will not function as intended.`);
  1954. }
  1955. root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
  1956. }
  1957. // inherit transition data
  1958. if (vnode.transition) {
  1959. if (true && !isElementRoot(root)) {
  1960. warn(`Component inside <Transition> renders non-element root node ` +
  1961. `that cannot be animated.`);
  1962. }
  1963. root.transition = vnode.transition;
  1964. }
  1965. if (true && setRoot) {
  1966. setRoot(root);
  1967. }
  1968. else {
  1969. result = root;
  1970. }
  1971. }
  1972. catch (err) {
  1973. handleError(err, instance, 1 /* RENDER_FUNCTION */);
  1974. result = createVNode(Comment);
  1975. }
  1976. currentRenderingInstance = null;
  1977. return result;
  1978. }
  1979. /**
  1980. * dev only
  1981. * In dev mode, template root level comments are rendered, which turns the
  1982. * template into a fragment root, but we need to locate the single element
  1983. * root for attrs and scope id processing.
  1984. */
  1985. const getChildRoot = (vnode) => {
  1986. if (vnode.type !== Fragment) {
  1987. return [vnode, undefined];
  1988. }
  1989. const rawChildren = vnode.children;
  1990. const dynamicChildren = vnode.dynamicChildren;
  1991. const childRoot = filterSingleRoot(rawChildren);
  1992. if (!childRoot) {
  1993. return [vnode, undefined];
  1994. }
  1995. const index = rawChildren.indexOf(childRoot);
  1996. const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
  1997. const setRoot = (updatedRoot) => {
  1998. rawChildren[index] = updatedRoot;
  1999. if (dynamicChildren) {
  2000. if (dynamicIndex > -1) {
  2001. dynamicChildren[dynamicIndex] = updatedRoot;
  2002. }
  2003. else if (updatedRoot.patchFlag > 0) {
  2004. vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
  2005. }
  2006. }
  2007. };
  2008. return [normalizeVNode(childRoot), setRoot];
  2009. };
  2010. /**
  2011. * dev only
  2012. */
  2013. function filterSingleRoot(children) {
  2014. const filtered = children.filter(child => {
  2015. return !(isVNode(child) &&
  2016. child.type === Comment &&
  2017. child.children !== 'v-if');
  2018. });
  2019. return filtered.length === 1 && isVNode(filtered[0]) ? filtered[0] : null;
  2020. }
  2021. const getFunctionalFallthrough = (attrs) => {
  2022. let res;
  2023. for (const key in attrs) {
  2024. if (key === 'class' || key === 'style' || isOn(key)) {
  2025. (res || (res = {}))[key] = attrs[key];
  2026. }
  2027. }
  2028. return res;
  2029. };
  2030. const filterModelListeners = (attrs, props) => {
  2031. const res = {};
  2032. for (const key in attrs) {
  2033. if (!isModelListener(key) || !(key.slice(9) in props)) {
  2034. res[key] = attrs[key];
  2035. }
  2036. }
  2037. return res;
  2038. };
  2039. const isElementRoot = (vnode) => {
  2040. return (vnode.shapeFlag & 6 /* COMPONENT */ ||
  2041. vnode.shapeFlag & 1 /* ELEMENT */ ||
  2042. vnode.type === Comment // potential v-if branch switch
  2043. );
  2044. };
  2045. function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
  2046. const { props: prevProps, children: prevChildren, component } = prevVNode;
  2047. const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
  2048. const emits = component.emitsOptions;
  2049. // Parent component's render function was hot-updated. Since this may have
  2050. // caused the child component's slots content to have changed, we need to
  2051. // force the child to update as well.
  2052. if ( (prevChildren || nextChildren) && isHmrUpdating) {
  2053. return true;
  2054. }
  2055. // force child update for runtime directive or transition on component vnode.
  2056. if (nextVNode.dirs || nextVNode.transition) {
  2057. return true;
  2058. }
  2059. if (optimized && patchFlag > 0) {
  2060. if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
  2061. // slot content that references values that might have changed,
  2062. // e.g. in a v-for
  2063. return true;
  2064. }
  2065. if (patchFlag & 16 /* FULL_PROPS */) {
  2066. if (!prevProps) {
  2067. return !!nextProps;
  2068. }
  2069. // presence of this flag indicates props are always non-null
  2070. return hasPropsChanged(prevProps, nextProps, emits);
  2071. }
  2072. else if (patchFlag & 8 /* PROPS */) {
  2073. const dynamicProps = nextVNode.dynamicProps;
  2074. for (let i = 0; i < dynamicProps.length; i++) {
  2075. const key = dynamicProps[i];
  2076. if (nextProps[key] !== prevProps[key] &&
  2077. !isEmitListener(emits, key)) {
  2078. return true;
  2079. }
  2080. }
  2081. }
  2082. }
  2083. else {
  2084. // this path is only taken by manually written render functions
  2085. // so presence of any children leads to a forced update
  2086. if (prevChildren || nextChildren) {
  2087. if (!nextChildren || !nextChildren.$stable) {
  2088. return true;
  2089. }
  2090. }
  2091. if (prevProps === nextProps) {
  2092. return false;
  2093. }
  2094. if (!prevProps) {
  2095. return !!nextProps;
  2096. }
  2097. if (!nextProps) {
  2098. return true;
  2099. }
  2100. return hasPropsChanged(prevProps, nextProps, emits);
  2101. }
  2102. return false;
  2103. }
  2104. function hasPropsChanged(prevProps, nextProps, emitsOptions) {
  2105. const nextKeys = Object.keys(nextProps);
  2106. if (nextKeys.length !== Object.keys(prevProps).length) {
  2107. return true;
  2108. }
  2109. for (let i = 0; i < nextKeys.length; i++) {
  2110. const key = nextKeys[i];
  2111. if (nextProps[key] !== prevProps[key] &&
  2112. !isEmitListener(emitsOptions, key)) {
  2113. return true;
  2114. }
  2115. }
  2116. return false;
  2117. }
  2118. function updateHOCHostEl({ vnode, parent }, el // HostNode
  2119. ) {
  2120. while (parent && parent.subTree === vnode) {
  2121. (vnode = parent.vnode).el = el;
  2122. parent = parent.parent;
  2123. }
  2124. }
  2125. const isSuspense = (type) => type.__isSuspense;
  2126. // Suspense exposes a component-like API, and is treated like a component
  2127. // in the compiler, but internally it's a special built-in type that hooks
  2128. // directly into the renderer.
  2129. const SuspenseImpl = {
  2130. // In order to make Suspense tree-shakable, we need to avoid importing it
  2131. // directly in the renderer. The renderer checks for the __isSuspense flag
  2132. // on a vnode's type and calls the `process` method, passing in renderer
  2133. // internals.
  2134. __isSuspense: true,
  2135. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized,
  2136. // platform-specific impl passed from renderer
  2137. rendererInternals) {
  2138. if (n1 == null) {
  2139. mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, rendererInternals);
  2140. }
  2141. else {
  2142. patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, rendererInternals);
  2143. }
  2144. },
  2145. hydrate: hydrateSuspense,
  2146. create: createSuspenseBoundary
  2147. };
  2148. // Force-casted public typing for h and TSX props inference
  2149. const Suspense = ( SuspenseImpl
  2150. );
  2151. function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, optimized, rendererInternals) {
  2152. const { p: patch, o: { createElement } } = rendererInternals;
  2153. const hiddenContainer = createElement('div');
  2154. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, optimized, rendererInternals));
  2155. // start mounting the content subtree in an off-dom container
  2156. patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG);
  2157. // now check if we have encountered any async deps
  2158. if (suspense.deps > 0) {
  2159. // has async
  2160. // mount the fallback tree
  2161. patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2162. isSVG);
  2163. setActiveBranch(suspense, vnode.ssFallback);
  2164. }
  2165. else {
  2166. // Suspense has no async deps. Just resolve.
  2167. suspense.resolve();
  2168. }
  2169. }
  2170. function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, { p: patch, um: unmount, o: { createElement } }) {
  2171. const suspense = (n2.suspense = n1.suspense);
  2172. suspense.vnode = n2;
  2173. n2.el = n1.el;
  2174. const newBranch = n2.ssContent;
  2175. const newFallback = n2.ssFallback;
  2176. const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
  2177. if (pendingBranch) {
  2178. suspense.pendingBranch = newBranch;
  2179. if (isSameVNodeType(newBranch, pendingBranch)) {
  2180. // same root type but content may have changed.
  2181. patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2182. if (suspense.deps <= 0) {
  2183. suspense.resolve();
  2184. }
  2185. else if (isInFallback) {
  2186. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2187. isSVG);
  2188. setActiveBranch(suspense, newFallback);
  2189. }
  2190. }
  2191. else {
  2192. // toggled before pending tree is resolved
  2193. suspense.pendingId++;
  2194. if (isHydrating) {
  2195. // if toggled before hydration is finished, the current DOM tree is
  2196. // no longer valid. set it as the active branch so it will be unmounted
  2197. // when resolved
  2198. suspense.isHydrating = false;
  2199. suspense.activeBranch = pendingBranch;
  2200. }
  2201. else {
  2202. unmount(pendingBranch, parentComponent, suspense);
  2203. }
  2204. // increment pending ID. this is used to invalidate async callbacks
  2205. // reset suspense state
  2206. suspense.deps = 0;
  2207. // discard effects from pending branch
  2208. suspense.effects.length = 0;
  2209. // discard previous container
  2210. suspense.hiddenContainer = createElement('div');
  2211. if (isInFallback) {
  2212. // already in fallback state
  2213. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2214. if (suspense.deps <= 0) {
  2215. suspense.resolve();
  2216. }
  2217. else {
  2218. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2219. isSVG);
  2220. setActiveBranch(suspense, newFallback);
  2221. }
  2222. }
  2223. else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2224. // toggled "back" to current active branch
  2225. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG);
  2226. // force resolve
  2227. suspense.resolve(true);
  2228. }
  2229. else {
  2230. // switched to a 3rd branch
  2231. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2232. if (suspense.deps <= 0) {
  2233. suspense.resolve();
  2234. }
  2235. }
  2236. }
  2237. }
  2238. else {
  2239. if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2240. // root did not change, just normal patch
  2241. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG);
  2242. setActiveBranch(suspense, newBranch);
  2243. }
  2244. else {
  2245. // root node toggled
  2246. // invoke @pending event
  2247. const onPending = n2.props && n2.props.onPending;
  2248. if (isFunction(onPending)) {
  2249. onPending();
  2250. }
  2251. // mount pending branch in off-dom container
  2252. suspense.pendingBranch = newBranch;
  2253. suspense.pendingId++;
  2254. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2255. if (suspense.deps <= 0) {
  2256. // incoming branch has no async deps, resolve now.
  2257. suspense.resolve();
  2258. }
  2259. else {
  2260. const { timeout, pendingId } = suspense;
  2261. if (timeout > 0) {
  2262. setTimeout(() => {
  2263. if (suspense.pendingId === pendingId) {
  2264. suspense.fallback(newFallback);
  2265. }
  2266. }, timeout);
  2267. }
  2268. else if (timeout === 0) {
  2269. suspense.fallback(newFallback);
  2270. }
  2271. }
  2272. }
  2273. }
  2274. }
  2275. let hasWarned = false;
  2276. function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, optimized, rendererInternals, isHydrating = false) {
  2277. /* istanbul ignore if */
  2278. if ( !hasWarned) {
  2279. hasWarned = true;
  2280. // @ts-ignore `console.info` cannot be null error
  2281. console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
  2282. }
  2283. const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
  2284. const timeout = toNumber(vnode.props && vnode.props.timeout);
  2285. const suspense = {
  2286. vnode,
  2287. parent,
  2288. parentComponent,
  2289. isSVG,
  2290. container,
  2291. hiddenContainer,
  2292. anchor,
  2293. deps: 0,
  2294. pendingId: 0,
  2295. timeout: typeof timeout === 'number' ? timeout : -1,
  2296. activeBranch: null,
  2297. pendingBranch: null,
  2298. isInFallback: true,
  2299. isHydrating,
  2300. isUnmounted: false,
  2301. effects: [],
  2302. resolve(resume = false) {
  2303. {
  2304. if (!resume && !suspense.pendingBranch) {
  2305. throw new Error(`suspense.resolve() is called without a pending branch.`);
  2306. }
  2307. if (suspense.isUnmounted) {
  2308. throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
  2309. }
  2310. }
  2311. const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
  2312. if (suspense.isHydrating) {
  2313. suspense.isHydrating = false;
  2314. }
  2315. else if (!resume) {
  2316. const delayEnter = activeBranch &&
  2317. pendingBranch.transition &&
  2318. pendingBranch.transition.mode === 'out-in';
  2319. if (delayEnter) {
  2320. activeBranch.transition.afterLeave = () => {
  2321. if (pendingId === suspense.pendingId) {
  2322. move(pendingBranch, container, anchor, 0 /* ENTER */);
  2323. }
  2324. };
  2325. }
  2326. // this is initial anchor on mount
  2327. let { anchor } = suspense;
  2328. // unmount current active tree
  2329. if (activeBranch) {
  2330. // if the fallback tree was mounted, it may have been moved
  2331. // as part of a parent suspense. get the latest anchor for insertion
  2332. anchor = next(activeBranch);
  2333. unmount(activeBranch, parentComponent, suspense, true);
  2334. }
  2335. if (!delayEnter) {
  2336. // move content from off-dom container to actual container
  2337. move(pendingBranch, container, anchor, 0 /* ENTER */);
  2338. }
  2339. }
  2340. setActiveBranch(suspense, pendingBranch);
  2341. suspense.pendingBranch = null;
  2342. suspense.isInFallback = false;
  2343. // flush buffered effects
  2344. // check if there is a pending parent suspense
  2345. let parent = suspense.parent;
  2346. let hasUnresolvedAncestor = false;
  2347. while (parent) {
  2348. if (parent.pendingBranch) {
  2349. // found a pending parent suspense, merge buffered post jobs
  2350. // into that parent
  2351. parent.effects.push(...effects);
  2352. hasUnresolvedAncestor = true;
  2353. break;
  2354. }
  2355. parent = parent.parent;
  2356. }
  2357. // no pending parent suspense, flush all jobs
  2358. if (!hasUnresolvedAncestor) {
  2359. queuePostFlushCb(effects);
  2360. }
  2361. suspense.effects = [];
  2362. // invoke @resolve event
  2363. const onResolve = vnode.props && vnode.props.onResolve;
  2364. if (isFunction(onResolve)) {
  2365. onResolve();
  2366. }
  2367. },
  2368. fallback(fallbackVNode) {
  2369. if (!suspense.pendingBranch) {
  2370. return;
  2371. }
  2372. const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
  2373. // invoke @fallback event
  2374. const onFallback = vnode.props && vnode.props.onFallback;
  2375. if (isFunction(onFallback)) {
  2376. onFallback();
  2377. }
  2378. const anchor = next(activeBranch);
  2379. const mountFallback = () => {
  2380. if (!suspense.isInFallback) {
  2381. return;
  2382. }
  2383. // mount the fallback tree
  2384. patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2385. isSVG);
  2386. setActiveBranch(suspense, fallbackVNode);
  2387. };
  2388. const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
  2389. if (delayEnter) {
  2390. activeBranch.transition.afterLeave = mountFallback;
  2391. }
  2392. // unmount current active branch
  2393. unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
  2394. true // shouldRemove
  2395. );
  2396. suspense.isInFallback = true;
  2397. if (!delayEnter) {
  2398. mountFallback();
  2399. }
  2400. },
  2401. move(container, anchor, type) {
  2402. suspense.activeBranch &&
  2403. move(suspense.activeBranch, container, anchor, type);
  2404. suspense.container = container;
  2405. },
  2406. next() {
  2407. return suspense.activeBranch && next(suspense.activeBranch);
  2408. },
  2409. registerDep(instance, setupRenderEffect) {
  2410. if (!suspense.pendingBranch) {
  2411. return;
  2412. }
  2413. const hydratedEl = instance.vnode.el;
  2414. suspense.deps++;
  2415. instance
  2416. .asyncDep.catch(err => {
  2417. handleError(err, instance, 0 /* SETUP_FUNCTION */);
  2418. })
  2419. .then(asyncSetupResult => {
  2420. // retry when the setup() promise resolves.
  2421. // component may have been unmounted before resolve.
  2422. if (instance.isUnmounted ||
  2423. suspense.isUnmounted ||
  2424. suspense.pendingId !== instance.suspenseId) {
  2425. return;
  2426. }
  2427. suspense.deps--;
  2428. // retry from this component
  2429. instance.asyncResolved = true;
  2430. const { vnode } = instance;
  2431. {
  2432. pushWarningContext(vnode);
  2433. }
  2434. handleSetupResult(instance, asyncSetupResult);
  2435. if (hydratedEl) {
  2436. // vnode may have been replaced if an update happened before the
  2437. // async dep is resolved.
  2438. vnode.el = hydratedEl;
  2439. }
  2440. const placeholder = !hydratedEl && instance.subTree.el;
  2441. setupRenderEffect(instance, vnode,
  2442. // component may have been moved before resolve.
  2443. // if this is not a hydration, instance.subTree will be the comment
  2444. // placeholder.
  2445. parentNode(hydratedEl || instance.subTree.el),
  2446. // anchor will not be used if this is hydration, so only need to
  2447. // consider the comment placeholder case.
  2448. hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
  2449. if (placeholder) {
  2450. remove(placeholder);
  2451. }
  2452. updateHOCHostEl(instance, vnode.el);
  2453. {
  2454. popWarningContext();
  2455. }
  2456. if (suspense.deps === 0) {
  2457. suspense.resolve();
  2458. }
  2459. });
  2460. },
  2461. unmount(parentSuspense, doRemove) {
  2462. suspense.isUnmounted = true;
  2463. if (suspense.activeBranch) {
  2464. unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
  2465. }
  2466. if (suspense.pendingBranch) {
  2467. unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
  2468. }
  2469. }
  2470. };
  2471. return suspense;
  2472. }
  2473. function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, optimized, rendererInternals, hydrateNode) {
  2474. /* eslint-disable no-restricted-globals */
  2475. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, optimized, rendererInternals, true /* hydrating */));
  2476. // there are two possible scenarios for server-rendered suspense:
  2477. // - success: ssr content should be fully resolved
  2478. // - failure: ssr content should be the fallback branch.
  2479. // however, on the client we don't really know if it has failed or not
  2480. // attempt to hydrate the DOM assuming it has succeeded, but we still
  2481. // need to construct a suspense boundary first
  2482. const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, optimized);
  2483. if (suspense.deps === 0) {
  2484. suspense.resolve();
  2485. }
  2486. return result;
  2487. /* eslint-enable no-restricted-globals */
  2488. }
  2489. function normalizeSuspenseChildren(vnode) {
  2490. const { shapeFlag, children } = vnode;
  2491. let content;
  2492. let fallback;
  2493. if (shapeFlag & 32 /* SLOTS_CHILDREN */) {
  2494. content = normalizeSuspenseSlot(children.default);
  2495. fallback = normalizeSuspenseSlot(children.fallback);
  2496. }
  2497. else {
  2498. content = normalizeSuspenseSlot(children);
  2499. fallback = normalizeVNode(null);
  2500. }
  2501. return {
  2502. content,
  2503. fallback
  2504. };
  2505. }
  2506. function normalizeSuspenseSlot(s) {
  2507. if (isFunction(s)) {
  2508. s = s();
  2509. }
  2510. if (isArray(s)) {
  2511. const singleChild = filterSingleRoot(s);
  2512. if ( !singleChild) {
  2513. warn(`<Suspense> slots expect a single root node.`);
  2514. }
  2515. s = singleChild;
  2516. }
  2517. return normalizeVNode(s);
  2518. }
  2519. function queueEffectWithSuspense(fn, suspense) {
  2520. if (suspense && suspense.pendingBranch) {
  2521. if (isArray(fn)) {
  2522. suspense.effects.push(...fn);
  2523. }
  2524. else {
  2525. suspense.effects.push(fn);
  2526. }
  2527. }
  2528. else {
  2529. queuePostFlushCb(fn);
  2530. }
  2531. }
  2532. function setActiveBranch(suspense, branch) {
  2533. suspense.activeBranch = branch;
  2534. const { vnode, parentComponent } = suspense;
  2535. const el = (vnode.el = branch.el);
  2536. // in case suspense is the root node of a component,
  2537. // recursively update the HOC el
  2538. if (parentComponent && parentComponent.subTree === vnode) {
  2539. parentComponent.vnode.el = el;
  2540. updateHOCHostEl(parentComponent, el);
  2541. }
  2542. }
  2543. let isRenderingCompiledSlot = 0;
  2544. const setCompiledSlotRendering = (n) => (isRenderingCompiledSlot += n);
  2545. /**
  2546. * Compiler runtime helper for rendering `<slot/>`
  2547. * @private
  2548. */
  2549. function renderSlot(slots, name, props = {},
  2550. // this is not a user-facing function, so the fallback is always generated by
  2551. // the compiler and guaranteed to be a function returning an array
  2552. fallback) {
  2553. let slot = slots[name];
  2554. if ( slot && slot.length > 1) {
  2555. warn(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
  2556. `function. You need to mark this component with $dynamic-slots in the ` +
  2557. `parent template.`);
  2558. slot = () => [];
  2559. }
  2560. // a compiled slot disables block tracking by default to avoid manual
  2561. // invocation interfering with template-based block tracking, but in
  2562. // `renderSlot` we can be sure that it's template-based so we can force
  2563. // enable it.
  2564. isRenderingCompiledSlot++;
  2565. const rendered = (openBlock(),
  2566. createBlock(Fragment, { key: props.key }, slot ? slot(props) : fallback ? fallback() : [], slots._ === 1 /* STABLE */
  2567. ? 64 /* STABLE_FRAGMENT */
  2568. : -2 /* BAIL */));
  2569. isRenderingCompiledSlot--;
  2570. return rendered;
  2571. }
  2572. /**
  2573. * Wrap a slot function to memoize current rendering instance
  2574. * @private
  2575. */
  2576. function withCtx(fn, ctx = currentRenderingInstance) {
  2577. if (!ctx)
  2578. return fn;
  2579. const renderFnWithContext = (...args) => {
  2580. // If a user calls a compiled slot inside a template expression (#1745), it
  2581. // can mess up block tracking, so by default we need to push a null block to
  2582. // avoid that. This isn't necessary if rendering a compiled `<slot>`.
  2583. if (!isRenderingCompiledSlot) {
  2584. openBlock(true /* null block that disables tracking */);
  2585. }
  2586. const owner = currentRenderingInstance;
  2587. setCurrentRenderingInstance(ctx);
  2588. const res = fn(...args);
  2589. setCurrentRenderingInstance(owner);
  2590. if (!isRenderingCompiledSlot) {
  2591. closeBlock();
  2592. }
  2593. return res;
  2594. };
  2595. renderFnWithContext._c = true;
  2596. return renderFnWithContext;
  2597. }
  2598. // SFC scoped style ID management.
  2599. let currentScopeId = null;
  2600. const scopeIdStack = [];
  2601. /**
  2602. * @private
  2603. */
  2604. function pushScopeId(id) {
  2605. scopeIdStack.push((currentScopeId = id));
  2606. }
  2607. /**
  2608. * @private
  2609. */
  2610. function popScopeId() {
  2611. scopeIdStack.pop();
  2612. currentScopeId = scopeIdStack[scopeIdStack.length - 1] || null;
  2613. }
  2614. /**
  2615. * @private
  2616. */
  2617. function withScopeId(id) {
  2618. return ((fn) => withCtx(function () {
  2619. pushScopeId(id);
  2620. const res = fn.apply(this, arguments);
  2621. popScopeId();
  2622. return res;
  2623. }));
  2624. }
  2625. function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
  2626. isSSR = false) {
  2627. const props = {};
  2628. const attrs = {};
  2629. def(attrs, InternalObjectKey, 1);
  2630. setFullProps(instance, rawProps, props, attrs);
  2631. // validation
  2632. {
  2633. validateProps(props, instance);
  2634. }
  2635. if (isStateful) {
  2636. // stateful
  2637. instance.props = isSSR ? props : shallowReactive(props);
  2638. }
  2639. else {
  2640. if (!instance.type.props) {
  2641. // functional w/ optional props, props === attrs
  2642. instance.props = attrs;
  2643. }
  2644. else {
  2645. // functional w/ declared props
  2646. instance.props = props;
  2647. }
  2648. }
  2649. instance.attrs = attrs;
  2650. }
  2651. function updateProps(instance, rawProps, rawPrevProps, optimized) {
  2652. const { props, attrs, vnode: { patchFlag } } = instance;
  2653. const rawCurrentProps = toRaw(props);
  2654. const [options] = instance.propsOptions;
  2655. if (
  2656. // always force full diff in dev
  2657. // - #1942 if hmr is enabled with sfc component
  2658. // - vite#872 non-sfc component used by sfc component
  2659. !(
  2660. (instance.type.__hmrId ||
  2661. (instance.parent && instance.parent.type.__hmrId))) &&
  2662. (optimized || patchFlag > 0) &&
  2663. !(patchFlag & 16 /* FULL_PROPS */)) {
  2664. if (patchFlag & 8 /* PROPS */) {
  2665. // Compiler-generated props & no keys change, just set the updated
  2666. // the props.
  2667. const propsToUpdate = instance.vnode.dynamicProps;
  2668. for (let i = 0; i < propsToUpdate.length; i++) {
  2669. const key = propsToUpdate[i];
  2670. // PROPS flag guarantees rawProps to be non-null
  2671. const value = rawProps[key];
  2672. if (options) {
  2673. // attr / props separation was done on init and will be consistent
  2674. // in this code path, so just check if attrs have it.
  2675. if (hasOwn(attrs, key)) {
  2676. attrs[key] = value;
  2677. }
  2678. else {
  2679. const camelizedKey = camelize(key);
  2680. props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance);
  2681. }
  2682. }
  2683. else {
  2684. attrs[key] = value;
  2685. }
  2686. }
  2687. }
  2688. }
  2689. else {
  2690. // full props update.
  2691. setFullProps(instance, rawProps, props, attrs);
  2692. // in case of dynamic props, check if we need to delete keys from
  2693. // the props object
  2694. let kebabKey;
  2695. for (const key in rawCurrentProps) {
  2696. if (!rawProps ||
  2697. // for camelCase
  2698. (!hasOwn(rawProps, key) &&
  2699. // it's possible the original props was passed in as kebab-case
  2700. // and converted to camelCase (#955)
  2701. ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
  2702. if (options) {
  2703. if (rawPrevProps &&
  2704. // for camelCase
  2705. (rawPrevProps[key] !== undefined ||
  2706. // for kebab-case
  2707. rawPrevProps[kebabKey] !== undefined)) {
  2708. props[key] = resolvePropValue(options, rawProps || EMPTY_OBJ, key, undefined, instance);
  2709. }
  2710. }
  2711. else {
  2712. delete props[key];
  2713. }
  2714. }
  2715. }
  2716. // in the case of functional component w/o props declaration, props and
  2717. // attrs point to the same object so it should already have been updated.
  2718. if (attrs !== rawCurrentProps) {
  2719. for (const key in attrs) {
  2720. if (!rawProps || !hasOwn(rawProps, key)) {
  2721. delete attrs[key];
  2722. }
  2723. }
  2724. }
  2725. }
  2726. // trigger updates for $attrs in case it's used in component slots
  2727. trigger(instance, "set" /* SET */, '$attrs');
  2728. if ( rawProps) {
  2729. validateProps(props, instance);
  2730. }
  2731. }
  2732. function setFullProps(instance, rawProps, props, attrs) {
  2733. const [options, needCastKeys] = instance.propsOptions;
  2734. if (rawProps) {
  2735. for (const key in rawProps) {
  2736. const value = rawProps[key];
  2737. // key, ref are reserved and never passed down
  2738. if (isReservedProp(key)) {
  2739. continue;
  2740. }
  2741. // prop option names are camelized during normalization, so to support
  2742. // kebab -> camel conversion here we need to camelize the key.
  2743. let camelKey;
  2744. if (options && hasOwn(options, (camelKey = camelize(key)))) {
  2745. props[camelKey] = value;
  2746. }
  2747. else if (!isEmitListener(instance.emitsOptions, key)) {
  2748. // Any non-declared (either as a prop or an emitted event) props are put
  2749. // into a separate `attrs` object for spreading. Make sure to preserve
  2750. // original key casing
  2751. attrs[key] = value;
  2752. }
  2753. }
  2754. }
  2755. if (needCastKeys) {
  2756. const rawCurrentProps = toRaw(props);
  2757. for (let i = 0; i < needCastKeys.length; i++) {
  2758. const key = needCastKeys[i];
  2759. props[key] = resolvePropValue(options, rawCurrentProps, key, rawCurrentProps[key], instance);
  2760. }
  2761. }
  2762. }
  2763. function resolvePropValue(options, props, key, value, instance) {
  2764. const opt = options[key];
  2765. if (opt != null) {
  2766. const hasDefault = hasOwn(opt, 'default');
  2767. // default values
  2768. if (hasDefault && value === undefined) {
  2769. const defaultValue = opt.default;
  2770. if (opt.type !== Function && isFunction(defaultValue)) {
  2771. setCurrentInstance(instance);
  2772. value = defaultValue(props);
  2773. setCurrentInstance(null);
  2774. }
  2775. else {
  2776. value = defaultValue;
  2777. }
  2778. }
  2779. // boolean casting
  2780. if (opt[0 /* shouldCast */]) {
  2781. if (!hasOwn(props, key) && !hasDefault) {
  2782. value = false;
  2783. }
  2784. else if (opt[1 /* shouldCastTrue */] &&
  2785. (value === '' || value === hyphenate(key))) {
  2786. value = true;
  2787. }
  2788. }
  2789. }
  2790. return value;
  2791. }
  2792. function normalizePropsOptions(comp, appContext, asMixin = false) {
  2793. if (!appContext.deopt && comp.__props) {
  2794. return comp.__props;
  2795. }
  2796. const raw = comp.props;
  2797. const normalized = {};
  2798. const needCastKeys = [];
  2799. // apply mixin/extends props
  2800. let hasExtends = false;
  2801. if ( !isFunction(comp)) {
  2802. const extendProps = (raw) => {
  2803. hasExtends = true;
  2804. const [props, keys] = normalizePropsOptions(raw, appContext, true);
  2805. extend(normalized, props);
  2806. if (keys)
  2807. needCastKeys.push(...keys);
  2808. };
  2809. if (!asMixin && appContext.mixins.length) {
  2810. appContext.mixins.forEach(extendProps);
  2811. }
  2812. if (comp.extends) {
  2813. extendProps(comp.extends);
  2814. }
  2815. if (comp.mixins) {
  2816. comp.mixins.forEach(extendProps);
  2817. }
  2818. }
  2819. if (!raw && !hasExtends) {
  2820. return (comp.__props = EMPTY_ARR);
  2821. }
  2822. if (isArray(raw)) {
  2823. for (let i = 0; i < raw.length; i++) {
  2824. if ( !isString(raw[i])) {
  2825. warn(`props must be strings when using array syntax.`, raw[i]);
  2826. }
  2827. const normalizedKey = camelize(raw[i]);
  2828. if (validatePropName(normalizedKey)) {
  2829. normalized[normalizedKey] = EMPTY_OBJ;
  2830. }
  2831. }
  2832. }
  2833. else if (raw) {
  2834. if ( !isObject(raw)) {
  2835. warn(`invalid props options`, raw);
  2836. }
  2837. for (const key in raw) {
  2838. const normalizedKey = camelize(key);
  2839. if (validatePropName(normalizedKey)) {
  2840. const opt = raw[key];
  2841. const prop = (normalized[normalizedKey] =
  2842. isArray(opt) || isFunction(opt) ? { type: opt } : opt);
  2843. if (prop) {
  2844. const booleanIndex = getTypeIndex(Boolean, prop.type);
  2845. const stringIndex = getTypeIndex(String, prop.type);
  2846. prop[0 /* shouldCast */] = booleanIndex > -1;
  2847. prop[1 /* shouldCastTrue */] =
  2848. stringIndex < 0 || booleanIndex < stringIndex;
  2849. // if the prop needs boolean casting or default value
  2850. if (booleanIndex > -1 || hasOwn(prop, 'default')) {
  2851. needCastKeys.push(normalizedKey);
  2852. }
  2853. }
  2854. }
  2855. }
  2856. }
  2857. return (comp.__props = [normalized, needCastKeys]);
  2858. }
  2859. function validatePropName(key) {
  2860. if (key[0] !== '$') {
  2861. return true;
  2862. }
  2863. else {
  2864. warn(`Invalid prop name: "${key}" is a reserved property.`);
  2865. }
  2866. return false;
  2867. }
  2868. // use function string name to check type constructors
  2869. // so that it works across vms / iframes.
  2870. function getType(ctor) {
  2871. const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
  2872. return match ? match[1] : '';
  2873. }
  2874. function isSameType(a, b) {
  2875. return getType(a) === getType(b);
  2876. }
  2877. function getTypeIndex(type, expectedTypes) {
  2878. if (isArray(expectedTypes)) {
  2879. for (let i = 0, len = expectedTypes.length; i < len; i++) {
  2880. if (isSameType(expectedTypes[i], type)) {
  2881. return i;
  2882. }
  2883. }
  2884. }
  2885. else if (isFunction(expectedTypes)) {
  2886. return isSameType(expectedTypes, type) ? 0 : -1;
  2887. }
  2888. return -1;
  2889. }
  2890. /**
  2891. * dev only
  2892. */
  2893. function validateProps(props, instance) {
  2894. const rawValues = toRaw(props);
  2895. const options = instance.propsOptions[0];
  2896. for (const key in options) {
  2897. let opt = options[key];
  2898. if (opt == null)
  2899. continue;
  2900. validateProp(key, rawValues[key], opt, !hasOwn(rawValues, key));
  2901. }
  2902. }
  2903. /**
  2904. * dev only
  2905. */
  2906. function validateProp(name, value, prop, isAbsent) {
  2907. const { type, required, validator } = prop;
  2908. // required!
  2909. if (required && isAbsent) {
  2910. warn('Missing required prop: "' + name + '"');
  2911. return;
  2912. }
  2913. // missing but optional
  2914. if (value == null && !prop.required) {
  2915. return;
  2916. }
  2917. // type check
  2918. if (type != null && type !== true) {
  2919. let isValid = false;
  2920. const types = isArray(type) ? type : [type];
  2921. const expectedTypes = [];
  2922. // value is valid as long as one of the specified types match
  2923. for (let i = 0; i < types.length && !isValid; i++) {
  2924. const { valid, expectedType } = assertType(value, types[i]);
  2925. expectedTypes.push(expectedType || '');
  2926. isValid = valid;
  2927. }
  2928. if (!isValid) {
  2929. warn(getInvalidTypeMessage(name, value, expectedTypes));
  2930. return;
  2931. }
  2932. }
  2933. // custom validator
  2934. if (validator && !validator(value)) {
  2935. warn('Invalid prop: custom validator check failed for prop "' + name + '".');
  2936. }
  2937. }
  2938. const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol');
  2939. /**
  2940. * dev only
  2941. */
  2942. function assertType(value, type) {
  2943. let valid;
  2944. const expectedType = getType(type);
  2945. if (isSimpleType(expectedType)) {
  2946. const t = typeof value;
  2947. valid = t === expectedType.toLowerCase();
  2948. // for primitive wrapper objects
  2949. if (!valid && t === 'object') {
  2950. valid = value instanceof type;
  2951. }
  2952. }
  2953. else if (expectedType === 'Object') {
  2954. valid = isObject(value);
  2955. }
  2956. else if (expectedType === 'Array') {
  2957. valid = isArray(value);
  2958. }
  2959. else {
  2960. valid = value instanceof type;
  2961. }
  2962. return {
  2963. valid,
  2964. expectedType
  2965. };
  2966. }
  2967. /**
  2968. * dev only
  2969. */
  2970. function getInvalidTypeMessage(name, value, expectedTypes) {
  2971. let message = `Invalid prop: type check failed for prop "${name}".` +
  2972. ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
  2973. const expectedType = expectedTypes[0];
  2974. const receivedType = toRawType(value);
  2975. const expectedValue = styleValue(value, expectedType);
  2976. const receivedValue = styleValue(value, receivedType);
  2977. // check if we need to specify expected value
  2978. if (expectedTypes.length === 1 &&
  2979. isExplicable(expectedType) &&
  2980. !isBoolean(expectedType, receivedType)) {
  2981. message += ` with value ${expectedValue}`;
  2982. }
  2983. message += `, got ${receivedType} `;
  2984. // check if we need to specify received value
  2985. if (isExplicable(receivedType)) {
  2986. message += `with value ${receivedValue}.`;
  2987. }
  2988. return message;
  2989. }
  2990. /**
  2991. * dev only
  2992. */
  2993. function styleValue(value, type) {
  2994. if (type === 'String') {
  2995. return `"${value}"`;
  2996. }
  2997. else if (type === 'Number') {
  2998. return `${Number(value)}`;
  2999. }
  3000. else {
  3001. return `${value}`;
  3002. }
  3003. }
  3004. /**
  3005. * dev only
  3006. */
  3007. function isExplicable(type) {
  3008. const explicitTypes = ['string', 'number', 'boolean'];
  3009. return explicitTypes.some(elem => type.toLowerCase() === elem);
  3010. }
  3011. /**
  3012. * dev only
  3013. */
  3014. function isBoolean(...args) {
  3015. return args.some(elem => elem.toLowerCase() === 'boolean');
  3016. }
  3017. function injectHook(type, hook, target = currentInstance, prepend = false) {
  3018. if (target) {
  3019. const hooks = target[type] || (target[type] = []);
  3020. // cache the error handling wrapper for injected hooks so the same hook
  3021. // can be properly deduped by the scheduler. "__weh" stands for "with error
  3022. // handling".
  3023. const wrappedHook = hook.__weh ||
  3024. (hook.__weh = (...args) => {
  3025. if (target.isUnmounted) {
  3026. return;
  3027. }
  3028. // disable tracking inside all lifecycle hooks
  3029. // since they can potentially be called inside effects.
  3030. pauseTracking();
  3031. // Set currentInstance during hook invocation.
  3032. // This assumes the hook does not synchronously trigger other hooks, which
  3033. // can only be false when the user does something really funky.
  3034. setCurrentInstance(target);
  3035. const res = callWithAsyncErrorHandling(hook, target, type, args);
  3036. setCurrentInstance(null);
  3037. resetTracking();
  3038. return res;
  3039. });
  3040. if (prepend) {
  3041. hooks.unshift(wrappedHook);
  3042. }
  3043. else {
  3044. hooks.push(wrappedHook);
  3045. }
  3046. return wrappedHook;
  3047. }
  3048. else {
  3049. const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
  3050. warn(`${apiName} is called when there is no active component instance to be ` +
  3051. `associated with. ` +
  3052. `Lifecycle injection APIs can only be used during execution of setup().` +
  3053. ( ` If you are using async setup(), make sure to register lifecycle ` +
  3054. `hooks before the first await statement.`
  3055. ));
  3056. }
  3057. }
  3058. const createHook = (lifecycle) => (hook, target = currentInstance) =>
  3059. // post-create lifecycle registrations are noops during SSR
  3060. !isInSSRComponentSetup && injectHook(lifecycle, hook, target);
  3061. const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
  3062. const onMounted = createHook("m" /* MOUNTED */);
  3063. const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
  3064. const onUpdated = createHook("u" /* UPDATED */);
  3065. const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
  3066. const onUnmounted = createHook("um" /* UNMOUNTED */);
  3067. const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
  3068. const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
  3069. const onErrorCaptured = (hook, target = currentInstance) => {
  3070. injectHook("ec" /* ERROR_CAPTURED */, hook, target);
  3071. };
  3072. // Simple effect.
  3073. function watchEffect(effect, options) {
  3074. return doWatch(effect, null, options);
  3075. }
  3076. // initial value for watchers to trigger on undefined initial values
  3077. const INITIAL_WATCHER_VALUE = {};
  3078. // implementation
  3079. function watch(source, cb, options) {
  3080. if ( !isFunction(cb)) {
  3081. warn(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
  3082. `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
  3083. `supports \`watch(source, cb, options?) signature.`);
  3084. }
  3085. return doWatch(source, cb, options);
  3086. }
  3087. function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ, instance = currentInstance) {
  3088. if ( !cb) {
  3089. if (immediate !== undefined) {
  3090. warn(`watch() "immediate" option is only respected when using the ` +
  3091. `watch(source, callback, options?) signature.`);
  3092. }
  3093. if (deep !== undefined) {
  3094. warn(`watch() "deep" option is only respected when using the ` +
  3095. `watch(source, callback, options?) signature.`);
  3096. }
  3097. }
  3098. const warnInvalidSource = (s) => {
  3099. warn(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
  3100. `a reactive object, or an array of these types.`);
  3101. };
  3102. let getter;
  3103. let forceTrigger = false;
  3104. if (isRef(source)) {
  3105. getter = () => source.value;
  3106. forceTrigger = !!source._shallow;
  3107. }
  3108. else if (isReactive(source)) {
  3109. getter = () => source;
  3110. deep = true;
  3111. }
  3112. else if (isArray(source)) {
  3113. getter = () => source.map(s => {
  3114. if (isRef(s)) {
  3115. return s.value;
  3116. }
  3117. else if (isReactive(s)) {
  3118. return traverse(s);
  3119. }
  3120. else if (isFunction(s)) {
  3121. return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
  3122. }
  3123. else {
  3124. warnInvalidSource(s);
  3125. }
  3126. });
  3127. }
  3128. else if (isFunction(source)) {
  3129. if (cb) {
  3130. // getter with cb
  3131. getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
  3132. }
  3133. else {
  3134. // no cb -> simple effect
  3135. getter = () => {
  3136. if (instance && instance.isUnmounted) {
  3137. return;
  3138. }
  3139. if (cleanup) {
  3140. cleanup();
  3141. }
  3142. return callWithErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
  3143. };
  3144. }
  3145. }
  3146. else {
  3147. getter = NOOP;
  3148. warnInvalidSource(source);
  3149. }
  3150. if (cb && deep) {
  3151. const baseGetter = getter;
  3152. getter = () => traverse(baseGetter());
  3153. }
  3154. let cleanup;
  3155. const onInvalidate = (fn) => {
  3156. cleanup = runner.options.onStop = () => {
  3157. callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
  3158. };
  3159. };
  3160. let oldValue = isArray(source) ? [] : INITIAL_WATCHER_VALUE;
  3161. const job = () => {
  3162. if (!runner.active) {
  3163. return;
  3164. }
  3165. if (cb) {
  3166. // watch(source, cb)
  3167. const newValue = runner();
  3168. if (deep || forceTrigger || hasChanged(newValue, oldValue)) {
  3169. // cleanup before running cb again
  3170. if (cleanup) {
  3171. cleanup();
  3172. }
  3173. callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
  3174. newValue,
  3175. // pass undefined as the old value when it's changed for the first time
  3176. oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
  3177. onInvalidate
  3178. ]);
  3179. oldValue = newValue;
  3180. }
  3181. }
  3182. else {
  3183. // watchEffect
  3184. runner();
  3185. }
  3186. };
  3187. // important: mark the job as a watcher callback so that scheduler knows
  3188. // it is allowed to self-trigger (#1727)
  3189. job.allowRecurse = !!cb;
  3190. let scheduler;
  3191. if (flush === 'sync') {
  3192. scheduler = job;
  3193. }
  3194. else if (flush === 'post') {
  3195. scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
  3196. }
  3197. else {
  3198. // default: 'pre'
  3199. scheduler = () => {
  3200. if (!instance || instance.isMounted) {
  3201. queuePreFlushCb(job);
  3202. }
  3203. else {
  3204. // with 'pre' option, the first call must happen before
  3205. // the component is mounted so it is called synchronously.
  3206. job();
  3207. }
  3208. };
  3209. }
  3210. const runner = effect(getter, {
  3211. lazy: true,
  3212. onTrack,
  3213. onTrigger,
  3214. scheduler
  3215. });
  3216. recordInstanceBoundEffect(runner);
  3217. // initial run
  3218. if (cb) {
  3219. if (immediate) {
  3220. job();
  3221. }
  3222. else {
  3223. oldValue = runner();
  3224. }
  3225. }
  3226. else if (flush === 'post') {
  3227. queuePostRenderEffect(runner, instance && instance.suspense);
  3228. }
  3229. else {
  3230. runner();
  3231. }
  3232. return () => {
  3233. stop(runner);
  3234. if (instance) {
  3235. remove(instance.effects, runner);
  3236. }
  3237. };
  3238. }
  3239. // this.$watch
  3240. function instanceWatch(source, cb, options) {
  3241. const publicThis = this.proxy;
  3242. const getter = isString(source)
  3243. ? () => publicThis[source]
  3244. : source.bind(publicThis);
  3245. return doWatch(getter, cb.bind(publicThis), options, this);
  3246. }
  3247. function traverse(value, seen = new Set()) {
  3248. if (!isObject(value) || seen.has(value)) {
  3249. return value;
  3250. }
  3251. seen.add(value);
  3252. if (isRef(value)) {
  3253. traverse(value.value, seen);
  3254. }
  3255. else if (isArray(value)) {
  3256. for (let i = 0; i < value.length; i++) {
  3257. traverse(value[i], seen);
  3258. }
  3259. }
  3260. else if (isSet(value) || isMap(value)) {
  3261. value.forEach((v) => {
  3262. traverse(v, seen);
  3263. });
  3264. }
  3265. else {
  3266. for (const key in value) {
  3267. traverse(value[key], seen);
  3268. }
  3269. }
  3270. return value;
  3271. }
  3272. function useTransitionState() {
  3273. const state = {
  3274. isMounted: false,
  3275. isLeaving: false,
  3276. isUnmounting: false,
  3277. leavingVNodes: new Map()
  3278. };
  3279. onMounted(() => {
  3280. state.isMounted = true;
  3281. });
  3282. onBeforeUnmount(() => {
  3283. state.isUnmounting = true;
  3284. });
  3285. return state;
  3286. }
  3287. const TransitionHookValidator = [Function, Array];
  3288. const BaseTransitionImpl = {
  3289. name: `BaseTransition`,
  3290. props: {
  3291. mode: String,
  3292. appear: Boolean,
  3293. persisted: Boolean,
  3294. // enter
  3295. onBeforeEnter: TransitionHookValidator,
  3296. onEnter: TransitionHookValidator,
  3297. onAfterEnter: TransitionHookValidator,
  3298. onEnterCancelled: TransitionHookValidator,
  3299. // leave
  3300. onBeforeLeave: TransitionHookValidator,
  3301. onLeave: TransitionHookValidator,
  3302. onAfterLeave: TransitionHookValidator,
  3303. onLeaveCancelled: TransitionHookValidator,
  3304. // appear
  3305. onBeforeAppear: TransitionHookValidator,
  3306. onAppear: TransitionHookValidator,
  3307. onAfterAppear: TransitionHookValidator,
  3308. onAppearCancelled: TransitionHookValidator
  3309. },
  3310. setup(props, { slots }) {
  3311. const instance = getCurrentInstance();
  3312. const state = useTransitionState();
  3313. let prevTransitionKey;
  3314. return () => {
  3315. const children = slots.default && getTransitionRawChildren(slots.default(), true);
  3316. if (!children || !children.length) {
  3317. return;
  3318. }
  3319. // warn multiple elements
  3320. if ( children.length > 1) {
  3321. warn('<transition> can only be used on a single element or component. Use ' +
  3322. '<transition-group> for lists.');
  3323. }
  3324. // there's no need to track reactivity for these props so use the raw
  3325. // props for a bit better perf
  3326. const rawProps = toRaw(props);
  3327. const { mode } = rawProps;
  3328. // check mode
  3329. if ( mode && !['in-out', 'out-in', 'default'].includes(mode)) {
  3330. warn(`invalid <transition> mode: ${mode}`);
  3331. }
  3332. // at this point children has a guaranteed length of 1.
  3333. const child = children[0];
  3334. if (state.isLeaving) {
  3335. return emptyPlaceholder(child);
  3336. }
  3337. // in the case of <transition><keep-alive/></transition>, we need to
  3338. // compare the type of the kept-alive children.
  3339. const innerChild = getKeepAliveChild(child);
  3340. if (!innerChild) {
  3341. return emptyPlaceholder(child);
  3342. }
  3343. const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
  3344. setTransitionHooks(innerChild, enterHooks);
  3345. const oldChild = instance.subTree;
  3346. const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
  3347. let transitionKeyChanged = false;
  3348. const { getTransitionKey } = innerChild.type;
  3349. if (getTransitionKey) {
  3350. const key = getTransitionKey();
  3351. if (prevTransitionKey === undefined) {
  3352. prevTransitionKey = key;
  3353. }
  3354. else if (key !== prevTransitionKey) {
  3355. prevTransitionKey = key;
  3356. transitionKeyChanged = true;
  3357. }
  3358. }
  3359. // handle mode
  3360. if (oldInnerChild &&
  3361. oldInnerChild.type !== Comment &&
  3362. (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
  3363. const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
  3364. // update old tree's hooks in case of dynamic transition
  3365. setTransitionHooks(oldInnerChild, leavingHooks);
  3366. // switching between different views
  3367. if (mode === 'out-in') {
  3368. state.isLeaving = true;
  3369. // return placeholder node and queue update when leave finishes
  3370. leavingHooks.afterLeave = () => {
  3371. state.isLeaving = false;
  3372. instance.update();
  3373. };
  3374. return emptyPlaceholder(child);
  3375. }
  3376. else if (mode === 'in-out') {
  3377. leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
  3378. const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
  3379. leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
  3380. // early removal callback
  3381. el._leaveCb = () => {
  3382. earlyRemove();
  3383. el._leaveCb = undefined;
  3384. delete enterHooks.delayedLeave;
  3385. };
  3386. enterHooks.delayedLeave = delayedLeave;
  3387. };
  3388. }
  3389. }
  3390. return child;
  3391. };
  3392. }
  3393. };
  3394. // export the public type for h/tsx inference
  3395. // also to avoid inline import() in generated d.ts files
  3396. const BaseTransition = BaseTransitionImpl;
  3397. function getLeavingNodesForType(state, vnode) {
  3398. const { leavingVNodes } = state;
  3399. let leavingVNodesCache = leavingVNodes.get(vnode.type);
  3400. if (!leavingVNodesCache) {
  3401. leavingVNodesCache = Object.create(null);
  3402. leavingVNodes.set(vnode.type, leavingVNodesCache);
  3403. }
  3404. return leavingVNodesCache;
  3405. }
  3406. // The transition hooks are attached to the vnode as vnode.transition
  3407. // and will be called at appropriate timing in the renderer.
  3408. function resolveTransitionHooks(vnode, props, state, instance) {
  3409. const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
  3410. const key = String(vnode.key);
  3411. const leavingVNodesCache = getLeavingNodesForType(state, vnode);
  3412. const callHook = (hook, args) => {
  3413. hook &&
  3414. callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
  3415. };
  3416. const hooks = {
  3417. mode,
  3418. persisted,
  3419. beforeEnter(el) {
  3420. let hook = onBeforeEnter;
  3421. if (!state.isMounted) {
  3422. if (appear) {
  3423. hook = onBeforeAppear || onBeforeEnter;
  3424. }
  3425. else {
  3426. return;
  3427. }
  3428. }
  3429. // for same element (v-show)
  3430. if (el._leaveCb) {
  3431. el._leaveCb(true /* cancelled */);
  3432. }
  3433. // for toggled element with same key (v-if)
  3434. const leavingVNode = leavingVNodesCache[key];
  3435. if (leavingVNode &&
  3436. isSameVNodeType(vnode, leavingVNode) &&
  3437. leavingVNode.el._leaveCb) {
  3438. // force early removal (not cancelled)
  3439. leavingVNode.el._leaveCb();
  3440. }
  3441. callHook(hook, [el]);
  3442. },
  3443. enter(el) {
  3444. let hook = onEnter;
  3445. let afterHook = onAfterEnter;
  3446. let cancelHook = onEnterCancelled;
  3447. if (!state.isMounted) {
  3448. if (appear) {
  3449. hook = onAppear || onEnter;
  3450. afterHook = onAfterAppear || onAfterEnter;
  3451. cancelHook = onAppearCancelled || onEnterCancelled;
  3452. }
  3453. else {
  3454. return;
  3455. }
  3456. }
  3457. let called = false;
  3458. const done = (el._enterCb = (cancelled) => {
  3459. if (called)
  3460. return;
  3461. called = true;
  3462. if (cancelled) {
  3463. callHook(cancelHook, [el]);
  3464. }
  3465. else {
  3466. callHook(afterHook, [el]);
  3467. }
  3468. if (hooks.delayedLeave) {
  3469. hooks.delayedLeave();
  3470. }
  3471. el._enterCb = undefined;
  3472. });
  3473. if (hook) {
  3474. hook(el, done);
  3475. if (hook.length <= 1) {
  3476. done();
  3477. }
  3478. }
  3479. else {
  3480. done();
  3481. }
  3482. },
  3483. leave(el, remove) {
  3484. const key = String(vnode.key);
  3485. if (el._enterCb) {
  3486. el._enterCb(true /* cancelled */);
  3487. }
  3488. if (state.isUnmounting) {
  3489. return remove();
  3490. }
  3491. callHook(onBeforeLeave, [el]);
  3492. let called = false;
  3493. const done = (el._leaveCb = (cancelled) => {
  3494. if (called)
  3495. return;
  3496. called = true;
  3497. remove();
  3498. if (cancelled) {
  3499. callHook(onLeaveCancelled, [el]);
  3500. }
  3501. else {
  3502. callHook(onAfterLeave, [el]);
  3503. }
  3504. el._leaveCb = undefined;
  3505. if (leavingVNodesCache[key] === vnode) {
  3506. delete leavingVNodesCache[key];
  3507. }
  3508. });
  3509. leavingVNodesCache[key] = vnode;
  3510. if (onLeave) {
  3511. onLeave(el, done);
  3512. if (onLeave.length <= 1) {
  3513. done();
  3514. }
  3515. }
  3516. else {
  3517. done();
  3518. }
  3519. },
  3520. clone(vnode) {
  3521. return resolveTransitionHooks(vnode, props, state, instance);
  3522. }
  3523. };
  3524. return hooks;
  3525. }
  3526. // the placeholder really only handles one special case: KeepAlive
  3527. // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
  3528. // placeholder with empty content to avoid the KeepAlive instance from being
  3529. // unmounted.
  3530. function emptyPlaceholder(vnode) {
  3531. if (isKeepAlive(vnode)) {
  3532. vnode = cloneVNode(vnode);
  3533. vnode.children = null;
  3534. return vnode;
  3535. }
  3536. }
  3537. function getKeepAliveChild(vnode) {
  3538. return isKeepAlive(vnode)
  3539. ? vnode.children
  3540. ? vnode.children[0]
  3541. : undefined
  3542. : vnode;
  3543. }
  3544. function setTransitionHooks(vnode, hooks) {
  3545. if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
  3546. setTransitionHooks(vnode.component.subTree, hooks);
  3547. }
  3548. else if ( vnode.shapeFlag & 128 /* SUSPENSE */) {
  3549. vnode.ssContent.transition = hooks.clone(vnode.ssContent);
  3550. vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
  3551. }
  3552. else {
  3553. vnode.transition = hooks;
  3554. }
  3555. }
  3556. function getTransitionRawChildren(children, keepComment = false) {
  3557. let ret = [];
  3558. let keyedFragmentCount = 0;
  3559. for (let i = 0; i < children.length; i++) {
  3560. const child = children[i];
  3561. // handle fragment children case, e.g. v-for
  3562. if (child.type === Fragment) {
  3563. if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
  3564. keyedFragmentCount++;
  3565. ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
  3566. }
  3567. // comment placeholders should be skipped, e.g. v-if
  3568. else if (keepComment || child.type !== Comment) {
  3569. ret.push(child);
  3570. }
  3571. }
  3572. // #1126 if a transition children list contains multiple sub fragments, these
  3573. // fragments will be merged into a flat children array. Since each v-for
  3574. // fragment may contain different static bindings inside, we need to de-top
  3575. // these children to force full diffs to ensure correct behavior.
  3576. if (keyedFragmentCount > 1) {
  3577. for (let i = 0; i < ret.length; i++) {
  3578. ret[i].patchFlag = -2 /* BAIL */;
  3579. }
  3580. }
  3581. return ret;
  3582. }
  3583. const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
  3584. const KeepAliveImpl = {
  3585. name: `KeepAlive`,
  3586. // Marker for special handling inside the renderer. We are not using a ===
  3587. // check directly on KeepAlive in the renderer, because importing it directly
  3588. // would prevent it from being tree-shaken.
  3589. __isKeepAlive: true,
  3590. inheritRef: true,
  3591. props: {
  3592. include: [String, RegExp, Array],
  3593. exclude: [String, RegExp, Array],
  3594. max: [String, Number]
  3595. },
  3596. setup(props, { slots }) {
  3597. const cache = new Map();
  3598. const keys = new Set();
  3599. let current = null;
  3600. const instance = getCurrentInstance();
  3601. const parentSuspense = instance.suspense;
  3602. // KeepAlive communicates with the instantiated renderer via the
  3603. // ctx where the renderer passes in its internals,
  3604. // and the KeepAlive instance exposes activate/deactivate implementations.
  3605. // The whole point of this is to avoid importing KeepAlive directly in the
  3606. // renderer to facilitate tree-shaking.
  3607. const sharedContext = instance.ctx;
  3608. const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
  3609. const storageContainer = createElement('div');
  3610. sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
  3611. const instance = vnode.component;
  3612. move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
  3613. // in case props have changed
  3614. patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, optimized);
  3615. queuePostRenderEffect(() => {
  3616. instance.isDeactivated = false;
  3617. if (instance.a) {
  3618. invokeArrayFns(instance.a);
  3619. }
  3620. const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
  3621. if (vnodeHook) {
  3622. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3623. }
  3624. }, parentSuspense);
  3625. };
  3626. sharedContext.deactivate = (vnode) => {
  3627. const instance = vnode.component;
  3628. move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
  3629. queuePostRenderEffect(() => {
  3630. if (instance.da) {
  3631. invokeArrayFns(instance.da);
  3632. }
  3633. const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
  3634. if (vnodeHook) {
  3635. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3636. }
  3637. instance.isDeactivated = true;
  3638. }, parentSuspense);
  3639. };
  3640. function unmount(vnode) {
  3641. // reset the shapeFlag so it can be properly unmounted
  3642. resetShapeFlag(vnode);
  3643. _unmount(vnode, instance, parentSuspense);
  3644. }
  3645. function pruneCache(filter) {
  3646. cache.forEach((vnode, key) => {
  3647. const name = getName(vnode.type);
  3648. if (name && (!filter || !filter(name))) {
  3649. pruneCacheEntry(key);
  3650. }
  3651. });
  3652. }
  3653. function pruneCacheEntry(key) {
  3654. const cached = cache.get(key);
  3655. if (!current || cached.type !== current.type) {
  3656. unmount(cached);
  3657. }
  3658. else if (current) {
  3659. // current active instance should no longer be kept-alive.
  3660. // we can't unmount it now but it might be later, so reset its flag now.
  3661. resetShapeFlag(current);
  3662. }
  3663. cache.delete(key);
  3664. keys.delete(key);
  3665. }
  3666. // prune cache on include/exclude prop change
  3667. watch(() => [props.include, props.exclude], ([include, exclude]) => {
  3668. include && pruneCache(name => matches(include, name));
  3669. exclude && pruneCache(name => !matches(exclude, name));
  3670. },
  3671. // prune post-render after `current` has been updated
  3672. { flush: 'post' });
  3673. // cache sub tree after render
  3674. let pendingCacheKey = null;
  3675. const cacheSubtree = () => {
  3676. // fix #1621, the pendingCacheKey could be 0
  3677. if (pendingCacheKey != null) {
  3678. cache.set(pendingCacheKey, getInnerChild(instance.subTree));
  3679. }
  3680. };
  3681. onMounted(cacheSubtree);
  3682. onUpdated(cacheSubtree);
  3683. onBeforeUnmount(() => {
  3684. cache.forEach(cached => {
  3685. const { subTree, suspense } = instance;
  3686. const vnode = getInnerChild(subTree);
  3687. if (cached.type === vnode.type) {
  3688. // current instance will be unmounted as part of keep-alive's unmount
  3689. resetShapeFlag(vnode);
  3690. // but invoke its deactivated hook here
  3691. const da = vnode.component.da;
  3692. da && queuePostRenderEffect(da, suspense);
  3693. return;
  3694. }
  3695. unmount(cached);
  3696. });
  3697. });
  3698. return () => {
  3699. pendingCacheKey = null;
  3700. if (!slots.default) {
  3701. return null;
  3702. }
  3703. const children = slots.default();
  3704. const rawVNode = children[0];
  3705. if (children.length > 1) {
  3706. {
  3707. warn(`KeepAlive should contain exactly one component child.`);
  3708. }
  3709. current = null;
  3710. return children;
  3711. }
  3712. else if (!isVNode(rawVNode) ||
  3713. (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
  3714. !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
  3715. current = null;
  3716. return rawVNode;
  3717. }
  3718. let vnode = getInnerChild(rawVNode);
  3719. const comp = vnode.type;
  3720. const name = getName(comp);
  3721. const { include, exclude, max } = props;
  3722. if ((include && (!name || !matches(include, name))) ||
  3723. (exclude && name && matches(exclude, name))) {
  3724. current = vnode;
  3725. return rawVNode;
  3726. }
  3727. const key = vnode.key == null ? comp : vnode.key;
  3728. const cachedVNode = cache.get(key);
  3729. // clone vnode if it's reused because we are going to mutate it
  3730. if (vnode.el) {
  3731. vnode = cloneVNode(vnode);
  3732. if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
  3733. rawVNode.ssContent = vnode;
  3734. }
  3735. }
  3736. // #1513 it's possible for the returned vnode to be cloned due to attr
  3737. // fallthrough or scopeId, so the vnode here may not be the final vnode
  3738. // that is mounted. Instead of caching it directly, we store the pending
  3739. // key and cache `instance.subTree` (the normalized vnode) in
  3740. // beforeMount/beforeUpdate hooks.
  3741. pendingCacheKey = key;
  3742. if (cachedVNode) {
  3743. // copy over mounted state
  3744. vnode.el = cachedVNode.el;
  3745. vnode.component = cachedVNode.component;
  3746. if (vnode.transition) {
  3747. // recursively update transition hooks on subTree
  3748. setTransitionHooks(vnode, vnode.transition);
  3749. }
  3750. // avoid vnode being mounted as fresh
  3751. vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
  3752. // make this key the freshest
  3753. keys.delete(key);
  3754. keys.add(key);
  3755. }
  3756. else {
  3757. keys.add(key);
  3758. // prune oldest entry
  3759. if (max && keys.size > parseInt(max, 10)) {
  3760. pruneCacheEntry(keys.values().next().value);
  3761. }
  3762. }
  3763. // avoid vnode being unmounted
  3764. vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
  3765. current = vnode;
  3766. return rawVNode;
  3767. };
  3768. }
  3769. };
  3770. // export the public type for h/tsx inference
  3771. // also to avoid inline import() in generated d.ts files
  3772. const KeepAlive = KeepAliveImpl;
  3773. function getName(comp) {
  3774. return comp.displayName || comp.name;
  3775. }
  3776. function matches(pattern, name) {
  3777. if (isArray(pattern)) {
  3778. return pattern.some((p) => matches(p, name));
  3779. }
  3780. else if (isString(pattern)) {
  3781. return pattern.split(',').indexOf(name) > -1;
  3782. }
  3783. else if (pattern.test) {
  3784. return pattern.test(name);
  3785. }
  3786. /* istanbul ignore next */
  3787. return false;
  3788. }
  3789. function onActivated(hook, target) {
  3790. registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
  3791. }
  3792. function onDeactivated(hook, target) {
  3793. registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
  3794. }
  3795. function registerKeepAliveHook(hook, type, target = currentInstance) {
  3796. // cache the deactivate branch check wrapper for injected hooks so the same
  3797. // hook can be properly deduped by the scheduler. "__wdc" stands for "with
  3798. // deactivation check".
  3799. const wrappedHook = hook.__wdc ||
  3800. (hook.__wdc = () => {
  3801. // only fire the hook if the target instance is NOT in a deactivated branch.
  3802. let current = target;
  3803. while (current) {
  3804. if (current.isDeactivated) {
  3805. return;
  3806. }
  3807. current = current.parent;
  3808. }
  3809. hook();
  3810. });
  3811. injectHook(type, wrappedHook, target);
  3812. // In addition to registering it on the target instance, we walk up the parent
  3813. // chain and register it on all ancestor instances that are keep-alive roots.
  3814. // This avoids the need to walk the entire component tree when invoking these
  3815. // hooks, and more importantly, avoids the need to track child components in
  3816. // arrays.
  3817. if (target) {
  3818. let current = target.parent;
  3819. while (current && current.parent) {
  3820. if (isKeepAlive(current.parent.vnode)) {
  3821. injectToKeepAliveRoot(wrappedHook, type, target, current);
  3822. }
  3823. current = current.parent;
  3824. }
  3825. }
  3826. }
  3827. function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
  3828. // injectHook wraps the original for error handling, so make sure to remove
  3829. // the wrapped version.
  3830. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
  3831. onUnmounted(() => {
  3832. remove(keepAliveRoot[type], injected);
  3833. }, target);
  3834. }
  3835. function resetShapeFlag(vnode) {
  3836. let shapeFlag = vnode.shapeFlag;
  3837. if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  3838. shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
  3839. }
  3840. if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
  3841. shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
  3842. }
  3843. vnode.shapeFlag = shapeFlag;
  3844. }
  3845. function getInnerChild(vnode) {
  3846. return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
  3847. }
  3848. const isInternalKey = (key) => key[0] === '_' || key === '$stable';
  3849. const normalizeSlotValue = (value) => isArray(value)
  3850. ? value.map(normalizeVNode)
  3851. : [normalizeVNode(value)];
  3852. const normalizeSlot = (key, rawSlot, ctx) => withCtx((props) => {
  3853. if ( currentInstance) {
  3854. warn(`Slot "${key}" invoked outside of the render function: ` +
  3855. `this will not track dependencies used in the slot. ` +
  3856. `Invoke the slot function inside the render function instead.`);
  3857. }
  3858. return normalizeSlotValue(rawSlot(props));
  3859. }, ctx);
  3860. const normalizeObjectSlots = (rawSlots, slots) => {
  3861. const ctx = rawSlots._ctx;
  3862. for (const key in rawSlots) {
  3863. if (isInternalKey(key))
  3864. continue;
  3865. const value = rawSlots[key];
  3866. if (isFunction(value)) {
  3867. slots[key] = normalizeSlot(key, value, ctx);
  3868. }
  3869. else if (value != null) {
  3870. {
  3871. warn(`Non-function value encountered for slot "${key}". ` +
  3872. `Prefer function slots for better performance.`);
  3873. }
  3874. const normalized = normalizeSlotValue(value);
  3875. slots[key] = () => normalized;
  3876. }
  3877. }
  3878. };
  3879. const normalizeVNodeSlots = (instance, children) => {
  3880. if ( !isKeepAlive(instance.vnode)) {
  3881. warn(`Non-function value encountered for default slot. ` +
  3882. `Prefer function slots for better performance.`);
  3883. }
  3884. const normalized = normalizeSlotValue(children);
  3885. instance.slots.default = () => normalized;
  3886. };
  3887. const initSlots = (instance, children) => {
  3888. if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
  3889. const type = children._;
  3890. if (type) {
  3891. instance.slots = children;
  3892. // make compiler marker non-enumerable
  3893. def(children, '_', type);
  3894. }
  3895. else {
  3896. normalizeObjectSlots(children, (instance.slots = {}));
  3897. }
  3898. }
  3899. else {
  3900. instance.slots = {};
  3901. if (children) {
  3902. normalizeVNodeSlots(instance, children);
  3903. }
  3904. }
  3905. def(instance.slots, InternalObjectKey, 1);
  3906. };
  3907. const updateSlots = (instance, children) => {
  3908. const { vnode, slots } = instance;
  3909. let needDeletionCheck = true;
  3910. let deletionComparisonTarget = EMPTY_OBJ;
  3911. if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
  3912. const type = children._;
  3913. if (type) {
  3914. // compiled slots.
  3915. if ( isHmrUpdating) {
  3916. // Parent was HMR updated so slot content may have changed.
  3917. // force update slots and mark instance for hmr as well
  3918. extend(slots, children);
  3919. }
  3920. else if (type === 1 /* STABLE */) {
  3921. // compiled AND stable.
  3922. // no need to update, and skip stale slots removal.
  3923. needDeletionCheck = false;
  3924. }
  3925. else {
  3926. // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
  3927. // normalization.
  3928. extend(slots, children);
  3929. }
  3930. }
  3931. else {
  3932. needDeletionCheck = !children.$stable;
  3933. normalizeObjectSlots(children, slots);
  3934. }
  3935. deletionComparisonTarget = children;
  3936. }
  3937. else if (children) {
  3938. // non slot object children (direct value) passed to a component
  3939. normalizeVNodeSlots(instance, children);
  3940. deletionComparisonTarget = { default: 1 };
  3941. }
  3942. // delete stale slots
  3943. if (needDeletionCheck) {
  3944. for (const key in slots) {
  3945. if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
  3946. delete slots[key];
  3947. }
  3948. }
  3949. }
  3950. };
  3951. /**
  3952. Runtime helper for applying directives to a vnode. Example usage:
  3953. const comp = resolveComponent('comp')
  3954. const foo = resolveDirective('foo')
  3955. const bar = resolveDirective('bar')
  3956. return withDirectives(h(comp), [
  3957. [foo, this.x],
  3958. [bar, this.y]
  3959. ])
  3960. */
  3961. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');
  3962. function validateDirectiveName(name) {
  3963. if (isBuiltInDirective(name)) {
  3964. warn('Do not use built-in directive ids as custom directive id: ' + name);
  3965. }
  3966. }
  3967. /**
  3968. * Adds directives to a VNode.
  3969. */
  3970. function withDirectives(vnode, directives) {
  3971. const internalInstance = currentRenderingInstance;
  3972. if (internalInstance === null) {
  3973. warn(`withDirectives can only be used inside render functions.`);
  3974. return vnode;
  3975. }
  3976. const instance = internalInstance.proxy;
  3977. const bindings = vnode.dirs || (vnode.dirs = []);
  3978. for (let i = 0; i < directives.length; i++) {
  3979. let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
  3980. if (isFunction(dir)) {
  3981. dir = {
  3982. mounted: dir,
  3983. updated: dir
  3984. };
  3985. }
  3986. bindings.push({
  3987. dir,
  3988. instance,
  3989. value,
  3990. oldValue: void 0,
  3991. arg,
  3992. modifiers
  3993. });
  3994. }
  3995. return vnode;
  3996. }
  3997. function invokeDirectiveHook(vnode, prevVNode, instance, name) {
  3998. const bindings = vnode.dirs;
  3999. const oldBindings = prevVNode && prevVNode.dirs;
  4000. for (let i = 0; i < bindings.length; i++) {
  4001. const binding = bindings[i];
  4002. if (oldBindings) {
  4003. binding.oldValue = oldBindings[i].value;
  4004. }
  4005. const hook = binding.dir[name];
  4006. if (hook) {
  4007. callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
  4008. vnode.el,
  4009. binding,
  4010. vnode,
  4011. prevVNode
  4012. ]);
  4013. }
  4014. }
  4015. }
  4016. function createAppContext() {
  4017. return {
  4018. app: null,
  4019. config: {
  4020. isNativeTag: NO,
  4021. performance: false,
  4022. globalProperties: {},
  4023. optionMergeStrategies: {},
  4024. isCustomElement: NO,
  4025. errorHandler: undefined,
  4026. warnHandler: undefined
  4027. },
  4028. mixins: [],
  4029. components: {},
  4030. directives: {},
  4031. provides: Object.create(null)
  4032. };
  4033. }
  4034. let uid$1 = 0;
  4035. function createAppAPI(render, hydrate) {
  4036. return function createApp(rootComponent, rootProps = null) {
  4037. if (rootProps != null && !isObject(rootProps)) {
  4038. warn(`root props passed to app.mount() must be an object.`);
  4039. rootProps = null;
  4040. }
  4041. const context = createAppContext();
  4042. const installedPlugins = new Set();
  4043. let isMounted = false;
  4044. const app = (context.app = {
  4045. _uid: uid$1++,
  4046. _component: rootComponent,
  4047. _props: rootProps,
  4048. _container: null,
  4049. _context: context,
  4050. version,
  4051. get config() {
  4052. return context.config;
  4053. },
  4054. set config(v) {
  4055. {
  4056. warn(`app.config cannot be replaced. Modify individual options instead.`);
  4057. }
  4058. },
  4059. use(plugin, ...options) {
  4060. if (installedPlugins.has(plugin)) {
  4061. warn(`Plugin has already been applied to target app.`);
  4062. }
  4063. else if (plugin && isFunction(plugin.install)) {
  4064. installedPlugins.add(plugin);
  4065. plugin.install(app, ...options);
  4066. }
  4067. else if (isFunction(plugin)) {
  4068. installedPlugins.add(plugin);
  4069. plugin(app, ...options);
  4070. }
  4071. else {
  4072. warn(`A plugin must either be a function or an object with an "install" ` +
  4073. `function.`);
  4074. }
  4075. return app;
  4076. },
  4077. mixin(mixin) {
  4078. {
  4079. if (!context.mixins.includes(mixin)) {
  4080. context.mixins.push(mixin);
  4081. // global mixin with props/emits de-optimizes props/emits
  4082. // normalization caching.
  4083. if (mixin.props || mixin.emits) {
  4084. context.deopt = true;
  4085. }
  4086. }
  4087. else {
  4088. warn('Mixin has already been applied to target app' +
  4089. (mixin.name ? `: ${mixin.name}` : ''));
  4090. }
  4091. }
  4092. return app;
  4093. },
  4094. component(name, component) {
  4095. {
  4096. validateComponentName(name, context.config);
  4097. }
  4098. if (!component) {
  4099. return context.components[name];
  4100. }
  4101. if ( context.components[name]) {
  4102. warn(`Component "${name}" has already been registered in target app.`);
  4103. }
  4104. context.components[name] = component;
  4105. return app;
  4106. },
  4107. directive(name, directive) {
  4108. {
  4109. validateDirectiveName(name);
  4110. }
  4111. if (!directive) {
  4112. return context.directives[name];
  4113. }
  4114. if ( context.directives[name]) {
  4115. warn(`Directive "${name}" has already been registered in target app.`);
  4116. }
  4117. context.directives[name] = directive;
  4118. return app;
  4119. },
  4120. mount(rootContainer, isHydrate) {
  4121. if (!isMounted) {
  4122. const vnode = createVNode(rootComponent, rootProps);
  4123. // store app context on the root VNode.
  4124. // this will be set on the root instance on initial mount.
  4125. vnode.appContext = context;
  4126. // HMR root reload
  4127. {
  4128. context.reload = () => {
  4129. render(cloneVNode(vnode), rootContainer);
  4130. };
  4131. }
  4132. if (isHydrate && hydrate) {
  4133. hydrate(vnode, rootContainer);
  4134. }
  4135. else {
  4136. render(vnode, rootContainer);
  4137. }
  4138. isMounted = true;
  4139. app._container = rootContainer;
  4140. rootContainer.__vue_app__ = app;
  4141. {
  4142. devtoolsInitApp(app, version);
  4143. }
  4144. return vnode.component.proxy;
  4145. }
  4146. else {
  4147. warn(`App has already been mounted.\n` +
  4148. `If you want to remount the same app, move your app creation logic ` +
  4149. `into a factory function and create fresh app instances for each ` +
  4150. `mount - e.g. \`const createMyApp = () => createApp(App)\``);
  4151. }
  4152. },
  4153. unmount() {
  4154. if (isMounted) {
  4155. render(null, app._container);
  4156. {
  4157. devtoolsUnmountApp(app);
  4158. }
  4159. }
  4160. else {
  4161. warn(`Cannot unmount an app that is not mounted.`);
  4162. }
  4163. },
  4164. provide(key, value) {
  4165. if ( key in context.provides) {
  4166. warn(`App already provides property with key "${String(key)}". ` +
  4167. `It will be overwritten with the new value.`);
  4168. }
  4169. // TypeScript doesn't allow symbols as index type
  4170. // https://github.com/Microsoft/TypeScript/issues/24587
  4171. context.provides[key] = value;
  4172. return app;
  4173. }
  4174. });
  4175. return app;
  4176. };
  4177. }
  4178. let hasMismatch = false;
  4179. const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
  4180. const isComment = (node) => node.nodeType === 8 /* COMMENT */;
  4181. // Note: hydration is DOM-specific
  4182. // But we have to place it in core due to tight coupling with core - splitting
  4183. // it out creates a ton of unnecessary complexity.
  4184. // Hydration also depends on some renderer internal logic which needs to be
  4185. // passed in via arguments.
  4186. function createHydrationFunctions(rendererInternals) {
  4187. const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
  4188. const hydrate = (vnode, container) => {
  4189. if ( !container.hasChildNodes()) {
  4190. warn(`Attempting to hydrate existing markup but container is empty. ` +
  4191. `Performing full mount instead.`);
  4192. patch(null, vnode, container);
  4193. return;
  4194. }
  4195. hasMismatch = false;
  4196. hydrateNode(container.firstChild, vnode, null, null);
  4197. flushPostFlushCbs();
  4198. if (hasMismatch && !false) {
  4199. // this error should show up in production
  4200. console.error(`Hydration completed but contains mismatches.`);
  4201. }
  4202. };
  4203. const hydrateNode = (node, vnode, parentComponent, parentSuspense, optimized = false) => {
  4204. const isFragmentStart = isComment(node) && node.data === '[';
  4205. const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, isFragmentStart);
  4206. const { type, ref, shapeFlag } = vnode;
  4207. const domType = node.nodeType;
  4208. vnode.el = node;
  4209. let nextNode = null;
  4210. switch (type) {
  4211. case Text:
  4212. if (domType !== 3 /* TEXT */) {
  4213. nextNode = onMismatch();
  4214. }
  4215. else {
  4216. if (node.data !== vnode.children) {
  4217. hasMismatch = true;
  4218. warn(`Hydration text mismatch:` +
  4219. `\n- Client: ${JSON.stringify(node.data)}` +
  4220. `\n- Server: ${JSON.stringify(vnode.children)}`);
  4221. node.data = vnode.children;
  4222. }
  4223. nextNode = nextSibling(node);
  4224. }
  4225. break;
  4226. case Comment:
  4227. if (domType !== 8 /* COMMENT */ || isFragmentStart) {
  4228. nextNode = onMismatch();
  4229. }
  4230. else {
  4231. nextNode = nextSibling(node);
  4232. }
  4233. break;
  4234. case Static:
  4235. if (domType !== 1 /* ELEMENT */) {
  4236. nextNode = onMismatch();
  4237. }
  4238. else {
  4239. // determine anchor, adopt content
  4240. nextNode = node;
  4241. // if the static vnode has its content stripped during build,
  4242. // adopt it from the server-rendered HTML.
  4243. const needToAdoptContent = !vnode.children.length;
  4244. for (let i = 0; i < vnode.staticCount; i++) {
  4245. if (needToAdoptContent)
  4246. vnode.children += nextNode.outerHTML;
  4247. if (i === vnode.staticCount - 1) {
  4248. vnode.anchor = nextNode;
  4249. }
  4250. nextNode = nextSibling(nextNode);
  4251. }
  4252. return nextNode;
  4253. }
  4254. break;
  4255. case Fragment:
  4256. if (!isFragmentStart) {
  4257. nextNode = onMismatch();
  4258. }
  4259. else {
  4260. nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, optimized);
  4261. }
  4262. break;
  4263. default:
  4264. if (shapeFlag & 1 /* ELEMENT */) {
  4265. if (domType !== 1 /* ELEMENT */ ||
  4266. vnode.type !== node.tagName.toLowerCase()) {
  4267. nextNode = onMismatch();
  4268. }
  4269. else {
  4270. nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, optimized);
  4271. }
  4272. }
  4273. else if (shapeFlag & 6 /* COMPONENT */) {
  4274. // when setting up the render effect, if the initial vnode already
  4275. // has .el set, the component will perform hydration instead of mount
  4276. // on its sub-tree.
  4277. const container = parentNode(node);
  4278. const hydrateComponent = () => {
  4279. mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
  4280. };
  4281. // async component
  4282. const loadAsync = vnode.type.__asyncLoader;
  4283. if (loadAsync) {
  4284. loadAsync().then(hydrateComponent);
  4285. }
  4286. else {
  4287. hydrateComponent();
  4288. }
  4289. // component may be async, so in the case of fragments we cannot rely
  4290. // on component's rendered output to determine the end of the fragment
  4291. // instead, we do a lookahead to find the end anchor node.
  4292. nextNode = isFragmentStart
  4293. ? locateClosingAsyncAnchor(node)
  4294. : nextSibling(node);
  4295. }
  4296. else if (shapeFlag & 64 /* TELEPORT */) {
  4297. if (domType !== 8 /* COMMENT */) {
  4298. nextNode = onMismatch();
  4299. }
  4300. else {
  4301. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, optimized, rendererInternals, hydrateChildren);
  4302. }
  4303. }
  4304. else if ( shapeFlag & 128 /* SUSPENSE */) {
  4305. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), optimized, rendererInternals, hydrateNode);
  4306. }
  4307. else {
  4308. warn('Invalid HostVNode type:', type, `(${typeof type})`);
  4309. }
  4310. }
  4311. if (ref != null && parentComponent) {
  4312. setRef(ref, null, parentComponent, parentSuspense, vnode);
  4313. }
  4314. return nextNode;
  4315. };
  4316. const hydrateElement = (el, vnode, parentComponent, parentSuspense, optimized) => {
  4317. optimized = optimized || !!vnode.dynamicChildren;
  4318. const { props, patchFlag, shapeFlag, dirs } = vnode;
  4319. // skip props & children if this is hoisted static nodes
  4320. if (patchFlag !== -1 /* HOISTED */) {
  4321. if (dirs) {
  4322. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  4323. }
  4324. // props
  4325. if (props) {
  4326. if (!optimized ||
  4327. (patchFlag & 16 /* FULL_PROPS */ ||
  4328. patchFlag & 32 /* HYDRATE_EVENTS */)) {
  4329. for (const key in props) {
  4330. if (!isReservedProp(key) && isOn(key)) {
  4331. patchProp(el, key, null, props[key]);
  4332. }
  4333. }
  4334. }
  4335. else if (props.onClick) {
  4336. // Fast path for click listeners (which is most often) to avoid
  4337. // iterating through props.
  4338. patchProp(el, 'onClick', null, props.onClick);
  4339. }
  4340. }
  4341. // vnode / directive hooks
  4342. let vnodeHooks;
  4343. if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
  4344. invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  4345. }
  4346. if (dirs) {
  4347. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  4348. }
  4349. if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
  4350. queueEffectWithSuspense(() => {
  4351. vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  4352. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  4353. }, parentSuspense);
  4354. }
  4355. // children
  4356. if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
  4357. // skip if element has innerHTML / textContent
  4358. !(props && (props.innerHTML || props.textContent))) {
  4359. let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, optimized);
  4360. let hasWarned = false;
  4361. while (next) {
  4362. hasMismatch = true;
  4363. if ( !hasWarned) {
  4364. warn(`Hydration children mismatch in <${vnode.type}>: ` +
  4365. `server rendered element contains more child nodes than client vdom.`);
  4366. hasWarned = true;
  4367. }
  4368. // The SSRed DOM contains more nodes than it should. Remove them.
  4369. const cur = next;
  4370. next = next.nextSibling;
  4371. remove(cur);
  4372. }
  4373. }
  4374. else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  4375. if (el.textContent !== vnode.children) {
  4376. hasMismatch = true;
  4377. warn(`Hydration text content mismatch in <${vnode.type}>:\n` +
  4378. `- Client: ${el.textContent}\n` +
  4379. `- Server: ${vnode.children}`);
  4380. el.textContent = vnode.children;
  4381. }
  4382. }
  4383. }
  4384. return el.nextSibling;
  4385. };
  4386. const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, optimized) => {
  4387. optimized = optimized || !!parentVNode.dynamicChildren;
  4388. const children = parentVNode.children;
  4389. const l = children.length;
  4390. let hasWarned = false;
  4391. for (let i = 0; i < l; i++) {
  4392. const vnode = optimized
  4393. ? children[i]
  4394. : (children[i] = normalizeVNode(children[i]));
  4395. if (node) {
  4396. node = hydrateNode(node, vnode, parentComponent, parentSuspense, optimized);
  4397. }
  4398. else {
  4399. hasMismatch = true;
  4400. if ( !hasWarned) {
  4401. warn(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
  4402. `server rendered element contains fewer child nodes than client vdom.`);
  4403. hasWarned = true;
  4404. }
  4405. // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
  4406. patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container));
  4407. }
  4408. }
  4409. return node;
  4410. };
  4411. const hydrateFragment = (node, vnode, parentComponent, parentSuspense, optimized) => {
  4412. const container = parentNode(node);
  4413. const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, optimized);
  4414. if (next && isComment(next) && next.data === ']') {
  4415. return nextSibling((vnode.anchor = next));
  4416. }
  4417. else {
  4418. // fragment didn't hydrate successfully, since we didn't get a end anchor
  4419. // back. This should have led to node/children mismatch warnings.
  4420. hasMismatch = true;
  4421. // since the anchor is missing, we need to create one and insert it
  4422. insert((vnode.anchor = createComment(`]`)), container, next);
  4423. return next;
  4424. }
  4425. };
  4426. const handleMismatch = (node, vnode, parentComponent, parentSuspense, isFragment) => {
  4427. hasMismatch = true;
  4428. warn(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
  4429. ? `(text)`
  4430. : isComment(node) && node.data === '['
  4431. ? `(start of fragment)`
  4432. : ``);
  4433. vnode.el = null;
  4434. if (isFragment) {
  4435. // remove excessive fragment nodes
  4436. const end = locateClosingAsyncAnchor(node);
  4437. while (true) {
  4438. const next = nextSibling(node);
  4439. if (next && next !== end) {
  4440. remove(next);
  4441. }
  4442. else {
  4443. break;
  4444. }
  4445. }
  4446. }
  4447. const next = nextSibling(node);
  4448. const container = parentNode(node);
  4449. remove(node);
  4450. patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container));
  4451. return next;
  4452. };
  4453. const locateClosingAsyncAnchor = (node) => {
  4454. let match = 0;
  4455. while (node) {
  4456. node = nextSibling(node);
  4457. if (node && isComment(node)) {
  4458. if (node.data === '[')
  4459. match++;
  4460. if (node.data === ']') {
  4461. if (match === 0) {
  4462. return nextSibling(node);
  4463. }
  4464. else {
  4465. match--;
  4466. }
  4467. }
  4468. }
  4469. }
  4470. return node;
  4471. };
  4472. return [hydrate, hydrateNode];
  4473. }
  4474. let supported;
  4475. let perf;
  4476. function startMeasure(instance, type) {
  4477. if (instance.appContext.config.performance && isSupported()) {
  4478. perf.mark(`vue-${type}-${instance.uid}`);
  4479. }
  4480. }
  4481. function endMeasure(instance, type) {
  4482. if (instance.appContext.config.performance && isSupported()) {
  4483. const startTag = `vue-${type}-${instance.uid}`;
  4484. const endTag = startTag + `:end`;
  4485. perf.mark(endTag);
  4486. perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
  4487. perf.clearMarks(startTag);
  4488. perf.clearMarks(endTag);
  4489. }
  4490. }
  4491. function isSupported() {
  4492. if (supported !== undefined) {
  4493. return supported;
  4494. }
  4495. /* eslint-disable no-restricted-globals */
  4496. if (typeof window !== 'undefined' && window.performance) {
  4497. supported = true;
  4498. perf = window.performance;
  4499. }
  4500. else {
  4501. supported = false;
  4502. }
  4503. /* eslint-enable no-restricted-globals */
  4504. return supported;
  4505. }
  4506. function createDevEffectOptions(instance) {
  4507. return {
  4508. scheduler: queueJob,
  4509. allowRecurse: true,
  4510. onTrack: instance.rtc ? e => invokeArrayFns(instance.rtc, e) : void 0,
  4511. onTrigger: instance.rtg ? e => invokeArrayFns(instance.rtg, e) : void 0
  4512. };
  4513. }
  4514. const queuePostRenderEffect = queueEffectWithSuspense
  4515. ;
  4516. const setRef = (rawRef, oldRawRef, parentComponent, parentSuspense, vnode) => {
  4517. if (isArray(rawRef)) {
  4518. rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentComponent, parentSuspense, vnode));
  4519. return;
  4520. }
  4521. let value;
  4522. if (!vnode) {
  4523. value = null;
  4524. }
  4525. else {
  4526. if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
  4527. value = vnode.component.proxy;
  4528. }
  4529. else {
  4530. value = vnode.el;
  4531. }
  4532. }
  4533. const { i: owner, r: ref } = rawRef;
  4534. if ( !owner) {
  4535. warn(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
  4536. `A vnode with ref must be created inside the render function.`);
  4537. return;
  4538. }
  4539. const oldRef = oldRawRef && oldRawRef.r;
  4540. const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
  4541. const setupState = owner.setupState;
  4542. // unset old ref
  4543. if (oldRef != null && oldRef !== ref) {
  4544. if (isString(oldRef)) {
  4545. refs[oldRef] = null;
  4546. if (hasOwn(setupState, oldRef)) {
  4547. setupState[oldRef] = null;
  4548. }
  4549. }
  4550. else if (isRef(oldRef)) {
  4551. oldRef.value = null;
  4552. }
  4553. }
  4554. if (isString(ref)) {
  4555. const doSet = () => {
  4556. refs[ref] = value;
  4557. if (hasOwn(setupState, ref)) {
  4558. setupState[ref] = value;
  4559. }
  4560. };
  4561. // #1789: for non-null values, set them after render
  4562. // null values means this is unmount and it should not overwrite another
  4563. // ref with the same key
  4564. if (value) {
  4565. doSet.id = -1;
  4566. queuePostRenderEffect(doSet, parentSuspense);
  4567. }
  4568. else {
  4569. doSet();
  4570. }
  4571. }
  4572. else if (isRef(ref)) {
  4573. const doSet = () => {
  4574. ref.value = value;
  4575. };
  4576. if (value) {
  4577. doSet.id = -1;
  4578. queuePostRenderEffect(doSet, parentSuspense);
  4579. }
  4580. else {
  4581. doSet();
  4582. }
  4583. }
  4584. else if (isFunction(ref)) {
  4585. callWithErrorHandling(ref, parentComponent, 12 /* FUNCTION_REF */, [
  4586. value,
  4587. refs
  4588. ]);
  4589. }
  4590. else {
  4591. warn('Invalid template ref type:', value, `(${typeof value})`);
  4592. }
  4593. };
  4594. /**
  4595. * The createRenderer function accepts two generic arguments:
  4596. * HostNode and HostElement, corresponding to Node and Element types in the
  4597. * host environment. For example, for runtime-dom, HostNode would be the DOM
  4598. * `Node` interface and HostElement would be the DOM `Element` interface.
  4599. *
  4600. * Custom renderers can pass in the platform specific types like this:
  4601. *
  4602. * ``` js
  4603. * const { render, createApp } = createRenderer<Node, Element>({
  4604. * patchProp,
  4605. * ...nodeOps
  4606. * })
  4607. * ```
  4608. */
  4609. function createRenderer(options) {
  4610. return baseCreateRenderer(options);
  4611. }
  4612. // Separate API for creating hydration-enabled renderer.
  4613. // Hydration logic is only used when calling this function, making it
  4614. // tree-shakable.
  4615. function createHydrationRenderer(options) {
  4616. return baseCreateRenderer(options, createHydrationFunctions);
  4617. }
  4618. // implementation
  4619. function baseCreateRenderer(options, createHydrationFns) {
  4620. const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, forcePatchProp: hostForcePatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
  4621. // Note: functions inside this closure should use `const xxx = () => {}`
  4622. // style in order to prevent being inlined by minifiers.
  4623. const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, optimized = false) => {
  4624. // patching & not same type, unmount old tree
  4625. if (n1 && !isSameVNodeType(n1, n2)) {
  4626. anchor = getNextHostNode(n1);
  4627. unmount(n1, parentComponent, parentSuspense, true);
  4628. n1 = null;
  4629. }
  4630. if (n2.patchFlag === -2 /* BAIL */) {
  4631. optimized = false;
  4632. n2.dynamicChildren = null;
  4633. }
  4634. const { type, ref, shapeFlag } = n2;
  4635. switch (type) {
  4636. case Text:
  4637. processText(n1, n2, container, anchor);
  4638. break;
  4639. case Comment:
  4640. processCommentNode(n1, n2, container, anchor);
  4641. break;
  4642. case Static:
  4643. if (n1 == null) {
  4644. mountStaticNode(n2, container, anchor, isSVG);
  4645. }
  4646. else {
  4647. patchStaticNode(n1, n2, container, isSVG);
  4648. }
  4649. break;
  4650. case Fragment:
  4651. processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4652. break;
  4653. default:
  4654. if (shapeFlag & 1 /* ELEMENT */) {
  4655. processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4656. }
  4657. else if (shapeFlag & 6 /* COMPONENT */) {
  4658. processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4659. }
  4660. else if (shapeFlag & 64 /* TELEPORT */) {
  4661. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals);
  4662. }
  4663. else if ( shapeFlag & 128 /* SUSPENSE */) {
  4664. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals);
  4665. }
  4666. else {
  4667. warn('Invalid VNode type:', type, `(${typeof type})`);
  4668. }
  4669. }
  4670. // set ref
  4671. if (ref != null && parentComponent) {
  4672. setRef(ref, n1 && n1.ref, parentComponent, parentSuspense, n2);
  4673. }
  4674. };
  4675. const processText = (n1, n2, container, anchor) => {
  4676. if (n1 == null) {
  4677. hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
  4678. }
  4679. else {
  4680. const el = (n2.el = n1.el);
  4681. if (n2.children !== n1.children) {
  4682. hostSetText(el, n2.children);
  4683. }
  4684. }
  4685. };
  4686. const processCommentNode = (n1, n2, container, anchor) => {
  4687. if (n1 == null) {
  4688. hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
  4689. }
  4690. else {
  4691. // there's no support for dynamic comments
  4692. n2.el = n1.el;
  4693. }
  4694. };
  4695. const mountStaticNode = (n2, container, anchor, isSVG) => {
  4696. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  4697. };
  4698. /**
  4699. * Dev / HMR only
  4700. */
  4701. const patchStaticNode = (n1, n2, container, isSVG) => {
  4702. // static nodes are only patched during dev for HMR
  4703. if (n2.children !== n1.children) {
  4704. const anchor = hostNextSibling(n1.anchor);
  4705. // remove existing
  4706. removeStaticNode(n1);
  4707. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  4708. }
  4709. else {
  4710. n2.el = n1.el;
  4711. n2.anchor = n1.anchor;
  4712. }
  4713. };
  4714. /**
  4715. * Dev / HMR only
  4716. */
  4717. const moveStaticNode = (vnode, container, anchor) => {
  4718. let cur = vnode.el;
  4719. const end = vnode.anchor;
  4720. while (cur && cur !== end) {
  4721. const next = hostNextSibling(cur);
  4722. hostInsert(cur, container, anchor);
  4723. cur = next;
  4724. }
  4725. hostInsert(end, container, anchor);
  4726. };
  4727. /**
  4728. * Dev / HMR only
  4729. */
  4730. const removeStaticNode = (vnode) => {
  4731. let cur = vnode.el;
  4732. while (cur && cur !== vnode.anchor) {
  4733. const next = hostNextSibling(cur);
  4734. hostRemove(cur);
  4735. cur = next;
  4736. }
  4737. hostRemove(vnode.anchor);
  4738. };
  4739. const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  4740. isSVG = isSVG || n2.type === 'svg';
  4741. if (n1 == null) {
  4742. mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4743. }
  4744. else {
  4745. patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized);
  4746. }
  4747. };
  4748. const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  4749. let el;
  4750. let vnodeHook;
  4751. const { type, props, shapeFlag, transition, scopeId, patchFlag, dirs } = vnode;
  4752. {
  4753. el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is);
  4754. // mount children first, since some props may rely on child content
  4755. // being already rendered, e.g. `<select value>`
  4756. if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  4757. hostSetElementText(el, vnode.children);
  4758. }
  4759. else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  4760. mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', optimized || !!vnode.dynamicChildren);
  4761. }
  4762. if (dirs) {
  4763. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  4764. }
  4765. // props
  4766. if (props) {
  4767. for (const key in props) {
  4768. if (!isReservedProp(key)) {
  4769. hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  4770. }
  4771. }
  4772. if ((vnodeHook = props.onVnodeBeforeMount)) {
  4773. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  4774. }
  4775. }
  4776. // scopeId
  4777. setScopeId(el, scopeId, vnode, parentComponent);
  4778. }
  4779. {
  4780. Object.defineProperty(el, '__vnode', {
  4781. value: vnode,
  4782. enumerable: false
  4783. });
  4784. Object.defineProperty(el, '__vueParentComponent', {
  4785. value: parentComponent,
  4786. enumerable: false
  4787. });
  4788. }
  4789. if (dirs) {
  4790. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  4791. }
  4792. // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
  4793. // #1689 For inside suspense + suspense resolved case, just call it
  4794. const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
  4795. transition &&
  4796. !transition.persisted;
  4797. if (needCallTransitionHooks) {
  4798. transition.beforeEnter(el);
  4799. }
  4800. hostInsert(el, container, anchor);
  4801. if ((vnodeHook = props && props.onVnodeMounted) ||
  4802. needCallTransitionHooks ||
  4803. dirs) {
  4804. queuePostRenderEffect(() => {
  4805. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  4806. needCallTransitionHooks && transition.enter(el);
  4807. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  4808. }, parentSuspense);
  4809. }
  4810. };
  4811. const setScopeId = (el, scopeId, vnode, parentComponent) => {
  4812. if (scopeId) {
  4813. hostSetScopeId(el, scopeId);
  4814. }
  4815. if (parentComponent) {
  4816. const treeOwnerId = parentComponent.type.__scopeId;
  4817. // vnode's own scopeId and the current patched component's scopeId is
  4818. // different - this is a slot content node.
  4819. if (treeOwnerId && treeOwnerId !== scopeId) {
  4820. hostSetScopeId(el, treeOwnerId + '-s');
  4821. }
  4822. let subTree = parentComponent.subTree;
  4823. if ( subTree.type === Fragment) {
  4824. subTree =
  4825. filterSingleRoot(subTree.children) || subTree;
  4826. }
  4827. if (vnode === subTree) {
  4828. setScopeId(el, parentComponent.vnode.scopeId, parentComponent.vnode, parentComponent.parent);
  4829. }
  4830. }
  4831. };
  4832. const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, optimized, start = 0) => {
  4833. for (let i = start; i < children.length; i++) {
  4834. const child = (children[i] = optimized
  4835. ? cloneIfMounted(children[i])
  4836. : normalizeVNode(children[i]));
  4837. patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4838. }
  4839. };
  4840. const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, optimized) => {
  4841. const el = (n2.el = n1.el);
  4842. let { patchFlag, dynamicChildren, dirs } = n2;
  4843. // #1426 take the old vnode's patch flag into account since user may clone a
  4844. // compiler-generated vnode, which de-opts to FULL_PROPS
  4845. patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
  4846. const oldProps = n1.props || EMPTY_OBJ;
  4847. const newProps = n2.props || EMPTY_OBJ;
  4848. let vnodeHook;
  4849. if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
  4850. invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  4851. }
  4852. if (dirs) {
  4853. invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
  4854. }
  4855. if ( isHmrUpdating) {
  4856. // HMR updated, force full diff
  4857. patchFlag = 0;
  4858. optimized = false;
  4859. dynamicChildren = null;
  4860. }
  4861. if (patchFlag > 0) {
  4862. // the presence of a patchFlag means this element's render code was
  4863. // generated by the compiler and can take the fast path.
  4864. // in this path old node and new node are guaranteed to have the same shape
  4865. // (i.e. at the exact same position in the source template)
  4866. if (patchFlag & 16 /* FULL_PROPS */) {
  4867. // element props contain dynamic keys, full diff needed
  4868. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  4869. }
  4870. else {
  4871. // class
  4872. // this flag is matched when the element has dynamic class bindings.
  4873. if (patchFlag & 2 /* CLASS */) {
  4874. if (oldProps.class !== newProps.class) {
  4875. hostPatchProp(el, 'class', null, newProps.class, isSVG);
  4876. }
  4877. }
  4878. // style
  4879. // this flag is matched when the element has dynamic style bindings
  4880. if (patchFlag & 4 /* STYLE */) {
  4881. hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
  4882. }
  4883. // props
  4884. // This flag is matched when the element has dynamic prop/attr bindings
  4885. // other than class and style. The keys of dynamic prop/attrs are saved for
  4886. // faster iteration.
  4887. // Note dynamic keys like :[foo]="bar" will cause this optimization to
  4888. // bail out and go through a full diff because we need to unset the old key
  4889. if (patchFlag & 8 /* PROPS */) {
  4890. // if the flag is present then dynamicProps must be non-null
  4891. const propsToUpdate = n2.dynamicProps;
  4892. for (let i = 0; i < propsToUpdate.length; i++) {
  4893. const key = propsToUpdate[i];
  4894. const prev = oldProps[key];
  4895. const next = newProps[key];
  4896. if (next !== prev ||
  4897. (hostForcePatchProp && hostForcePatchProp(el, key))) {
  4898. hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
  4899. }
  4900. }
  4901. }
  4902. }
  4903. // text
  4904. // This flag is matched when the element has only dynamic text children.
  4905. if (patchFlag & 1 /* TEXT */) {
  4906. if (n1.children !== n2.children) {
  4907. hostSetElementText(el, n2.children);
  4908. }
  4909. }
  4910. }
  4911. else if (!optimized && dynamicChildren == null) {
  4912. // unoptimized, full diff
  4913. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  4914. }
  4915. const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
  4916. if (dynamicChildren) {
  4917. patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG);
  4918. if (
  4919. parentComponent &&
  4920. parentComponent.type.__hmrId) {
  4921. traverseStaticChildren(n1, n2);
  4922. }
  4923. }
  4924. else if (!optimized) {
  4925. // full diff
  4926. patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG);
  4927. }
  4928. if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
  4929. queuePostRenderEffect(() => {
  4930. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  4931. dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
  4932. }, parentSuspense);
  4933. }
  4934. };
  4935. // The fast path for blocks.
  4936. const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG) => {
  4937. for (let i = 0; i < newChildren.length; i++) {
  4938. const oldVNode = oldChildren[i];
  4939. const newVNode = newChildren[i];
  4940. // Determine the container (parent element) for the patch.
  4941. const container =
  4942. // - In the case of a Fragment, we need to provide the actual parent
  4943. // of the Fragment itself so it can move its children.
  4944. oldVNode.type === Fragment ||
  4945. // - In the case of different nodes, there is going to be a replacement
  4946. // which also requires the correct parent container
  4947. !isSameVNodeType(oldVNode, newVNode) ||
  4948. // - In the case of a component, it could contain anything.
  4949. oldVNode.shapeFlag & 6 /* COMPONENT */ ||
  4950. oldVNode.shapeFlag & 64 /* TELEPORT */
  4951. ? hostParentNode(oldVNode.el)
  4952. : // In other cases, the parent container is not actually used so we
  4953. // just pass the block element here to avoid a DOM parentNode call.
  4954. fallbackContainer;
  4955. patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, true);
  4956. }
  4957. };
  4958. const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
  4959. if (oldProps !== newProps) {
  4960. for (const key in newProps) {
  4961. // empty string is not valid prop
  4962. if (isReservedProp(key))
  4963. continue;
  4964. const next = newProps[key];
  4965. const prev = oldProps[key];
  4966. if (next !== prev ||
  4967. (hostForcePatchProp && hostForcePatchProp(el, key))) {
  4968. hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  4969. }
  4970. }
  4971. if (oldProps !== EMPTY_OBJ) {
  4972. for (const key in oldProps) {
  4973. if (!isReservedProp(key) && !(key in newProps)) {
  4974. hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  4975. }
  4976. }
  4977. }
  4978. }
  4979. };
  4980. const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  4981. const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
  4982. const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
  4983. let { patchFlag, dynamicChildren } = n2;
  4984. if (patchFlag > 0) {
  4985. optimized = true;
  4986. }
  4987. if ( isHmrUpdating) {
  4988. // HMR updated, force full diff
  4989. patchFlag = 0;
  4990. optimized = false;
  4991. dynamicChildren = null;
  4992. }
  4993. if (n1 == null) {
  4994. hostInsert(fragmentStartAnchor, container, anchor);
  4995. hostInsert(fragmentEndAnchor, container, anchor);
  4996. // a fragment can only have array children
  4997. // since they are either generated by the compiler, or implicitly created
  4998. // from arrays.
  4999. mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);
  5000. }
  5001. else {
  5002. if (patchFlag > 0 &&
  5003. patchFlag & 64 /* STABLE_FRAGMENT */ &&
  5004. dynamicChildren) {
  5005. // a stable fragment (template root or <template v-for>) doesn't need to
  5006. // patch children order, but it may contain dynamicChildren.
  5007. patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG);
  5008. if ( parentComponent && parentComponent.type.__hmrId) {
  5009. traverseStaticChildren(n1, n2);
  5010. }
  5011. else if (
  5012. // #2080 if the stable fragment has a key, it's a <template v-for> that may
  5013. // get moved around. Make sure all root level vnodes inherit el.
  5014. // #2134 or if it's a component root, it may also get moved around
  5015. // as the component is being moved.
  5016. n2.key != null ||
  5017. (parentComponent && n2 === parentComponent.subTree)) {
  5018. traverseStaticChildren(n1, n2, true /* shallow */);
  5019. }
  5020. }
  5021. else {
  5022. // keyed / unkeyed, or manual fragments.
  5023. // for keyed & unkeyed, since they are compiler generated from v-for,
  5024. // each child is guaranteed to be a block so the fragment will never
  5025. // have dynamicChildren.
  5026. patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);
  5027. }
  5028. }
  5029. };
  5030. const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5031. if (n1 == null) {
  5032. if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
  5033. parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
  5034. }
  5035. else {
  5036. mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5037. }
  5038. }
  5039. else {
  5040. updateComponent(n1, n2, optimized);
  5041. }
  5042. };
  5043. const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5044. const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
  5045. if ( instance.type.__hmrId) {
  5046. registerHMR(instance);
  5047. }
  5048. {
  5049. pushWarningContext(initialVNode);
  5050. startMeasure(instance, `mount`);
  5051. }
  5052. // inject renderer internals for keepAlive
  5053. if (isKeepAlive(initialVNode)) {
  5054. instance.ctx.renderer = internals;
  5055. }
  5056. // resolve props and slots for setup context
  5057. {
  5058. startMeasure(instance, `init`);
  5059. }
  5060. setupComponent(instance);
  5061. {
  5062. endMeasure(instance, `init`);
  5063. }
  5064. // setup() is async. This component relies on async logic to be resolved
  5065. // before proceeding
  5066. if ( instance.asyncDep) {
  5067. parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
  5068. // Give it a placeholder if this is not hydration
  5069. // TODO handle self-defined fallback
  5070. if (!initialVNode.el) {
  5071. const placeholder = (instance.subTree = createVNode(Comment));
  5072. processCommentNode(null, placeholder, container, anchor);
  5073. }
  5074. return;
  5075. }
  5076. setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
  5077. {
  5078. popWarningContext();
  5079. endMeasure(instance, `mount`);
  5080. }
  5081. };
  5082. const updateComponent = (n1, n2, optimized) => {
  5083. const instance = (n2.component = n1.component);
  5084. if (shouldUpdateComponent(n1, n2, optimized)) {
  5085. if (
  5086. instance.asyncDep &&
  5087. !instance.asyncResolved) {
  5088. // async & still pending - just update props and slots
  5089. // since the component's reactive effect for render isn't set-up yet
  5090. {
  5091. pushWarningContext(n2);
  5092. }
  5093. updateComponentPreRender(instance, n2, optimized);
  5094. {
  5095. popWarningContext();
  5096. }
  5097. return;
  5098. }
  5099. else {
  5100. // normal update
  5101. instance.next = n2;
  5102. // in case the child component is also queued, remove it to avoid
  5103. // double updating the same child component in the same flush.
  5104. invalidateJob(instance.update);
  5105. // instance.update is the reactive effect runner.
  5106. instance.update();
  5107. }
  5108. }
  5109. else {
  5110. // no update needed. just copy over properties
  5111. n2.component = n1.component;
  5112. n2.el = n1.el;
  5113. instance.vnode = n2;
  5114. }
  5115. };
  5116. const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
  5117. // create reactive effect for rendering
  5118. instance.update = effect(function componentEffect() {
  5119. if (!instance.isMounted) {
  5120. let vnodeHook;
  5121. const { el, props } = initialVNode;
  5122. const { bm, m, parent } = instance;
  5123. // beforeMount hook
  5124. if (bm) {
  5125. invokeArrayFns(bm);
  5126. }
  5127. // onVnodeBeforeMount
  5128. if ((vnodeHook = props && props.onVnodeBeforeMount)) {
  5129. invokeVNodeHook(vnodeHook, parent, initialVNode);
  5130. }
  5131. // render
  5132. {
  5133. startMeasure(instance, `render`);
  5134. }
  5135. const subTree = (instance.subTree = renderComponentRoot(instance));
  5136. {
  5137. endMeasure(instance, `render`);
  5138. }
  5139. if (el && hydrateNode) {
  5140. {
  5141. startMeasure(instance, `hydrate`);
  5142. }
  5143. // vnode has adopted host node - perform hydration instead of mount.
  5144. hydrateNode(initialVNode.el, subTree, instance, parentSuspense);
  5145. {
  5146. endMeasure(instance, `hydrate`);
  5147. }
  5148. }
  5149. else {
  5150. {
  5151. startMeasure(instance, `patch`);
  5152. }
  5153. patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
  5154. {
  5155. endMeasure(instance, `patch`);
  5156. }
  5157. initialVNode.el = subTree.el;
  5158. }
  5159. // mounted hook
  5160. if (m) {
  5161. queuePostRenderEffect(m, parentSuspense);
  5162. }
  5163. // onVnodeMounted
  5164. if ((vnodeHook = props && props.onVnodeMounted)) {
  5165. queuePostRenderEffect(() => {
  5166. invokeVNodeHook(vnodeHook, parent, initialVNode);
  5167. }, parentSuspense);
  5168. }
  5169. // activated hook for keep-alive roots.
  5170. // #1742 activated hook must be accessed after first render
  5171. // since the hook may be injected by a child keep-alive
  5172. const { a } = instance;
  5173. if (a &&
  5174. initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  5175. queuePostRenderEffect(a, parentSuspense);
  5176. }
  5177. instance.isMounted = true;
  5178. }
  5179. else {
  5180. // updateComponent
  5181. // This is triggered by mutation of component's own state (next: null)
  5182. // OR parent calling processComponent (next: VNode)
  5183. let { next, bu, u, parent, vnode } = instance;
  5184. let originNext = next;
  5185. let vnodeHook;
  5186. {
  5187. pushWarningContext(next || instance.vnode);
  5188. }
  5189. if (next) {
  5190. next.el = vnode.el;
  5191. updateComponentPreRender(instance, next, optimized);
  5192. }
  5193. else {
  5194. next = vnode;
  5195. }
  5196. // beforeUpdate hook
  5197. if (bu) {
  5198. invokeArrayFns(bu);
  5199. }
  5200. // onVnodeBeforeUpdate
  5201. if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
  5202. invokeVNodeHook(vnodeHook, parent, next, vnode);
  5203. }
  5204. // render
  5205. {
  5206. startMeasure(instance, `render`);
  5207. }
  5208. const nextTree = renderComponentRoot(instance);
  5209. {
  5210. endMeasure(instance, `render`);
  5211. }
  5212. const prevTree = instance.subTree;
  5213. instance.subTree = nextTree;
  5214. {
  5215. startMeasure(instance, `patch`);
  5216. }
  5217. patch(prevTree, nextTree,
  5218. // parent may have changed if it's in a teleport
  5219. hostParentNode(prevTree.el),
  5220. // anchor may have changed if it's in a fragment
  5221. getNextHostNode(prevTree), instance, parentSuspense, isSVG);
  5222. {
  5223. endMeasure(instance, `patch`);
  5224. }
  5225. next.el = nextTree.el;
  5226. if (originNext === null) {
  5227. // self-triggered update. In case of HOC, update parent component
  5228. // vnode el. HOC is indicated by parent instance's subTree pointing
  5229. // to child component's vnode
  5230. updateHOCHostEl(instance, nextTree.el);
  5231. }
  5232. // updated hook
  5233. if (u) {
  5234. queuePostRenderEffect(u, parentSuspense);
  5235. }
  5236. // onVnodeUpdated
  5237. if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
  5238. queuePostRenderEffect(() => {
  5239. invokeVNodeHook(vnodeHook, parent, next, vnode);
  5240. }, parentSuspense);
  5241. }
  5242. {
  5243. devtoolsComponentUpdated(instance);
  5244. }
  5245. {
  5246. popWarningContext();
  5247. }
  5248. }
  5249. }, createDevEffectOptions(instance) );
  5250. };
  5251. const updateComponentPreRender = (instance, nextVNode, optimized) => {
  5252. nextVNode.component = instance;
  5253. const prevProps = instance.vnode.props;
  5254. instance.vnode = nextVNode;
  5255. instance.next = null;
  5256. updateProps(instance, nextVNode.props, prevProps, optimized);
  5257. updateSlots(instance, nextVNode.children);
  5258. // props update may have triggered pre-flush watchers.
  5259. // flush them before the render update.
  5260. flushPreFlushCbs(undefined, instance.update);
  5261. };
  5262. const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized = false) => {
  5263. const c1 = n1 && n1.children;
  5264. const prevShapeFlag = n1 ? n1.shapeFlag : 0;
  5265. const c2 = n2.children;
  5266. const { patchFlag, shapeFlag } = n2;
  5267. // fast path
  5268. if (patchFlag > 0) {
  5269. if (patchFlag & 128 /* KEYED_FRAGMENT */) {
  5270. // this could be either fully-keyed or mixed (some keyed some not)
  5271. // presence of patchFlag means children are guaranteed to be arrays
  5272. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5273. return;
  5274. }
  5275. else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
  5276. // unkeyed
  5277. patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5278. return;
  5279. }
  5280. }
  5281. // children has 3 possibilities: text, array or no children.
  5282. if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  5283. // text children fast path
  5284. if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
  5285. unmountChildren(c1, parentComponent, parentSuspense);
  5286. }
  5287. if (c2 !== c1) {
  5288. hostSetElementText(container, c2);
  5289. }
  5290. }
  5291. else {
  5292. if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
  5293. // prev children was array
  5294. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5295. // two arrays, cannot assume anything, do full diff
  5296. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5297. }
  5298. else {
  5299. // no new children, just unmount old
  5300. unmountChildren(c1, parentComponent, parentSuspense, true);
  5301. }
  5302. }
  5303. else {
  5304. // prev children was text OR null
  5305. // new children is array OR null
  5306. if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
  5307. hostSetElementText(container, '');
  5308. }
  5309. // mount new if array
  5310. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5311. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5312. }
  5313. }
  5314. }
  5315. };
  5316. const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5317. c1 = c1 || EMPTY_ARR;
  5318. c2 = c2 || EMPTY_ARR;
  5319. const oldLength = c1.length;
  5320. const newLength = c2.length;
  5321. const commonLength = Math.min(oldLength, newLength);
  5322. let i;
  5323. for (i = 0; i < commonLength; i++) {
  5324. const nextChild = (c2[i] = optimized
  5325. ? cloneIfMounted(c2[i])
  5326. : normalizeVNode(c2[i]));
  5327. patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, optimized);
  5328. }
  5329. if (oldLength > newLength) {
  5330. // remove old
  5331. unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
  5332. }
  5333. else {
  5334. // mount new
  5335. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, commonLength);
  5336. }
  5337. };
  5338. // can be all-keyed or mixed
  5339. const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5340. let i = 0;
  5341. const l2 = c2.length;
  5342. let e1 = c1.length - 1; // prev ending index
  5343. let e2 = l2 - 1; // next ending index
  5344. // 1. sync from start
  5345. // (a b) c
  5346. // (a b) d e
  5347. while (i <= e1 && i <= e2) {
  5348. const n1 = c1[i];
  5349. const n2 = (c2[i] = optimized
  5350. ? cloneIfMounted(c2[i])
  5351. : normalizeVNode(c2[i]));
  5352. if (isSameVNodeType(n1, n2)) {
  5353. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, optimized);
  5354. }
  5355. else {
  5356. break;
  5357. }
  5358. i++;
  5359. }
  5360. // 2. sync from end
  5361. // a (b c)
  5362. // d e (b c)
  5363. while (i <= e1 && i <= e2) {
  5364. const n1 = c1[e1];
  5365. const n2 = (c2[e2] = optimized
  5366. ? cloneIfMounted(c2[e2])
  5367. : normalizeVNode(c2[e2]));
  5368. if (isSameVNodeType(n1, n2)) {
  5369. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, optimized);
  5370. }
  5371. else {
  5372. break;
  5373. }
  5374. e1--;
  5375. e2--;
  5376. }
  5377. // 3. common sequence + mount
  5378. // (a b)
  5379. // (a b) c
  5380. // i = 2, e1 = 1, e2 = 2
  5381. // (a b)
  5382. // c (a b)
  5383. // i = 0, e1 = -1, e2 = 0
  5384. if (i > e1) {
  5385. if (i <= e2) {
  5386. const nextPos = e2 + 1;
  5387. const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
  5388. while (i <= e2) {
  5389. patch(null, (c2[i] = optimized
  5390. ? cloneIfMounted(c2[i])
  5391. : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG);
  5392. i++;
  5393. }
  5394. }
  5395. }
  5396. // 4. common sequence + unmount
  5397. // (a b) c
  5398. // (a b)
  5399. // i = 2, e1 = 2, e2 = 1
  5400. // a (b c)
  5401. // (b c)
  5402. // i = 0, e1 = 0, e2 = -1
  5403. else if (i > e2) {
  5404. while (i <= e1) {
  5405. unmount(c1[i], parentComponent, parentSuspense, true);
  5406. i++;
  5407. }
  5408. }
  5409. // 5. unknown sequence
  5410. // [i ... e1 + 1]: a b [c d e] f g
  5411. // [i ... e2 + 1]: a b [e d c h] f g
  5412. // i = 2, e1 = 4, e2 = 5
  5413. else {
  5414. const s1 = i; // prev starting index
  5415. const s2 = i; // next starting index
  5416. // 5.1 build key:index map for newChildren
  5417. const keyToNewIndexMap = new Map();
  5418. for (i = s2; i <= e2; i++) {
  5419. const nextChild = (c2[i] = optimized
  5420. ? cloneIfMounted(c2[i])
  5421. : normalizeVNode(c2[i]));
  5422. if (nextChild.key != null) {
  5423. if ( keyToNewIndexMap.has(nextChild.key)) {
  5424. warn(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
  5425. }
  5426. keyToNewIndexMap.set(nextChild.key, i);
  5427. }
  5428. }
  5429. // 5.2 loop through old children left to be patched and try to patch
  5430. // matching nodes & remove nodes that are no longer present
  5431. let j;
  5432. let patched = 0;
  5433. const toBePatched = e2 - s2 + 1;
  5434. let moved = false;
  5435. // used to track whether any node has moved
  5436. let maxNewIndexSoFar = 0;
  5437. // works as Map<newIndex, oldIndex>
  5438. // Note that oldIndex is offset by +1
  5439. // and oldIndex = 0 is a special value indicating the new node has
  5440. // no corresponding old node.
  5441. // used for determining longest stable subsequence
  5442. const newIndexToOldIndexMap = new Array(toBePatched);
  5443. for (i = 0; i < toBePatched; i++)
  5444. newIndexToOldIndexMap[i] = 0;
  5445. for (i = s1; i <= e1; i++) {
  5446. const prevChild = c1[i];
  5447. if (patched >= toBePatched) {
  5448. // all new children have been patched so this can only be a removal
  5449. unmount(prevChild, parentComponent, parentSuspense, true);
  5450. continue;
  5451. }
  5452. let newIndex;
  5453. if (prevChild.key != null) {
  5454. newIndex = keyToNewIndexMap.get(prevChild.key);
  5455. }
  5456. else {
  5457. // key-less node, try to locate a key-less node of the same type
  5458. for (j = s2; j <= e2; j++) {
  5459. if (newIndexToOldIndexMap[j - s2] === 0 &&
  5460. isSameVNodeType(prevChild, c2[j])) {
  5461. newIndex = j;
  5462. break;
  5463. }
  5464. }
  5465. }
  5466. if (newIndex === undefined) {
  5467. unmount(prevChild, parentComponent, parentSuspense, true);
  5468. }
  5469. else {
  5470. newIndexToOldIndexMap[newIndex - s2] = i + 1;
  5471. if (newIndex >= maxNewIndexSoFar) {
  5472. maxNewIndexSoFar = newIndex;
  5473. }
  5474. else {
  5475. moved = true;
  5476. }
  5477. patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, optimized);
  5478. patched++;
  5479. }
  5480. }
  5481. // 5.3 move and mount
  5482. // generate longest stable subsequence only when nodes have moved
  5483. const increasingNewIndexSequence = moved
  5484. ? getSequence(newIndexToOldIndexMap)
  5485. : EMPTY_ARR;
  5486. j = increasingNewIndexSequence.length - 1;
  5487. // looping backwards so that we can use last patched node as anchor
  5488. for (i = toBePatched - 1; i >= 0; i--) {
  5489. const nextIndex = s2 + i;
  5490. const nextChild = c2[nextIndex];
  5491. const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
  5492. if (newIndexToOldIndexMap[i] === 0) {
  5493. // mount new
  5494. patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG);
  5495. }
  5496. else if (moved) {
  5497. // move if:
  5498. // There is no stable subsequence (e.g. a reverse)
  5499. // OR current node is not among the stable sequence
  5500. if (j < 0 || i !== increasingNewIndexSequence[j]) {
  5501. move(nextChild, container, anchor, 2 /* REORDER */);
  5502. }
  5503. else {
  5504. j--;
  5505. }
  5506. }
  5507. }
  5508. }
  5509. };
  5510. const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
  5511. const { el, type, transition, children, shapeFlag } = vnode;
  5512. if (shapeFlag & 6 /* COMPONENT */) {
  5513. move(vnode.component.subTree, container, anchor, moveType);
  5514. return;
  5515. }
  5516. if ( shapeFlag & 128 /* SUSPENSE */) {
  5517. vnode.suspense.move(container, anchor, moveType);
  5518. return;
  5519. }
  5520. if (shapeFlag & 64 /* TELEPORT */) {
  5521. type.move(vnode, container, anchor, internals);
  5522. return;
  5523. }
  5524. if (type === Fragment) {
  5525. hostInsert(el, container, anchor);
  5526. for (let i = 0; i < children.length; i++) {
  5527. move(children[i], container, anchor, moveType);
  5528. }
  5529. hostInsert(vnode.anchor, container, anchor);
  5530. return;
  5531. }
  5532. // static node move can only happen when force updating HMR
  5533. if ( type === Static) {
  5534. moveStaticNode(vnode, container, anchor);
  5535. return;
  5536. }
  5537. // single nodes
  5538. const needTransition = moveType !== 2 /* REORDER */ &&
  5539. shapeFlag & 1 /* ELEMENT */ &&
  5540. transition;
  5541. if (needTransition) {
  5542. if (moveType === 0 /* ENTER */) {
  5543. transition.beforeEnter(el);
  5544. hostInsert(el, container, anchor);
  5545. queuePostRenderEffect(() => transition.enter(el), parentSuspense);
  5546. }
  5547. else {
  5548. const { leave, delayLeave, afterLeave } = transition;
  5549. const remove = () => hostInsert(el, container, anchor);
  5550. const performLeave = () => {
  5551. leave(el, () => {
  5552. remove();
  5553. afterLeave && afterLeave();
  5554. });
  5555. };
  5556. if (delayLeave) {
  5557. delayLeave(el, remove, performLeave);
  5558. }
  5559. else {
  5560. performLeave();
  5561. }
  5562. }
  5563. }
  5564. else {
  5565. hostInsert(el, container, anchor);
  5566. }
  5567. };
  5568. const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
  5569. const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
  5570. // unset ref
  5571. if (ref != null && parentComponent) {
  5572. setRef(ref, null, parentComponent, parentSuspense, null);
  5573. }
  5574. if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  5575. parentComponent.ctx.deactivate(vnode);
  5576. return;
  5577. }
  5578. const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
  5579. let vnodeHook;
  5580. if ((vnodeHook = props && props.onVnodeBeforeUnmount)) {
  5581. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  5582. }
  5583. if (shapeFlag & 6 /* COMPONENT */) {
  5584. unmountComponent(vnode.component, parentSuspense, doRemove);
  5585. }
  5586. else {
  5587. if ( shapeFlag & 128 /* SUSPENSE */) {
  5588. vnode.suspense.unmount(parentSuspense, doRemove);
  5589. return;
  5590. }
  5591. if (shouldInvokeDirs) {
  5592. invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
  5593. }
  5594. if (dynamicChildren &&
  5595. // #1153: fast path should not be taken for non-stable (v-for) fragments
  5596. (type !== Fragment ||
  5597. (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
  5598. // fast path for block nodes: only need to unmount dynamic children.
  5599. unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
  5600. }
  5601. else if ((type === Fragment &&
  5602. (patchFlag & 128 /* KEYED_FRAGMENT */ ||
  5603. patchFlag & 256 /* UNKEYED_FRAGMENT */)) ||
  5604. (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
  5605. unmountChildren(children, parentComponent, parentSuspense);
  5606. }
  5607. // an unmounted teleport should always remove its children if not disabled
  5608. if (shapeFlag & 64 /* TELEPORT */ &&
  5609. (doRemove || !isTeleportDisabled(vnode.props))) {
  5610. vnode.type.remove(vnode, internals);
  5611. }
  5612. if (doRemove) {
  5613. remove(vnode);
  5614. }
  5615. }
  5616. if ((vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs) {
  5617. queuePostRenderEffect(() => {
  5618. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  5619. shouldInvokeDirs &&
  5620. invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
  5621. }, parentSuspense);
  5622. }
  5623. };
  5624. const remove = vnode => {
  5625. const { type, el, anchor, transition } = vnode;
  5626. if (type === Fragment) {
  5627. removeFragment(el, anchor);
  5628. return;
  5629. }
  5630. if ( type === Static) {
  5631. removeStaticNode(vnode);
  5632. return;
  5633. }
  5634. const performRemove = () => {
  5635. hostRemove(el);
  5636. if (transition && !transition.persisted && transition.afterLeave) {
  5637. transition.afterLeave();
  5638. }
  5639. };
  5640. if (vnode.shapeFlag & 1 /* ELEMENT */ &&
  5641. transition &&
  5642. !transition.persisted) {
  5643. const { leave, delayLeave } = transition;
  5644. const performLeave = () => leave(el, performRemove);
  5645. if (delayLeave) {
  5646. delayLeave(vnode.el, performRemove, performLeave);
  5647. }
  5648. else {
  5649. performLeave();
  5650. }
  5651. }
  5652. else {
  5653. performRemove();
  5654. }
  5655. };
  5656. const removeFragment = (cur, end) => {
  5657. // For fragments, directly remove all contained DOM nodes.
  5658. // (fragment child nodes cannot have transition)
  5659. let next;
  5660. while (cur !== end) {
  5661. next = hostNextSibling(cur);
  5662. hostRemove(cur);
  5663. cur = next;
  5664. }
  5665. hostRemove(end);
  5666. };
  5667. const unmountComponent = (instance, parentSuspense, doRemove) => {
  5668. if ( instance.type.__hmrId) {
  5669. unregisterHMR(instance);
  5670. }
  5671. const { bum, effects, update, subTree, um } = instance;
  5672. // beforeUnmount hook
  5673. if (bum) {
  5674. invokeArrayFns(bum);
  5675. }
  5676. if (effects) {
  5677. for (let i = 0; i < effects.length; i++) {
  5678. stop(effects[i]);
  5679. }
  5680. }
  5681. // update may be null if a component is unmounted before its async
  5682. // setup has resolved.
  5683. if (update) {
  5684. stop(update);
  5685. unmount(subTree, instance, parentSuspense, doRemove);
  5686. }
  5687. // unmounted hook
  5688. if (um) {
  5689. queuePostRenderEffect(um, parentSuspense);
  5690. }
  5691. queuePostRenderEffect(() => {
  5692. instance.isUnmounted = true;
  5693. }, parentSuspense);
  5694. // A component with async dep inside a pending suspense is unmounted before
  5695. // its async dep resolves. This should remove the dep from the suspense, and
  5696. // cause the suspense to resolve immediately if that was the last dep.
  5697. if (
  5698. parentSuspense &&
  5699. parentSuspense.pendingBranch &&
  5700. !parentSuspense.isUnmounted &&
  5701. instance.asyncDep &&
  5702. !instance.asyncResolved &&
  5703. instance.suspenseId === parentSuspense.pendingId) {
  5704. parentSuspense.deps--;
  5705. if (parentSuspense.deps === 0) {
  5706. parentSuspense.resolve();
  5707. }
  5708. }
  5709. {
  5710. devtoolsComponentRemoved(instance);
  5711. }
  5712. };
  5713. const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
  5714. for (let i = start; i < children.length; i++) {
  5715. unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
  5716. }
  5717. };
  5718. const getNextHostNode = vnode => {
  5719. if (vnode.shapeFlag & 6 /* COMPONENT */) {
  5720. return getNextHostNode(vnode.component.subTree);
  5721. }
  5722. if ( vnode.shapeFlag & 128 /* SUSPENSE */) {
  5723. return vnode.suspense.next();
  5724. }
  5725. return hostNextSibling((vnode.anchor || vnode.el));
  5726. };
  5727. const render = (vnode, container) => {
  5728. if (vnode == null) {
  5729. if (container._vnode) {
  5730. unmount(container._vnode, null, null, true);
  5731. }
  5732. }
  5733. else {
  5734. patch(container._vnode || null, vnode, container);
  5735. }
  5736. flushPostFlushCbs();
  5737. container._vnode = vnode;
  5738. };
  5739. const internals = {
  5740. p: patch,
  5741. um: unmount,
  5742. m: move,
  5743. r: remove,
  5744. mt: mountComponent,
  5745. mc: mountChildren,
  5746. pc: patchChildren,
  5747. pbc: patchBlockChildren,
  5748. n: getNextHostNode,
  5749. o: options
  5750. };
  5751. let hydrate;
  5752. let hydrateNode;
  5753. if (createHydrationFns) {
  5754. [hydrate, hydrateNode] = createHydrationFns(internals);
  5755. }
  5756. return {
  5757. render,
  5758. hydrate,
  5759. createApp: createAppAPI(render, hydrate)
  5760. };
  5761. }
  5762. function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
  5763. callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
  5764. vnode,
  5765. prevVNode
  5766. ]);
  5767. }
  5768. /**
  5769. * #1156
  5770. * When a component is HMR-enabled, we need to make sure that all static nodes
  5771. * inside a block also inherit the DOM element from the previous tree so that
  5772. * HMR updates (which are full updates) can retrieve the element for patching.
  5773. *
  5774. * #2080
  5775. * Inside keyed `template` fragment static children, if a fragment is moved,
  5776. * the children will always moved so that need inherit el form previous nodes
  5777. * to ensure correct moved position.
  5778. */
  5779. function traverseStaticChildren(n1, n2, shallow = false) {
  5780. const ch1 = n1.children;
  5781. const ch2 = n2.children;
  5782. if (isArray(ch1) && isArray(ch2)) {
  5783. for (let i = 0; i < ch1.length; i++) {
  5784. // this is only called in the optimized path so array children are
  5785. // guaranteed to be vnodes
  5786. const c1 = ch1[i];
  5787. let c2 = ch2[i];
  5788. if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
  5789. if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
  5790. c2 = ch2[i] = cloneIfMounted(ch2[i]);
  5791. c2.el = c1.el;
  5792. }
  5793. if (!shallow)
  5794. traverseStaticChildren(c1, c2);
  5795. }
  5796. // also inherit for comment nodes, but not placeholders (e.g. v-if which
  5797. // would have received .el during block patch)
  5798. if ( c2.type === Comment && !c2.el) {
  5799. c2.el = c1.el;
  5800. }
  5801. }
  5802. }
  5803. }
  5804. // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
  5805. function getSequence(arr) {
  5806. const p = arr.slice();
  5807. const result = [0];
  5808. let i, j, u, v, c;
  5809. const len = arr.length;
  5810. for (i = 0; i < len; i++) {
  5811. const arrI = arr[i];
  5812. if (arrI !== 0) {
  5813. j = result[result.length - 1];
  5814. if (arr[j] < arrI) {
  5815. p[i] = j;
  5816. result.push(i);
  5817. continue;
  5818. }
  5819. u = 0;
  5820. v = result.length - 1;
  5821. while (u < v) {
  5822. c = ((u + v) / 2) | 0;
  5823. if (arr[result[c]] < arrI) {
  5824. u = c + 1;
  5825. }
  5826. else {
  5827. v = c;
  5828. }
  5829. }
  5830. if (arrI < arr[result[u]]) {
  5831. if (u > 0) {
  5832. p[i] = result[u - 1];
  5833. }
  5834. result[u] = i;
  5835. }
  5836. }
  5837. }
  5838. u = result.length;
  5839. v = result[u - 1];
  5840. while (u-- > 0) {
  5841. result[u] = v;
  5842. v = p[v];
  5843. }
  5844. return result;
  5845. }
  5846. const isTeleport = (type) => type.__isTeleport;
  5847. const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
  5848. const resolveTarget = (props, select) => {
  5849. const targetSelector = props && props.to;
  5850. if (isString(targetSelector)) {
  5851. if (!select) {
  5852. warn(`Current renderer does not support string target for Teleports. ` +
  5853. `(missing querySelector renderer option)`);
  5854. return null;
  5855. }
  5856. else {
  5857. const target = select(targetSelector);
  5858. if (!target) {
  5859. warn(`Failed to locate Teleport target with selector "${targetSelector}". ` +
  5860. `Note the target element must exist before the component is mounted - ` +
  5861. `i.e. the target cannot be rendered by the component itself, and ` +
  5862. `ideally should be outside of the entire Vue component tree.`);
  5863. }
  5864. return target;
  5865. }
  5866. }
  5867. else {
  5868. if ( !targetSelector && !isTeleportDisabled(props)) {
  5869. warn(`Invalid Teleport target: ${targetSelector}`);
  5870. }
  5871. return targetSelector;
  5872. }
  5873. };
  5874. const TeleportImpl = {
  5875. __isTeleport: true,
  5876. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals) {
  5877. const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
  5878. const disabled = isTeleportDisabled(n2.props);
  5879. const { shapeFlag, children } = n2;
  5880. if (n1 == null) {
  5881. // insert anchors in the main view
  5882. const placeholder = (n2.el = createComment('teleport start')
  5883. );
  5884. const mainAnchor = (n2.anchor = createComment('teleport end')
  5885. );
  5886. insert(placeholder, container, anchor);
  5887. insert(mainAnchor, container, anchor);
  5888. const target = (n2.target = resolveTarget(n2.props, querySelector));
  5889. const targetAnchor = (n2.targetAnchor = createText(''));
  5890. if (target) {
  5891. insert(targetAnchor, target);
  5892. }
  5893. else if ( !disabled) {
  5894. warn('Invalid Teleport target on mount:', target, `(${typeof target})`);
  5895. }
  5896. const mount = (container, anchor) => {
  5897. // Teleport *always* has Array children. This is enforced in both the
  5898. // compiler and vnode children normalization.
  5899. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5900. mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5901. }
  5902. };
  5903. if (disabled) {
  5904. mount(container, mainAnchor);
  5905. }
  5906. else if (target) {
  5907. mount(target, targetAnchor);
  5908. }
  5909. }
  5910. else {
  5911. // update content
  5912. n2.el = n1.el;
  5913. const mainAnchor = (n2.anchor = n1.anchor);
  5914. const target = (n2.target = n1.target);
  5915. const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
  5916. const wasDisabled = isTeleportDisabled(n1.props);
  5917. const currentContainer = wasDisabled ? container : target;
  5918. const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
  5919. if (n2.dynamicChildren) {
  5920. // fast path when the teleport happens to be a block root
  5921. patchBlockChildren(n1.dynamicChildren, n2.dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG);
  5922. // even in block tree mode we need to make sure all root-level nodes
  5923. // in the teleport inherit previous DOM references so that they can
  5924. // be moved in future patches.
  5925. traverseStaticChildren(n1, n2, true);
  5926. }
  5927. else if (!optimized) {
  5928. patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG);
  5929. }
  5930. if (disabled) {
  5931. if (!wasDisabled) {
  5932. // enabled -> disabled
  5933. // move into main container
  5934. moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
  5935. }
  5936. }
  5937. else {
  5938. // target changed
  5939. if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
  5940. const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
  5941. if (nextTarget) {
  5942. moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
  5943. }
  5944. else {
  5945. warn('Invalid Teleport target on update:', target, `(${typeof target})`);
  5946. }
  5947. }
  5948. else if (wasDisabled) {
  5949. // disabled -> enabled
  5950. // move into teleport target
  5951. moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
  5952. }
  5953. }
  5954. }
  5955. },
  5956. remove(vnode, { r: remove, o: { remove: hostRemove } }) {
  5957. const { shapeFlag, children, anchor } = vnode;
  5958. hostRemove(anchor);
  5959. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5960. for (let i = 0; i < children.length; i++) {
  5961. remove(children[i]);
  5962. }
  5963. }
  5964. },
  5965. move: moveTeleport,
  5966. hydrate: hydrateTeleport
  5967. };
  5968. function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
  5969. // move target anchor if this is a target change.
  5970. if (moveType === 0 /* TARGET_CHANGE */) {
  5971. insert(vnode.targetAnchor, container, parentAnchor);
  5972. }
  5973. const { el, anchor, shapeFlag, children, props } = vnode;
  5974. const isReorder = moveType === 2 /* REORDER */;
  5975. // move main view anchor if this is a re-order.
  5976. if (isReorder) {
  5977. insert(el, container, parentAnchor);
  5978. }
  5979. // if this is a re-order and teleport is enabled (content is in target)
  5980. // do not move children. So the opposite is: only move children if this
  5981. // is not a reorder, or the teleport is disabled
  5982. if (!isReorder || isTeleportDisabled(props)) {
  5983. // Teleport has either Array children or no children.
  5984. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5985. for (let i = 0; i < children.length; i++) {
  5986. move(children[i], container, parentAnchor, 2 /* REORDER */);
  5987. }
  5988. }
  5989. }
  5990. // move main view anchor if this is a re-order.
  5991. if (isReorder) {
  5992. insert(anchor, container, parentAnchor);
  5993. }
  5994. }
  5995. function hydrateTeleport(node, vnode, parentComponent, parentSuspense, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
  5996. const target = (vnode.target = resolveTarget(vnode.props, querySelector));
  5997. if (target) {
  5998. // if multiple teleports rendered to the same target element, we need to
  5999. // pick up from where the last teleport finished instead of the first node
  6000. const targetNode = target._lpa || target.firstChild;
  6001. if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6002. if (isTeleportDisabled(vnode.props)) {
  6003. vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, optimized);
  6004. vnode.targetAnchor = targetNode;
  6005. }
  6006. else {
  6007. vnode.anchor = nextSibling(node);
  6008. vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, optimized);
  6009. }
  6010. target._lpa =
  6011. vnode.targetAnchor && nextSibling(vnode.targetAnchor);
  6012. }
  6013. }
  6014. return vnode.anchor && nextSibling(vnode.anchor);
  6015. }
  6016. // Force-casted public typing for h and TSX props inference
  6017. const Teleport = TeleportImpl;
  6018. const COMPONENTS = 'components';
  6019. const DIRECTIVES = 'directives';
  6020. /**
  6021. * @private
  6022. */
  6023. function resolveComponent(name) {
  6024. return resolveAsset(COMPONENTS, name) || name;
  6025. }
  6026. const NULL_DYNAMIC_COMPONENT = Symbol();
  6027. /**
  6028. * @private
  6029. */
  6030. function resolveDynamicComponent(component) {
  6031. if (isString(component)) {
  6032. return resolveAsset(COMPONENTS, component, false) || component;
  6033. }
  6034. else {
  6035. // invalid types will fallthrough to createVNode and raise warning
  6036. return (component || NULL_DYNAMIC_COMPONENT);
  6037. }
  6038. }
  6039. /**
  6040. * @private
  6041. */
  6042. function resolveDirective(name) {
  6043. return resolveAsset(DIRECTIVES, name);
  6044. }
  6045. // implementation
  6046. function resolveAsset(type, name, warnMissing = true) {
  6047. const instance = currentRenderingInstance || currentInstance;
  6048. if (instance) {
  6049. const Component = instance.type;
  6050. // self name has highest priority
  6051. if (type === COMPONENTS) {
  6052. const selfName = Component.displayName || Component.name;
  6053. if (selfName &&
  6054. (selfName === name ||
  6055. selfName === camelize(name) ||
  6056. selfName === capitalize(camelize(name)))) {
  6057. return Component;
  6058. }
  6059. }
  6060. const res =
  6061. // local registration
  6062. // check instance[type] first for components with mixin or extends.
  6063. resolve(instance[type] || Component[type], name) ||
  6064. // global registration
  6065. resolve(instance.appContext[type], name);
  6066. if ( warnMissing && !res) {
  6067. warn(`Failed to resolve ${type.slice(0, -1)}: ${name}`);
  6068. }
  6069. return res;
  6070. }
  6071. else {
  6072. warn(`resolve${capitalize(type.slice(0, -1))} ` +
  6073. `can only be used in render() or setup().`);
  6074. }
  6075. }
  6076. function resolve(registry, name) {
  6077. return (registry &&
  6078. (registry[name] ||
  6079. registry[camelize(name)] ||
  6080. registry[capitalize(camelize(name))]));
  6081. }
  6082. const Fragment = Symbol( 'Fragment' );
  6083. const Text = Symbol( 'Text' );
  6084. const Comment = Symbol( 'Comment' );
  6085. const Static = Symbol( 'Static' );
  6086. // Since v-if and v-for are the two possible ways node structure can dynamically
  6087. // change, once we consider v-if branches and each v-for fragment a block, we
  6088. // can divide a template into nested blocks, and within each block the node
  6089. // structure would be stable. This allows us to skip most children diffing
  6090. // and only worry about the dynamic nodes (indicated by patch flags).
  6091. const blockStack = [];
  6092. let currentBlock = null;
  6093. /**
  6094. * Open a block.
  6095. * This must be called before `createBlock`. It cannot be part of `createBlock`
  6096. * because the children of the block are evaluated before `createBlock` itself
  6097. * is called. The generated code typically looks like this:
  6098. *
  6099. * ```js
  6100. * function render() {
  6101. * return (openBlock(),createBlock('div', null, [...]))
  6102. * }
  6103. * ```
  6104. * disableTracking is true when creating a v-for fragment block, since a v-for
  6105. * fragment always diffs its children.
  6106. *
  6107. * @private
  6108. */
  6109. function openBlock(disableTracking = false) {
  6110. blockStack.push((currentBlock = disableTracking ? null : []));
  6111. }
  6112. function closeBlock() {
  6113. blockStack.pop();
  6114. currentBlock = blockStack[blockStack.length - 1] || null;
  6115. }
  6116. // Whether we should be tracking dynamic child nodes inside a block.
  6117. // Only tracks when this value is > 0
  6118. // We are not using a simple boolean because this value may need to be
  6119. // incremented/decremented by nested usage of v-once (see below)
  6120. let shouldTrack$1 = 1;
  6121. /**
  6122. * Block tracking sometimes needs to be disabled, for example during the
  6123. * creation of a tree that needs to be cached by v-once. The compiler generates
  6124. * code like this:
  6125. *
  6126. * ``` js
  6127. * _cache[1] || (
  6128. * setBlockTracking(-1),
  6129. * _cache[1] = createVNode(...),
  6130. * setBlockTracking(1),
  6131. * _cache[1]
  6132. * )
  6133. * ```
  6134. *
  6135. * @private
  6136. */
  6137. function setBlockTracking(value) {
  6138. shouldTrack$1 += value;
  6139. }
  6140. /**
  6141. * Create a block root vnode. Takes the same exact arguments as `createVNode`.
  6142. * A block root keeps track of dynamic nodes within the block in the
  6143. * `dynamicChildren` array.
  6144. *
  6145. * @private
  6146. */
  6147. function createBlock(type, props, children, patchFlag, dynamicProps) {
  6148. const vnode = createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */);
  6149. // save current block children on the block vnode
  6150. vnode.dynamicChildren = currentBlock || EMPTY_ARR;
  6151. // close block
  6152. closeBlock();
  6153. // a block is always going to be patched, so track it as a child of its
  6154. // parent block
  6155. if (shouldTrack$1 > 0 && currentBlock) {
  6156. currentBlock.push(vnode);
  6157. }
  6158. return vnode;
  6159. }
  6160. function isVNode(value) {
  6161. return value ? value.__v_isVNode === true : false;
  6162. }
  6163. function isSameVNodeType(n1, n2) {
  6164. if (
  6165. n2.shapeFlag & 6 /* COMPONENT */ &&
  6166. hmrDirtyComponents.has(n2.type)) {
  6167. // HMR only: if the component has been hot-updated, force a reload.
  6168. return false;
  6169. }
  6170. return n1.type === n2.type && n1.key === n2.key;
  6171. }
  6172. let vnodeArgsTransformer;
  6173. /**
  6174. * Internal API for registering an arguments transform for createVNode
  6175. * used for creating stubs in the test-utils
  6176. * It is *internal* but needs to be exposed for test-utils to pick up proper
  6177. * typings
  6178. */
  6179. function transformVNodeArgs(transformer) {
  6180. vnodeArgsTransformer = transformer;
  6181. }
  6182. const createVNodeWithArgsTransform = (...args) => {
  6183. return _createVNode(...(vnodeArgsTransformer
  6184. ? vnodeArgsTransformer(args, currentRenderingInstance)
  6185. : args));
  6186. };
  6187. const InternalObjectKey = `__vInternal`;
  6188. const normalizeKey = ({ key }) => key != null ? key : null;
  6189. const normalizeRef = ({ ref }) => {
  6190. return (ref != null
  6191. ? isArray(ref)
  6192. ? ref
  6193. : { i: currentRenderingInstance, r: ref }
  6194. : null);
  6195. };
  6196. const createVNode = ( createVNodeWithArgsTransform
  6197. );
  6198. function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
  6199. if (!type || type === NULL_DYNAMIC_COMPONENT) {
  6200. if ( !type) {
  6201. warn(`Invalid vnode type when creating vnode: ${type}.`);
  6202. }
  6203. type = Comment;
  6204. }
  6205. if (isVNode(type)) {
  6206. // createVNode receiving an existing vnode. This happens in cases like
  6207. // <component :is="vnode"/>
  6208. // #2078 make sure to merge refs during the clone instead of overwriting it
  6209. const cloned = cloneVNode(type, props, true /* mergeRef: true */);
  6210. if (children) {
  6211. normalizeChildren(cloned, children);
  6212. }
  6213. return cloned;
  6214. }
  6215. // class component normalization.
  6216. if (isClassComponent(type)) {
  6217. type = type.__vccOpts;
  6218. }
  6219. // class & style normalization.
  6220. if (props) {
  6221. // for reactive or proxy objects, we need to clone it to enable mutation.
  6222. if (isProxy(props) || InternalObjectKey in props) {
  6223. props = extend({}, props);
  6224. }
  6225. let { class: klass, style } = props;
  6226. if (klass && !isString(klass)) {
  6227. props.class = normalizeClass(klass);
  6228. }
  6229. if (isObject(style)) {
  6230. // reactive state objects need to be cloned since they are likely to be
  6231. // mutated
  6232. if (isProxy(style) && !isArray(style)) {
  6233. style = extend({}, style);
  6234. }
  6235. props.style = normalizeStyle(style);
  6236. }
  6237. }
  6238. // encode the vnode type information into a bitmap
  6239. const shapeFlag = isString(type)
  6240. ? 1 /* ELEMENT */
  6241. : isSuspense(type)
  6242. ? 128 /* SUSPENSE */
  6243. : isTeleport(type)
  6244. ? 64 /* TELEPORT */
  6245. : isObject(type)
  6246. ? 4 /* STATEFUL_COMPONENT */
  6247. : isFunction(type)
  6248. ? 2 /* FUNCTIONAL_COMPONENT */
  6249. : 0;
  6250. if ( shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
  6251. type = toRaw(type);
  6252. warn(`Vue received a Component which was made a reactive object. This can ` +
  6253. `lead to unnecessary performance overhead, and should be avoided by ` +
  6254. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  6255. `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
  6256. }
  6257. const vnode = {
  6258. __v_isVNode: true,
  6259. ["__v_skip" /* SKIP */]: true,
  6260. type,
  6261. props,
  6262. key: props && normalizeKey(props),
  6263. ref: props && normalizeRef(props),
  6264. scopeId: currentScopeId,
  6265. children: null,
  6266. component: null,
  6267. suspense: null,
  6268. ssContent: null,
  6269. ssFallback: null,
  6270. dirs: null,
  6271. transition: null,
  6272. el: null,
  6273. anchor: null,
  6274. target: null,
  6275. targetAnchor: null,
  6276. staticCount: 0,
  6277. shapeFlag,
  6278. patchFlag,
  6279. dynamicProps,
  6280. dynamicChildren: null,
  6281. appContext: null
  6282. };
  6283. // validate key
  6284. if ( vnode.key !== vnode.key) {
  6285. warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
  6286. }
  6287. normalizeChildren(vnode, children);
  6288. // normalize suspense children
  6289. if ( shapeFlag & 128 /* SUSPENSE */) {
  6290. const { content, fallback } = normalizeSuspenseChildren(vnode);
  6291. vnode.ssContent = content;
  6292. vnode.ssFallback = fallback;
  6293. }
  6294. if (shouldTrack$1 > 0 &&
  6295. // avoid a block node from tracking itself
  6296. !isBlockNode &&
  6297. // has current parent block
  6298. currentBlock &&
  6299. // presence of a patch flag indicates this node needs patching on updates.
  6300. // component nodes also should always be patched, because even if the
  6301. // component doesn't need to update, it needs to persist the instance on to
  6302. // the next vnode so that it can be properly unmounted later.
  6303. (patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
  6304. // the EVENTS flag is only for hydration and if it is the only flag, the
  6305. // vnode should not be considered dynamic due to handler caching.
  6306. patchFlag !== 32 /* HYDRATE_EVENTS */) {
  6307. currentBlock.push(vnode);
  6308. }
  6309. return vnode;
  6310. }
  6311. function cloneVNode(vnode, extraProps, mergeRef = false) {
  6312. // This is intentionally NOT using spread or extend to avoid the runtime
  6313. // key enumeration cost.
  6314. const { props, ref, patchFlag } = vnode;
  6315. const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
  6316. return {
  6317. __v_isVNode: true,
  6318. ["__v_skip" /* SKIP */]: true,
  6319. type: vnode.type,
  6320. props: mergedProps,
  6321. key: mergedProps && normalizeKey(mergedProps),
  6322. ref: extraProps && extraProps.ref
  6323. ? // #2078 in the case of <component :is="vnode" ref="extra"/>
  6324. // if the vnode itself already has a ref, cloneVNode will need to merge
  6325. // the refs so the single vnode can be set on multiple refs
  6326. mergeRef && ref
  6327. ? isArray(ref)
  6328. ? ref.concat(normalizeRef(extraProps))
  6329. : [ref, normalizeRef(extraProps)]
  6330. : normalizeRef(extraProps)
  6331. : ref,
  6332. scopeId: vnode.scopeId,
  6333. children: vnode.children,
  6334. target: vnode.target,
  6335. targetAnchor: vnode.targetAnchor,
  6336. staticCount: vnode.staticCount,
  6337. shapeFlag: vnode.shapeFlag,
  6338. // if the vnode is cloned with extra props, we can no longer assume its
  6339. // existing patch flag to be reliable and need to add the FULL_PROPS flag.
  6340. // note: perserve flag for fragments since they use the flag for children
  6341. // fast paths only.
  6342. patchFlag: extraProps && vnode.type !== Fragment
  6343. ? patchFlag === -1 // hoisted node
  6344. ? 16 /* FULL_PROPS */
  6345. : patchFlag | 16 /* FULL_PROPS */
  6346. : patchFlag,
  6347. dynamicProps: vnode.dynamicProps,
  6348. dynamicChildren: vnode.dynamicChildren,
  6349. appContext: vnode.appContext,
  6350. dirs: vnode.dirs,
  6351. transition: vnode.transition,
  6352. // These should technically only be non-null on mounted VNodes. However,
  6353. // they *should* be copied for kept-alive vnodes. So we just always copy
  6354. // them since them being non-null during a mount doesn't affect the logic as
  6355. // they will simply be overwritten.
  6356. component: vnode.component,
  6357. suspense: vnode.suspense,
  6358. ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
  6359. ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
  6360. el: vnode.el,
  6361. anchor: vnode.anchor
  6362. };
  6363. }
  6364. /**
  6365. * @private
  6366. */
  6367. function createTextVNode(text = ' ', flag = 0) {
  6368. return createVNode(Text, null, text, flag);
  6369. }
  6370. /**
  6371. * @private
  6372. */
  6373. function createStaticVNode(content, numberOfNodes) {
  6374. // A static vnode can contain multiple stringified elements, and the number
  6375. // of elements is necessary for hydration.
  6376. const vnode = createVNode(Static, null, content);
  6377. vnode.staticCount = numberOfNodes;
  6378. return vnode;
  6379. }
  6380. /**
  6381. * @private
  6382. */
  6383. function createCommentVNode(text = '',
  6384. // when used as the v-else branch, the comment node must be created as a
  6385. // block to ensure correct updates.
  6386. asBlock = false) {
  6387. return asBlock
  6388. ? (openBlock(), createBlock(Comment, null, text))
  6389. : createVNode(Comment, null, text);
  6390. }
  6391. function normalizeVNode(child) {
  6392. if (child == null || typeof child === 'boolean') {
  6393. // empty placeholder
  6394. return createVNode(Comment);
  6395. }
  6396. else if (isArray(child)) {
  6397. // fragment
  6398. return createVNode(Fragment, null, child);
  6399. }
  6400. else if (typeof child === 'object') {
  6401. // already vnode, this should be the most common since compiled templates
  6402. // always produce all-vnode children arrays
  6403. return child.el === null ? child : cloneVNode(child);
  6404. }
  6405. else {
  6406. // strings and numbers
  6407. return createVNode(Text, null, String(child));
  6408. }
  6409. }
  6410. // optimized normalization for template-compiled render fns
  6411. function cloneIfMounted(child) {
  6412. return child.el === null ? child : cloneVNode(child);
  6413. }
  6414. function normalizeChildren(vnode, children) {
  6415. let type = 0;
  6416. const { shapeFlag } = vnode;
  6417. if (children == null) {
  6418. children = null;
  6419. }
  6420. else if (isArray(children)) {
  6421. type = 16 /* ARRAY_CHILDREN */;
  6422. }
  6423. else if (typeof children === 'object') {
  6424. if (shapeFlag & 1 /* ELEMENT */ || shapeFlag & 64 /* TELEPORT */) {
  6425. // Normalize slot to plain children for plain element and Teleport
  6426. const slot = children.default;
  6427. if (slot) {
  6428. // _c marker is added by withCtx() indicating this is a compiled slot
  6429. slot._c && setCompiledSlotRendering(1);
  6430. normalizeChildren(vnode, slot());
  6431. slot._c && setCompiledSlotRendering(-1);
  6432. }
  6433. return;
  6434. }
  6435. else {
  6436. type = 32 /* SLOTS_CHILDREN */;
  6437. const slotFlag = children._;
  6438. if (!slotFlag && !(InternalObjectKey in children)) {
  6439. children._ctx = currentRenderingInstance;
  6440. }
  6441. else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
  6442. // a child component receives forwarded slots from the parent.
  6443. // its slot type is determined by its parent's slot type.
  6444. if (currentRenderingInstance.vnode.patchFlag & 1024 /* DYNAMIC_SLOTS */) {
  6445. children._ = 2 /* DYNAMIC */;
  6446. vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  6447. }
  6448. else {
  6449. children._ = 1 /* STABLE */;
  6450. }
  6451. }
  6452. }
  6453. }
  6454. else if (isFunction(children)) {
  6455. children = { default: children, _ctx: currentRenderingInstance };
  6456. type = 32 /* SLOTS_CHILDREN */;
  6457. }
  6458. else {
  6459. children = String(children);
  6460. // force teleport children to array so it can be moved around
  6461. if (shapeFlag & 64 /* TELEPORT */) {
  6462. type = 16 /* ARRAY_CHILDREN */;
  6463. children = [createTextVNode(children)];
  6464. }
  6465. else {
  6466. type = 8 /* TEXT_CHILDREN */;
  6467. }
  6468. }
  6469. vnode.children = children;
  6470. vnode.shapeFlag |= type;
  6471. }
  6472. function mergeProps(...args) {
  6473. const ret = extend({}, args[0]);
  6474. for (let i = 1; i < args.length; i++) {
  6475. const toMerge = args[i];
  6476. for (const key in toMerge) {
  6477. if (key === 'class') {
  6478. if (ret.class !== toMerge.class) {
  6479. ret.class = normalizeClass([ret.class, toMerge.class]);
  6480. }
  6481. }
  6482. else if (key === 'style') {
  6483. ret.style = normalizeStyle([ret.style, toMerge.style]);
  6484. }
  6485. else if (isOn(key)) {
  6486. const existing = ret[key];
  6487. const incoming = toMerge[key];
  6488. if (existing !== incoming) {
  6489. ret[key] = existing
  6490. ? [].concat(existing, toMerge[key])
  6491. : incoming;
  6492. }
  6493. }
  6494. else if (key !== '') {
  6495. ret[key] = toMerge[key];
  6496. }
  6497. }
  6498. }
  6499. return ret;
  6500. }
  6501. function provide(key, value) {
  6502. if (!currentInstance) {
  6503. {
  6504. warn(`provide() can only be used inside setup().`);
  6505. }
  6506. }
  6507. else {
  6508. let provides = currentInstance.provides;
  6509. // by default an instance inherits its parent's provides object
  6510. // but when it needs to provide values of its own, it creates its
  6511. // own provides object using parent provides object as prototype.
  6512. // this way in `inject` we can simply look up injections from direct
  6513. // parent and let the prototype chain do the work.
  6514. const parentProvides = currentInstance.parent && currentInstance.parent.provides;
  6515. if (parentProvides === provides) {
  6516. provides = currentInstance.provides = Object.create(parentProvides);
  6517. }
  6518. // TS doesn't allow symbol as index type
  6519. provides[key] = value;
  6520. }
  6521. }
  6522. function inject(key, defaultValue, treatDefaultAsFactory = false) {
  6523. // fallback to `currentRenderingInstance` so that this can be called in
  6524. // a functional component
  6525. const instance = currentInstance || currentRenderingInstance;
  6526. if (instance) {
  6527. // #2400
  6528. // to support `app.use` plugins,
  6529. // fallback to appContext's `provides` if the intance is at root
  6530. const provides = instance.parent == null
  6531. ? instance.vnode.appContext && instance.vnode.appContext.provides
  6532. : instance.parent.provides;
  6533. if (provides && key in provides) {
  6534. // TS doesn't allow symbol as index type
  6535. return provides[key];
  6536. }
  6537. else if (arguments.length > 1) {
  6538. return treatDefaultAsFactory && isFunction(defaultValue)
  6539. ? defaultValue()
  6540. : defaultValue;
  6541. }
  6542. else {
  6543. warn(`injection "${String(key)}" not found.`);
  6544. }
  6545. }
  6546. else {
  6547. warn(`inject() can only be used inside setup() or functional components.`);
  6548. }
  6549. }
  6550. function createDuplicateChecker() {
  6551. const cache = Object.create(null);
  6552. return (type, key) => {
  6553. if (cache[key]) {
  6554. warn(`${type} property "${key}" is already defined in ${cache[key]}.`);
  6555. }
  6556. else {
  6557. cache[key] = type;
  6558. }
  6559. };
  6560. }
  6561. let isInBeforeCreate = false;
  6562. function applyOptions(instance, options, deferredData = [], deferredWatch = [], deferredProvide = [], asMixin = false) {
  6563. const {
  6564. // composition
  6565. mixins, extends: extendsOptions,
  6566. // state
  6567. data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
  6568. // assets
  6569. components, directives,
  6570. // lifecycle
  6571. beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured } = options;
  6572. const publicThis = instance.proxy;
  6573. const ctx = instance.ctx;
  6574. const globalMixins = instance.appContext.mixins;
  6575. if (asMixin && render && instance.render === NOOP) {
  6576. instance.render = render;
  6577. }
  6578. // applyOptions is called non-as-mixin once per instance
  6579. if (!asMixin) {
  6580. isInBeforeCreate = true;
  6581. callSyncHook('beforeCreate', "bc" /* BEFORE_CREATE */, options, instance, globalMixins);
  6582. isInBeforeCreate = false;
  6583. // global mixins are applied first
  6584. applyMixins(instance, globalMixins, deferredData, deferredWatch, deferredProvide);
  6585. }
  6586. // extending a base component...
  6587. if (extendsOptions) {
  6588. applyOptions(instance, extendsOptions, deferredData, deferredWatch, deferredProvide, true);
  6589. }
  6590. // local mixins
  6591. if (mixins) {
  6592. applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide);
  6593. }
  6594. const checkDuplicateProperties = createDuplicateChecker() ;
  6595. {
  6596. const [propsOptions] = instance.propsOptions;
  6597. if (propsOptions) {
  6598. for (const key in propsOptions) {
  6599. checkDuplicateProperties("Props" /* PROPS */, key);
  6600. }
  6601. }
  6602. }
  6603. // options initialization order (to be consistent with Vue 2):
  6604. // - props (already done outside of this function)
  6605. // - inject
  6606. // - methods
  6607. // - data (deferred since it relies on `this` access)
  6608. // - computed
  6609. // - watch (deferred since it relies on `this` access)
  6610. if (injectOptions) {
  6611. if (isArray(injectOptions)) {
  6612. for (let i = 0; i < injectOptions.length; i++) {
  6613. const key = injectOptions[i];
  6614. ctx[key] = inject(key);
  6615. {
  6616. checkDuplicateProperties("Inject" /* INJECT */, key);
  6617. }
  6618. }
  6619. }
  6620. else {
  6621. for (const key in injectOptions) {
  6622. const opt = injectOptions[key];
  6623. if (isObject(opt)) {
  6624. ctx[key] = inject(opt.from || key, opt.default, true /* treat default function as factory */);
  6625. }
  6626. else {
  6627. ctx[key] = inject(opt);
  6628. }
  6629. {
  6630. checkDuplicateProperties("Inject" /* INJECT */, key);
  6631. }
  6632. }
  6633. }
  6634. }
  6635. if (methods) {
  6636. for (const key in methods) {
  6637. const methodHandler = methods[key];
  6638. if (isFunction(methodHandler)) {
  6639. ctx[key] = methodHandler.bind(publicThis);
  6640. {
  6641. checkDuplicateProperties("Methods" /* METHODS */, key);
  6642. }
  6643. }
  6644. else {
  6645. warn(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
  6646. `Did you reference the function correctly?`);
  6647. }
  6648. }
  6649. }
  6650. if (!asMixin) {
  6651. if (deferredData.length) {
  6652. deferredData.forEach(dataFn => resolveData(instance, dataFn, publicThis));
  6653. }
  6654. if (dataOptions) {
  6655. resolveData(instance, dataOptions, publicThis);
  6656. }
  6657. {
  6658. const rawData = toRaw(instance.data);
  6659. for (const key in rawData) {
  6660. checkDuplicateProperties("Data" /* DATA */, key);
  6661. // expose data on ctx during dev
  6662. if (key[0] !== '$' && key[0] !== '_') {
  6663. Object.defineProperty(ctx, key, {
  6664. configurable: true,
  6665. enumerable: true,
  6666. get: () => rawData[key],
  6667. set: NOOP
  6668. });
  6669. }
  6670. }
  6671. }
  6672. }
  6673. else if (dataOptions) {
  6674. deferredData.push(dataOptions);
  6675. }
  6676. if (computedOptions) {
  6677. for (const key in computedOptions) {
  6678. const opt = computedOptions[key];
  6679. const get = isFunction(opt)
  6680. ? opt.bind(publicThis, publicThis)
  6681. : isFunction(opt.get)
  6682. ? opt.get.bind(publicThis, publicThis)
  6683. : NOOP;
  6684. if ( get === NOOP) {
  6685. warn(`Computed property "${key}" has no getter.`);
  6686. }
  6687. const set = !isFunction(opt) && isFunction(opt.set)
  6688. ? opt.set.bind(publicThis)
  6689. : () => {
  6690. warn(`Write operation failed: computed property "${key}" is readonly.`);
  6691. }
  6692. ;
  6693. const c = computed$1({
  6694. get,
  6695. set
  6696. });
  6697. Object.defineProperty(ctx, key, {
  6698. enumerable: true,
  6699. configurable: true,
  6700. get: () => c.value,
  6701. set: v => (c.value = v)
  6702. });
  6703. {
  6704. checkDuplicateProperties("Computed" /* COMPUTED */, key);
  6705. }
  6706. }
  6707. }
  6708. if (watchOptions) {
  6709. deferredWatch.push(watchOptions);
  6710. }
  6711. if (!asMixin && deferredWatch.length) {
  6712. deferredWatch.forEach(watchOptions => {
  6713. for (const key in watchOptions) {
  6714. createWatcher(watchOptions[key], ctx, publicThis, key);
  6715. }
  6716. });
  6717. }
  6718. if (provideOptions) {
  6719. deferredProvide.push(provideOptions);
  6720. }
  6721. if (!asMixin && deferredProvide.length) {
  6722. deferredProvide.forEach(provideOptions => {
  6723. const provides = isFunction(provideOptions)
  6724. ? provideOptions.call(publicThis)
  6725. : provideOptions;
  6726. for (const key in provides) {
  6727. provide(key, provides[key]);
  6728. }
  6729. });
  6730. }
  6731. // asset options.
  6732. // To reduce memory usage, only components with mixins or extends will have
  6733. // resolved asset registry attached to instance.
  6734. if (asMixin) {
  6735. if (components) {
  6736. extend(instance.components ||
  6737. (instance.components = extend({}, instance.type.components)), components);
  6738. }
  6739. if (directives) {
  6740. extend(instance.directives ||
  6741. (instance.directives = extend({}, instance.type.directives)), directives);
  6742. }
  6743. }
  6744. // lifecycle options
  6745. if (!asMixin) {
  6746. callSyncHook('created', "c" /* CREATED */, options, instance, globalMixins);
  6747. }
  6748. if (beforeMount) {
  6749. onBeforeMount(beforeMount.bind(publicThis));
  6750. }
  6751. if (mounted) {
  6752. onMounted(mounted.bind(publicThis));
  6753. }
  6754. if (beforeUpdate) {
  6755. onBeforeUpdate(beforeUpdate.bind(publicThis));
  6756. }
  6757. if (updated) {
  6758. onUpdated(updated.bind(publicThis));
  6759. }
  6760. if (activated) {
  6761. onActivated(activated.bind(publicThis));
  6762. }
  6763. if (deactivated) {
  6764. onDeactivated(deactivated.bind(publicThis));
  6765. }
  6766. if (errorCaptured) {
  6767. onErrorCaptured(errorCaptured.bind(publicThis));
  6768. }
  6769. if (renderTracked) {
  6770. onRenderTracked(renderTracked.bind(publicThis));
  6771. }
  6772. if (renderTriggered) {
  6773. onRenderTriggered(renderTriggered.bind(publicThis));
  6774. }
  6775. if ( beforeDestroy) {
  6776. warn(`\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`);
  6777. }
  6778. if (beforeUnmount) {
  6779. onBeforeUnmount(beforeUnmount.bind(publicThis));
  6780. }
  6781. if ( destroyed) {
  6782. warn(`\`destroyed\` has been renamed to \`unmounted\`.`);
  6783. }
  6784. if (unmounted) {
  6785. onUnmounted(unmounted.bind(publicThis));
  6786. }
  6787. }
  6788. function callSyncHook(name, type, options, instance, globalMixins) {
  6789. callHookFromMixins(name, type, globalMixins, instance);
  6790. const { extends: base, mixins } = options;
  6791. if (base) {
  6792. callHookFromExtends(name, type, base, instance);
  6793. }
  6794. if (mixins) {
  6795. callHookFromMixins(name, type, mixins, instance);
  6796. }
  6797. const selfHook = options[name];
  6798. if (selfHook) {
  6799. callWithAsyncErrorHandling(selfHook.bind(instance.proxy), instance, type);
  6800. }
  6801. }
  6802. function callHookFromExtends(name, type, base, instance) {
  6803. if (base.extends) {
  6804. callHookFromExtends(name, type, base.extends, instance);
  6805. }
  6806. const baseHook = base[name];
  6807. if (baseHook) {
  6808. callWithAsyncErrorHandling(baseHook.bind(instance.proxy), instance, type);
  6809. }
  6810. }
  6811. function callHookFromMixins(name, type, mixins, instance) {
  6812. for (let i = 0; i < mixins.length; i++) {
  6813. const chainedMixins = mixins[i].mixins;
  6814. if (chainedMixins) {
  6815. callHookFromMixins(name, type, chainedMixins, instance);
  6816. }
  6817. const fn = mixins[i][name];
  6818. if (fn) {
  6819. callWithAsyncErrorHandling(fn.bind(instance.proxy), instance, type);
  6820. }
  6821. }
  6822. }
  6823. function applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide) {
  6824. for (let i = 0; i < mixins.length; i++) {
  6825. applyOptions(instance, mixins[i], deferredData, deferredWatch, deferredProvide, true);
  6826. }
  6827. }
  6828. function resolveData(instance, dataFn, publicThis) {
  6829. if ( !isFunction(dataFn)) {
  6830. warn(`The data option must be a function. ` +
  6831. `Plain object usage is no longer supported.`);
  6832. }
  6833. const data = dataFn.call(publicThis, publicThis);
  6834. if ( isPromise(data)) {
  6835. warn(`data() returned a Promise - note data() cannot be async; If you ` +
  6836. `intend to perform data fetching before component renders, use ` +
  6837. `async setup() + <Suspense>.`);
  6838. }
  6839. if (!isObject(data)) {
  6840. warn(`data() should return an object.`);
  6841. }
  6842. else if (instance.data === EMPTY_OBJ) {
  6843. instance.data = reactive(data);
  6844. }
  6845. else {
  6846. // existing data: this is a mixin or extends.
  6847. extend(instance.data, data);
  6848. }
  6849. }
  6850. function createWatcher(raw, ctx, publicThis, key) {
  6851. const getter = key.includes('.')
  6852. ? createPathGetter(publicThis, key)
  6853. : () => publicThis[key];
  6854. if (isString(raw)) {
  6855. const handler = ctx[raw];
  6856. if (isFunction(handler)) {
  6857. watch(getter, handler);
  6858. }
  6859. else {
  6860. warn(`Invalid watch handler specified by key "${raw}"`, handler);
  6861. }
  6862. }
  6863. else if (isFunction(raw)) {
  6864. watch(getter, raw.bind(publicThis));
  6865. }
  6866. else if (isObject(raw)) {
  6867. if (isArray(raw)) {
  6868. raw.forEach(r => createWatcher(r, ctx, publicThis, key));
  6869. }
  6870. else {
  6871. const handler = isFunction(raw.handler)
  6872. ? raw.handler.bind(publicThis)
  6873. : ctx[raw.handler];
  6874. if (isFunction(handler)) {
  6875. watch(getter, handler, raw);
  6876. }
  6877. else {
  6878. warn(`Invalid watch handler specified by key "${raw.handler}"`, handler);
  6879. }
  6880. }
  6881. }
  6882. else {
  6883. warn(`Invalid watch option: "${key}"`, raw);
  6884. }
  6885. }
  6886. function createPathGetter(ctx, path) {
  6887. const segments = path.split('.');
  6888. return () => {
  6889. let cur = ctx;
  6890. for (let i = 0; i < segments.length && cur; i++) {
  6891. cur = cur[segments[i]];
  6892. }
  6893. return cur;
  6894. };
  6895. }
  6896. function resolveMergedOptions(instance) {
  6897. const raw = instance.type;
  6898. const { __merged, mixins, extends: extendsOptions } = raw;
  6899. if (__merged)
  6900. return __merged;
  6901. const globalMixins = instance.appContext.mixins;
  6902. if (!globalMixins.length && !mixins && !extendsOptions)
  6903. return raw;
  6904. const options = {};
  6905. globalMixins.forEach(m => mergeOptions(options, m, instance));
  6906. mergeOptions(options, raw, instance);
  6907. return (raw.__merged = options);
  6908. }
  6909. function mergeOptions(to, from, instance) {
  6910. const strats = instance.appContext.config.optionMergeStrategies;
  6911. const { mixins, extends: extendsOptions } = from;
  6912. extendsOptions && mergeOptions(to, extendsOptions, instance);
  6913. mixins &&
  6914. mixins.forEach((m) => mergeOptions(to, m, instance));
  6915. for (const key in from) {
  6916. if (strats && hasOwn(strats, key)) {
  6917. to[key] = strats[key](to[key], from[key], instance.proxy, key);
  6918. }
  6919. else {
  6920. to[key] = from[key];
  6921. }
  6922. }
  6923. }
  6924. const publicPropertiesMap = extend(Object.create(null), {
  6925. $: i => i,
  6926. $el: i => i.vnode.el,
  6927. $data: i => i.data,
  6928. $props: i => ( shallowReadonly(i.props) ),
  6929. $attrs: i => ( shallowReadonly(i.attrs) ),
  6930. $slots: i => ( shallowReadonly(i.slots) ),
  6931. $refs: i => ( shallowReadonly(i.refs) ),
  6932. $parent: i => i.parent && i.parent.proxy,
  6933. $root: i => i.root && i.root.proxy,
  6934. $emit: i => i.emit,
  6935. $options: i => ( resolveMergedOptions(i) ),
  6936. $forceUpdate: i => () => queueJob(i.update),
  6937. $nextTick: i => nextTick.bind(i.proxy),
  6938. $watch: i => ( instanceWatch.bind(i) )
  6939. });
  6940. const PublicInstanceProxyHandlers = {
  6941. get({ _: instance }, key) {
  6942. const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
  6943. // let @vue/reactivity know it should never observe Vue public instances.
  6944. if (key === "__v_skip" /* SKIP */) {
  6945. return true;
  6946. }
  6947. // for internal formatters to know that this is a Vue instance
  6948. if ( key === '__isVue') {
  6949. return true;
  6950. }
  6951. // data / props / ctx
  6952. // This getter gets called for every property access on the render context
  6953. // during render and is a major hotspot. The most expensive part of this
  6954. // is the multiple hasOwn() calls. It's much faster to do a simple property
  6955. // access on a plain object, so we use an accessCache object (with null
  6956. // prototype) to memoize what access type a key corresponds to.
  6957. let normalizedProps;
  6958. if (key[0] !== '$') {
  6959. const n = accessCache[key];
  6960. if (n !== undefined) {
  6961. switch (n) {
  6962. case 0 /* SETUP */:
  6963. return setupState[key];
  6964. case 1 /* DATA */:
  6965. return data[key];
  6966. case 3 /* CONTEXT */:
  6967. return ctx[key];
  6968. case 2 /* PROPS */:
  6969. return props[key];
  6970. // default: just fallthrough
  6971. }
  6972. }
  6973. else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  6974. accessCache[key] = 0 /* SETUP */;
  6975. return setupState[key];
  6976. }
  6977. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  6978. accessCache[key] = 1 /* DATA */;
  6979. return data[key];
  6980. }
  6981. else if (
  6982. // only cache other properties when instance has declared (thus stable)
  6983. // props
  6984. (normalizedProps = instance.propsOptions[0]) &&
  6985. hasOwn(normalizedProps, key)) {
  6986. accessCache[key] = 2 /* PROPS */;
  6987. return props[key];
  6988. }
  6989. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  6990. accessCache[key] = 3 /* CONTEXT */;
  6991. return ctx[key];
  6992. }
  6993. else if ( !isInBeforeCreate) {
  6994. accessCache[key] = 4 /* OTHER */;
  6995. }
  6996. }
  6997. const publicGetter = publicPropertiesMap[key];
  6998. let cssModule, globalProperties;
  6999. // public $xxx properties
  7000. if (publicGetter) {
  7001. if (key === '$attrs') {
  7002. track(instance, "get" /* GET */, key);
  7003. markAttrsAccessed();
  7004. }
  7005. return publicGetter(instance);
  7006. }
  7007. else if (
  7008. // css module (injected by vue-loader)
  7009. (cssModule = type.__cssModules) &&
  7010. (cssModule = cssModule[key])) {
  7011. return cssModule;
  7012. }
  7013. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  7014. // user may set custom properties to `this` that start with `$`
  7015. accessCache[key] = 3 /* CONTEXT */;
  7016. return ctx[key];
  7017. }
  7018. else if (
  7019. // global properties
  7020. ((globalProperties = appContext.config.globalProperties),
  7021. hasOwn(globalProperties, key))) {
  7022. return globalProperties[key];
  7023. }
  7024. else if (
  7025. currentRenderingInstance &&
  7026. (!isString(key) ||
  7027. // #1091 avoid internal isRef/isVNode checks on component instance leading
  7028. // to infinite warning loop
  7029. key.indexOf('__v') !== 0)) {
  7030. if (data !== EMPTY_OBJ &&
  7031. (key[0] === '$' || key[0] === '_') &&
  7032. hasOwn(data, key)) {
  7033. warn(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
  7034. `character ("$" or "_") and is not proxied on the render context.`);
  7035. }
  7036. else {
  7037. warn(`Property ${JSON.stringify(key)} was accessed during render ` +
  7038. `but is not defined on instance.`);
  7039. }
  7040. }
  7041. },
  7042. set({ _: instance }, key, value) {
  7043. const { data, setupState, ctx } = instance;
  7044. if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  7045. setupState[key] = value;
  7046. }
  7047. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  7048. data[key] = value;
  7049. }
  7050. else if (key in instance.props) {
  7051. warn(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
  7052. return false;
  7053. }
  7054. if (key[0] === '$' && key.slice(1) in instance) {
  7055. warn(`Attempting to mutate public property "${key}". ` +
  7056. `Properties starting with $ are reserved and readonly.`, instance);
  7057. return false;
  7058. }
  7059. else {
  7060. if ( key in instance.appContext.config.globalProperties) {
  7061. Object.defineProperty(ctx, key, {
  7062. enumerable: true,
  7063. configurable: true,
  7064. value
  7065. });
  7066. }
  7067. else {
  7068. ctx[key] = value;
  7069. }
  7070. }
  7071. return true;
  7072. },
  7073. has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
  7074. let normalizedProps;
  7075. return (accessCache[key] !== undefined ||
  7076. (data !== EMPTY_OBJ && hasOwn(data, key)) ||
  7077. (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
  7078. ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
  7079. hasOwn(ctx, key) ||
  7080. hasOwn(publicPropertiesMap, key) ||
  7081. hasOwn(appContext.config.globalProperties, key));
  7082. }
  7083. };
  7084. {
  7085. PublicInstanceProxyHandlers.ownKeys = (target) => {
  7086. warn(`Avoid app logic that relies on enumerating keys on a component instance. ` +
  7087. `The keys will be empty in production mode to avoid performance overhead.`);
  7088. return Reflect.ownKeys(target);
  7089. };
  7090. }
  7091. const RuntimeCompiledPublicInstanceProxyHandlers = extend({}, PublicInstanceProxyHandlers, {
  7092. get(target, key) {
  7093. // fast path for unscopables when using `with` block
  7094. if (key === Symbol.unscopables) {
  7095. return;
  7096. }
  7097. return PublicInstanceProxyHandlers.get(target, key, target);
  7098. },
  7099. has(_, key) {
  7100. const has = key[0] !== '_' && !isGloballyWhitelisted(key);
  7101. if ( !has && PublicInstanceProxyHandlers.has(_, key)) {
  7102. warn(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
  7103. }
  7104. return has;
  7105. }
  7106. });
  7107. // In dev mode, the proxy target exposes the same properties as seen on `this`
  7108. // for easier console inspection. In prod mode it will be an empty object so
  7109. // these properties definitions can be skipped.
  7110. function createRenderContext(instance) {
  7111. const target = {};
  7112. // expose internal instance for proxy handlers
  7113. Object.defineProperty(target, `_`, {
  7114. configurable: true,
  7115. enumerable: false,
  7116. get: () => instance
  7117. });
  7118. // expose public properties
  7119. Object.keys(publicPropertiesMap).forEach(key => {
  7120. Object.defineProperty(target, key, {
  7121. configurable: true,
  7122. enumerable: false,
  7123. get: () => publicPropertiesMap[key](instance),
  7124. // intercepted by the proxy so no need for implementation,
  7125. // but needed to prevent set errors
  7126. set: NOOP
  7127. });
  7128. });
  7129. // expose global properties
  7130. const { globalProperties } = instance.appContext.config;
  7131. Object.keys(globalProperties).forEach(key => {
  7132. Object.defineProperty(target, key, {
  7133. configurable: true,
  7134. enumerable: false,
  7135. get: () => globalProperties[key],
  7136. set: NOOP
  7137. });
  7138. });
  7139. return target;
  7140. }
  7141. // dev only
  7142. function exposePropsOnRenderContext(instance) {
  7143. const { ctx, propsOptions: [propsOptions] } = instance;
  7144. if (propsOptions) {
  7145. Object.keys(propsOptions).forEach(key => {
  7146. Object.defineProperty(ctx, key, {
  7147. enumerable: true,
  7148. configurable: true,
  7149. get: () => instance.props[key],
  7150. set: NOOP
  7151. });
  7152. });
  7153. }
  7154. }
  7155. // dev only
  7156. function exposeSetupStateOnRenderContext(instance) {
  7157. const { ctx, setupState } = instance;
  7158. Object.keys(toRaw(setupState)).forEach(key => {
  7159. if (key[0] === '$' || key[0] === '_') {
  7160. warn(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
  7161. `which are reserved prefixes for Vue internals.`);
  7162. return;
  7163. }
  7164. Object.defineProperty(ctx, key, {
  7165. enumerable: true,
  7166. configurable: true,
  7167. get: () => setupState[key],
  7168. set: NOOP
  7169. });
  7170. });
  7171. }
  7172. const emptyAppContext = createAppContext();
  7173. let uid$2 = 0;
  7174. function createComponentInstance(vnode, parent, suspense) {
  7175. const type = vnode.type;
  7176. // inherit parent app context - or - if root, adopt from root vnode
  7177. const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
  7178. const instance = {
  7179. uid: uid$2++,
  7180. vnode,
  7181. type,
  7182. parent,
  7183. appContext,
  7184. root: null,
  7185. next: null,
  7186. subTree: null,
  7187. update: null,
  7188. render: null,
  7189. proxy: null,
  7190. withProxy: null,
  7191. effects: null,
  7192. provides: parent ? parent.provides : Object.create(appContext.provides),
  7193. accessCache: null,
  7194. renderCache: [],
  7195. // local resovled assets
  7196. components: null,
  7197. directives: null,
  7198. // resolved props and emits options
  7199. propsOptions: normalizePropsOptions(type, appContext),
  7200. emitsOptions: normalizeEmitsOptions(type, appContext),
  7201. // emit
  7202. emit: null,
  7203. emitted: null,
  7204. // state
  7205. ctx: EMPTY_OBJ,
  7206. data: EMPTY_OBJ,
  7207. props: EMPTY_OBJ,
  7208. attrs: EMPTY_OBJ,
  7209. slots: EMPTY_OBJ,
  7210. refs: EMPTY_OBJ,
  7211. setupState: EMPTY_OBJ,
  7212. setupContext: null,
  7213. // suspense related
  7214. suspense,
  7215. suspenseId: suspense ? suspense.pendingId : 0,
  7216. asyncDep: null,
  7217. asyncResolved: false,
  7218. // lifecycle hooks
  7219. // not using enums here because it results in computed properties
  7220. isMounted: false,
  7221. isUnmounted: false,
  7222. isDeactivated: false,
  7223. bc: null,
  7224. c: null,
  7225. bm: null,
  7226. m: null,
  7227. bu: null,
  7228. u: null,
  7229. um: null,
  7230. bum: null,
  7231. da: null,
  7232. a: null,
  7233. rtg: null,
  7234. rtc: null,
  7235. ec: null
  7236. };
  7237. {
  7238. instance.ctx = createRenderContext(instance);
  7239. }
  7240. instance.root = parent ? parent.root : instance;
  7241. instance.emit = emit.bind(null, instance);
  7242. {
  7243. devtoolsComponentAdded(instance);
  7244. }
  7245. return instance;
  7246. }
  7247. let currentInstance = null;
  7248. const getCurrentInstance = () => currentInstance || currentRenderingInstance;
  7249. const setCurrentInstance = (instance) => {
  7250. currentInstance = instance;
  7251. };
  7252. const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
  7253. function validateComponentName(name, config) {
  7254. const appIsNativeTag = config.isNativeTag || NO;
  7255. if (isBuiltInTag(name) || appIsNativeTag(name)) {
  7256. warn('Do not use built-in or reserved HTML elements as component id: ' + name);
  7257. }
  7258. }
  7259. let isInSSRComponentSetup = false;
  7260. function setupComponent(instance, isSSR = false) {
  7261. isInSSRComponentSetup = isSSR;
  7262. const { props, children, shapeFlag } = instance.vnode;
  7263. const isStateful = shapeFlag & 4 /* STATEFUL_COMPONENT */;
  7264. initProps(instance, props, isStateful, isSSR);
  7265. initSlots(instance, children);
  7266. const setupResult = isStateful
  7267. ? setupStatefulComponent(instance, isSSR)
  7268. : undefined;
  7269. isInSSRComponentSetup = false;
  7270. return setupResult;
  7271. }
  7272. function setupStatefulComponent(instance, isSSR) {
  7273. const Component = instance.type;
  7274. {
  7275. if (Component.name) {
  7276. validateComponentName(Component.name, instance.appContext.config);
  7277. }
  7278. if (Component.components) {
  7279. const names = Object.keys(Component.components);
  7280. for (let i = 0; i < names.length; i++) {
  7281. validateComponentName(names[i], instance.appContext.config);
  7282. }
  7283. }
  7284. if (Component.directives) {
  7285. const names = Object.keys(Component.directives);
  7286. for (let i = 0; i < names.length; i++) {
  7287. validateDirectiveName(names[i]);
  7288. }
  7289. }
  7290. }
  7291. // 0. create render proxy property access cache
  7292. instance.accessCache = Object.create(null);
  7293. // 1. create public instance / render proxy
  7294. // also mark it raw so it's never observed
  7295. instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);
  7296. {
  7297. exposePropsOnRenderContext(instance);
  7298. }
  7299. // 2. call setup()
  7300. const { setup } = Component;
  7301. if (setup) {
  7302. const setupContext = (instance.setupContext =
  7303. setup.length > 1 ? createSetupContext(instance) : null);
  7304. currentInstance = instance;
  7305. pauseTracking();
  7306. const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [ shallowReadonly(instance.props) , setupContext]);
  7307. resetTracking();
  7308. currentInstance = null;
  7309. if (isPromise(setupResult)) {
  7310. if (isSSR) {
  7311. // return the promise so server-renderer can wait on it
  7312. return setupResult.then((resolvedResult) => {
  7313. handleSetupResult(instance, resolvedResult);
  7314. });
  7315. }
  7316. else {
  7317. // async setup returned Promise.
  7318. // bail here and wait for re-entry.
  7319. instance.asyncDep = setupResult;
  7320. }
  7321. }
  7322. else {
  7323. handleSetupResult(instance, setupResult);
  7324. }
  7325. }
  7326. else {
  7327. finishComponentSetup(instance);
  7328. }
  7329. }
  7330. function handleSetupResult(instance, setupResult, isSSR) {
  7331. if (isFunction(setupResult)) {
  7332. // setup returned an inline render function
  7333. instance.render = setupResult;
  7334. }
  7335. else if (isObject(setupResult)) {
  7336. if ( isVNode(setupResult)) {
  7337. warn(`setup() should not return VNodes directly - ` +
  7338. `return a render function instead.`);
  7339. }
  7340. // setup returned bindings.
  7341. // assuming a render function compiled from template is present.
  7342. {
  7343. instance.devtoolsRawSetupState = setupResult;
  7344. }
  7345. instance.setupState = proxyRefs(setupResult);
  7346. {
  7347. exposeSetupStateOnRenderContext(instance);
  7348. }
  7349. }
  7350. else if ( setupResult !== undefined) {
  7351. warn(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
  7352. }
  7353. finishComponentSetup(instance);
  7354. }
  7355. let compile;
  7356. /**
  7357. * For runtime-dom to register the compiler.
  7358. * Note the exported method uses any to avoid d.ts relying on the compiler types.
  7359. */
  7360. function registerRuntimeCompiler(_compile) {
  7361. compile = _compile;
  7362. }
  7363. function finishComponentSetup(instance, isSSR) {
  7364. const Component = instance.type;
  7365. // template / render function normalization
  7366. if (!instance.render) {
  7367. // could be set from setup()
  7368. if (compile && Component.template && !Component.render) {
  7369. {
  7370. startMeasure(instance, `compile`);
  7371. }
  7372. Component.render = compile(Component.template, {
  7373. isCustomElement: instance.appContext.config.isCustomElement,
  7374. delimiters: Component.delimiters
  7375. });
  7376. {
  7377. endMeasure(instance, `compile`);
  7378. }
  7379. }
  7380. instance.render = (Component.render || NOOP);
  7381. // for runtime-compiled render functions using `with` blocks, the render
  7382. // proxy used needs a different `has` handler which is more performant and
  7383. // also only allows a whitelist of globals to fallthrough.
  7384. if (instance.render._rc) {
  7385. instance.withProxy = new Proxy(instance.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
  7386. }
  7387. }
  7388. // support for 2.x options
  7389. {
  7390. currentInstance = instance;
  7391. applyOptions(instance, Component);
  7392. currentInstance = null;
  7393. }
  7394. // warn missing template/render
  7395. if ( !Component.render && instance.render === NOOP) {
  7396. /* istanbul ignore if */
  7397. if (!compile && Component.template) {
  7398. warn(`Component provided template option but ` +
  7399. `runtime compilation is not supported in this build of Vue.` +
  7400. ( ` Use "vue.esm-browser.js" instead.`
  7401. ) /* should not happen */);
  7402. }
  7403. else {
  7404. warn(`Component is missing template or render function.`);
  7405. }
  7406. }
  7407. }
  7408. const attrHandlers = {
  7409. get: (target, key) => {
  7410. {
  7411. markAttrsAccessed();
  7412. }
  7413. return target[key];
  7414. },
  7415. set: () => {
  7416. warn(`setupContext.attrs is readonly.`);
  7417. return false;
  7418. },
  7419. deleteProperty: () => {
  7420. warn(`setupContext.attrs is readonly.`);
  7421. return false;
  7422. }
  7423. };
  7424. function createSetupContext(instance) {
  7425. {
  7426. // We use getters in dev in case libs like test-utils overwrite instance
  7427. // properties (overwrites should not be done in prod)
  7428. return Object.freeze({
  7429. get attrs() {
  7430. return new Proxy(instance.attrs, attrHandlers);
  7431. },
  7432. get slots() {
  7433. return shallowReadonly(instance.slots);
  7434. },
  7435. get emit() {
  7436. return (event, ...args) => instance.emit(event, ...args);
  7437. }
  7438. });
  7439. }
  7440. }
  7441. // record effects created during a component's setup() so that they can be
  7442. // stopped when the component unmounts
  7443. function recordInstanceBoundEffect(effect) {
  7444. if (currentInstance) {
  7445. (currentInstance.effects || (currentInstance.effects = [])).push(effect);
  7446. }
  7447. }
  7448. const classifyRE = /(?:^|[-_])(\w)/g;
  7449. const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
  7450. /* istanbul ignore next */
  7451. function formatComponentName(instance, Component, isRoot = false) {
  7452. let name = isFunction(Component)
  7453. ? Component.displayName || Component.name
  7454. : Component.name;
  7455. if (!name && Component.__file) {
  7456. const match = Component.__file.match(/([^/\\]+)\.vue$/);
  7457. if (match) {
  7458. name = match[1];
  7459. }
  7460. }
  7461. if (!name && instance && instance.parent) {
  7462. // try to infer the name based on reverse resolution
  7463. const inferFromRegistry = (registry) => {
  7464. for (const key in registry) {
  7465. if (registry[key] === Component) {
  7466. return key;
  7467. }
  7468. }
  7469. };
  7470. name =
  7471. inferFromRegistry(instance.components ||
  7472. instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
  7473. }
  7474. return name ? classify(name) : isRoot ? `App` : `Anonymous`;
  7475. }
  7476. function isClassComponent(value) {
  7477. return isFunction(value) && '__vccOpts' in value;
  7478. }
  7479. function computed$1(getterOrOptions) {
  7480. const c = computed(getterOrOptions);
  7481. recordInstanceBoundEffect(c.effect);
  7482. return c;
  7483. }
  7484. // implementation, close to no-op
  7485. function defineComponent(options) {
  7486. return isFunction(options) ? { setup: options, name: options.name } : options;
  7487. }
  7488. function defineAsyncComponent(source) {
  7489. if (isFunction(source)) {
  7490. source = { loader: source };
  7491. }
  7492. const { loader, loadingComponent: loadingComponent, errorComponent: errorComponent, delay = 200, timeout, // undefined = never times out
  7493. suspensible = true, onError: userOnError } = source;
  7494. let pendingRequest = null;
  7495. let resolvedComp;
  7496. let retries = 0;
  7497. const retry = () => {
  7498. retries++;
  7499. pendingRequest = null;
  7500. return load();
  7501. };
  7502. const load = () => {
  7503. let thisRequest;
  7504. return (pendingRequest ||
  7505. (thisRequest = pendingRequest = loader()
  7506. .catch(err => {
  7507. err = err instanceof Error ? err : new Error(String(err));
  7508. if (userOnError) {
  7509. return new Promise((resolve, reject) => {
  7510. const userRetry = () => resolve(retry());
  7511. const userFail = () => reject(err);
  7512. userOnError(err, userRetry, userFail, retries + 1);
  7513. });
  7514. }
  7515. else {
  7516. throw err;
  7517. }
  7518. })
  7519. .then((comp) => {
  7520. if (thisRequest !== pendingRequest && pendingRequest) {
  7521. return pendingRequest;
  7522. }
  7523. if ( !comp) {
  7524. warn(`Async component loader resolved to undefined. ` +
  7525. `If you are using retry(), make sure to return its return value.`);
  7526. }
  7527. // interop module default
  7528. if (comp &&
  7529. (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
  7530. comp = comp.default;
  7531. }
  7532. if ( comp && !isObject(comp) && !isFunction(comp)) {
  7533. throw new Error(`Invalid async component load result: ${comp}`);
  7534. }
  7535. resolvedComp = comp;
  7536. return comp;
  7537. })));
  7538. };
  7539. return defineComponent({
  7540. __asyncLoader: load,
  7541. name: 'AsyncComponentWrapper',
  7542. setup() {
  7543. const instance = currentInstance;
  7544. // already resolved
  7545. if (resolvedComp) {
  7546. return () => createInnerComp(resolvedComp, instance);
  7547. }
  7548. const onError = (err) => {
  7549. pendingRequest = null;
  7550. handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
  7551. };
  7552. // suspense-controlled or SSR.
  7553. if (( suspensible && instance.suspense) ||
  7554. (false )) {
  7555. return load()
  7556. .then(comp => {
  7557. return () => createInnerComp(comp, instance);
  7558. })
  7559. .catch(err => {
  7560. onError(err);
  7561. return () => errorComponent
  7562. ? createVNode(errorComponent, {
  7563. error: err
  7564. })
  7565. : null;
  7566. });
  7567. }
  7568. const loaded = ref(false);
  7569. const error = ref();
  7570. const delayed = ref(!!delay);
  7571. if (delay) {
  7572. setTimeout(() => {
  7573. delayed.value = false;
  7574. }, delay);
  7575. }
  7576. if (timeout != null) {
  7577. setTimeout(() => {
  7578. if (!loaded.value && !error.value) {
  7579. const err = new Error(`Async component timed out after ${timeout}ms.`);
  7580. onError(err);
  7581. error.value = err;
  7582. }
  7583. }, timeout);
  7584. }
  7585. load()
  7586. .then(() => {
  7587. loaded.value = true;
  7588. })
  7589. .catch(err => {
  7590. onError(err);
  7591. error.value = err;
  7592. });
  7593. return () => {
  7594. if (loaded.value && resolvedComp) {
  7595. return createInnerComp(resolvedComp, instance);
  7596. }
  7597. else if (error.value && errorComponent) {
  7598. return createVNode(errorComponent, {
  7599. error: error.value
  7600. });
  7601. }
  7602. else if (loadingComponent && !delayed.value) {
  7603. return createVNode(loadingComponent);
  7604. }
  7605. };
  7606. }
  7607. });
  7608. }
  7609. function createInnerComp(comp, { vnode: { props, children } }) {
  7610. return createVNode(comp, props, children);
  7611. }
  7612. // Actual implementation
  7613. function h(type, propsOrChildren, children) {
  7614. const l = arguments.length;
  7615. if (l === 2) {
  7616. if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
  7617. // single vnode without props
  7618. if (isVNode(propsOrChildren)) {
  7619. return createVNode(type, null, [propsOrChildren]);
  7620. }
  7621. // props without children
  7622. return createVNode(type, propsOrChildren);
  7623. }
  7624. else {
  7625. // omit props
  7626. return createVNode(type, null, propsOrChildren);
  7627. }
  7628. }
  7629. else {
  7630. if (l > 3) {
  7631. children = Array.prototype.slice.call(arguments, 2);
  7632. }
  7633. else if (l === 3 && isVNode(children)) {
  7634. children = [children];
  7635. }
  7636. return createVNode(type, propsOrChildren, children);
  7637. }
  7638. }
  7639. const ssrContextKey = Symbol( `ssrContext` );
  7640. const useSSRContext = () => {
  7641. {
  7642. const ctx = inject(ssrContextKey);
  7643. if (!ctx) {
  7644. warn(`Server rendering context not provided. Make sure to only call ` +
  7645. `useSsrContext() conditionally in the server build.`);
  7646. }
  7647. return ctx;
  7648. }
  7649. };
  7650. function initCustomFormatter() {
  7651. const vueStyle = { style: 'color:#3ba776' };
  7652. const numberStyle = { style: 'color:#0b1bc9' };
  7653. const stringStyle = { style: 'color:#b62e24' };
  7654. const keywordStyle = { style: 'color:#9d288c' };
  7655. // custom formatter for Chrome
  7656. // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
  7657. const formatter = {
  7658. header(obj) {
  7659. // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
  7660. if (!isObject(obj)) {
  7661. return null;
  7662. }
  7663. if (obj.__isVue) {
  7664. return ['div', vueStyle, `VueInstance`];
  7665. }
  7666. else if (isRef(obj)) {
  7667. return [
  7668. 'div',
  7669. {},
  7670. ['span', vueStyle, genRefFlag(obj)],
  7671. '<',
  7672. formatValue(obj.value),
  7673. `>`
  7674. ];
  7675. }
  7676. else if (isReactive(obj)) {
  7677. return [
  7678. 'div',
  7679. {},
  7680. ['span', vueStyle, 'Reactive'],
  7681. '<',
  7682. formatValue(obj),
  7683. `>${isReadonly(obj) ? ` (readonly)` : ``}`
  7684. ];
  7685. }
  7686. else if (isReadonly(obj)) {
  7687. return [
  7688. 'div',
  7689. {},
  7690. ['span', vueStyle, 'Readonly'],
  7691. '<',
  7692. formatValue(obj),
  7693. '>'
  7694. ];
  7695. }
  7696. return null;
  7697. },
  7698. hasBody(obj) {
  7699. return obj && obj.__isVue;
  7700. },
  7701. body(obj) {
  7702. if (obj && obj.__isVue) {
  7703. return [
  7704. 'div',
  7705. {},
  7706. ...formatInstance(obj.$)
  7707. ];
  7708. }
  7709. }
  7710. };
  7711. function formatInstance(instance) {
  7712. const blocks = [];
  7713. if (instance.type.props && instance.props) {
  7714. blocks.push(createInstanceBlock('props', toRaw(instance.props)));
  7715. }
  7716. if (instance.setupState !== EMPTY_OBJ) {
  7717. blocks.push(createInstanceBlock('setup', instance.setupState));
  7718. }
  7719. if (instance.data !== EMPTY_OBJ) {
  7720. blocks.push(createInstanceBlock('data', toRaw(instance.data)));
  7721. }
  7722. const computed = extractKeys(instance, 'computed');
  7723. if (computed) {
  7724. blocks.push(createInstanceBlock('computed', computed));
  7725. }
  7726. const injected = extractKeys(instance, 'inject');
  7727. if (injected) {
  7728. blocks.push(createInstanceBlock('injected', injected));
  7729. }
  7730. blocks.push([
  7731. 'div',
  7732. {},
  7733. [
  7734. 'span',
  7735. {
  7736. style: keywordStyle.style + ';opacity:0.66'
  7737. },
  7738. '$ (internal): '
  7739. ],
  7740. ['object', { object: instance }]
  7741. ]);
  7742. return blocks;
  7743. }
  7744. function createInstanceBlock(type, target) {
  7745. target = extend({}, target);
  7746. if (!Object.keys(target).length) {
  7747. return ['span', {}];
  7748. }
  7749. return [
  7750. 'div',
  7751. { style: 'line-height:1.25em;margin-bottom:0.6em' },
  7752. [
  7753. 'div',
  7754. {
  7755. style: 'color:#476582'
  7756. },
  7757. type
  7758. ],
  7759. [
  7760. 'div',
  7761. {
  7762. style: 'padding-left:1.25em'
  7763. },
  7764. ...Object.keys(target).map(key => {
  7765. return [
  7766. 'div',
  7767. {},
  7768. ['span', keywordStyle, key + ': '],
  7769. formatValue(target[key], false)
  7770. ];
  7771. })
  7772. ]
  7773. ];
  7774. }
  7775. function formatValue(v, asRaw = true) {
  7776. if (typeof v === 'number') {
  7777. return ['span', numberStyle, v];
  7778. }
  7779. else if (typeof v === 'string') {
  7780. return ['span', stringStyle, JSON.stringify(v)];
  7781. }
  7782. else if (typeof v === 'boolean') {
  7783. return ['span', keywordStyle, v];
  7784. }
  7785. else if (isObject(v)) {
  7786. return ['object', { object: asRaw ? toRaw(v) : v }];
  7787. }
  7788. else {
  7789. return ['span', stringStyle, String(v)];
  7790. }
  7791. }
  7792. function extractKeys(instance, type) {
  7793. const Comp = instance.type;
  7794. if (isFunction(Comp)) {
  7795. return;
  7796. }
  7797. const extracted = {};
  7798. for (const key in instance.ctx) {
  7799. if (isKeyOfType(Comp, key, type)) {
  7800. extracted[key] = instance.ctx[key];
  7801. }
  7802. }
  7803. return extracted;
  7804. }
  7805. function isKeyOfType(Comp, key, type) {
  7806. const opts = Comp[type];
  7807. if ((isArray(opts) && opts.includes(key)) ||
  7808. (isObject(opts) && key in opts)) {
  7809. return true;
  7810. }
  7811. if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
  7812. return true;
  7813. }
  7814. if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
  7815. return true;
  7816. }
  7817. }
  7818. function genRefFlag(v) {
  7819. if (v._shallow) {
  7820. return `ShallowRef`;
  7821. }
  7822. if (v.effect) {
  7823. return `ComputedRef`;
  7824. }
  7825. return `Ref`;
  7826. }
  7827. /* eslint-disable no-restricted-globals */
  7828. if (window.devtoolsFormatters) {
  7829. window.devtoolsFormatters.push(formatter);
  7830. }
  7831. else {
  7832. window.devtoolsFormatters = [formatter];
  7833. }
  7834. }
  7835. /**
  7836. * Actual implementation
  7837. */
  7838. function renderList(source, renderItem) {
  7839. let ret;
  7840. if (isArray(source) || isString(source)) {
  7841. ret = new Array(source.length);
  7842. for (let i = 0, l = source.length; i < l; i++) {
  7843. ret[i] = renderItem(source[i], i);
  7844. }
  7845. }
  7846. else if (typeof source === 'number') {
  7847. if ( !Number.isInteger(source)) {
  7848. warn(`The v-for range expect an integer value but got ${source}.`);
  7849. return [];
  7850. }
  7851. ret = new Array(source);
  7852. for (let i = 0; i < source; i++) {
  7853. ret[i] = renderItem(i + 1, i);
  7854. }
  7855. }
  7856. else if (isObject(source)) {
  7857. if (source[Symbol.iterator]) {
  7858. ret = Array.from(source, renderItem);
  7859. }
  7860. else {
  7861. const keys = Object.keys(source);
  7862. ret = new Array(keys.length);
  7863. for (let i = 0, l = keys.length; i < l; i++) {
  7864. const key = keys[i];
  7865. ret[i] = renderItem(source[key], key, i);
  7866. }
  7867. }
  7868. }
  7869. else {
  7870. ret = [];
  7871. }
  7872. return ret;
  7873. }
  7874. /**
  7875. * For prefixing keys in v-on="obj" with "on"
  7876. * @private
  7877. */
  7878. function toHandlers(obj) {
  7879. const ret = {};
  7880. if ( !isObject(obj)) {
  7881. warn(`v-on with no argument expects an object value.`);
  7882. return ret;
  7883. }
  7884. for (const key in obj) {
  7885. ret[toHandlerKey(key)] = obj[key];
  7886. }
  7887. return ret;
  7888. }
  7889. /**
  7890. * Compiler runtime helper for creating dynamic slots object
  7891. * @private
  7892. */
  7893. function createSlots(slots, dynamicSlots) {
  7894. for (let i = 0; i < dynamicSlots.length; i++) {
  7895. const slot = dynamicSlots[i];
  7896. // array of dynamic slot generated by <template v-for="..." #[...]>
  7897. if (isArray(slot)) {
  7898. for (let j = 0; j < slot.length; j++) {
  7899. slots[slot[j].name] = slot[j].fn;
  7900. }
  7901. }
  7902. else if (slot) {
  7903. // conditional single slot generated by <template v-if="..." #foo>
  7904. slots[slot.name] = slot.fn;
  7905. }
  7906. }
  7907. return slots;
  7908. }
  7909. // Core API ------------------------------------------------------------------
  7910. const version = "3.0.2";
  7911. /**
  7912. * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
  7913. * @internal
  7914. */
  7915. const ssrUtils = ( null);
  7916. const svgNS = 'http://www.w3.org/2000/svg';
  7917. const doc = (typeof document !== 'undefined' ? document : null);
  7918. let tempContainer;
  7919. let tempSVGContainer;
  7920. const nodeOps = {
  7921. insert: (child, parent, anchor) => {
  7922. parent.insertBefore(child, anchor || null);
  7923. },
  7924. remove: child => {
  7925. const parent = child.parentNode;
  7926. if (parent) {
  7927. parent.removeChild(child);
  7928. }
  7929. },
  7930. createElement: (tag, isSVG, is) => isSVG
  7931. ? doc.createElementNS(svgNS, tag)
  7932. : doc.createElement(tag, is ? { is } : undefined),
  7933. createText: text => doc.createTextNode(text),
  7934. createComment: text => doc.createComment(text),
  7935. setText: (node, text) => {
  7936. node.nodeValue = text;
  7937. },
  7938. setElementText: (el, text) => {
  7939. el.textContent = text;
  7940. },
  7941. parentNode: node => node.parentNode,
  7942. nextSibling: node => node.nextSibling,
  7943. querySelector: selector => doc.querySelector(selector),
  7944. setScopeId(el, id) {
  7945. el.setAttribute(id, '');
  7946. },
  7947. cloneNode(el) {
  7948. return el.cloneNode(true);
  7949. },
  7950. // __UNSAFE__
  7951. // Reason: innerHTML.
  7952. // Static content here can only come from compiled templates.
  7953. // As long as the user only uses trusted templates, this is safe.
  7954. insertStaticContent(content, parent, anchor, isSVG) {
  7955. const temp = isSVG
  7956. ? tempSVGContainer ||
  7957. (tempSVGContainer = doc.createElementNS(svgNS, 'svg'))
  7958. : tempContainer || (tempContainer = doc.createElement('div'));
  7959. temp.innerHTML = content;
  7960. const first = temp.firstChild;
  7961. let node = first;
  7962. let last = node;
  7963. while (node) {
  7964. last = node;
  7965. nodeOps.insert(node, parent, anchor);
  7966. node = temp.firstChild;
  7967. }
  7968. return [first, last];
  7969. }
  7970. };
  7971. // compiler should normalize class + :class bindings on the same element
  7972. // into a single binding ['staticClass', dynamic]
  7973. function patchClass(el, value, isSVG) {
  7974. if (value == null) {
  7975. value = '';
  7976. }
  7977. if (isSVG) {
  7978. el.setAttribute('class', value);
  7979. }
  7980. else {
  7981. // directly setting className should be faster than setAttribute in theory
  7982. // if this is an element during a transition, take the temporary transition
  7983. // classes into account.
  7984. const transitionClasses = el._vtc;
  7985. if (transitionClasses) {
  7986. value = (value
  7987. ? [value, ...transitionClasses]
  7988. : [...transitionClasses]).join(' ');
  7989. }
  7990. el.className = value;
  7991. }
  7992. }
  7993. function patchStyle(el, prev, next) {
  7994. const style = el.style;
  7995. if (!next) {
  7996. el.removeAttribute('style');
  7997. }
  7998. else if (isString(next)) {
  7999. if (prev !== next) {
  8000. style.cssText = next;
  8001. }
  8002. }
  8003. else {
  8004. for (const key in next) {
  8005. setStyle(style, key, next[key]);
  8006. }
  8007. if (prev && !isString(prev)) {
  8008. for (const key in prev) {
  8009. if (next[key] == null) {
  8010. setStyle(style, key, '');
  8011. }
  8012. }
  8013. }
  8014. }
  8015. }
  8016. const importantRE = /\s*!important$/;
  8017. function setStyle(style, name, val) {
  8018. if (isArray(val)) {
  8019. val.forEach(v => setStyle(style, name, v));
  8020. }
  8021. else {
  8022. if (name.startsWith('--')) {
  8023. // custom property definition
  8024. style.setProperty(name, val);
  8025. }
  8026. else {
  8027. const prefixed = autoPrefix(style, name);
  8028. if (importantRE.test(val)) {
  8029. // !important
  8030. style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
  8031. }
  8032. else {
  8033. style[prefixed] = val;
  8034. }
  8035. }
  8036. }
  8037. }
  8038. const prefixes = ['Webkit', 'Moz', 'ms'];
  8039. const prefixCache = {};
  8040. function autoPrefix(style, rawName) {
  8041. const cached = prefixCache[rawName];
  8042. if (cached) {
  8043. return cached;
  8044. }
  8045. let name = camelize(rawName);
  8046. if (name !== 'filter' && name in style) {
  8047. return (prefixCache[rawName] = name);
  8048. }
  8049. name = capitalize(name);
  8050. for (let i = 0; i < prefixes.length; i++) {
  8051. const prefixed = prefixes[i] + name;
  8052. if (prefixed in style) {
  8053. return (prefixCache[rawName] = prefixed);
  8054. }
  8055. }
  8056. return rawName;
  8057. }
  8058. const xlinkNS = 'http://www.w3.org/1999/xlink';
  8059. function patchAttr(el, key, value, isSVG) {
  8060. if (isSVG && key.startsWith('xlink:')) {
  8061. if (value == null) {
  8062. el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
  8063. }
  8064. else {
  8065. el.setAttributeNS(xlinkNS, key, value);
  8066. }
  8067. }
  8068. else {
  8069. // note we are only checking boolean attributes that don't have a
  8070. // corresponding dom prop of the same name here.
  8071. const isBoolean = isSpecialBooleanAttr(key);
  8072. if (value == null || (isBoolean && value === false)) {
  8073. el.removeAttribute(key);
  8074. }
  8075. else {
  8076. el.setAttribute(key, isBoolean ? '' : value);
  8077. }
  8078. }
  8079. }
  8080. // __UNSAFE__
  8081. // functions. The user is responsible for using them with only trusted content.
  8082. function patchDOMProp(el, key, value,
  8083. // the following args are passed only due to potential innerHTML/textContent
  8084. // overriding existing VNodes, in which case the old tree must be properly
  8085. // unmounted.
  8086. prevChildren, parentComponent, parentSuspense, unmountChildren) {
  8087. if (key === 'innerHTML' || key === 'textContent') {
  8088. if (prevChildren) {
  8089. unmountChildren(prevChildren, parentComponent, parentSuspense);
  8090. }
  8091. el[key] = value == null ? '' : value;
  8092. return;
  8093. }
  8094. if (key === 'value' && el.tagName !== 'PROGRESS') {
  8095. // store value as _value as well since
  8096. // non-string values will be stringified.
  8097. el._value = value;
  8098. const newValue = value == null ? '' : value;
  8099. if (el.value !== newValue) {
  8100. el.value = newValue;
  8101. }
  8102. return;
  8103. }
  8104. if (value === '' && typeof el[key] === 'boolean') {
  8105. // e.g. <select multiple> compiles to { multiple: '' }
  8106. el[key] = true;
  8107. }
  8108. else if (value == null && typeof el[key] === 'string') {
  8109. // e.g. <div :id="null">
  8110. el[key] = '';
  8111. el.removeAttribute(key);
  8112. }
  8113. else {
  8114. // some properties perform value validation and throw
  8115. try {
  8116. el[key] = value;
  8117. }
  8118. catch (e) {
  8119. {
  8120. warn(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
  8121. `value ${value} is invalid.`, e);
  8122. }
  8123. }
  8124. }
  8125. }
  8126. // Async edge case fix requires storing an event listener's attach timestamp.
  8127. let _getNow = Date.now;
  8128. // Determine what event timestamp the browser is using. Annoyingly, the
  8129. // timestamp can either be hi-res (relative to page load) or low-res
  8130. // (relative to UNIX epoch), so in order to compare time we have to use the
  8131. // same timestamp type when saving the flush timestamp.
  8132. if (typeof document !== 'undefined' &&
  8133. _getNow() > document.createEvent('Event').timeStamp) {
  8134. // if the low-res timestamp which is bigger than the event timestamp
  8135. // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
  8136. // and we need to use the hi-res version for event listeners as well.
  8137. _getNow = () => performance.now();
  8138. }
  8139. // To avoid the overhead of repeatedly calling performance.now(), we cache
  8140. // and use the same timestamp for all event listeners attached in the same tick.
  8141. let cachedNow = 0;
  8142. const p = Promise.resolve();
  8143. const reset = () => {
  8144. cachedNow = 0;
  8145. };
  8146. const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
  8147. function addEventListener(el, event, handler, options) {
  8148. el.addEventListener(event, handler, options);
  8149. }
  8150. function removeEventListener(el, event, handler, options) {
  8151. el.removeEventListener(event, handler, options);
  8152. }
  8153. function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  8154. // vei = vue event invokers
  8155. const invokers = el._vei || (el._vei = {});
  8156. const existingInvoker = invokers[rawName];
  8157. if (nextValue && existingInvoker) {
  8158. // patch
  8159. existingInvoker.value = nextValue;
  8160. }
  8161. else {
  8162. const [name, options] = parseName(rawName);
  8163. if (nextValue) {
  8164. // add
  8165. const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
  8166. addEventListener(el, name, invoker, options);
  8167. }
  8168. else if (existingInvoker) {
  8169. // remove
  8170. removeEventListener(el, name, existingInvoker, options);
  8171. invokers[rawName] = undefined;
  8172. }
  8173. }
  8174. }
  8175. const optionsModifierRE = /(?:Once|Passive|Capture)$/;
  8176. function parseName(name) {
  8177. let options;
  8178. if (optionsModifierRE.test(name)) {
  8179. options = {};
  8180. let m;
  8181. while ((m = name.match(optionsModifierRE))) {
  8182. name = name.slice(0, name.length - m[0].length);
  8183. options[m[0].toLowerCase()] = true;
  8184. }
  8185. }
  8186. return [name.slice(2).toLowerCase(), options];
  8187. }
  8188. function createInvoker(initialValue, instance) {
  8189. const invoker = (e) => {
  8190. // async edge case #6566: inner click event triggers patch, event handler
  8191. // attached to outer element during patch, and triggered again. This
  8192. // happens because browsers fire microtask ticks between event propagation.
  8193. // the solution is simple: we save the timestamp when a handler is attached,
  8194. // and the handler would only fire if the event passed to it was fired
  8195. // AFTER it was attached.
  8196. const timeStamp = e.timeStamp || _getNow();
  8197. if (timeStamp >= invoker.attached - 1) {
  8198. callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
  8199. }
  8200. };
  8201. invoker.value = initialValue;
  8202. invoker.attached = getNow();
  8203. return invoker;
  8204. }
  8205. function patchStopImmediatePropagation(e, value) {
  8206. if (isArray(value)) {
  8207. const originalStop = e.stopImmediatePropagation;
  8208. e.stopImmediatePropagation = () => {
  8209. originalStop.call(e);
  8210. e._stopped = true;
  8211. };
  8212. return value.map(fn => (e) => !e._stopped && fn(e));
  8213. }
  8214. else {
  8215. return value;
  8216. }
  8217. }
  8218. const nativeOnRE = /^on[a-z]/;
  8219. const forcePatchProp = (_, key) => key === 'value';
  8220. const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
  8221. switch (key) {
  8222. // special
  8223. case 'class':
  8224. patchClass(el, nextValue, isSVG);
  8225. break;
  8226. case 'style':
  8227. patchStyle(el, prevValue, nextValue);
  8228. break;
  8229. default:
  8230. if (isOn(key)) {
  8231. // ignore v-model listeners
  8232. if (!isModelListener(key)) {
  8233. patchEvent(el, key, prevValue, nextValue, parentComponent);
  8234. }
  8235. }
  8236. else if (shouldSetAsProp(el, key, nextValue, isSVG)) {
  8237. patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
  8238. }
  8239. else {
  8240. // special case for <input v-model type="checkbox"> with
  8241. // :true-value & :false-value
  8242. // store value as dom properties since non-string values will be
  8243. // stringified.
  8244. if (key === 'true-value') {
  8245. el._trueValue = nextValue;
  8246. }
  8247. else if (key === 'false-value') {
  8248. el._falseValue = nextValue;
  8249. }
  8250. patchAttr(el, key, nextValue, isSVG);
  8251. }
  8252. break;
  8253. }
  8254. };
  8255. function shouldSetAsProp(el, key, value, isSVG) {
  8256. if (isSVG) {
  8257. // most keys must be set as attribute on svg elements to work
  8258. // ...except innerHTML
  8259. if (key === 'innerHTML') {
  8260. return true;
  8261. }
  8262. // or native onclick with function values
  8263. if (key in el && nativeOnRE.test(key) && isFunction(value)) {
  8264. return true;
  8265. }
  8266. return false;
  8267. }
  8268. // spellcheck and draggable are numerated attrs, however their
  8269. // corresponding DOM properties are actually booleans - this leads to
  8270. // setting it with a string "false" value leading it to be coerced to
  8271. // `true`, so we need to always treat them as attributes.
  8272. // Note that `contentEditable` doesn't have this problem: its DOM
  8273. // property is also enumerated string values.
  8274. if (key === 'spellcheck' || key === 'draggable') {
  8275. return false;
  8276. }
  8277. // #1787 form as an attribute must be a string, while it accepts an Element as
  8278. // a prop
  8279. if (key === 'form' && typeof value === 'string') {
  8280. return false;
  8281. }
  8282. // #1526 <input list> must be set as attribute
  8283. if (key === 'list' && el.tagName === 'INPUT') {
  8284. return false;
  8285. }
  8286. // native onclick with string value, must be set as attribute
  8287. if (nativeOnRE.test(key) && isString(value)) {
  8288. return false;
  8289. }
  8290. return key in el;
  8291. }
  8292. function useCssModule(name = '$style') {
  8293. /* istanbul ignore else */
  8294. {
  8295. const instance = getCurrentInstance();
  8296. if (!instance) {
  8297. warn(`useCssModule must be called inside setup()`);
  8298. return EMPTY_OBJ;
  8299. }
  8300. const modules = instance.type.__cssModules;
  8301. if (!modules) {
  8302. warn(`Current instance does not have CSS modules injected.`);
  8303. return EMPTY_OBJ;
  8304. }
  8305. const mod = modules[name];
  8306. if (!mod) {
  8307. warn(`Current instance does not have CSS module named "${name}".`);
  8308. return EMPTY_OBJ;
  8309. }
  8310. return mod;
  8311. }
  8312. }
  8313. function useCssVars(getter, scoped = false) {
  8314. const instance = getCurrentInstance();
  8315. /* istanbul ignore next */
  8316. if (!instance) {
  8317. warn(`useCssVars is called without current active component instance.`);
  8318. return;
  8319. }
  8320. const prefix = scoped && instance.type.__scopeId
  8321. ? `${instance.type.__scopeId.replace(/^data-v-/, '')}-`
  8322. : ``;
  8323. const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy), prefix);
  8324. onMounted(() => watchEffect(setVars));
  8325. onUpdated(setVars);
  8326. }
  8327. function setVarsOnVNode(vnode, vars, prefix) {
  8328. if ( vnode.shapeFlag & 128 /* SUSPENSE */) {
  8329. const suspense = vnode.suspense;
  8330. vnode = suspense.activeBranch;
  8331. if (suspense.pendingBranch && !suspense.isHydrating) {
  8332. suspense.effects.push(() => {
  8333. setVarsOnVNode(suspense.activeBranch, vars, prefix);
  8334. });
  8335. }
  8336. }
  8337. // drill down HOCs until it's a non-component vnode
  8338. while (vnode.component) {
  8339. vnode = vnode.component.subTree;
  8340. }
  8341. if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
  8342. const style = vnode.el.style;
  8343. for (const key in vars) {
  8344. style.setProperty(`--${prefix}${key}`, unref(vars[key]));
  8345. }
  8346. }
  8347. else if (vnode.type === Fragment) {
  8348. vnode.children.forEach(c => setVarsOnVNode(c, vars, prefix));
  8349. }
  8350. }
  8351. const TRANSITION = 'transition';
  8352. const ANIMATION = 'animation';
  8353. // DOM Transition is a higher-order-component based on the platform-agnostic
  8354. // base Transition component, with DOM-specific logic.
  8355. const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
  8356. Transition.displayName = 'Transition';
  8357. const DOMTransitionPropsValidators = {
  8358. name: String,
  8359. type: String,
  8360. css: {
  8361. type: Boolean,
  8362. default: true
  8363. },
  8364. duration: [String, Number, Object],
  8365. enterFromClass: String,
  8366. enterActiveClass: String,
  8367. enterToClass: String,
  8368. appearFromClass: String,
  8369. appearActiveClass: String,
  8370. appearToClass: String,
  8371. leaveFromClass: String,
  8372. leaveActiveClass: String,
  8373. leaveToClass: String
  8374. };
  8375. const TransitionPropsValidators = (Transition.props = /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
  8376. function resolveTransitionProps(rawProps) {
  8377. let { name = 'v', type, css = true, 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;
  8378. const baseProps = {};
  8379. for (const key in rawProps) {
  8380. if (!(key in DOMTransitionPropsValidators)) {
  8381. baseProps[key] = rawProps[key];
  8382. }
  8383. }
  8384. if (!css) {
  8385. return baseProps;
  8386. }
  8387. const durations = normalizeDuration(duration);
  8388. const enterDuration = durations && durations[0];
  8389. const leaveDuration = durations && durations[1];
  8390. const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
  8391. const finishEnter = (el, isAppear, done) => {
  8392. removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
  8393. removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
  8394. done && done();
  8395. };
  8396. const finishLeave = (el, done) => {
  8397. removeTransitionClass(el, leaveToClass);
  8398. removeTransitionClass(el, leaveActiveClass);
  8399. done && done();
  8400. };
  8401. const makeEnterHook = (isAppear) => {
  8402. return (el, done) => {
  8403. const hook = isAppear ? onAppear : onEnter;
  8404. const resolve = () => finishEnter(el, isAppear, done);
  8405. hook && hook(el, resolve);
  8406. nextFrame(() => {
  8407. removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
  8408. addTransitionClass(el, isAppear ? appearToClass : enterToClass);
  8409. if (!(hook && hook.length > 1)) {
  8410. if (enterDuration) {
  8411. setTimeout(resolve, enterDuration);
  8412. }
  8413. else {
  8414. whenTransitionEnds(el, type, resolve);
  8415. }
  8416. }
  8417. });
  8418. };
  8419. };
  8420. return extend(baseProps, {
  8421. onBeforeEnter(el) {
  8422. onBeforeEnter && onBeforeEnter(el);
  8423. addTransitionClass(el, enterActiveClass);
  8424. addTransitionClass(el, enterFromClass);
  8425. },
  8426. onBeforeAppear(el) {
  8427. onBeforeAppear && onBeforeAppear(el);
  8428. addTransitionClass(el, appearActiveClass);
  8429. addTransitionClass(el, appearFromClass);
  8430. },
  8431. onEnter: makeEnterHook(false),
  8432. onAppear: makeEnterHook(true),
  8433. onLeave(el, done) {
  8434. const resolve = () => finishLeave(el, done);
  8435. addTransitionClass(el, leaveActiveClass);
  8436. addTransitionClass(el, leaveFromClass);
  8437. nextFrame(() => {
  8438. removeTransitionClass(el, leaveFromClass);
  8439. addTransitionClass(el, leaveToClass);
  8440. if (!(onLeave && onLeave.length > 1)) {
  8441. if (leaveDuration) {
  8442. setTimeout(resolve, leaveDuration);
  8443. }
  8444. else {
  8445. whenTransitionEnds(el, type, resolve);
  8446. }
  8447. }
  8448. });
  8449. onLeave && onLeave(el, resolve);
  8450. },
  8451. onEnterCancelled(el) {
  8452. finishEnter(el, false);
  8453. onEnterCancelled && onEnterCancelled(el);
  8454. },
  8455. onAppearCancelled(el) {
  8456. finishEnter(el, true);
  8457. onAppearCancelled && onAppearCancelled(el);
  8458. },
  8459. onLeaveCancelled(el) {
  8460. finishLeave(el);
  8461. onLeaveCancelled && onLeaveCancelled(el);
  8462. }
  8463. });
  8464. }
  8465. function normalizeDuration(duration) {
  8466. if (duration == null) {
  8467. return null;
  8468. }
  8469. else if (isObject(duration)) {
  8470. return [NumberOf(duration.enter), NumberOf(duration.leave)];
  8471. }
  8472. else {
  8473. const n = NumberOf(duration);
  8474. return [n, n];
  8475. }
  8476. }
  8477. function NumberOf(val) {
  8478. const res = toNumber(val);
  8479. validateDuration(res);
  8480. return res;
  8481. }
  8482. function validateDuration(val) {
  8483. if (typeof val !== 'number') {
  8484. warn(`<transition> explicit duration is not a valid number - ` +
  8485. `got ${JSON.stringify(val)}.`);
  8486. }
  8487. else if (isNaN(val)) {
  8488. warn(`<transition> explicit duration is NaN - ` +
  8489. 'the duration expression might be incorrect.');
  8490. }
  8491. }
  8492. function addTransitionClass(el, cls) {
  8493. cls.split(/\s+/).forEach(c => c && el.classList.add(c));
  8494. (el._vtc ||
  8495. (el._vtc = new Set())).add(cls);
  8496. }
  8497. function removeTransitionClass(el, cls) {
  8498. cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
  8499. const { _vtc } = el;
  8500. if (_vtc) {
  8501. _vtc.delete(cls);
  8502. if (!_vtc.size) {
  8503. el._vtc = undefined;
  8504. }
  8505. }
  8506. }
  8507. function nextFrame(cb) {
  8508. requestAnimationFrame(() => {
  8509. requestAnimationFrame(cb);
  8510. });
  8511. }
  8512. function whenTransitionEnds(el, expectedType, cb) {
  8513. const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
  8514. if (!type) {
  8515. return cb();
  8516. }
  8517. const endEvent = type + 'end';
  8518. let ended = 0;
  8519. const end = () => {
  8520. el.removeEventListener(endEvent, onEnd);
  8521. cb();
  8522. };
  8523. const onEnd = (e) => {
  8524. if (e.target === el) {
  8525. if (++ended >= propCount) {
  8526. end();
  8527. }
  8528. }
  8529. };
  8530. setTimeout(() => {
  8531. if (ended < propCount) {
  8532. end();
  8533. }
  8534. }, timeout + 1);
  8535. el.addEventListener(endEvent, onEnd);
  8536. }
  8537. function getTransitionInfo(el, expectedType) {
  8538. const styles = window.getComputedStyle(el);
  8539. // JSDOM may return undefined for transition properties
  8540. const getStyleProperties = (key) => (styles[key] || '').split(', ');
  8541. const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
  8542. const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
  8543. const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
  8544. const animationDelays = getStyleProperties(ANIMATION + 'Delay');
  8545. const animationDurations = getStyleProperties(ANIMATION + 'Duration');
  8546. const animationTimeout = getTimeout(animationDelays, animationDurations);
  8547. let type = null;
  8548. let timeout = 0;
  8549. let propCount = 0;
  8550. /* istanbul ignore if */
  8551. if (expectedType === TRANSITION) {
  8552. if (transitionTimeout > 0) {
  8553. type = TRANSITION;
  8554. timeout = transitionTimeout;
  8555. propCount = transitionDurations.length;
  8556. }
  8557. }
  8558. else if (expectedType === ANIMATION) {
  8559. if (animationTimeout > 0) {
  8560. type = ANIMATION;
  8561. timeout = animationTimeout;
  8562. propCount = animationDurations.length;
  8563. }
  8564. }
  8565. else {
  8566. timeout = Math.max(transitionTimeout, animationTimeout);
  8567. type =
  8568. timeout > 0
  8569. ? transitionTimeout > animationTimeout
  8570. ? TRANSITION
  8571. : ANIMATION
  8572. : null;
  8573. propCount = type
  8574. ? type === TRANSITION
  8575. ? transitionDurations.length
  8576. : animationDurations.length
  8577. : 0;
  8578. }
  8579. const hasTransform = type === TRANSITION &&
  8580. /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
  8581. return {
  8582. type,
  8583. timeout,
  8584. propCount,
  8585. hasTransform
  8586. };
  8587. }
  8588. function getTimeout(delays, durations) {
  8589. while (delays.length < durations.length) {
  8590. delays = delays.concat(delays);
  8591. }
  8592. return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
  8593. }
  8594. // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
  8595. // numbers in a locale-dependent way, using a comma instead of a dot.
  8596. // If comma is not replaced with a dot, the input will be rounded down
  8597. // (i.e. acting as a floor function) causing unexpected behaviors
  8598. function toMs(s) {
  8599. return Number(s.slice(0, -1).replace(',', '.')) * 1000;
  8600. }
  8601. const positionMap = new WeakMap();
  8602. const newPositionMap = new WeakMap();
  8603. const TransitionGroupImpl = {
  8604. name: 'TransitionGroup',
  8605. props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
  8606. tag: String,
  8607. moveClass: String
  8608. }),
  8609. setup(props, { slots }) {
  8610. const instance = getCurrentInstance();
  8611. const state = useTransitionState();
  8612. let prevChildren;
  8613. let children;
  8614. onUpdated(() => {
  8615. // children is guaranteed to exist after initial render
  8616. if (!prevChildren.length) {
  8617. return;
  8618. }
  8619. const moveClass = props.moveClass || `${props.name || 'v'}-move`;
  8620. if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
  8621. return;
  8622. }
  8623. // we divide the work into three loops to avoid mixing DOM reads and writes
  8624. // in each iteration - which helps prevent layout thrashing.
  8625. prevChildren.forEach(callPendingCbs);
  8626. prevChildren.forEach(recordPosition);
  8627. const movedChildren = prevChildren.filter(applyTranslation);
  8628. // force reflow to put everything in position
  8629. forceReflow();
  8630. movedChildren.forEach(c => {
  8631. const el = c.el;
  8632. const style = el.style;
  8633. addTransitionClass(el, moveClass);
  8634. style.transform = style.webkitTransform = style.transitionDuration = '';
  8635. const cb = (el._moveCb = (e) => {
  8636. if (e && e.target !== el) {
  8637. return;
  8638. }
  8639. if (!e || /transform$/.test(e.propertyName)) {
  8640. el.removeEventListener('transitionend', cb);
  8641. el._moveCb = null;
  8642. removeTransitionClass(el, moveClass);
  8643. }
  8644. });
  8645. el.addEventListener('transitionend', cb);
  8646. });
  8647. });
  8648. return () => {
  8649. const rawProps = toRaw(props);
  8650. const cssTransitionProps = resolveTransitionProps(rawProps);
  8651. const tag = rawProps.tag || Fragment;
  8652. prevChildren = children;
  8653. children = slots.default ? getTransitionRawChildren(slots.default()) : [];
  8654. for (let i = 0; i < children.length; i++) {
  8655. const child = children[i];
  8656. if (child.key != null) {
  8657. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  8658. }
  8659. else {
  8660. warn(`<TransitionGroup> children must be keyed.`);
  8661. }
  8662. }
  8663. if (prevChildren) {
  8664. for (let i = 0; i < prevChildren.length; i++) {
  8665. const child = prevChildren[i];
  8666. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  8667. positionMap.set(child, child.el.getBoundingClientRect());
  8668. }
  8669. }
  8670. return createVNode(tag, null, children);
  8671. };
  8672. }
  8673. };
  8674. const TransitionGroup = TransitionGroupImpl;
  8675. function callPendingCbs(c) {
  8676. const el = c.el;
  8677. if (el._moveCb) {
  8678. el._moveCb();
  8679. }
  8680. if (el._enterCb) {
  8681. el._enterCb();
  8682. }
  8683. }
  8684. function recordPosition(c) {
  8685. newPositionMap.set(c, c.el.getBoundingClientRect());
  8686. }
  8687. function applyTranslation(c) {
  8688. const oldPos = positionMap.get(c);
  8689. const newPos = newPositionMap.get(c);
  8690. const dx = oldPos.left - newPos.left;
  8691. const dy = oldPos.top - newPos.top;
  8692. if (dx || dy) {
  8693. const s = c.el.style;
  8694. s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
  8695. s.transitionDuration = '0s';
  8696. return c;
  8697. }
  8698. }
  8699. // this is put in a dedicated function to avoid the line from being treeshaken
  8700. function forceReflow() {
  8701. return document.body.offsetHeight;
  8702. }
  8703. function hasCSSTransform(el, root, moveClass) {
  8704. // Detect whether an element with the move class applied has
  8705. // CSS transitions. Since the element may be inside an entering
  8706. // transition at this very moment, we make a clone of it and remove
  8707. // all other transition classes applied to ensure only the move class
  8708. // is applied.
  8709. const clone = el.cloneNode();
  8710. if (el._vtc) {
  8711. el._vtc.forEach(cls => {
  8712. cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
  8713. });
  8714. }
  8715. moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
  8716. clone.style.display = 'none';
  8717. const container = (root.nodeType === 1
  8718. ? root
  8719. : root.parentNode);
  8720. container.appendChild(clone);
  8721. const { hasTransform } = getTransitionInfo(clone);
  8722. container.removeChild(clone);
  8723. return hasTransform;
  8724. }
  8725. const getModelAssigner = (vnode) => {
  8726. const fn = vnode.props['onUpdate:modelValue'];
  8727. return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
  8728. };
  8729. function onCompositionStart(e) {
  8730. e.target.composing = true;
  8731. }
  8732. function onCompositionEnd(e) {
  8733. const target = e.target;
  8734. if (target.composing) {
  8735. target.composing = false;
  8736. trigger$1(target, 'input');
  8737. }
  8738. }
  8739. function trigger$1(el, type) {
  8740. const e = document.createEvent('HTMLEvents');
  8741. e.initEvent(type, true, true);
  8742. el.dispatchEvent(e);
  8743. }
  8744. // We are exporting the v-model runtime directly as vnode hooks so that it can
  8745. // be tree-shaken in case v-model is never used.
  8746. const vModelText = {
  8747. created(el, { modifiers: { lazy, trim, number } }, vnode) {
  8748. el._assign = getModelAssigner(vnode);
  8749. const castToNumber = number || el.type === 'number';
  8750. addEventListener(el, lazy ? 'change' : 'input', e => {
  8751. if (e.target.composing)
  8752. return;
  8753. let domValue = el.value;
  8754. if (trim) {
  8755. domValue = domValue.trim();
  8756. }
  8757. else if (castToNumber) {
  8758. domValue = toNumber(domValue);
  8759. }
  8760. el._assign(domValue);
  8761. });
  8762. if (trim) {
  8763. addEventListener(el, 'change', () => {
  8764. el.value = el.value.trim();
  8765. });
  8766. }
  8767. if (!lazy) {
  8768. addEventListener(el, 'compositionstart', onCompositionStart);
  8769. addEventListener(el, 'compositionend', onCompositionEnd);
  8770. // Safari < 10.2 & UIWebView doesn't fire compositionend when
  8771. // switching focus before confirming composition choice
  8772. // this also fixes the issue where some browsers e.g. iOS Chrome
  8773. // fires "change" instead of "input" on autocomplete.
  8774. addEventListener(el, 'change', onCompositionEnd);
  8775. }
  8776. },
  8777. // set value on mounted so it's after min/max for type="range"
  8778. mounted(el, { value }) {
  8779. el.value = value == null ? '' : value;
  8780. },
  8781. beforeUpdate(el, { value, modifiers: { trim, number } }, vnode) {
  8782. el._assign = getModelAssigner(vnode);
  8783. // avoid clearing unresolved text. #2302
  8784. if (el.composing)
  8785. return;
  8786. if (document.activeElement === el) {
  8787. if (trim && el.value.trim() === value) {
  8788. return;
  8789. }
  8790. if ((number || el.type === 'number') && toNumber(el.value) === value) {
  8791. return;
  8792. }
  8793. }
  8794. const newValue = value == null ? '' : value;
  8795. if (el.value !== newValue) {
  8796. el.value = newValue;
  8797. }
  8798. }
  8799. };
  8800. const vModelCheckbox = {
  8801. created(el, binding, vnode) {
  8802. setChecked(el, binding, vnode);
  8803. el._assign = getModelAssigner(vnode);
  8804. addEventListener(el, 'change', () => {
  8805. const modelValue = el._modelValue;
  8806. const elementValue = getValue(el);
  8807. const checked = el.checked;
  8808. const assign = el._assign;
  8809. if (isArray(modelValue)) {
  8810. const index = looseIndexOf(modelValue, elementValue);
  8811. const found = index !== -1;
  8812. if (checked && !found) {
  8813. assign(modelValue.concat(elementValue));
  8814. }
  8815. else if (!checked && found) {
  8816. const filtered = [...modelValue];
  8817. filtered.splice(index, 1);
  8818. assign(filtered);
  8819. }
  8820. }
  8821. else if (isSet(modelValue)) {
  8822. if (checked) {
  8823. modelValue.add(elementValue);
  8824. }
  8825. else {
  8826. modelValue.delete(elementValue);
  8827. }
  8828. }
  8829. else {
  8830. assign(getCheckboxValue(el, checked));
  8831. }
  8832. });
  8833. },
  8834. beforeUpdate(el, binding, vnode) {
  8835. el._assign = getModelAssigner(vnode);
  8836. setChecked(el, binding, vnode);
  8837. }
  8838. };
  8839. function setChecked(el, { value, oldValue }, vnode) {
  8840. el._modelValue = value;
  8841. if (isArray(value)) {
  8842. el.checked = looseIndexOf(value, vnode.props.value) > -1;
  8843. }
  8844. else if (isSet(value)) {
  8845. el.checked = value.has(vnode.props.value);
  8846. }
  8847. else if (value !== oldValue) {
  8848. el.checked = looseEqual(value, getCheckboxValue(el, true));
  8849. }
  8850. }
  8851. const vModelRadio = {
  8852. created(el, { value }, vnode) {
  8853. el.checked = looseEqual(value, vnode.props.value);
  8854. el._assign = getModelAssigner(vnode);
  8855. addEventListener(el, 'change', () => {
  8856. el._assign(getValue(el));
  8857. });
  8858. },
  8859. beforeUpdate(el, { value, oldValue }, vnode) {
  8860. el._assign = getModelAssigner(vnode);
  8861. if (value !== oldValue) {
  8862. el.checked = looseEqual(value, vnode.props.value);
  8863. }
  8864. }
  8865. };
  8866. const vModelSelect = {
  8867. created(el, { modifiers: { number } }, vnode) {
  8868. addEventListener(el, 'change', () => {
  8869. const selectedVal = Array.prototype.filter
  8870. .call(el.options, (o) => o.selected)
  8871. .map((o) => number ? toNumber(getValue(o)) : getValue(o));
  8872. el._assign(el.multiple ? selectedVal : selectedVal[0]);
  8873. });
  8874. el._assign = getModelAssigner(vnode);
  8875. },
  8876. // set value in mounted & updated because <select> relies on its children
  8877. // <option>s.
  8878. mounted(el, { value }) {
  8879. setSelected(el, value);
  8880. },
  8881. beforeUpdate(el, _binding, vnode) {
  8882. el._assign = getModelAssigner(vnode);
  8883. },
  8884. updated(el, { value }) {
  8885. setSelected(el, value);
  8886. }
  8887. };
  8888. function setSelected(el, value) {
  8889. const isMultiple = el.multiple;
  8890. if (isMultiple && !isArray(value) && !isSet(value)) {
  8891. warn(`<select multiple v-model> expects an Array or Set value for its binding, ` +
  8892. `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
  8893. return;
  8894. }
  8895. for (let i = 0, l = el.options.length; i < l; i++) {
  8896. const option = el.options[i];
  8897. const optionValue = getValue(option);
  8898. if (isMultiple) {
  8899. if (isArray(value)) {
  8900. option.selected = looseIndexOf(value, optionValue) > -1;
  8901. }
  8902. else {
  8903. option.selected = value.has(optionValue);
  8904. }
  8905. }
  8906. else {
  8907. if (looseEqual(getValue(option), value)) {
  8908. el.selectedIndex = i;
  8909. return;
  8910. }
  8911. }
  8912. }
  8913. if (!isMultiple) {
  8914. el.selectedIndex = -1;
  8915. }
  8916. }
  8917. // retrieve raw value set via :value bindings
  8918. function getValue(el) {
  8919. return '_value' in el ? el._value : el.value;
  8920. }
  8921. // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
  8922. function getCheckboxValue(el, checked) {
  8923. const key = checked ? '_trueValue' : '_falseValue';
  8924. return key in el ? el[key] : checked;
  8925. }
  8926. const vModelDynamic = {
  8927. created(el, binding, vnode) {
  8928. callModelHook(el, binding, vnode, null, 'created');
  8929. },
  8930. mounted(el, binding, vnode) {
  8931. callModelHook(el, binding, vnode, null, 'mounted');
  8932. },
  8933. beforeUpdate(el, binding, vnode, prevVNode) {
  8934. callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
  8935. },
  8936. updated(el, binding, vnode, prevVNode) {
  8937. callModelHook(el, binding, vnode, prevVNode, 'updated');
  8938. }
  8939. };
  8940. function callModelHook(el, binding, vnode, prevVNode, hook) {
  8941. let modelToUse;
  8942. switch (el.tagName) {
  8943. case 'SELECT':
  8944. modelToUse = vModelSelect;
  8945. break;
  8946. case 'TEXTAREA':
  8947. modelToUse = vModelText;
  8948. break;
  8949. default:
  8950. switch (vnode.props && vnode.props.type) {
  8951. case 'checkbox':
  8952. modelToUse = vModelCheckbox;
  8953. break;
  8954. case 'radio':
  8955. modelToUse = vModelRadio;
  8956. break;
  8957. default:
  8958. modelToUse = vModelText;
  8959. }
  8960. }
  8961. const fn = modelToUse[hook];
  8962. fn && fn(el, binding, vnode, prevVNode);
  8963. }
  8964. const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
  8965. const modifierGuards = {
  8966. stop: e => e.stopPropagation(),
  8967. prevent: e => e.preventDefault(),
  8968. self: e => e.target !== e.currentTarget,
  8969. ctrl: e => !e.ctrlKey,
  8970. shift: e => !e.shiftKey,
  8971. alt: e => !e.altKey,
  8972. meta: e => !e.metaKey,
  8973. left: e => 'button' in e && e.button !== 0,
  8974. middle: e => 'button' in e && e.button !== 1,
  8975. right: e => 'button' in e && e.button !== 2,
  8976. exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
  8977. };
  8978. /**
  8979. * @private
  8980. */
  8981. const withModifiers = (fn, modifiers) => {
  8982. return (event, ...args) => {
  8983. for (let i = 0; i < modifiers.length; i++) {
  8984. const guard = modifierGuards[modifiers[i]];
  8985. if (guard && guard(event, modifiers))
  8986. return;
  8987. }
  8988. return fn(event, ...args);
  8989. };
  8990. };
  8991. // Kept for 2.x compat.
  8992. // Note: IE11 compat for `spacebar` and `del` is removed for now.
  8993. const keyNames = {
  8994. esc: 'escape',
  8995. space: ' ',
  8996. up: 'arrow-up',
  8997. left: 'arrow-left',
  8998. right: 'arrow-right',
  8999. down: 'arrow-down',
  9000. delete: 'backspace'
  9001. };
  9002. /**
  9003. * @private
  9004. */
  9005. const withKeys = (fn, modifiers) => {
  9006. return (event) => {
  9007. if (!('key' in event))
  9008. return;
  9009. const eventKey = hyphenate(event.key);
  9010. if (
  9011. // None of the provided key modifiers match the current event key
  9012. !modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
  9013. return;
  9014. }
  9015. return fn(event);
  9016. };
  9017. };
  9018. const vShow = {
  9019. beforeMount(el, { value }, { transition }) {
  9020. el._vod = el.style.display === 'none' ? '' : el.style.display;
  9021. if (transition && value) {
  9022. transition.beforeEnter(el);
  9023. }
  9024. else {
  9025. setDisplay(el, value);
  9026. }
  9027. },
  9028. mounted(el, { value }, { transition }) {
  9029. if (transition && value) {
  9030. transition.enter(el);
  9031. }
  9032. },
  9033. updated(el, { value, oldValue }, { transition }) {
  9034. if (!value === !oldValue)
  9035. return;
  9036. if (transition) {
  9037. if (value) {
  9038. transition.beforeEnter(el);
  9039. setDisplay(el, true);
  9040. transition.enter(el);
  9041. }
  9042. else {
  9043. transition.leave(el, () => {
  9044. setDisplay(el, false);
  9045. });
  9046. }
  9047. }
  9048. else {
  9049. setDisplay(el, value);
  9050. }
  9051. },
  9052. beforeUnmount(el, { value }) {
  9053. setDisplay(el, value);
  9054. }
  9055. };
  9056. function setDisplay(el, value) {
  9057. el.style.display = value ? el._vod : 'none';
  9058. }
  9059. const rendererOptions = extend({ patchProp, forcePatchProp }, nodeOps);
  9060. // lazy create the renderer - this makes core renderer logic tree-shakable
  9061. // in case the user only imports reactivity utilities from Vue.
  9062. let renderer;
  9063. let enabledHydration = false;
  9064. function ensureRenderer() {
  9065. return renderer || (renderer = createRenderer(rendererOptions));
  9066. }
  9067. function ensureHydrationRenderer() {
  9068. renderer = enabledHydration
  9069. ? renderer
  9070. : createHydrationRenderer(rendererOptions);
  9071. enabledHydration = true;
  9072. return renderer;
  9073. }
  9074. // use explicit type casts here to avoid import() calls in rolled-up d.ts
  9075. const render = ((...args) => {
  9076. ensureRenderer().render(...args);
  9077. });
  9078. const hydrate = ((...args) => {
  9079. ensureHydrationRenderer().hydrate(...args);
  9080. });
  9081. const createApp = ((...args) => {
  9082. const app = ensureRenderer().createApp(...args);
  9083. {
  9084. injectNativeTagCheck(app);
  9085. }
  9086. const { mount } = app;
  9087. app.mount = (containerOrSelector) => {
  9088. const container = normalizeContainer(containerOrSelector);
  9089. if (!container)
  9090. return;
  9091. const component = app._component;
  9092. if (!isFunction(component) && !component.render && !component.template) {
  9093. component.template = container.innerHTML;
  9094. }
  9095. // clear content before mounting
  9096. container.innerHTML = '';
  9097. const proxy = mount(container);
  9098. container.removeAttribute('v-cloak');
  9099. container.setAttribute('data-v-app', '');
  9100. return proxy;
  9101. };
  9102. return app;
  9103. });
  9104. const createSSRApp = ((...args) => {
  9105. const app = ensureHydrationRenderer().createApp(...args);
  9106. {
  9107. injectNativeTagCheck(app);
  9108. }
  9109. const { mount } = app;
  9110. app.mount = (containerOrSelector) => {
  9111. const container = normalizeContainer(containerOrSelector);
  9112. if (container) {
  9113. return mount(container, true);
  9114. }
  9115. };
  9116. return app;
  9117. });
  9118. function injectNativeTagCheck(app) {
  9119. // Inject `isNativeTag`
  9120. // this is used for component name validation (dev only)
  9121. Object.defineProperty(app.config, 'isNativeTag', {
  9122. value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
  9123. writable: false
  9124. });
  9125. }
  9126. function normalizeContainer(container) {
  9127. if (isString(container)) {
  9128. const res = document.querySelector(container);
  9129. if ( !res) {
  9130. warn(`Failed to mount app: mount target selector returned null.`);
  9131. }
  9132. return res;
  9133. }
  9134. return container;
  9135. }
  9136. var runtimeDom = /*#__PURE__*/Object.freeze({
  9137. __proto__: null,
  9138. render: render,
  9139. hydrate: hydrate,
  9140. createApp: createApp,
  9141. createSSRApp: createSSRApp,
  9142. useCssModule: useCssModule,
  9143. useCssVars: useCssVars,
  9144. Transition: Transition,
  9145. TransitionGroup: TransitionGroup,
  9146. vModelText: vModelText,
  9147. vModelCheckbox: vModelCheckbox,
  9148. vModelRadio: vModelRadio,
  9149. vModelSelect: vModelSelect,
  9150. vModelDynamic: vModelDynamic,
  9151. withModifiers: withModifiers,
  9152. withKeys: withKeys,
  9153. vShow: vShow,
  9154. reactive: reactive,
  9155. ref: ref,
  9156. readonly: readonly,
  9157. unref: unref,
  9158. proxyRefs: proxyRefs,
  9159. isRef: isRef,
  9160. toRef: toRef,
  9161. toRefs: toRefs,
  9162. isProxy: isProxy,
  9163. isReactive: isReactive,
  9164. isReadonly: isReadonly,
  9165. customRef: customRef,
  9166. triggerRef: triggerRef,
  9167. shallowRef: shallowRef,
  9168. shallowReactive: shallowReactive,
  9169. shallowReadonly: shallowReadonly,
  9170. markRaw: markRaw,
  9171. toRaw: toRaw,
  9172. computed: computed$1,
  9173. watch: watch,
  9174. watchEffect: watchEffect,
  9175. onBeforeMount: onBeforeMount,
  9176. onMounted: onMounted,
  9177. onBeforeUpdate: onBeforeUpdate,
  9178. onUpdated: onUpdated,
  9179. onBeforeUnmount: onBeforeUnmount,
  9180. onUnmounted: onUnmounted,
  9181. onActivated: onActivated,
  9182. onDeactivated: onDeactivated,
  9183. onRenderTracked: onRenderTracked,
  9184. onRenderTriggered: onRenderTriggered,
  9185. onErrorCaptured: onErrorCaptured,
  9186. provide: provide,
  9187. inject: inject,
  9188. nextTick: nextTick,
  9189. defineComponent: defineComponent,
  9190. defineAsyncComponent: defineAsyncComponent,
  9191. getCurrentInstance: getCurrentInstance,
  9192. h: h,
  9193. createVNode: createVNode,
  9194. cloneVNode: cloneVNode,
  9195. mergeProps: mergeProps,
  9196. isVNode: isVNode,
  9197. Fragment: Fragment,
  9198. Text: Text,
  9199. Comment: Comment,
  9200. Static: Static,
  9201. Teleport: Teleport,
  9202. Suspense: Suspense,
  9203. KeepAlive: KeepAlive,
  9204. BaseTransition: BaseTransition,
  9205. withDirectives: withDirectives,
  9206. useSSRContext: useSSRContext,
  9207. ssrContextKey: ssrContextKey,
  9208. createRenderer: createRenderer,
  9209. createHydrationRenderer: createHydrationRenderer,
  9210. queuePostFlushCb: queuePostFlushCb,
  9211. warn: warn,
  9212. handleError: handleError,
  9213. callWithErrorHandling: callWithErrorHandling,
  9214. callWithAsyncErrorHandling: callWithAsyncErrorHandling,
  9215. resolveComponent: resolveComponent,
  9216. resolveDirective: resolveDirective,
  9217. resolveDynamicComponent: resolveDynamicComponent,
  9218. registerRuntimeCompiler: registerRuntimeCompiler,
  9219. useTransitionState: useTransitionState,
  9220. resolveTransitionHooks: resolveTransitionHooks,
  9221. setTransitionHooks: setTransitionHooks,
  9222. getTransitionRawChildren: getTransitionRawChildren,
  9223. initCustomFormatter: initCustomFormatter,
  9224. get devtools () { return devtools; },
  9225. setDevtoolsHook: setDevtoolsHook,
  9226. withCtx: withCtx,
  9227. renderList: renderList,
  9228. toHandlers: toHandlers,
  9229. renderSlot: renderSlot,
  9230. createSlots: createSlots,
  9231. pushScopeId: pushScopeId,
  9232. popScopeId: popScopeId,
  9233. withScopeId: withScopeId,
  9234. openBlock: openBlock,
  9235. createBlock: createBlock,
  9236. setBlockTracking: setBlockTracking,
  9237. createTextVNode: createTextVNode,
  9238. createCommentVNode: createCommentVNode,
  9239. createStaticVNode: createStaticVNode,
  9240. toDisplayString: toDisplayString,
  9241. camelize: camelize,
  9242. capitalize: capitalize,
  9243. toHandlerKey: toHandlerKey,
  9244. transformVNodeArgs: transformVNodeArgs,
  9245. version: version,
  9246. ssrUtils: ssrUtils
  9247. });
  9248. function initDev() {
  9249. const target = getGlobalThis();
  9250. target.__VUE__ = true;
  9251. setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__);
  9252. {
  9253. console.info(`You are running a development build of Vue.\n` +
  9254. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  9255. initCustomFormatter();
  9256. }
  9257. }
  9258. function defaultOnError(error) {
  9259. throw error;
  9260. }
  9261. function createCompilerError(code, loc, messages, additionalMessage) {
  9262. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  9263. ;
  9264. const error = new SyntaxError(String(msg));
  9265. error.code = code;
  9266. error.loc = loc;
  9267. return error;
  9268. }
  9269. const errorMessages = {
  9270. // parse errors
  9271. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  9272. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  9273. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  9274. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  9275. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  9276. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  9277. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  9278. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  9279. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  9280. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  9281. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  9282. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  9283. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  9284. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  9285. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  9286. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  9287. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  9288. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  9289. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  9290. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  9291. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  9292. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  9293. // Vue-specific parse errors
  9294. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  9295. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  9296. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  9297. [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  9298. 'Note that dynamic directive argument cannot contain spaces.',
  9299. // transform errors
  9300. [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  9301. [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  9302. [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
  9303. [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  9304. [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  9305. [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  9306. [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  9307. [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  9308. [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  9309. [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  9310. `When there are multiple named slots, all slots should use <template> ` +
  9311. `syntax to avoid scope ambiguity.`,
  9312. [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  9313. [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  9314. `default slot. These children will be ignored.`,
  9315. [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  9316. [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  9317. [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  9318. [42 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  9319. [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  9320. [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  9321. // generic errors
  9322. [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  9323. [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  9324. [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  9325. [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
  9326. };
  9327. const FRAGMENT = Symbol( `Fragment` );
  9328. const TELEPORT = Symbol( `Teleport` );
  9329. const SUSPENSE = Symbol( `Suspense` );
  9330. const KEEP_ALIVE = Symbol( `KeepAlive` );
  9331. const BASE_TRANSITION = Symbol( `BaseTransition` );
  9332. const OPEN_BLOCK = Symbol( `openBlock` );
  9333. const CREATE_BLOCK = Symbol( `createBlock` );
  9334. const CREATE_VNODE = Symbol( `createVNode` );
  9335. const CREATE_COMMENT = Symbol( `createCommentVNode` );
  9336. const CREATE_TEXT = Symbol( `createTextVNode` );
  9337. const CREATE_STATIC = Symbol( `createStaticVNode` );
  9338. const RESOLVE_COMPONENT = Symbol( `resolveComponent` );
  9339. const RESOLVE_DYNAMIC_COMPONENT = Symbol( `resolveDynamicComponent` );
  9340. const RESOLVE_DIRECTIVE = Symbol( `resolveDirective` );
  9341. const WITH_DIRECTIVES = Symbol( `withDirectives` );
  9342. const RENDER_LIST = Symbol( `renderList` );
  9343. const RENDER_SLOT = Symbol( `renderSlot` );
  9344. const CREATE_SLOTS = Symbol( `createSlots` );
  9345. const TO_DISPLAY_STRING = Symbol( `toDisplayString` );
  9346. const MERGE_PROPS = Symbol( `mergeProps` );
  9347. const TO_HANDLERS = Symbol( `toHandlers` );
  9348. const CAMELIZE = Symbol( `camelize` );
  9349. const CAPITALIZE = Symbol( `capitalize` );
  9350. const TO_HANDLER_KEY = Symbol( `toHandlerKey` );
  9351. const SET_BLOCK_TRACKING = Symbol( `setBlockTracking` );
  9352. const PUSH_SCOPE_ID = Symbol( `pushScopeId` );
  9353. const POP_SCOPE_ID = Symbol( `popScopeId` );
  9354. const WITH_SCOPE_ID = Symbol( `withScopeId` );
  9355. const WITH_CTX = Symbol( `withCtx` );
  9356. // Name mapping for runtime helpers that need to be imported from 'vue' in
  9357. // generated code. Make sure these are correctly exported in the runtime!
  9358. // Using `any` here because TS doesn't allow symbols as index type.
  9359. const helperNameMap = {
  9360. [FRAGMENT]: `Fragment`,
  9361. [TELEPORT]: `Teleport`,
  9362. [SUSPENSE]: `Suspense`,
  9363. [KEEP_ALIVE]: `KeepAlive`,
  9364. [BASE_TRANSITION]: `BaseTransition`,
  9365. [OPEN_BLOCK]: `openBlock`,
  9366. [CREATE_BLOCK]: `createBlock`,
  9367. [CREATE_VNODE]: `createVNode`,
  9368. [CREATE_COMMENT]: `createCommentVNode`,
  9369. [CREATE_TEXT]: `createTextVNode`,
  9370. [CREATE_STATIC]: `createStaticVNode`,
  9371. [RESOLVE_COMPONENT]: `resolveComponent`,
  9372. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  9373. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  9374. [WITH_DIRECTIVES]: `withDirectives`,
  9375. [RENDER_LIST]: `renderList`,
  9376. [RENDER_SLOT]: `renderSlot`,
  9377. [CREATE_SLOTS]: `createSlots`,
  9378. [TO_DISPLAY_STRING]: `toDisplayString`,
  9379. [MERGE_PROPS]: `mergeProps`,
  9380. [TO_HANDLERS]: `toHandlers`,
  9381. [CAMELIZE]: `camelize`,
  9382. [CAPITALIZE]: `capitalize`,
  9383. [TO_HANDLER_KEY]: `toHandlerKey`,
  9384. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  9385. [PUSH_SCOPE_ID]: `pushScopeId`,
  9386. [POP_SCOPE_ID]: `popScopeId`,
  9387. [WITH_SCOPE_ID]: `withScopeId`,
  9388. [WITH_CTX]: `withCtx`
  9389. };
  9390. function registerRuntimeHelpers(helpers) {
  9391. Object.getOwnPropertySymbols(helpers).forEach(s => {
  9392. helperNameMap[s] = helpers[s];
  9393. });
  9394. }
  9395. // AST Utilities ---------------------------------------------------------------
  9396. // Some expressions, e.g. sequence and conditional expressions, are never
  9397. // associated with template nodes, so their source locations are just a stub.
  9398. // Container types like CompoundExpression also don't need a real location.
  9399. const locStub = {
  9400. source: '',
  9401. start: { line: 1, column: 1, offset: 0 },
  9402. end: { line: 1, column: 1, offset: 0 }
  9403. };
  9404. function createRoot(children, loc = locStub) {
  9405. return {
  9406. type: 0 /* ROOT */,
  9407. children,
  9408. helpers: [],
  9409. components: [],
  9410. directives: [],
  9411. hoists: [],
  9412. imports: [],
  9413. cached: 0,
  9414. temps: 0,
  9415. codegenNode: undefined,
  9416. loc
  9417. };
  9418. }
  9419. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
  9420. if (context) {
  9421. if (isBlock) {
  9422. context.helper(OPEN_BLOCK);
  9423. context.helper(CREATE_BLOCK);
  9424. }
  9425. else {
  9426. context.helper(CREATE_VNODE);
  9427. }
  9428. if (directives) {
  9429. context.helper(WITH_DIRECTIVES);
  9430. }
  9431. }
  9432. return {
  9433. type: 13 /* VNODE_CALL */,
  9434. tag,
  9435. props,
  9436. children,
  9437. patchFlag,
  9438. dynamicProps,
  9439. directives,
  9440. isBlock,
  9441. disableTracking,
  9442. loc
  9443. };
  9444. }
  9445. function createArrayExpression(elements, loc = locStub) {
  9446. return {
  9447. type: 17 /* JS_ARRAY_EXPRESSION */,
  9448. loc,
  9449. elements
  9450. };
  9451. }
  9452. function createObjectExpression(properties, loc = locStub) {
  9453. return {
  9454. type: 15 /* JS_OBJECT_EXPRESSION */,
  9455. loc,
  9456. properties
  9457. };
  9458. }
  9459. function createObjectProperty(key, value) {
  9460. return {
  9461. type: 16 /* JS_PROPERTY */,
  9462. loc: locStub,
  9463. key: isString(key) ? createSimpleExpression(key, true) : key,
  9464. value
  9465. };
  9466. }
  9467. function createSimpleExpression(content, isStatic, loc = locStub, isConstant = false) {
  9468. return {
  9469. type: 4 /* SIMPLE_EXPRESSION */,
  9470. loc,
  9471. isConstant,
  9472. content,
  9473. isStatic
  9474. };
  9475. }
  9476. function createCompoundExpression(children, loc = locStub) {
  9477. return {
  9478. type: 8 /* COMPOUND_EXPRESSION */,
  9479. loc,
  9480. children
  9481. };
  9482. }
  9483. function createCallExpression(callee, args = [], loc = locStub) {
  9484. return {
  9485. type: 14 /* JS_CALL_EXPRESSION */,
  9486. loc,
  9487. callee,
  9488. arguments: args
  9489. };
  9490. }
  9491. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  9492. return {
  9493. type: 18 /* JS_FUNCTION_EXPRESSION */,
  9494. params,
  9495. returns,
  9496. newline,
  9497. isSlot,
  9498. loc
  9499. };
  9500. }
  9501. function createConditionalExpression(test, consequent, alternate, newline = true) {
  9502. return {
  9503. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  9504. test,
  9505. consequent,
  9506. alternate,
  9507. newline,
  9508. loc: locStub
  9509. };
  9510. }
  9511. function createCacheExpression(index, value, isVNode = false) {
  9512. return {
  9513. type: 20 /* JS_CACHE_EXPRESSION */,
  9514. index,
  9515. value,
  9516. isVNode,
  9517. loc: locStub
  9518. };
  9519. }
  9520. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  9521. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  9522. function isCoreComponent(tag) {
  9523. if (isBuiltInType(tag, 'Teleport')) {
  9524. return TELEPORT;
  9525. }
  9526. else if (isBuiltInType(tag, 'Suspense')) {
  9527. return SUSPENSE;
  9528. }
  9529. else if (isBuiltInType(tag, 'KeepAlive')) {
  9530. return KEEP_ALIVE;
  9531. }
  9532. else if (isBuiltInType(tag, 'BaseTransition')) {
  9533. return BASE_TRANSITION;
  9534. }
  9535. }
  9536. const nonIdentifierRE = /^\d|[^\$\w]/;
  9537. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  9538. const memberExpRE = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]]+\])*$/;
  9539. const isMemberExpression = (path) => {
  9540. if (!path)
  9541. return false;
  9542. return memberExpRE.test(path.trim());
  9543. };
  9544. function getInnerRange(loc, offset, length) {
  9545. const source = loc.source.substr(offset, length);
  9546. const newLoc = {
  9547. source,
  9548. start: advancePositionWithClone(loc.start, loc.source, offset),
  9549. end: loc.end
  9550. };
  9551. if (length != null) {
  9552. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  9553. }
  9554. return newLoc;
  9555. }
  9556. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  9557. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  9558. }
  9559. // advance by mutation without cloning (for performance reasons), since this
  9560. // gets called a lot in the parser
  9561. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  9562. let linesCount = 0;
  9563. let lastNewLinePos = -1;
  9564. for (let i = 0; i < numberOfCharacters; i++) {
  9565. if (source.charCodeAt(i) === 10 /* newline char code */) {
  9566. linesCount++;
  9567. lastNewLinePos = i;
  9568. }
  9569. }
  9570. pos.offset += numberOfCharacters;
  9571. pos.line += linesCount;
  9572. pos.column =
  9573. lastNewLinePos === -1
  9574. ? pos.column + numberOfCharacters
  9575. : numberOfCharacters - lastNewLinePos;
  9576. return pos;
  9577. }
  9578. function assert(condition, msg) {
  9579. /* istanbul ignore if */
  9580. if (!condition) {
  9581. throw new Error(msg || `unexpected compiler condition`);
  9582. }
  9583. }
  9584. function findDir(node, name, allowEmpty = false) {
  9585. for (let i = 0; i < node.props.length; i++) {
  9586. const p = node.props[i];
  9587. if (p.type === 7 /* DIRECTIVE */ &&
  9588. (allowEmpty || p.exp) &&
  9589. (isString(name) ? p.name === name : name.test(p.name))) {
  9590. return p;
  9591. }
  9592. }
  9593. }
  9594. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  9595. for (let i = 0; i < node.props.length; i++) {
  9596. const p = node.props[i];
  9597. if (p.type === 6 /* ATTRIBUTE */) {
  9598. if (dynamicOnly)
  9599. continue;
  9600. if (p.name === name && (p.value || allowEmpty)) {
  9601. return p;
  9602. }
  9603. }
  9604. else if (p.name === 'bind' &&
  9605. (p.exp || allowEmpty) &&
  9606. isBindKey(p.arg, name)) {
  9607. return p;
  9608. }
  9609. }
  9610. }
  9611. function isBindKey(arg, name) {
  9612. return !!(arg && isStaticExp(arg) && arg.content === name);
  9613. }
  9614. function hasDynamicKeyVBind(node) {
  9615. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  9616. p.name === 'bind' &&
  9617. (!p.arg || // v-bind="obj"
  9618. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  9619. !p.arg.isStatic) // v-bind:[foo]
  9620. );
  9621. }
  9622. function isText(node) {
  9623. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  9624. }
  9625. function isVSlot(p) {
  9626. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  9627. }
  9628. function isTemplateNode(node) {
  9629. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  9630. }
  9631. function isSlotOutlet(node) {
  9632. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  9633. }
  9634. function injectProp(node, prop, context) {
  9635. let propsWithInjection;
  9636. const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  9637. if (props == null || isString(props)) {
  9638. propsWithInjection = createObjectExpression([prop]);
  9639. }
  9640. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  9641. // merged props... add ours
  9642. // only inject key to object literal if it's the first argument so that
  9643. // if doesn't override user provided keys
  9644. const first = props.arguments[0];
  9645. if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  9646. first.properties.unshift(prop);
  9647. }
  9648. else {
  9649. if (props.callee === TO_HANDLERS) {
  9650. // #2366
  9651. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  9652. createObjectExpression([prop]),
  9653. props
  9654. ]);
  9655. }
  9656. else {
  9657. props.arguments.unshift(createObjectExpression([prop]));
  9658. }
  9659. }
  9660. !propsWithInjection && (propsWithInjection = props);
  9661. }
  9662. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  9663. let alreadyExists = false;
  9664. // check existing key to avoid overriding user provided keys
  9665. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  9666. const propKeyName = prop.key.content;
  9667. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  9668. p.key.content === propKeyName);
  9669. }
  9670. if (!alreadyExists) {
  9671. props.properties.unshift(prop);
  9672. }
  9673. propsWithInjection = props;
  9674. }
  9675. else {
  9676. // single v-bind with expression, return a merged replacement
  9677. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  9678. createObjectExpression([prop]),
  9679. props
  9680. ]);
  9681. }
  9682. if (node.type === 13 /* VNODE_CALL */) {
  9683. node.props = propsWithInjection;
  9684. }
  9685. else {
  9686. node.arguments[2] = propsWithInjection;
  9687. }
  9688. }
  9689. function toValidAssetId(name, type) {
  9690. return `_${type}_${name.replace(/[^\w]/g, '_')}`;
  9691. }
  9692. // The default decoder only provides escapes for characters reserved as part of
  9693. // the template syntax, and is only used if the custom renderer did not provide
  9694. // a platform-specific decoder.
  9695. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  9696. const decodeMap = {
  9697. gt: '>',
  9698. lt: '<',
  9699. amp: '&',
  9700. apos: "'",
  9701. quot: '"'
  9702. };
  9703. const defaultParserOptions = {
  9704. delimiters: [`{{`, `}}`],
  9705. getNamespace: () => 0 /* HTML */,
  9706. getTextMode: () => 0 /* DATA */,
  9707. isVoidTag: NO,
  9708. isPreTag: NO,
  9709. isCustomElement: NO,
  9710. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  9711. onError: defaultOnError,
  9712. comments: false
  9713. };
  9714. function baseParse(content, options = {}) {
  9715. const context = createParserContext(content, options);
  9716. const start = getCursor(context);
  9717. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  9718. }
  9719. function createParserContext(content, rawOptions) {
  9720. const options = extend({}, defaultParserOptions);
  9721. for (const key in rawOptions) {
  9722. // @ts-ignore
  9723. options[key] = rawOptions[key] || defaultParserOptions[key];
  9724. }
  9725. return {
  9726. options,
  9727. column: 1,
  9728. line: 1,
  9729. offset: 0,
  9730. originalSource: content,
  9731. source: content,
  9732. inPre: false,
  9733. inVPre: false
  9734. };
  9735. }
  9736. function parseChildren(context, mode, ancestors) {
  9737. const parent = last(ancestors);
  9738. const ns = parent ? parent.ns : 0 /* HTML */;
  9739. const nodes = [];
  9740. while (!isEnd(context, mode, ancestors)) {
  9741. const s = context.source;
  9742. let node = undefined;
  9743. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  9744. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  9745. // '{{'
  9746. node = parseInterpolation(context, mode);
  9747. }
  9748. else if (mode === 0 /* DATA */ && s[0] === '<') {
  9749. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  9750. if (s.length === 1) {
  9751. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  9752. }
  9753. else if (s[1] === '!') {
  9754. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  9755. if (startsWith(s, '<!--')) {
  9756. node = parseComment(context);
  9757. }
  9758. else if (startsWith(s, '<!DOCTYPE')) {
  9759. // Ignore DOCTYPE by a limitation.
  9760. node = parseBogusComment(context);
  9761. }
  9762. else if (startsWith(s, '<![CDATA[')) {
  9763. if (ns !== 0 /* HTML */) {
  9764. node = parseCDATA(context, ancestors);
  9765. }
  9766. else {
  9767. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  9768. node = parseBogusComment(context);
  9769. }
  9770. }
  9771. else {
  9772. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  9773. node = parseBogusComment(context);
  9774. }
  9775. }
  9776. else if (s[1] === '/') {
  9777. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  9778. if (s.length === 2) {
  9779. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  9780. }
  9781. else if (s[2] === '>') {
  9782. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  9783. advanceBy(context, 3);
  9784. continue;
  9785. }
  9786. else if (/[a-z]/i.test(s[2])) {
  9787. emitError(context, 23 /* X_INVALID_END_TAG */);
  9788. parseTag(context, 1 /* End */, parent);
  9789. continue;
  9790. }
  9791. else {
  9792. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  9793. node = parseBogusComment(context);
  9794. }
  9795. }
  9796. else if (/[a-z]/i.test(s[1])) {
  9797. node = parseElement(context, ancestors);
  9798. }
  9799. else if (s[1] === '?') {
  9800. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  9801. node = parseBogusComment(context);
  9802. }
  9803. else {
  9804. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  9805. }
  9806. }
  9807. }
  9808. if (!node) {
  9809. node = parseText(context, mode);
  9810. }
  9811. if (isArray(node)) {
  9812. for (let i = 0; i < node.length; i++) {
  9813. pushNode(nodes, node[i]);
  9814. }
  9815. }
  9816. else {
  9817. pushNode(nodes, node);
  9818. }
  9819. }
  9820. // Whitespace management for more efficient output
  9821. // (same as v2 whitespace: 'condense')
  9822. let removedWhitespace = false;
  9823. if (mode !== 2 /* RAWTEXT */) {
  9824. for (let i = 0; i < nodes.length; i++) {
  9825. const node = nodes[i];
  9826. if (!context.inPre && node.type === 2 /* TEXT */) {
  9827. if (!/[^\t\r\n\f ]/.test(node.content)) {
  9828. const prev = nodes[i - 1];
  9829. const next = nodes[i + 1];
  9830. // If:
  9831. // - the whitespace is the first or last node, or:
  9832. // - the whitespace is adjacent to a comment, or:
  9833. // - the whitespace is between two elements AND contains newline
  9834. // Then the whitespace is ignored.
  9835. if (!prev ||
  9836. !next ||
  9837. prev.type === 3 /* COMMENT */ ||
  9838. next.type === 3 /* COMMENT */ ||
  9839. (prev.type === 1 /* ELEMENT */ &&
  9840. next.type === 1 /* ELEMENT */ &&
  9841. /[\r\n]/.test(node.content))) {
  9842. removedWhitespace = true;
  9843. nodes[i] = null;
  9844. }
  9845. else {
  9846. // Otherwise, condensed consecutive whitespace inside the text
  9847. // down to a single space
  9848. node.content = ' ';
  9849. }
  9850. }
  9851. else {
  9852. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  9853. }
  9854. }
  9855. }
  9856. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  9857. // remove leading newline per html spec
  9858. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  9859. const first = nodes[0];
  9860. if (first && first.type === 2 /* TEXT */) {
  9861. first.content = first.content.replace(/^\r?\n/, '');
  9862. }
  9863. }
  9864. }
  9865. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  9866. }
  9867. function pushNode(nodes, node) {
  9868. if (node.type === 2 /* TEXT */) {
  9869. const prev = last(nodes);
  9870. // Merge if both this and the previous node are text and those are
  9871. // consecutive. This happens for cases like "a < b".
  9872. if (prev &&
  9873. prev.type === 2 /* TEXT */ &&
  9874. prev.loc.end.offset === node.loc.start.offset) {
  9875. prev.content += node.content;
  9876. prev.loc.end = node.loc.end;
  9877. prev.loc.source += node.loc.source;
  9878. return;
  9879. }
  9880. }
  9881. nodes.push(node);
  9882. }
  9883. function parseCDATA(context, ancestors) {
  9884. advanceBy(context, 9);
  9885. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  9886. if (context.source.length === 0) {
  9887. emitError(context, 6 /* EOF_IN_CDATA */);
  9888. }
  9889. else {
  9890. advanceBy(context, 3);
  9891. }
  9892. return nodes;
  9893. }
  9894. function parseComment(context) {
  9895. const start = getCursor(context);
  9896. let content;
  9897. // Regular comment.
  9898. const match = /--(\!)?>/.exec(context.source);
  9899. if (!match) {
  9900. content = context.source.slice(4);
  9901. advanceBy(context, context.source.length);
  9902. emitError(context, 7 /* EOF_IN_COMMENT */);
  9903. }
  9904. else {
  9905. if (match.index <= 3) {
  9906. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  9907. }
  9908. if (match[1]) {
  9909. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  9910. }
  9911. content = context.source.slice(4, match.index);
  9912. // Advancing with reporting nested comments.
  9913. const s = context.source.slice(0, match.index);
  9914. let prevIndex = 1, nestedIndex = 0;
  9915. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  9916. advanceBy(context, nestedIndex - prevIndex + 1);
  9917. if (nestedIndex + 4 < s.length) {
  9918. emitError(context, 16 /* NESTED_COMMENT */);
  9919. }
  9920. prevIndex = nestedIndex + 1;
  9921. }
  9922. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  9923. }
  9924. return {
  9925. type: 3 /* COMMENT */,
  9926. content,
  9927. loc: getSelection(context, start)
  9928. };
  9929. }
  9930. function parseBogusComment(context) {
  9931. const start = getCursor(context);
  9932. const contentStart = context.source[1] === '?' ? 1 : 2;
  9933. let content;
  9934. const closeIndex = context.source.indexOf('>');
  9935. if (closeIndex === -1) {
  9936. content = context.source.slice(contentStart);
  9937. advanceBy(context, context.source.length);
  9938. }
  9939. else {
  9940. content = context.source.slice(contentStart, closeIndex);
  9941. advanceBy(context, closeIndex + 1);
  9942. }
  9943. return {
  9944. type: 3 /* COMMENT */,
  9945. content,
  9946. loc: getSelection(context, start)
  9947. };
  9948. }
  9949. function parseElement(context, ancestors) {
  9950. // Start tag.
  9951. const wasInPre = context.inPre;
  9952. const wasInVPre = context.inVPre;
  9953. const parent = last(ancestors);
  9954. const element = parseTag(context, 0 /* Start */, parent);
  9955. const isPreBoundary = context.inPre && !wasInPre;
  9956. const isVPreBoundary = context.inVPre && !wasInVPre;
  9957. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  9958. return element;
  9959. }
  9960. // Children.
  9961. ancestors.push(element);
  9962. const mode = context.options.getTextMode(element, parent);
  9963. const children = parseChildren(context, mode, ancestors);
  9964. ancestors.pop();
  9965. element.children = children;
  9966. // End tag.
  9967. if (startsWithEndTagOpen(context.source, element.tag)) {
  9968. parseTag(context, 1 /* End */, parent);
  9969. }
  9970. else {
  9971. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  9972. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  9973. const first = children[0];
  9974. if (first && startsWith(first.loc.source, '<!--')) {
  9975. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  9976. }
  9977. }
  9978. }
  9979. element.loc = getSelection(context, element.loc.start);
  9980. if (isPreBoundary) {
  9981. context.inPre = false;
  9982. }
  9983. if (isVPreBoundary) {
  9984. context.inVPre = false;
  9985. }
  9986. return element;
  9987. }
  9988. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  9989. /**
  9990. * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
  9991. */
  9992. function parseTag(context, type, parent) {
  9993. // Tag open.
  9994. const start = getCursor(context);
  9995. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  9996. const tag = match[1];
  9997. const ns = context.options.getNamespace(tag, parent);
  9998. advanceBy(context, match[0].length);
  9999. advanceSpaces(context);
  10000. // save current state in case we need to re-parse attributes with v-pre
  10001. const cursor = getCursor(context);
  10002. const currentSource = context.source;
  10003. // Attributes.
  10004. let props = parseAttributes(context, type);
  10005. // check <pre> tag
  10006. if (context.options.isPreTag(tag)) {
  10007. context.inPre = true;
  10008. }
  10009. // check v-pre
  10010. if (!context.inVPre &&
  10011. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  10012. context.inVPre = true;
  10013. // reset context
  10014. extend(context, cursor);
  10015. context.source = currentSource;
  10016. // re-parse attrs and filter out v-pre itself
  10017. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  10018. }
  10019. // Tag close.
  10020. let isSelfClosing = false;
  10021. if (context.source.length === 0) {
  10022. emitError(context, 9 /* EOF_IN_TAG */);
  10023. }
  10024. else {
  10025. isSelfClosing = startsWith(context.source, '/>');
  10026. if (type === 1 /* End */ && isSelfClosing) {
  10027. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  10028. }
  10029. advanceBy(context, isSelfClosing ? 2 : 1);
  10030. }
  10031. let tagType = 0 /* ELEMENT */;
  10032. const options = context.options;
  10033. if (!context.inVPre && !options.isCustomElement(tag)) {
  10034. const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
  10035. if (options.isNativeTag && !hasVIs) {
  10036. if (!options.isNativeTag(tag))
  10037. tagType = 1 /* COMPONENT */;
  10038. }
  10039. else if (hasVIs ||
  10040. isCoreComponent(tag) ||
  10041. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  10042. /^[A-Z]/.test(tag) ||
  10043. tag === 'component') {
  10044. tagType = 1 /* COMPONENT */;
  10045. }
  10046. if (tag === 'slot') {
  10047. tagType = 2 /* SLOT */;
  10048. }
  10049. else if (tag === 'template' &&
  10050. props.some(p => {
  10051. return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
  10052. })) {
  10053. tagType = 3 /* TEMPLATE */;
  10054. }
  10055. }
  10056. return {
  10057. type: 1 /* ELEMENT */,
  10058. ns,
  10059. tag,
  10060. tagType,
  10061. props,
  10062. isSelfClosing,
  10063. children: [],
  10064. loc: getSelection(context, start),
  10065. codegenNode: undefined // to be created during transform phase
  10066. };
  10067. }
  10068. function parseAttributes(context, type) {
  10069. const props = [];
  10070. const attributeNames = new Set();
  10071. while (context.source.length > 0 &&
  10072. !startsWith(context.source, '>') &&
  10073. !startsWith(context.source, '/>')) {
  10074. if (startsWith(context.source, '/')) {
  10075. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  10076. advanceBy(context, 1);
  10077. advanceSpaces(context);
  10078. continue;
  10079. }
  10080. if (type === 1 /* End */) {
  10081. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  10082. }
  10083. const attr = parseAttribute(context, attributeNames);
  10084. if (type === 0 /* Start */) {
  10085. props.push(attr);
  10086. }
  10087. if (/^[^\t\r\n\f />]/.test(context.source)) {
  10088. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  10089. }
  10090. advanceSpaces(context);
  10091. }
  10092. return props;
  10093. }
  10094. function parseAttribute(context, nameSet) {
  10095. // Name.
  10096. const start = getCursor(context);
  10097. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  10098. const name = match[0];
  10099. if (nameSet.has(name)) {
  10100. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  10101. }
  10102. nameSet.add(name);
  10103. if (name[0] === '=') {
  10104. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  10105. }
  10106. {
  10107. const pattern = /["'<]/g;
  10108. let m;
  10109. while ((m = pattern.exec(name))) {
  10110. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  10111. }
  10112. }
  10113. advanceBy(context, name.length);
  10114. // Value
  10115. let value = undefined;
  10116. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  10117. advanceSpaces(context);
  10118. advanceBy(context, 1);
  10119. advanceSpaces(context);
  10120. value = parseAttributeValue(context);
  10121. if (!value) {
  10122. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  10123. }
  10124. }
  10125. const loc = getSelection(context, start);
  10126. if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
  10127. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  10128. const dirName = match[1] ||
  10129. (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
  10130. let arg;
  10131. if (match[2]) {
  10132. const isSlot = dirName === 'slot';
  10133. const startOffset = name.indexOf(match[2]);
  10134. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  10135. let content = match[2];
  10136. let isStatic = true;
  10137. if (content.startsWith('[')) {
  10138. isStatic = false;
  10139. if (!content.endsWith(']')) {
  10140. emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  10141. }
  10142. content = content.substr(1, content.length - 2);
  10143. }
  10144. else if (isSlot) {
  10145. // #1241 special case for v-slot: vuetify relies extensively on slot
  10146. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  10147. // supports such usage so we are keeping it consistent with 2.x.
  10148. content += match[3] || '';
  10149. }
  10150. arg = {
  10151. type: 4 /* SIMPLE_EXPRESSION */,
  10152. content,
  10153. isStatic,
  10154. isConstant: isStatic,
  10155. loc
  10156. };
  10157. }
  10158. if (value && value.isQuoted) {
  10159. const valueLoc = value.loc;
  10160. valueLoc.start.offset++;
  10161. valueLoc.start.column++;
  10162. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  10163. valueLoc.source = valueLoc.source.slice(1, -1);
  10164. }
  10165. return {
  10166. type: 7 /* DIRECTIVE */,
  10167. name: dirName,
  10168. exp: value && {
  10169. type: 4 /* SIMPLE_EXPRESSION */,
  10170. content: value.content,
  10171. isStatic: false,
  10172. // Treat as non-constant by default. This can be potentially set to
  10173. // true by `transformExpression` to make it eligible for hoisting.
  10174. isConstant: false,
  10175. loc: value.loc
  10176. },
  10177. arg,
  10178. modifiers: match[3] ? match[3].substr(1).split('.') : [],
  10179. loc
  10180. };
  10181. }
  10182. return {
  10183. type: 6 /* ATTRIBUTE */,
  10184. name,
  10185. value: value && {
  10186. type: 2 /* TEXT */,
  10187. content: value.content,
  10188. loc: value.loc
  10189. },
  10190. loc
  10191. };
  10192. }
  10193. function parseAttributeValue(context) {
  10194. const start = getCursor(context);
  10195. let content;
  10196. const quote = context.source[0];
  10197. const isQuoted = quote === `"` || quote === `'`;
  10198. if (isQuoted) {
  10199. // Quoted value.
  10200. advanceBy(context, 1);
  10201. const endIndex = context.source.indexOf(quote);
  10202. if (endIndex === -1) {
  10203. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  10204. }
  10205. else {
  10206. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  10207. advanceBy(context, 1);
  10208. }
  10209. }
  10210. else {
  10211. // Unquoted
  10212. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  10213. if (!match) {
  10214. return undefined;
  10215. }
  10216. const unexpectedChars = /["'<=`]/g;
  10217. let m;
  10218. while ((m = unexpectedChars.exec(match[0]))) {
  10219. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  10220. }
  10221. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  10222. }
  10223. return { content, isQuoted, loc: getSelection(context, start) };
  10224. }
  10225. function parseInterpolation(context, mode) {
  10226. const [open, close] = context.options.delimiters;
  10227. const closeIndex = context.source.indexOf(close, open.length);
  10228. if (closeIndex === -1) {
  10229. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  10230. return undefined;
  10231. }
  10232. const start = getCursor(context);
  10233. advanceBy(context, open.length);
  10234. const innerStart = getCursor(context);
  10235. const innerEnd = getCursor(context);
  10236. const rawContentLength = closeIndex - open.length;
  10237. const rawContent = context.source.slice(0, rawContentLength);
  10238. const preTrimContent = parseTextData(context, rawContentLength, mode);
  10239. const content = preTrimContent.trim();
  10240. const startOffset = preTrimContent.indexOf(content);
  10241. if (startOffset > 0) {
  10242. advancePositionWithMutation(innerStart, rawContent, startOffset);
  10243. }
  10244. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  10245. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  10246. advanceBy(context, close.length);
  10247. return {
  10248. type: 5 /* INTERPOLATION */,
  10249. content: {
  10250. type: 4 /* SIMPLE_EXPRESSION */,
  10251. isStatic: false,
  10252. // Set `isConstant` to false by default and will decide in transformExpression
  10253. isConstant: false,
  10254. content,
  10255. loc: getSelection(context, innerStart, innerEnd)
  10256. },
  10257. loc: getSelection(context, start)
  10258. };
  10259. }
  10260. function parseText(context, mode) {
  10261. const endTokens = ['<', context.options.delimiters[0]];
  10262. if (mode === 3 /* CDATA */) {
  10263. endTokens.push(']]>');
  10264. }
  10265. let endIndex = context.source.length;
  10266. for (let i = 0; i < endTokens.length; i++) {
  10267. const index = context.source.indexOf(endTokens[i], 1);
  10268. if (index !== -1 && endIndex > index) {
  10269. endIndex = index;
  10270. }
  10271. }
  10272. const start = getCursor(context);
  10273. const content = parseTextData(context, endIndex, mode);
  10274. return {
  10275. type: 2 /* TEXT */,
  10276. content,
  10277. loc: getSelection(context, start)
  10278. };
  10279. }
  10280. /**
  10281. * Get text data with a given length from the current location.
  10282. * This translates HTML entities in the text data.
  10283. */
  10284. function parseTextData(context, length, mode) {
  10285. const rawText = context.source.slice(0, length);
  10286. advanceBy(context, length);
  10287. if (mode === 2 /* RAWTEXT */ ||
  10288. mode === 3 /* CDATA */ ||
  10289. rawText.indexOf('&') === -1) {
  10290. return rawText;
  10291. }
  10292. else {
  10293. // DATA or RCDATA containing "&"". Entity decoding required.
  10294. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  10295. }
  10296. }
  10297. function getCursor(context) {
  10298. const { column, line, offset } = context;
  10299. return { column, line, offset };
  10300. }
  10301. function getSelection(context, start, end) {
  10302. end = end || getCursor(context);
  10303. return {
  10304. start,
  10305. end,
  10306. source: context.originalSource.slice(start.offset, end.offset)
  10307. };
  10308. }
  10309. function last(xs) {
  10310. return xs[xs.length - 1];
  10311. }
  10312. function startsWith(source, searchString) {
  10313. return source.startsWith(searchString);
  10314. }
  10315. function advanceBy(context, numberOfCharacters) {
  10316. const { source } = context;
  10317. advancePositionWithMutation(context, source, numberOfCharacters);
  10318. context.source = source.slice(numberOfCharacters);
  10319. }
  10320. function advanceSpaces(context) {
  10321. const match = /^[\t\r\n\f ]+/.exec(context.source);
  10322. if (match) {
  10323. advanceBy(context, match[0].length);
  10324. }
  10325. }
  10326. function getNewPosition(context, start, numberOfCharacters) {
  10327. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  10328. }
  10329. function emitError(context, code, offset, loc = getCursor(context)) {
  10330. if (offset) {
  10331. loc.offset += offset;
  10332. loc.column += offset;
  10333. }
  10334. context.options.onError(createCompilerError(code, {
  10335. start: loc,
  10336. end: loc,
  10337. source: ''
  10338. }));
  10339. }
  10340. function isEnd(context, mode, ancestors) {
  10341. const s = context.source;
  10342. switch (mode) {
  10343. case 0 /* DATA */:
  10344. if (startsWith(s, '</')) {
  10345. //TODO: probably bad performance
  10346. for (let i = ancestors.length - 1; i >= 0; --i) {
  10347. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  10348. return true;
  10349. }
  10350. }
  10351. }
  10352. break;
  10353. case 1 /* RCDATA */:
  10354. case 2 /* RAWTEXT */: {
  10355. const parent = last(ancestors);
  10356. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  10357. return true;
  10358. }
  10359. break;
  10360. }
  10361. case 3 /* CDATA */:
  10362. if (startsWith(s, ']]>')) {
  10363. return true;
  10364. }
  10365. break;
  10366. }
  10367. return !s;
  10368. }
  10369. function startsWithEndTagOpen(source, tag) {
  10370. return (startsWith(source, '</') &&
  10371. source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
  10372. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  10373. }
  10374. function hoistStatic(root, context) {
  10375. walk(root, context, new Map(),
  10376. // Root node is unfortunately non-hoistable due to potential parent
  10377. // fallthrough attributes.
  10378. isSingleElementRoot(root, root.children[0]));
  10379. }
  10380. function isSingleElementRoot(root, child) {
  10381. const { children } = root;
  10382. return (children.length === 1 &&
  10383. child.type === 1 /* ELEMENT */ &&
  10384. !isSlotOutlet(child));
  10385. }
  10386. function walk(node, context, resultCache, doNotHoistNode = false) {
  10387. let hasHoistedNode = false;
  10388. // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
  10389. // static bindings with expressions. These expressions are guaranteed to be
  10390. // constant so they are still eligible for hoisting, but they are only
  10391. // available at runtime and therefore cannot be evaluated ahead of time.
  10392. // This is only a concern for pre-stringification (via transformHoist by
  10393. // @vue/compiler-dom), but doing it here allows us to perform only one full
  10394. // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
  10395. // stringficiation threshold is met.
  10396. let hasRuntimeConstant = false;
  10397. const { children } = node;
  10398. for (let i = 0; i < children.length; i++) {
  10399. const child = children[i];
  10400. // only plain elements & text calls are eligible for hoisting.
  10401. if (child.type === 1 /* ELEMENT */ &&
  10402. child.tagType === 0 /* ELEMENT */) {
  10403. let staticType;
  10404. if (!doNotHoistNode &&
  10405. (staticType = getStaticType(child, resultCache)) > 0) {
  10406. if (staticType === 2 /* HAS_RUNTIME_CONSTANT */) {
  10407. hasRuntimeConstant = true;
  10408. }
  10409. child.codegenNode.patchFlag =
  10410. -1 /* HOISTED */ + ( ` /* HOISTED */` );
  10411. child.codegenNode = context.hoist(child.codegenNode);
  10412. hasHoistedNode = true;
  10413. continue;
  10414. }
  10415. else {
  10416. // node may contain dynamic children, but its props may be eligible for
  10417. // hoisting.
  10418. const codegenNode = child.codegenNode;
  10419. if (codegenNode.type === 13 /* VNODE_CALL */) {
  10420. const flag = getPatchFlag(codegenNode);
  10421. if ((!flag ||
  10422. flag === 512 /* NEED_PATCH */ ||
  10423. flag === 1 /* TEXT */) &&
  10424. !hasNonHoistableProps(child)) {
  10425. const props = getNodeProps(child);
  10426. if (props) {
  10427. codegenNode.props = context.hoist(props);
  10428. }
  10429. }
  10430. }
  10431. }
  10432. }
  10433. else if (child.type === 12 /* TEXT_CALL */) {
  10434. const staticType = getStaticType(child.content, resultCache);
  10435. if (staticType > 0) {
  10436. if (staticType === 2 /* HAS_RUNTIME_CONSTANT */) {
  10437. hasRuntimeConstant = true;
  10438. }
  10439. child.codegenNode = context.hoist(child.codegenNode);
  10440. hasHoistedNode = true;
  10441. }
  10442. }
  10443. // walk further
  10444. if (child.type === 1 /* ELEMENT */) {
  10445. walk(child, context, resultCache);
  10446. }
  10447. else if (child.type === 11 /* FOR */) {
  10448. // Do not hoist v-for single child because it has to be a block
  10449. walk(child, context, resultCache, child.children.length === 1);
  10450. }
  10451. else if (child.type === 9 /* IF */) {
  10452. for (let i = 0; i < child.branches.length; i++) {
  10453. // Do not hoist v-if single child because it has to be a block
  10454. walk(child.branches[i], context, resultCache, child.branches[i].children.length === 1);
  10455. }
  10456. }
  10457. }
  10458. if (!hasRuntimeConstant && hasHoistedNode && context.transformHoist) {
  10459. context.transformHoist(children, context, node);
  10460. }
  10461. }
  10462. function getStaticType(node, resultCache = new Map()) {
  10463. switch (node.type) {
  10464. case 1 /* ELEMENT */:
  10465. if (node.tagType !== 0 /* ELEMENT */) {
  10466. return 0 /* NOT_STATIC */;
  10467. }
  10468. const cached = resultCache.get(node);
  10469. if (cached !== undefined) {
  10470. return cached;
  10471. }
  10472. const codegenNode = node.codegenNode;
  10473. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  10474. return 0 /* NOT_STATIC */;
  10475. }
  10476. const flag = getPatchFlag(codegenNode);
  10477. if (!flag && !hasNonHoistableProps(node)) {
  10478. // element self is static. check its children.
  10479. let returnType = 1 /* FULL_STATIC */;
  10480. for (let i = 0; i < node.children.length; i++) {
  10481. const childType = getStaticType(node.children[i], resultCache);
  10482. if (childType === 0 /* NOT_STATIC */) {
  10483. resultCache.set(node, 0 /* NOT_STATIC */);
  10484. return 0 /* NOT_STATIC */;
  10485. }
  10486. else if (childType === 2 /* HAS_RUNTIME_CONSTANT */) {
  10487. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  10488. }
  10489. }
  10490. // check if any of the props contain runtime constants
  10491. if (returnType !== 2 /* HAS_RUNTIME_CONSTANT */) {
  10492. for (let i = 0; i < node.props.length; i++) {
  10493. const p = node.props[i];
  10494. if (p.type === 7 /* DIRECTIVE */ &&
  10495. p.name === 'bind' &&
  10496. p.exp &&
  10497. (p.exp.type === 8 /* COMPOUND_EXPRESSION */ ||
  10498. p.exp.isRuntimeConstant)) {
  10499. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  10500. }
  10501. }
  10502. }
  10503. // only svg/foreignObject could be block here, however if they are
  10504. // stati then they don't need to be blocks since there will be no
  10505. // nested updates.
  10506. if (codegenNode.isBlock) {
  10507. codegenNode.isBlock = false;
  10508. }
  10509. resultCache.set(node, returnType);
  10510. return returnType;
  10511. }
  10512. else {
  10513. resultCache.set(node, 0 /* NOT_STATIC */);
  10514. return 0 /* NOT_STATIC */;
  10515. }
  10516. case 2 /* TEXT */:
  10517. case 3 /* COMMENT */:
  10518. return 1 /* FULL_STATIC */;
  10519. case 9 /* IF */:
  10520. case 11 /* FOR */:
  10521. case 10 /* IF_BRANCH */:
  10522. return 0 /* NOT_STATIC */;
  10523. case 5 /* INTERPOLATION */:
  10524. case 12 /* TEXT_CALL */:
  10525. return getStaticType(node.content, resultCache);
  10526. case 4 /* SIMPLE_EXPRESSION */:
  10527. return node.isConstant
  10528. ? node.isRuntimeConstant
  10529. ? 2 /* HAS_RUNTIME_CONSTANT */
  10530. : 1 /* FULL_STATIC */
  10531. : 0 /* NOT_STATIC */;
  10532. case 8 /* COMPOUND_EXPRESSION */:
  10533. let returnType = 1 /* FULL_STATIC */;
  10534. for (let i = 0; i < node.children.length; i++) {
  10535. const child = node.children[i];
  10536. if (isString(child) || isSymbol(child)) {
  10537. continue;
  10538. }
  10539. const childType = getStaticType(child, resultCache);
  10540. if (childType === 0 /* NOT_STATIC */) {
  10541. return 0 /* NOT_STATIC */;
  10542. }
  10543. else if (childType === 2 /* HAS_RUNTIME_CONSTANT */) {
  10544. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  10545. }
  10546. }
  10547. return returnType;
  10548. default:
  10549. return 0 /* NOT_STATIC */;
  10550. }
  10551. }
  10552. /**
  10553. * Even for a node with no patch flag, it is possible for it to contain
  10554. * non-hoistable expressions that refers to scope variables, e.g. compiler
  10555. * injected keys or cached event handlers. Therefore we need to always check the
  10556. * codegenNode's props to be sure.
  10557. */
  10558. function hasNonHoistableProps(node) {
  10559. const props = getNodeProps(node);
  10560. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  10561. const { properties } = props;
  10562. for (let i = 0; i < properties.length; i++) {
  10563. const { key, value } = properties[i];
  10564. if (key.type !== 4 /* SIMPLE_EXPRESSION */ ||
  10565. !key.isStatic ||
  10566. (value.type !== 4 /* SIMPLE_EXPRESSION */ ||
  10567. (!value.isStatic && !value.isConstant))) {
  10568. return true;
  10569. }
  10570. }
  10571. }
  10572. return false;
  10573. }
  10574. function getNodeProps(node) {
  10575. const codegenNode = node.codegenNode;
  10576. if (codegenNode.type === 13 /* VNODE_CALL */) {
  10577. return codegenNode.props;
  10578. }
  10579. }
  10580. function getPatchFlag(node) {
  10581. const flag = node.patchFlag;
  10582. return flag ? parseInt(flag, 10) : undefined;
  10583. }
  10584. function createTransformContext(root, { prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, ssr = false, ssrCssVars = ``, bindingMetadata = {}, onError = defaultOnError }) {
  10585. const context = {
  10586. // options
  10587. prefixIdentifiers,
  10588. hoistStatic,
  10589. cacheHandlers,
  10590. nodeTransforms,
  10591. directiveTransforms,
  10592. transformHoist,
  10593. isBuiltInComponent,
  10594. isCustomElement,
  10595. expressionPlugins,
  10596. scopeId,
  10597. ssr,
  10598. ssrCssVars,
  10599. bindingMetadata,
  10600. onError,
  10601. // state
  10602. root,
  10603. helpers: new Set(),
  10604. components: new Set(),
  10605. directives: new Set(),
  10606. hoists: [],
  10607. imports: new Set(),
  10608. temps: 0,
  10609. cached: 0,
  10610. identifiers: Object.create(null),
  10611. scopes: {
  10612. vFor: 0,
  10613. vSlot: 0,
  10614. vPre: 0,
  10615. vOnce: 0
  10616. },
  10617. parent: null,
  10618. currentNode: root,
  10619. childIndex: 0,
  10620. // methods
  10621. helper(name) {
  10622. context.helpers.add(name);
  10623. return name;
  10624. },
  10625. helperString(name) {
  10626. return `_${helperNameMap[context.helper(name)]}`;
  10627. },
  10628. replaceNode(node) {
  10629. /* istanbul ignore if */
  10630. {
  10631. if (!context.currentNode) {
  10632. throw new Error(`Node being replaced is already removed.`);
  10633. }
  10634. if (!context.parent) {
  10635. throw new Error(`Cannot replace root node.`);
  10636. }
  10637. }
  10638. context.parent.children[context.childIndex] = context.currentNode = node;
  10639. },
  10640. removeNode(node) {
  10641. if ( !context.parent) {
  10642. throw new Error(`Cannot remove root node.`);
  10643. }
  10644. const list = context.parent.children;
  10645. const removalIndex = node
  10646. ? list.indexOf(node)
  10647. : context.currentNode
  10648. ? context.childIndex
  10649. : -1;
  10650. /* istanbul ignore if */
  10651. if ( removalIndex < 0) {
  10652. throw new Error(`node being removed is not a child of current parent`);
  10653. }
  10654. if (!node || node === context.currentNode) {
  10655. // current node removed
  10656. context.currentNode = null;
  10657. context.onNodeRemoved();
  10658. }
  10659. else {
  10660. // sibling node removed
  10661. if (context.childIndex > removalIndex) {
  10662. context.childIndex--;
  10663. context.onNodeRemoved();
  10664. }
  10665. }
  10666. context.parent.children.splice(removalIndex, 1);
  10667. },
  10668. onNodeRemoved: () => { },
  10669. addIdentifiers(exp) {
  10670. },
  10671. removeIdentifiers(exp) {
  10672. },
  10673. hoist(exp) {
  10674. context.hoists.push(exp);
  10675. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, true);
  10676. identifier.hoisted = exp;
  10677. return identifier;
  10678. },
  10679. cache(exp, isVNode = false) {
  10680. return createCacheExpression(++context.cached, exp, isVNode);
  10681. }
  10682. };
  10683. return context;
  10684. }
  10685. function transform(root, options) {
  10686. const context = createTransformContext(root, options);
  10687. traverseNode(root, context);
  10688. if (options.hoistStatic) {
  10689. hoistStatic(root, context);
  10690. }
  10691. if (!options.ssr) {
  10692. createRootCodegen(root, context);
  10693. }
  10694. // finalize meta information
  10695. root.helpers = [...context.helpers];
  10696. root.components = [...context.components];
  10697. root.directives = [...context.directives];
  10698. root.imports = [...context.imports];
  10699. root.hoists = context.hoists;
  10700. root.temps = context.temps;
  10701. root.cached = context.cached;
  10702. }
  10703. function createRootCodegen(root, context) {
  10704. const { helper } = context;
  10705. const { children } = root;
  10706. if (children.length === 1) {
  10707. const child = children[0];
  10708. // if the single child is an element, turn it into a block.
  10709. if (isSingleElementRoot(root, child) && child.codegenNode) {
  10710. // single element root is never hoisted so codegenNode will never be
  10711. // SimpleExpressionNode
  10712. const codegenNode = child.codegenNode;
  10713. if (codegenNode.type === 13 /* VNODE_CALL */) {
  10714. codegenNode.isBlock = true;
  10715. helper(OPEN_BLOCK);
  10716. helper(CREATE_BLOCK);
  10717. }
  10718. root.codegenNode = codegenNode;
  10719. }
  10720. else {
  10721. // - single <slot/>, IfNode, ForNode: already blocks.
  10722. // - single text node: always patched.
  10723. // root codegen falls through via genNode()
  10724. root.codegenNode = child;
  10725. }
  10726. }
  10727. else if (children.length > 1) {
  10728. // root has multiple nodes - return a fragment block.
  10729. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, `${64 /* STABLE_FRAGMENT */} /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true);
  10730. }
  10731. else ;
  10732. }
  10733. function traverseChildren(parent, context) {
  10734. let i = 0;
  10735. const nodeRemoved = () => {
  10736. i--;
  10737. };
  10738. for (; i < parent.children.length; i++) {
  10739. const child = parent.children[i];
  10740. if (isString(child))
  10741. continue;
  10742. context.parent = parent;
  10743. context.childIndex = i;
  10744. context.onNodeRemoved = nodeRemoved;
  10745. traverseNode(child, context);
  10746. }
  10747. }
  10748. function traverseNode(node, context) {
  10749. context.currentNode = node;
  10750. // apply transform plugins
  10751. const { nodeTransforms } = context;
  10752. const exitFns = [];
  10753. for (let i = 0; i < nodeTransforms.length; i++) {
  10754. const onExit = nodeTransforms[i](node, context);
  10755. if (onExit) {
  10756. if (isArray(onExit)) {
  10757. exitFns.push(...onExit);
  10758. }
  10759. else {
  10760. exitFns.push(onExit);
  10761. }
  10762. }
  10763. if (!context.currentNode) {
  10764. // node was removed
  10765. return;
  10766. }
  10767. else {
  10768. // node may have been replaced
  10769. node = context.currentNode;
  10770. }
  10771. }
  10772. switch (node.type) {
  10773. case 3 /* COMMENT */:
  10774. if (!context.ssr) {
  10775. // inject import for the Comment symbol, which is needed for creating
  10776. // comment nodes with `createVNode`
  10777. context.helper(CREATE_COMMENT);
  10778. }
  10779. break;
  10780. case 5 /* INTERPOLATION */:
  10781. // no need to traverse, but we need to inject toString helper
  10782. if (!context.ssr) {
  10783. context.helper(TO_DISPLAY_STRING);
  10784. }
  10785. break;
  10786. // for container types, further traverse downwards
  10787. case 9 /* IF */:
  10788. for (let i = 0; i < node.branches.length; i++) {
  10789. traverseNode(node.branches[i], context);
  10790. }
  10791. break;
  10792. case 10 /* IF_BRANCH */:
  10793. case 11 /* FOR */:
  10794. case 1 /* ELEMENT */:
  10795. case 0 /* ROOT */:
  10796. traverseChildren(node, context);
  10797. break;
  10798. }
  10799. // exit transforms
  10800. context.currentNode = node;
  10801. let i = exitFns.length;
  10802. while (i--) {
  10803. exitFns[i]();
  10804. }
  10805. }
  10806. function createStructuralDirectiveTransform(name, fn) {
  10807. const matches = isString(name)
  10808. ? (n) => n === name
  10809. : (n) => name.test(n);
  10810. return (node, context) => {
  10811. if (node.type === 1 /* ELEMENT */) {
  10812. const { props } = node;
  10813. // structural directive transforms are not concerned with slots
  10814. // as they are handled separately in vSlot.ts
  10815. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  10816. return;
  10817. }
  10818. const exitFns = [];
  10819. for (let i = 0; i < props.length; i++) {
  10820. const prop = props[i];
  10821. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  10822. // structural directives are removed to avoid infinite recursion
  10823. // also we remove them *before* applying so that it can further
  10824. // traverse itself in case it moves the node around
  10825. props.splice(i, 1);
  10826. i--;
  10827. const onExit = fn(node, prop, context);
  10828. if (onExit)
  10829. exitFns.push(onExit);
  10830. }
  10831. }
  10832. return exitFns;
  10833. }
  10834. };
  10835. }
  10836. const PURE_ANNOTATION = `/*#__PURE__*/`;
  10837. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
  10838. const context = {
  10839. mode,
  10840. prefixIdentifiers,
  10841. sourceMap,
  10842. filename,
  10843. scopeId,
  10844. optimizeImports,
  10845. runtimeGlobalName,
  10846. runtimeModuleName,
  10847. ssr,
  10848. source: ast.loc.source,
  10849. code: ``,
  10850. column: 1,
  10851. line: 1,
  10852. offset: 0,
  10853. indentLevel: 0,
  10854. pure: false,
  10855. map: undefined,
  10856. helper(key) {
  10857. return `_${helperNameMap[key]}`;
  10858. },
  10859. push(code, node) {
  10860. context.code += code;
  10861. },
  10862. indent() {
  10863. newline(++context.indentLevel);
  10864. },
  10865. deindent(withoutNewLine = false) {
  10866. if (withoutNewLine) {
  10867. --context.indentLevel;
  10868. }
  10869. else {
  10870. newline(--context.indentLevel);
  10871. }
  10872. },
  10873. newline() {
  10874. newline(context.indentLevel);
  10875. }
  10876. };
  10877. function newline(n) {
  10878. context.push('\n' + ` `.repeat(n));
  10879. }
  10880. return context;
  10881. }
  10882. function generate(ast, options = {}) {
  10883. const context = createCodegenContext(ast, options);
  10884. if (options.onContextCreated)
  10885. options.onContextCreated(context);
  10886. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  10887. const hasHelpers = ast.helpers.length > 0;
  10888. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  10889. // preambles
  10890. {
  10891. genFunctionPreamble(ast, context);
  10892. }
  10893. // binding optimizations
  10894. const optimizeSources = options.bindingMetadata
  10895. ? `, $props, $setup, $data, $options`
  10896. : ``;
  10897. // enter render function
  10898. if (!ssr) {
  10899. push(`function render(_ctx, _cache${optimizeSources}) {`);
  10900. }
  10901. else {
  10902. push(`function ssrRender(_ctx, _push, _parent, _attrs${optimizeSources}) {`);
  10903. }
  10904. indent();
  10905. if (useWithBlock) {
  10906. push(`with (_ctx) {`);
  10907. indent();
  10908. // function mode const declarations should be inside with block
  10909. // also they should be renamed to avoid collision with user properties
  10910. if (hasHelpers) {
  10911. push(`const { ${ast.helpers
  10912. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  10913. .join(', ')} } = _Vue`);
  10914. push(`\n`);
  10915. newline();
  10916. }
  10917. }
  10918. // generate asset resolution statements
  10919. if (ast.components.length) {
  10920. genAssets(ast.components, 'component', context);
  10921. if (ast.directives.length || ast.temps > 0) {
  10922. newline();
  10923. }
  10924. }
  10925. if (ast.directives.length) {
  10926. genAssets(ast.directives, 'directive', context);
  10927. if (ast.temps > 0) {
  10928. newline();
  10929. }
  10930. }
  10931. if (ast.temps > 0) {
  10932. push(`let `);
  10933. for (let i = 0; i < ast.temps; i++) {
  10934. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  10935. }
  10936. }
  10937. if (ast.components.length || ast.directives.length || ast.temps) {
  10938. push(`\n`);
  10939. newline();
  10940. }
  10941. // generate the VNode tree expression
  10942. if (!ssr) {
  10943. push(`return `);
  10944. }
  10945. if (ast.codegenNode) {
  10946. genNode(ast.codegenNode, context);
  10947. }
  10948. else {
  10949. push(`null`);
  10950. }
  10951. if (useWithBlock) {
  10952. deindent();
  10953. push(`}`);
  10954. }
  10955. deindent();
  10956. push(`}`);
  10957. return {
  10958. ast,
  10959. code: context.code,
  10960. // SourceMapGenerator does have toJSON() method but it's not in the types
  10961. map: context.map ? context.map.toJSON() : undefined
  10962. };
  10963. }
  10964. function genFunctionPreamble(ast, context) {
  10965. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
  10966. const VueBinding = runtimeGlobalName;
  10967. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  10968. // Generate const declaration for helpers
  10969. // In prefix mode, we place the const declaration at top so it's done
  10970. // only once; But if we not prefixing, we place the declaration inside the
  10971. // with block so it doesn't incur the `in` check cost for every helper access.
  10972. if (ast.helpers.length > 0) {
  10973. {
  10974. // "with" mode.
  10975. // save Vue in a separate variable to avoid collision
  10976. push(`const _Vue = ${VueBinding}\n`);
  10977. // in "with" mode, helpers are declared inside the with block to avoid
  10978. // has check cost, but hoists are lifted out of the function - we need
  10979. // to provide the helper here.
  10980. if (ast.hoists.length) {
  10981. const staticHelpers = [
  10982. CREATE_VNODE,
  10983. CREATE_COMMENT,
  10984. CREATE_TEXT,
  10985. CREATE_STATIC
  10986. ]
  10987. .filter(helper => ast.helpers.includes(helper))
  10988. .map(aliasHelper)
  10989. .join(', ');
  10990. push(`const { ${staticHelpers} } = _Vue\n`);
  10991. }
  10992. }
  10993. }
  10994. genHoists(ast.hoists, context);
  10995. newline();
  10996. push(`return `);
  10997. }
  10998. function genAssets(assets, type, { helper, push, newline }) {
  10999. const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
  11000. for (let i = 0; i < assets.length; i++) {
  11001. const id = assets[i];
  11002. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})`);
  11003. if (i < assets.length - 1) {
  11004. newline();
  11005. }
  11006. }
  11007. }
  11008. function genHoists(hoists, context) {
  11009. if (!hoists.length) {
  11010. return;
  11011. }
  11012. context.pure = true;
  11013. const { push, newline, helper, scopeId, mode } = context;
  11014. newline();
  11015. hoists.forEach((exp, i) => {
  11016. if (exp) {
  11017. push(`const _hoisted_${i + 1} = `);
  11018. genNode(exp, context);
  11019. newline();
  11020. }
  11021. });
  11022. context.pure = false;
  11023. }
  11024. function isText$1(n) {
  11025. return (isString(n) ||
  11026. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  11027. n.type === 2 /* TEXT */ ||
  11028. n.type === 5 /* INTERPOLATION */ ||
  11029. n.type === 8 /* COMPOUND_EXPRESSION */);
  11030. }
  11031. function genNodeListAsArray(nodes, context) {
  11032. const multilines = nodes.length > 3 ||
  11033. ( nodes.some(n => isArray(n) || !isText$1(n)));
  11034. context.push(`[`);
  11035. multilines && context.indent();
  11036. genNodeList(nodes, context, multilines);
  11037. multilines && context.deindent();
  11038. context.push(`]`);
  11039. }
  11040. function genNodeList(nodes, context, multilines = false, comma = true) {
  11041. const { push, newline } = context;
  11042. for (let i = 0; i < nodes.length; i++) {
  11043. const node = nodes[i];
  11044. if (isString(node)) {
  11045. push(node);
  11046. }
  11047. else if (isArray(node)) {
  11048. genNodeListAsArray(node, context);
  11049. }
  11050. else {
  11051. genNode(node, context);
  11052. }
  11053. if (i < nodes.length - 1) {
  11054. if (multilines) {
  11055. comma && push(',');
  11056. newline();
  11057. }
  11058. else {
  11059. comma && push(', ');
  11060. }
  11061. }
  11062. }
  11063. }
  11064. function genNode(node, context) {
  11065. if (isString(node)) {
  11066. context.push(node);
  11067. return;
  11068. }
  11069. if (isSymbol(node)) {
  11070. context.push(context.helper(node));
  11071. return;
  11072. }
  11073. switch (node.type) {
  11074. case 1 /* ELEMENT */:
  11075. case 9 /* IF */:
  11076. case 11 /* FOR */:
  11077. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  11078. `Apply appropriate transforms first.`);
  11079. genNode(node.codegenNode, context);
  11080. break;
  11081. case 2 /* TEXT */:
  11082. genText(node, context);
  11083. break;
  11084. case 4 /* SIMPLE_EXPRESSION */:
  11085. genExpression(node, context);
  11086. break;
  11087. case 5 /* INTERPOLATION */:
  11088. genInterpolation(node, context);
  11089. break;
  11090. case 12 /* TEXT_CALL */:
  11091. genNode(node.codegenNode, context);
  11092. break;
  11093. case 8 /* COMPOUND_EXPRESSION */:
  11094. genCompoundExpression(node, context);
  11095. break;
  11096. case 3 /* COMMENT */:
  11097. genComment(node, context);
  11098. break;
  11099. case 13 /* VNODE_CALL */:
  11100. genVNodeCall(node, context);
  11101. break;
  11102. case 14 /* JS_CALL_EXPRESSION */:
  11103. genCallExpression(node, context);
  11104. break;
  11105. case 15 /* JS_OBJECT_EXPRESSION */:
  11106. genObjectExpression(node, context);
  11107. break;
  11108. case 17 /* JS_ARRAY_EXPRESSION */:
  11109. genArrayExpression(node, context);
  11110. break;
  11111. case 18 /* JS_FUNCTION_EXPRESSION */:
  11112. genFunctionExpression(node, context);
  11113. break;
  11114. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  11115. genConditionalExpression(node, context);
  11116. break;
  11117. case 20 /* JS_CACHE_EXPRESSION */:
  11118. genCacheExpression(node, context);
  11119. break;
  11120. // SSR only types
  11121. case 21 /* JS_BLOCK_STATEMENT */:
  11122. break;
  11123. case 22 /* JS_TEMPLATE_LITERAL */:
  11124. break;
  11125. case 23 /* JS_IF_STATEMENT */:
  11126. break;
  11127. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  11128. break;
  11129. case 25 /* JS_SEQUENCE_EXPRESSION */:
  11130. break;
  11131. case 26 /* JS_RETURN_STATEMENT */:
  11132. break;
  11133. /* istanbul ignore next */
  11134. case 10 /* IF_BRANCH */:
  11135. // noop
  11136. break;
  11137. default:
  11138. {
  11139. assert(false, `unhandled codegen node type: ${node.type}`);
  11140. // make sure we exhaust all possible types
  11141. const exhaustiveCheck = node;
  11142. return exhaustiveCheck;
  11143. }
  11144. }
  11145. }
  11146. function genText(node, context) {
  11147. context.push(JSON.stringify(node.content), node);
  11148. }
  11149. function genExpression(node, context) {
  11150. const { content, isStatic } = node;
  11151. context.push(isStatic ? JSON.stringify(content) : content, node);
  11152. }
  11153. function genInterpolation(node, context) {
  11154. const { push, helper, pure } = context;
  11155. if (pure)
  11156. push(PURE_ANNOTATION);
  11157. push(`${helper(TO_DISPLAY_STRING)}(`);
  11158. genNode(node.content, context);
  11159. push(`)`);
  11160. }
  11161. function genCompoundExpression(node, context) {
  11162. for (let i = 0; i < node.children.length; i++) {
  11163. const child = node.children[i];
  11164. if (isString(child)) {
  11165. context.push(child);
  11166. }
  11167. else {
  11168. genNode(child, context);
  11169. }
  11170. }
  11171. }
  11172. function genExpressionAsPropertyKey(node, context) {
  11173. const { push } = context;
  11174. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  11175. push(`[`);
  11176. genCompoundExpression(node, context);
  11177. push(`]`);
  11178. }
  11179. else if (node.isStatic) {
  11180. // only quote keys if necessary
  11181. const text = isSimpleIdentifier(node.content)
  11182. ? node.content
  11183. : JSON.stringify(node.content);
  11184. push(text, node);
  11185. }
  11186. else {
  11187. push(`[${node.content}]`, node);
  11188. }
  11189. }
  11190. function genComment(node, context) {
  11191. {
  11192. const { push, helper, pure } = context;
  11193. if (pure) {
  11194. push(PURE_ANNOTATION);
  11195. }
  11196. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  11197. }
  11198. }
  11199. function genVNodeCall(node, context) {
  11200. const { push, helper, pure } = context;
  11201. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
  11202. if (directives) {
  11203. push(helper(WITH_DIRECTIVES) + `(`);
  11204. }
  11205. if (isBlock) {
  11206. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  11207. }
  11208. if (pure) {
  11209. push(PURE_ANNOTATION);
  11210. }
  11211. push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
  11212. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  11213. push(`)`);
  11214. if (isBlock) {
  11215. push(`)`);
  11216. }
  11217. if (directives) {
  11218. push(`, `);
  11219. genNode(directives, context);
  11220. push(`)`);
  11221. }
  11222. }
  11223. function genNullableArgs(args) {
  11224. let i = args.length;
  11225. while (i--) {
  11226. if (args[i] != null)
  11227. break;
  11228. }
  11229. return args.slice(0, i + 1).map(arg => arg || `null`);
  11230. }
  11231. // JavaScript
  11232. function genCallExpression(node, context) {
  11233. const { push, helper, pure } = context;
  11234. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  11235. if (pure) {
  11236. push(PURE_ANNOTATION);
  11237. }
  11238. push(callee + `(`, node);
  11239. genNodeList(node.arguments, context);
  11240. push(`)`);
  11241. }
  11242. function genObjectExpression(node, context) {
  11243. const { push, indent, deindent, newline } = context;
  11244. const { properties } = node;
  11245. if (!properties.length) {
  11246. push(`{}`, node);
  11247. return;
  11248. }
  11249. const multilines = properties.length > 1 ||
  11250. (
  11251. properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  11252. push(multilines ? `{` : `{ `);
  11253. multilines && indent();
  11254. for (let i = 0; i < properties.length; i++) {
  11255. const { key, value } = properties[i];
  11256. // key
  11257. genExpressionAsPropertyKey(key, context);
  11258. push(`: `);
  11259. // value
  11260. genNode(value, context);
  11261. if (i < properties.length - 1) {
  11262. // will only reach this if it's multilines
  11263. push(`,`);
  11264. newline();
  11265. }
  11266. }
  11267. multilines && deindent();
  11268. push(multilines ? `}` : ` }`);
  11269. }
  11270. function genArrayExpression(node, context) {
  11271. genNodeListAsArray(node.elements, context);
  11272. }
  11273. function genFunctionExpression(node, context) {
  11274. const { push, indent, deindent, scopeId, mode } = context;
  11275. const { params, returns, body, newline, isSlot } = node;
  11276. if (isSlot) {
  11277. push(`_${helperNameMap[WITH_CTX]}(`);
  11278. }
  11279. push(`(`, node);
  11280. if (isArray(params)) {
  11281. genNodeList(params, context);
  11282. }
  11283. else if (params) {
  11284. genNode(params, context);
  11285. }
  11286. push(`) => `);
  11287. if (newline || body) {
  11288. push(`{`);
  11289. indent();
  11290. }
  11291. if (returns) {
  11292. if (newline) {
  11293. push(`return `);
  11294. }
  11295. if (isArray(returns)) {
  11296. genNodeListAsArray(returns, context);
  11297. }
  11298. else {
  11299. genNode(returns, context);
  11300. }
  11301. }
  11302. else if (body) {
  11303. genNode(body, context);
  11304. }
  11305. if (newline || body) {
  11306. deindent();
  11307. push(`}`);
  11308. }
  11309. if ( isSlot) {
  11310. push(`)`);
  11311. }
  11312. }
  11313. function genConditionalExpression(node, context) {
  11314. const { test, consequent, alternate, newline: needNewline } = node;
  11315. const { push, indent, deindent, newline } = context;
  11316. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  11317. const needsParens = !isSimpleIdentifier(test.content);
  11318. needsParens && push(`(`);
  11319. genExpression(test, context);
  11320. needsParens && push(`)`);
  11321. }
  11322. else {
  11323. push(`(`);
  11324. genNode(test, context);
  11325. push(`)`);
  11326. }
  11327. needNewline && indent();
  11328. context.indentLevel++;
  11329. needNewline || push(` `);
  11330. push(`? `);
  11331. genNode(consequent, context);
  11332. context.indentLevel--;
  11333. needNewline && newline();
  11334. needNewline || push(` `);
  11335. push(`: `);
  11336. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  11337. if (!isNested) {
  11338. context.indentLevel++;
  11339. }
  11340. genNode(alternate, context);
  11341. if (!isNested) {
  11342. context.indentLevel--;
  11343. }
  11344. needNewline && deindent(true /* without newline */);
  11345. }
  11346. function genCacheExpression(node, context) {
  11347. const { push, helper, indent, deindent, newline } = context;
  11348. push(`_cache[${node.index}] || (`);
  11349. if (node.isVNode) {
  11350. indent();
  11351. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  11352. newline();
  11353. }
  11354. push(`_cache[${node.index}] = `);
  11355. genNode(node.value, context);
  11356. if (node.isVNode) {
  11357. push(`,`);
  11358. newline();
  11359. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  11360. newline();
  11361. push(`_cache[${node.index}]`);
  11362. deindent();
  11363. }
  11364. push(`)`);
  11365. }
  11366. // these keywords should not appear inside expressions, but operators like
  11367. // typeof, instanceof and in are allowed
  11368. const prohibitedKeywordRE = new RegExp('\\b' +
  11369. ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
  11370. 'super,throw,while,yield,delete,export,import,return,switch,default,' +
  11371. 'extends,finally,continue,debugger,function,arguments,typeof,void')
  11372. .split(',')
  11373. .join('\\b|\\b') +
  11374. '\\b');
  11375. // strip strings in expressions
  11376. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  11377. /**
  11378. * Validate a non-prefixed expression.
  11379. * This is only called when using the in-browser runtime compiler since it
  11380. * doesn't prefix expressions.
  11381. */
  11382. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  11383. const exp = node.content;
  11384. // empty expressions are validated per-directive since some directives
  11385. // do allow empty expressions.
  11386. if (!exp.trim()) {
  11387. return;
  11388. }
  11389. try {
  11390. new Function(asRawStatements
  11391. ? ` ${exp} `
  11392. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  11393. }
  11394. catch (e) {
  11395. let message = e.message;
  11396. const keywordMatch = exp
  11397. .replace(stripStringRE, '')
  11398. .match(prohibitedKeywordRE);
  11399. if (keywordMatch) {
  11400. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  11401. }
  11402. context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
  11403. }
  11404. }
  11405. const transformExpression = (node, context) => {
  11406. if (node.type === 5 /* INTERPOLATION */) {
  11407. node.content = processExpression(node.content, context);
  11408. }
  11409. else if (node.type === 1 /* ELEMENT */) {
  11410. // handle directives on element
  11411. for (let i = 0; i < node.props.length; i++) {
  11412. const dir = node.props[i];
  11413. // do not process for v-on & v-for since they are special handled
  11414. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  11415. const exp = dir.exp;
  11416. const arg = dir.arg;
  11417. // do not process exp if this is v-on:arg - we need special handling
  11418. // for wrapping inline statements.
  11419. if (exp &&
  11420. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  11421. !(dir.name === 'on' && arg)) {
  11422. dir.exp = processExpression(exp, context,
  11423. // slot args must be processed as function params
  11424. dir.name === 'slot');
  11425. }
  11426. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  11427. dir.arg = processExpression(arg, context);
  11428. }
  11429. }
  11430. }
  11431. }
  11432. };
  11433. // Important: since this function uses Node.js only dependencies, it should
  11434. // always be used with a leading !true check so that it can be
  11435. // tree-shaken from the browser build.
  11436. function processExpression(node, context,
  11437. // some expressions like v-slot props & v-for aliases should be parsed as
  11438. // function params
  11439. asParams = false,
  11440. // v-on handler values may contain multiple statements
  11441. asRawStatements = false) {
  11442. {
  11443. // simple in-browser validation (same logic in 2.x)
  11444. validateBrowserExpression(node, context, asParams, asRawStatements);
  11445. return node;
  11446. }
  11447. }
  11448. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  11449. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  11450. // #1587: We need to dynamically increment the key based on the current
  11451. // node's sibling nodes, since chained v-if/else branches are
  11452. // rendered at the same depth
  11453. const siblings = context.parent.children;
  11454. let i = siblings.indexOf(ifNode);
  11455. let key = 0;
  11456. while (i-- >= 0) {
  11457. const sibling = siblings[i];
  11458. if (sibling && sibling.type === 9 /* IF */) {
  11459. key += sibling.branches.length;
  11460. }
  11461. }
  11462. // Exit callback. Complete the codegenNode when all children have been
  11463. // transformed.
  11464. return () => {
  11465. if (isRoot) {
  11466. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  11467. }
  11468. else {
  11469. // attach this branch's codegen node to the v-if root.
  11470. const parentCondition = getParentCondition(ifNode.codegenNode);
  11471. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  11472. }
  11473. };
  11474. });
  11475. });
  11476. // target-agnostic transform used for both Client and SSR
  11477. function processIf(node, dir, context, processCodegen) {
  11478. if (dir.name !== 'else' &&
  11479. (!dir.exp || !dir.exp.content.trim())) {
  11480. const loc = dir.exp ? dir.exp.loc : node.loc;
  11481. context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  11482. dir.exp = createSimpleExpression(`true`, false, loc);
  11483. }
  11484. if ( dir.exp) {
  11485. validateBrowserExpression(dir.exp, context);
  11486. }
  11487. if (dir.name === 'if') {
  11488. const branch = createIfBranch(node, dir);
  11489. const ifNode = {
  11490. type: 9 /* IF */,
  11491. loc: node.loc,
  11492. branches: [branch]
  11493. };
  11494. context.replaceNode(ifNode);
  11495. if (processCodegen) {
  11496. return processCodegen(ifNode, branch, true);
  11497. }
  11498. }
  11499. else {
  11500. // locate the adjacent v-if
  11501. const siblings = context.parent.children;
  11502. const comments = [];
  11503. let i = siblings.indexOf(node);
  11504. while (i-- >= -1) {
  11505. const sibling = siblings[i];
  11506. if ( sibling && sibling.type === 3 /* COMMENT */) {
  11507. context.removeNode(sibling);
  11508. comments.unshift(sibling);
  11509. continue;
  11510. }
  11511. if (sibling &&
  11512. sibling.type === 2 /* TEXT */ &&
  11513. !sibling.content.trim().length) {
  11514. context.removeNode(sibling);
  11515. continue;
  11516. }
  11517. if (sibling && sibling.type === 9 /* IF */) {
  11518. // move the node to the if node's branches
  11519. context.removeNode();
  11520. const branch = createIfBranch(node, dir);
  11521. if ( comments.length) {
  11522. branch.children = [...comments, ...branch.children];
  11523. }
  11524. // check if user is forcing same key on different branches
  11525. {
  11526. const key = branch.userKey;
  11527. if (key) {
  11528. sibling.branches.forEach(({ userKey }) => {
  11529. if (isSameKey(userKey, key)) {
  11530. context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  11531. }
  11532. });
  11533. }
  11534. }
  11535. sibling.branches.push(branch);
  11536. const onExit = processCodegen && processCodegen(sibling, branch, false);
  11537. // since the branch was removed, it will not be traversed.
  11538. // make sure to traverse here.
  11539. traverseNode(branch, context);
  11540. // call on exit
  11541. if (onExit)
  11542. onExit();
  11543. // make sure to reset currentNode after traversal to indicate this
  11544. // node has been removed.
  11545. context.currentNode = null;
  11546. }
  11547. else {
  11548. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  11549. }
  11550. break;
  11551. }
  11552. }
  11553. }
  11554. function createIfBranch(node, dir) {
  11555. return {
  11556. type: 10 /* IF_BRANCH */,
  11557. loc: node.loc,
  11558. condition: dir.name === 'else' ? undefined : dir.exp,
  11559. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  11560. ? node.children
  11561. : [node],
  11562. userKey: findProp(node, `key`)
  11563. };
  11564. }
  11565. function createCodegenNodeForBranch(branch, keyIndex, context) {
  11566. if (branch.condition) {
  11567. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  11568. // make sure to pass in asBlock: true so that the comment node call
  11569. // closes the current block.
  11570. createCallExpression(context.helper(CREATE_COMMENT), [
  11571. '"v-if"' ,
  11572. 'true'
  11573. ]));
  11574. }
  11575. else {
  11576. return createChildrenCodegenNode(branch, keyIndex, context);
  11577. }
  11578. }
  11579. function createChildrenCodegenNode(branch, keyIndex, context) {
  11580. const { helper } = context;
  11581. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, true));
  11582. const { children } = branch;
  11583. const firstChild = children[0];
  11584. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  11585. if (needFragmentWrapper) {
  11586. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  11587. // optimize away nested fragments when child is a ForNode
  11588. const vnodeCall = firstChild.codegenNode;
  11589. injectProp(vnodeCall, keyProperty, context);
  11590. return vnodeCall;
  11591. }
  11592. else {
  11593. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, `${64 /* STABLE_FRAGMENT */} /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true, false, branch.loc);
  11594. }
  11595. }
  11596. else {
  11597. const vnodeCall = firstChild
  11598. .codegenNode;
  11599. // Change createVNode to createBlock.
  11600. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  11601. vnodeCall.isBlock = true;
  11602. helper(OPEN_BLOCK);
  11603. helper(CREATE_BLOCK);
  11604. }
  11605. // inject branch key
  11606. injectProp(vnodeCall, keyProperty, context);
  11607. return vnodeCall;
  11608. }
  11609. }
  11610. function isSameKey(a, b) {
  11611. if (!a || a.type !== b.type) {
  11612. return false;
  11613. }
  11614. if (a.type === 6 /* ATTRIBUTE */) {
  11615. if (a.value.content !== b.value.content) {
  11616. return false;
  11617. }
  11618. }
  11619. else {
  11620. // directive
  11621. const exp = a.exp;
  11622. const branchExp = b.exp;
  11623. if (exp.type !== branchExp.type) {
  11624. return false;
  11625. }
  11626. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  11627. (exp.isStatic !== branchExp.isStatic ||
  11628. exp.content !== branchExp.content)) {
  11629. return false;
  11630. }
  11631. }
  11632. return true;
  11633. }
  11634. function getParentCondition(node) {
  11635. while (true) {
  11636. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  11637. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  11638. node = node.alternate;
  11639. }
  11640. else {
  11641. return node;
  11642. }
  11643. }
  11644. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  11645. node = node.value;
  11646. }
  11647. }
  11648. }
  11649. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  11650. const { helper } = context;
  11651. return processFor(node, dir, context, forNode => {
  11652. // create the loop render function expression now, and add the
  11653. // iterator on exit after all children have been traversed
  11654. const renderExp = createCallExpression(helper(RENDER_LIST), [
  11655. forNode.source
  11656. ]);
  11657. const keyProp = findProp(node, `key`);
  11658. const keyProperty = keyProp
  11659. ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
  11660. ? createSimpleExpression(keyProp.value.content, true)
  11661. : keyProp.exp)
  11662. : null;
  11663. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  11664. forNode.source.isConstant;
  11665. const fragmentFlag = isStableFragment
  11666. ? 64 /* STABLE_FRAGMENT */
  11667. : keyProp
  11668. ? 128 /* KEYED_FRAGMENT */
  11669. : 256 /* UNKEYED_FRAGMENT */;
  11670. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, `${fragmentFlag} /* ${PatchFlagNames[fragmentFlag]} */`, undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
  11671. return () => {
  11672. // finish the codegen now that all children have been traversed
  11673. let childBlock;
  11674. const isTemplate = isTemplateNode(node);
  11675. const { children } = forNode;
  11676. // check <template v-for> key placement
  11677. if ( isTemplate) {
  11678. node.children.some(c => {
  11679. if (c.type === 1 /* ELEMENT */) {
  11680. const key = findProp(c, 'key');
  11681. if (key) {
  11682. context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  11683. return true;
  11684. }
  11685. }
  11686. });
  11687. }
  11688. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  11689. const slotOutlet = isSlotOutlet(node)
  11690. ? node
  11691. : isTemplate &&
  11692. node.children.length === 1 &&
  11693. isSlotOutlet(node.children[0])
  11694. ? node.children[0] // api-extractor somehow fails to infer this
  11695. : null;
  11696. if (slotOutlet) {
  11697. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  11698. childBlock = slotOutlet.codegenNode;
  11699. if (isTemplate && keyProperty) {
  11700. // <template v-for="..." :key="..."><slot/></template>
  11701. // we need to inject the key to the renderSlot() call.
  11702. // the props for renderSlot is passed as the 3rd argument.
  11703. injectProp(childBlock, keyProperty, context);
  11704. }
  11705. }
  11706. else if (needFragmentWrapper) {
  11707. // <template v-for="..."> with text or multi-elements
  11708. // should generate a fragment block for each loop
  11709. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, `${64 /* STABLE_FRAGMENT */} /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true);
  11710. }
  11711. else {
  11712. // Normal element v-for. Directly use the child's codegenNode
  11713. // but mark it as a block.
  11714. childBlock = children[0]
  11715. .codegenNode;
  11716. if (isTemplate && keyProperty) {
  11717. injectProp(childBlock, keyProperty, context);
  11718. }
  11719. childBlock.isBlock = !isStableFragment;
  11720. if (childBlock.isBlock) {
  11721. helper(OPEN_BLOCK);
  11722. helper(CREATE_BLOCK);
  11723. }
  11724. }
  11725. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  11726. };
  11727. });
  11728. });
  11729. // target-agnostic transform used for both Client and SSR
  11730. function processFor(node, dir, context, processCodegen) {
  11731. if (!dir.exp) {
  11732. context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  11733. return;
  11734. }
  11735. const parseResult = parseForExpression(
  11736. // can only be simple expression because vFor transform is applied
  11737. // before expression transform.
  11738. dir.exp, context);
  11739. if (!parseResult) {
  11740. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  11741. return;
  11742. }
  11743. const { addIdentifiers, removeIdentifiers, scopes } = context;
  11744. const { source, value, key, index } = parseResult;
  11745. const forNode = {
  11746. type: 11 /* FOR */,
  11747. loc: dir.loc,
  11748. source,
  11749. valueAlias: value,
  11750. keyAlias: key,
  11751. objectIndexAlias: index,
  11752. parseResult,
  11753. children: isTemplateNode(node) ? node.children : [node]
  11754. };
  11755. context.replaceNode(forNode);
  11756. // bookkeeping
  11757. scopes.vFor++;
  11758. const onExit = processCodegen && processCodegen(forNode);
  11759. return () => {
  11760. scopes.vFor--;
  11761. if (onExit)
  11762. onExit();
  11763. };
  11764. }
  11765. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  11766. // This regex doesn't cover the case if key or index aliases have destructuring,
  11767. // but those do not make sense in the first place, so this works in practice.
  11768. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  11769. const stripParensRE = /^\(|\)$/g;
  11770. function parseForExpression(input, context) {
  11771. const loc = input.loc;
  11772. const exp = input.content;
  11773. const inMatch = exp.match(forAliasRE);
  11774. if (!inMatch)
  11775. return;
  11776. const [, LHS, RHS] = inMatch;
  11777. const result = {
  11778. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  11779. value: undefined,
  11780. key: undefined,
  11781. index: undefined
  11782. };
  11783. {
  11784. validateBrowserExpression(result.source, context);
  11785. }
  11786. let valueContent = LHS.trim()
  11787. .replace(stripParensRE, '')
  11788. .trim();
  11789. const trimmedOffset = LHS.indexOf(valueContent);
  11790. const iteratorMatch = valueContent.match(forIteratorRE);
  11791. if (iteratorMatch) {
  11792. valueContent = valueContent.replace(forIteratorRE, '').trim();
  11793. const keyContent = iteratorMatch[1].trim();
  11794. let keyOffset;
  11795. if (keyContent) {
  11796. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  11797. result.key = createAliasExpression(loc, keyContent, keyOffset);
  11798. {
  11799. validateBrowserExpression(result.key, context, true);
  11800. }
  11801. }
  11802. if (iteratorMatch[2]) {
  11803. const indexContent = iteratorMatch[2].trim();
  11804. if (indexContent) {
  11805. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  11806. ? keyOffset + keyContent.length
  11807. : trimmedOffset + valueContent.length));
  11808. {
  11809. validateBrowserExpression(result.index, context, true);
  11810. }
  11811. }
  11812. }
  11813. }
  11814. if (valueContent) {
  11815. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  11816. {
  11817. validateBrowserExpression(result.value, context, true);
  11818. }
  11819. }
  11820. return result;
  11821. }
  11822. function createAliasExpression(range, content, offset) {
  11823. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  11824. }
  11825. function createForLoopParams({ value, key, index }) {
  11826. const params = [];
  11827. if (value) {
  11828. params.push(value);
  11829. }
  11830. if (key) {
  11831. if (!value) {
  11832. params.push(createSimpleExpression(`_`, false));
  11833. }
  11834. params.push(key);
  11835. }
  11836. if (index) {
  11837. if (!key) {
  11838. if (!value) {
  11839. params.push(createSimpleExpression(`_`, false));
  11840. }
  11841. params.push(createSimpleExpression(`__`, false));
  11842. }
  11843. params.push(index);
  11844. }
  11845. return params;
  11846. }
  11847. const defaultFallback = createSimpleExpression(`undefined`, false);
  11848. // A NodeTransform that:
  11849. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  11850. // by transformExpression. This is only applied in non-browser builds with
  11851. // { prefixIdentifiers: true }.
  11852. // 2. Track v-slot depths so that we know a slot is inside another slot.
  11853. // Note the exit callback is executed before buildSlots() on the same node,
  11854. // so only nested slots see positive numbers.
  11855. const trackSlotScopes = (node, context) => {
  11856. if (node.type === 1 /* ELEMENT */ &&
  11857. (node.tagType === 1 /* COMPONENT */ ||
  11858. node.tagType === 3 /* TEMPLATE */)) {
  11859. // We are only checking non-empty v-slot here
  11860. // since we only care about slots that introduce scope variables.
  11861. const vSlot = findDir(node, 'slot');
  11862. if (vSlot) {
  11863. const slotProps = vSlot.exp;
  11864. context.scopes.vSlot++;
  11865. return () => {
  11866. context.scopes.vSlot--;
  11867. };
  11868. }
  11869. }
  11870. };
  11871. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  11872. // Instead of being a DirectiveTransform, v-slot processing is called during
  11873. // transformElement to build the slots object for a component.
  11874. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  11875. context.helper(WITH_CTX);
  11876. const { children, loc } = node;
  11877. const slotsProperties = [];
  11878. const dynamicSlots = [];
  11879. const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
  11880. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  11881. // since it likely uses a scope variable.
  11882. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  11883. // 1. Check for slot with slotProps on component itself.
  11884. // <Comp v-slot="{ prop }"/>
  11885. const onComponentSlot = findDir(node, 'slot', true);
  11886. if (onComponentSlot) {
  11887. const { arg, exp } = onComponentSlot;
  11888. if (arg && !isStaticExp(arg)) {
  11889. hasDynamicSlots = true;
  11890. }
  11891. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  11892. }
  11893. // 2. Iterate through children and check for template slots
  11894. // <template v-slot:foo="{ prop }">
  11895. let hasTemplateSlots = false;
  11896. let hasNamedDefaultSlot = false;
  11897. const implicitDefaultChildren = [];
  11898. const seenSlotNames = new Set();
  11899. for (let i = 0; i < children.length; i++) {
  11900. const slotElement = children[i];
  11901. let slotDir;
  11902. if (!isTemplateNode(slotElement) ||
  11903. !(slotDir = findDir(slotElement, 'slot', true))) {
  11904. // not a <template v-slot>, skip.
  11905. if (slotElement.type !== 3 /* COMMENT */) {
  11906. implicitDefaultChildren.push(slotElement);
  11907. }
  11908. continue;
  11909. }
  11910. if (onComponentSlot) {
  11911. // already has on-component slot - this is incorrect usage.
  11912. context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  11913. break;
  11914. }
  11915. hasTemplateSlots = true;
  11916. const { children: slotChildren, loc: slotLoc } = slotElement;
  11917. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  11918. // check if name is dynamic.
  11919. let staticSlotName;
  11920. if (isStaticExp(slotName)) {
  11921. staticSlotName = slotName ? slotName.content : `default`;
  11922. }
  11923. else {
  11924. hasDynamicSlots = true;
  11925. }
  11926. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  11927. // check if this slot is conditional (v-if/v-for)
  11928. let vIf;
  11929. let vElse;
  11930. let vFor;
  11931. if ((vIf = findDir(slotElement, 'if'))) {
  11932. hasDynamicSlots = true;
  11933. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  11934. }
  11935. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  11936. // find adjacent v-if
  11937. let j = i;
  11938. let prev;
  11939. while (j--) {
  11940. prev = children[j];
  11941. if (prev.type !== 3 /* COMMENT */) {
  11942. break;
  11943. }
  11944. }
  11945. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  11946. // remove node
  11947. children.splice(i, 1);
  11948. i--;
  11949. // attach this slot to previous conditional
  11950. let conditional = dynamicSlots[dynamicSlots.length - 1];
  11951. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  11952. conditional = conditional.alternate;
  11953. }
  11954. conditional.alternate = vElse.exp
  11955. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  11956. : buildDynamicSlot(slotName, slotFunction);
  11957. }
  11958. else {
  11959. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  11960. }
  11961. }
  11962. else if ((vFor = findDir(slotElement, 'for'))) {
  11963. hasDynamicSlots = true;
  11964. const parseResult = vFor.parseResult ||
  11965. parseForExpression(vFor.exp, context);
  11966. if (parseResult) {
  11967. // Render the dynamic slots as an array and add it to the createSlot()
  11968. // args. The runtime knows how to handle it appropriately.
  11969. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  11970. parseResult.source,
  11971. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  11972. ]));
  11973. }
  11974. else {
  11975. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  11976. }
  11977. }
  11978. else {
  11979. // check duplicate static names
  11980. if (staticSlotName) {
  11981. if (seenSlotNames.has(staticSlotName)) {
  11982. context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  11983. continue;
  11984. }
  11985. seenSlotNames.add(staticSlotName);
  11986. if (staticSlotName === 'default') {
  11987. hasNamedDefaultSlot = true;
  11988. }
  11989. }
  11990. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  11991. }
  11992. }
  11993. if (!onComponentSlot) {
  11994. if (!hasTemplateSlots) {
  11995. // implicit default slot (on component)
  11996. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  11997. }
  11998. else if (implicitDefaultChildren.length) {
  11999. // implicit default slot (mixed with named slots)
  12000. if (hasNamedDefaultSlot) {
  12001. context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  12002. }
  12003. else {
  12004. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  12005. }
  12006. }
  12007. }
  12008. const slotFlag = hasDynamicSlots
  12009. ? 2 /* DYNAMIC */
  12010. : hasForwardedSlots(node.children)
  12011. ? 3 /* FORWARDED */
  12012. : 1 /* STABLE */;
  12013. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  12014. // 2 = compiled but dynamic = can skip normalization, but must run diff
  12015. // 1 = compiled and static = can skip normalization AND diff as optimized
  12016. createSimpleExpression('' + slotFlag, false))), loc);
  12017. if (dynamicSlots.length) {
  12018. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  12019. slots,
  12020. createArrayExpression(dynamicSlots)
  12021. ]);
  12022. }
  12023. return {
  12024. slots,
  12025. hasDynamicSlots
  12026. };
  12027. }
  12028. function buildDynamicSlot(name, fn) {
  12029. return createObjectExpression([
  12030. createObjectProperty(`name`, name),
  12031. createObjectProperty(`fn`, fn)
  12032. ]);
  12033. }
  12034. function hasForwardedSlots(children) {
  12035. for (let i = 0; i < children.length; i++) {
  12036. const child = children[i];
  12037. if (child.type === 1 /* ELEMENT */) {
  12038. if (child.tagType === 2 /* SLOT */ ||
  12039. (child.tagType === 0 /* ELEMENT */ &&
  12040. hasForwardedSlots(child.children))) {
  12041. return true;
  12042. }
  12043. }
  12044. }
  12045. return false;
  12046. }
  12047. // some directive transforms (e.g. v-model) may return a symbol for runtime
  12048. // import, which should be used instead of a resolveDirective call.
  12049. const directiveImportMap = new WeakMap();
  12050. // generate a JavaScript AST for this element's codegen
  12051. const transformElement = (node, context) => {
  12052. if (!(node.type === 1 /* ELEMENT */ &&
  12053. (node.tagType === 0 /* ELEMENT */ ||
  12054. node.tagType === 1 /* COMPONENT */))) {
  12055. return;
  12056. }
  12057. // perform the work on exit, after all child expressions have been
  12058. // processed and merged.
  12059. return function postTransformElement() {
  12060. const { tag, props } = node;
  12061. const isComponent = node.tagType === 1 /* COMPONENT */;
  12062. // The goal of the transform is to create a codegenNode implementing the
  12063. // VNodeCall interface.
  12064. const vnodeTag = isComponent
  12065. ? resolveComponentType(node, context)
  12066. : `"${tag}"`;
  12067. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  12068. let vnodeProps;
  12069. let vnodeChildren;
  12070. let vnodePatchFlag;
  12071. let patchFlag = 0;
  12072. let vnodeDynamicProps;
  12073. let dynamicPropNames;
  12074. let vnodeDirectives;
  12075. let shouldUseBlock =
  12076. // dynamic component may resolve to plain elements
  12077. isDynamicComponent ||
  12078. vnodeTag === TELEPORT ||
  12079. vnodeTag === SUSPENSE ||
  12080. (!isComponent &&
  12081. // <svg> and <foreignObject> must be forced into blocks so that block
  12082. // updates inside get proper isSVG flag at runtime. (#639, #643)
  12083. // This is technically web-specific, but splitting the logic out of core
  12084. // leads to too much unnecessary complexity.
  12085. (tag === 'svg' ||
  12086. tag === 'foreignObject' ||
  12087. // #938: elements with dynamic keys should be forced into blocks
  12088. findProp(node, 'key', true)));
  12089. // props
  12090. if (props.length > 0) {
  12091. const propsBuildResult = buildProps(node, context);
  12092. vnodeProps = propsBuildResult.props;
  12093. patchFlag = propsBuildResult.patchFlag;
  12094. dynamicPropNames = propsBuildResult.dynamicPropNames;
  12095. const directives = propsBuildResult.directives;
  12096. vnodeDirectives =
  12097. directives && directives.length
  12098. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  12099. : undefined;
  12100. }
  12101. // children
  12102. if (node.children.length > 0) {
  12103. if (vnodeTag === KEEP_ALIVE) {
  12104. // Although a built-in component, we compile KeepAlive with raw children
  12105. // instead of slot functions so that it can be used inside Transition
  12106. // or other Transition-wrapping HOCs.
  12107. // To ensure correct updates with block optimizations, we need to:
  12108. // 1. Force keep-alive into a block. This avoids its children being
  12109. // collected by a parent block.
  12110. shouldUseBlock = true;
  12111. // 2. Force keep-alive to always be updated, since it uses raw children.
  12112. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  12113. if ( node.children.length > 1) {
  12114. context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  12115. start: node.children[0].loc.start,
  12116. end: node.children[node.children.length - 1].loc.end,
  12117. source: ''
  12118. }));
  12119. }
  12120. }
  12121. const shouldBuildAsSlots = isComponent &&
  12122. // Teleport is not a real component and has dedicated runtime handling
  12123. vnodeTag !== TELEPORT &&
  12124. // explained above.
  12125. vnodeTag !== KEEP_ALIVE;
  12126. if (shouldBuildAsSlots) {
  12127. const { slots, hasDynamicSlots } = buildSlots(node, context);
  12128. vnodeChildren = slots;
  12129. if (hasDynamicSlots) {
  12130. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  12131. }
  12132. }
  12133. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  12134. const child = node.children[0];
  12135. const type = child.type;
  12136. // check for dynamic text children
  12137. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  12138. type === 8 /* COMPOUND_EXPRESSION */;
  12139. if (hasDynamicTextChild && !getStaticType(child)) {
  12140. patchFlag |= 1 /* TEXT */;
  12141. }
  12142. // pass directly if the only child is a text node
  12143. // (plain / interpolation / expression)
  12144. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  12145. vnodeChildren = child;
  12146. }
  12147. else {
  12148. vnodeChildren = node.children;
  12149. }
  12150. }
  12151. else {
  12152. vnodeChildren = node.children;
  12153. }
  12154. }
  12155. // patchFlag & dynamicPropNames
  12156. if (patchFlag !== 0) {
  12157. {
  12158. if (patchFlag < 0) {
  12159. // special flags (negative and mutually exclusive)
  12160. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  12161. }
  12162. else {
  12163. // bitwise flags
  12164. const flagNames = Object.keys(PatchFlagNames)
  12165. .map(Number)
  12166. .filter(n => n > 0 && patchFlag & n)
  12167. .map(n => PatchFlagNames[n])
  12168. .join(`, `);
  12169. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  12170. }
  12171. }
  12172. if (dynamicPropNames && dynamicPropNames.length) {
  12173. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  12174. }
  12175. }
  12176. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
  12177. };
  12178. };
  12179. function resolveComponentType(node, context, ssr = false) {
  12180. const { tag } = node;
  12181. // 1. dynamic component
  12182. const isProp = node.tag === 'component' ? findProp(node, 'is') : findDir(node, 'is');
  12183. if (isProp) {
  12184. const exp = isProp.type === 6 /* ATTRIBUTE */
  12185. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  12186. : isProp.exp;
  12187. if (exp) {
  12188. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  12189. exp
  12190. ]);
  12191. }
  12192. }
  12193. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  12194. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  12195. if (builtIn) {
  12196. // built-ins are simply fallthroughs / have special handling during ssr
  12197. // no we don't need to import their runtime equivalents
  12198. if (!ssr)
  12199. context.helper(builtIn);
  12200. return builtIn;
  12201. }
  12202. // 3. user component (from setup bindings)
  12203. if (context.bindingMetadata[tag] === 'setup') {
  12204. return `$setup[${JSON.stringify(tag)}]`;
  12205. }
  12206. // 4. user component (resolve)
  12207. context.helper(RESOLVE_COMPONENT);
  12208. context.components.add(tag);
  12209. return toValidAssetId(tag, `component`);
  12210. }
  12211. function buildProps(node, context, props = node.props, ssr = false) {
  12212. const { tag, loc: elementLoc } = node;
  12213. const isComponent = node.tagType === 1 /* COMPONENT */;
  12214. let properties = [];
  12215. const mergeArgs = [];
  12216. const runtimeDirectives = [];
  12217. // patchFlag analysis
  12218. let patchFlag = 0;
  12219. let hasRef = false;
  12220. let hasClassBinding = false;
  12221. let hasStyleBinding = false;
  12222. let hasHydrationEventBinding = false;
  12223. let hasDynamicKeys = false;
  12224. let hasVnodeHook = false;
  12225. const dynamicPropNames = [];
  12226. const analyzePatchFlag = ({ key, value }) => {
  12227. if (isStaticExp(key)) {
  12228. const name = key.content;
  12229. const isEventHandler = isOn(name);
  12230. if (!isComponent &&
  12231. isEventHandler &&
  12232. // omit the flag for click handlers because hydration gives click
  12233. // dedicated fast path.
  12234. name.toLowerCase() !== 'onclick' &&
  12235. // omit v-model handlers
  12236. name !== 'onUpdate:modelValue' &&
  12237. // omit onVnodeXXX hooks
  12238. !isReservedProp(name)) {
  12239. hasHydrationEventBinding = true;
  12240. }
  12241. if (isEventHandler && isReservedProp(name)) {
  12242. hasVnodeHook = true;
  12243. }
  12244. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  12245. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  12246. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  12247. getStaticType(value) > 0)) {
  12248. // skip if the prop is a cached handler or has constant value
  12249. return;
  12250. }
  12251. if (name === 'ref') {
  12252. hasRef = true;
  12253. }
  12254. else if (name === 'class' && !isComponent) {
  12255. hasClassBinding = true;
  12256. }
  12257. else if (name === 'style' && !isComponent) {
  12258. hasStyleBinding = true;
  12259. }
  12260. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  12261. dynamicPropNames.push(name);
  12262. }
  12263. }
  12264. else {
  12265. hasDynamicKeys = true;
  12266. }
  12267. };
  12268. for (let i = 0; i < props.length; i++) {
  12269. // static attribute
  12270. const prop = props[i];
  12271. if (prop.type === 6 /* ATTRIBUTE */) {
  12272. const { loc, name, value } = prop;
  12273. if (name === 'ref') {
  12274. hasRef = true;
  12275. }
  12276. // skip :is on <component>
  12277. if (name === 'is' && tag === 'component') {
  12278. continue;
  12279. }
  12280. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', true, value ? value.loc : loc)));
  12281. }
  12282. else {
  12283. // directives
  12284. const { name, arg, exp, loc } = prop;
  12285. const isBind = name === 'bind';
  12286. const isOn = name === 'on';
  12287. // skip v-slot - it is handled by its dedicated transform.
  12288. if (name === 'slot') {
  12289. if (!isComponent) {
  12290. context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
  12291. }
  12292. continue;
  12293. }
  12294. // skip v-once - it is handled by its dedicated transform.
  12295. if (name === 'once') {
  12296. continue;
  12297. }
  12298. // skip v-is and :is on <component>
  12299. if (name === 'is' ||
  12300. (isBind && tag === 'component' && isBindKey(arg, 'is'))) {
  12301. continue;
  12302. }
  12303. // skip v-on in SSR compilation
  12304. if (isOn && ssr) {
  12305. continue;
  12306. }
  12307. // special case for v-bind and v-on with no argument
  12308. if (!arg && (isBind || isOn)) {
  12309. hasDynamicKeys = true;
  12310. if (exp) {
  12311. if (properties.length) {
  12312. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  12313. properties = [];
  12314. }
  12315. if (isBind) {
  12316. mergeArgs.push(exp);
  12317. }
  12318. else {
  12319. // v-on="obj" -> toHandlers(obj)
  12320. mergeArgs.push({
  12321. type: 14 /* JS_CALL_EXPRESSION */,
  12322. loc,
  12323. callee: context.helper(TO_HANDLERS),
  12324. arguments: [exp]
  12325. });
  12326. }
  12327. }
  12328. else {
  12329. context.onError(createCompilerError(isBind
  12330. ? 33 /* X_V_BIND_NO_EXPRESSION */
  12331. : 34 /* X_V_ON_NO_EXPRESSION */, loc));
  12332. }
  12333. continue;
  12334. }
  12335. const directiveTransform = context.directiveTransforms[name];
  12336. if (directiveTransform) {
  12337. // has built-in directive transform.
  12338. const { props, needRuntime } = directiveTransform(prop, node, context);
  12339. !ssr && props.forEach(analyzePatchFlag);
  12340. properties.push(...props);
  12341. if (needRuntime) {
  12342. runtimeDirectives.push(prop);
  12343. if (isSymbol(needRuntime)) {
  12344. directiveImportMap.set(prop, needRuntime);
  12345. }
  12346. }
  12347. }
  12348. else {
  12349. // no built-in transform, this is a user custom directive.
  12350. runtimeDirectives.push(prop);
  12351. }
  12352. }
  12353. }
  12354. let propsExpression = undefined;
  12355. // has v-bind="object" or v-on="object", wrap with mergeProps
  12356. if (mergeArgs.length) {
  12357. if (properties.length) {
  12358. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  12359. }
  12360. if (mergeArgs.length > 1) {
  12361. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  12362. }
  12363. else {
  12364. // single v-bind with nothing else - no need for a mergeProps call
  12365. propsExpression = mergeArgs[0];
  12366. }
  12367. }
  12368. else if (properties.length) {
  12369. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  12370. }
  12371. // patchFlag analysis
  12372. if (hasDynamicKeys) {
  12373. patchFlag |= 16 /* FULL_PROPS */;
  12374. }
  12375. else {
  12376. if (hasClassBinding) {
  12377. patchFlag |= 2 /* CLASS */;
  12378. }
  12379. if (hasStyleBinding) {
  12380. patchFlag |= 4 /* STYLE */;
  12381. }
  12382. if (dynamicPropNames.length) {
  12383. patchFlag |= 8 /* PROPS */;
  12384. }
  12385. if (hasHydrationEventBinding) {
  12386. patchFlag |= 32 /* HYDRATE_EVENTS */;
  12387. }
  12388. }
  12389. if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  12390. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  12391. patchFlag |= 512 /* NEED_PATCH */;
  12392. }
  12393. return {
  12394. props: propsExpression,
  12395. directives: runtimeDirectives,
  12396. patchFlag,
  12397. dynamicPropNames
  12398. };
  12399. }
  12400. // Dedupe props in an object literal.
  12401. // Literal duplicated attributes would have been warned during the parse phase,
  12402. // however, it's possible to encounter duplicated `onXXX` handlers with different
  12403. // modifiers. We also need to merge static and dynamic class / style attributes.
  12404. // - onXXX handlers / style: merge into array
  12405. // - class: merge into single expression with concatenation
  12406. function dedupeProperties(properties) {
  12407. const knownProps = new Map();
  12408. const deduped = [];
  12409. for (let i = 0; i < properties.length; i++) {
  12410. const prop = properties[i];
  12411. // dynamic keys are always allowed
  12412. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  12413. deduped.push(prop);
  12414. continue;
  12415. }
  12416. const name = prop.key.content;
  12417. const existing = knownProps.get(name);
  12418. if (existing) {
  12419. if (name === 'style' || name === 'class' || name.startsWith('on')) {
  12420. mergeAsArray(existing, prop);
  12421. }
  12422. // unexpected duplicate, should have emitted error during parse
  12423. }
  12424. else {
  12425. knownProps.set(name, prop);
  12426. deduped.push(prop);
  12427. }
  12428. }
  12429. return deduped;
  12430. }
  12431. function mergeAsArray(existing, incoming) {
  12432. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  12433. existing.value.elements.push(incoming.value);
  12434. }
  12435. else {
  12436. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  12437. }
  12438. }
  12439. function buildDirectiveArgs(dir, context) {
  12440. const dirArgs = [];
  12441. const runtime = directiveImportMap.get(dir);
  12442. if (runtime) {
  12443. dirArgs.push(context.helperString(runtime));
  12444. }
  12445. else {
  12446. // inject statement for resolving directive
  12447. context.helper(RESOLVE_DIRECTIVE);
  12448. context.directives.add(dir.name);
  12449. dirArgs.push(toValidAssetId(dir.name, `directive`));
  12450. }
  12451. const { loc } = dir;
  12452. if (dir.exp)
  12453. dirArgs.push(dir.exp);
  12454. if (dir.arg) {
  12455. if (!dir.exp) {
  12456. dirArgs.push(`void 0`);
  12457. }
  12458. dirArgs.push(dir.arg);
  12459. }
  12460. if (Object.keys(dir.modifiers).length) {
  12461. if (!dir.arg) {
  12462. if (!dir.exp) {
  12463. dirArgs.push(`void 0`);
  12464. }
  12465. dirArgs.push(`void 0`);
  12466. }
  12467. const trueExpression = createSimpleExpression(`true`, false, loc);
  12468. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  12469. }
  12470. return createArrayExpression(dirArgs, dir.loc);
  12471. }
  12472. function stringifyDynamicPropNames(props) {
  12473. let propsNamesString = `[`;
  12474. for (let i = 0, l = props.length; i < l; i++) {
  12475. propsNamesString += JSON.stringify(props[i]);
  12476. if (i < l - 1)
  12477. propsNamesString += ', ';
  12478. }
  12479. return propsNamesString + `]`;
  12480. }
  12481. const transformSlotOutlet = (node, context) => {
  12482. if (isSlotOutlet(node)) {
  12483. const { children, loc } = node;
  12484. const { slotName, slotProps } = processSlotOutlet(node, context);
  12485. const slotArgs = [
  12486. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  12487. slotName
  12488. ];
  12489. if (slotProps) {
  12490. slotArgs.push(slotProps);
  12491. }
  12492. if (children.length) {
  12493. if (!slotProps) {
  12494. slotArgs.push(`{}`);
  12495. }
  12496. slotArgs.push(createFunctionExpression([], children, false, false, loc));
  12497. }
  12498. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  12499. }
  12500. };
  12501. function processSlotOutlet(node, context) {
  12502. let slotName = `"default"`;
  12503. let slotProps = undefined;
  12504. // check for <slot name="xxx" OR :name="xxx" />
  12505. const name = findProp(node, 'name');
  12506. if (name) {
  12507. if (name.type === 6 /* ATTRIBUTE */ && name.value) {
  12508. // static name
  12509. slotName = JSON.stringify(name.value.content);
  12510. }
  12511. else if (name.type === 7 /* DIRECTIVE */ && name.exp) {
  12512. // dynamic name
  12513. slotName = name.exp;
  12514. }
  12515. }
  12516. const propsWithoutName = name
  12517. ? node.props.filter(p => p !== name)
  12518. : node.props;
  12519. if (propsWithoutName.length > 0) {
  12520. const { props, directives } = buildProps(node, context, propsWithoutName);
  12521. slotProps = props;
  12522. if (directives.length) {
  12523. context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  12524. }
  12525. }
  12526. return {
  12527. slotName,
  12528. slotProps
  12529. };
  12530. }
  12531. const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
  12532. const transformOn = (dir, node, context, augmentor) => {
  12533. const { loc, modifiers, arg } = dir;
  12534. if (!dir.exp && !modifiers.length) {
  12535. context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
  12536. }
  12537. let eventName;
  12538. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  12539. if (arg.isStatic) {
  12540. const rawName = arg.content;
  12541. // for all event listeners, auto convert it to camelCase. See issue #2249
  12542. eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
  12543. }
  12544. else {
  12545. // #2388
  12546. eventName = createCompoundExpression([
  12547. `${context.helperString(TO_HANDLER_KEY)}(`,
  12548. arg,
  12549. `)`
  12550. ]);
  12551. }
  12552. }
  12553. else {
  12554. // already a compound expression.
  12555. eventName = arg;
  12556. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  12557. eventName.children.push(`)`);
  12558. }
  12559. // handler processing
  12560. let exp = dir.exp;
  12561. if (exp && !exp.content.trim()) {
  12562. exp = undefined;
  12563. }
  12564. let isCacheable = context.cacheHandlers && !exp;
  12565. if (exp) {
  12566. const isMemberExp = isMemberExpression(exp.content);
  12567. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  12568. const hasMultipleStatements = exp.content.includes(`;`);
  12569. {
  12570. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  12571. }
  12572. if (isInlineStatement || (isCacheable && isMemberExp)) {
  12573. // wrap inline statement in a function expression
  12574. exp = createCompoundExpression([
  12575. `${isInlineStatement ? `$event` : `(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  12576. exp,
  12577. hasMultipleStatements ? `}` : `)`
  12578. ]);
  12579. }
  12580. }
  12581. let ret = {
  12582. props: [
  12583. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  12584. ]
  12585. };
  12586. // apply extended compiler augmentor
  12587. if (augmentor) {
  12588. ret = augmentor(ret);
  12589. }
  12590. if (isCacheable) {
  12591. // cache handlers so that it's always the same handler being passed down.
  12592. // this avoids unnecessary re-renders when users use inline handlers on
  12593. // components.
  12594. ret.props[0].value = context.cache(ret.props[0].value);
  12595. }
  12596. return ret;
  12597. };
  12598. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  12599. // codegen for the entire props object. This transform here is only for v-bind
  12600. // *with* args.
  12601. const transformBind = (dir, node, context) => {
  12602. const { exp, modifiers, loc } = dir;
  12603. const arg = dir.arg;
  12604. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  12605. arg.children.unshift(`(`);
  12606. arg.children.push(`) || ""`);
  12607. }
  12608. else if (!arg.isStatic) {
  12609. arg.content = `${arg.content} || ""`;
  12610. }
  12611. // .prop is no longer necessary due to new patch behavior
  12612. // .sync is replaced by v-model:arg
  12613. if (modifiers.includes('camel')) {
  12614. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  12615. if (arg.isStatic) {
  12616. arg.content = camelize(arg.content);
  12617. }
  12618. else {
  12619. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  12620. }
  12621. }
  12622. else {
  12623. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  12624. arg.children.push(`)`);
  12625. }
  12626. }
  12627. if (!exp ||
  12628. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  12629. context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
  12630. return {
  12631. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  12632. };
  12633. }
  12634. return {
  12635. props: [createObjectProperty(arg, exp)]
  12636. };
  12637. };
  12638. // Merge adjacent text nodes and expressions into a single expression
  12639. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  12640. const transformText = (node, context) => {
  12641. if (node.type === 0 /* ROOT */ ||
  12642. node.type === 1 /* ELEMENT */ ||
  12643. node.type === 11 /* FOR */ ||
  12644. node.type === 10 /* IF_BRANCH */) {
  12645. // perform the transform on node exit so that all expressions have already
  12646. // been processed.
  12647. return () => {
  12648. const children = node.children;
  12649. let currentContainer = undefined;
  12650. let hasText = false;
  12651. for (let i = 0; i < children.length; i++) {
  12652. const child = children[i];
  12653. if (isText(child)) {
  12654. hasText = true;
  12655. for (let j = i + 1; j < children.length; j++) {
  12656. const next = children[j];
  12657. if (isText(next)) {
  12658. if (!currentContainer) {
  12659. currentContainer = children[i] = {
  12660. type: 8 /* COMPOUND_EXPRESSION */,
  12661. loc: child.loc,
  12662. children: [child]
  12663. };
  12664. }
  12665. // merge adjacent text node into current
  12666. currentContainer.children.push(` + `, next);
  12667. children.splice(j, 1);
  12668. j--;
  12669. }
  12670. else {
  12671. currentContainer = undefined;
  12672. break;
  12673. }
  12674. }
  12675. }
  12676. }
  12677. if (!hasText ||
  12678. // if this is a plain element with a single text child, leave it
  12679. // as-is since the runtime has dedicated fast path for this by directly
  12680. // setting textContent of the element.
  12681. // for component root it's always normalized anyway.
  12682. (children.length === 1 &&
  12683. (node.type === 0 /* ROOT */ ||
  12684. (node.type === 1 /* ELEMENT */ &&
  12685. node.tagType === 0 /* ELEMENT */)))) {
  12686. return;
  12687. }
  12688. // pre-convert text nodes into createTextVNode(text) calls to avoid
  12689. // runtime normalization.
  12690. for (let i = 0; i < children.length; i++) {
  12691. const child = children[i];
  12692. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  12693. const callArgs = [];
  12694. // createTextVNode defaults to single whitespace, so if it is a
  12695. // single space the code could be an empty call to save bytes.
  12696. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  12697. callArgs.push(child);
  12698. }
  12699. // mark dynamic text with flag so it gets patched inside a block
  12700. if (!context.ssr && child.type !== 2 /* TEXT */) {
  12701. callArgs.push(`${1 /* TEXT */} /* ${PatchFlagNames[1 /* TEXT */]} */`);
  12702. }
  12703. children[i] = {
  12704. type: 12 /* TEXT_CALL */,
  12705. content: child,
  12706. loc: child.loc,
  12707. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  12708. };
  12709. }
  12710. }
  12711. };
  12712. }
  12713. };
  12714. const seen = new WeakSet();
  12715. const transformOnce = (node, context) => {
  12716. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  12717. if (seen.has(node)) {
  12718. return;
  12719. }
  12720. seen.add(node);
  12721. context.helper(SET_BLOCK_TRACKING);
  12722. return () => {
  12723. const cur = context.currentNode;
  12724. if (cur.codegenNode) {
  12725. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  12726. }
  12727. };
  12728. }
  12729. };
  12730. const transformModel = (dir, node, context) => {
  12731. const { exp, arg } = dir;
  12732. if (!exp) {
  12733. context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  12734. return createTransformProps();
  12735. }
  12736. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : exp.loc.source;
  12737. if (!isMemberExpression(expString)) {
  12738. context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  12739. return createTransformProps();
  12740. }
  12741. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  12742. const eventName = arg
  12743. ? isStaticExp(arg)
  12744. ? `onUpdate:${arg.content}`
  12745. : createCompoundExpression(['"onUpdate:" + ', arg])
  12746. : `onUpdate:modelValue`;
  12747. const props = [
  12748. // modelValue: foo
  12749. createObjectProperty(propName, dir.exp),
  12750. // "onUpdate:modelValue": $event => (foo = $event)
  12751. createObjectProperty(eventName, createCompoundExpression([`$event => (`, exp, ` = $event)`]))
  12752. ];
  12753. // modelModifiers: { foo: true, "bar-baz": true }
  12754. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  12755. const modifiers = dir.modifiers
  12756. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  12757. .join(`, `);
  12758. const modifiersKey = arg
  12759. ? isStaticExp(arg)
  12760. ? `${arg.content}Modifiers`
  12761. : createCompoundExpression([arg, ' + "Modifiers"'])
  12762. : `modelModifiers`;
  12763. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, true)));
  12764. }
  12765. return createTransformProps(props);
  12766. };
  12767. function createTransformProps(props = []) {
  12768. return { props };
  12769. }
  12770. function getBaseTransformPreset(prefixIdentifiers) {
  12771. return [
  12772. [
  12773. transformOnce,
  12774. transformIf,
  12775. transformFor,
  12776. ...( [transformExpression]
  12777. ),
  12778. transformSlotOutlet,
  12779. transformElement,
  12780. trackSlotScopes,
  12781. transformText
  12782. ],
  12783. {
  12784. on: transformOn,
  12785. bind: transformBind,
  12786. model: transformModel
  12787. }
  12788. ];
  12789. }
  12790. // we name it `baseCompile` so that higher order compilers like
  12791. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  12792. function baseCompile(template, options = {}) {
  12793. const onError = options.onError || defaultOnError;
  12794. const isModuleMode = options.mode === 'module';
  12795. /* istanbul ignore if */
  12796. {
  12797. if (options.prefixIdentifiers === true) {
  12798. onError(createCompilerError(45 /* X_PREFIX_ID_NOT_SUPPORTED */));
  12799. }
  12800. else if (isModuleMode) {
  12801. onError(createCompilerError(46 /* X_MODULE_MODE_NOT_SUPPORTED */));
  12802. }
  12803. }
  12804. const prefixIdentifiers = !true ;
  12805. if ( options.cacheHandlers) {
  12806. onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  12807. }
  12808. if (options.scopeId && !isModuleMode) {
  12809. onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
  12810. }
  12811. const ast = isString(template) ? baseParse(template, options) : template;
  12812. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  12813. transform(ast, extend({}, options, {
  12814. prefixIdentifiers,
  12815. nodeTransforms: [
  12816. ...nodeTransforms,
  12817. ...(options.nodeTransforms || []) // user transforms
  12818. ],
  12819. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  12820. )
  12821. }));
  12822. return generate(ast, extend({}, options, {
  12823. prefixIdentifiers
  12824. }));
  12825. }
  12826. const noopDirectiveTransform = () => ({ props: [] });
  12827. const V_MODEL_RADIO = Symbol( `vModelRadio` );
  12828. const V_MODEL_CHECKBOX = Symbol( `vModelCheckbox` );
  12829. const V_MODEL_TEXT = Symbol( `vModelText` );
  12830. const V_MODEL_SELECT = Symbol( `vModelSelect` );
  12831. const V_MODEL_DYNAMIC = Symbol( `vModelDynamic` );
  12832. const V_ON_WITH_MODIFIERS = Symbol( `vOnModifiersGuard` );
  12833. const V_ON_WITH_KEYS = Symbol( `vOnKeysGuard` );
  12834. const V_SHOW = Symbol( `vShow` );
  12835. const TRANSITION$1 = Symbol( `Transition` );
  12836. const TRANSITION_GROUP = Symbol( `TransitionGroup` );
  12837. registerRuntimeHelpers({
  12838. [V_MODEL_RADIO]: `vModelRadio`,
  12839. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  12840. [V_MODEL_TEXT]: `vModelText`,
  12841. [V_MODEL_SELECT]: `vModelSelect`,
  12842. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  12843. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  12844. [V_ON_WITH_KEYS]: `withKeys`,
  12845. [V_SHOW]: `vShow`,
  12846. [TRANSITION$1]: `Transition`,
  12847. [TRANSITION_GROUP]: `TransitionGroup`
  12848. });
  12849. /* eslint-disable no-restricted-globals */
  12850. let decoder;
  12851. function decodeHtmlBrowser(raw) {
  12852. (decoder || (decoder = document.createElement('div'))).innerHTML = raw;
  12853. return decoder.textContent;
  12854. }
  12855. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  12856. const parserOptions = {
  12857. isVoidTag,
  12858. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  12859. isPreTag: tag => tag === 'pre',
  12860. decodeEntities: decodeHtmlBrowser ,
  12861. isBuiltInComponent: (tag) => {
  12862. if (isBuiltInType(tag, `Transition`)) {
  12863. return TRANSITION$1;
  12864. }
  12865. else if (isBuiltInType(tag, `TransitionGroup`)) {
  12866. return TRANSITION_GROUP;
  12867. }
  12868. },
  12869. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  12870. getNamespace(tag, parent) {
  12871. let ns = parent ? parent.ns : 0 /* HTML */;
  12872. if (parent && ns === 2 /* MATH_ML */) {
  12873. if (parent.tag === 'annotation-xml') {
  12874. if (tag === 'svg') {
  12875. return 1 /* SVG */;
  12876. }
  12877. if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
  12878. a.name === 'encoding' &&
  12879. a.value != null &&
  12880. (a.value.content === 'text/html' ||
  12881. a.value.content === 'application/xhtml+xml'))) {
  12882. ns = 0 /* HTML */;
  12883. }
  12884. }
  12885. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  12886. tag !== 'mglyph' &&
  12887. tag !== 'malignmark') {
  12888. ns = 0 /* HTML */;
  12889. }
  12890. }
  12891. else if (parent && ns === 1 /* SVG */) {
  12892. if (parent.tag === 'foreignObject' ||
  12893. parent.tag === 'desc' ||
  12894. parent.tag === 'title') {
  12895. ns = 0 /* HTML */;
  12896. }
  12897. }
  12898. if (ns === 0 /* HTML */) {
  12899. if (tag === 'svg') {
  12900. return 1 /* SVG */;
  12901. }
  12902. if (tag === 'math') {
  12903. return 2 /* MATH_ML */;
  12904. }
  12905. }
  12906. return ns;
  12907. },
  12908. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  12909. getTextMode({ tag, ns }) {
  12910. if (ns === 0 /* HTML */) {
  12911. if (tag === 'textarea' || tag === 'title') {
  12912. return 1 /* RCDATA */;
  12913. }
  12914. if (isRawTextContainer(tag)) {
  12915. return 2 /* RAWTEXT */;
  12916. }
  12917. }
  12918. return 0 /* DATA */;
  12919. }
  12920. };
  12921. // Parse inline CSS strings for static style attributes into an object.
  12922. // This is a NodeTransform since it works on the static `style` attribute and
  12923. // converts it into a dynamic equivalent:
  12924. // style="color: red" -> :style='{ "color": "red" }'
  12925. // It is then processed by `transformElement` and included in the generated
  12926. // props.
  12927. const transformStyle = node => {
  12928. if (node.type === 1 /* ELEMENT */) {
  12929. node.props.forEach((p, i) => {
  12930. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  12931. // replace p with an expression node
  12932. node.props[i] = {
  12933. type: 7 /* DIRECTIVE */,
  12934. name: `bind`,
  12935. arg: createSimpleExpression(`style`, true, p.loc),
  12936. exp: parseInlineCSS(p.value.content, p.loc),
  12937. modifiers: [],
  12938. loc: p.loc
  12939. };
  12940. }
  12941. });
  12942. }
  12943. };
  12944. const parseInlineCSS = (cssText, loc) => {
  12945. const normalized = parseStringStyle(cssText);
  12946. return createSimpleExpression(JSON.stringify(normalized), false, loc, true);
  12947. };
  12948. function createDOMCompilerError(code, loc) {
  12949. return createCompilerError(code, loc, DOMErrorMessages );
  12950. }
  12951. const DOMErrorMessages = {
  12952. [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  12953. [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  12954. [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  12955. [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  12956. [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  12957. [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  12958. [55 /* 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.`,
  12959. [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  12960. [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  12961. [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  12962. [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  12963. };
  12964. const transformVHtml = (dir, node, context) => {
  12965. const { exp, loc } = dir;
  12966. if (!exp) {
  12967. context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
  12968. }
  12969. if (node.children.length) {
  12970. context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
  12971. node.children.length = 0;
  12972. }
  12973. return {
  12974. props: [
  12975. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  12976. ]
  12977. };
  12978. };
  12979. const transformVText = (dir, node, context) => {
  12980. const { exp, loc } = dir;
  12981. if (!exp) {
  12982. context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
  12983. }
  12984. if (node.children.length) {
  12985. context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
  12986. node.children.length = 0;
  12987. }
  12988. return {
  12989. props: [
  12990. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  12991. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  12992. : createSimpleExpression('', true))
  12993. ]
  12994. };
  12995. };
  12996. const transformModel$1 = (dir, node, context) => {
  12997. const baseResult = transformModel(dir, node, context);
  12998. // base transform has errors OR component v-model (only need props)
  12999. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  13000. return baseResult;
  13001. }
  13002. if (dir.arg) {
  13003. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  13004. }
  13005. function checkDuplicatedValue() {
  13006. const value = findProp(node, 'value');
  13007. if (value) {
  13008. context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  13009. }
  13010. }
  13011. const { tag } = node;
  13012. const isCustomElement = context.isCustomElement(tag);
  13013. if (tag === 'input' ||
  13014. tag === 'textarea' ||
  13015. tag === 'select' ||
  13016. isCustomElement) {
  13017. let directiveToUse = V_MODEL_TEXT;
  13018. let isInvalidType = false;
  13019. if (tag === 'input' || isCustomElement) {
  13020. const type = findProp(node, `type`);
  13021. if (type) {
  13022. if (type.type === 7 /* DIRECTIVE */) {
  13023. // :type="foo"
  13024. directiveToUse = V_MODEL_DYNAMIC;
  13025. }
  13026. else if (type.value) {
  13027. switch (type.value.content) {
  13028. case 'radio':
  13029. directiveToUse = V_MODEL_RADIO;
  13030. break;
  13031. case 'checkbox':
  13032. directiveToUse = V_MODEL_CHECKBOX;
  13033. break;
  13034. case 'file':
  13035. isInvalidType = true;
  13036. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  13037. break;
  13038. default:
  13039. // text type
  13040. checkDuplicatedValue();
  13041. break;
  13042. }
  13043. }
  13044. }
  13045. else if (hasDynamicKeyVBind(node)) {
  13046. // element has bindings with dynamic keys, which can possibly contain
  13047. // "type".
  13048. directiveToUse = V_MODEL_DYNAMIC;
  13049. }
  13050. else {
  13051. // text type
  13052. checkDuplicatedValue();
  13053. }
  13054. }
  13055. else if (tag === 'select') {
  13056. directiveToUse = V_MODEL_SELECT;
  13057. }
  13058. else {
  13059. // textarea
  13060. checkDuplicatedValue();
  13061. }
  13062. // inject runtime directive
  13063. // by returning the helper symbol via needRuntime
  13064. // the import will replaced a resolveDirective call.
  13065. if (!isInvalidType) {
  13066. baseResult.needRuntime = context.helper(directiveToUse);
  13067. }
  13068. }
  13069. else {
  13070. context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  13071. }
  13072. // native vmodel doesn't need the `modelValue` props since they are also
  13073. // passed to the runtime as `binding.value`. removing it reduces code size.
  13074. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  13075. p.key.content === 'modelValue'));
  13076. return baseResult;
  13077. };
  13078. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  13079. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  13080. // event propagation management
  13081. `stop,prevent,self,` +
  13082. // system modifiers + exact
  13083. `ctrl,shift,alt,meta,exact,` +
  13084. // mouse
  13085. `middle`);
  13086. // left & right could be mouse or key modifiers based on event type
  13087. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  13088. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  13089. const resolveModifiers = (key, modifiers) => {
  13090. const keyModifiers = [];
  13091. const nonKeyModifiers = [];
  13092. const eventOptionModifiers = [];
  13093. for (let i = 0; i < modifiers.length; i++) {
  13094. const modifier = modifiers[i];
  13095. if (isEventOptionModifier(modifier)) {
  13096. // eventOptionModifiers: modifiers for addEventListener() options,
  13097. // e.g. .passive & .capture
  13098. eventOptionModifiers.push(modifier);
  13099. }
  13100. else {
  13101. // runtimeModifiers: modifiers that needs runtime guards
  13102. if (maybeKeyModifier(modifier)) {
  13103. if (isStaticExp(key)) {
  13104. if (isKeyboardEvent(key.content)) {
  13105. keyModifiers.push(modifier);
  13106. }
  13107. else {
  13108. nonKeyModifiers.push(modifier);
  13109. }
  13110. }
  13111. else {
  13112. keyModifiers.push(modifier);
  13113. nonKeyModifiers.push(modifier);
  13114. }
  13115. }
  13116. else {
  13117. if (isNonKeyModifier(modifier)) {
  13118. nonKeyModifiers.push(modifier);
  13119. }
  13120. else {
  13121. keyModifiers.push(modifier);
  13122. }
  13123. }
  13124. }
  13125. }
  13126. return {
  13127. keyModifiers,
  13128. nonKeyModifiers,
  13129. eventOptionModifiers
  13130. };
  13131. };
  13132. const transformClick = (key, event) => {
  13133. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  13134. return isStaticClick
  13135. ? createSimpleExpression(event, true)
  13136. : key.type !== 4 /* SIMPLE_EXPRESSION */
  13137. ? createCompoundExpression([
  13138. `(`,
  13139. key,
  13140. `) === "onClick" ? "${event}" : (`,
  13141. key,
  13142. `)`
  13143. ])
  13144. : key;
  13145. };
  13146. const transformOn$1 = (dir, node, context) => {
  13147. return transformOn(dir, node, context, baseResult => {
  13148. const { modifiers } = dir;
  13149. if (!modifiers.length)
  13150. return baseResult;
  13151. let { key, value: handlerExp } = baseResult.props[0];
  13152. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
  13153. // normalize click.right and click.middle since they don't actually fire
  13154. if (nonKeyModifiers.includes('right')) {
  13155. key = transformClick(key, `onContextmenu`);
  13156. }
  13157. if (nonKeyModifiers.includes('middle')) {
  13158. key = transformClick(key, `onMouseup`);
  13159. }
  13160. if (nonKeyModifiers.length) {
  13161. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  13162. handlerExp,
  13163. JSON.stringify(nonKeyModifiers)
  13164. ]);
  13165. }
  13166. if (keyModifiers.length &&
  13167. // if event name is dynamic, always wrap with keys guard
  13168. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  13169. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  13170. handlerExp,
  13171. JSON.stringify(keyModifiers)
  13172. ]);
  13173. }
  13174. if (eventOptionModifiers.length) {
  13175. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  13176. key = isStaticExp(key)
  13177. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  13178. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  13179. }
  13180. return {
  13181. props: [createObjectProperty(key, handlerExp)]
  13182. };
  13183. });
  13184. };
  13185. const transformShow = (dir, node, context) => {
  13186. const { exp, loc } = dir;
  13187. if (!exp) {
  13188. context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
  13189. }
  13190. return {
  13191. props: [],
  13192. needRuntime: context.helper(V_SHOW)
  13193. };
  13194. };
  13195. const warnTransitionChildren = (node, context) => {
  13196. if (node.type === 1 /* ELEMENT */ &&
  13197. node.tagType === 1 /* COMPONENT */) {
  13198. const component = context.isBuiltInComponent(node.tag);
  13199. if (component === TRANSITION$1) {
  13200. return () => {
  13201. if (node.children.length && hasMultipleChildren(node)) {
  13202. context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
  13203. start: node.children[0].loc.start,
  13204. end: node.children[node.children.length - 1].loc.end,
  13205. source: ''
  13206. }));
  13207. }
  13208. };
  13209. }
  13210. }
  13211. };
  13212. function hasMultipleChildren(node) {
  13213. // #1352 filter out potential comment nodes.
  13214. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
  13215. const child = children[0];
  13216. return (children.length !== 1 ||
  13217. child.type === 11 /* FOR */ ||
  13218. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  13219. }
  13220. const ignoreSideEffectTags = (node, context) => {
  13221. if (node.type === 1 /* ELEMENT */ &&
  13222. node.tagType === 0 /* ELEMENT */ &&
  13223. (node.tag === 'script' || node.tag === 'style')) {
  13224. context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  13225. context.removeNode();
  13226. }
  13227. };
  13228. const DOMNodeTransforms = [
  13229. transformStyle,
  13230. ...( [warnTransitionChildren] )
  13231. ];
  13232. const DOMDirectiveTransforms = {
  13233. cloak: noopDirectiveTransform,
  13234. html: transformVHtml,
  13235. text: transformVText,
  13236. model: transformModel$1,
  13237. on: transformOn$1,
  13238. show: transformShow
  13239. };
  13240. function compile$1(template, options = {}) {
  13241. return baseCompile(template, extend({}, parserOptions, options, {
  13242. nodeTransforms: [
  13243. // ignore <script> and <tag>
  13244. // this is not put inside DOMNodeTransforms because that list is used
  13245. // by compiler-ssr to generate vnode fallback branches
  13246. ignoreSideEffectTags,
  13247. ...DOMNodeTransforms,
  13248. ...(options.nodeTransforms || [])
  13249. ],
  13250. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  13251. transformHoist: null
  13252. }));
  13253. }
  13254. // This entry is the "full-build" that includes both the runtime
  13255. initDev();
  13256. const compileCache = Object.create(null);
  13257. function compileToFunction(template, options) {
  13258. if (!isString(template)) {
  13259. if (template.nodeType) {
  13260. template = template.innerHTML;
  13261. }
  13262. else {
  13263. warn(`invalid template option: `, template);
  13264. return NOOP;
  13265. }
  13266. }
  13267. const key = template;
  13268. const cached = compileCache[key];
  13269. if (cached) {
  13270. return cached;
  13271. }
  13272. if (template[0] === '#') {
  13273. const el = document.querySelector(template);
  13274. if ( !el) {
  13275. warn(`Template element not found or is empty: ${template}`);
  13276. }
  13277. // __UNSAFE__
  13278. // Reason: potential execution of JS expressions in in-DOM template.
  13279. // The user must make sure the in-DOM template is trusted. If it's rendered
  13280. // by the server, the template should not contain any user data.
  13281. template = el ? el.innerHTML : ``;
  13282. }
  13283. const { code } = compile$1(template, extend({
  13284. hoistStatic: true,
  13285. onError(err) {
  13286. {
  13287. const message = `Template compilation error: ${err.message}`;
  13288. const codeFrame = err.loc &&
  13289. generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
  13290. warn(codeFrame ? `${message}\n${codeFrame}` : message);
  13291. }
  13292. }
  13293. }, options));
  13294. // The wildcard import results in a huge object with every export
  13295. // with keys that cannot be mangled, and can be quite heavy size-wise.
  13296. // In the global build we know `Vue` is available globally so we can avoid
  13297. // the wildcard object.
  13298. const render = ( new Function('Vue', code)(runtimeDom));
  13299. render._rc = true;
  13300. return (compileCache[key] = render);
  13301. }
  13302. registerRuntimeCompiler(compileToFunction);
  13303. export { BaseTransition, Comment, Fragment, KeepAlive, Static, Suspense, Teleport, Text, Transition, TransitionGroup, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compileToFunction as compile, computed$1 as computed, createApp, createBlock, createCommentVNode, createHydrationRenderer, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, devtools, getCurrentInstance, getTransitionRawChildren, h, handleError, hydrate, initCustomFormatter, inject, isProxy, isReactive, isReadonly, isRef, isVNode, markRaw, mergeProps, nextTick, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onUnmounted, onUpdated, openBlock, popScopeId, provide, proxyRefs, pushScopeId, queuePostFlushCb, reactive, readonly, ref, registerRuntimeCompiler, render, renderList, renderSlot, resolveComponent, resolveDirective, resolveDynamicComponent, resolveTransitionHooks, setBlockTracking, setDevtoolsHook, setTransitionHooks, shallowReactive, shallowReadonly, shallowRef, ssrContextKey, ssrUtils, toDisplayString, toHandlerKey, toHandlers, toRaw, toRef, toRefs, transformVNodeArgs, triggerRef, unref, useCssModule, useCssVars, useSSRContext, useTransitionState, vModelCheckbox, vModelDynamic, vModelRadio, vModelSelect, vModelText, vShow, version, warn, watch, watchEffect, withCtx, withDirectives, withKeys, withModifiers, withScopeId };