vue.esm-browser.js 577 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853
  1. /**
  2. * Make a map and return a function for checking if a key
  3. * is in that map.
  4. * IMPORTANT: all calls of this function must be prefixed with
  5. * \/\*#\_\_PURE\_\_\*\/
  6. * So that rollup can tree-shake them if necessary.
  7. */
  8. function makeMap(str, expectsLowerCase) {
  9. const map = Object.create(null);
  10. const list = str.split(',');
  11. for (let i = 0; i < list.length; i++) {
  12. map[list[i]] = true;
  13. }
  14. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  15. }
  16. /**
  17. * dev only flag -> name mapping
  18. */
  19. const PatchFlagNames = {
  20. [1 /* TEXT */]: `TEXT`,
  21. [2 /* CLASS */]: `CLASS`,
  22. [4 /* STYLE */]: `STYLE`,
  23. [8 /* PROPS */]: `PROPS`,
  24. [16 /* FULL_PROPS */]: `FULL_PROPS`,
  25. [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  26. [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  27. [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  28. [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  29. [512 /* NEED_PATCH */]: `NEED_PATCH`,
  30. [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  31. [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
  32. [-1 /* HOISTED */]: `HOISTED`,
  33. [-2 /* BAIL */]: `BAIL`
  34. };
  35. /**
  36. * Dev only
  37. */
  38. const slotFlagsText = {
  39. [1 /* STABLE */]: 'STABLE',
  40. [2 /* DYNAMIC */]: 'DYNAMIC',
  41. [3 /* FORWARDED */]: 'FORWARDED'
  42. };
  43. const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  44. 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  45. 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
  46. const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
  47. const range = 2;
  48. function generateCodeFrame(source, start = 0, end = source.length) {
  49. // Split the content into individual lines but capture the newline sequence
  50. // that separated each line. This is important because the actual sequence is
  51. // needed to properly take into account the full line length for offset
  52. // comparison
  53. let lines = source.split(/(\r?\n)/);
  54. // Separate the lines and newline sequences into separate arrays for easier referencing
  55. const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
  56. lines = lines.filter((_, idx) => idx % 2 === 0);
  57. let count = 0;
  58. const res = [];
  59. for (let i = 0; i < lines.length; i++) {
  60. count +=
  61. lines[i].length +
  62. ((newlineSequences[i] && newlineSequences[i].length) || 0);
  63. if (count >= start) {
  64. for (let j = i - range; j <= i + range || end > count; j++) {
  65. if (j < 0 || j >= lines.length)
  66. continue;
  67. const line = j + 1;
  68. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  69. const lineLength = lines[j].length;
  70. const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
  71. if (j === i) {
  72. // push underline
  73. const pad = start - (count - (lineLength + newLineSeqLength));
  74. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  75. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  76. }
  77. else if (j > i) {
  78. if (end > count) {
  79. const length = Math.max(Math.min(end - count, lineLength), 1);
  80. res.push(` | ` + '^'.repeat(length));
  81. }
  82. count += lineLength + newLineSeqLength;
  83. }
  84. }
  85. break;
  86. }
  87. }
  88. return res.join('\n');
  89. }
  90. /**
  91. * On the client we only need to offer special cases for boolean attributes that
  92. * have different names from their corresponding dom properties:
  93. * - itemscope -> N/A
  94. * - allowfullscreen -> allowFullscreen
  95. * - formnovalidate -> formNoValidate
  96. * - ismap -> isMap
  97. * - nomodule -> noModule
  98. * - novalidate -> noValidate
  99. * - readonly -> readOnly
  100. */
  101. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  102. const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
  103. /**
  104. * Boolean attributes should be included if the value is truthy or ''.
  105. * e.g. `<select multiple>` compiles to `{ multiple: '' }`
  106. */
  107. function includeBooleanAttr(value) {
  108. return !!value || value === '';
  109. }
  110. function normalizeStyle(value) {
  111. if (isArray(value)) {
  112. const res = {};
  113. for (let i = 0; i < value.length; i++) {
  114. const item = value[i];
  115. const normalized = isString(item)
  116. ? parseStringStyle(item)
  117. : normalizeStyle(item);
  118. if (normalized) {
  119. for (const key in normalized) {
  120. res[key] = normalized[key];
  121. }
  122. }
  123. }
  124. return res;
  125. }
  126. else if (isString(value)) {
  127. return value;
  128. }
  129. else if (isObject(value)) {
  130. return value;
  131. }
  132. }
  133. const listDelimiterRE = /;(?![^(]*\))/g;
  134. const propertyDelimiterRE = /:(.+)/;
  135. function parseStringStyle(cssText) {
  136. const ret = {};
  137. cssText.split(listDelimiterRE).forEach(item => {
  138. if (item) {
  139. const tmp = item.split(propertyDelimiterRE);
  140. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  141. }
  142. });
  143. return ret;
  144. }
  145. function normalizeClass(value) {
  146. let res = '';
  147. if (isString(value)) {
  148. res = value;
  149. }
  150. else if (isArray(value)) {
  151. for (let i = 0; i < value.length; i++) {
  152. const normalized = normalizeClass(value[i]);
  153. if (normalized) {
  154. res += normalized + ' ';
  155. }
  156. }
  157. }
  158. else if (isObject(value)) {
  159. for (const name in value) {
  160. if (value[name]) {
  161. res += name + ' ';
  162. }
  163. }
  164. }
  165. return res.trim();
  166. }
  167. function normalizeProps(props) {
  168. if (!props)
  169. return null;
  170. let { class: klass, style } = props;
  171. if (klass && !isString(klass)) {
  172. props.class = normalizeClass(klass);
  173. }
  174. if (style) {
  175. props.style = normalizeStyle(style);
  176. }
  177. return props;
  178. }
  179. // These tag configs are shared between compiler-dom and runtime-dom, so they
  180. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  181. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  182. 'header,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,' +
  183. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  184. 'data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,' +
  185. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  186. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  187. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  188. 'option,output,progress,select,textarea,details,dialog,menu,' +
  189. 'summary,template,blockquote,iframe,tfoot';
  190. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  191. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  192. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  193. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  194. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  195. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  196. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  197. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  198. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  199. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  200. 'text,textPath,title,tspan,unknown,use,view';
  201. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  202. /**
  203. * Compiler only.
  204. * Do NOT use in runtime code paths unless behind `true` flag.
  205. */
  206. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  207. /**
  208. * Compiler only.
  209. * Do NOT use in runtime code paths unless behind `true` flag.
  210. */
  211. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  212. /**
  213. * Compiler only.
  214. * Do NOT use in runtime code paths unless behind `true` flag.
  215. */
  216. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  217. function looseCompareArrays(a, b) {
  218. if (a.length !== b.length)
  219. return false;
  220. let equal = true;
  221. for (let i = 0; equal && i < a.length; i++) {
  222. equal = looseEqual(a[i], b[i]);
  223. }
  224. return equal;
  225. }
  226. function looseEqual(a, b) {
  227. if (a === b)
  228. return true;
  229. let aValidType = isDate(a);
  230. let bValidType = isDate(b);
  231. if (aValidType || bValidType) {
  232. return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  233. }
  234. aValidType = isArray(a);
  235. bValidType = isArray(b);
  236. if (aValidType || bValidType) {
  237. return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  238. }
  239. aValidType = isObject(a);
  240. bValidType = isObject(b);
  241. if (aValidType || bValidType) {
  242. /* istanbul ignore if: this if will probably never be called */
  243. if (!aValidType || !bValidType) {
  244. return false;
  245. }
  246. const aKeysCount = Object.keys(a).length;
  247. const bKeysCount = Object.keys(b).length;
  248. if (aKeysCount !== bKeysCount) {
  249. return false;
  250. }
  251. for (const key in a) {
  252. const aHasKey = a.hasOwnProperty(key);
  253. const bHasKey = b.hasOwnProperty(key);
  254. if ((aHasKey && !bHasKey) ||
  255. (!aHasKey && bHasKey) ||
  256. !looseEqual(a[key], b[key])) {
  257. return false;
  258. }
  259. }
  260. }
  261. return String(a) === String(b);
  262. }
  263. function looseIndexOf(arr, val) {
  264. return arr.findIndex(item => looseEqual(item, val));
  265. }
  266. /**
  267. * For converting {{ interpolation }} values to displayed strings.
  268. * @private
  269. */
  270. const toDisplayString = (val) => {
  271. return isString(val)
  272. ? val
  273. : val == null
  274. ? ''
  275. : isArray(val) ||
  276. (isObject(val) &&
  277. (val.toString === objectToString || !isFunction(val.toString)))
  278. ? JSON.stringify(val, replacer, 2)
  279. : String(val);
  280. };
  281. const replacer = (_key, val) => {
  282. // can't use isRef here since @vue/shared has no deps
  283. if (val && val.__v_isRef) {
  284. return replacer(_key, val.value);
  285. }
  286. else if (isMap(val)) {
  287. return {
  288. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  289. entries[`${key} =>`] = val;
  290. return entries;
  291. }, {})
  292. };
  293. }
  294. else if (isSet(val)) {
  295. return {
  296. [`Set(${val.size})`]: [...val.values()]
  297. };
  298. }
  299. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  300. return String(val);
  301. }
  302. return val;
  303. };
  304. const EMPTY_OBJ = Object.freeze({})
  305. ;
  306. const EMPTY_ARR = Object.freeze([]) ;
  307. const NOOP = () => { };
  308. /**
  309. * Always return false.
  310. */
  311. const NO = () => false;
  312. const onRE = /^on[^a-z]/;
  313. const isOn = (key) => onRE.test(key);
  314. const isModelListener = (key) => key.startsWith('onUpdate:');
  315. const extend = Object.assign;
  316. const remove = (arr, el) => {
  317. const i = arr.indexOf(el);
  318. if (i > -1) {
  319. arr.splice(i, 1);
  320. }
  321. };
  322. const hasOwnProperty = Object.prototype.hasOwnProperty;
  323. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  324. const isArray = Array.isArray;
  325. const isMap = (val) => toTypeString(val) === '[object Map]';
  326. const isSet = (val) => toTypeString(val) === '[object Set]';
  327. const isDate = (val) => val instanceof Date;
  328. const isFunction = (val) => typeof val === 'function';
  329. const isString = (val) => typeof val === 'string';
  330. const isSymbol = (val) => typeof val === 'symbol';
  331. const isObject = (val) => val !== null && typeof val === 'object';
  332. const isPromise = (val) => {
  333. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  334. };
  335. const objectToString = Object.prototype.toString;
  336. const toTypeString = (value) => objectToString.call(value);
  337. const toRawType = (value) => {
  338. // extract "RawType" from strings like "[object RawType]"
  339. return toTypeString(value).slice(8, -1);
  340. };
  341. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  342. const isIntegerKey = (key) => isString(key) &&
  343. key !== 'NaN' &&
  344. key[0] !== '-' &&
  345. '' + parseInt(key, 10) === key;
  346. const isReservedProp = /*#__PURE__*/ makeMap(
  347. // the leading comma is intentional so empty string "" is also included
  348. ',key,ref,ref_for,ref_key,' +
  349. 'onVnodeBeforeMount,onVnodeMounted,' +
  350. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  351. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  352. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
  353. const cacheStringFunction = (fn) => {
  354. const cache = Object.create(null);
  355. return ((str) => {
  356. const hit = cache[str];
  357. return hit || (cache[str] = fn(str));
  358. });
  359. };
  360. const camelizeRE = /-(\w)/g;
  361. /**
  362. * @private
  363. */
  364. const camelize = cacheStringFunction((str) => {
  365. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  366. });
  367. const hyphenateRE = /\B([A-Z])/g;
  368. /**
  369. * @private
  370. */
  371. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  372. /**
  373. * @private
  374. */
  375. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  376. /**
  377. * @private
  378. */
  379. const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
  380. // compare whether a value has changed, accounting for NaN.
  381. const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
  382. const invokeArrayFns = (fns, arg) => {
  383. for (let i = 0; i < fns.length; i++) {
  384. fns[i](arg);
  385. }
  386. };
  387. const def = (obj, key, value) => {
  388. Object.defineProperty(obj, key, {
  389. configurable: true,
  390. enumerable: false,
  391. value
  392. });
  393. };
  394. const toNumber = (val) => {
  395. const n = parseFloat(val);
  396. return isNaN(n) ? val : n;
  397. };
  398. let _globalThis;
  399. const getGlobalThis = () => {
  400. return (_globalThis ||
  401. (_globalThis =
  402. typeof globalThis !== 'undefined'
  403. ? globalThis
  404. : typeof self !== 'undefined'
  405. ? self
  406. : typeof window !== 'undefined'
  407. ? window
  408. : typeof global !== 'undefined'
  409. ? global
  410. : {}));
  411. };
  412. function warn(msg, ...args) {
  413. console.warn(`[Vue warn] ${msg}`, ...args);
  414. }
  415. let activeEffectScope;
  416. class EffectScope {
  417. constructor(detached = false) {
  418. /**
  419. * @internal
  420. */
  421. this.active = true;
  422. /**
  423. * @internal
  424. */
  425. this.effects = [];
  426. /**
  427. * @internal
  428. */
  429. this.cleanups = [];
  430. if (!detached && activeEffectScope) {
  431. this.parent = activeEffectScope;
  432. this.index =
  433. (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
  434. }
  435. }
  436. run(fn) {
  437. if (this.active) {
  438. const currentEffectScope = activeEffectScope;
  439. try {
  440. activeEffectScope = this;
  441. return fn();
  442. }
  443. finally {
  444. activeEffectScope = currentEffectScope;
  445. }
  446. }
  447. else {
  448. warn(`cannot run an inactive effect scope.`);
  449. }
  450. }
  451. /**
  452. * This should only be called on non-detached scopes
  453. * @internal
  454. */
  455. on() {
  456. activeEffectScope = this;
  457. }
  458. /**
  459. * This should only be called on non-detached scopes
  460. * @internal
  461. */
  462. off() {
  463. activeEffectScope = this.parent;
  464. }
  465. stop(fromParent) {
  466. if (this.active) {
  467. let i, l;
  468. for (i = 0, l = this.effects.length; i < l; i++) {
  469. this.effects[i].stop();
  470. }
  471. for (i = 0, l = this.cleanups.length; i < l; i++) {
  472. this.cleanups[i]();
  473. }
  474. if (this.scopes) {
  475. for (i = 0, l = this.scopes.length; i < l; i++) {
  476. this.scopes[i].stop(true);
  477. }
  478. }
  479. // nested scope, dereference from parent to avoid memory leaks
  480. if (this.parent && !fromParent) {
  481. // optimized O(1) removal
  482. const last = this.parent.scopes.pop();
  483. if (last && last !== this) {
  484. this.parent.scopes[this.index] = last;
  485. last.index = this.index;
  486. }
  487. }
  488. this.active = false;
  489. }
  490. }
  491. }
  492. function effectScope(detached) {
  493. return new EffectScope(detached);
  494. }
  495. function recordEffectScope(effect, scope = activeEffectScope) {
  496. if (scope && scope.active) {
  497. scope.effects.push(effect);
  498. }
  499. }
  500. function getCurrentScope() {
  501. return activeEffectScope;
  502. }
  503. function onScopeDispose(fn) {
  504. if (activeEffectScope) {
  505. activeEffectScope.cleanups.push(fn);
  506. }
  507. else {
  508. warn(`onScopeDispose() is called when there is no active effect scope` +
  509. ` to be associated with.`);
  510. }
  511. }
  512. const createDep = (effects) => {
  513. const dep = new Set(effects);
  514. dep.w = 0;
  515. dep.n = 0;
  516. return dep;
  517. };
  518. const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
  519. const newTracked = (dep) => (dep.n & trackOpBit) > 0;
  520. const initDepMarkers = ({ deps }) => {
  521. if (deps.length) {
  522. for (let i = 0; i < deps.length; i++) {
  523. deps[i].w |= trackOpBit; // set was tracked
  524. }
  525. }
  526. };
  527. const finalizeDepMarkers = (effect) => {
  528. const { deps } = effect;
  529. if (deps.length) {
  530. let ptr = 0;
  531. for (let i = 0; i < deps.length; i++) {
  532. const dep = deps[i];
  533. if (wasTracked(dep) && !newTracked(dep)) {
  534. dep.delete(effect);
  535. }
  536. else {
  537. deps[ptr++] = dep;
  538. }
  539. // clear bits
  540. dep.w &= ~trackOpBit;
  541. dep.n &= ~trackOpBit;
  542. }
  543. deps.length = ptr;
  544. }
  545. };
  546. const targetMap = new WeakMap();
  547. // The number of effects currently being tracked recursively.
  548. let effectTrackDepth = 0;
  549. let trackOpBit = 1;
  550. /**
  551. * The bitwise track markers support at most 30 levels of recursion.
  552. * This value is chosen to enable modern JS engines to use a SMI on all platforms.
  553. * When recursion depth is greater, fall back to using a full cleanup.
  554. */
  555. const maxMarkerBits = 30;
  556. let activeEffect;
  557. const ITERATE_KEY = Symbol('iterate' );
  558. const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
  559. class ReactiveEffect {
  560. constructor(fn, scheduler = null, scope) {
  561. this.fn = fn;
  562. this.scheduler = scheduler;
  563. this.active = true;
  564. this.deps = [];
  565. this.parent = undefined;
  566. recordEffectScope(this, scope);
  567. }
  568. run() {
  569. if (!this.active) {
  570. return this.fn();
  571. }
  572. let parent = activeEffect;
  573. let lastShouldTrack = shouldTrack;
  574. while (parent) {
  575. if (parent === this) {
  576. return;
  577. }
  578. parent = parent.parent;
  579. }
  580. try {
  581. this.parent = activeEffect;
  582. activeEffect = this;
  583. shouldTrack = true;
  584. trackOpBit = 1 << ++effectTrackDepth;
  585. if (effectTrackDepth <= maxMarkerBits) {
  586. initDepMarkers(this);
  587. }
  588. else {
  589. cleanupEffect(this);
  590. }
  591. return this.fn();
  592. }
  593. finally {
  594. if (effectTrackDepth <= maxMarkerBits) {
  595. finalizeDepMarkers(this);
  596. }
  597. trackOpBit = 1 << --effectTrackDepth;
  598. activeEffect = this.parent;
  599. shouldTrack = lastShouldTrack;
  600. this.parent = undefined;
  601. if (this.deferStop) {
  602. this.stop();
  603. }
  604. }
  605. }
  606. stop() {
  607. // stopped while running itself - defer the cleanup
  608. if (activeEffect === this) {
  609. this.deferStop = true;
  610. }
  611. else if (this.active) {
  612. cleanupEffect(this);
  613. if (this.onStop) {
  614. this.onStop();
  615. }
  616. this.active = false;
  617. }
  618. }
  619. }
  620. function cleanupEffect(effect) {
  621. const { deps } = effect;
  622. if (deps.length) {
  623. for (let i = 0; i < deps.length; i++) {
  624. deps[i].delete(effect);
  625. }
  626. deps.length = 0;
  627. }
  628. }
  629. function effect(fn, options) {
  630. if (fn.effect) {
  631. fn = fn.effect.fn;
  632. }
  633. const _effect = new ReactiveEffect(fn);
  634. if (options) {
  635. extend(_effect, options);
  636. if (options.scope)
  637. recordEffectScope(_effect, options.scope);
  638. }
  639. if (!options || !options.lazy) {
  640. _effect.run();
  641. }
  642. const runner = _effect.run.bind(_effect);
  643. runner.effect = _effect;
  644. return runner;
  645. }
  646. function stop(runner) {
  647. runner.effect.stop();
  648. }
  649. let shouldTrack = true;
  650. const trackStack = [];
  651. function pauseTracking() {
  652. trackStack.push(shouldTrack);
  653. shouldTrack = false;
  654. }
  655. function resetTracking() {
  656. const last = trackStack.pop();
  657. shouldTrack = last === undefined ? true : last;
  658. }
  659. function track(target, type, key) {
  660. if (shouldTrack && activeEffect) {
  661. let depsMap = targetMap.get(target);
  662. if (!depsMap) {
  663. targetMap.set(target, (depsMap = new Map()));
  664. }
  665. let dep = depsMap.get(key);
  666. if (!dep) {
  667. depsMap.set(key, (dep = createDep()));
  668. }
  669. const eventInfo = { effect: activeEffect, target, type, key }
  670. ;
  671. trackEffects(dep, eventInfo);
  672. }
  673. }
  674. function trackEffects(dep, debuggerEventExtraInfo) {
  675. let shouldTrack = false;
  676. if (effectTrackDepth <= maxMarkerBits) {
  677. if (!newTracked(dep)) {
  678. dep.n |= trackOpBit; // set newly tracked
  679. shouldTrack = !wasTracked(dep);
  680. }
  681. }
  682. else {
  683. // Full cleanup mode.
  684. shouldTrack = !dep.has(activeEffect);
  685. }
  686. if (shouldTrack) {
  687. dep.add(activeEffect);
  688. activeEffect.deps.push(dep);
  689. if (activeEffect.onTrack) {
  690. activeEffect.onTrack(Object.assign({ effect: activeEffect }, debuggerEventExtraInfo));
  691. }
  692. }
  693. }
  694. function trigger(target, type, key, newValue, oldValue, oldTarget) {
  695. const depsMap = targetMap.get(target);
  696. if (!depsMap) {
  697. // never been tracked
  698. return;
  699. }
  700. let deps = [];
  701. if (type === "clear" /* CLEAR */) {
  702. // collection being cleared
  703. // trigger all effects for target
  704. deps = [...depsMap.values()];
  705. }
  706. else if (key === 'length' && isArray(target)) {
  707. depsMap.forEach((dep, key) => {
  708. if (key === 'length' || key >= newValue) {
  709. deps.push(dep);
  710. }
  711. });
  712. }
  713. else {
  714. // schedule runs for SET | ADD | DELETE
  715. if (key !== void 0) {
  716. deps.push(depsMap.get(key));
  717. }
  718. // also run for iteration key on ADD | DELETE | Map.SET
  719. switch (type) {
  720. case "add" /* ADD */:
  721. if (!isArray(target)) {
  722. deps.push(depsMap.get(ITERATE_KEY));
  723. if (isMap(target)) {
  724. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  725. }
  726. }
  727. else if (isIntegerKey(key)) {
  728. // new index added to array -> length changes
  729. deps.push(depsMap.get('length'));
  730. }
  731. break;
  732. case "delete" /* DELETE */:
  733. if (!isArray(target)) {
  734. deps.push(depsMap.get(ITERATE_KEY));
  735. if (isMap(target)) {
  736. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  737. }
  738. }
  739. break;
  740. case "set" /* SET */:
  741. if (isMap(target)) {
  742. deps.push(depsMap.get(ITERATE_KEY));
  743. }
  744. break;
  745. }
  746. }
  747. const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
  748. ;
  749. if (deps.length === 1) {
  750. if (deps[0]) {
  751. {
  752. triggerEffects(deps[0], eventInfo);
  753. }
  754. }
  755. }
  756. else {
  757. const effects = [];
  758. for (const dep of deps) {
  759. if (dep) {
  760. effects.push(...dep);
  761. }
  762. }
  763. {
  764. triggerEffects(createDep(effects), eventInfo);
  765. }
  766. }
  767. }
  768. function triggerEffects(dep, debuggerEventExtraInfo) {
  769. // spread into array for stabilization
  770. for (const effect of isArray(dep) ? dep : [...dep]) {
  771. if (effect !== activeEffect || effect.allowRecurse) {
  772. if (effect.onTrigger) {
  773. effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
  774. }
  775. if (effect.scheduler) {
  776. effect.scheduler();
  777. }
  778. else {
  779. effect.run();
  780. }
  781. }
  782. }
  783. }
  784. const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
  785. const builtInSymbols = new Set(
  786. /*#__PURE__*/
  787. Object.getOwnPropertyNames(Symbol)
  788. .map(key => Symbol[key])
  789. .filter(isSymbol));
  790. const get = /*#__PURE__*/ createGetter();
  791. const shallowGet = /*#__PURE__*/ createGetter(false, true);
  792. const readonlyGet = /*#__PURE__*/ createGetter(true);
  793. const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
  794. const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
  795. function createArrayInstrumentations() {
  796. const instrumentations = {};
  797. ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
  798. instrumentations[key] = function (...args) {
  799. const arr = toRaw(this);
  800. for (let i = 0, l = this.length; i < l; i++) {
  801. track(arr, "get" /* GET */, i + '');
  802. }
  803. // we run the method using the original args first (which may be reactive)
  804. const res = arr[key](...args);
  805. if (res === -1 || res === false) {
  806. // if that didn't work, run it again using raw values.
  807. return arr[key](...args.map(toRaw));
  808. }
  809. else {
  810. return res;
  811. }
  812. };
  813. });
  814. ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
  815. instrumentations[key] = function (...args) {
  816. pauseTracking();
  817. const res = toRaw(this)[key].apply(this, args);
  818. resetTracking();
  819. return res;
  820. };
  821. });
  822. return instrumentations;
  823. }
  824. function createGetter(isReadonly = false, shallow = false) {
  825. return function get(target, key, receiver) {
  826. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  827. return !isReadonly;
  828. }
  829. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  830. return isReadonly;
  831. }
  832. else if (key === "__v_isShallow" /* IS_SHALLOW */) {
  833. return shallow;
  834. }
  835. else if (key === "__v_raw" /* RAW */ &&
  836. receiver ===
  837. (isReadonly
  838. ? shallow
  839. ? shallowReadonlyMap
  840. : readonlyMap
  841. : shallow
  842. ? shallowReactiveMap
  843. : reactiveMap).get(target)) {
  844. return target;
  845. }
  846. const targetIsArray = isArray(target);
  847. if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
  848. return Reflect.get(arrayInstrumentations, key, receiver);
  849. }
  850. const res = Reflect.get(target, key, receiver);
  851. if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
  852. return res;
  853. }
  854. if (!isReadonly) {
  855. track(target, "get" /* GET */, key);
  856. }
  857. if (shallow) {
  858. return res;
  859. }
  860. if (isRef(res)) {
  861. // ref unwrapping - does not apply for Array + integer key.
  862. const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
  863. return shouldUnwrap ? res.value : res;
  864. }
  865. if (isObject(res)) {
  866. // Convert returned value into a proxy as well. we do the isObject check
  867. // here to avoid invalid value warning. Also need to lazy access readonly
  868. // and reactive here to avoid circular dependency.
  869. return isReadonly ? readonly(res) : reactive(res);
  870. }
  871. return res;
  872. };
  873. }
  874. const set = /*#__PURE__*/ createSetter();
  875. const shallowSet = /*#__PURE__*/ createSetter(true);
  876. function createSetter(shallow = false) {
  877. return function set(target, key, value, receiver) {
  878. let oldValue = target[key];
  879. if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) {
  880. return false;
  881. }
  882. if (!shallow && !isReadonly(value)) {
  883. if (!isShallow(value)) {
  884. value = toRaw(value);
  885. oldValue = toRaw(oldValue);
  886. }
  887. if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
  888. oldValue.value = value;
  889. return true;
  890. }
  891. }
  892. const hadKey = isArray(target) && isIntegerKey(key)
  893. ? Number(key) < target.length
  894. : hasOwn(target, key);
  895. const result = Reflect.set(target, key, value, receiver);
  896. // don't trigger if target is something up in the prototype chain of original
  897. if (target === toRaw(receiver)) {
  898. if (!hadKey) {
  899. trigger(target, "add" /* ADD */, key, value);
  900. }
  901. else if (hasChanged(value, oldValue)) {
  902. trigger(target, "set" /* SET */, key, value, oldValue);
  903. }
  904. }
  905. return result;
  906. };
  907. }
  908. function deleteProperty(target, key) {
  909. const hadKey = hasOwn(target, key);
  910. const oldValue = target[key];
  911. const result = Reflect.deleteProperty(target, key);
  912. if (result && hadKey) {
  913. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  914. }
  915. return result;
  916. }
  917. function has(target, key) {
  918. const result = Reflect.has(target, key);
  919. if (!isSymbol(key) || !builtInSymbols.has(key)) {
  920. track(target, "has" /* HAS */, key);
  921. }
  922. return result;
  923. }
  924. function ownKeys(target) {
  925. track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
  926. return Reflect.ownKeys(target);
  927. }
  928. const mutableHandlers = {
  929. get,
  930. set,
  931. deleteProperty,
  932. has,
  933. ownKeys
  934. };
  935. const readonlyHandlers = {
  936. get: readonlyGet,
  937. set(target, key) {
  938. {
  939. warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
  940. }
  941. return true;
  942. },
  943. deleteProperty(target, key) {
  944. {
  945. warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
  946. }
  947. return true;
  948. }
  949. };
  950. const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
  951. get: shallowGet,
  952. set: shallowSet
  953. });
  954. // Props handlers are special in the sense that it should not unwrap top-level
  955. // refs (in order to allow refs to be explicitly passed down), but should
  956. // retain the reactivity of the normal readonly object.
  957. const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
  958. get: shallowReadonlyGet
  959. });
  960. const toShallow = (value) => value;
  961. const getProto = (v) => Reflect.getPrototypeOf(v);
  962. function get$1(target, key, isReadonly = false, isShallow = false) {
  963. // #1772: readonly(reactive(Map)) should return readonly + reactive version
  964. // of the value
  965. target = target["__v_raw" /* RAW */];
  966. const rawTarget = toRaw(target);
  967. const rawKey = toRaw(key);
  968. if (key !== rawKey) {
  969. !isReadonly && track(rawTarget, "get" /* GET */, key);
  970. }
  971. !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
  972. const { has } = getProto(rawTarget);
  973. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  974. if (has.call(rawTarget, key)) {
  975. return wrap(target.get(key));
  976. }
  977. else if (has.call(rawTarget, rawKey)) {
  978. return wrap(target.get(rawKey));
  979. }
  980. else if (target !== rawTarget) {
  981. // #3602 readonly(reactive(Map))
  982. // ensure that the nested reactive `Map` can do tracking for itself
  983. target.get(key);
  984. }
  985. }
  986. function has$1(key, isReadonly = false) {
  987. const target = this["__v_raw" /* RAW */];
  988. const rawTarget = toRaw(target);
  989. const rawKey = toRaw(key);
  990. if (key !== rawKey) {
  991. !isReadonly && track(rawTarget, "has" /* HAS */, key);
  992. }
  993. !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
  994. return key === rawKey
  995. ? target.has(key)
  996. : target.has(key) || target.has(rawKey);
  997. }
  998. function size(target, isReadonly = false) {
  999. target = target["__v_raw" /* RAW */];
  1000. !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
  1001. return Reflect.get(target, 'size', target);
  1002. }
  1003. function add(value) {
  1004. value = toRaw(value);
  1005. const target = toRaw(this);
  1006. const proto = getProto(target);
  1007. const hadKey = proto.has.call(target, value);
  1008. if (!hadKey) {
  1009. target.add(value);
  1010. trigger(target, "add" /* ADD */, value, value);
  1011. }
  1012. return this;
  1013. }
  1014. function set$1(key, value) {
  1015. value = toRaw(value);
  1016. const target = toRaw(this);
  1017. const { has, get } = getProto(target);
  1018. let hadKey = has.call(target, key);
  1019. if (!hadKey) {
  1020. key = toRaw(key);
  1021. hadKey = has.call(target, key);
  1022. }
  1023. else {
  1024. checkIdentityKeys(target, has, key);
  1025. }
  1026. const oldValue = get.call(target, key);
  1027. target.set(key, value);
  1028. if (!hadKey) {
  1029. trigger(target, "add" /* ADD */, key, value);
  1030. }
  1031. else if (hasChanged(value, oldValue)) {
  1032. trigger(target, "set" /* SET */, key, value, oldValue);
  1033. }
  1034. return this;
  1035. }
  1036. function deleteEntry(key) {
  1037. const target = toRaw(this);
  1038. const { has, get } = getProto(target);
  1039. let hadKey = has.call(target, key);
  1040. if (!hadKey) {
  1041. key = toRaw(key);
  1042. hadKey = has.call(target, key);
  1043. }
  1044. else {
  1045. checkIdentityKeys(target, has, key);
  1046. }
  1047. const oldValue = get ? get.call(target, key) : undefined;
  1048. // forward the operation before queueing reactions
  1049. const result = target.delete(key);
  1050. if (hadKey) {
  1051. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  1052. }
  1053. return result;
  1054. }
  1055. function clear() {
  1056. const target = toRaw(this);
  1057. const hadItems = target.size !== 0;
  1058. const oldTarget = isMap(target)
  1059. ? new Map(target)
  1060. : new Set(target)
  1061. ;
  1062. // forward the operation before queueing reactions
  1063. const result = target.clear();
  1064. if (hadItems) {
  1065. trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
  1066. }
  1067. return result;
  1068. }
  1069. function createForEach(isReadonly, isShallow) {
  1070. return function forEach(callback, thisArg) {
  1071. const observed = this;
  1072. const target = observed["__v_raw" /* RAW */];
  1073. const rawTarget = toRaw(target);
  1074. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  1075. !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
  1076. return target.forEach((value, key) => {
  1077. // important: make sure the callback is
  1078. // 1. invoked with the reactive map as `this` and 3rd arg
  1079. // 2. the value received should be a corresponding reactive/readonly.
  1080. return callback.call(thisArg, wrap(value), wrap(key), observed);
  1081. });
  1082. };
  1083. }
  1084. function createIterableMethod(method, isReadonly, isShallow) {
  1085. return function (...args) {
  1086. const target = this["__v_raw" /* RAW */];
  1087. const rawTarget = toRaw(target);
  1088. const targetIsMap = isMap(rawTarget);
  1089. const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
  1090. const isKeyOnly = method === 'keys' && targetIsMap;
  1091. const innerIterator = target[method](...args);
  1092. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  1093. !isReadonly &&
  1094. track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
  1095. // return a wrapped iterator which returns observed versions of the
  1096. // values emitted from the real iterator
  1097. return {
  1098. // iterator protocol
  1099. next() {
  1100. const { value, done } = innerIterator.next();
  1101. return done
  1102. ? { value, done }
  1103. : {
  1104. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  1105. done
  1106. };
  1107. },
  1108. // iterable protocol
  1109. [Symbol.iterator]() {
  1110. return this;
  1111. }
  1112. };
  1113. };
  1114. }
  1115. function createReadonlyMethod(type) {
  1116. return function (...args) {
  1117. {
  1118. const key = args[0] ? `on key "${args[0]}" ` : ``;
  1119. console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
  1120. }
  1121. return type === "delete" /* DELETE */ ? false : this;
  1122. };
  1123. }
  1124. function createInstrumentations() {
  1125. const mutableInstrumentations = {
  1126. get(key) {
  1127. return get$1(this, key);
  1128. },
  1129. get size() {
  1130. return size(this);
  1131. },
  1132. has: has$1,
  1133. add,
  1134. set: set$1,
  1135. delete: deleteEntry,
  1136. clear,
  1137. forEach: createForEach(false, false)
  1138. };
  1139. const shallowInstrumentations = {
  1140. get(key) {
  1141. return get$1(this, key, false, true);
  1142. },
  1143. get size() {
  1144. return size(this);
  1145. },
  1146. has: has$1,
  1147. add,
  1148. set: set$1,
  1149. delete: deleteEntry,
  1150. clear,
  1151. forEach: createForEach(false, true)
  1152. };
  1153. const readonlyInstrumentations = {
  1154. get(key) {
  1155. return get$1(this, key, true);
  1156. },
  1157. get size() {
  1158. return size(this, true);
  1159. },
  1160. has(key) {
  1161. return has$1.call(this, key, true);
  1162. },
  1163. add: createReadonlyMethod("add" /* ADD */),
  1164. set: createReadonlyMethod("set" /* SET */),
  1165. delete: createReadonlyMethod("delete" /* DELETE */),
  1166. clear: createReadonlyMethod("clear" /* CLEAR */),
  1167. forEach: createForEach(true, false)
  1168. };
  1169. const shallowReadonlyInstrumentations = {
  1170. get(key) {
  1171. return get$1(this, key, true, true);
  1172. },
  1173. get size() {
  1174. return size(this, true);
  1175. },
  1176. has(key) {
  1177. return has$1.call(this, key, true);
  1178. },
  1179. add: createReadonlyMethod("add" /* ADD */),
  1180. set: createReadonlyMethod("set" /* SET */),
  1181. delete: createReadonlyMethod("delete" /* DELETE */),
  1182. clear: createReadonlyMethod("clear" /* CLEAR */),
  1183. forEach: createForEach(true, true)
  1184. };
  1185. const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
  1186. iteratorMethods.forEach(method => {
  1187. mutableInstrumentations[method] = createIterableMethod(method, false, false);
  1188. readonlyInstrumentations[method] = createIterableMethod(method, true, false);
  1189. shallowInstrumentations[method] = createIterableMethod(method, false, true);
  1190. shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
  1191. });
  1192. return [
  1193. mutableInstrumentations,
  1194. readonlyInstrumentations,
  1195. shallowInstrumentations,
  1196. shallowReadonlyInstrumentations
  1197. ];
  1198. }
  1199. const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
  1200. function createInstrumentationGetter(isReadonly, shallow) {
  1201. const instrumentations = shallow
  1202. ? isReadonly
  1203. ? shallowReadonlyInstrumentations
  1204. : shallowInstrumentations
  1205. : isReadonly
  1206. ? readonlyInstrumentations
  1207. : mutableInstrumentations;
  1208. return (target, key, receiver) => {
  1209. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  1210. return !isReadonly;
  1211. }
  1212. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  1213. return isReadonly;
  1214. }
  1215. else if (key === "__v_raw" /* RAW */) {
  1216. return target;
  1217. }
  1218. return Reflect.get(hasOwn(instrumentations, key) && key in target
  1219. ? instrumentations
  1220. : target, key, receiver);
  1221. };
  1222. }
  1223. const mutableCollectionHandlers = {
  1224. get: /*#__PURE__*/ createInstrumentationGetter(false, false)
  1225. };
  1226. const shallowCollectionHandlers = {
  1227. get: /*#__PURE__*/ createInstrumentationGetter(false, true)
  1228. };
  1229. const readonlyCollectionHandlers = {
  1230. get: /*#__PURE__*/ createInstrumentationGetter(true, false)
  1231. };
  1232. const shallowReadonlyCollectionHandlers = {
  1233. get: /*#__PURE__*/ createInstrumentationGetter(true, true)
  1234. };
  1235. function checkIdentityKeys(target, has, key) {
  1236. const rawKey = toRaw(key);
  1237. if (rawKey !== key && has.call(target, rawKey)) {
  1238. const type = toRawType(target);
  1239. console.warn(`Reactive ${type} contains both the raw and reactive ` +
  1240. `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
  1241. `which can lead to inconsistencies. ` +
  1242. `Avoid differentiating between the raw and reactive versions ` +
  1243. `of an object and only use the reactive version if possible.`);
  1244. }
  1245. }
  1246. const reactiveMap = new WeakMap();
  1247. const shallowReactiveMap = new WeakMap();
  1248. const readonlyMap = new WeakMap();
  1249. const shallowReadonlyMap = new WeakMap();
  1250. function targetTypeMap(rawType) {
  1251. switch (rawType) {
  1252. case 'Object':
  1253. case 'Array':
  1254. return 1 /* COMMON */;
  1255. case 'Map':
  1256. case 'Set':
  1257. case 'WeakMap':
  1258. case 'WeakSet':
  1259. return 2 /* COLLECTION */;
  1260. default:
  1261. return 0 /* INVALID */;
  1262. }
  1263. }
  1264. function getTargetType(value) {
  1265. return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
  1266. ? 0 /* INVALID */
  1267. : targetTypeMap(toRawType(value));
  1268. }
  1269. function reactive(target) {
  1270. // if trying to observe a readonly proxy, return the readonly version.
  1271. if (isReadonly(target)) {
  1272. return target;
  1273. }
  1274. return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
  1275. }
  1276. /**
  1277. * Return a shallowly-reactive copy of the original object, where only the root
  1278. * level properties are reactive. It also does not auto-unwrap refs (even at the
  1279. * root level).
  1280. */
  1281. function shallowReactive(target) {
  1282. return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
  1283. }
  1284. /**
  1285. * Creates a readonly copy of the original object. Note the returned copy is not
  1286. * made reactive, but `readonly` can be called on an already reactive object.
  1287. */
  1288. function readonly(target) {
  1289. return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
  1290. }
  1291. /**
  1292. * Returns a reactive-copy of the original object, where only the root level
  1293. * properties are readonly, and does NOT unwrap refs nor recursively convert
  1294. * returned properties.
  1295. * This is used for creating the props proxy object for stateful components.
  1296. */
  1297. function shallowReadonly(target) {
  1298. return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
  1299. }
  1300. function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
  1301. if (!isObject(target)) {
  1302. {
  1303. console.warn(`value cannot be made reactive: ${String(target)}`);
  1304. }
  1305. return target;
  1306. }
  1307. // target is already a Proxy, return it.
  1308. // exception: calling readonly() on a reactive object
  1309. if (target["__v_raw" /* RAW */] &&
  1310. !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
  1311. return target;
  1312. }
  1313. // target already has corresponding Proxy
  1314. const existingProxy = proxyMap.get(target);
  1315. if (existingProxy) {
  1316. return existingProxy;
  1317. }
  1318. // only a whitelist of value types can be observed.
  1319. const targetType = getTargetType(target);
  1320. if (targetType === 0 /* INVALID */) {
  1321. return target;
  1322. }
  1323. const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
  1324. proxyMap.set(target, proxy);
  1325. return proxy;
  1326. }
  1327. function isReactive(value) {
  1328. if (isReadonly(value)) {
  1329. return isReactive(value["__v_raw" /* RAW */]);
  1330. }
  1331. return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
  1332. }
  1333. function isReadonly(value) {
  1334. return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
  1335. }
  1336. function isShallow(value) {
  1337. return !!(value && value["__v_isShallow" /* IS_SHALLOW */]);
  1338. }
  1339. function isProxy(value) {
  1340. return isReactive(value) || isReadonly(value);
  1341. }
  1342. function toRaw(observed) {
  1343. const raw = observed && observed["__v_raw" /* RAW */];
  1344. return raw ? toRaw(raw) : observed;
  1345. }
  1346. function markRaw(value) {
  1347. def(value, "__v_skip" /* SKIP */, true);
  1348. return value;
  1349. }
  1350. const toReactive = (value) => isObject(value) ? reactive(value) : value;
  1351. const toReadonly = (value) => isObject(value) ? readonly(value) : value;
  1352. function trackRefValue(ref) {
  1353. if (shouldTrack && activeEffect) {
  1354. ref = toRaw(ref);
  1355. {
  1356. trackEffects(ref.dep || (ref.dep = createDep()), {
  1357. target: ref,
  1358. type: "get" /* GET */,
  1359. key: 'value'
  1360. });
  1361. }
  1362. }
  1363. }
  1364. function triggerRefValue(ref, newVal) {
  1365. ref = toRaw(ref);
  1366. if (ref.dep) {
  1367. {
  1368. triggerEffects(ref.dep, {
  1369. target: ref,
  1370. type: "set" /* SET */,
  1371. key: 'value',
  1372. newValue: newVal
  1373. });
  1374. }
  1375. }
  1376. }
  1377. function isRef(r) {
  1378. return !!(r && r.__v_isRef === true);
  1379. }
  1380. function ref(value) {
  1381. return createRef(value, false);
  1382. }
  1383. function shallowRef(value) {
  1384. return createRef(value, true);
  1385. }
  1386. function createRef(rawValue, shallow) {
  1387. if (isRef(rawValue)) {
  1388. return rawValue;
  1389. }
  1390. return new RefImpl(rawValue, shallow);
  1391. }
  1392. class RefImpl {
  1393. constructor(value, __v_isShallow) {
  1394. this.__v_isShallow = __v_isShallow;
  1395. this.dep = undefined;
  1396. this.__v_isRef = true;
  1397. this._rawValue = __v_isShallow ? value : toRaw(value);
  1398. this._value = __v_isShallow ? value : toReactive(value);
  1399. }
  1400. get value() {
  1401. trackRefValue(this);
  1402. return this._value;
  1403. }
  1404. set value(newVal) {
  1405. newVal = this.__v_isShallow ? newVal : toRaw(newVal);
  1406. if (hasChanged(newVal, this._rawValue)) {
  1407. this._rawValue = newVal;
  1408. this._value = this.__v_isShallow ? newVal : toReactive(newVal);
  1409. triggerRefValue(this, newVal);
  1410. }
  1411. }
  1412. }
  1413. function triggerRef(ref) {
  1414. triggerRefValue(ref, ref.value );
  1415. }
  1416. function unref(ref) {
  1417. return isRef(ref) ? ref.value : ref;
  1418. }
  1419. const shallowUnwrapHandlers = {
  1420. get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  1421. set: (target, key, value, receiver) => {
  1422. const oldValue = target[key];
  1423. if (isRef(oldValue) && !isRef(value)) {
  1424. oldValue.value = value;
  1425. return true;
  1426. }
  1427. else {
  1428. return Reflect.set(target, key, value, receiver);
  1429. }
  1430. }
  1431. };
  1432. function proxyRefs(objectWithRefs) {
  1433. return isReactive(objectWithRefs)
  1434. ? objectWithRefs
  1435. : new Proxy(objectWithRefs, shallowUnwrapHandlers);
  1436. }
  1437. class CustomRefImpl {
  1438. constructor(factory) {
  1439. this.dep = undefined;
  1440. this.__v_isRef = true;
  1441. const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
  1442. this._get = get;
  1443. this._set = set;
  1444. }
  1445. get value() {
  1446. return this._get();
  1447. }
  1448. set value(newVal) {
  1449. this._set(newVal);
  1450. }
  1451. }
  1452. function customRef(factory) {
  1453. return new CustomRefImpl(factory);
  1454. }
  1455. function toRefs(object) {
  1456. if (!isProxy(object)) {
  1457. console.warn(`toRefs() expects a reactive object but received a plain one.`);
  1458. }
  1459. const ret = isArray(object) ? new Array(object.length) : {};
  1460. for (const key in object) {
  1461. ret[key] = toRef(object, key);
  1462. }
  1463. return ret;
  1464. }
  1465. class ObjectRefImpl {
  1466. constructor(_object, _key, _defaultValue) {
  1467. this._object = _object;
  1468. this._key = _key;
  1469. this._defaultValue = _defaultValue;
  1470. this.__v_isRef = true;
  1471. }
  1472. get value() {
  1473. const val = this._object[this._key];
  1474. return val === undefined ? this._defaultValue : val;
  1475. }
  1476. set value(newVal) {
  1477. this._object[this._key] = newVal;
  1478. }
  1479. }
  1480. function toRef(object, key, defaultValue) {
  1481. const val = object[key];
  1482. return isRef(val)
  1483. ? val
  1484. : new ObjectRefImpl(object, key, defaultValue);
  1485. }
  1486. class ComputedRefImpl {
  1487. constructor(getter, _setter, isReadonly, isSSR) {
  1488. this._setter = _setter;
  1489. this.dep = undefined;
  1490. this.__v_isRef = true;
  1491. this._dirty = true;
  1492. this.effect = new ReactiveEffect(getter, () => {
  1493. if (!this._dirty) {
  1494. this._dirty = true;
  1495. triggerRefValue(this);
  1496. }
  1497. });
  1498. this.effect.computed = this;
  1499. this.effect.active = this._cacheable = !isSSR;
  1500. this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
  1501. }
  1502. get value() {
  1503. // the computed ref may get wrapped by other proxies e.g. readonly() #3376
  1504. const self = toRaw(this);
  1505. trackRefValue(self);
  1506. if (self._dirty || !self._cacheable) {
  1507. self._dirty = false;
  1508. self._value = self.effect.run();
  1509. }
  1510. return self._value;
  1511. }
  1512. set value(newValue) {
  1513. this._setter(newValue);
  1514. }
  1515. }
  1516. function computed(getterOrOptions, debugOptions, isSSR = false) {
  1517. let getter;
  1518. let setter;
  1519. const onlyGetter = isFunction(getterOrOptions);
  1520. if (onlyGetter) {
  1521. getter = getterOrOptions;
  1522. setter = () => {
  1523. console.warn('Write operation failed: computed value is readonly');
  1524. }
  1525. ;
  1526. }
  1527. else {
  1528. getter = getterOrOptions.get;
  1529. setter = getterOrOptions.set;
  1530. }
  1531. const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
  1532. if (debugOptions && !isSSR) {
  1533. cRef.effect.onTrack = debugOptions.onTrack;
  1534. cRef.effect.onTrigger = debugOptions.onTrigger;
  1535. }
  1536. return cRef;
  1537. }
  1538. const stack = [];
  1539. function pushWarningContext(vnode) {
  1540. stack.push(vnode);
  1541. }
  1542. function popWarningContext() {
  1543. stack.pop();
  1544. }
  1545. function warn$1(msg, ...args) {
  1546. // avoid props formatting or warn handler tracking deps that might be mutated
  1547. // during patch, leading to infinite recursion.
  1548. pauseTracking();
  1549. const instance = stack.length ? stack[stack.length - 1].component : null;
  1550. const appWarnHandler = instance && instance.appContext.config.warnHandler;
  1551. const trace = getComponentTrace();
  1552. if (appWarnHandler) {
  1553. callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
  1554. msg + args.join(''),
  1555. instance && instance.proxy,
  1556. trace
  1557. .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
  1558. .join('\n'),
  1559. trace
  1560. ]);
  1561. }
  1562. else {
  1563. const warnArgs = [`[Vue warn]: ${msg}`, ...args];
  1564. /* istanbul ignore if */
  1565. if (trace.length &&
  1566. // avoid spamming console during tests
  1567. !false) {
  1568. warnArgs.push(`\n`, ...formatTrace(trace));
  1569. }
  1570. console.warn(...warnArgs);
  1571. }
  1572. resetTracking();
  1573. }
  1574. function getComponentTrace() {
  1575. let currentVNode = stack[stack.length - 1];
  1576. if (!currentVNode) {
  1577. return [];
  1578. }
  1579. // we can't just use the stack because it will be incomplete during updates
  1580. // that did not start from the root. Re-construct the parent chain using
  1581. // instance parent pointers.
  1582. const normalizedStack = [];
  1583. while (currentVNode) {
  1584. const last = normalizedStack[0];
  1585. if (last && last.vnode === currentVNode) {
  1586. last.recurseCount++;
  1587. }
  1588. else {
  1589. normalizedStack.push({
  1590. vnode: currentVNode,
  1591. recurseCount: 0
  1592. });
  1593. }
  1594. const parentInstance = currentVNode.component && currentVNode.component.parent;
  1595. currentVNode = parentInstance && parentInstance.vnode;
  1596. }
  1597. return normalizedStack;
  1598. }
  1599. /* istanbul ignore next */
  1600. function formatTrace(trace) {
  1601. const logs = [];
  1602. trace.forEach((entry, i) => {
  1603. logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
  1604. });
  1605. return logs;
  1606. }
  1607. function formatTraceEntry({ vnode, recurseCount }) {
  1608. const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
  1609. const isRoot = vnode.component ? vnode.component.parent == null : false;
  1610. const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
  1611. const close = `>` + postfix;
  1612. return vnode.props
  1613. ? [open, ...formatProps(vnode.props), close]
  1614. : [open + close];
  1615. }
  1616. /* istanbul ignore next */
  1617. function formatProps(props) {
  1618. const res = [];
  1619. const keys = Object.keys(props);
  1620. keys.slice(0, 3).forEach(key => {
  1621. res.push(...formatProp(key, props[key]));
  1622. });
  1623. if (keys.length > 3) {
  1624. res.push(` ...`);
  1625. }
  1626. return res;
  1627. }
  1628. /* istanbul ignore next */
  1629. function formatProp(key, value, raw) {
  1630. if (isString(value)) {
  1631. value = JSON.stringify(value);
  1632. return raw ? value : [`${key}=${value}`];
  1633. }
  1634. else if (typeof value === 'number' ||
  1635. typeof value === 'boolean' ||
  1636. value == null) {
  1637. return raw ? value : [`${key}=${value}`];
  1638. }
  1639. else if (isRef(value)) {
  1640. value = formatProp(key, toRaw(value.value), true);
  1641. return raw ? value : [`${key}=Ref<`, value, `>`];
  1642. }
  1643. else if (isFunction(value)) {
  1644. return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
  1645. }
  1646. else {
  1647. value = toRaw(value);
  1648. return raw ? value : [`${key}=`, value];
  1649. }
  1650. }
  1651. const ErrorTypeStrings = {
  1652. ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',
  1653. ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
  1654. ["c" /* CREATED */]: 'created hook',
  1655. ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
  1656. ["m" /* MOUNTED */]: 'mounted hook',
  1657. ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
  1658. ["u" /* UPDATED */]: 'updated',
  1659. ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
  1660. ["um" /* UNMOUNTED */]: 'unmounted hook',
  1661. ["a" /* ACTIVATED */]: 'activated hook',
  1662. ["da" /* DEACTIVATED */]: 'deactivated hook',
  1663. ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
  1664. ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
  1665. ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
  1666. [0 /* SETUP_FUNCTION */]: 'setup function',
  1667. [1 /* RENDER_FUNCTION */]: 'render function',
  1668. [2 /* WATCH_GETTER */]: 'watcher getter',
  1669. [3 /* WATCH_CALLBACK */]: 'watcher callback',
  1670. [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
  1671. [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
  1672. [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
  1673. [7 /* VNODE_HOOK */]: 'vnode hook',
  1674. [8 /* DIRECTIVE_HOOK */]: 'directive hook',
  1675. [9 /* TRANSITION_HOOK */]: 'transition hook',
  1676. [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
  1677. [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
  1678. [12 /* FUNCTION_REF */]: 'ref function',
  1679. [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
  1680. [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
  1681. 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core'
  1682. };
  1683. function callWithErrorHandling(fn, instance, type, args) {
  1684. let res;
  1685. try {
  1686. res = args ? fn(...args) : fn();
  1687. }
  1688. catch (err) {
  1689. handleError(err, instance, type);
  1690. }
  1691. return res;
  1692. }
  1693. function callWithAsyncErrorHandling(fn, instance, type, args) {
  1694. if (isFunction(fn)) {
  1695. const res = callWithErrorHandling(fn, instance, type, args);
  1696. if (res && isPromise(res)) {
  1697. res.catch(err => {
  1698. handleError(err, instance, type);
  1699. });
  1700. }
  1701. return res;
  1702. }
  1703. const values = [];
  1704. for (let i = 0; i < fn.length; i++) {
  1705. values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
  1706. }
  1707. return values;
  1708. }
  1709. function handleError(err, instance, type, throwInDev = true) {
  1710. const contextVNode = instance ? instance.vnode : null;
  1711. if (instance) {
  1712. let cur = instance.parent;
  1713. // the exposed instance is the render proxy to keep it consistent with 2.x
  1714. const exposedInstance = instance.proxy;
  1715. // in production the hook receives only the error code
  1716. const errorInfo = ErrorTypeStrings[type] ;
  1717. while (cur) {
  1718. const errorCapturedHooks = cur.ec;
  1719. if (errorCapturedHooks) {
  1720. for (let i = 0; i < errorCapturedHooks.length; i++) {
  1721. if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
  1722. return;
  1723. }
  1724. }
  1725. }
  1726. cur = cur.parent;
  1727. }
  1728. // app-level handling
  1729. const appErrorHandler = instance.appContext.config.errorHandler;
  1730. if (appErrorHandler) {
  1731. callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
  1732. return;
  1733. }
  1734. }
  1735. logError(err, type, contextVNode, throwInDev);
  1736. }
  1737. function logError(err, type, contextVNode, throwInDev = true) {
  1738. {
  1739. const info = ErrorTypeStrings[type];
  1740. if (contextVNode) {
  1741. pushWarningContext(contextVNode);
  1742. }
  1743. warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
  1744. if (contextVNode) {
  1745. popWarningContext();
  1746. }
  1747. // crash in dev by default so it's more noticeable
  1748. if (throwInDev) {
  1749. throw err;
  1750. }
  1751. else {
  1752. console.error(err);
  1753. }
  1754. }
  1755. }
  1756. let isFlushing = false;
  1757. let isFlushPending = false;
  1758. const queue = [];
  1759. let flushIndex = 0;
  1760. const pendingPreFlushCbs = [];
  1761. let activePreFlushCbs = null;
  1762. let preFlushIndex = 0;
  1763. const pendingPostFlushCbs = [];
  1764. let activePostFlushCbs = null;
  1765. let postFlushIndex = 0;
  1766. const resolvedPromise = /*#__PURE__*/ Promise.resolve();
  1767. let currentFlushPromise = null;
  1768. let currentPreFlushParentJob = null;
  1769. const RECURSION_LIMIT = 100;
  1770. function nextTick(fn) {
  1771. const p = currentFlushPromise || resolvedPromise;
  1772. return fn ? p.then(this ? fn.bind(this) : fn) : p;
  1773. }
  1774. // #2768
  1775. // Use binary-search to find a suitable position in the queue,
  1776. // so that the queue maintains the increasing order of job's id,
  1777. // which can prevent the job from being skipped and also can avoid repeated patching.
  1778. function findInsertionIndex(id) {
  1779. // the start index should be `flushIndex + 1`
  1780. let start = flushIndex + 1;
  1781. let end = queue.length;
  1782. while (start < end) {
  1783. const middle = (start + end) >>> 1;
  1784. const middleJobId = getId(queue[middle]);
  1785. middleJobId < id ? (start = middle + 1) : (end = middle);
  1786. }
  1787. return start;
  1788. }
  1789. function queueJob(job) {
  1790. // the dedupe search uses the startIndex argument of Array.includes()
  1791. // by default the search index includes the current job that is being run
  1792. // so it cannot recursively trigger itself again.
  1793. // if the job is a watch() callback, the search will start with a +1 index to
  1794. // allow it recursively trigger itself - it is the user's responsibility to
  1795. // ensure it doesn't end up in an infinite loop.
  1796. if ((!queue.length ||
  1797. !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
  1798. job !== currentPreFlushParentJob) {
  1799. if (job.id == null) {
  1800. queue.push(job);
  1801. }
  1802. else {
  1803. queue.splice(findInsertionIndex(job.id), 0, job);
  1804. }
  1805. queueFlush();
  1806. }
  1807. }
  1808. function queueFlush() {
  1809. if (!isFlushing && !isFlushPending) {
  1810. isFlushPending = true;
  1811. currentFlushPromise = resolvedPromise.then(flushJobs);
  1812. }
  1813. }
  1814. function invalidateJob(job) {
  1815. const i = queue.indexOf(job);
  1816. if (i > flushIndex) {
  1817. queue.splice(i, 1);
  1818. }
  1819. }
  1820. function queueCb(cb, activeQueue, pendingQueue, index) {
  1821. if (!isArray(cb)) {
  1822. if (!activeQueue ||
  1823. !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
  1824. pendingQueue.push(cb);
  1825. }
  1826. }
  1827. else {
  1828. // if cb is an array, it is a component lifecycle hook which can only be
  1829. // triggered by a job, which is already deduped in the main queue, so
  1830. // we can skip duplicate check here to improve perf
  1831. pendingQueue.push(...cb);
  1832. }
  1833. queueFlush();
  1834. }
  1835. function queuePreFlushCb(cb) {
  1836. queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
  1837. }
  1838. function queuePostFlushCb(cb) {
  1839. queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
  1840. }
  1841. function flushPreFlushCbs(seen, parentJob = null) {
  1842. if (pendingPreFlushCbs.length) {
  1843. currentPreFlushParentJob = parentJob;
  1844. activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
  1845. pendingPreFlushCbs.length = 0;
  1846. {
  1847. seen = seen || new Map();
  1848. }
  1849. for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
  1850. if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
  1851. continue;
  1852. }
  1853. activePreFlushCbs[preFlushIndex]();
  1854. }
  1855. activePreFlushCbs = null;
  1856. preFlushIndex = 0;
  1857. currentPreFlushParentJob = null;
  1858. // recursively flush until it drains
  1859. flushPreFlushCbs(seen, parentJob);
  1860. }
  1861. }
  1862. function flushPostFlushCbs(seen) {
  1863. if (pendingPostFlushCbs.length) {
  1864. const deduped = [...new Set(pendingPostFlushCbs)];
  1865. pendingPostFlushCbs.length = 0;
  1866. // #1947 already has active queue, nested flushPostFlushCbs call
  1867. if (activePostFlushCbs) {
  1868. activePostFlushCbs.push(...deduped);
  1869. return;
  1870. }
  1871. activePostFlushCbs = deduped;
  1872. {
  1873. seen = seen || new Map();
  1874. }
  1875. activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
  1876. for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
  1877. if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
  1878. continue;
  1879. }
  1880. activePostFlushCbs[postFlushIndex]();
  1881. }
  1882. activePostFlushCbs = null;
  1883. postFlushIndex = 0;
  1884. }
  1885. }
  1886. const getId = (job) => job.id == null ? Infinity : job.id;
  1887. function flushJobs(seen) {
  1888. isFlushPending = false;
  1889. isFlushing = true;
  1890. {
  1891. seen = seen || new Map();
  1892. }
  1893. flushPreFlushCbs(seen);
  1894. // Sort queue before flush.
  1895. // This ensures that:
  1896. // 1. Components are updated from parent to child. (because parent is always
  1897. // created before the child so its render effect will have smaller
  1898. // priority number)
  1899. // 2. If a component is unmounted during a parent component's update,
  1900. // its update can be skipped.
  1901. queue.sort((a, b) => getId(a) - getId(b));
  1902. // conditional usage of checkRecursiveUpdate must be determined out of
  1903. // try ... catch block since Rollup by default de-optimizes treeshaking
  1904. // inside try-catch. This can leave all warning code unshaked. Although
  1905. // they would get eventually shaken by a minifier like terser, some minifiers
  1906. // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)
  1907. const check = (job) => checkRecursiveUpdates(seen, job)
  1908. ;
  1909. try {
  1910. for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
  1911. const job = queue[flushIndex];
  1912. if (job && job.active !== false) {
  1913. if (true && check(job)) {
  1914. continue;
  1915. }
  1916. // console.log(`running:`, job.id)
  1917. callWithErrorHandling(job, null, 14 /* SCHEDULER */);
  1918. }
  1919. }
  1920. }
  1921. finally {
  1922. flushIndex = 0;
  1923. queue.length = 0;
  1924. flushPostFlushCbs(seen);
  1925. isFlushing = false;
  1926. currentFlushPromise = null;
  1927. // some postFlushCb queued jobs!
  1928. // keep flushing until it drains.
  1929. if (queue.length ||
  1930. pendingPreFlushCbs.length ||
  1931. pendingPostFlushCbs.length) {
  1932. flushJobs(seen);
  1933. }
  1934. }
  1935. }
  1936. function checkRecursiveUpdates(seen, fn) {
  1937. if (!seen.has(fn)) {
  1938. seen.set(fn, 1);
  1939. }
  1940. else {
  1941. const count = seen.get(fn);
  1942. if (count > RECURSION_LIMIT) {
  1943. const instance = fn.ownerInstance;
  1944. const componentName = instance && getComponentName(instance.type);
  1945. warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
  1946. `This means you have a reactive effect that is mutating its own ` +
  1947. `dependencies and thus recursively triggering itself. Possible sources ` +
  1948. `include component template, render function, updated hook or ` +
  1949. `watcher source function.`);
  1950. return true;
  1951. }
  1952. else {
  1953. seen.set(fn, count + 1);
  1954. }
  1955. }
  1956. }
  1957. /* eslint-disable no-restricted-globals */
  1958. let isHmrUpdating = false;
  1959. const hmrDirtyComponents = new Set();
  1960. // Expose the HMR runtime on the global object
  1961. // This makes it entirely tree-shakable without polluting the exports and makes
  1962. // it easier to be used in toolings like vue-loader
  1963. // Note: for a component to be eligible for HMR it also needs the __hmrId option
  1964. // to be set so that its instances can be registered / removed.
  1965. {
  1966. getGlobalThis().__VUE_HMR_RUNTIME__ = {
  1967. createRecord: tryWrap(createRecord),
  1968. rerender: tryWrap(rerender),
  1969. reload: tryWrap(reload)
  1970. };
  1971. }
  1972. const map = new Map();
  1973. function registerHMR(instance) {
  1974. const id = instance.type.__hmrId;
  1975. let record = map.get(id);
  1976. if (!record) {
  1977. createRecord(id, instance.type);
  1978. record = map.get(id);
  1979. }
  1980. record.instances.add(instance);
  1981. }
  1982. function unregisterHMR(instance) {
  1983. map.get(instance.type.__hmrId).instances.delete(instance);
  1984. }
  1985. function createRecord(id, initialDef) {
  1986. if (map.has(id)) {
  1987. return false;
  1988. }
  1989. map.set(id, {
  1990. initialDef: normalizeClassComponent(initialDef),
  1991. instances: new Set()
  1992. });
  1993. return true;
  1994. }
  1995. function normalizeClassComponent(component) {
  1996. return isClassComponent(component) ? component.__vccOpts : component;
  1997. }
  1998. function rerender(id, newRender) {
  1999. const record = map.get(id);
  2000. if (!record) {
  2001. return;
  2002. }
  2003. // update initial record (for not-yet-rendered component)
  2004. record.initialDef.render = newRender;
  2005. [...record.instances].forEach(instance => {
  2006. if (newRender) {
  2007. instance.render = newRender;
  2008. normalizeClassComponent(instance.type).render = newRender;
  2009. }
  2010. instance.renderCache = [];
  2011. // this flag forces child components with slot content to update
  2012. isHmrUpdating = true;
  2013. instance.update();
  2014. isHmrUpdating = false;
  2015. });
  2016. }
  2017. function reload(id, newComp) {
  2018. const record = map.get(id);
  2019. if (!record)
  2020. return;
  2021. newComp = normalizeClassComponent(newComp);
  2022. // update initial def (for not-yet-rendered components)
  2023. updateComponentDef(record.initialDef, newComp);
  2024. // create a snapshot which avoids the set being mutated during updates
  2025. const instances = [...record.instances];
  2026. for (const instance of instances) {
  2027. const oldComp = normalizeClassComponent(instance.type);
  2028. if (!hmrDirtyComponents.has(oldComp)) {
  2029. // 1. Update existing comp definition to match new one
  2030. if (oldComp !== record.initialDef) {
  2031. updateComponentDef(oldComp, newComp);
  2032. }
  2033. // 2. mark definition dirty. This forces the renderer to replace the
  2034. // component on patch.
  2035. hmrDirtyComponents.add(oldComp);
  2036. }
  2037. // 3. invalidate options resolution cache
  2038. instance.appContext.optionsCache.delete(instance.type);
  2039. // 4. actually update
  2040. if (instance.ceReload) {
  2041. // custom element
  2042. hmrDirtyComponents.add(oldComp);
  2043. instance.ceReload(newComp.styles);
  2044. hmrDirtyComponents.delete(oldComp);
  2045. }
  2046. else if (instance.parent) {
  2047. // 4. Force the parent instance to re-render. This will cause all updated
  2048. // components to be unmounted and re-mounted. Queue the update so that we
  2049. // don't end up forcing the same parent to re-render multiple times.
  2050. queueJob(instance.parent.update);
  2051. // instance is the inner component of an async custom element
  2052. // invoke to reset styles
  2053. if (instance.parent.type.__asyncLoader &&
  2054. instance.parent.ceReload) {
  2055. instance.parent.ceReload(newComp.styles);
  2056. }
  2057. }
  2058. else if (instance.appContext.reload) {
  2059. // root instance mounted via createApp() has a reload method
  2060. instance.appContext.reload();
  2061. }
  2062. else if (typeof window !== 'undefined') {
  2063. // root instance inside tree created via raw render(). Force reload.
  2064. window.location.reload();
  2065. }
  2066. else {
  2067. console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
  2068. }
  2069. }
  2070. // 5. make sure to cleanup dirty hmr components after update
  2071. queuePostFlushCb(() => {
  2072. for (const instance of instances) {
  2073. hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
  2074. }
  2075. });
  2076. }
  2077. function updateComponentDef(oldComp, newComp) {
  2078. extend(oldComp, newComp);
  2079. for (const key in oldComp) {
  2080. if (key !== '__file' && !(key in newComp)) {
  2081. delete oldComp[key];
  2082. }
  2083. }
  2084. }
  2085. function tryWrap(fn) {
  2086. return (id, arg) => {
  2087. try {
  2088. return fn(id, arg);
  2089. }
  2090. catch (e) {
  2091. console.error(e);
  2092. console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
  2093. `Full reload required.`);
  2094. }
  2095. };
  2096. }
  2097. let devtools;
  2098. let buffer = [];
  2099. let devtoolsNotInstalled = false;
  2100. function emit(event, ...args) {
  2101. if (devtools) {
  2102. devtools.emit(event, ...args);
  2103. }
  2104. else if (!devtoolsNotInstalled) {
  2105. buffer.push({ event, args });
  2106. }
  2107. }
  2108. function setDevtoolsHook(hook, target) {
  2109. var _a, _b;
  2110. devtools = hook;
  2111. if (devtools) {
  2112. devtools.enabled = true;
  2113. buffer.forEach(({ event, args }) => devtools.emit(event, ...args));
  2114. buffer = [];
  2115. }
  2116. else if (
  2117. // handle late devtools injection - only do this if we are in an actual
  2118. // browser environment to avoid the timer handle stalling test runner exit
  2119. // (#4815)
  2120. // eslint-disable-next-line no-restricted-globals
  2121. typeof window !== 'undefined' &&
  2122. // some envs mock window but not fully
  2123. window.HTMLElement &&
  2124. // also exclude jsdom
  2125. !((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) === null || _b === void 0 ? void 0 : _b.includes('jsdom'))) {
  2126. const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ =
  2127. target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []);
  2128. replay.push((newHook) => {
  2129. setDevtoolsHook(newHook, target);
  2130. });
  2131. // clear buffer after 3s - the user probably doesn't have devtools installed
  2132. // at all, and keeping the buffer will cause memory leaks (#4738)
  2133. setTimeout(() => {
  2134. if (!devtools) {
  2135. target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
  2136. devtoolsNotInstalled = true;
  2137. buffer = [];
  2138. }
  2139. }, 3000);
  2140. }
  2141. else {
  2142. // non-browser env, assume not installed
  2143. devtoolsNotInstalled = true;
  2144. buffer = [];
  2145. }
  2146. }
  2147. function devtoolsInitApp(app, version) {
  2148. emit("app:init" /* APP_INIT */, app, version, {
  2149. Fragment,
  2150. Text,
  2151. Comment,
  2152. Static
  2153. });
  2154. }
  2155. function devtoolsUnmountApp(app) {
  2156. emit("app:unmount" /* APP_UNMOUNT */, app);
  2157. }
  2158. const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
  2159. const devtoolsComponentUpdated =
  2160. /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
  2161. const devtoolsComponentRemoved =
  2162. /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
  2163. function createDevtoolsComponentHook(hook) {
  2164. return (component) => {
  2165. emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
  2166. };
  2167. }
  2168. const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
  2169. const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
  2170. function createDevtoolsPerformanceHook(hook) {
  2171. return (component, type, time) => {
  2172. emit(hook, component.appContext.app, component.uid, component, type, time);
  2173. };
  2174. }
  2175. function devtoolsComponentEmit(component, event, params) {
  2176. emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
  2177. }
  2178. function emit$1(instance, event, ...rawArgs) {
  2179. if (instance.isUnmounted)
  2180. return;
  2181. const props = instance.vnode.props || EMPTY_OBJ;
  2182. {
  2183. const { emitsOptions, propsOptions: [propsOptions] } = instance;
  2184. if (emitsOptions) {
  2185. if (!(event in emitsOptions) &&
  2186. !(false )) {
  2187. if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
  2188. warn$1(`Component emitted event "${event}" but it is neither declared in ` +
  2189. `the emits option nor as an "${toHandlerKey(event)}" prop.`);
  2190. }
  2191. }
  2192. else {
  2193. const validator = emitsOptions[event];
  2194. if (isFunction(validator)) {
  2195. const isValid = validator(...rawArgs);
  2196. if (!isValid) {
  2197. warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
  2198. }
  2199. }
  2200. }
  2201. }
  2202. }
  2203. let args = rawArgs;
  2204. const isModelListener = event.startsWith('update:');
  2205. // for v-model update:xxx events, apply modifiers on args
  2206. const modelArg = isModelListener && event.slice(7);
  2207. if (modelArg && modelArg in props) {
  2208. const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
  2209. const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
  2210. if (trim) {
  2211. args = rawArgs.map(a => a.trim());
  2212. }
  2213. else if (number) {
  2214. args = rawArgs.map(toNumber);
  2215. }
  2216. }
  2217. {
  2218. devtoolsComponentEmit(instance, event, args);
  2219. }
  2220. {
  2221. const lowerCaseEvent = event.toLowerCase();
  2222. if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
  2223. warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
  2224. `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
  2225. `Note that HTML attributes are case-insensitive and you cannot use ` +
  2226. `v-on to listen to camelCase events when using in-DOM templates. ` +
  2227. `You should probably use "${hyphenate(event)}" instead of "${event}".`);
  2228. }
  2229. }
  2230. let handlerName;
  2231. let handler = props[(handlerName = toHandlerKey(event))] ||
  2232. // also try camelCase event handler (#2249)
  2233. props[(handlerName = toHandlerKey(camelize(event)))];
  2234. // for v-model update:xxx events, also trigger kebab-case equivalent
  2235. // for props passed via kebab-case
  2236. if (!handler && isModelListener) {
  2237. handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
  2238. }
  2239. if (handler) {
  2240. callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
  2241. }
  2242. const onceHandler = props[handlerName + `Once`];
  2243. if (onceHandler) {
  2244. if (!instance.emitted) {
  2245. instance.emitted = {};
  2246. }
  2247. else if (instance.emitted[handlerName]) {
  2248. return;
  2249. }
  2250. instance.emitted[handlerName] = true;
  2251. callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
  2252. }
  2253. }
  2254. function normalizeEmitsOptions(comp, appContext, asMixin = false) {
  2255. const cache = appContext.emitsCache;
  2256. const cached = cache.get(comp);
  2257. if (cached !== undefined) {
  2258. return cached;
  2259. }
  2260. const raw = comp.emits;
  2261. let normalized = {};
  2262. // apply mixin/extends props
  2263. let hasExtends = false;
  2264. if (!isFunction(comp)) {
  2265. const extendEmits = (raw) => {
  2266. const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
  2267. if (normalizedFromExtend) {
  2268. hasExtends = true;
  2269. extend(normalized, normalizedFromExtend);
  2270. }
  2271. };
  2272. if (!asMixin && appContext.mixins.length) {
  2273. appContext.mixins.forEach(extendEmits);
  2274. }
  2275. if (comp.extends) {
  2276. extendEmits(comp.extends);
  2277. }
  2278. if (comp.mixins) {
  2279. comp.mixins.forEach(extendEmits);
  2280. }
  2281. }
  2282. if (!raw && !hasExtends) {
  2283. cache.set(comp, null);
  2284. return null;
  2285. }
  2286. if (isArray(raw)) {
  2287. raw.forEach(key => (normalized[key] = null));
  2288. }
  2289. else {
  2290. extend(normalized, raw);
  2291. }
  2292. cache.set(comp, normalized);
  2293. return normalized;
  2294. }
  2295. // Check if an incoming prop key is a declared emit event listener.
  2296. // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
  2297. // both considered matched listeners.
  2298. function isEmitListener(options, key) {
  2299. if (!options || !isOn(key)) {
  2300. return false;
  2301. }
  2302. key = key.slice(2).replace(/Once$/, '');
  2303. return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
  2304. hasOwn(options, hyphenate(key)) ||
  2305. hasOwn(options, key));
  2306. }
  2307. /**
  2308. * mark the current rendering instance for asset resolution (e.g.
  2309. * resolveComponent, resolveDirective) during render
  2310. */
  2311. let currentRenderingInstance = null;
  2312. let currentScopeId = null;
  2313. /**
  2314. * Note: rendering calls maybe nested. The function returns the parent rendering
  2315. * instance if present, which should be restored after the render is done:
  2316. *
  2317. * ```js
  2318. * const prev = setCurrentRenderingInstance(i)
  2319. * // ...render
  2320. * setCurrentRenderingInstance(prev)
  2321. * ```
  2322. */
  2323. function setCurrentRenderingInstance(instance) {
  2324. const prev = currentRenderingInstance;
  2325. currentRenderingInstance = instance;
  2326. currentScopeId = (instance && instance.type.__scopeId) || null;
  2327. return prev;
  2328. }
  2329. /**
  2330. * Set scope id when creating hoisted vnodes.
  2331. * @private compiler helper
  2332. */
  2333. function pushScopeId(id) {
  2334. currentScopeId = id;
  2335. }
  2336. /**
  2337. * Technically we no longer need this after 3.0.8 but we need to keep the same
  2338. * API for backwards compat w/ code generated by compilers.
  2339. * @private
  2340. */
  2341. function popScopeId() {
  2342. currentScopeId = null;
  2343. }
  2344. /**
  2345. * Only for backwards compat
  2346. * @private
  2347. */
  2348. const withScopeId = (_id) => withCtx;
  2349. /**
  2350. * Wrap a slot function to memoize current rendering instance
  2351. * @private compiler helper
  2352. */
  2353. function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
  2354. ) {
  2355. if (!ctx)
  2356. return fn;
  2357. // already normalized
  2358. if (fn._n) {
  2359. return fn;
  2360. }
  2361. const renderFnWithContext = (...args) => {
  2362. // If a user calls a compiled slot inside a template expression (#1745), it
  2363. // can mess up block tracking, so by default we disable block tracking and
  2364. // force bail out when invoking a compiled slot (indicated by the ._d flag).
  2365. // This isn't necessary if rendering a compiled `<slot>`, so we flip the
  2366. // ._d flag off when invoking the wrapped fn inside `renderSlot`.
  2367. if (renderFnWithContext._d) {
  2368. setBlockTracking(-1);
  2369. }
  2370. const prevInstance = setCurrentRenderingInstance(ctx);
  2371. const res = fn(...args);
  2372. setCurrentRenderingInstance(prevInstance);
  2373. if (renderFnWithContext._d) {
  2374. setBlockTracking(1);
  2375. }
  2376. {
  2377. devtoolsComponentUpdated(ctx);
  2378. }
  2379. return res;
  2380. };
  2381. // mark normalized to avoid duplicated wrapping
  2382. renderFnWithContext._n = true;
  2383. // mark this as compiled by default
  2384. // this is used in vnode.ts -> normalizeChildren() to set the slot
  2385. // rendering flag.
  2386. renderFnWithContext._c = true;
  2387. // disable block tracking by default
  2388. renderFnWithContext._d = true;
  2389. return renderFnWithContext;
  2390. }
  2391. /**
  2392. * dev only flag to track whether $attrs was used during render.
  2393. * If $attrs was used during render then the warning for failed attrs
  2394. * fallthrough can be suppressed.
  2395. */
  2396. let accessedAttrs = false;
  2397. function markAttrsAccessed() {
  2398. accessedAttrs = true;
  2399. }
  2400. function renderComponentRoot(instance) {
  2401. const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
  2402. let result;
  2403. let fallthroughAttrs;
  2404. const prev = setCurrentRenderingInstance(instance);
  2405. {
  2406. accessedAttrs = false;
  2407. }
  2408. try {
  2409. if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
  2410. // withProxy is a proxy with a different `has` trap only for
  2411. // runtime-compiled render functions using `with` block.
  2412. const proxyToUse = withProxy || proxy;
  2413. result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
  2414. fallthroughAttrs = attrs;
  2415. }
  2416. else {
  2417. // functional
  2418. const render = Component;
  2419. // in dev, mark attrs accessed if optional props (attrs === props)
  2420. if (true && attrs === props) {
  2421. markAttrsAccessed();
  2422. }
  2423. result = normalizeVNode(render.length > 1
  2424. ? render(props, true
  2425. ? {
  2426. get attrs() {
  2427. markAttrsAccessed();
  2428. return attrs;
  2429. },
  2430. slots,
  2431. emit
  2432. }
  2433. : { attrs, slots, emit })
  2434. : render(props, null /* we know it doesn't need it */));
  2435. fallthroughAttrs = Component.props
  2436. ? attrs
  2437. : getFunctionalFallthrough(attrs);
  2438. }
  2439. }
  2440. catch (err) {
  2441. blockStack.length = 0;
  2442. handleError(err, instance, 1 /* RENDER_FUNCTION */);
  2443. result = createVNode(Comment);
  2444. }
  2445. // attr merging
  2446. // in dev mode, comments are preserved, and it's possible for a template
  2447. // to have comments along side the root element which makes it a fragment
  2448. let root = result;
  2449. let setRoot = undefined;
  2450. if (result.patchFlag > 0 &&
  2451. result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
  2452. [root, setRoot] = getChildRoot(result);
  2453. }
  2454. if (fallthroughAttrs && inheritAttrs !== false) {
  2455. const keys = Object.keys(fallthroughAttrs);
  2456. const { shapeFlag } = root;
  2457. if (keys.length) {
  2458. if (shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) {
  2459. if (propsOptions && keys.some(isModelListener)) {
  2460. // If a v-model listener (onUpdate:xxx) has a corresponding declared
  2461. // prop, it indicates this component expects to handle v-model and
  2462. // it should not fallthrough.
  2463. // related: #1543, #1643, #1989
  2464. fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
  2465. }
  2466. root = cloneVNode(root, fallthroughAttrs);
  2467. }
  2468. else if (!accessedAttrs && root.type !== Comment) {
  2469. const allAttrs = Object.keys(attrs);
  2470. const eventAttrs = [];
  2471. const extraAttrs = [];
  2472. for (let i = 0, l = allAttrs.length; i < l; i++) {
  2473. const key = allAttrs[i];
  2474. if (isOn(key)) {
  2475. // ignore v-model handlers when they fail to fallthrough
  2476. if (!isModelListener(key)) {
  2477. // remove `on`, lowercase first letter to reflect event casing
  2478. // accurately
  2479. eventAttrs.push(key[2].toLowerCase() + key.slice(3));
  2480. }
  2481. }
  2482. else {
  2483. extraAttrs.push(key);
  2484. }
  2485. }
  2486. if (extraAttrs.length) {
  2487. warn$1(`Extraneous non-props attributes (` +
  2488. `${extraAttrs.join(', ')}) ` +
  2489. `were passed to component but could not be automatically inherited ` +
  2490. `because component renders fragment or text root nodes.`);
  2491. }
  2492. if (eventAttrs.length) {
  2493. warn$1(`Extraneous non-emits event listeners (` +
  2494. `${eventAttrs.join(', ')}) ` +
  2495. `were passed to component but could not be automatically inherited ` +
  2496. `because component renders fragment or text root nodes. ` +
  2497. `If the listener is intended to be a component custom event listener only, ` +
  2498. `declare it using the "emits" option.`);
  2499. }
  2500. }
  2501. }
  2502. }
  2503. // inherit directives
  2504. if (vnode.dirs) {
  2505. if (!isElementRoot(root)) {
  2506. warn$1(`Runtime directive used on component with non-element root node. ` +
  2507. `The directives will not function as intended.`);
  2508. }
  2509. root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
  2510. }
  2511. // inherit transition data
  2512. if (vnode.transition) {
  2513. if (!isElementRoot(root)) {
  2514. warn$1(`Component inside <Transition> renders non-element root node ` +
  2515. `that cannot be animated.`);
  2516. }
  2517. root.transition = vnode.transition;
  2518. }
  2519. if (setRoot) {
  2520. setRoot(root);
  2521. }
  2522. else {
  2523. result = root;
  2524. }
  2525. setCurrentRenderingInstance(prev);
  2526. return result;
  2527. }
  2528. /**
  2529. * dev only
  2530. * In dev mode, template root level comments are rendered, which turns the
  2531. * template into a fragment root, but we need to locate the single element
  2532. * root for attrs and scope id processing.
  2533. */
  2534. const getChildRoot = (vnode) => {
  2535. const rawChildren = vnode.children;
  2536. const dynamicChildren = vnode.dynamicChildren;
  2537. const childRoot = filterSingleRoot(rawChildren);
  2538. if (!childRoot) {
  2539. return [vnode, undefined];
  2540. }
  2541. const index = rawChildren.indexOf(childRoot);
  2542. const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
  2543. const setRoot = (updatedRoot) => {
  2544. rawChildren[index] = updatedRoot;
  2545. if (dynamicChildren) {
  2546. if (dynamicIndex > -1) {
  2547. dynamicChildren[dynamicIndex] = updatedRoot;
  2548. }
  2549. else if (updatedRoot.patchFlag > 0) {
  2550. vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
  2551. }
  2552. }
  2553. };
  2554. return [normalizeVNode(childRoot), setRoot];
  2555. };
  2556. function filterSingleRoot(children) {
  2557. let singleRoot;
  2558. for (let i = 0; i < children.length; i++) {
  2559. const child = children[i];
  2560. if (isVNode(child)) {
  2561. // ignore user comment
  2562. if (child.type !== Comment || child.children === 'v-if') {
  2563. if (singleRoot) {
  2564. // has more than 1 non-comment child, return now
  2565. return;
  2566. }
  2567. else {
  2568. singleRoot = child;
  2569. }
  2570. }
  2571. }
  2572. else {
  2573. return;
  2574. }
  2575. }
  2576. return singleRoot;
  2577. }
  2578. const getFunctionalFallthrough = (attrs) => {
  2579. let res;
  2580. for (const key in attrs) {
  2581. if (key === 'class' || key === 'style' || isOn(key)) {
  2582. (res || (res = {}))[key] = attrs[key];
  2583. }
  2584. }
  2585. return res;
  2586. };
  2587. const filterModelListeners = (attrs, props) => {
  2588. const res = {};
  2589. for (const key in attrs) {
  2590. if (!isModelListener(key) || !(key.slice(9) in props)) {
  2591. res[key] = attrs[key];
  2592. }
  2593. }
  2594. return res;
  2595. };
  2596. const isElementRoot = (vnode) => {
  2597. return (vnode.shapeFlag & (6 /* COMPONENT */ | 1 /* ELEMENT */) ||
  2598. vnode.type === Comment // potential v-if branch switch
  2599. );
  2600. };
  2601. function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
  2602. const { props: prevProps, children: prevChildren, component } = prevVNode;
  2603. const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
  2604. const emits = component.emitsOptions;
  2605. // Parent component's render function was hot-updated. Since this may have
  2606. // caused the child component's slots content to have changed, we need to
  2607. // force the child to update as well.
  2608. if ((prevChildren || nextChildren) && isHmrUpdating) {
  2609. return true;
  2610. }
  2611. // force child update for runtime directive or transition on component vnode.
  2612. if (nextVNode.dirs || nextVNode.transition) {
  2613. return true;
  2614. }
  2615. if (optimized && patchFlag >= 0) {
  2616. if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
  2617. // slot content that references values that might have changed,
  2618. // e.g. in a v-for
  2619. return true;
  2620. }
  2621. if (patchFlag & 16 /* FULL_PROPS */) {
  2622. if (!prevProps) {
  2623. return !!nextProps;
  2624. }
  2625. // presence of this flag indicates props are always non-null
  2626. return hasPropsChanged(prevProps, nextProps, emits);
  2627. }
  2628. else if (patchFlag & 8 /* PROPS */) {
  2629. const dynamicProps = nextVNode.dynamicProps;
  2630. for (let i = 0; i < dynamicProps.length; i++) {
  2631. const key = dynamicProps[i];
  2632. if (nextProps[key] !== prevProps[key] &&
  2633. !isEmitListener(emits, key)) {
  2634. return true;
  2635. }
  2636. }
  2637. }
  2638. }
  2639. else {
  2640. // this path is only taken by manually written render functions
  2641. // so presence of any children leads to a forced update
  2642. if (prevChildren || nextChildren) {
  2643. if (!nextChildren || !nextChildren.$stable) {
  2644. return true;
  2645. }
  2646. }
  2647. if (prevProps === nextProps) {
  2648. return false;
  2649. }
  2650. if (!prevProps) {
  2651. return !!nextProps;
  2652. }
  2653. if (!nextProps) {
  2654. return true;
  2655. }
  2656. return hasPropsChanged(prevProps, nextProps, emits);
  2657. }
  2658. return false;
  2659. }
  2660. function hasPropsChanged(prevProps, nextProps, emitsOptions) {
  2661. const nextKeys = Object.keys(nextProps);
  2662. if (nextKeys.length !== Object.keys(prevProps).length) {
  2663. return true;
  2664. }
  2665. for (let i = 0; i < nextKeys.length; i++) {
  2666. const key = nextKeys[i];
  2667. if (nextProps[key] !== prevProps[key] &&
  2668. !isEmitListener(emitsOptions, key)) {
  2669. return true;
  2670. }
  2671. }
  2672. return false;
  2673. }
  2674. function updateHOCHostEl({ vnode, parent }, el // HostNode
  2675. ) {
  2676. while (parent && parent.subTree === vnode) {
  2677. (vnode = parent.vnode).el = el;
  2678. parent = parent.parent;
  2679. }
  2680. }
  2681. const isSuspense = (type) => type.__isSuspense;
  2682. // Suspense exposes a component-like API, and is treated like a component
  2683. // in the compiler, but internally it's a special built-in type that hooks
  2684. // directly into the renderer.
  2685. const SuspenseImpl = {
  2686. name: 'Suspense',
  2687. // In order to make Suspense tree-shakable, we need to avoid importing it
  2688. // directly in the renderer. The renderer checks for the __isSuspense flag
  2689. // on a vnode's type and calls the `process` method, passing in renderer
  2690. // internals.
  2691. __isSuspense: true,
  2692. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
  2693. // platform-specific impl passed from renderer
  2694. rendererInternals) {
  2695. if (n1 == null) {
  2696. mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
  2697. }
  2698. else {
  2699. patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
  2700. }
  2701. },
  2702. hydrate: hydrateSuspense,
  2703. create: createSuspenseBoundary,
  2704. normalize: normalizeSuspenseChildren
  2705. };
  2706. // Force-casted public typing for h and TSX props inference
  2707. const Suspense = (SuspenseImpl );
  2708. function triggerEvent(vnode, name) {
  2709. const eventListener = vnode.props && vnode.props[name];
  2710. if (isFunction(eventListener)) {
  2711. eventListener();
  2712. }
  2713. }
  2714. function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
  2715. const { p: patch, o: { createElement } } = rendererInternals;
  2716. const hiddenContainer = createElement('div');
  2717. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
  2718. // start mounting the content subtree in an off-dom container
  2719. patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
  2720. // now check if we have encountered any async deps
  2721. if (suspense.deps > 0) {
  2722. // has async
  2723. // invoke @fallback event
  2724. triggerEvent(vnode, 'onPending');
  2725. triggerEvent(vnode, 'onFallback');
  2726. // mount the fallback tree
  2727. patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2728. isSVG, slotScopeIds);
  2729. setActiveBranch(suspense, vnode.ssFallback);
  2730. }
  2731. else {
  2732. // Suspense has no async deps. Just resolve.
  2733. suspense.resolve();
  2734. }
  2735. }
  2736. function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
  2737. const suspense = (n2.suspense = n1.suspense);
  2738. suspense.vnode = n2;
  2739. n2.el = n1.el;
  2740. const newBranch = n2.ssContent;
  2741. const newFallback = n2.ssFallback;
  2742. const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
  2743. if (pendingBranch) {
  2744. suspense.pendingBranch = newBranch;
  2745. if (isSameVNodeType(newBranch, pendingBranch)) {
  2746. // same root type but content may have changed.
  2747. patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2748. if (suspense.deps <= 0) {
  2749. suspense.resolve();
  2750. }
  2751. else if (isInFallback) {
  2752. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2753. isSVG, slotScopeIds, optimized);
  2754. setActiveBranch(suspense, newFallback);
  2755. }
  2756. }
  2757. else {
  2758. // toggled before pending tree is resolved
  2759. suspense.pendingId++;
  2760. if (isHydrating) {
  2761. // if toggled before hydration is finished, the current DOM tree is
  2762. // no longer valid. set it as the active branch so it will be unmounted
  2763. // when resolved
  2764. suspense.isHydrating = false;
  2765. suspense.activeBranch = pendingBranch;
  2766. }
  2767. else {
  2768. unmount(pendingBranch, parentComponent, suspense);
  2769. }
  2770. // increment pending ID. this is used to invalidate async callbacks
  2771. // reset suspense state
  2772. suspense.deps = 0;
  2773. // discard effects from pending branch
  2774. suspense.effects.length = 0;
  2775. // discard previous container
  2776. suspense.hiddenContainer = createElement('div');
  2777. if (isInFallback) {
  2778. // already in fallback state
  2779. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2780. if (suspense.deps <= 0) {
  2781. suspense.resolve();
  2782. }
  2783. else {
  2784. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2785. isSVG, slotScopeIds, optimized);
  2786. setActiveBranch(suspense, newFallback);
  2787. }
  2788. }
  2789. else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2790. // toggled "back" to current active branch
  2791. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2792. // force resolve
  2793. suspense.resolve(true);
  2794. }
  2795. else {
  2796. // switched to a 3rd branch
  2797. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2798. if (suspense.deps <= 0) {
  2799. suspense.resolve();
  2800. }
  2801. }
  2802. }
  2803. }
  2804. else {
  2805. if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2806. // root did not change, just normal patch
  2807. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2808. setActiveBranch(suspense, newBranch);
  2809. }
  2810. else {
  2811. // root node toggled
  2812. // invoke @pending event
  2813. triggerEvent(n2, 'onPending');
  2814. // mount pending branch in off-dom container
  2815. suspense.pendingBranch = newBranch;
  2816. suspense.pendingId++;
  2817. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2818. if (suspense.deps <= 0) {
  2819. // incoming branch has no async deps, resolve now.
  2820. suspense.resolve();
  2821. }
  2822. else {
  2823. const { timeout, pendingId } = suspense;
  2824. if (timeout > 0) {
  2825. setTimeout(() => {
  2826. if (suspense.pendingId === pendingId) {
  2827. suspense.fallback(newFallback);
  2828. }
  2829. }, timeout);
  2830. }
  2831. else if (timeout === 0) {
  2832. suspense.fallback(newFallback);
  2833. }
  2834. }
  2835. }
  2836. }
  2837. }
  2838. let hasWarned = false;
  2839. function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
  2840. /* istanbul ignore if */
  2841. if (!hasWarned) {
  2842. hasWarned = true;
  2843. // @ts-ignore `console.info` cannot be null error
  2844. console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
  2845. }
  2846. const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
  2847. const timeout = toNumber(vnode.props && vnode.props.timeout);
  2848. const suspense = {
  2849. vnode,
  2850. parent,
  2851. parentComponent,
  2852. isSVG,
  2853. container,
  2854. hiddenContainer,
  2855. anchor,
  2856. deps: 0,
  2857. pendingId: 0,
  2858. timeout: typeof timeout === 'number' ? timeout : -1,
  2859. activeBranch: null,
  2860. pendingBranch: null,
  2861. isInFallback: true,
  2862. isHydrating,
  2863. isUnmounted: false,
  2864. effects: [],
  2865. resolve(resume = false) {
  2866. {
  2867. if (!resume && !suspense.pendingBranch) {
  2868. throw new Error(`suspense.resolve() is called without a pending branch.`);
  2869. }
  2870. if (suspense.isUnmounted) {
  2871. throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
  2872. }
  2873. }
  2874. const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
  2875. if (suspense.isHydrating) {
  2876. suspense.isHydrating = false;
  2877. }
  2878. else if (!resume) {
  2879. const delayEnter = activeBranch &&
  2880. pendingBranch.transition &&
  2881. pendingBranch.transition.mode === 'out-in';
  2882. if (delayEnter) {
  2883. activeBranch.transition.afterLeave = () => {
  2884. if (pendingId === suspense.pendingId) {
  2885. move(pendingBranch, container, anchor, 0 /* ENTER */);
  2886. }
  2887. };
  2888. }
  2889. // this is initial anchor on mount
  2890. let { anchor } = suspense;
  2891. // unmount current active tree
  2892. if (activeBranch) {
  2893. // if the fallback tree was mounted, it may have been moved
  2894. // as part of a parent suspense. get the latest anchor for insertion
  2895. anchor = next(activeBranch);
  2896. unmount(activeBranch, parentComponent, suspense, true);
  2897. }
  2898. if (!delayEnter) {
  2899. // move content from off-dom container to actual container
  2900. move(pendingBranch, container, anchor, 0 /* ENTER */);
  2901. }
  2902. }
  2903. setActiveBranch(suspense, pendingBranch);
  2904. suspense.pendingBranch = null;
  2905. suspense.isInFallback = false;
  2906. // flush buffered effects
  2907. // check if there is a pending parent suspense
  2908. let parent = suspense.parent;
  2909. let hasUnresolvedAncestor = false;
  2910. while (parent) {
  2911. if (parent.pendingBranch) {
  2912. // found a pending parent suspense, merge buffered post jobs
  2913. // into that parent
  2914. parent.effects.push(...effects);
  2915. hasUnresolvedAncestor = true;
  2916. break;
  2917. }
  2918. parent = parent.parent;
  2919. }
  2920. // no pending parent suspense, flush all jobs
  2921. if (!hasUnresolvedAncestor) {
  2922. queuePostFlushCb(effects);
  2923. }
  2924. suspense.effects = [];
  2925. // invoke @resolve event
  2926. triggerEvent(vnode, 'onResolve');
  2927. },
  2928. fallback(fallbackVNode) {
  2929. if (!suspense.pendingBranch) {
  2930. return;
  2931. }
  2932. const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
  2933. // invoke @fallback event
  2934. triggerEvent(vnode, 'onFallback');
  2935. const anchor = next(activeBranch);
  2936. const mountFallback = () => {
  2937. if (!suspense.isInFallback) {
  2938. return;
  2939. }
  2940. // mount the fallback tree
  2941. patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2942. isSVG, slotScopeIds, optimized);
  2943. setActiveBranch(suspense, fallbackVNode);
  2944. };
  2945. const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
  2946. if (delayEnter) {
  2947. activeBranch.transition.afterLeave = mountFallback;
  2948. }
  2949. suspense.isInFallback = true;
  2950. // unmount current active branch
  2951. unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
  2952. true // shouldRemove
  2953. );
  2954. if (!delayEnter) {
  2955. mountFallback();
  2956. }
  2957. },
  2958. move(container, anchor, type) {
  2959. suspense.activeBranch &&
  2960. move(suspense.activeBranch, container, anchor, type);
  2961. suspense.container = container;
  2962. },
  2963. next() {
  2964. return suspense.activeBranch && next(suspense.activeBranch);
  2965. },
  2966. registerDep(instance, setupRenderEffect) {
  2967. const isInPendingSuspense = !!suspense.pendingBranch;
  2968. if (isInPendingSuspense) {
  2969. suspense.deps++;
  2970. }
  2971. const hydratedEl = instance.vnode.el;
  2972. instance
  2973. .asyncDep.catch(err => {
  2974. handleError(err, instance, 0 /* SETUP_FUNCTION */);
  2975. })
  2976. .then(asyncSetupResult => {
  2977. // retry when the setup() promise resolves.
  2978. // component may have been unmounted before resolve.
  2979. if (instance.isUnmounted ||
  2980. suspense.isUnmounted ||
  2981. suspense.pendingId !== instance.suspenseId) {
  2982. return;
  2983. }
  2984. // retry from this component
  2985. instance.asyncResolved = true;
  2986. const { vnode } = instance;
  2987. {
  2988. pushWarningContext(vnode);
  2989. }
  2990. handleSetupResult(instance, asyncSetupResult, false);
  2991. if (hydratedEl) {
  2992. // vnode may have been replaced if an update happened before the
  2993. // async dep is resolved.
  2994. vnode.el = hydratedEl;
  2995. }
  2996. const placeholder = !hydratedEl && instance.subTree.el;
  2997. setupRenderEffect(instance, vnode,
  2998. // component may have been moved before resolve.
  2999. // if this is not a hydration, instance.subTree will be the comment
  3000. // placeholder.
  3001. parentNode(hydratedEl || instance.subTree.el),
  3002. // anchor will not be used if this is hydration, so only need to
  3003. // consider the comment placeholder case.
  3004. hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
  3005. if (placeholder) {
  3006. remove(placeholder);
  3007. }
  3008. updateHOCHostEl(instance, vnode.el);
  3009. {
  3010. popWarningContext();
  3011. }
  3012. // only decrease deps count if suspense is not already resolved
  3013. if (isInPendingSuspense && --suspense.deps === 0) {
  3014. suspense.resolve();
  3015. }
  3016. });
  3017. },
  3018. unmount(parentSuspense, doRemove) {
  3019. suspense.isUnmounted = true;
  3020. if (suspense.activeBranch) {
  3021. unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
  3022. }
  3023. if (suspense.pendingBranch) {
  3024. unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
  3025. }
  3026. }
  3027. };
  3028. return suspense;
  3029. }
  3030. function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
  3031. /* eslint-disable no-restricted-globals */
  3032. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
  3033. // there are two possible scenarios for server-rendered suspense:
  3034. // - success: ssr content should be fully resolved
  3035. // - failure: ssr content should be the fallback branch.
  3036. // however, on the client we don't really know if it has failed or not
  3037. // attempt to hydrate the DOM assuming it has succeeded, but we still
  3038. // need to construct a suspense boundary first
  3039. const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
  3040. if (suspense.deps === 0) {
  3041. suspense.resolve();
  3042. }
  3043. return result;
  3044. /* eslint-enable no-restricted-globals */
  3045. }
  3046. function normalizeSuspenseChildren(vnode) {
  3047. const { shapeFlag, children } = vnode;
  3048. const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
  3049. vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
  3050. vnode.ssFallback = isSlotChildren
  3051. ? normalizeSuspenseSlot(children.fallback)
  3052. : createVNode(Comment);
  3053. }
  3054. function normalizeSuspenseSlot(s) {
  3055. let block;
  3056. if (isFunction(s)) {
  3057. const trackBlock = isBlockTreeEnabled && s._c;
  3058. if (trackBlock) {
  3059. // disableTracking: false
  3060. // allow block tracking for compiled slots
  3061. // (see ./componentRenderContext.ts)
  3062. s._d = false;
  3063. openBlock();
  3064. }
  3065. s = s();
  3066. if (trackBlock) {
  3067. s._d = true;
  3068. block = currentBlock;
  3069. closeBlock();
  3070. }
  3071. }
  3072. if (isArray(s)) {
  3073. const singleChild = filterSingleRoot(s);
  3074. if (!singleChild) {
  3075. warn$1(`<Suspense> slots expect a single root node.`);
  3076. }
  3077. s = singleChild;
  3078. }
  3079. s = normalizeVNode(s);
  3080. if (block && !s.dynamicChildren) {
  3081. s.dynamicChildren = block.filter(c => c !== s);
  3082. }
  3083. return s;
  3084. }
  3085. function queueEffectWithSuspense(fn, suspense) {
  3086. if (suspense && suspense.pendingBranch) {
  3087. if (isArray(fn)) {
  3088. suspense.effects.push(...fn);
  3089. }
  3090. else {
  3091. suspense.effects.push(fn);
  3092. }
  3093. }
  3094. else {
  3095. queuePostFlushCb(fn);
  3096. }
  3097. }
  3098. function setActiveBranch(suspense, branch) {
  3099. suspense.activeBranch = branch;
  3100. const { vnode, parentComponent } = suspense;
  3101. const el = (vnode.el = branch.el);
  3102. // in case suspense is the root node of a component,
  3103. // recursively update the HOC el
  3104. if (parentComponent && parentComponent.subTree === vnode) {
  3105. parentComponent.vnode.el = el;
  3106. updateHOCHostEl(parentComponent, el);
  3107. }
  3108. }
  3109. function provide(key, value) {
  3110. if (!currentInstance) {
  3111. {
  3112. warn$1(`provide() can only be used inside setup().`);
  3113. }
  3114. }
  3115. else {
  3116. let provides = currentInstance.provides;
  3117. // by default an instance inherits its parent's provides object
  3118. // but when it needs to provide values of its own, it creates its
  3119. // own provides object using parent provides object as prototype.
  3120. // this way in `inject` we can simply look up injections from direct
  3121. // parent and let the prototype chain do the work.
  3122. const parentProvides = currentInstance.parent && currentInstance.parent.provides;
  3123. if (parentProvides === provides) {
  3124. provides = currentInstance.provides = Object.create(parentProvides);
  3125. }
  3126. // TS doesn't allow symbol as index type
  3127. provides[key] = value;
  3128. }
  3129. }
  3130. function inject(key, defaultValue, treatDefaultAsFactory = false) {
  3131. // fallback to `currentRenderingInstance` so that this can be called in
  3132. // a functional component
  3133. const instance = currentInstance || currentRenderingInstance;
  3134. if (instance) {
  3135. // #2400
  3136. // to support `app.use` plugins,
  3137. // fallback to appContext's `provides` if the instance is at root
  3138. const provides = instance.parent == null
  3139. ? instance.vnode.appContext && instance.vnode.appContext.provides
  3140. : instance.parent.provides;
  3141. if (provides && key in provides) {
  3142. // TS doesn't allow symbol as index type
  3143. return provides[key];
  3144. }
  3145. else if (arguments.length > 1) {
  3146. return treatDefaultAsFactory && isFunction(defaultValue)
  3147. ? defaultValue.call(instance.proxy)
  3148. : defaultValue;
  3149. }
  3150. else {
  3151. warn$1(`injection "${String(key)}" not found.`);
  3152. }
  3153. }
  3154. else {
  3155. warn$1(`inject() can only be used inside setup() or functional components.`);
  3156. }
  3157. }
  3158. // Simple effect.
  3159. function watchEffect(effect, options) {
  3160. return doWatch(effect, null, options);
  3161. }
  3162. function watchPostEffect(effect, options) {
  3163. return doWatch(effect, null, (Object.assign(Object.assign({}, options), { flush: 'post' }) ));
  3164. }
  3165. function watchSyncEffect(effect, options) {
  3166. return doWatch(effect, null, (Object.assign(Object.assign({}, options), { flush: 'sync' }) ));
  3167. }
  3168. // initial value for watchers to trigger on undefined initial values
  3169. const INITIAL_WATCHER_VALUE = {};
  3170. // implementation
  3171. function watch(source, cb, options) {
  3172. if (!isFunction(cb)) {
  3173. warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
  3174. `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
  3175. `supports \`watch(source, cb, options?) signature.`);
  3176. }
  3177. return doWatch(source, cb, options);
  3178. }
  3179. function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
  3180. if (!cb) {
  3181. if (immediate !== undefined) {
  3182. warn$1(`watch() "immediate" option is only respected when using the ` +
  3183. `watch(source, callback, options?) signature.`);
  3184. }
  3185. if (deep !== undefined) {
  3186. warn$1(`watch() "deep" option is only respected when using the ` +
  3187. `watch(source, callback, options?) signature.`);
  3188. }
  3189. }
  3190. const warnInvalidSource = (s) => {
  3191. warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
  3192. `a reactive object, or an array of these types.`);
  3193. };
  3194. const instance = currentInstance;
  3195. let getter;
  3196. let forceTrigger = false;
  3197. let isMultiSource = false;
  3198. if (isRef(source)) {
  3199. getter = () => source.value;
  3200. forceTrigger = isShallow(source);
  3201. }
  3202. else if (isReactive(source)) {
  3203. getter = () => source;
  3204. deep = true;
  3205. }
  3206. else if (isArray(source)) {
  3207. isMultiSource = true;
  3208. forceTrigger = source.some(isReactive);
  3209. getter = () => source.map(s => {
  3210. if (isRef(s)) {
  3211. return s.value;
  3212. }
  3213. else if (isReactive(s)) {
  3214. return traverse(s);
  3215. }
  3216. else if (isFunction(s)) {
  3217. return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
  3218. }
  3219. else {
  3220. warnInvalidSource(s);
  3221. }
  3222. });
  3223. }
  3224. else if (isFunction(source)) {
  3225. if (cb) {
  3226. // getter with cb
  3227. getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
  3228. }
  3229. else {
  3230. // no cb -> simple effect
  3231. getter = () => {
  3232. if (instance && instance.isUnmounted) {
  3233. return;
  3234. }
  3235. if (cleanup) {
  3236. cleanup();
  3237. }
  3238. return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onCleanup]);
  3239. };
  3240. }
  3241. }
  3242. else {
  3243. getter = NOOP;
  3244. warnInvalidSource(source);
  3245. }
  3246. if (cb && deep) {
  3247. const baseGetter = getter;
  3248. getter = () => traverse(baseGetter());
  3249. }
  3250. let cleanup;
  3251. let onCleanup = (fn) => {
  3252. cleanup = effect.onStop = () => {
  3253. callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
  3254. };
  3255. };
  3256. let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
  3257. const job = () => {
  3258. if (!effect.active) {
  3259. return;
  3260. }
  3261. if (cb) {
  3262. // watch(source, cb)
  3263. const newValue = effect.run();
  3264. if (deep ||
  3265. forceTrigger ||
  3266. (isMultiSource
  3267. ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
  3268. : hasChanged(newValue, oldValue)) ||
  3269. (false )) {
  3270. // cleanup before running cb again
  3271. if (cleanup) {
  3272. cleanup();
  3273. }
  3274. callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
  3275. newValue,
  3276. // pass undefined as the old value when it's changed for the first time
  3277. oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
  3278. onCleanup
  3279. ]);
  3280. oldValue = newValue;
  3281. }
  3282. }
  3283. else {
  3284. // watchEffect
  3285. effect.run();
  3286. }
  3287. };
  3288. // important: mark the job as a watcher callback so that scheduler knows
  3289. // it is allowed to self-trigger (#1727)
  3290. job.allowRecurse = !!cb;
  3291. let scheduler;
  3292. if (flush === 'sync') {
  3293. scheduler = job; // the scheduler function gets called directly
  3294. }
  3295. else if (flush === 'post') {
  3296. scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
  3297. }
  3298. else {
  3299. // default: 'pre'
  3300. scheduler = () => {
  3301. if (!instance || instance.isMounted) {
  3302. queuePreFlushCb(job);
  3303. }
  3304. else {
  3305. // with 'pre' option, the first call must happen before
  3306. // the component is mounted so it is called synchronously.
  3307. job();
  3308. }
  3309. };
  3310. }
  3311. const effect = new ReactiveEffect(getter, scheduler);
  3312. {
  3313. effect.onTrack = onTrack;
  3314. effect.onTrigger = onTrigger;
  3315. }
  3316. // initial run
  3317. if (cb) {
  3318. if (immediate) {
  3319. job();
  3320. }
  3321. else {
  3322. oldValue = effect.run();
  3323. }
  3324. }
  3325. else if (flush === 'post') {
  3326. queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
  3327. }
  3328. else {
  3329. effect.run();
  3330. }
  3331. return () => {
  3332. effect.stop();
  3333. if (instance && instance.scope) {
  3334. remove(instance.scope.effects, effect);
  3335. }
  3336. };
  3337. }
  3338. // this.$watch
  3339. function instanceWatch(source, value, options) {
  3340. const publicThis = this.proxy;
  3341. const getter = isString(source)
  3342. ? source.includes('.')
  3343. ? createPathGetter(publicThis, source)
  3344. : () => publicThis[source]
  3345. : source.bind(publicThis, publicThis);
  3346. let cb;
  3347. if (isFunction(value)) {
  3348. cb = value;
  3349. }
  3350. else {
  3351. cb = value.handler;
  3352. options = value;
  3353. }
  3354. const cur = currentInstance;
  3355. setCurrentInstance(this);
  3356. const res = doWatch(getter, cb.bind(publicThis), options);
  3357. if (cur) {
  3358. setCurrentInstance(cur);
  3359. }
  3360. else {
  3361. unsetCurrentInstance();
  3362. }
  3363. return res;
  3364. }
  3365. function createPathGetter(ctx, path) {
  3366. const segments = path.split('.');
  3367. return () => {
  3368. let cur = ctx;
  3369. for (let i = 0; i < segments.length && cur; i++) {
  3370. cur = cur[segments[i]];
  3371. }
  3372. return cur;
  3373. };
  3374. }
  3375. function traverse(value, seen) {
  3376. if (!isObject(value) || value["__v_skip" /* SKIP */]) {
  3377. return value;
  3378. }
  3379. seen = seen || new Set();
  3380. if (seen.has(value)) {
  3381. return value;
  3382. }
  3383. seen.add(value);
  3384. if (isRef(value)) {
  3385. traverse(value.value, seen);
  3386. }
  3387. else if (isArray(value)) {
  3388. for (let i = 0; i < value.length; i++) {
  3389. traverse(value[i], seen);
  3390. }
  3391. }
  3392. else if (isSet(value) || isMap(value)) {
  3393. value.forEach((v) => {
  3394. traverse(v, seen);
  3395. });
  3396. }
  3397. else if (isPlainObject(value)) {
  3398. for (const key in value) {
  3399. traverse(value[key], seen);
  3400. }
  3401. }
  3402. return value;
  3403. }
  3404. function useTransitionState() {
  3405. const state = {
  3406. isMounted: false,
  3407. isLeaving: false,
  3408. isUnmounting: false,
  3409. leavingVNodes: new Map()
  3410. };
  3411. onMounted(() => {
  3412. state.isMounted = true;
  3413. });
  3414. onBeforeUnmount(() => {
  3415. state.isUnmounting = true;
  3416. });
  3417. return state;
  3418. }
  3419. const TransitionHookValidator = [Function, Array];
  3420. const BaseTransitionImpl = {
  3421. name: `BaseTransition`,
  3422. props: {
  3423. mode: String,
  3424. appear: Boolean,
  3425. persisted: Boolean,
  3426. // enter
  3427. onBeforeEnter: TransitionHookValidator,
  3428. onEnter: TransitionHookValidator,
  3429. onAfterEnter: TransitionHookValidator,
  3430. onEnterCancelled: TransitionHookValidator,
  3431. // leave
  3432. onBeforeLeave: TransitionHookValidator,
  3433. onLeave: TransitionHookValidator,
  3434. onAfterLeave: TransitionHookValidator,
  3435. onLeaveCancelled: TransitionHookValidator,
  3436. // appear
  3437. onBeforeAppear: TransitionHookValidator,
  3438. onAppear: TransitionHookValidator,
  3439. onAfterAppear: TransitionHookValidator,
  3440. onAppearCancelled: TransitionHookValidator
  3441. },
  3442. setup(props, { slots }) {
  3443. const instance = getCurrentInstance();
  3444. const state = useTransitionState();
  3445. let prevTransitionKey;
  3446. return () => {
  3447. const children = slots.default && getTransitionRawChildren(slots.default(), true);
  3448. if (!children || !children.length) {
  3449. return;
  3450. }
  3451. let child = children[0];
  3452. if (children.length > 1) {
  3453. let hasFound = false;
  3454. // locate first non-comment child
  3455. for (const c of children) {
  3456. if (c.type !== Comment) {
  3457. if (hasFound) {
  3458. // warn more than one non-comment child
  3459. warn$1('<transition> can only be used on a single element or component. ' +
  3460. 'Use <transition-group> for lists.');
  3461. break;
  3462. }
  3463. child = c;
  3464. hasFound = true;
  3465. }
  3466. }
  3467. }
  3468. // there's no need to track reactivity for these props so use the raw
  3469. // props for a bit better perf
  3470. const rawProps = toRaw(props);
  3471. const { mode } = rawProps;
  3472. // check mode
  3473. if (mode &&
  3474. mode !== 'in-out' &&
  3475. mode !== 'out-in' &&
  3476. mode !== 'default') {
  3477. warn$1(`invalid <transition> mode: ${mode}`);
  3478. }
  3479. if (state.isLeaving) {
  3480. return emptyPlaceholder(child);
  3481. }
  3482. // in the case of <transition><keep-alive/></transition>, we need to
  3483. // compare the type of the kept-alive children.
  3484. const innerChild = getKeepAliveChild(child);
  3485. if (!innerChild) {
  3486. return emptyPlaceholder(child);
  3487. }
  3488. const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
  3489. setTransitionHooks(innerChild, enterHooks);
  3490. const oldChild = instance.subTree;
  3491. const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
  3492. let transitionKeyChanged = false;
  3493. const { getTransitionKey } = innerChild.type;
  3494. if (getTransitionKey) {
  3495. const key = getTransitionKey();
  3496. if (prevTransitionKey === undefined) {
  3497. prevTransitionKey = key;
  3498. }
  3499. else if (key !== prevTransitionKey) {
  3500. prevTransitionKey = key;
  3501. transitionKeyChanged = true;
  3502. }
  3503. }
  3504. // handle mode
  3505. if (oldInnerChild &&
  3506. oldInnerChild.type !== Comment &&
  3507. (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
  3508. const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
  3509. // update old tree's hooks in case of dynamic transition
  3510. setTransitionHooks(oldInnerChild, leavingHooks);
  3511. // switching between different views
  3512. if (mode === 'out-in') {
  3513. state.isLeaving = true;
  3514. // return placeholder node and queue update when leave finishes
  3515. leavingHooks.afterLeave = () => {
  3516. state.isLeaving = false;
  3517. instance.update();
  3518. };
  3519. return emptyPlaceholder(child);
  3520. }
  3521. else if (mode === 'in-out' && innerChild.type !== Comment) {
  3522. leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
  3523. const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
  3524. leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
  3525. // early removal callback
  3526. el._leaveCb = () => {
  3527. earlyRemove();
  3528. el._leaveCb = undefined;
  3529. delete enterHooks.delayedLeave;
  3530. };
  3531. enterHooks.delayedLeave = delayedLeave;
  3532. };
  3533. }
  3534. }
  3535. return child;
  3536. };
  3537. }
  3538. };
  3539. // export the public type for h/tsx inference
  3540. // also to avoid inline import() in generated d.ts files
  3541. const BaseTransition = BaseTransitionImpl;
  3542. function getLeavingNodesForType(state, vnode) {
  3543. const { leavingVNodes } = state;
  3544. let leavingVNodesCache = leavingVNodes.get(vnode.type);
  3545. if (!leavingVNodesCache) {
  3546. leavingVNodesCache = Object.create(null);
  3547. leavingVNodes.set(vnode.type, leavingVNodesCache);
  3548. }
  3549. return leavingVNodesCache;
  3550. }
  3551. // The transition hooks are attached to the vnode as vnode.transition
  3552. // and will be called at appropriate timing in the renderer.
  3553. function resolveTransitionHooks(vnode, props, state, instance) {
  3554. const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
  3555. const key = String(vnode.key);
  3556. const leavingVNodesCache = getLeavingNodesForType(state, vnode);
  3557. const callHook = (hook, args) => {
  3558. hook &&
  3559. callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
  3560. };
  3561. const hooks = {
  3562. mode,
  3563. persisted,
  3564. beforeEnter(el) {
  3565. let hook = onBeforeEnter;
  3566. if (!state.isMounted) {
  3567. if (appear) {
  3568. hook = onBeforeAppear || onBeforeEnter;
  3569. }
  3570. else {
  3571. return;
  3572. }
  3573. }
  3574. // for same element (v-show)
  3575. if (el._leaveCb) {
  3576. el._leaveCb(true /* cancelled */);
  3577. }
  3578. // for toggled element with same key (v-if)
  3579. const leavingVNode = leavingVNodesCache[key];
  3580. if (leavingVNode &&
  3581. isSameVNodeType(vnode, leavingVNode) &&
  3582. leavingVNode.el._leaveCb) {
  3583. // force early removal (not cancelled)
  3584. leavingVNode.el._leaveCb();
  3585. }
  3586. callHook(hook, [el]);
  3587. },
  3588. enter(el) {
  3589. let hook = onEnter;
  3590. let afterHook = onAfterEnter;
  3591. let cancelHook = onEnterCancelled;
  3592. if (!state.isMounted) {
  3593. if (appear) {
  3594. hook = onAppear || onEnter;
  3595. afterHook = onAfterAppear || onAfterEnter;
  3596. cancelHook = onAppearCancelled || onEnterCancelled;
  3597. }
  3598. else {
  3599. return;
  3600. }
  3601. }
  3602. let called = false;
  3603. const done = (el._enterCb = (cancelled) => {
  3604. if (called)
  3605. return;
  3606. called = true;
  3607. if (cancelled) {
  3608. callHook(cancelHook, [el]);
  3609. }
  3610. else {
  3611. callHook(afterHook, [el]);
  3612. }
  3613. if (hooks.delayedLeave) {
  3614. hooks.delayedLeave();
  3615. }
  3616. el._enterCb = undefined;
  3617. });
  3618. if (hook) {
  3619. hook(el, done);
  3620. if (hook.length <= 1) {
  3621. done();
  3622. }
  3623. }
  3624. else {
  3625. done();
  3626. }
  3627. },
  3628. leave(el, remove) {
  3629. const key = String(vnode.key);
  3630. if (el._enterCb) {
  3631. el._enterCb(true /* cancelled */);
  3632. }
  3633. if (state.isUnmounting) {
  3634. return remove();
  3635. }
  3636. callHook(onBeforeLeave, [el]);
  3637. let called = false;
  3638. const done = (el._leaveCb = (cancelled) => {
  3639. if (called)
  3640. return;
  3641. called = true;
  3642. remove();
  3643. if (cancelled) {
  3644. callHook(onLeaveCancelled, [el]);
  3645. }
  3646. else {
  3647. callHook(onAfterLeave, [el]);
  3648. }
  3649. el._leaveCb = undefined;
  3650. if (leavingVNodesCache[key] === vnode) {
  3651. delete leavingVNodesCache[key];
  3652. }
  3653. });
  3654. leavingVNodesCache[key] = vnode;
  3655. if (onLeave) {
  3656. onLeave(el, done);
  3657. if (onLeave.length <= 1) {
  3658. done();
  3659. }
  3660. }
  3661. else {
  3662. done();
  3663. }
  3664. },
  3665. clone(vnode) {
  3666. return resolveTransitionHooks(vnode, props, state, instance);
  3667. }
  3668. };
  3669. return hooks;
  3670. }
  3671. // the placeholder really only handles one special case: KeepAlive
  3672. // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
  3673. // placeholder with empty content to avoid the KeepAlive instance from being
  3674. // unmounted.
  3675. function emptyPlaceholder(vnode) {
  3676. if (isKeepAlive(vnode)) {
  3677. vnode = cloneVNode(vnode);
  3678. vnode.children = null;
  3679. return vnode;
  3680. }
  3681. }
  3682. function getKeepAliveChild(vnode) {
  3683. return isKeepAlive(vnode)
  3684. ? vnode.children
  3685. ? vnode.children[0]
  3686. : undefined
  3687. : vnode;
  3688. }
  3689. function setTransitionHooks(vnode, hooks) {
  3690. if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
  3691. setTransitionHooks(vnode.component.subTree, hooks);
  3692. }
  3693. else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
  3694. vnode.ssContent.transition = hooks.clone(vnode.ssContent);
  3695. vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
  3696. }
  3697. else {
  3698. vnode.transition = hooks;
  3699. }
  3700. }
  3701. function getTransitionRawChildren(children, keepComment = false, parentKey) {
  3702. let ret = [];
  3703. let keyedFragmentCount = 0;
  3704. for (let i = 0; i < children.length; i++) {
  3705. let child = children[i];
  3706. // #5360 inherit parent key in case of <template v-for>
  3707. const key = parentKey == null
  3708. ? child.key
  3709. : String(parentKey) + String(child.key != null ? child.key : i);
  3710. // handle fragment children case, e.g. v-for
  3711. if (child.type === Fragment) {
  3712. if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
  3713. keyedFragmentCount++;
  3714. ret = ret.concat(getTransitionRawChildren(child.children, keepComment, key));
  3715. }
  3716. // comment placeholders should be skipped, e.g. v-if
  3717. else if (keepComment || child.type !== Comment) {
  3718. ret.push(key != null ? cloneVNode(child, { key }) : child);
  3719. }
  3720. }
  3721. // #1126 if a transition children list contains multiple sub fragments, these
  3722. // fragments will be merged into a flat children array. Since each v-for
  3723. // fragment may contain different static bindings inside, we need to de-op
  3724. // these children to force full diffs to ensure correct behavior.
  3725. if (keyedFragmentCount > 1) {
  3726. for (let i = 0; i < ret.length; i++) {
  3727. ret[i].patchFlag = -2 /* BAIL */;
  3728. }
  3729. }
  3730. return ret;
  3731. }
  3732. // implementation, close to no-op
  3733. function defineComponent(options) {
  3734. return isFunction(options) ? { setup: options, name: options.name } : options;
  3735. }
  3736. const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
  3737. function defineAsyncComponent(source) {
  3738. if (isFunction(source)) {
  3739. source = { loader: source };
  3740. }
  3741. const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
  3742. suspensible = true, onError: userOnError } = source;
  3743. let pendingRequest = null;
  3744. let resolvedComp;
  3745. let retries = 0;
  3746. const retry = () => {
  3747. retries++;
  3748. pendingRequest = null;
  3749. return load();
  3750. };
  3751. const load = () => {
  3752. let thisRequest;
  3753. return (pendingRequest ||
  3754. (thisRequest = pendingRequest =
  3755. loader()
  3756. .catch(err => {
  3757. err = err instanceof Error ? err : new Error(String(err));
  3758. if (userOnError) {
  3759. return new Promise((resolve, reject) => {
  3760. const userRetry = () => resolve(retry());
  3761. const userFail = () => reject(err);
  3762. userOnError(err, userRetry, userFail, retries + 1);
  3763. });
  3764. }
  3765. else {
  3766. throw err;
  3767. }
  3768. })
  3769. .then((comp) => {
  3770. if (thisRequest !== pendingRequest && pendingRequest) {
  3771. return pendingRequest;
  3772. }
  3773. if (!comp) {
  3774. warn$1(`Async component loader resolved to undefined. ` +
  3775. `If you are using retry(), make sure to return its return value.`);
  3776. }
  3777. // interop module default
  3778. if (comp &&
  3779. (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
  3780. comp = comp.default;
  3781. }
  3782. if (comp && !isObject(comp) && !isFunction(comp)) {
  3783. throw new Error(`Invalid async component load result: ${comp}`);
  3784. }
  3785. resolvedComp = comp;
  3786. return comp;
  3787. })));
  3788. };
  3789. return defineComponent({
  3790. name: 'AsyncComponentWrapper',
  3791. __asyncLoader: load,
  3792. get __asyncResolved() {
  3793. return resolvedComp;
  3794. },
  3795. setup() {
  3796. const instance = currentInstance;
  3797. // already resolved
  3798. if (resolvedComp) {
  3799. return () => createInnerComp(resolvedComp, instance);
  3800. }
  3801. const onError = (err) => {
  3802. pendingRequest = null;
  3803. handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
  3804. };
  3805. // suspense-controlled or SSR.
  3806. if ((suspensible && instance.suspense) ||
  3807. (false )) {
  3808. return load()
  3809. .then(comp => {
  3810. return () => createInnerComp(comp, instance);
  3811. })
  3812. .catch(err => {
  3813. onError(err);
  3814. return () => errorComponent
  3815. ? createVNode(errorComponent, {
  3816. error: err
  3817. })
  3818. : null;
  3819. });
  3820. }
  3821. const loaded = ref(false);
  3822. const error = ref();
  3823. const delayed = ref(!!delay);
  3824. if (delay) {
  3825. setTimeout(() => {
  3826. delayed.value = false;
  3827. }, delay);
  3828. }
  3829. if (timeout != null) {
  3830. setTimeout(() => {
  3831. if (!loaded.value && !error.value) {
  3832. const err = new Error(`Async component timed out after ${timeout}ms.`);
  3833. onError(err);
  3834. error.value = err;
  3835. }
  3836. }, timeout);
  3837. }
  3838. load()
  3839. .then(() => {
  3840. loaded.value = true;
  3841. if (instance.parent && isKeepAlive(instance.parent.vnode)) {
  3842. // parent is keep-alive, force update so the loaded component's
  3843. // name is taken into account
  3844. queueJob(instance.parent.update);
  3845. }
  3846. })
  3847. .catch(err => {
  3848. onError(err);
  3849. error.value = err;
  3850. });
  3851. return () => {
  3852. if (loaded.value && resolvedComp) {
  3853. return createInnerComp(resolvedComp, instance);
  3854. }
  3855. else if (error.value && errorComponent) {
  3856. return createVNode(errorComponent, {
  3857. error: error.value
  3858. });
  3859. }
  3860. else if (loadingComponent && !delayed.value) {
  3861. return createVNode(loadingComponent);
  3862. }
  3863. };
  3864. }
  3865. });
  3866. }
  3867. function createInnerComp(comp, { vnode: { ref, props, children } }) {
  3868. const vnode = createVNode(comp, props, children);
  3869. // ensure inner component inherits the async wrapper's ref owner
  3870. vnode.ref = ref;
  3871. return vnode;
  3872. }
  3873. const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
  3874. const KeepAliveImpl = {
  3875. name: `KeepAlive`,
  3876. // Marker for special handling inside the renderer. We are not using a ===
  3877. // check directly on KeepAlive in the renderer, because importing it directly
  3878. // would prevent it from being tree-shaken.
  3879. __isKeepAlive: true,
  3880. props: {
  3881. include: [String, RegExp, Array],
  3882. exclude: [String, RegExp, Array],
  3883. max: [String, Number]
  3884. },
  3885. setup(props, { slots }) {
  3886. const instance = getCurrentInstance();
  3887. // KeepAlive communicates with the instantiated renderer via the
  3888. // ctx where the renderer passes in its internals,
  3889. // and the KeepAlive instance exposes activate/deactivate implementations.
  3890. // The whole point of this is to avoid importing KeepAlive directly in the
  3891. // renderer to facilitate tree-shaking.
  3892. const sharedContext = instance.ctx;
  3893. // if the internal renderer is not registered, it indicates that this is server-side rendering,
  3894. // for KeepAlive, we just need to render its children
  3895. if (!sharedContext.renderer) {
  3896. return slots.default;
  3897. }
  3898. const cache = new Map();
  3899. const keys = new Set();
  3900. let current = null;
  3901. {
  3902. instance.__v_cache = cache;
  3903. }
  3904. const parentSuspense = instance.suspense;
  3905. const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
  3906. const storageContainer = createElement('div');
  3907. sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
  3908. const instance = vnode.component;
  3909. move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
  3910. // in case props have changed
  3911. patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
  3912. queuePostRenderEffect(() => {
  3913. instance.isDeactivated = false;
  3914. if (instance.a) {
  3915. invokeArrayFns(instance.a);
  3916. }
  3917. const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
  3918. if (vnodeHook) {
  3919. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3920. }
  3921. }, parentSuspense);
  3922. {
  3923. // Update components tree
  3924. devtoolsComponentAdded(instance);
  3925. }
  3926. };
  3927. sharedContext.deactivate = (vnode) => {
  3928. const instance = vnode.component;
  3929. move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
  3930. queuePostRenderEffect(() => {
  3931. if (instance.da) {
  3932. invokeArrayFns(instance.da);
  3933. }
  3934. const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
  3935. if (vnodeHook) {
  3936. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3937. }
  3938. instance.isDeactivated = true;
  3939. }, parentSuspense);
  3940. {
  3941. // Update components tree
  3942. devtoolsComponentAdded(instance);
  3943. }
  3944. };
  3945. function unmount(vnode) {
  3946. // reset the shapeFlag so it can be properly unmounted
  3947. resetShapeFlag(vnode);
  3948. _unmount(vnode, instance, parentSuspense, true);
  3949. }
  3950. function pruneCache(filter) {
  3951. cache.forEach((vnode, key) => {
  3952. const name = getComponentName(vnode.type);
  3953. if (name && (!filter || !filter(name))) {
  3954. pruneCacheEntry(key);
  3955. }
  3956. });
  3957. }
  3958. function pruneCacheEntry(key) {
  3959. const cached = cache.get(key);
  3960. if (!current || cached.type !== current.type) {
  3961. unmount(cached);
  3962. }
  3963. else if (current) {
  3964. // current active instance should no longer be kept-alive.
  3965. // we can't unmount it now but it might be later, so reset its flag now.
  3966. resetShapeFlag(current);
  3967. }
  3968. cache.delete(key);
  3969. keys.delete(key);
  3970. }
  3971. // prune cache on include/exclude prop change
  3972. watch(() => [props.include, props.exclude], ([include, exclude]) => {
  3973. include && pruneCache(name => matches(include, name));
  3974. exclude && pruneCache(name => !matches(exclude, name));
  3975. },
  3976. // prune post-render after `current` has been updated
  3977. { flush: 'post', deep: true });
  3978. // cache sub tree after render
  3979. let pendingCacheKey = null;
  3980. const cacheSubtree = () => {
  3981. // fix #1621, the pendingCacheKey could be 0
  3982. if (pendingCacheKey != null) {
  3983. cache.set(pendingCacheKey, getInnerChild(instance.subTree));
  3984. }
  3985. };
  3986. onMounted(cacheSubtree);
  3987. onUpdated(cacheSubtree);
  3988. onBeforeUnmount(() => {
  3989. cache.forEach(cached => {
  3990. const { subTree, suspense } = instance;
  3991. const vnode = getInnerChild(subTree);
  3992. if (cached.type === vnode.type) {
  3993. // current instance will be unmounted as part of keep-alive's unmount
  3994. resetShapeFlag(vnode);
  3995. // but invoke its deactivated hook here
  3996. const da = vnode.component.da;
  3997. da && queuePostRenderEffect(da, suspense);
  3998. return;
  3999. }
  4000. unmount(cached);
  4001. });
  4002. });
  4003. return () => {
  4004. pendingCacheKey = null;
  4005. if (!slots.default) {
  4006. return null;
  4007. }
  4008. const children = slots.default();
  4009. const rawVNode = children[0];
  4010. if (children.length > 1) {
  4011. {
  4012. warn$1(`KeepAlive should contain exactly one component child.`);
  4013. }
  4014. current = null;
  4015. return children;
  4016. }
  4017. else if (!isVNode(rawVNode) ||
  4018. (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
  4019. !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
  4020. current = null;
  4021. return rawVNode;
  4022. }
  4023. let vnode = getInnerChild(rawVNode);
  4024. const comp = vnode.type;
  4025. // for async components, name check should be based in its loaded
  4026. // inner component if available
  4027. const name = getComponentName(isAsyncWrapper(vnode)
  4028. ? vnode.type.__asyncResolved || {}
  4029. : comp);
  4030. const { include, exclude, max } = props;
  4031. if ((include && (!name || !matches(include, name))) ||
  4032. (exclude && name && matches(exclude, name))) {
  4033. current = vnode;
  4034. return rawVNode;
  4035. }
  4036. const key = vnode.key == null ? comp : vnode.key;
  4037. const cachedVNode = cache.get(key);
  4038. // clone vnode if it's reused because we are going to mutate it
  4039. if (vnode.el) {
  4040. vnode = cloneVNode(vnode);
  4041. if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
  4042. rawVNode.ssContent = vnode;
  4043. }
  4044. }
  4045. // #1513 it's possible for the returned vnode to be cloned due to attr
  4046. // fallthrough or scopeId, so the vnode here may not be the final vnode
  4047. // that is mounted. Instead of caching it directly, we store the pending
  4048. // key and cache `instance.subTree` (the normalized vnode) in
  4049. // beforeMount/beforeUpdate hooks.
  4050. pendingCacheKey = key;
  4051. if (cachedVNode) {
  4052. // copy over mounted state
  4053. vnode.el = cachedVNode.el;
  4054. vnode.component = cachedVNode.component;
  4055. if (vnode.transition) {
  4056. // recursively update transition hooks on subTree
  4057. setTransitionHooks(vnode, vnode.transition);
  4058. }
  4059. // avoid vnode being mounted as fresh
  4060. vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
  4061. // make this key the freshest
  4062. keys.delete(key);
  4063. keys.add(key);
  4064. }
  4065. else {
  4066. keys.add(key);
  4067. // prune oldest entry
  4068. if (max && keys.size > parseInt(max, 10)) {
  4069. pruneCacheEntry(keys.values().next().value);
  4070. }
  4071. }
  4072. // avoid vnode being unmounted
  4073. vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
  4074. current = vnode;
  4075. return rawVNode;
  4076. };
  4077. }
  4078. };
  4079. // export the public type for h/tsx inference
  4080. // also to avoid inline import() in generated d.ts files
  4081. const KeepAlive = KeepAliveImpl;
  4082. function matches(pattern, name) {
  4083. if (isArray(pattern)) {
  4084. return pattern.some((p) => matches(p, name));
  4085. }
  4086. else if (isString(pattern)) {
  4087. return pattern.split(',').includes(name);
  4088. }
  4089. else if (pattern.test) {
  4090. return pattern.test(name);
  4091. }
  4092. /* istanbul ignore next */
  4093. return false;
  4094. }
  4095. function onActivated(hook, target) {
  4096. registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
  4097. }
  4098. function onDeactivated(hook, target) {
  4099. registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
  4100. }
  4101. function registerKeepAliveHook(hook, type, target = currentInstance) {
  4102. // cache the deactivate branch check wrapper for injected hooks so the same
  4103. // hook can be properly deduped by the scheduler. "__wdc" stands for "with
  4104. // deactivation check".
  4105. const wrappedHook = hook.__wdc ||
  4106. (hook.__wdc = () => {
  4107. // only fire the hook if the target instance is NOT in a deactivated branch.
  4108. let current = target;
  4109. while (current) {
  4110. if (current.isDeactivated) {
  4111. return;
  4112. }
  4113. current = current.parent;
  4114. }
  4115. return hook();
  4116. });
  4117. injectHook(type, wrappedHook, target);
  4118. // In addition to registering it on the target instance, we walk up the parent
  4119. // chain and register it on all ancestor instances that are keep-alive roots.
  4120. // This avoids the need to walk the entire component tree when invoking these
  4121. // hooks, and more importantly, avoids the need to track child components in
  4122. // arrays.
  4123. if (target) {
  4124. let current = target.parent;
  4125. while (current && current.parent) {
  4126. if (isKeepAlive(current.parent.vnode)) {
  4127. injectToKeepAliveRoot(wrappedHook, type, target, current);
  4128. }
  4129. current = current.parent;
  4130. }
  4131. }
  4132. }
  4133. function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
  4134. // injectHook wraps the original for error handling, so make sure to remove
  4135. // the wrapped version.
  4136. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
  4137. onUnmounted(() => {
  4138. remove(keepAliveRoot[type], injected);
  4139. }, target);
  4140. }
  4141. function resetShapeFlag(vnode) {
  4142. let shapeFlag = vnode.shapeFlag;
  4143. if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  4144. shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
  4145. }
  4146. if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
  4147. shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
  4148. }
  4149. vnode.shapeFlag = shapeFlag;
  4150. }
  4151. function getInnerChild(vnode) {
  4152. return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
  4153. }
  4154. function injectHook(type, hook, target = currentInstance, prepend = false) {
  4155. if (target) {
  4156. const hooks = target[type] || (target[type] = []);
  4157. // cache the error handling wrapper for injected hooks so the same hook
  4158. // can be properly deduped by the scheduler. "__weh" stands for "with error
  4159. // handling".
  4160. const wrappedHook = hook.__weh ||
  4161. (hook.__weh = (...args) => {
  4162. if (target.isUnmounted) {
  4163. return;
  4164. }
  4165. // disable tracking inside all lifecycle hooks
  4166. // since they can potentially be called inside effects.
  4167. pauseTracking();
  4168. // Set currentInstance during hook invocation.
  4169. // This assumes the hook does not synchronously trigger other hooks, which
  4170. // can only be false when the user does something really funky.
  4171. setCurrentInstance(target);
  4172. const res = callWithAsyncErrorHandling(hook, target, type, args);
  4173. unsetCurrentInstance();
  4174. resetTracking();
  4175. return res;
  4176. });
  4177. if (prepend) {
  4178. hooks.unshift(wrappedHook);
  4179. }
  4180. else {
  4181. hooks.push(wrappedHook);
  4182. }
  4183. return wrappedHook;
  4184. }
  4185. else {
  4186. const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
  4187. warn$1(`${apiName} is called when there is no active component instance to be ` +
  4188. `associated with. ` +
  4189. `Lifecycle injection APIs can only be used during execution of setup().` +
  4190. (` If you are using async setup(), make sure to register lifecycle ` +
  4191. `hooks before the first await statement.`
  4192. ));
  4193. }
  4194. }
  4195. const createHook = (lifecycle) => (hook, target = currentInstance) =>
  4196. // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
  4197. (!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
  4198. injectHook(lifecycle, hook, target);
  4199. const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
  4200. const onMounted = createHook("m" /* MOUNTED */);
  4201. const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
  4202. const onUpdated = createHook("u" /* UPDATED */);
  4203. const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
  4204. const onUnmounted = createHook("um" /* UNMOUNTED */);
  4205. const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
  4206. const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
  4207. const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
  4208. function onErrorCaptured(hook, target = currentInstance) {
  4209. injectHook("ec" /* ERROR_CAPTURED */, hook, target);
  4210. }
  4211. function createDuplicateChecker() {
  4212. const cache = Object.create(null);
  4213. return (type, key) => {
  4214. if (cache[key]) {
  4215. warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
  4216. }
  4217. else {
  4218. cache[key] = type;
  4219. }
  4220. };
  4221. }
  4222. let shouldCacheAccess = true;
  4223. function applyOptions(instance) {
  4224. const options = resolveMergedOptions(instance);
  4225. const publicThis = instance.proxy;
  4226. const ctx = instance.ctx;
  4227. // do not cache property access on public proxy during state initialization
  4228. shouldCacheAccess = false;
  4229. // call beforeCreate first before accessing other options since
  4230. // the hook may mutate resolved options (#2791)
  4231. if (options.beforeCreate) {
  4232. callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
  4233. }
  4234. const {
  4235. // state
  4236. data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
  4237. // lifecycle
  4238. created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
  4239. // public API
  4240. expose, inheritAttrs,
  4241. // assets
  4242. components, directives, filters } = options;
  4243. const checkDuplicateProperties = createDuplicateChecker() ;
  4244. {
  4245. const [propsOptions] = instance.propsOptions;
  4246. if (propsOptions) {
  4247. for (const key in propsOptions) {
  4248. checkDuplicateProperties("Props" /* PROPS */, key);
  4249. }
  4250. }
  4251. }
  4252. // options initialization order (to be consistent with Vue 2):
  4253. // - props (already done outside of this function)
  4254. // - inject
  4255. // - methods
  4256. // - data (deferred since it relies on `this` access)
  4257. // - computed
  4258. // - watch (deferred since it relies on `this` access)
  4259. if (injectOptions) {
  4260. resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
  4261. }
  4262. if (methods) {
  4263. for (const key in methods) {
  4264. const methodHandler = methods[key];
  4265. if (isFunction(methodHandler)) {
  4266. // In dev mode, we use the `createRenderContext` function to define
  4267. // methods to the proxy target, and those are read-only but
  4268. // reconfigurable, so it needs to be redefined here
  4269. {
  4270. Object.defineProperty(ctx, key, {
  4271. value: methodHandler.bind(publicThis),
  4272. configurable: true,
  4273. enumerable: true,
  4274. writable: true
  4275. });
  4276. }
  4277. {
  4278. checkDuplicateProperties("Methods" /* METHODS */, key);
  4279. }
  4280. }
  4281. else {
  4282. warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
  4283. `Did you reference the function correctly?`);
  4284. }
  4285. }
  4286. }
  4287. if (dataOptions) {
  4288. if (!isFunction(dataOptions)) {
  4289. warn$1(`The data option must be a function. ` +
  4290. `Plain object usage is no longer supported.`);
  4291. }
  4292. const data = dataOptions.call(publicThis, publicThis);
  4293. if (isPromise(data)) {
  4294. warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
  4295. `intend to perform data fetching before component renders, use ` +
  4296. `async setup() + <Suspense>.`);
  4297. }
  4298. if (!isObject(data)) {
  4299. warn$1(`data() should return an object.`);
  4300. }
  4301. else {
  4302. instance.data = reactive(data);
  4303. {
  4304. for (const key in data) {
  4305. checkDuplicateProperties("Data" /* DATA */, key);
  4306. // expose data on ctx during dev
  4307. if (key[0] !== '$' && key[0] !== '_') {
  4308. Object.defineProperty(ctx, key, {
  4309. configurable: true,
  4310. enumerable: true,
  4311. get: () => data[key],
  4312. set: NOOP
  4313. });
  4314. }
  4315. }
  4316. }
  4317. }
  4318. }
  4319. // state initialization complete at this point - start caching access
  4320. shouldCacheAccess = true;
  4321. if (computedOptions) {
  4322. for (const key in computedOptions) {
  4323. const opt = computedOptions[key];
  4324. const get = isFunction(opt)
  4325. ? opt.bind(publicThis, publicThis)
  4326. : isFunction(opt.get)
  4327. ? opt.get.bind(publicThis, publicThis)
  4328. : NOOP;
  4329. if (get === NOOP) {
  4330. warn$1(`Computed property "${key}" has no getter.`);
  4331. }
  4332. const set = !isFunction(opt) && isFunction(opt.set)
  4333. ? opt.set.bind(publicThis)
  4334. : () => {
  4335. warn$1(`Write operation failed: computed property "${key}" is readonly.`);
  4336. }
  4337. ;
  4338. const c = computed$1({
  4339. get,
  4340. set
  4341. });
  4342. Object.defineProperty(ctx, key, {
  4343. enumerable: true,
  4344. configurable: true,
  4345. get: () => c.value,
  4346. set: v => (c.value = v)
  4347. });
  4348. {
  4349. checkDuplicateProperties("Computed" /* COMPUTED */, key);
  4350. }
  4351. }
  4352. }
  4353. if (watchOptions) {
  4354. for (const key in watchOptions) {
  4355. createWatcher(watchOptions[key], ctx, publicThis, key);
  4356. }
  4357. }
  4358. if (provideOptions) {
  4359. const provides = isFunction(provideOptions)
  4360. ? provideOptions.call(publicThis)
  4361. : provideOptions;
  4362. Reflect.ownKeys(provides).forEach(key => {
  4363. provide(key, provides[key]);
  4364. });
  4365. }
  4366. if (created) {
  4367. callHook(created, instance, "c" /* CREATED */);
  4368. }
  4369. function registerLifecycleHook(register, hook) {
  4370. if (isArray(hook)) {
  4371. hook.forEach(_hook => register(_hook.bind(publicThis)));
  4372. }
  4373. else if (hook) {
  4374. register(hook.bind(publicThis));
  4375. }
  4376. }
  4377. registerLifecycleHook(onBeforeMount, beforeMount);
  4378. registerLifecycleHook(onMounted, mounted);
  4379. registerLifecycleHook(onBeforeUpdate, beforeUpdate);
  4380. registerLifecycleHook(onUpdated, updated);
  4381. registerLifecycleHook(onActivated, activated);
  4382. registerLifecycleHook(onDeactivated, deactivated);
  4383. registerLifecycleHook(onErrorCaptured, errorCaptured);
  4384. registerLifecycleHook(onRenderTracked, renderTracked);
  4385. registerLifecycleHook(onRenderTriggered, renderTriggered);
  4386. registerLifecycleHook(onBeforeUnmount, beforeUnmount);
  4387. registerLifecycleHook(onUnmounted, unmounted);
  4388. registerLifecycleHook(onServerPrefetch, serverPrefetch);
  4389. if (isArray(expose)) {
  4390. if (expose.length) {
  4391. const exposed = instance.exposed || (instance.exposed = {});
  4392. expose.forEach(key => {
  4393. Object.defineProperty(exposed, key, {
  4394. get: () => publicThis[key],
  4395. set: val => (publicThis[key] = val)
  4396. });
  4397. });
  4398. }
  4399. else if (!instance.exposed) {
  4400. instance.exposed = {};
  4401. }
  4402. }
  4403. // options that are handled when creating the instance but also need to be
  4404. // applied from mixins
  4405. if (render && instance.render === NOOP) {
  4406. instance.render = render;
  4407. }
  4408. if (inheritAttrs != null) {
  4409. instance.inheritAttrs = inheritAttrs;
  4410. }
  4411. // asset options.
  4412. if (components)
  4413. instance.components = components;
  4414. if (directives)
  4415. instance.directives = directives;
  4416. }
  4417. function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
  4418. if (isArray(injectOptions)) {
  4419. injectOptions = normalizeInject(injectOptions);
  4420. }
  4421. for (const key in injectOptions) {
  4422. const opt = injectOptions[key];
  4423. let injected;
  4424. if (isObject(opt)) {
  4425. if ('default' in opt) {
  4426. injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
  4427. }
  4428. else {
  4429. injected = inject(opt.from || key);
  4430. }
  4431. }
  4432. else {
  4433. injected = inject(opt);
  4434. }
  4435. if (isRef(injected)) {
  4436. // TODO remove the check in 3.3
  4437. if (unwrapRef) {
  4438. Object.defineProperty(ctx, key, {
  4439. enumerable: true,
  4440. configurable: true,
  4441. get: () => injected.value,
  4442. set: v => (injected.value = v)
  4443. });
  4444. }
  4445. else {
  4446. {
  4447. warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
  4448. `and no longer needs \`.value\` in the next minor release. ` +
  4449. `To opt-in to the new behavior now, ` +
  4450. `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
  4451. `temporary and will not be needed in the future.)`);
  4452. }
  4453. ctx[key] = injected;
  4454. }
  4455. }
  4456. else {
  4457. ctx[key] = injected;
  4458. }
  4459. {
  4460. checkDuplicateProperties("Inject" /* INJECT */, key);
  4461. }
  4462. }
  4463. }
  4464. function callHook(hook, instance, type) {
  4465. callWithAsyncErrorHandling(isArray(hook)
  4466. ? hook.map(h => h.bind(instance.proxy))
  4467. : hook.bind(instance.proxy), instance, type);
  4468. }
  4469. function createWatcher(raw, ctx, publicThis, key) {
  4470. const getter = key.includes('.')
  4471. ? createPathGetter(publicThis, key)
  4472. : () => publicThis[key];
  4473. if (isString(raw)) {
  4474. const handler = ctx[raw];
  4475. if (isFunction(handler)) {
  4476. watch(getter, handler);
  4477. }
  4478. else {
  4479. warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
  4480. }
  4481. }
  4482. else if (isFunction(raw)) {
  4483. watch(getter, raw.bind(publicThis));
  4484. }
  4485. else if (isObject(raw)) {
  4486. if (isArray(raw)) {
  4487. raw.forEach(r => createWatcher(r, ctx, publicThis, key));
  4488. }
  4489. else {
  4490. const handler = isFunction(raw.handler)
  4491. ? raw.handler.bind(publicThis)
  4492. : ctx[raw.handler];
  4493. if (isFunction(handler)) {
  4494. watch(getter, handler, raw);
  4495. }
  4496. else {
  4497. warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
  4498. }
  4499. }
  4500. }
  4501. else {
  4502. warn$1(`Invalid watch option: "${key}"`, raw);
  4503. }
  4504. }
  4505. /**
  4506. * Resolve merged options and cache it on the component.
  4507. * This is done only once per-component since the merging does not involve
  4508. * instances.
  4509. */
  4510. function resolveMergedOptions(instance) {
  4511. const base = instance.type;
  4512. const { mixins, extends: extendsOptions } = base;
  4513. const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
  4514. const cached = cache.get(base);
  4515. let resolved;
  4516. if (cached) {
  4517. resolved = cached;
  4518. }
  4519. else if (!globalMixins.length && !mixins && !extendsOptions) {
  4520. {
  4521. resolved = base;
  4522. }
  4523. }
  4524. else {
  4525. resolved = {};
  4526. if (globalMixins.length) {
  4527. globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
  4528. }
  4529. mergeOptions(resolved, base, optionMergeStrategies);
  4530. }
  4531. cache.set(base, resolved);
  4532. return resolved;
  4533. }
  4534. function mergeOptions(to, from, strats, asMixin = false) {
  4535. const { mixins, extends: extendsOptions } = from;
  4536. if (extendsOptions) {
  4537. mergeOptions(to, extendsOptions, strats, true);
  4538. }
  4539. if (mixins) {
  4540. mixins.forEach((m) => mergeOptions(to, m, strats, true));
  4541. }
  4542. for (const key in from) {
  4543. if (asMixin && key === 'expose') {
  4544. warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
  4545. `It should only be declared in the base component itself.`);
  4546. }
  4547. else {
  4548. const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
  4549. to[key] = strat ? strat(to[key], from[key]) : from[key];
  4550. }
  4551. }
  4552. return to;
  4553. }
  4554. const internalOptionMergeStrats = {
  4555. data: mergeDataFn,
  4556. props: mergeObjectOptions,
  4557. emits: mergeObjectOptions,
  4558. // objects
  4559. methods: mergeObjectOptions,
  4560. computed: mergeObjectOptions,
  4561. // lifecycle
  4562. beforeCreate: mergeAsArray,
  4563. created: mergeAsArray,
  4564. beforeMount: mergeAsArray,
  4565. mounted: mergeAsArray,
  4566. beforeUpdate: mergeAsArray,
  4567. updated: mergeAsArray,
  4568. beforeDestroy: mergeAsArray,
  4569. beforeUnmount: mergeAsArray,
  4570. destroyed: mergeAsArray,
  4571. unmounted: mergeAsArray,
  4572. activated: mergeAsArray,
  4573. deactivated: mergeAsArray,
  4574. errorCaptured: mergeAsArray,
  4575. serverPrefetch: mergeAsArray,
  4576. // assets
  4577. components: mergeObjectOptions,
  4578. directives: mergeObjectOptions,
  4579. // watch
  4580. watch: mergeWatchOptions,
  4581. // provide / inject
  4582. provide: mergeDataFn,
  4583. inject: mergeInject
  4584. };
  4585. function mergeDataFn(to, from) {
  4586. if (!from) {
  4587. return to;
  4588. }
  4589. if (!to) {
  4590. return from;
  4591. }
  4592. return function mergedDataFn() {
  4593. return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
  4594. };
  4595. }
  4596. function mergeInject(to, from) {
  4597. return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
  4598. }
  4599. function normalizeInject(raw) {
  4600. if (isArray(raw)) {
  4601. const res = {};
  4602. for (let i = 0; i < raw.length; i++) {
  4603. res[raw[i]] = raw[i];
  4604. }
  4605. return res;
  4606. }
  4607. return raw;
  4608. }
  4609. function mergeAsArray(to, from) {
  4610. return to ? [...new Set([].concat(to, from))] : from;
  4611. }
  4612. function mergeObjectOptions(to, from) {
  4613. return to ? extend(extend(Object.create(null), to), from) : from;
  4614. }
  4615. function mergeWatchOptions(to, from) {
  4616. if (!to)
  4617. return from;
  4618. if (!from)
  4619. return to;
  4620. const merged = extend(Object.create(null), to);
  4621. for (const key in from) {
  4622. merged[key] = mergeAsArray(to[key], from[key]);
  4623. }
  4624. return merged;
  4625. }
  4626. function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
  4627. isSSR = false) {
  4628. const props = {};
  4629. const attrs = {};
  4630. def(attrs, InternalObjectKey, 1);
  4631. instance.propsDefaults = Object.create(null);
  4632. setFullProps(instance, rawProps, props, attrs);
  4633. // ensure all declared prop keys are present
  4634. for (const key in instance.propsOptions[0]) {
  4635. if (!(key in props)) {
  4636. props[key] = undefined;
  4637. }
  4638. }
  4639. // validation
  4640. {
  4641. validateProps(rawProps || {}, props, instance);
  4642. }
  4643. if (isStateful) {
  4644. // stateful
  4645. instance.props = isSSR ? props : shallowReactive(props);
  4646. }
  4647. else {
  4648. if (!instance.type.props) {
  4649. // functional w/ optional props, props === attrs
  4650. instance.props = attrs;
  4651. }
  4652. else {
  4653. // functional w/ declared props
  4654. instance.props = props;
  4655. }
  4656. }
  4657. instance.attrs = attrs;
  4658. }
  4659. function updateProps(instance, rawProps, rawPrevProps, optimized) {
  4660. const { props, attrs, vnode: { patchFlag } } = instance;
  4661. const rawCurrentProps = toRaw(props);
  4662. const [options] = instance.propsOptions;
  4663. let hasAttrsChanged = false;
  4664. if (
  4665. // always force full diff in dev
  4666. // - #1942 if hmr is enabled with sfc component
  4667. // - vite#872 non-sfc component used by sfc component
  4668. !((instance.type.__hmrId ||
  4669. (instance.parent && instance.parent.type.__hmrId))) &&
  4670. (optimized || patchFlag > 0) &&
  4671. !(patchFlag & 16 /* FULL_PROPS */)) {
  4672. if (patchFlag & 8 /* PROPS */) {
  4673. // Compiler-generated props & no keys change, just set the updated
  4674. // the props.
  4675. const propsToUpdate = instance.vnode.dynamicProps;
  4676. for (let i = 0; i < propsToUpdate.length; i++) {
  4677. let key = propsToUpdate[i];
  4678. // skip if the prop key is a declared emit event listener
  4679. if (isEmitListener(instance.emitsOptions, key)) {
  4680. continue;
  4681. }
  4682. // PROPS flag guarantees rawProps to be non-null
  4683. const value = rawProps[key];
  4684. if (options) {
  4685. // attr / props separation was done on init and will be consistent
  4686. // in this code path, so just check if attrs have it.
  4687. if (hasOwn(attrs, key)) {
  4688. if (value !== attrs[key]) {
  4689. attrs[key] = value;
  4690. hasAttrsChanged = true;
  4691. }
  4692. }
  4693. else {
  4694. const camelizedKey = camelize(key);
  4695. props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
  4696. }
  4697. }
  4698. else {
  4699. if (value !== attrs[key]) {
  4700. attrs[key] = value;
  4701. hasAttrsChanged = true;
  4702. }
  4703. }
  4704. }
  4705. }
  4706. }
  4707. else {
  4708. // full props update.
  4709. if (setFullProps(instance, rawProps, props, attrs)) {
  4710. hasAttrsChanged = true;
  4711. }
  4712. // in case of dynamic props, check if we need to delete keys from
  4713. // the props object
  4714. let kebabKey;
  4715. for (const key in rawCurrentProps) {
  4716. if (!rawProps ||
  4717. // for camelCase
  4718. (!hasOwn(rawProps, key) &&
  4719. // it's possible the original props was passed in as kebab-case
  4720. // and converted to camelCase (#955)
  4721. ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
  4722. if (options) {
  4723. if (rawPrevProps &&
  4724. // for camelCase
  4725. (rawPrevProps[key] !== undefined ||
  4726. // for kebab-case
  4727. rawPrevProps[kebabKey] !== undefined)) {
  4728. props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
  4729. }
  4730. }
  4731. else {
  4732. delete props[key];
  4733. }
  4734. }
  4735. }
  4736. // in the case of functional component w/o props declaration, props and
  4737. // attrs point to the same object so it should already have been updated.
  4738. if (attrs !== rawCurrentProps) {
  4739. for (const key in attrs) {
  4740. if (!rawProps ||
  4741. (!hasOwn(rawProps, key) &&
  4742. (!false ))) {
  4743. delete attrs[key];
  4744. hasAttrsChanged = true;
  4745. }
  4746. }
  4747. }
  4748. }
  4749. // trigger updates for $attrs in case it's used in component slots
  4750. if (hasAttrsChanged) {
  4751. trigger(instance, "set" /* SET */, '$attrs');
  4752. }
  4753. {
  4754. validateProps(rawProps || {}, props, instance);
  4755. }
  4756. }
  4757. function setFullProps(instance, rawProps, props, attrs) {
  4758. const [options, needCastKeys] = instance.propsOptions;
  4759. let hasAttrsChanged = false;
  4760. let rawCastValues;
  4761. if (rawProps) {
  4762. for (let key in rawProps) {
  4763. // key, ref are reserved and never passed down
  4764. if (isReservedProp(key)) {
  4765. continue;
  4766. }
  4767. const value = rawProps[key];
  4768. // prop option names are camelized during normalization, so to support
  4769. // kebab -> camel conversion here we need to camelize the key.
  4770. let camelKey;
  4771. if (options && hasOwn(options, (camelKey = camelize(key)))) {
  4772. if (!needCastKeys || !needCastKeys.includes(camelKey)) {
  4773. props[camelKey] = value;
  4774. }
  4775. else {
  4776. (rawCastValues || (rawCastValues = {}))[camelKey] = value;
  4777. }
  4778. }
  4779. else if (!isEmitListener(instance.emitsOptions, key)) {
  4780. if (!(key in attrs) || value !== attrs[key]) {
  4781. attrs[key] = value;
  4782. hasAttrsChanged = true;
  4783. }
  4784. }
  4785. }
  4786. }
  4787. if (needCastKeys) {
  4788. const rawCurrentProps = toRaw(props);
  4789. const castValues = rawCastValues || EMPTY_OBJ;
  4790. for (let i = 0; i < needCastKeys.length; i++) {
  4791. const key = needCastKeys[i];
  4792. props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
  4793. }
  4794. }
  4795. return hasAttrsChanged;
  4796. }
  4797. function resolvePropValue(options, props, key, value, instance, isAbsent) {
  4798. const opt = options[key];
  4799. if (opt != null) {
  4800. const hasDefault = hasOwn(opt, 'default');
  4801. // default values
  4802. if (hasDefault && value === undefined) {
  4803. const defaultValue = opt.default;
  4804. if (opt.type !== Function && isFunction(defaultValue)) {
  4805. const { propsDefaults } = instance;
  4806. if (key in propsDefaults) {
  4807. value = propsDefaults[key];
  4808. }
  4809. else {
  4810. setCurrentInstance(instance);
  4811. value = propsDefaults[key] = defaultValue.call(null, props);
  4812. unsetCurrentInstance();
  4813. }
  4814. }
  4815. else {
  4816. value = defaultValue;
  4817. }
  4818. }
  4819. // boolean casting
  4820. if (opt[0 /* shouldCast */]) {
  4821. if (isAbsent && !hasDefault) {
  4822. value = false;
  4823. }
  4824. else if (opt[1 /* shouldCastTrue */] &&
  4825. (value === '' || value === hyphenate(key))) {
  4826. value = true;
  4827. }
  4828. }
  4829. }
  4830. return value;
  4831. }
  4832. function normalizePropsOptions(comp, appContext, asMixin = false) {
  4833. const cache = appContext.propsCache;
  4834. const cached = cache.get(comp);
  4835. if (cached) {
  4836. return cached;
  4837. }
  4838. const raw = comp.props;
  4839. const normalized = {};
  4840. const needCastKeys = [];
  4841. // apply mixin/extends props
  4842. let hasExtends = false;
  4843. if (!isFunction(comp)) {
  4844. const extendProps = (raw) => {
  4845. hasExtends = true;
  4846. const [props, keys] = normalizePropsOptions(raw, appContext, true);
  4847. extend(normalized, props);
  4848. if (keys)
  4849. needCastKeys.push(...keys);
  4850. };
  4851. if (!asMixin && appContext.mixins.length) {
  4852. appContext.mixins.forEach(extendProps);
  4853. }
  4854. if (comp.extends) {
  4855. extendProps(comp.extends);
  4856. }
  4857. if (comp.mixins) {
  4858. comp.mixins.forEach(extendProps);
  4859. }
  4860. }
  4861. if (!raw && !hasExtends) {
  4862. cache.set(comp, EMPTY_ARR);
  4863. return EMPTY_ARR;
  4864. }
  4865. if (isArray(raw)) {
  4866. for (let i = 0; i < raw.length; i++) {
  4867. if (!isString(raw[i])) {
  4868. warn$1(`props must be strings when using array syntax.`, raw[i]);
  4869. }
  4870. const normalizedKey = camelize(raw[i]);
  4871. if (validatePropName(normalizedKey)) {
  4872. normalized[normalizedKey] = EMPTY_OBJ;
  4873. }
  4874. }
  4875. }
  4876. else if (raw) {
  4877. if (!isObject(raw)) {
  4878. warn$1(`invalid props options`, raw);
  4879. }
  4880. for (const key in raw) {
  4881. const normalizedKey = camelize(key);
  4882. if (validatePropName(normalizedKey)) {
  4883. const opt = raw[key];
  4884. const prop = (normalized[normalizedKey] =
  4885. isArray(opt) || isFunction(opt) ? { type: opt } : opt);
  4886. if (prop) {
  4887. const booleanIndex = getTypeIndex(Boolean, prop.type);
  4888. const stringIndex = getTypeIndex(String, prop.type);
  4889. prop[0 /* shouldCast */] = booleanIndex > -1;
  4890. prop[1 /* shouldCastTrue */] =
  4891. stringIndex < 0 || booleanIndex < stringIndex;
  4892. // if the prop needs boolean casting or default value
  4893. if (booleanIndex > -1 || hasOwn(prop, 'default')) {
  4894. needCastKeys.push(normalizedKey);
  4895. }
  4896. }
  4897. }
  4898. }
  4899. }
  4900. const res = [normalized, needCastKeys];
  4901. cache.set(comp, res);
  4902. return res;
  4903. }
  4904. function validatePropName(key) {
  4905. if (key[0] !== '$') {
  4906. return true;
  4907. }
  4908. else {
  4909. warn$1(`Invalid prop name: "${key}" is a reserved property.`);
  4910. }
  4911. return false;
  4912. }
  4913. // use function string name to check type constructors
  4914. // so that it works across vms / iframes.
  4915. function getType(ctor) {
  4916. const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
  4917. return match ? match[1] : ctor === null ? 'null' : '';
  4918. }
  4919. function isSameType(a, b) {
  4920. return getType(a) === getType(b);
  4921. }
  4922. function getTypeIndex(type, expectedTypes) {
  4923. if (isArray(expectedTypes)) {
  4924. return expectedTypes.findIndex(t => isSameType(t, type));
  4925. }
  4926. else if (isFunction(expectedTypes)) {
  4927. return isSameType(expectedTypes, type) ? 0 : -1;
  4928. }
  4929. return -1;
  4930. }
  4931. /**
  4932. * dev only
  4933. */
  4934. function validateProps(rawProps, props, instance) {
  4935. const resolvedValues = toRaw(props);
  4936. const options = instance.propsOptions[0];
  4937. for (const key in options) {
  4938. let opt = options[key];
  4939. if (opt == null)
  4940. continue;
  4941. validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
  4942. }
  4943. }
  4944. /**
  4945. * dev only
  4946. */
  4947. function validateProp(name, value, prop, isAbsent) {
  4948. const { type, required, validator } = prop;
  4949. // required!
  4950. if (required && isAbsent) {
  4951. warn$1('Missing required prop: "' + name + '"');
  4952. return;
  4953. }
  4954. // missing but optional
  4955. if (value == null && !prop.required) {
  4956. return;
  4957. }
  4958. // type check
  4959. if (type != null && type !== true) {
  4960. let isValid = false;
  4961. const types = isArray(type) ? type : [type];
  4962. const expectedTypes = [];
  4963. // value is valid as long as one of the specified types match
  4964. for (let i = 0; i < types.length && !isValid; i++) {
  4965. const { valid, expectedType } = assertType(value, types[i]);
  4966. expectedTypes.push(expectedType || '');
  4967. isValid = valid;
  4968. }
  4969. if (!isValid) {
  4970. warn$1(getInvalidTypeMessage(name, value, expectedTypes));
  4971. return;
  4972. }
  4973. }
  4974. // custom validator
  4975. if (validator && !validator(value)) {
  4976. warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
  4977. }
  4978. }
  4979. const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
  4980. /**
  4981. * dev only
  4982. */
  4983. function assertType(value, type) {
  4984. let valid;
  4985. const expectedType = getType(type);
  4986. if (isSimpleType(expectedType)) {
  4987. const t = typeof value;
  4988. valid = t === expectedType.toLowerCase();
  4989. // for primitive wrapper objects
  4990. if (!valid && t === 'object') {
  4991. valid = value instanceof type;
  4992. }
  4993. }
  4994. else if (expectedType === 'Object') {
  4995. valid = isObject(value);
  4996. }
  4997. else if (expectedType === 'Array') {
  4998. valid = isArray(value);
  4999. }
  5000. else if (expectedType === 'null') {
  5001. valid = value === null;
  5002. }
  5003. else {
  5004. valid = value instanceof type;
  5005. }
  5006. return {
  5007. valid,
  5008. expectedType
  5009. };
  5010. }
  5011. /**
  5012. * dev only
  5013. */
  5014. function getInvalidTypeMessage(name, value, expectedTypes) {
  5015. let message = `Invalid prop: type check failed for prop "${name}".` +
  5016. ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
  5017. const expectedType = expectedTypes[0];
  5018. const receivedType = toRawType(value);
  5019. const expectedValue = styleValue(value, expectedType);
  5020. const receivedValue = styleValue(value, receivedType);
  5021. // check if we need to specify expected value
  5022. if (expectedTypes.length === 1 &&
  5023. isExplicable(expectedType) &&
  5024. !isBoolean(expectedType, receivedType)) {
  5025. message += ` with value ${expectedValue}`;
  5026. }
  5027. message += `, got ${receivedType} `;
  5028. // check if we need to specify received value
  5029. if (isExplicable(receivedType)) {
  5030. message += `with value ${receivedValue}.`;
  5031. }
  5032. return message;
  5033. }
  5034. /**
  5035. * dev only
  5036. */
  5037. function styleValue(value, type) {
  5038. if (type === 'String') {
  5039. return `"${value}"`;
  5040. }
  5041. else if (type === 'Number') {
  5042. return `${Number(value)}`;
  5043. }
  5044. else {
  5045. return `${value}`;
  5046. }
  5047. }
  5048. /**
  5049. * dev only
  5050. */
  5051. function isExplicable(type) {
  5052. const explicitTypes = ['string', 'number', 'boolean'];
  5053. return explicitTypes.some(elem => type.toLowerCase() === elem);
  5054. }
  5055. /**
  5056. * dev only
  5057. */
  5058. function isBoolean(...args) {
  5059. return args.some(elem => elem.toLowerCase() === 'boolean');
  5060. }
  5061. const isInternalKey = (key) => key[0] === '_' || key === '$stable';
  5062. const normalizeSlotValue = (value) => isArray(value)
  5063. ? value.map(normalizeVNode)
  5064. : [normalizeVNode(value)];
  5065. const normalizeSlot = (key, rawSlot, ctx) => {
  5066. const normalized = withCtx((...args) => {
  5067. if (currentInstance) {
  5068. warn$1(`Slot "${key}" invoked outside of the render function: ` +
  5069. `this will not track dependencies used in the slot. ` +
  5070. `Invoke the slot function inside the render function instead.`);
  5071. }
  5072. return normalizeSlotValue(rawSlot(...args));
  5073. }, ctx);
  5074. normalized._c = false;
  5075. return normalized;
  5076. };
  5077. const normalizeObjectSlots = (rawSlots, slots, instance) => {
  5078. const ctx = rawSlots._ctx;
  5079. for (const key in rawSlots) {
  5080. if (isInternalKey(key))
  5081. continue;
  5082. const value = rawSlots[key];
  5083. if (isFunction(value)) {
  5084. slots[key] = normalizeSlot(key, value, ctx);
  5085. }
  5086. else if (value != null) {
  5087. {
  5088. warn$1(`Non-function value encountered for slot "${key}". ` +
  5089. `Prefer function slots for better performance.`);
  5090. }
  5091. const normalized = normalizeSlotValue(value);
  5092. slots[key] = () => normalized;
  5093. }
  5094. }
  5095. };
  5096. const normalizeVNodeSlots = (instance, children) => {
  5097. if (!isKeepAlive(instance.vnode) &&
  5098. !(false )) {
  5099. warn$1(`Non-function value encountered for default slot. ` +
  5100. `Prefer function slots for better performance.`);
  5101. }
  5102. const normalized = normalizeSlotValue(children);
  5103. instance.slots.default = () => normalized;
  5104. };
  5105. const initSlots = (instance, children) => {
  5106. if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
  5107. const type = children._;
  5108. if (type) {
  5109. // users can get the shallow readonly version of the slots object through `this.$slots`,
  5110. // we should avoid the proxy object polluting the slots of the internal instance
  5111. instance.slots = toRaw(children);
  5112. // make compiler marker non-enumerable
  5113. def(children, '_', type);
  5114. }
  5115. else {
  5116. normalizeObjectSlots(children, (instance.slots = {}));
  5117. }
  5118. }
  5119. else {
  5120. instance.slots = {};
  5121. if (children) {
  5122. normalizeVNodeSlots(instance, children);
  5123. }
  5124. }
  5125. def(instance.slots, InternalObjectKey, 1);
  5126. };
  5127. const updateSlots = (instance, children, optimized) => {
  5128. const { vnode, slots } = instance;
  5129. let needDeletionCheck = true;
  5130. let deletionComparisonTarget = EMPTY_OBJ;
  5131. if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
  5132. const type = children._;
  5133. if (type) {
  5134. // compiled slots.
  5135. if (isHmrUpdating) {
  5136. // Parent was HMR updated so slot content may have changed.
  5137. // force update slots and mark instance for hmr as well
  5138. extend(slots, children);
  5139. }
  5140. else if (optimized && type === 1 /* STABLE */) {
  5141. // compiled AND stable.
  5142. // no need to update, and skip stale slots removal.
  5143. needDeletionCheck = false;
  5144. }
  5145. else {
  5146. // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
  5147. // normalization.
  5148. extend(slots, children);
  5149. // #2893
  5150. // when rendering the optimized slots by manually written render function,
  5151. // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
  5152. // i.e. let the `renderSlot` create the bailed Fragment
  5153. if (!optimized && type === 1 /* STABLE */) {
  5154. delete slots._;
  5155. }
  5156. }
  5157. }
  5158. else {
  5159. needDeletionCheck = !children.$stable;
  5160. normalizeObjectSlots(children, slots);
  5161. }
  5162. deletionComparisonTarget = children;
  5163. }
  5164. else if (children) {
  5165. // non slot object children (direct value) passed to a component
  5166. normalizeVNodeSlots(instance, children);
  5167. deletionComparisonTarget = { default: 1 };
  5168. }
  5169. // delete stale slots
  5170. if (needDeletionCheck) {
  5171. for (const key in slots) {
  5172. if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
  5173. delete slots[key];
  5174. }
  5175. }
  5176. }
  5177. };
  5178. /**
  5179. Runtime helper for applying directives to a vnode. Example usage:
  5180. const comp = resolveComponent('comp')
  5181. const foo = resolveDirective('foo')
  5182. const bar = resolveDirective('bar')
  5183. return withDirectives(h(comp), [
  5184. [foo, this.x],
  5185. [bar, this.y]
  5186. ])
  5187. */
  5188. function validateDirectiveName(name) {
  5189. if (isBuiltInDirective(name)) {
  5190. warn$1('Do not use built-in directive ids as custom directive id: ' + name);
  5191. }
  5192. }
  5193. /**
  5194. * Adds directives to a VNode.
  5195. */
  5196. function withDirectives(vnode, directives) {
  5197. const internalInstance = currentRenderingInstance;
  5198. if (internalInstance === null) {
  5199. warn$1(`withDirectives can only be used inside render functions.`);
  5200. return vnode;
  5201. }
  5202. const instance = getExposeProxy(internalInstance) ||
  5203. internalInstance.proxy;
  5204. const bindings = vnode.dirs || (vnode.dirs = []);
  5205. for (let i = 0; i < directives.length; i++) {
  5206. let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
  5207. if (isFunction(dir)) {
  5208. dir = {
  5209. mounted: dir,
  5210. updated: dir
  5211. };
  5212. }
  5213. if (dir.deep) {
  5214. traverse(value);
  5215. }
  5216. bindings.push({
  5217. dir,
  5218. instance,
  5219. value,
  5220. oldValue: void 0,
  5221. arg,
  5222. modifiers
  5223. });
  5224. }
  5225. return vnode;
  5226. }
  5227. function invokeDirectiveHook(vnode, prevVNode, instance, name) {
  5228. const bindings = vnode.dirs;
  5229. const oldBindings = prevVNode && prevVNode.dirs;
  5230. for (let i = 0; i < bindings.length; i++) {
  5231. const binding = bindings[i];
  5232. if (oldBindings) {
  5233. binding.oldValue = oldBindings[i].value;
  5234. }
  5235. let hook = binding.dir[name];
  5236. if (hook) {
  5237. // disable tracking inside all lifecycle hooks
  5238. // since they can potentially be called inside effects.
  5239. pauseTracking();
  5240. callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
  5241. vnode.el,
  5242. binding,
  5243. vnode,
  5244. prevVNode
  5245. ]);
  5246. resetTracking();
  5247. }
  5248. }
  5249. }
  5250. function createAppContext() {
  5251. return {
  5252. app: null,
  5253. config: {
  5254. isNativeTag: NO,
  5255. performance: false,
  5256. globalProperties: {},
  5257. optionMergeStrategies: {},
  5258. errorHandler: undefined,
  5259. warnHandler: undefined,
  5260. compilerOptions: {}
  5261. },
  5262. mixins: [],
  5263. components: {},
  5264. directives: {},
  5265. provides: Object.create(null),
  5266. optionsCache: new WeakMap(),
  5267. propsCache: new WeakMap(),
  5268. emitsCache: new WeakMap()
  5269. };
  5270. }
  5271. let uid = 0;
  5272. function createAppAPI(render, hydrate) {
  5273. return function createApp(rootComponent, rootProps = null) {
  5274. if (!isFunction(rootComponent)) {
  5275. rootComponent = Object.assign({}, rootComponent);
  5276. }
  5277. if (rootProps != null && !isObject(rootProps)) {
  5278. warn$1(`root props passed to app.mount() must be an object.`);
  5279. rootProps = null;
  5280. }
  5281. const context = createAppContext();
  5282. const installedPlugins = new Set();
  5283. let isMounted = false;
  5284. const app = (context.app = {
  5285. _uid: uid++,
  5286. _component: rootComponent,
  5287. _props: rootProps,
  5288. _container: null,
  5289. _context: context,
  5290. _instance: null,
  5291. version,
  5292. get config() {
  5293. return context.config;
  5294. },
  5295. set config(v) {
  5296. {
  5297. warn$1(`app.config cannot be replaced. Modify individual options instead.`);
  5298. }
  5299. },
  5300. use(plugin, ...options) {
  5301. if (installedPlugins.has(plugin)) {
  5302. warn$1(`Plugin has already been applied to target app.`);
  5303. }
  5304. else if (plugin && isFunction(plugin.install)) {
  5305. installedPlugins.add(plugin);
  5306. plugin.install(app, ...options);
  5307. }
  5308. else if (isFunction(plugin)) {
  5309. installedPlugins.add(plugin);
  5310. plugin(app, ...options);
  5311. }
  5312. else {
  5313. warn$1(`A plugin must either be a function or an object with an "install" ` +
  5314. `function.`);
  5315. }
  5316. return app;
  5317. },
  5318. mixin(mixin) {
  5319. {
  5320. if (!context.mixins.includes(mixin)) {
  5321. context.mixins.push(mixin);
  5322. }
  5323. else {
  5324. warn$1('Mixin has already been applied to target app' +
  5325. (mixin.name ? `: ${mixin.name}` : ''));
  5326. }
  5327. }
  5328. return app;
  5329. },
  5330. component(name, component) {
  5331. {
  5332. validateComponentName(name, context.config);
  5333. }
  5334. if (!component) {
  5335. return context.components[name];
  5336. }
  5337. if (context.components[name]) {
  5338. warn$1(`Component "${name}" has already been registered in target app.`);
  5339. }
  5340. context.components[name] = component;
  5341. return app;
  5342. },
  5343. directive(name, directive) {
  5344. {
  5345. validateDirectiveName(name);
  5346. }
  5347. if (!directive) {
  5348. return context.directives[name];
  5349. }
  5350. if (context.directives[name]) {
  5351. warn$1(`Directive "${name}" has already been registered in target app.`);
  5352. }
  5353. context.directives[name] = directive;
  5354. return app;
  5355. },
  5356. mount(rootContainer, isHydrate, isSVG) {
  5357. if (!isMounted) {
  5358. const vnode = createVNode(rootComponent, rootProps);
  5359. // store app context on the root VNode.
  5360. // this will be set on the root instance on initial mount.
  5361. vnode.appContext = context;
  5362. // HMR root reload
  5363. {
  5364. context.reload = () => {
  5365. render(cloneVNode(vnode), rootContainer, isSVG);
  5366. };
  5367. }
  5368. if (isHydrate && hydrate) {
  5369. hydrate(vnode, rootContainer);
  5370. }
  5371. else {
  5372. render(vnode, rootContainer, isSVG);
  5373. }
  5374. isMounted = true;
  5375. app._container = rootContainer;
  5376. rootContainer.__vue_app__ = app;
  5377. {
  5378. app._instance = vnode.component;
  5379. devtoolsInitApp(app, version);
  5380. }
  5381. return getExposeProxy(vnode.component) || vnode.component.proxy;
  5382. }
  5383. else {
  5384. warn$1(`App has already been mounted.\n` +
  5385. `If you want to remount the same app, move your app creation logic ` +
  5386. `into a factory function and create fresh app instances for each ` +
  5387. `mount - e.g. \`const createMyApp = () => createApp(App)\``);
  5388. }
  5389. },
  5390. unmount() {
  5391. if (isMounted) {
  5392. render(null, app._container);
  5393. {
  5394. app._instance = null;
  5395. devtoolsUnmountApp(app);
  5396. }
  5397. delete app._container.__vue_app__;
  5398. }
  5399. else {
  5400. warn$1(`Cannot unmount an app that is not mounted.`);
  5401. }
  5402. },
  5403. provide(key, value) {
  5404. if (key in context.provides) {
  5405. warn$1(`App already provides property with key "${String(key)}". ` +
  5406. `It will be overwritten with the new value.`);
  5407. }
  5408. // TypeScript doesn't allow symbols as index type
  5409. // https://github.com/Microsoft/TypeScript/issues/24587
  5410. context.provides[key] = value;
  5411. return app;
  5412. }
  5413. });
  5414. return app;
  5415. };
  5416. }
  5417. /**
  5418. * Function for handling a template ref
  5419. */
  5420. function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
  5421. if (isArray(rawRef)) {
  5422. rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
  5423. return;
  5424. }
  5425. if (isAsyncWrapper(vnode) && !isUnmount) {
  5426. // when mounting async components, nothing needs to be done,
  5427. // because the template ref is forwarded to inner component
  5428. return;
  5429. }
  5430. const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
  5431. ? getExposeProxy(vnode.component) || vnode.component.proxy
  5432. : vnode.el;
  5433. const value = isUnmount ? null : refValue;
  5434. const { i: owner, r: ref } = rawRef;
  5435. if (!owner) {
  5436. warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
  5437. `A vnode with ref must be created inside the render function.`);
  5438. return;
  5439. }
  5440. const oldRef = oldRawRef && oldRawRef.r;
  5441. const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
  5442. const setupState = owner.setupState;
  5443. // dynamic ref changed. unset old ref
  5444. if (oldRef != null && oldRef !== ref) {
  5445. if (isString(oldRef)) {
  5446. refs[oldRef] = null;
  5447. if (hasOwn(setupState, oldRef)) {
  5448. setupState[oldRef] = null;
  5449. }
  5450. }
  5451. else if (isRef(oldRef)) {
  5452. oldRef.value = null;
  5453. }
  5454. }
  5455. if (isFunction(ref)) {
  5456. callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
  5457. }
  5458. else {
  5459. const _isString = isString(ref);
  5460. const _isRef = isRef(ref);
  5461. if (_isString || _isRef) {
  5462. const doSet = () => {
  5463. if (rawRef.f) {
  5464. const existing = _isString ? refs[ref] : ref.value;
  5465. if (isUnmount) {
  5466. isArray(existing) && remove(existing, refValue);
  5467. }
  5468. else {
  5469. if (!isArray(existing)) {
  5470. if (_isString) {
  5471. refs[ref] = [refValue];
  5472. if (hasOwn(setupState, ref)) {
  5473. setupState[ref] = refs[ref];
  5474. }
  5475. }
  5476. else {
  5477. ref.value = [refValue];
  5478. if (rawRef.k)
  5479. refs[rawRef.k] = ref.value;
  5480. }
  5481. }
  5482. else if (!existing.includes(refValue)) {
  5483. existing.push(refValue);
  5484. }
  5485. }
  5486. }
  5487. else if (_isString) {
  5488. refs[ref] = value;
  5489. if (hasOwn(setupState, ref)) {
  5490. setupState[ref] = value;
  5491. }
  5492. }
  5493. else if (isRef(ref)) {
  5494. ref.value = value;
  5495. if (rawRef.k)
  5496. refs[rawRef.k] = value;
  5497. }
  5498. else {
  5499. warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
  5500. }
  5501. };
  5502. if (value) {
  5503. doSet.id = -1;
  5504. queuePostRenderEffect(doSet, parentSuspense);
  5505. }
  5506. else {
  5507. doSet();
  5508. }
  5509. }
  5510. else {
  5511. warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
  5512. }
  5513. }
  5514. }
  5515. let hasMismatch = false;
  5516. const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
  5517. const isComment = (node) => node.nodeType === 8 /* COMMENT */;
  5518. // Note: hydration is DOM-specific
  5519. // But we have to place it in core due to tight coupling with core - splitting
  5520. // it out creates a ton of unnecessary complexity.
  5521. // Hydration also depends on some renderer internal logic which needs to be
  5522. // passed in via arguments.
  5523. function createHydrationFunctions(rendererInternals) {
  5524. const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
  5525. const hydrate = (vnode, container) => {
  5526. if (!container.hasChildNodes()) {
  5527. warn$1(`Attempting to hydrate existing markup but container is empty. ` +
  5528. `Performing full mount instead.`);
  5529. patch(null, vnode, container);
  5530. flushPostFlushCbs();
  5531. return;
  5532. }
  5533. hasMismatch = false;
  5534. hydrateNode(container.firstChild, vnode, null, null, null);
  5535. flushPostFlushCbs();
  5536. if (hasMismatch && !false) {
  5537. // this error should show up in production
  5538. console.error(`Hydration completed but contains mismatches.`);
  5539. }
  5540. };
  5541. const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
  5542. const isFragmentStart = isComment(node) && node.data === '[';
  5543. const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
  5544. const { type, ref, shapeFlag } = vnode;
  5545. const domType = node.nodeType;
  5546. vnode.el = node;
  5547. let nextNode = null;
  5548. switch (type) {
  5549. case Text:
  5550. if (domType !== 3 /* TEXT */) {
  5551. nextNode = onMismatch();
  5552. }
  5553. else {
  5554. if (node.data !== vnode.children) {
  5555. hasMismatch = true;
  5556. warn$1(`Hydration text mismatch:` +
  5557. `\n- Client: ${JSON.stringify(node.data)}` +
  5558. `\n- Server: ${JSON.stringify(vnode.children)}`);
  5559. node.data = vnode.children;
  5560. }
  5561. nextNode = nextSibling(node);
  5562. }
  5563. break;
  5564. case Comment:
  5565. if (domType !== 8 /* COMMENT */ || isFragmentStart) {
  5566. nextNode = onMismatch();
  5567. }
  5568. else {
  5569. nextNode = nextSibling(node);
  5570. }
  5571. break;
  5572. case Static:
  5573. if (domType !== 1 /* ELEMENT */) {
  5574. nextNode = onMismatch();
  5575. }
  5576. else {
  5577. // determine anchor, adopt content
  5578. nextNode = node;
  5579. // if the static vnode has its content stripped during build,
  5580. // adopt it from the server-rendered HTML.
  5581. const needToAdoptContent = !vnode.children.length;
  5582. for (let i = 0; i < vnode.staticCount; i++) {
  5583. if (needToAdoptContent)
  5584. vnode.children += nextNode.outerHTML;
  5585. if (i === vnode.staticCount - 1) {
  5586. vnode.anchor = nextNode;
  5587. }
  5588. nextNode = nextSibling(nextNode);
  5589. }
  5590. return nextNode;
  5591. }
  5592. break;
  5593. case Fragment:
  5594. if (!isFragmentStart) {
  5595. nextNode = onMismatch();
  5596. }
  5597. else {
  5598. nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  5599. }
  5600. break;
  5601. default:
  5602. if (shapeFlag & 1 /* ELEMENT */) {
  5603. if (domType !== 1 /* ELEMENT */ ||
  5604. vnode.type.toLowerCase() !==
  5605. node.tagName.toLowerCase()) {
  5606. nextNode = onMismatch();
  5607. }
  5608. else {
  5609. nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  5610. }
  5611. }
  5612. else if (shapeFlag & 6 /* COMPONENT */) {
  5613. // when setting up the render effect, if the initial vnode already
  5614. // has .el set, the component will perform hydration instead of mount
  5615. // on its sub-tree.
  5616. vnode.slotScopeIds = slotScopeIds;
  5617. const container = parentNode(node);
  5618. mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
  5619. // component may be async, so in the case of fragments we cannot rely
  5620. // on component's rendered output to determine the end of the fragment
  5621. // instead, we do a lookahead to find the end anchor node.
  5622. nextNode = isFragmentStart
  5623. ? locateClosingAsyncAnchor(node)
  5624. : nextSibling(node);
  5625. // #3787
  5626. // if component is async, it may get moved / unmounted before its
  5627. // inner component is loaded, so we need to give it a placeholder
  5628. // vnode that matches its adopted DOM.
  5629. if (isAsyncWrapper(vnode)) {
  5630. let subTree;
  5631. if (isFragmentStart) {
  5632. subTree = createVNode(Fragment);
  5633. subTree.anchor = nextNode
  5634. ? nextNode.previousSibling
  5635. : container.lastChild;
  5636. }
  5637. else {
  5638. subTree =
  5639. node.nodeType === 3 ? createTextVNode('') : createVNode('div');
  5640. }
  5641. subTree.el = node;
  5642. vnode.component.subTree = subTree;
  5643. }
  5644. }
  5645. else if (shapeFlag & 64 /* TELEPORT */) {
  5646. if (domType !== 8 /* COMMENT */) {
  5647. nextNode = onMismatch();
  5648. }
  5649. else {
  5650. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
  5651. }
  5652. }
  5653. else if (shapeFlag & 128 /* SUSPENSE */) {
  5654. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
  5655. }
  5656. else {
  5657. warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
  5658. }
  5659. }
  5660. if (ref != null) {
  5661. setRef(ref, null, parentSuspense, vnode);
  5662. }
  5663. return nextNode;
  5664. };
  5665. const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  5666. optimized = optimized || !!vnode.dynamicChildren;
  5667. const { type, props, patchFlag, shapeFlag, dirs } = vnode;
  5668. // #4006 for form elements with non-string v-model value bindings
  5669. // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
  5670. const forcePatchValue = (type === 'input' && dirs) || type === 'option';
  5671. // skip props & children if this is hoisted static nodes
  5672. // #5405 in dev, always hydrate children for HMR
  5673. {
  5674. if (dirs) {
  5675. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  5676. }
  5677. // props
  5678. if (props) {
  5679. if (forcePatchValue ||
  5680. !optimized ||
  5681. patchFlag & (16 /* FULL_PROPS */ | 32 /* HYDRATE_EVENTS */)) {
  5682. for (const key in props) {
  5683. if ((forcePatchValue && key.endsWith('value')) ||
  5684. (isOn(key) && !isReservedProp(key))) {
  5685. patchProp(el, key, null, props[key], false, undefined, parentComponent);
  5686. }
  5687. }
  5688. }
  5689. else if (props.onClick) {
  5690. // Fast path for click listeners (which is most often) to avoid
  5691. // iterating through props.
  5692. patchProp(el, 'onClick', null, props.onClick, false, undefined, parentComponent);
  5693. }
  5694. }
  5695. // vnode / directive hooks
  5696. let vnodeHooks;
  5697. if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
  5698. invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  5699. }
  5700. if (dirs) {
  5701. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  5702. }
  5703. if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
  5704. queueEffectWithSuspense(() => {
  5705. vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  5706. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  5707. }, parentSuspense);
  5708. }
  5709. // children
  5710. if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
  5711. // skip if element has innerHTML / textContent
  5712. !(props && (props.innerHTML || props.textContent))) {
  5713. let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
  5714. let hasWarned = false;
  5715. while (next) {
  5716. hasMismatch = true;
  5717. if (!hasWarned) {
  5718. warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
  5719. `server rendered element contains more child nodes than client vdom.`);
  5720. hasWarned = true;
  5721. }
  5722. // The SSRed DOM contains more nodes than it should. Remove them.
  5723. const cur = next;
  5724. next = next.nextSibling;
  5725. remove(cur);
  5726. }
  5727. }
  5728. else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  5729. if (el.textContent !== vnode.children) {
  5730. hasMismatch = true;
  5731. warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
  5732. `- Client: ${el.textContent}\n` +
  5733. `- Server: ${vnode.children}`);
  5734. el.textContent = vnode.children;
  5735. }
  5736. }
  5737. }
  5738. return el.nextSibling;
  5739. };
  5740. const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  5741. optimized = optimized || !!parentVNode.dynamicChildren;
  5742. const children = parentVNode.children;
  5743. const l = children.length;
  5744. let hasWarned = false;
  5745. for (let i = 0; i < l; i++) {
  5746. const vnode = optimized
  5747. ? children[i]
  5748. : (children[i] = normalizeVNode(children[i]));
  5749. if (node) {
  5750. node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  5751. }
  5752. else if (vnode.type === Text && !vnode.children) {
  5753. continue;
  5754. }
  5755. else {
  5756. hasMismatch = true;
  5757. if (!hasWarned) {
  5758. warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
  5759. `server rendered element contains fewer child nodes than client vdom.`);
  5760. hasWarned = true;
  5761. }
  5762. // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
  5763. patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
  5764. }
  5765. }
  5766. return node;
  5767. };
  5768. const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  5769. const { slotScopeIds: fragmentSlotScopeIds } = vnode;
  5770. if (fragmentSlotScopeIds) {
  5771. slotScopeIds = slotScopeIds
  5772. ? slotScopeIds.concat(fragmentSlotScopeIds)
  5773. : fragmentSlotScopeIds;
  5774. }
  5775. const container = parentNode(node);
  5776. const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
  5777. if (next && isComment(next) && next.data === ']') {
  5778. return nextSibling((vnode.anchor = next));
  5779. }
  5780. else {
  5781. // fragment didn't hydrate successfully, since we didn't get a end anchor
  5782. // back. This should have led to node/children mismatch warnings.
  5783. hasMismatch = true;
  5784. // since the anchor is missing, we need to create one and insert it
  5785. insert((vnode.anchor = createComment(`]`)), container, next);
  5786. return next;
  5787. }
  5788. };
  5789. const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
  5790. hasMismatch = true;
  5791. warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
  5792. ? `(text)`
  5793. : isComment(node) && node.data === '['
  5794. ? `(start of fragment)`
  5795. : ``);
  5796. vnode.el = null;
  5797. if (isFragment) {
  5798. // remove excessive fragment nodes
  5799. const end = locateClosingAsyncAnchor(node);
  5800. while (true) {
  5801. const next = nextSibling(node);
  5802. if (next && next !== end) {
  5803. remove(next);
  5804. }
  5805. else {
  5806. break;
  5807. }
  5808. }
  5809. }
  5810. const next = nextSibling(node);
  5811. const container = parentNode(node);
  5812. remove(node);
  5813. patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
  5814. return next;
  5815. };
  5816. const locateClosingAsyncAnchor = (node) => {
  5817. let match = 0;
  5818. while (node) {
  5819. node = nextSibling(node);
  5820. if (node && isComment(node)) {
  5821. if (node.data === '[')
  5822. match++;
  5823. if (node.data === ']') {
  5824. if (match === 0) {
  5825. return nextSibling(node);
  5826. }
  5827. else {
  5828. match--;
  5829. }
  5830. }
  5831. }
  5832. }
  5833. return node;
  5834. };
  5835. return [hydrate, hydrateNode];
  5836. }
  5837. /* eslint-disable no-restricted-globals */
  5838. let supported;
  5839. let perf;
  5840. function startMeasure(instance, type) {
  5841. if (instance.appContext.config.performance && isSupported()) {
  5842. perf.mark(`vue-${type}-${instance.uid}`);
  5843. }
  5844. {
  5845. devtoolsPerfStart(instance, type, isSupported() ? perf.now() : Date.now());
  5846. }
  5847. }
  5848. function endMeasure(instance, type) {
  5849. if (instance.appContext.config.performance && isSupported()) {
  5850. const startTag = `vue-${type}-${instance.uid}`;
  5851. const endTag = startTag + `:end`;
  5852. perf.mark(endTag);
  5853. perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
  5854. perf.clearMarks(startTag);
  5855. perf.clearMarks(endTag);
  5856. }
  5857. {
  5858. devtoolsPerfEnd(instance, type, isSupported() ? perf.now() : Date.now());
  5859. }
  5860. }
  5861. function isSupported() {
  5862. if (supported !== undefined) {
  5863. return supported;
  5864. }
  5865. if (typeof window !== 'undefined' && window.performance) {
  5866. supported = true;
  5867. perf = window.performance;
  5868. }
  5869. else {
  5870. supported = false;
  5871. }
  5872. return supported;
  5873. }
  5874. const queuePostRenderEffect = queueEffectWithSuspense
  5875. ;
  5876. /**
  5877. * The createRenderer function accepts two generic arguments:
  5878. * HostNode and HostElement, corresponding to Node and Element types in the
  5879. * host environment. For example, for runtime-dom, HostNode would be the DOM
  5880. * `Node` interface and HostElement would be the DOM `Element` interface.
  5881. *
  5882. * Custom renderers can pass in the platform specific types like this:
  5883. *
  5884. * ``` js
  5885. * const { render, createApp } = createRenderer<Node, Element>({
  5886. * patchProp,
  5887. * ...nodeOps
  5888. * })
  5889. * ```
  5890. */
  5891. function createRenderer(options) {
  5892. return baseCreateRenderer(options);
  5893. }
  5894. // Separate API for creating hydration-enabled renderer.
  5895. // Hydration logic is only used when calling this function, making it
  5896. // tree-shakable.
  5897. function createHydrationRenderer(options) {
  5898. return baseCreateRenderer(options, createHydrationFunctions);
  5899. }
  5900. // implementation
  5901. function baseCreateRenderer(options, createHydrationFns) {
  5902. const target = getGlobalThis();
  5903. target.__VUE__ = true;
  5904. {
  5905. setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
  5906. }
  5907. const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
  5908. // Note: functions inside this closure should use `const xxx = () => {}`
  5909. // style in order to prevent being inlined by minifiers.
  5910. const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
  5911. if (n1 === n2) {
  5912. return;
  5913. }
  5914. // patching & not same type, unmount old tree
  5915. if (n1 && !isSameVNodeType(n1, n2)) {
  5916. anchor = getNextHostNode(n1);
  5917. unmount(n1, parentComponent, parentSuspense, true);
  5918. n1 = null;
  5919. }
  5920. if (n2.patchFlag === -2 /* BAIL */) {
  5921. optimized = false;
  5922. n2.dynamicChildren = null;
  5923. }
  5924. const { type, ref, shapeFlag } = n2;
  5925. switch (type) {
  5926. case Text:
  5927. processText(n1, n2, container, anchor);
  5928. break;
  5929. case Comment:
  5930. processCommentNode(n1, n2, container, anchor);
  5931. break;
  5932. case Static:
  5933. if (n1 == null) {
  5934. mountStaticNode(n2, container, anchor, isSVG);
  5935. }
  5936. else {
  5937. patchStaticNode(n1, n2, container, isSVG);
  5938. }
  5939. break;
  5940. case Fragment:
  5941. processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5942. break;
  5943. default:
  5944. if (shapeFlag & 1 /* ELEMENT */) {
  5945. processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5946. }
  5947. else if (shapeFlag & 6 /* COMPONENT */) {
  5948. processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5949. }
  5950. else if (shapeFlag & 64 /* TELEPORT */) {
  5951. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
  5952. }
  5953. else if (shapeFlag & 128 /* SUSPENSE */) {
  5954. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
  5955. }
  5956. else {
  5957. warn$1('Invalid VNode type:', type, `(${typeof type})`);
  5958. }
  5959. }
  5960. // set ref
  5961. if (ref != null && parentComponent) {
  5962. setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
  5963. }
  5964. };
  5965. const processText = (n1, n2, container, anchor) => {
  5966. if (n1 == null) {
  5967. hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
  5968. }
  5969. else {
  5970. const el = (n2.el = n1.el);
  5971. if (n2.children !== n1.children) {
  5972. hostSetText(el, n2.children);
  5973. }
  5974. }
  5975. };
  5976. const processCommentNode = (n1, n2, container, anchor) => {
  5977. if (n1 == null) {
  5978. hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
  5979. }
  5980. else {
  5981. // there's no support for dynamic comments
  5982. n2.el = n1.el;
  5983. }
  5984. };
  5985. const mountStaticNode = (n2, container, anchor, isSVG) => {
  5986. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG, n2.el, n2.anchor);
  5987. };
  5988. /**
  5989. * Dev / HMR only
  5990. */
  5991. const patchStaticNode = (n1, n2, container, isSVG) => {
  5992. // static nodes are only patched during dev for HMR
  5993. if (n2.children !== n1.children) {
  5994. const anchor = hostNextSibling(n1.anchor);
  5995. // remove existing
  5996. removeStaticNode(n1);
  5997. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  5998. }
  5999. else {
  6000. n2.el = n1.el;
  6001. n2.anchor = n1.anchor;
  6002. }
  6003. };
  6004. const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
  6005. let next;
  6006. while (el && el !== anchor) {
  6007. next = hostNextSibling(el);
  6008. hostInsert(el, container, nextSibling);
  6009. el = next;
  6010. }
  6011. hostInsert(anchor, container, nextSibling);
  6012. };
  6013. const removeStaticNode = ({ el, anchor }) => {
  6014. let next;
  6015. while (el && el !== anchor) {
  6016. next = hostNextSibling(el);
  6017. hostRemove(el);
  6018. el = next;
  6019. }
  6020. hostRemove(anchor);
  6021. };
  6022. const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6023. isSVG = isSVG || n2.type === 'svg';
  6024. if (n1 == null) {
  6025. mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6026. }
  6027. else {
  6028. patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6029. }
  6030. };
  6031. const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6032. let el;
  6033. let vnodeHook;
  6034. const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
  6035. {
  6036. el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
  6037. // mount children first, since some props may rely on child content
  6038. // being already rendered, e.g. `<select value>`
  6039. if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  6040. hostSetElementText(el, vnode.children);
  6041. }
  6042. else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6043. mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
  6044. }
  6045. if (dirs) {
  6046. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  6047. }
  6048. // props
  6049. if (props) {
  6050. for (const key in props) {
  6051. if (key !== 'value' && !isReservedProp(key)) {
  6052. hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  6053. }
  6054. }
  6055. /**
  6056. * Special case for setting value on DOM elements:
  6057. * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
  6058. * - it needs to be forced (#1471)
  6059. * #2353 proposes adding another renderer option to configure this, but
  6060. * the properties affects are so finite it is worth special casing it
  6061. * here to reduce the complexity. (Special casing it also should not
  6062. * affect non-DOM renderers)
  6063. */
  6064. if ('value' in props) {
  6065. hostPatchProp(el, 'value', null, props.value);
  6066. }
  6067. if ((vnodeHook = props.onVnodeBeforeMount)) {
  6068. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  6069. }
  6070. }
  6071. // scopeId
  6072. setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
  6073. }
  6074. {
  6075. Object.defineProperty(el, '__vnode', {
  6076. value: vnode,
  6077. enumerable: false
  6078. });
  6079. Object.defineProperty(el, '__vueParentComponent', {
  6080. value: parentComponent,
  6081. enumerable: false
  6082. });
  6083. }
  6084. if (dirs) {
  6085. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  6086. }
  6087. // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
  6088. // #1689 For inside suspense + suspense resolved case, just call it
  6089. const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
  6090. transition &&
  6091. !transition.persisted;
  6092. if (needCallTransitionHooks) {
  6093. transition.beforeEnter(el);
  6094. }
  6095. hostInsert(el, container, anchor);
  6096. if ((vnodeHook = props && props.onVnodeMounted) ||
  6097. needCallTransitionHooks ||
  6098. dirs) {
  6099. queuePostRenderEffect(() => {
  6100. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  6101. needCallTransitionHooks && transition.enter(el);
  6102. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  6103. }, parentSuspense);
  6104. }
  6105. };
  6106. const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
  6107. if (scopeId) {
  6108. hostSetScopeId(el, scopeId);
  6109. }
  6110. if (slotScopeIds) {
  6111. for (let i = 0; i < slotScopeIds.length; i++) {
  6112. hostSetScopeId(el, slotScopeIds[i]);
  6113. }
  6114. }
  6115. if (parentComponent) {
  6116. let subTree = parentComponent.subTree;
  6117. if (subTree.patchFlag > 0 &&
  6118. subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
  6119. subTree =
  6120. filterSingleRoot(subTree.children) || subTree;
  6121. }
  6122. if (vnode === subTree) {
  6123. const parentVNode = parentComponent.vnode;
  6124. setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
  6125. }
  6126. }
  6127. };
  6128. const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
  6129. for (let i = start; i < children.length; i++) {
  6130. const child = (children[i] = optimized
  6131. ? cloneIfMounted(children[i])
  6132. : normalizeVNode(children[i]));
  6133. patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6134. }
  6135. };
  6136. const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6137. const el = (n2.el = n1.el);
  6138. let { patchFlag, dynamicChildren, dirs } = n2;
  6139. // #1426 take the old vnode's patch flag into account since user may clone a
  6140. // compiler-generated vnode, which de-opts to FULL_PROPS
  6141. patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
  6142. const oldProps = n1.props || EMPTY_OBJ;
  6143. const newProps = n2.props || EMPTY_OBJ;
  6144. let vnodeHook;
  6145. // disable recurse in beforeUpdate hooks
  6146. parentComponent && toggleRecurse(parentComponent, false);
  6147. if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
  6148. invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  6149. }
  6150. if (dirs) {
  6151. invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
  6152. }
  6153. parentComponent && toggleRecurse(parentComponent, true);
  6154. if (isHmrUpdating) {
  6155. // HMR updated, force full diff
  6156. patchFlag = 0;
  6157. optimized = false;
  6158. dynamicChildren = null;
  6159. }
  6160. const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
  6161. if (dynamicChildren) {
  6162. patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
  6163. if (parentComponent && parentComponent.type.__hmrId) {
  6164. traverseStaticChildren(n1, n2);
  6165. }
  6166. }
  6167. else if (!optimized) {
  6168. // full diff
  6169. patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
  6170. }
  6171. if (patchFlag > 0) {
  6172. // the presence of a patchFlag means this element's render code was
  6173. // generated by the compiler and can take the fast path.
  6174. // in this path old node and new node are guaranteed to have the same shape
  6175. // (i.e. at the exact same position in the source template)
  6176. if (patchFlag & 16 /* FULL_PROPS */) {
  6177. // element props contain dynamic keys, full diff needed
  6178. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  6179. }
  6180. else {
  6181. // class
  6182. // this flag is matched when the element has dynamic class bindings.
  6183. if (patchFlag & 2 /* CLASS */) {
  6184. if (oldProps.class !== newProps.class) {
  6185. hostPatchProp(el, 'class', null, newProps.class, isSVG);
  6186. }
  6187. }
  6188. // style
  6189. // this flag is matched when the element has dynamic style bindings
  6190. if (patchFlag & 4 /* STYLE */) {
  6191. hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
  6192. }
  6193. // props
  6194. // This flag is matched when the element has dynamic prop/attr bindings
  6195. // other than class and style. The keys of dynamic prop/attrs are saved for
  6196. // faster iteration.
  6197. // Note dynamic keys like :[foo]="bar" will cause this optimization to
  6198. // bail out and go through a full diff because we need to unset the old key
  6199. if (patchFlag & 8 /* PROPS */) {
  6200. // if the flag is present then dynamicProps must be non-null
  6201. const propsToUpdate = n2.dynamicProps;
  6202. for (let i = 0; i < propsToUpdate.length; i++) {
  6203. const key = propsToUpdate[i];
  6204. const prev = oldProps[key];
  6205. const next = newProps[key];
  6206. // #1471 force patch value
  6207. if (next !== prev || key === 'value') {
  6208. hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
  6209. }
  6210. }
  6211. }
  6212. }
  6213. // text
  6214. // This flag is matched when the element has only dynamic text children.
  6215. if (patchFlag & 1 /* TEXT */) {
  6216. if (n1.children !== n2.children) {
  6217. hostSetElementText(el, n2.children);
  6218. }
  6219. }
  6220. }
  6221. else if (!optimized && dynamicChildren == null) {
  6222. // unoptimized, full diff
  6223. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  6224. }
  6225. if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
  6226. queuePostRenderEffect(() => {
  6227. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  6228. dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
  6229. }, parentSuspense);
  6230. }
  6231. };
  6232. // The fast path for blocks.
  6233. const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
  6234. for (let i = 0; i < newChildren.length; i++) {
  6235. const oldVNode = oldChildren[i];
  6236. const newVNode = newChildren[i];
  6237. // Determine the container (parent element) for the patch.
  6238. const container =
  6239. // oldVNode may be an errored async setup() component inside Suspense
  6240. // which will not have a mounted element
  6241. oldVNode.el &&
  6242. // - In the case of a Fragment, we need to provide the actual parent
  6243. // of the Fragment itself so it can move its children.
  6244. (oldVNode.type === Fragment ||
  6245. // - In the case of different nodes, there is going to be a replacement
  6246. // which also requires the correct parent container
  6247. !isSameVNodeType(oldVNode, newVNode) ||
  6248. // - In the case of a component, it could contain anything.
  6249. oldVNode.shapeFlag & (6 /* COMPONENT */ | 64 /* TELEPORT */))
  6250. ? hostParentNode(oldVNode.el)
  6251. : // In other cases, the parent container is not actually used so we
  6252. // just pass the block element here to avoid a DOM parentNode call.
  6253. fallbackContainer;
  6254. patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
  6255. }
  6256. };
  6257. const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
  6258. if (oldProps !== newProps) {
  6259. for (const key in newProps) {
  6260. // empty string is not valid prop
  6261. if (isReservedProp(key))
  6262. continue;
  6263. const next = newProps[key];
  6264. const prev = oldProps[key];
  6265. // defer patching value
  6266. if (next !== prev && key !== 'value') {
  6267. hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  6268. }
  6269. }
  6270. if (oldProps !== EMPTY_OBJ) {
  6271. for (const key in oldProps) {
  6272. if (!isReservedProp(key) && !(key in newProps)) {
  6273. hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  6274. }
  6275. }
  6276. }
  6277. if ('value' in newProps) {
  6278. hostPatchProp(el, 'value', oldProps.value, newProps.value);
  6279. }
  6280. }
  6281. };
  6282. const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6283. const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
  6284. const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
  6285. let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
  6286. if (isHmrUpdating) {
  6287. // HMR updated, force full diff
  6288. patchFlag = 0;
  6289. optimized = false;
  6290. dynamicChildren = null;
  6291. }
  6292. // check if this is a slot fragment with :slotted scope ids
  6293. if (fragmentSlotScopeIds) {
  6294. slotScopeIds = slotScopeIds
  6295. ? slotScopeIds.concat(fragmentSlotScopeIds)
  6296. : fragmentSlotScopeIds;
  6297. }
  6298. if (n1 == null) {
  6299. hostInsert(fragmentStartAnchor, container, anchor);
  6300. hostInsert(fragmentEndAnchor, container, anchor);
  6301. // a fragment can only have array children
  6302. // since they are either generated by the compiler, or implicitly created
  6303. // from arrays.
  6304. mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6305. }
  6306. else {
  6307. if (patchFlag > 0 &&
  6308. patchFlag & 64 /* STABLE_FRAGMENT */ &&
  6309. dynamicChildren &&
  6310. // #2715 the previous fragment could've been a BAILed one as a result
  6311. // of renderSlot() with no valid children
  6312. n1.dynamicChildren) {
  6313. // a stable fragment (template root or <template v-for>) doesn't need to
  6314. // patch children order, but it may contain dynamicChildren.
  6315. patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
  6316. if (parentComponent && parentComponent.type.__hmrId) {
  6317. traverseStaticChildren(n1, n2);
  6318. }
  6319. else if (
  6320. // #2080 if the stable fragment has a key, it's a <template v-for> that may
  6321. // get moved around. Make sure all root level vnodes inherit el.
  6322. // #2134 or if it's a component root, it may also get moved around
  6323. // as the component is being moved.
  6324. n2.key != null ||
  6325. (parentComponent && n2 === parentComponent.subTree)) {
  6326. traverseStaticChildren(n1, n2, true /* shallow */);
  6327. }
  6328. }
  6329. else {
  6330. // keyed / unkeyed, or manual fragments.
  6331. // for keyed & unkeyed, since they are compiler generated from v-for,
  6332. // each child is guaranteed to be a block so the fragment will never
  6333. // have dynamicChildren.
  6334. patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6335. }
  6336. }
  6337. };
  6338. const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6339. n2.slotScopeIds = slotScopeIds;
  6340. if (n1 == null) {
  6341. if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
  6342. parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
  6343. }
  6344. else {
  6345. mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  6346. }
  6347. }
  6348. else {
  6349. updateComponent(n1, n2, optimized);
  6350. }
  6351. };
  6352. const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  6353. const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
  6354. if (instance.type.__hmrId) {
  6355. registerHMR(instance);
  6356. }
  6357. {
  6358. pushWarningContext(initialVNode);
  6359. startMeasure(instance, `mount`);
  6360. }
  6361. // inject renderer internals for keepAlive
  6362. if (isKeepAlive(initialVNode)) {
  6363. instance.ctx.renderer = internals;
  6364. }
  6365. // resolve props and slots for setup context
  6366. {
  6367. {
  6368. startMeasure(instance, `init`);
  6369. }
  6370. setupComponent(instance);
  6371. {
  6372. endMeasure(instance, `init`);
  6373. }
  6374. }
  6375. // setup() is async. This component relies on async logic to be resolved
  6376. // before proceeding
  6377. if (instance.asyncDep) {
  6378. parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
  6379. // Give it a placeholder if this is not hydration
  6380. // TODO handle self-defined fallback
  6381. if (!initialVNode.el) {
  6382. const placeholder = (instance.subTree = createVNode(Comment));
  6383. processCommentNode(null, placeholder, container, anchor);
  6384. }
  6385. return;
  6386. }
  6387. setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
  6388. {
  6389. popWarningContext();
  6390. endMeasure(instance, `mount`);
  6391. }
  6392. };
  6393. const updateComponent = (n1, n2, optimized) => {
  6394. const instance = (n2.component = n1.component);
  6395. if (shouldUpdateComponent(n1, n2, optimized)) {
  6396. if (instance.asyncDep &&
  6397. !instance.asyncResolved) {
  6398. // async & still pending - just update props and slots
  6399. // since the component's reactive effect for render isn't set-up yet
  6400. {
  6401. pushWarningContext(n2);
  6402. }
  6403. updateComponentPreRender(instance, n2, optimized);
  6404. {
  6405. popWarningContext();
  6406. }
  6407. return;
  6408. }
  6409. else {
  6410. // normal update
  6411. instance.next = n2;
  6412. // in case the child component is also queued, remove it to avoid
  6413. // double updating the same child component in the same flush.
  6414. invalidateJob(instance.update);
  6415. // instance.update is the reactive effect.
  6416. instance.update();
  6417. }
  6418. }
  6419. else {
  6420. // no update needed. just copy over properties
  6421. n2.component = n1.component;
  6422. n2.el = n1.el;
  6423. instance.vnode = n2;
  6424. }
  6425. };
  6426. const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
  6427. const componentUpdateFn = () => {
  6428. if (!instance.isMounted) {
  6429. let vnodeHook;
  6430. const { el, props } = initialVNode;
  6431. const { bm, m, parent } = instance;
  6432. const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
  6433. toggleRecurse(instance, false);
  6434. // beforeMount hook
  6435. if (bm) {
  6436. invokeArrayFns(bm);
  6437. }
  6438. // onVnodeBeforeMount
  6439. if (!isAsyncWrapperVNode &&
  6440. (vnodeHook = props && props.onVnodeBeforeMount)) {
  6441. invokeVNodeHook(vnodeHook, parent, initialVNode);
  6442. }
  6443. toggleRecurse(instance, true);
  6444. if (el && hydrateNode) {
  6445. // vnode has adopted host node - perform hydration instead of mount.
  6446. const hydrateSubTree = () => {
  6447. {
  6448. startMeasure(instance, `render`);
  6449. }
  6450. instance.subTree = renderComponentRoot(instance);
  6451. {
  6452. endMeasure(instance, `render`);
  6453. }
  6454. {
  6455. startMeasure(instance, `hydrate`);
  6456. }
  6457. hydrateNode(el, instance.subTree, instance, parentSuspense, null);
  6458. {
  6459. endMeasure(instance, `hydrate`);
  6460. }
  6461. };
  6462. if (isAsyncWrapperVNode) {
  6463. initialVNode.type.__asyncLoader().then(
  6464. // note: we are moving the render call into an async callback,
  6465. // which means it won't track dependencies - but it's ok because
  6466. // a server-rendered async wrapper is already in resolved state
  6467. // and it will never need to change.
  6468. () => !instance.isUnmounted && hydrateSubTree());
  6469. }
  6470. else {
  6471. hydrateSubTree();
  6472. }
  6473. }
  6474. else {
  6475. {
  6476. startMeasure(instance, `render`);
  6477. }
  6478. const subTree = (instance.subTree = renderComponentRoot(instance));
  6479. {
  6480. endMeasure(instance, `render`);
  6481. }
  6482. {
  6483. startMeasure(instance, `patch`);
  6484. }
  6485. patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
  6486. {
  6487. endMeasure(instance, `patch`);
  6488. }
  6489. initialVNode.el = subTree.el;
  6490. }
  6491. // mounted hook
  6492. if (m) {
  6493. queuePostRenderEffect(m, parentSuspense);
  6494. }
  6495. // onVnodeMounted
  6496. if (!isAsyncWrapperVNode &&
  6497. (vnodeHook = props && props.onVnodeMounted)) {
  6498. const scopedInitialVNode = initialVNode;
  6499. queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
  6500. }
  6501. // activated hook for keep-alive roots.
  6502. // #1742 activated hook must be accessed after first render
  6503. // since the hook may be injected by a child keep-alive
  6504. if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  6505. instance.a && queuePostRenderEffect(instance.a, parentSuspense);
  6506. }
  6507. instance.isMounted = true;
  6508. {
  6509. devtoolsComponentAdded(instance);
  6510. }
  6511. // #2458: deference mount-only object parameters to prevent memleaks
  6512. initialVNode = container = anchor = null;
  6513. }
  6514. else {
  6515. // updateComponent
  6516. // This is triggered by mutation of component's own state (next: null)
  6517. // OR parent calling processComponent (next: VNode)
  6518. let { next, bu, u, parent, vnode } = instance;
  6519. let originNext = next;
  6520. let vnodeHook;
  6521. {
  6522. pushWarningContext(next || instance.vnode);
  6523. }
  6524. // Disallow component effect recursion during pre-lifecycle hooks.
  6525. toggleRecurse(instance, false);
  6526. if (next) {
  6527. next.el = vnode.el;
  6528. updateComponentPreRender(instance, next, optimized);
  6529. }
  6530. else {
  6531. next = vnode;
  6532. }
  6533. // beforeUpdate hook
  6534. if (bu) {
  6535. invokeArrayFns(bu);
  6536. }
  6537. // onVnodeBeforeUpdate
  6538. if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
  6539. invokeVNodeHook(vnodeHook, parent, next, vnode);
  6540. }
  6541. toggleRecurse(instance, true);
  6542. // render
  6543. {
  6544. startMeasure(instance, `render`);
  6545. }
  6546. const nextTree = renderComponentRoot(instance);
  6547. {
  6548. endMeasure(instance, `render`);
  6549. }
  6550. const prevTree = instance.subTree;
  6551. instance.subTree = nextTree;
  6552. {
  6553. startMeasure(instance, `patch`);
  6554. }
  6555. patch(prevTree, nextTree,
  6556. // parent may have changed if it's in a teleport
  6557. hostParentNode(prevTree.el),
  6558. // anchor may have changed if it's in a fragment
  6559. getNextHostNode(prevTree), instance, parentSuspense, isSVG);
  6560. {
  6561. endMeasure(instance, `patch`);
  6562. }
  6563. next.el = nextTree.el;
  6564. if (originNext === null) {
  6565. // self-triggered update. In case of HOC, update parent component
  6566. // vnode el. HOC is indicated by parent instance's subTree pointing
  6567. // to child component's vnode
  6568. updateHOCHostEl(instance, nextTree.el);
  6569. }
  6570. // updated hook
  6571. if (u) {
  6572. queuePostRenderEffect(u, parentSuspense);
  6573. }
  6574. // onVnodeUpdated
  6575. if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
  6576. queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
  6577. }
  6578. {
  6579. devtoolsComponentUpdated(instance);
  6580. }
  6581. {
  6582. popWarningContext();
  6583. }
  6584. }
  6585. };
  6586. // create reactive effect for rendering
  6587. const effect = (instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(instance.update), instance.scope // track it in component's effect scope
  6588. ));
  6589. const update = (instance.update = effect.run.bind(effect));
  6590. update.id = instance.uid;
  6591. // allowRecurse
  6592. // #1801, #2043 component render effects should allow recursive updates
  6593. toggleRecurse(instance, true);
  6594. {
  6595. effect.onTrack = instance.rtc
  6596. ? e => invokeArrayFns(instance.rtc, e)
  6597. : void 0;
  6598. effect.onTrigger = instance.rtg
  6599. ? e => invokeArrayFns(instance.rtg, e)
  6600. : void 0;
  6601. // @ts-ignore (for scheduler)
  6602. update.ownerInstance = instance;
  6603. }
  6604. update();
  6605. };
  6606. const updateComponentPreRender = (instance, nextVNode, optimized) => {
  6607. nextVNode.component = instance;
  6608. const prevProps = instance.vnode.props;
  6609. instance.vnode = nextVNode;
  6610. instance.next = null;
  6611. updateProps(instance, nextVNode.props, prevProps, optimized);
  6612. updateSlots(instance, nextVNode.children, optimized);
  6613. pauseTracking();
  6614. // props update may have triggered pre-flush watchers.
  6615. // flush them before the render update.
  6616. flushPreFlushCbs(undefined, instance.update);
  6617. resetTracking();
  6618. };
  6619. const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
  6620. const c1 = n1 && n1.children;
  6621. const prevShapeFlag = n1 ? n1.shapeFlag : 0;
  6622. const c2 = n2.children;
  6623. const { patchFlag, shapeFlag } = n2;
  6624. // fast path
  6625. if (patchFlag > 0) {
  6626. if (patchFlag & 128 /* KEYED_FRAGMENT */) {
  6627. // this could be either fully-keyed or mixed (some keyed some not)
  6628. // presence of patchFlag means children are guaranteed to be arrays
  6629. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6630. return;
  6631. }
  6632. else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
  6633. // unkeyed
  6634. patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6635. return;
  6636. }
  6637. }
  6638. // children has 3 possibilities: text, array or no children.
  6639. if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  6640. // text children fast path
  6641. if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
  6642. unmountChildren(c1, parentComponent, parentSuspense);
  6643. }
  6644. if (c2 !== c1) {
  6645. hostSetElementText(container, c2);
  6646. }
  6647. }
  6648. else {
  6649. if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
  6650. // prev children was array
  6651. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6652. // two arrays, cannot assume anything, do full diff
  6653. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6654. }
  6655. else {
  6656. // no new children, just unmount old
  6657. unmountChildren(c1, parentComponent, parentSuspense, true);
  6658. }
  6659. }
  6660. else {
  6661. // prev children was text OR null
  6662. // new children is array OR null
  6663. if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
  6664. hostSetElementText(container, '');
  6665. }
  6666. // mount new if array
  6667. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6668. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6669. }
  6670. }
  6671. }
  6672. };
  6673. const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6674. c1 = c1 || EMPTY_ARR;
  6675. c2 = c2 || EMPTY_ARR;
  6676. const oldLength = c1.length;
  6677. const newLength = c2.length;
  6678. const commonLength = Math.min(oldLength, newLength);
  6679. let i;
  6680. for (i = 0; i < commonLength; i++) {
  6681. const nextChild = (c2[i] = optimized
  6682. ? cloneIfMounted(c2[i])
  6683. : normalizeVNode(c2[i]));
  6684. patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6685. }
  6686. if (oldLength > newLength) {
  6687. // remove old
  6688. unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
  6689. }
  6690. else {
  6691. // mount new
  6692. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
  6693. }
  6694. };
  6695. // can be all-keyed or mixed
  6696. const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  6697. let i = 0;
  6698. const l2 = c2.length;
  6699. let e1 = c1.length - 1; // prev ending index
  6700. let e2 = l2 - 1; // next ending index
  6701. // 1. sync from start
  6702. // (a b) c
  6703. // (a b) d e
  6704. while (i <= e1 && i <= e2) {
  6705. const n1 = c1[i];
  6706. const n2 = (c2[i] = optimized
  6707. ? cloneIfMounted(c2[i])
  6708. : normalizeVNode(c2[i]));
  6709. if (isSameVNodeType(n1, n2)) {
  6710. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6711. }
  6712. else {
  6713. break;
  6714. }
  6715. i++;
  6716. }
  6717. // 2. sync from end
  6718. // a (b c)
  6719. // d e (b c)
  6720. while (i <= e1 && i <= e2) {
  6721. const n1 = c1[e1];
  6722. const n2 = (c2[e2] = optimized
  6723. ? cloneIfMounted(c2[e2])
  6724. : normalizeVNode(c2[e2]));
  6725. if (isSameVNodeType(n1, n2)) {
  6726. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6727. }
  6728. else {
  6729. break;
  6730. }
  6731. e1--;
  6732. e2--;
  6733. }
  6734. // 3. common sequence + mount
  6735. // (a b)
  6736. // (a b) c
  6737. // i = 2, e1 = 1, e2 = 2
  6738. // (a b)
  6739. // c (a b)
  6740. // i = 0, e1 = -1, e2 = 0
  6741. if (i > e1) {
  6742. if (i <= e2) {
  6743. const nextPos = e2 + 1;
  6744. const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
  6745. while (i <= e2) {
  6746. patch(null, (c2[i] = optimized
  6747. ? cloneIfMounted(c2[i])
  6748. : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6749. i++;
  6750. }
  6751. }
  6752. }
  6753. // 4. common sequence + unmount
  6754. // (a b) c
  6755. // (a b)
  6756. // i = 2, e1 = 2, e2 = 1
  6757. // a (b c)
  6758. // (b c)
  6759. // i = 0, e1 = 0, e2 = -1
  6760. else if (i > e2) {
  6761. while (i <= e1) {
  6762. unmount(c1[i], parentComponent, parentSuspense, true);
  6763. i++;
  6764. }
  6765. }
  6766. // 5. unknown sequence
  6767. // [i ... e1 + 1]: a b [c d e] f g
  6768. // [i ... e2 + 1]: a b [e d c h] f g
  6769. // i = 2, e1 = 4, e2 = 5
  6770. else {
  6771. const s1 = i; // prev starting index
  6772. const s2 = i; // next starting index
  6773. // 5.1 build key:index map for newChildren
  6774. const keyToNewIndexMap = new Map();
  6775. for (i = s2; i <= e2; i++) {
  6776. const nextChild = (c2[i] = optimized
  6777. ? cloneIfMounted(c2[i])
  6778. : normalizeVNode(c2[i]));
  6779. if (nextChild.key != null) {
  6780. if (keyToNewIndexMap.has(nextChild.key)) {
  6781. warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
  6782. }
  6783. keyToNewIndexMap.set(nextChild.key, i);
  6784. }
  6785. }
  6786. // 5.2 loop through old children left to be patched and try to patch
  6787. // matching nodes & remove nodes that are no longer present
  6788. let j;
  6789. let patched = 0;
  6790. const toBePatched = e2 - s2 + 1;
  6791. let moved = false;
  6792. // used to track whether any node has moved
  6793. let maxNewIndexSoFar = 0;
  6794. // works as Map<newIndex, oldIndex>
  6795. // Note that oldIndex is offset by +1
  6796. // and oldIndex = 0 is a special value indicating the new node has
  6797. // no corresponding old node.
  6798. // used for determining longest stable subsequence
  6799. const newIndexToOldIndexMap = new Array(toBePatched);
  6800. for (i = 0; i < toBePatched; i++)
  6801. newIndexToOldIndexMap[i] = 0;
  6802. for (i = s1; i <= e1; i++) {
  6803. const prevChild = c1[i];
  6804. if (patched >= toBePatched) {
  6805. // all new children have been patched so this can only be a removal
  6806. unmount(prevChild, parentComponent, parentSuspense, true);
  6807. continue;
  6808. }
  6809. let newIndex;
  6810. if (prevChild.key != null) {
  6811. newIndex = keyToNewIndexMap.get(prevChild.key);
  6812. }
  6813. else {
  6814. // key-less node, try to locate a key-less node of the same type
  6815. for (j = s2; j <= e2; j++) {
  6816. if (newIndexToOldIndexMap[j - s2] === 0 &&
  6817. isSameVNodeType(prevChild, c2[j])) {
  6818. newIndex = j;
  6819. break;
  6820. }
  6821. }
  6822. }
  6823. if (newIndex === undefined) {
  6824. unmount(prevChild, parentComponent, parentSuspense, true);
  6825. }
  6826. else {
  6827. newIndexToOldIndexMap[newIndex - s2] = i + 1;
  6828. if (newIndex >= maxNewIndexSoFar) {
  6829. maxNewIndexSoFar = newIndex;
  6830. }
  6831. else {
  6832. moved = true;
  6833. }
  6834. patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6835. patched++;
  6836. }
  6837. }
  6838. // 5.3 move and mount
  6839. // generate longest stable subsequence only when nodes have moved
  6840. const increasingNewIndexSequence = moved
  6841. ? getSequence(newIndexToOldIndexMap)
  6842. : EMPTY_ARR;
  6843. j = increasingNewIndexSequence.length - 1;
  6844. // looping backwards so that we can use last patched node as anchor
  6845. for (i = toBePatched - 1; i >= 0; i--) {
  6846. const nextIndex = s2 + i;
  6847. const nextChild = c2[nextIndex];
  6848. const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
  6849. if (newIndexToOldIndexMap[i] === 0) {
  6850. // mount new
  6851. patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6852. }
  6853. else if (moved) {
  6854. // move if:
  6855. // There is no stable subsequence (e.g. a reverse)
  6856. // OR current node is not among the stable sequence
  6857. if (j < 0 || i !== increasingNewIndexSequence[j]) {
  6858. move(nextChild, container, anchor, 2 /* REORDER */);
  6859. }
  6860. else {
  6861. j--;
  6862. }
  6863. }
  6864. }
  6865. }
  6866. };
  6867. const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
  6868. const { el, type, transition, children, shapeFlag } = vnode;
  6869. if (shapeFlag & 6 /* COMPONENT */) {
  6870. move(vnode.component.subTree, container, anchor, moveType);
  6871. return;
  6872. }
  6873. if (shapeFlag & 128 /* SUSPENSE */) {
  6874. vnode.suspense.move(container, anchor, moveType);
  6875. return;
  6876. }
  6877. if (shapeFlag & 64 /* TELEPORT */) {
  6878. type.move(vnode, container, anchor, internals);
  6879. return;
  6880. }
  6881. if (type === Fragment) {
  6882. hostInsert(el, container, anchor);
  6883. for (let i = 0; i < children.length; i++) {
  6884. move(children[i], container, anchor, moveType);
  6885. }
  6886. hostInsert(vnode.anchor, container, anchor);
  6887. return;
  6888. }
  6889. if (type === Static) {
  6890. moveStaticNode(vnode, container, anchor);
  6891. return;
  6892. }
  6893. // single nodes
  6894. const needTransition = moveType !== 2 /* REORDER */ &&
  6895. shapeFlag & 1 /* ELEMENT */ &&
  6896. transition;
  6897. if (needTransition) {
  6898. if (moveType === 0 /* ENTER */) {
  6899. transition.beforeEnter(el);
  6900. hostInsert(el, container, anchor);
  6901. queuePostRenderEffect(() => transition.enter(el), parentSuspense);
  6902. }
  6903. else {
  6904. const { leave, delayLeave, afterLeave } = transition;
  6905. const remove = () => hostInsert(el, container, anchor);
  6906. const performLeave = () => {
  6907. leave(el, () => {
  6908. remove();
  6909. afterLeave && afterLeave();
  6910. });
  6911. };
  6912. if (delayLeave) {
  6913. delayLeave(el, remove, performLeave);
  6914. }
  6915. else {
  6916. performLeave();
  6917. }
  6918. }
  6919. }
  6920. else {
  6921. hostInsert(el, container, anchor);
  6922. }
  6923. };
  6924. const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
  6925. const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
  6926. // unset ref
  6927. if (ref != null) {
  6928. setRef(ref, null, parentSuspense, vnode, true);
  6929. }
  6930. if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  6931. parentComponent.ctx.deactivate(vnode);
  6932. return;
  6933. }
  6934. const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
  6935. const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
  6936. let vnodeHook;
  6937. if (shouldInvokeVnodeHook &&
  6938. (vnodeHook = props && props.onVnodeBeforeUnmount)) {
  6939. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  6940. }
  6941. if (shapeFlag & 6 /* COMPONENT */) {
  6942. unmountComponent(vnode.component, parentSuspense, doRemove);
  6943. }
  6944. else {
  6945. if (shapeFlag & 128 /* SUSPENSE */) {
  6946. vnode.suspense.unmount(parentSuspense, doRemove);
  6947. return;
  6948. }
  6949. if (shouldInvokeDirs) {
  6950. invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
  6951. }
  6952. if (shapeFlag & 64 /* TELEPORT */) {
  6953. vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
  6954. }
  6955. else if (dynamicChildren &&
  6956. // #1153: fast path should not be taken for non-stable (v-for) fragments
  6957. (type !== Fragment ||
  6958. (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
  6959. // fast path for block nodes: only need to unmount dynamic children.
  6960. unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
  6961. }
  6962. else if ((type === Fragment &&
  6963. patchFlag &
  6964. (128 /* KEYED_FRAGMENT */ | 256 /* UNKEYED_FRAGMENT */)) ||
  6965. (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
  6966. unmountChildren(children, parentComponent, parentSuspense);
  6967. }
  6968. if (doRemove) {
  6969. remove(vnode);
  6970. }
  6971. }
  6972. if ((shouldInvokeVnodeHook &&
  6973. (vnodeHook = props && props.onVnodeUnmounted)) ||
  6974. shouldInvokeDirs) {
  6975. queuePostRenderEffect(() => {
  6976. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  6977. shouldInvokeDirs &&
  6978. invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
  6979. }, parentSuspense);
  6980. }
  6981. };
  6982. const remove = vnode => {
  6983. const { type, el, anchor, transition } = vnode;
  6984. if (type === Fragment) {
  6985. if (vnode.patchFlag > 0 &&
  6986. vnode.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */ &&
  6987. transition &&
  6988. !transition.persisted) {
  6989. vnode.children.forEach(child => {
  6990. if (child.type === Comment) {
  6991. hostRemove(child.el);
  6992. }
  6993. else {
  6994. remove(child);
  6995. }
  6996. });
  6997. }
  6998. else {
  6999. removeFragment(el, anchor);
  7000. }
  7001. return;
  7002. }
  7003. if (type === Static) {
  7004. removeStaticNode(vnode);
  7005. return;
  7006. }
  7007. const performRemove = () => {
  7008. hostRemove(el);
  7009. if (transition && !transition.persisted && transition.afterLeave) {
  7010. transition.afterLeave();
  7011. }
  7012. };
  7013. if (vnode.shapeFlag & 1 /* ELEMENT */ &&
  7014. transition &&
  7015. !transition.persisted) {
  7016. const { leave, delayLeave } = transition;
  7017. const performLeave = () => leave(el, performRemove);
  7018. if (delayLeave) {
  7019. delayLeave(vnode.el, performRemove, performLeave);
  7020. }
  7021. else {
  7022. performLeave();
  7023. }
  7024. }
  7025. else {
  7026. performRemove();
  7027. }
  7028. };
  7029. const removeFragment = (cur, end) => {
  7030. // For fragments, directly remove all contained DOM nodes.
  7031. // (fragment child nodes cannot have transition)
  7032. let next;
  7033. while (cur !== end) {
  7034. next = hostNextSibling(cur);
  7035. hostRemove(cur);
  7036. cur = next;
  7037. }
  7038. hostRemove(end);
  7039. };
  7040. const unmountComponent = (instance, parentSuspense, doRemove) => {
  7041. if (instance.type.__hmrId) {
  7042. unregisterHMR(instance);
  7043. }
  7044. const { bum, scope, update, subTree, um } = instance;
  7045. // beforeUnmount hook
  7046. if (bum) {
  7047. invokeArrayFns(bum);
  7048. }
  7049. // stop effects in component scope
  7050. scope.stop();
  7051. // update may be null if a component is unmounted before its async
  7052. // setup has resolved.
  7053. if (update) {
  7054. // so that scheduler will no longer invoke it
  7055. update.active = false;
  7056. unmount(subTree, instance, parentSuspense, doRemove);
  7057. }
  7058. // unmounted hook
  7059. if (um) {
  7060. queuePostRenderEffect(um, parentSuspense);
  7061. }
  7062. queuePostRenderEffect(() => {
  7063. instance.isUnmounted = true;
  7064. }, parentSuspense);
  7065. // A component with async dep inside a pending suspense is unmounted before
  7066. // its async dep resolves. This should remove the dep from the suspense, and
  7067. // cause the suspense to resolve immediately if that was the last dep.
  7068. if (parentSuspense &&
  7069. parentSuspense.pendingBranch &&
  7070. !parentSuspense.isUnmounted &&
  7071. instance.asyncDep &&
  7072. !instance.asyncResolved &&
  7073. instance.suspenseId === parentSuspense.pendingId) {
  7074. parentSuspense.deps--;
  7075. if (parentSuspense.deps === 0) {
  7076. parentSuspense.resolve();
  7077. }
  7078. }
  7079. {
  7080. devtoolsComponentRemoved(instance);
  7081. }
  7082. };
  7083. const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
  7084. for (let i = start; i < children.length; i++) {
  7085. unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
  7086. }
  7087. };
  7088. const getNextHostNode = vnode => {
  7089. if (vnode.shapeFlag & 6 /* COMPONENT */) {
  7090. return getNextHostNode(vnode.component.subTree);
  7091. }
  7092. if (vnode.shapeFlag & 128 /* SUSPENSE */) {
  7093. return vnode.suspense.next();
  7094. }
  7095. return hostNextSibling((vnode.anchor || vnode.el));
  7096. };
  7097. const render = (vnode, container, isSVG) => {
  7098. if (vnode == null) {
  7099. if (container._vnode) {
  7100. unmount(container._vnode, null, null, true);
  7101. }
  7102. }
  7103. else {
  7104. patch(container._vnode || null, vnode, container, null, null, null, isSVG);
  7105. }
  7106. flushPostFlushCbs();
  7107. container._vnode = vnode;
  7108. };
  7109. const internals = {
  7110. p: patch,
  7111. um: unmount,
  7112. m: move,
  7113. r: remove,
  7114. mt: mountComponent,
  7115. mc: mountChildren,
  7116. pc: patchChildren,
  7117. pbc: patchBlockChildren,
  7118. n: getNextHostNode,
  7119. o: options
  7120. };
  7121. let hydrate;
  7122. let hydrateNode;
  7123. if (createHydrationFns) {
  7124. [hydrate, hydrateNode] = createHydrationFns(internals);
  7125. }
  7126. return {
  7127. render,
  7128. hydrate,
  7129. createApp: createAppAPI(render, hydrate)
  7130. };
  7131. }
  7132. function toggleRecurse({ effect, update }, allowed) {
  7133. effect.allowRecurse = update.allowRecurse = allowed;
  7134. }
  7135. /**
  7136. * #1156
  7137. * When a component is HMR-enabled, we need to make sure that all static nodes
  7138. * inside a block also inherit the DOM element from the previous tree so that
  7139. * HMR updates (which are full updates) can retrieve the element for patching.
  7140. *
  7141. * #2080
  7142. * Inside keyed `template` fragment static children, if a fragment is moved,
  7143. * the children will always be moved. Therefore, in order to ensure correct move
  7144. * position, el should be inherited from previous nodes.
  7145. */
  7146. function traverseStaticChildren(n1, n2, shallow = false) {
  7147. const ch1 = n1.children;
  7148. const ch2 = n2.children;
  7149. if (isArray(ch1) && isArray(ch2)) {
  7150. for (let i = 0; i < ch1.length; i++) {
  7151. // this is only called in the optimized path so array children are
  7152. // guaranteed to be vnodes
  7153. const c1 = ch1[i];
  7154. let c2 = ch2[i];
  7155. if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
  7156. if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
  7157. c2 = ch2[i] = cloneIfMounted(ch2[i]);
  7158. c2.el = c1.el;
  7159. }
  7160. if (!shallow)
  7161. traverseStaticChildren(c1, c2);
  7162. }
  7163. // also inherit for comment nodes, but not placeholders (e.g. v-if which
  7164. // would have received .el during block patch)
  7165. if (c2.type === Comment && !c2.el) {
  7166. c2.el = c1.el;
  7167. }
  7168. }
  7169. }
  7170. }
  7171. // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
  7172. function getSequence(arr) {
  7173. const p = arr.slice();
  7174. const result = [0];
  7175. let i, j, u, v, c;
  7176. const len = arr.length;
  7177. for (i = 0; i < len; i++) {
  7178. const arrI = arr[i];
  7179. if (arrI !== 0) {
  7180. j = result[result.length - 1];
  7181. if (arr[j] < arrI) {
  7182. p[i] = j;
  7183. result.push(i);
  7184. continue;
  7185. }
  7186. u = 0;
  7187. v = result.length - 1;
  7188. while (u < v) {
  7189. c = (u + v) >> 1;
  7190. if (arr[result[c]] < arrI) {
  7191. u = c + 1;
  7192. }
  7193. else {
  7194. v = c;
  7195. }
  7196. }
  7197. if (arrI < arr[result[u]]) {
  7198. if (u > 0) {
  7199. p[i] = result[u - 1];
  7200. }
  7201. result[u] = i;
  7202. }
  7203. }
  7204. }
  7205. u = result.length;
  7206. v = result[u - 1];
  7207. while (u-- > 0) {
  7208. result[u] = v;
  7209. v = p[v];
  7210. }
  7211. return result;
  7212. }
  7213. const isTeleport = (type) => type.__isTeleport;
  7214. const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
  7215. const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
  7216. const resolveTarget = (props, select) => {
  7217. const targetSelector = props && props.to;
  7218. if (isString(targetSelector)) {
  7219. if (!select) {
  7220. warn$1(`Current renderer does not support string target for Teleports. ` +
  7221. `(missing querySelector renderer option)`);
  7222. return null;
  7223. }
  7224. else {
  7225. const target = select(targetSelector);
  7226. if (!target) {
  7227. warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
  7228. `Note the target element must exist before the component is mounted - ` +
  7229. `i.e. the target cannot be rendered by the component itself, and ` +
  7230. `ideally should be outside of the entire Vue component tree.`);
  7231. }
  7232. return target;
  7233. }
  7234. }
  7235. else {
  7236. if (!targetSelector && !isTeleportDisabled(props)) {
  7237. warn$1(`Invalid Teleport target: ${targetSelector}`);
  7238. }
  7239. return targetSelector;
  7240. }
  7241. };
  7242. const TeleportImpl = {
  7243. __isTeleport: true,
  7244. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
  7245. const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
  7246. const disabled = isTeleportDisabled(n2.props);
  7247. let { shapeFlag, children, dynamicChildren } = n2;
  7248. // #3302
  7249. // HMR updated, force full diff
  7250. if (isHmrUpdating) {
  7251. optimized = false;
  7252. dynamicChildren = null;
  7253. }
  7254. if (n1 == null) {
  7255. // insert anchors in the main view
  7256. const placeholder = (n2.el = createComment('teleport start')
  7257. );
  7258. const mainAnchor = (n2.anchor = createComment('teleport end')
  7259. );
  7260. insert(placeholder, container, anchor);
  7261. insert(mainAnchor, container, anchor);
  7262. const target = (n2.target = resolveTarget(n2.props, querySelector));
  7263. const targetAnchor = (n2.targetAnchor = createText(''));
  7264. if (target) {
  7265. insert(targetAnchor, target);
  7266. // #2652 we could be teleporting from a non-SVG tree into an SVG tree
  7267. isSVG = isSVG || isTargetSVG(target);
  7268. }
  7269. else if (!disabled) {
  7270. warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
  7271. }
  7272. const mount = (container, anchor) => {
  7273. // Teleport *always* has Array children. This is enforced in both the
  7274. // compiler and vnode children normalization.
  7275. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  7276. mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  7277. }
  7278. };
  7279. if (disabled) {
  7280. mount(container, mainAnchor);
  7281. }
  7282. else if (target) {
  7283. mount(target, targetAnchor);
  7284. }
  7285. }
  7286. else {
  7287. // update content
  7288. n2.el = n1.el;
  7289. const mainAnchor = (n2.anchor = n1.anchor);
  7290. const target = (n2.target = n1.target);
  7291. const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
  7292. const wasDisabled = isTeleportDisabled(n1.props);
  7293. const currentContainer = wasDisabled ? container : target;
  7294. const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
  7295. isSVG = isSVG || isTargetSVG(target);
  7296. if (dynamicChildren) {
  7297. // fast path when the teleport happens to be a block root
  7298. patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
  7299. // even in block tree mode we need to make sure all root-level nodes
  7300. // in the teleport inherit previous DOM references so that they can
  7301. // be moved in future patches.
  7302. traverseStaticChildren(n1, n2, true);
  7303. }
  7304. else if (!optimized) {
  7305. patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
  7306. }
  7307. if (disabled) {
  7308. if (!wasDisabled) {
  7309. // enabled -> disabled
  7310. // move into main container
  7311. moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
  7312. }
  7313. }
  7314. else {
  7315. // target changed
  7316. if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
  7317. const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
  7318. if (nextTarget) {
  7319. moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
  7320. }
  7321. else {
  7322. warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
  7323. }
  7324. }
  7325. else if (wasDisabled) {
  7326. // disabled -> enabled
  7327. // move into teleport target
  7328. moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
  7329. }
  7330. }
  7331. }
  7332. },
  7333. remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
  7334. const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
  7335. if (target) {
  7336. hostRemove(targetAnchor);
  7337. }
  7338. // an unmounted teleport should always remove its children if not disabled
  7339. if (doRemove || !isTeleportDisabled(props)) {
  7340. hostRemove(anchor);
  7341. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  7342. for (let i = 0; i < children.length; i++) {
  7343. const child = children[i];
  7344. unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
  7345. }
  7346. }
  7347. }
  7348. },
  7349. move: moveTeleport,
  7350. hydrate: hydrateTeleport
  7351. };
  7352. function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
  7353. // move target anchor if this is a target change.
  7354. if (moveType === 0 /* TARGET_CHANGE */) {
  7355. insert(vnode.targetAnchor, container, parentAnchor);
  7356. }
  7357. const { el, anchor, shapeFlag, children, props } = vnode;
  7358. const isReorder = moveType === 2 /* REORDER */;
  7359. // move main view anchor if this is a re-order.
  7360. if (isReorder) {
  7361. insert(el, container, parentAnchor);
  7362. }
  7363. // if this is a re-order and teleport is enabled (content is in target)
  7364. // do not move children. So the opposite is: only move children if this
  7365. // is not a reorder, or the teleport is disabled
  7366. if (!isReorder || isTeleportDisabled(props)) {
  7367. // Teleport has either Array children or no children.
  7368. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  7369. for (let i = 0; i < children.length; i++) {
  7370. move(children[i], container, parentAnchor, 2 /* REORDER */);
  7371. }
  7372. }
  7373. }
  7374. // move main view anchor if this is a re-order.
  7375. if (isReorder) {
  7376. insert(anchor, container, parentAnchor);
  7377. }
  7378. }
  7379. function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
  7380. const target = (vnode.target = resolveTarget(vnode.props, querySelector));
  7381. if (target) {
  7382. // if multiple teleports rendered to the same target element, we need to
  7383. // pick up from where the last teleport finished instead of the first node
  7384. const targetNode = target._lpa || target.firstChild;
  7385. if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
  7386. if (isTeleportDisabled(vnode.props)) {
  7387. vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
  7388. vnode.targetAnchor = targetNode;
  7389. }
  7390. else {
  7391. vnode.anchor = nextSibling(node);
  7392. vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
  7393. }
  7394. target._lpa =
  7395. vnode.targetAnchor && nextSibling(vnode.targetAnchor);
  7396. }
  7397. }
  7398. return vnode.anchor && nextSibling(vnode.anchor);
  7399. }
  7400. // Force-casted public typing for h and TSX props inference
  7401. const Teleport = TeleportImpl;
  7402. const COMPONENTS = 'components';
  7403. const DIRECTIVES = 'directives';
  7404. /**
  7405. * @private
  7406. */
  7407. function resolveComponent(name, maybeSelfReference) {
  7408. return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
  7409. }
  7410. const NULL_DYNAMIC_COMPONENT = Symbol();
  7411. /**
  7412. * @private
  7413. */
  7414. function resolveDynamicComponent(component) {
  7415. if (isString(component)) {
  7416. return resolveAsset(COMPONENTS, component, false) || component;
  7417. }
  7418. else {
  7419. // invalid types will fallthrough to createVNode and raise warning
  7420. return (component || NULL_DYNAMIC_COMPONENT);
  7421. }
  7422. }
  7423. /**
  7424. * @private
  7425. */
  7426. function resolveDirective(name) {
  7427. return resolveAsset(DIRECTIVES, name);
  7428. }
  7429. // implementation
  7430. function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
  7431. const instance = currentRenderingInstance || currentInstance;
  7432. if (instance) {
  7433. const Component = instance.type;
  7434. // explicit self name has highest priority
  7435. if (type === COMPONENTS) {
  7436. const selfName = getComponentName(Component);
  7437. if (selfName &&
  7438. (selfName === name ||
  7439. selfName === camelize(name) ||
  7440. selfName === capitalize(camelize(name)))) {
  7441. return Component;
  7442. }
  7443. }
  7444. const res =
  7445. // local registration
  7446. // check instance[type] first which is resolved for options API
  7447. resolve(instance[type] || Component[type], name) ||
  7448. // global registration
  7449. resolve(instance.appContext[type], name);
  7450. if (!res && maybeSelfReference) {
  7451. // fallback to implicit self-reference
  7452. return Component;
  7453. }
  7454. if (warnMissing && !res) {
  7455. const extra = type === COMPONENTS
  7456. ? `\nIf this is a native custom element, make sure to exclude it from ` +
  7457. `component resolution via compilerOptions.isCustomElement.`
  7458. : ``;
  7459. warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
  7460. }
  7461. return res;
  7462. }
  7463. else {
  7464. warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
  7465. `can only be used in render() or setup().`);
  7466. }
  7467. }
  7468. function resolve(registry, name) {
  7469. return (registry &&
  7470. (registry[name] ||
  7471. registry[camelize(name)] ||
  7472. registry[capitalize(camelize(name))]));
  7473. }
  7474. const Fragment = Symbol('Fragment' );
  7475. const Text = Symbol('Text' );
  7476. const Comment = Symbol('Comment' );
  7477. const Static = Symbol('Static' );
  7478. // Since v-if and v-for are the two possible ways node structure can dynamically
  7479. // change, once we consider v-if branches and each v-for fragment a block, we
  7480. // can divide a template into nested blocks, and within each block the node
  7481. // structure would be stable. This allows us to skip most children diffing
  7482. // and only worry about the dynamic nodes (indicated by patch flags).
  7483. const blockStack = [];
  7484. let currentBlock = null;
  7485. /**
  7486. * Open a block.
  7487. * This must be called before `createBlock`. It cannot be part of `createBlock`
  7488. * because the children of the block are evaluated before `createBlock` itself
  7489. * is called. The generated code typically looks like this:
  7490. *
  7491. * ```js
  7492. * function render() {
  7493. * return (openBlock(),createBlock('div', null, [...]))
  7494. * }
  7495. * ```
  7496. * disableTracking is true when creating a v-for fragment block, since a v-for
  7497. * fragment always diffs its children.
  7498. *
  7499. * @private
  7500. */
  7501. function openBlock(disableTracking = false) {
  7502. blockStack.push((currentBlock = disableTracking ? null : []));
  7503. }
  7504. function closeBlock() {
  7505. blockStack.pop();
  7506. currentBlock = blockStack[blockStack.length - 1] || null;
  7507. }
  7508. // Whether we should be tracking dynamic child nodes inside a block.
  7509. // Only tracks when this value is > 0
  7510. // We are not using a simple boolean because this value may need to be
  7511. // incremented/decremented by nested usage of v-once (see below)
  7512. let isBlockTreeEnabled = 1;
  7513. /**
  7514. * Block tracking sometimes needs to be disabled, for example during the
  7515. * creation of a tree that needs to be cached by v-once. The compiler generates
  7516. * code like this:
  7517. *
  7518. * ``` js
  7519. * _cache[1] || (
  7520. * setBlockTracking(-1),
  7521. * _cache[1] = createVNode(...),
  7522. * setBlockTracking(1),
  7523. * _cache[1]
  7524. * )
  7525. * ```
  7526. *
  7527. * @private
  7528. */
  7529. function setBlockTracking(value) {
  7530. isBlockTreeEnabled += value;
  7531. }
  7532. function setupBlock(vnode) {
  7533. // save current block children on the block vnode
  7534. vnode.dynamicChildren =
  7535. isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
  7536. // close block
  7537. closeBlock();
  7538. // a block is always going to be patched, so track it as a child of its
  7539. // parent block
  7540. if (isBlockTreeEnabled > 0 && currentBlock) {
  7541. currentBlock.push(vnode);
  7542. }
  7543. return vnode;
  7544. }
  7545. /**
  7546. * @private
  7547. */
  7548. function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
  7549. return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
  7550. }
  7551. /**
  7552. * Create a block root vnode. Takes the same exact arguments as `createVNode`.
  7553. * A block root keeps track of dynamic nodes within the block in the
  7554. * `dynamicChildren` array.
  7555. *
  7556. * @private
  7557. */
  7558. function createBlock(type, props, children, patchFlag, dynamicProps) {
  7559. return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
  7560. }
  7561. function isVNode(value) {
  7562. return value ? value.__v_isVNode === true : false;
  7563. }
  7564. function isSameVNodeType(n1, n2) {
  7565. if (n2.shapeFlag & 6 /* COMPONENT */ &&
  7566. hmrDirtyComponents.has(n2.type)) {
  7567. // HMR only: if the component has been hot-updated, force a reload.
  7568. return false;
  7569. }
  7570. return n1.type === n2.type && n1.key === n2.key;
  7571. }
  7572. let vnodeArgsTransformer;
  7573. /**
  7574. * Internal API for registering an arguments transform for createVNode
  7575. * used for creating stubs in the test-utils
  7576. * It is *internal* but needs to be exposed for test-utils to pick up proper
  7577. * typings
  7578. */
  7579. function transformVNodeArgs(transformer) {
  7580. vnodeArgsTransformer = transformer;
  7581. }
  7582. const createVNodeWithArgsTransform = (...args) => {
  7583. return _createVNode(...(vnodeArgsTransformer
  7584. ? vnodeArgsTransformer(args, currentRenderingInstance)
  7585. : args));
  7586. };
  7587. const InternalObjectKey = `__vInternal`;
  7588. const normalizeKey = ({ key }) => key != null ? key : null;
  7589. const normalizeRef = ({ ref, ref_key, ref_for }) => {
  7590. return (ref != null
  7591. ? isString(ref) || isRef(ref) || isFunction(ref)
  7592. ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
  7593. : ref
  7594. : null);
  7595. };
  7596. function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
  7597. const vnode = {
  7598. __v_isVNode: true,
  7599. __v_skip: true,
  7600. type,
  7601. props,
  7602. key: props && normalizeKey(props),
  7603. ref: props && normalizeRef(props),
  7604. scopeId: currentScopeId,
  7605. slotScopeIds: null,
  7606. children,
  7607. component: null,
  7608. suspense: null,
  7609. ssContent: null,
  7610. ssFallback: null,
  7611. dirs: null,
  7612. transition: null,
  7613. el: null,
  7614. anchor: null,
  7615. target: null,
  7616. targetAnchor: null,
  7617. staticCount: 0,
  7618. shapeFlag,
  7619. patchFlag,
  7620. dynamicProps,
  7621. dynamicChildren: null,
  7622. appContext: null
  7623. };
  7624. if (needFullChildrenNormalization) {
  7625. normalizeChildren(vnode, children);
  7626. // normalize suspense children
  7627. if (shapeFlag & 128 /* SUSPENSE */) {
  7628. type.normalize(vnode);
  7629. }
  7630. }
  7631. else if (children) {
  7632. // compiled element vnode - if children is passed, only possible types are
  7633. // string or Array.
  7634. vnode.shapeFlag |= isString(children)
  7635. ? 8 /* TEXT_CHILDREN */
  7636. : 16 /* ARRAY_CHILDREN */;
  7637. }
  7638. // validate key
  7639. if (vnode.key !== vnode.key) {
  7640. warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
  7641. }
  7642. // track vnode for block tree
  7643. if (isBlockTreeEnabled > 0 &&
  7644. // avoid a block node from tracking itself
  7645. !isBlockNode &&
  7646. // has current parent block
  7647. currentBlock &&
  7648. // presence of a patch flag indicates this node needs patching on updates.
  7649. // component nodes also should always be patched, because even if the
  7650. // component doesn't need to update, it needs to persist the instance on to
  7651. // the next vnode so that it can be properly unmounted later.
  7652. (vnode.patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
  7653. // the EVENTS flag is only for hydration and if it is the only flag, the
  7654. // vnode should not be considered dynamic due to handler caching.
  7655. vnode.patchFlag !== 32 /* HYDRATE_EVENTS */) {
  7656. currentBlock.push(vnode);
  7657. }
  7658. return vnode;
  7659. }
  7660. const createVNode = (createVNodeWithArgsTransform );
  7661. function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
  7662. if (!type || type === NULL_DYNAMIC_COMPONENT) {
  7663. if (!type) {
  7664. warn$1(`Invalid vnode type when creating vnode: ${type}.`);
  7665. }
  7666. type = Comment;
  7667. }
  7668. if (isVNode(type)) {
  7669. // createVNode receiving an existing vnode. This happens in cases like
  7670. // <component :is="vnode"/>
  7671. // #2078 make sure to merge refs during the clone instead of overwriting it
  7672. const cloned = cloneVNode(type, props, true /* mergeRef: true */);
  7673. if (children) {
  7674. normalizeChildren(cloned, children);
  7675. }
  7676. return cloned;
  7677. }
  7678. // class component normalization.
  7679. if (isClassComponent(type)) {
  7680. type = type.__vccOpts;
  7681. }
  7682. // class & style normalization.
  7683. if (props) {
  7684. // for reactive or proxy objects, we need to clone it to enable mutation.
  7685. props = guardReactiveProps(props);
  7686. let { class: klass, style } = props;
  7687. if (klass && !isString(klass)) {
  7688. props.class = normalizeClass(klass);
  7689. }
  7690. if (isObject(style)) {
  7691. // reactive state objects need to be cloned since they are likely to be
  7692. // mutated
  7693. if (isProxy(style) && !isArray(style)) {
  7694. style = extend({}, style);
  7695. }
  7696. props.style = normalizeStyle(style);
  7697. }
  7698. }
  7699. // encode the vnode type information into a bitmap
  7700. const shapeFlag = isString(type)
  7701. ? 1 /* ELEMENT */
  7702. : isSuspense(type)
  7703. ? 128 /* SUSPENSE */
  7704. : isTeleport(type)
  7705. ? 64 /* TELEPORT */
  7706. : isObject(type)
  7707. ? 4 /* STATEFUL_COMPONENT */
  7708. : isFunction(type)
  7709. ? 2 /* FUNCTIONAL_COMPONENT */
  7710. : 0;
  7711. if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
  7712. type = toRaw(type);
  7713. warn$1(`Vue received a Component which was made a reactive object. This can ` +
  7714. `lead to unnecessary performance overhead, and should be avoided by ` +
  7715. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  7716. `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
  7717. }
  7718. return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
  7719. }
  7720. function guardReactiveProps(props) {
  7721. if (!props)
  7722. return null;
  7723. return isProxy(props) || InternalObjectKey in props
  7724. ? extend({}, props)
  7725. : props;
  7726. }
  7727. function cloneVNode(vnode, extraProps, mergeRef = false) {
  7728. // This is intentionally NOT using spread or extend to avoid the runtime
  7729. // key enumeration cost.
  7730. const { props, ref, patchFlag, children } = vnode;
  7731. const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
  7732. const cloned = {
  7733. __v_isVNode: true,
  7734. __v_skip: true,
  7735. type: vnode.type,
  7736. props: mergedProps,
  7737. key: mergedProps && normalizeKey(mergedProps),
  7738. ref: extraProps && extraProps.ref
  7739. ? // #2078 in the case of <component :is="vnode" ref="extra"/>
  7740. // if the vnode itself already has a ref, cloneVNode will need to merge
  7741. // the refs so the single vnode can be set on multiple refs
  7742. mergeRef && ref
  7743. ? isArray(ref)
  7744. ? ref.concat(normalizeRef(extraProps))
  7745. : [ref, normalizeRef(extraProps)]
  7746. : normalizeRef(extraProps)
  7747. : ref,
  7748. scopeId: vnode.scopeId,
  7749. slotScopeIds: vnode.slotScopeIds,
  7750. children: patchFlag === -1 /* HOISTED */ && isArray(children)
  7751. ? children.map(deepCloneVNode)
  7752. : children,
  7753. target: vnode.target,
  7754. targetAnchor: vnode.targetAnchor,
  7755. staticCount: vnode.staticCount,
  7756. shapeFlag: vnode.shapeFlag,
  7757. // if the vnode is cloned with extra props, we can no longer assume its
  7758. // existing patch flag to be reliable and need to add the FULL_PROPS flag.
  7759. // note: preserve flag for fragments since they use the flag for children
  7760. // fast paths only.
  7761. patchFlag: extraProps && vnode.type !== Fragment
  7762. ? patchFlag === -1 // hoisted node
  7763. ? 16 /* FULL_PROPS */
  7764. : patchFlag | 16 /* FULL_PROPS */
  7765. : patchFlag,
  7766. dynamicProps: vnode.dynamicProps,
  7767. dynamicChildren: vnode.dynamicChildren,
  7768. appContext: vnode.appContext,
  7769. dirs: vnode.dirs,
  7770. transition: vnode.transition,
  7771. // These should technically only be non-null on mounted VNodes. However,
  7772. // they *should* be copied for kept-alive vnodes. So we just always copy
  7773. // them since them being non-null during a mount doesn't affect the logic as
  7774. // they will simply be overwritten.
  7775. component: vnode.component,
  7776. suspense: vnode.suspense,
  7777. ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
  7778. ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
  7779. el: vnode.el,
  7780. anchor: vnode.anchor
  7781. };
  7782. return cloned;
  7783. }
  7784. /**
  7785. * Dev only, for HMR of hoisted vnodes reused in v-for
  7786. * https://github.com/vitejs/vite/issues/2022
  7787. */
  7788. function deepCloneVNode(vnode) {
  7789. const cloned = cloneVNode(vnode);
  7790. if (isArray(vnode.children)) {
  7791. cloned.children = vnode.children.map(deepCloneVNode);
  7792. }
  7793. return cloned;
  7794. }
  7795. /**
  7796. * @private
  7797. */
  7798. function createTextVNode(text = ' ', flag = 0) {
  7799. return createVNode(Text, null, text, flag);
  7800. }
  7801. /**
  7802. * @private
  7803. */
  7804. function createStaticVNode(content, numberOfNodes) {
  7805. // A static vnode can contain multiple stringified elements, and the number
  7806. // of elements is necessary for hydration.
  7807. const vnode = createVNode(Static, null, content);
  7808. vnode.staticCount = numberOfNodes;
  7809. return vnode;
  7810. }
  7811. /**
  7812. * @private
  7813. */
  7814. function createCommentVNode(text = '',
  7815. // when used as the v-else branch, the comment node must be created as a
  7816. // block to ensure correct updates.
  7817. asBlock = false) {
  7818. return asBlock
  7819. ? (openBlock(), createBlock(Comment, null, text))
  7820. : createVNode(Comment, null, text);
  7821. }
  7822. function normalizeVNode(child) {
  7823. if (child == null || typeof child === 'boolean') {
  7824. // empty placeholder
  7825. return createVNode(Comment);
  7826. }
  7827. else if (isArray(child)) {
  7828. // fragment
  7829. return createVNode(Fragment, null,
  7830. // #3666, avoid reference pollution when reusing vnode
  7831. child.slice());
  7832. }
  7833. else if (typeof child === 'object') {
  7834. // already vnode, this should be the most common since compiled templates
  7835. // always produce all-vnode children arrays
  7836. return cloneIfMounted(child);
  7837. }
  7838. else {
  7839. // strings and numbers
  7840. return createVNode(Text, null, String(child));
  7841. }
  7842. }
  7843. // optimized normalization for template-compiled render fns
  7844. function cloneIfMounted(child) {
  7845. return child.el === null || child.memo ? child : cloneVNode(child);
  7846. }
  7847. function normalizeChildren(vnode, children) {
  7848. let type = 0;
  7849. const { shapeFlag } = vnode;
  7850. if (children == null) {
  7851. children = null;
  7852. }
  7853. else if (isArray(children)) {
  7854. type = 16 /* ARRAY_CHILDREN */;
  7855. }
  7856. else if (typeof children === 'object') {
  7857. if (shapeFlag & (1 /* ELEMENT */ | 64 /* TELEPORT */)) {
  7858. // Normalize slot to plain children for plain element and Teleport
  7859. const slot = children.default;
  7860. if (slot) {
  7861. // _c marker is added by withCtx() indicating this is a compiled slot
  7862. slot._c && (slot._d = false);
  7863. normalizeChildren(vnode, slot());
  7864. slot._c && (slot._d = true);
  7865. }
  7866. return;
  7867. }
  7868. else {
  7869. type = 32 /* SLOTS_CHILDREN */;
  7870. const slotFlag = children._;
  7871. if (!slotFlag && !(InternalObjectKey in children)) {
  7872. children._ctx = currentRenderingInstance;
  7873. }
  7874. else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
  7875. // a child component receives forwarded slots from the parent.
  7876. // its slot type is determined by its parent's slot type.
  7877. if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
  7878. children._ = 1 /* STABLE */;
  7879. }
  7880. else {
  7881. children._ = 2 /* DYNAMIC */;
  7882. vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  7883. }
  7884. }
  7885. }
  7886. }
  7887. else if (isFunction(children)) {
  7888. children = { default: children, _ctx: currentRenderingInstance };
  7889. type = 32 /* SLOTS_CHILDREN */;
  7890. }
  7891. else {
  7892. children = String(children);
  7893. // force teleport children to array so it can be moved around
  7894. if (shapeFlag & 64 /* TELEPORT */) {
  7895. type = 16 /* ARRAY_CHILDREN */;
  7896. children = [createTextVNode(children)];
  7897. }
  7898. else {
  7899. type = 8 /* TEXT_CHILDREN */;
  7900. }
  7901. }
  7902. vnode.children = children;
  7903. vnode.shapeFlag |= type;
  7904. }
  7905. function mergeProps(...args) {
  7906. const ret = {};
  7907. for (let i = 0; i < args.length; i++) {
  7908. const toMerge = args[i];
  7909. for (const key in toMerge) {
  7910. if (key === 'class') {
  7911. if (ret.class !== toMerge.class) {
  7912. ret.class = normalizeClass([ret.class, toMerge.class]);
  7913. }
  7914. }
  7915. else if (key === 'style') {
  7916. ret.style = normalizeStyle([ret.style, toMerge.style]);
  7917. }
  7918. else if (isOn(key)) {
  7919. const existing = ret[key];
  7920. const incoming = toMerge[key];
  7921. if (incoming &&
  7922. existing !== incoming &&
  7923. !(isArray(existing) && existing.includes(incoming))) {
  7924. ret[key] = existing
  7925. ? [].concat(existing, incoming)
  7926. : incoming;
  7927. }
  7928. }
  7929. else if (key !== '') {
  7930. ret[key] = toMerge[key];
  7931. }
  7932. }
  7933. }
  7934. return ret;
  7935. }
  7936. function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
  7937. callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
  7938. vnode,
  7939. prevVNode
  7940. ]);
  7941. }
  7942. /**
  7943. * Actual implementation
  7944. */
  7945. function renderList(source, renderItem, cache, index) {
  7946. let ret;
  7947. const cached = (cache && cache[index]);
  7948. if (isArray(source) || isString(source)) {
  7949. ret = new Array(source.length);
  7950. for (let i = 0, l = source.length; i < l; i++) {
  7951. ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
  7952. }
  7953. }
  7954. else if (typeof source === 'number') {
  7955. if (!Number.isInteger(source)) {
  7956. warn$1(`The v-for range expect an integer value but got ${source}.`);
  7957. return [];
  7958. }
  7959. ret = new Array(source);
  7960. for (let i = 0; i < source; i++) {
  7961. ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
  7962. }
  7963. }
  7964. else if (isObject(source)) {
  7965. if (source[Symbol.iterator]) {
  7966. ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
  7967. }
  7968. else {
  7969. const keys = Object.keys(source);
  7970. ret = new Array(keys.length);
  7971. for (let i = 0, l = keys.length; i < l; i++) {
  7972. const key = keys[i];
  7973. ret[i] = renderItem(source[key], key, i, cached && cached[i]);
  7974. }
  7975. }
  7976. }
  7977. else {
  7978. ret = [];
  7979. }
  7980. if (cache) {
  7981. cache[index] = ret;
  7982. }
  7983. return ret;
  7984. }
  7985. /**
  7986. * Compiler runtime helper for creating dynamic slots object
  7987. * @private
  7988. */
  7989. function createSlots(slots, dynamicSlots) {
  7990. for (let i = 0; i < dynamicSlots.length; i++) {
  7991. const slot = dynamicSlots[i];
  7992. // array of dynamic slot generated by <template v-for="..." #[...]>
  7993. if (isArray(slot)) {
  7994. for (let j = 0; j < slot.length; j++) {
  7995. slots[slot[j].name] = slot[j].fn;
  7996. }
  7997. }
  7998. else if (slot) {
  7999. // conditional single slot generated by <template v-if="..." #foo>
  8000. slots[slot.name] = slot.fn;
  8001. }
  8002. }
  8003. return slots;
  8004. }
  8005. /**
  8006. * Compiler runtime helper for rendering `<slot/>`
  8007. * @private
  8008. */
  8009. function renderSlot(slots, name, props = {},
  8010. // this is not a user-facing function, so the fallback is always generated by
  8011. // the compiler and guaranteed to be a function returning an array
  8012. fallback, noSlotted) {
  8013. if (currentRenderingInstance.isCE ||
  8014. (currentRenderingInstance.parent &&
  8015. isAsyncWrapper(currentRenderingInstance.parent) &&
  8016. currentRenderingInstance.parent.isCE)) {
  8017. return createVNode('slot', name === 'default' ? null : { name }, fallback && fallback());
  8018. }
  8019. let slot = slots[name];
  8020. if (slot && slot.length > 1) {
  8021. warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
  8022. `function. You need to mark this component with $dynamic-slots in the ` +
  8023. `parent template.`);
  8024. slot = () => [];
  8025. }
  8026. // a compiled slot disables block tracking by default to avoid manual
  8027. // invocation interfering with template-based block tracking, but in
  8028. // `renderSlot` we can be sure that it's template-based so we can force
  8029. // enable it.
  8030. if (slot && slot._c) {
  8031. slot._d = false;
  8032. }
  8033. openBlock();
  8034. const validSlotContent = slot && ensureValidVNode(slot(props));
  8035. const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
  8036. ? 64 /* STABLE_FRAGMENT */
  8037. : -2 /* BAIL */);
  8038. if (!noSlotted && rendered.scopeId) {
  8039. rendered.slotScopeIds = [rendered.scopeId + '-s'];
  8040. }
  8041. if (slot && slot._c) {
  8042. slot._d = true;
  8043. }
  8044. return rendered;
  8045. }
  8046. function ensureValidVNode(vnodes) {
  8047. return vnodes.some(child => {
  8048. if (!isVNode(child))
  8049. return true;
  8050. if (child.type === Comment)
  8051. return false;
  8052. if (child.type === Fragment &&
  8053. !ensureValidVNode(child.children))
  8054. return false;
  8055. return true;
  8056. })
  8057. ? vnodes
  8058. : null;
  8059. }
  8060. /**
  8061. * For prefixing keys in v-on="obj" with "on"
  8062. * @private
  8063. */
  8064. function toHandlers(obj) {
  8065. const ret = {};
  8066. if (!isObject(obj)) {
  8067. warn$1(`v-on with no argument expects an object value.`);
  8068. return ret;
  8069. }
  8070. for (const key in obj) {
  8071. ret[toHandlerKey(key)] = obj[key];
  8072. }
  8073. return ret;
  8074. }
  8075. /**
  8076. * #2437 In Vue 3, functional components do not have a public instance proxy but
  8077. * they exist in the internal parent chain. For code that relies on traversing
  8078. * public $parent chains, skip functional ones and go to the parent instead.
  8079. */
  8080. const getPublicInstance = (i) => {
  8081. if (!i)
  8082. return null;
  8083. if (isStatefulComponent(i))
  8084. return getExposeProxy(i) || i.proxy;
  8085. return getPublicInstance(i.parent);
  8086. };
  8087. const publicPropertiesMap =
  8088. // Move PURE marker to new line to workaround compiler discarding it
  8089. // due to type annotation
  8090. /*#__PURE__*/ extend(Object.create(null), {
  8091. $: i => i,
  8092. $el: i => i.vnode.el,
  8093. $data: i => i.data,
  8094. $props: i => (shallowReadonly(i.props) ),
  8095. $attrs: i => (shallowReadonly(i.attrs) ),
  8096. $slots: i => (shallowReadonly(i.slots) ),
  8097. $refs: i => (shallowReadonly(i.refs) ),
  8098. $parent: i => getPublicInstance(i.parent),
  8099. $root: i => getPublicInstance(i.root),
  8100. $emit: i => i.emit,
  8101. $options: i => (resolveMergedOptions(i) ),
  8102. $forceUpdate: i => () => queueJob(i.update),
  8103. $nextTick: i => nextTick.bind(i.proxy),
  8104. $watch: i => (instanceWatch.bind(i) )
  8105. });
  8106. const PublicInstanceProxyHandlers = {
  8107. get({ _: instance }, key) {
  8108. const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
  8109. // for internal formatters to know that this is a Vue instance
  8110. if (key === '__isVue') {
  8111. return true;
  8112. }
  8113. // prioritize <script setup> bindings during dev.
  8114. // this allows even properties that start with _ or $ to be used - so that
  8115. // it aligns with the production behavior where the render fn is inlined and
  8116. // indeed has access to all declared variables.
  8117. if (setupState !== EMPTY_OBJ &&
  8118. setupState.__isScriptSetup &&
  8119. hasOwn(setupState, key)) {
  8120. return setupState[key];
  8121. }
  8122. // data / props / ctx
  8123. // This getter gets called for every property access on the render context
  8124. // during render and is a major hotspot. The most expensive part of this
  8125. // is the multiple hasOwn() calls. It's much faster to do a simple property
  8126. // access on a plain object, so we use an accessCache object (with null
  8127. // prototype) to memoize what access type a key corresponds to.
  8128. let normalizedProps;
  8129. if (key[0] !== '$') {
  8130. const n = accessCache[key];
  8131. if (n !== undefined) {
  8132. switch (n) {
  8133. case 1 /* SETUP */:
  8134. return setupState[key];
  8135. case 2 /* DATA */:
  8136. return data[key];
  8137. case 4 /* CONTEXT */:
  8138. return ctx[key];
  8139. case 3 /* PROPS */:
  8140. return props[key];
  8141. // default: just fallthrough
  8142. }
  8143. }
  8144. else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  8145. accessCache[key] = 1 /* SETUP */;
  8146. return setupState[key];
  8147. }
  8148. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  8149. accessCache[key] = 2 /* DATA */;
  8150. return data[key];
  8151. }
  8152. else if (
  8153. // only cache other properties when instance has declared (thus stable)
  8154. // props
  8155. (normalizedProps = instance.propsOptions[0]) &&
  8156. hasOwn(normalizedProps, key)) {
  8157. accessCache[key] = 3 /* PROPS */;
  8158. return props[key];
  8159. }
  8160. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  8161. accessCache[key] = 4 /* CONTEXT */;
  8162. return ctx[key];
  8163. }
  8164. else if (shouldCacheAccess) {
  8165. accessCache[key] = 0 /* OTHER */;
  8166. }
  8167. }
  8168. const publicGetter = publicPropertiesMap[key];
  8169. let cssModule, globalProperties;
  8170. // public $xxx properties
  8171. if (publicGetter) {
  8172. if (key === '$attrs') {
  8173. track(instance, "get" /* GET */, key);
  8174. markAttrsAccessed();
  8175. }
  8176. return publicGetter(instance);
  8177. }
  8178. else if (
  8179. // css module (injected by vue-loader)
  8180. (cssModule = type.__cssModules) &&
  8181. (cssModule = cssModule[key])) {
  8182. return cssModule;
  8183. }
  8184. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  8185. // user may set custom properties to `this` that start with `$`
  8186. accessCache[key] = 4 /* CONTEXT */;
  8187. return ctx[key];
  8188. }
  8189. else if (
  8190. // global properties
  8191. ((globalProperties = appContext.config.globalProperties),
  8192. hasOwn(globalProperties, key))) {
  8193. {
  8194. return globalProperties[key];
  8195. }
  8196. }
  8197. else if (currentRenderingInstance &&
  8198. (!isString(key) ||
  8199. // #1091 avoid internal isRef/isVNode checks on component instance leading
  8200. // to infinite warning loop
  8201. key.indexOf('__v') !== 0)) {
  8202. if (data !== EMPTY_OBJ &&
  8203. (key[0] === '$' || key[0] === '_') &&
  8204. hasOwn(data, key)) {
  8205. warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
  8206. `character ("$" or "_") and is not proxied on the render context.`);
  8207. }
  8208. else if (instance === currentRenderingInstance) {
  8209. warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
  8210. `but is not defined on instance.`);
  8211. }
  8212. }
  8213. },
  8214. set({ _: instance }, key, value) {
  8215. const { data, setupState, ctx } = instance;
  8216. if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  8217. setupState[key] = value;
  8218. return true;
  8219. }
  8220. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  8221. data[key] = value;
  8222. return true;
  8223. }
  8224. else if (hasOwn(instance.props, key)) {
  8225. warn$1(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
  8226. return false;
  8227. }
  8228. if (key[0] === '$' && key.slice(1) in instance) {
  8229. warn$1(`Attempting to mutate public property "${key}". ` +
  8230. `Properties starting with $ are reserved and readonly.`, instance);
  8231. return false;
  8232. }
  8233. else {
  8234. if (key in instance.appContext.config.globalProperties) {
  8235. Object.defineProperty(ctx, key, {
  8236. enumerable: true,
  8237. configurable: true,
  8238. value
  8239. });
  8240. }
  8241. else {
  8242. ctx[key] = value;
  8243. }
  8244. }
  8245. return true;
  8246. },
  8247. has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
  8248. let normalizedProps;
  8249. return (!!accessCache[key] ||
  8250. (data !== EMPTY_OBJ && hasOwn(data, key)) ||
  8251. (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
  8252. ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
  8253. hasOwn(ctx, key) ||
  8254. hasOwn(publicPropertiesMap, key) ||
  8255. hasOwn(appContext.config.globalProperties, key));
  8256. },
  8257. defineProperty(target, key, descriptor) {
  8258. if (descriptor.get != null) {
  8259. // invalidate key cache of a getter based property #5417
  8260. target._.accessCache[key] = 0;
  8261. }
  8262. else if (hasOwn(descriptor, 'value')) {
  8263. this.set(target, key, descriptor.value, null);
  8264. }
  8265. return Reflect.defineProperty(target, key, descriptor);
  8266. }
  8267. };
  8268. {
  8269. PublicInstanceProxyHandlers.ownKeys = (target) => {
  8270. warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
  8271. `The keys will be empty in production mode to avoid performance overhead.`);
  8272. return Reflect.ownKeys(target);
  8273. };
  8274. }
  8275. const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
  8276. get(target, key) {
  8277. // fast path for unscopables when using `with` block
  8278. if (key === Symbol.unscopables) {
  8279. return;
  8280. }
  8281. return PublicInstanceProxyHandlers.get(target, key, target);
  8282. },
  8283. has(_, key) {
  8284. const has = key[0] !== '_' && !isGloballyWhitelisted(key);
  8285. if (!has && PublicInstanceProxyHandlers.has(_, key)) {
  8286. warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
  8287. }
  8288. return has;
  8289. }
  8290. });
  8291. // dev only
  8292. // In dev mode, the proxy target exposes the same properties as seen on `this`
  8293. // for easier console inspection. In prod mode it will be an empty object so
  8294. // these properties definitions can be skipped.
  8295. function createDevRenderContext(instance) {
  8296. const target = {};
  8297. // expose internal instance for proxy handlers
  8298. Object.defineProperty(target, `_`, {
  8299. configurable: true,
  8300. enumerable: false,
  8301. get: () => instance
  8302. });
  8303. // expose public properties
  8304. Object.keys(publicPropertiesMap).forEach(key => {
  8305. Object.defineProperty(target, key, {
  8306. configurable: true,
  8307. enumerable: false,
  8308. get: () => publicPropertiesMap[key](instance),
  8309. // intercepted by the proxy so no need for implementation,
  8310. // but needed to prevent set errors
  8311. set: NOOP
  8312. });
  8313. });
  8314. return target;
  8315. }
  8316. // dev only
  8317. function exposePropsOnRenderContext(instance) {
  8318. const { ctx, propsOptions: [propsOptions] } = instance;
  8319. if (propsOptions) {
  8320. Object.keys(propsOptions).forEach(key => {
  8321. Object.defineProperty(ctx, key, {
  8322. enumerable: true,
  8323. configurable: true,
  8324. get: () => instance.props[key],
  8325. set: NOOP
  8326. });
  8327. });
  8328. }
  8329. }
  8330. // dev only
  8331. function exposeSetupStateOnRenderContext(instance) {
  8332. const { ctx, setupState } = instance;
  8333. Object.keys(toRaw(setupState)).forEach(key => {
  8334. if (!setupState.__isScriptSetup) {
  8335. if (key[0] === '$' || key[0] === '_') {
  8336. warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
  8337. `which are reserved prefixes for Vue internals.`);
  8338. return;
  8339. }
  8340. Object.defineProperty(ctx, key, {
  8341. enumerable: true,
  8342. configurable: true,
  8343. get: () => setupState[key],
  8344. set: NOOP
  8345. });
  8346. }
  8347. });
  8348. }
  8349. const emptyAppContext = createAppContext();
  8350. let uid$1 = 0;
  8351. function createComponentInstance(vnode, parent, suspense) {
  8352. const type = vnode.type;
  8353. // inherit parent app context - or - if root, adopt from root vnode
  8354. const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
  8355. const instance = {
  8356. uid: uid$1++,
  8357. vnode,
  8358. type,
  8359. parent,
  8360. appContext,
  8361. root: null,
  8362. next: null,
  8363. subTree: null,
  8364. effect: null,
  8365. update: null,
  8366. scope: new EffectScope(true /* detached */),
  8367. render: null,
  8368. proxy: null,
  8369. exposed: null,
  8370. exposeProxy: null,
  8371. withProxy: null,
  8372. provides: parent ? parent.provides : Object.create(appContext.provides),
  8373. accessCache: null,
  8374. renderCache: [],
  8375. // local resovled assets
  8376. components: null,
  8377. directives: null,
  8378. // resolved props and emits options
  8379. propsOptions: normalizePropsOptions(type, appContext),
  8380. emitsOptions: normalizeEmitsOptions(type, appContext),
  8381. // emit
  8382. emit: null,
  8383. emitted: null,
  8384. // props default value
  8385. propsDefaults: EMPTY_OBJ,
  8386. // inheritAttrs
  8387. inheritAttrs: type.inheritAttrs,
  8388. // state
  8389. ctx: EMPTY_OBJ,
  8390. data: EMPTY_OBJ,
  8391. props: EMPTY_OBJ,
  8392. attrs: EMPTY_OBJ,
  8393. slots: EMPTY_OBJ,
  8394. refs: EMPTY_OBJ,
  8395. setupState: EMPTY_OBJ,
  8396. setupContext: null,
  8397. // suspense related
  8398. suspense,
  8399. suspenseId: suspense ? suspense.pendingId : 0,
  8400. asyncDep: null,
  8401. asyncResolved: false,
  8402. // lifecycle hooks
  8403. // not using enums here because it results in computed properties
  8404. isMounted: false,
  8405. isUnmounted: false,
  8406. isDeactivated: false,
  8407. bc: null,
  8408. c: null,
  8409. bm: null,
  8410. m: null,
  8411. bu: null,
  8412. u: null,
  8413. um: null,
  8414. bum: null,
  8415. da: null,
  8416. a: null,
  8417. rtg: null,
  8418. rtc: null,
  8419. ec: null,
  8420. sp: null
  8421. };
  8422. {
  8423. instance.ctx = createDevRenderContext(instance);
  8424. }
  8425. instance.root = parent ? parent.root : instance;
  8426. instance.emit = emit$1.bind(null, instance);
  8427. // apply custom element special handling
  8428. if (vnode.ce) {
  8429. vnode.ce(instance);
  8430. }
  8431. return instance;
  8432. }
  8433. let currentInstance = null;
  8434. const getCurrentInstance = () => currentInstance || currentRenderingInstance;
  8435. const setCurrentInstance = (instance) => {
  8436. currentInstance = instance;
  8437. instance.scope.on();
  8438. };
  8439. const unsetCurrentInstance = () => {
  8440. currentInstance && currentInstance.scope.off();
  8441. currentInstance = null;
  8442. };
  8443. const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
  8444. function validateComponentName(name, config) {
  8445. const appIsNativeTag = config.isNativeTag || NO;
  8446. if (isBuiltInTag(name) || appIsNativeTag(name)) {
  8447. warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
  8448. }
  8449. }
  8450. function isStatefulComponent(instance) {
  8451. return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
  8452. }
  8453. let isInSSRComponentSetup = false;
  8454. function setupComponent(instance, isSSR = false) {
  8455. isInSSRComponentSetup = isSSR;
  8456. const { props, children } = instance.vnode;
  8457. const isStateful = isStatefulComponent(instance);
  8458. initProps(instance, props, isStateful, isSSR);
  8459. initSlots(instance, children);
  8460. const setupResult = isStateful
  8461. ? setupStatefulComponent(instance, isSSR)
  8462. : undefined;
  8463. isInSSRComponentSetup = false;
  8464. return setupResult;
  8465. }
  8466. function setupStatefulComponent(instance, isSSR) {
  8467. var _a;
  8468. const Component = instance.type;
  8469. {
  8470. if (Component.name) {
  8471. validateComponentName(Component.name, instance.appContext.config);
  8472. }
  8473. if (Component.components) {
  8474. const names = Object.keys(Component.components);
  8475. for (let i = 0; i < names.length; i++) {
  8476. validateComponentName(names[i], instance.appContext.config);
  8477. }
  8478. }
  8479. if (Component.directives) {
  8480. const names = Object.keys(Component.directives);
  8481. for (let i = 0; i < names.length; i++) {
  8482. validateDirectiveName(names[i]);
  8483. }
  8484. }
  8485. if (Component.compilerOptions && isRuntimeOnly()) {
  8486. warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
  8487. `includes the runtime compiler. Since you are using a runtime-only ` +
  8488. `build, the options should be passed via your build tool config instead.`);
  8489. }
  8490. }
  8491. // 0. create render proxy property access cache
  8492. instance.accessCache = Object.create(null);
  8493. // 1. create public instance / render proxy
  8494. // also mark it raw so it's never observed
  8495. instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
  8496. {
  8497. exposePropsOnRenderContext(instance);
  8498. }
  8499. // 2. call setup()
  8500. const { setup } = Component;
  8501. if (setup) {
  8502. const setupContext = (instance.setupContext =
  8503. setup.length > 1 ? createSetupContext(instance) : null);
  8504. setCurrentInstance(instance);
  8505. pauseTracking();
  8506. const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
  8507. resetTracking();
  8508. unsetCurrentInstance();
  8509. if (isPromise(setupResult)) {
  8510. setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
  8511. if (isSSR) {
  8512. // return the promise so server-renderer can wait on it
  8513. return setupResult
  8514. .then((resolvedResult) => {
  8515. handleSetupResult(instance, resolvedResult, isSSR);
  8516. })
  8517. .catch(e => {
  8518. handleError(e, instance, 0 /* SETUP_FUNCTION */);
  8519. });
  8520. }
  8521. else {
  8522. // async setup returned Promise.
  8523. // bail here and wait for re-entry.
  8524. instance.asyncDep = setupResult;
  8525. if (!instance.suspense) {
  8526. const name = (_a = Component.name) !== null && _a !== void 0 ? _a : 'Anonymous';
  8527. warn$1(`Component <${name}>: setup function returned a promise, but no ` +
  8528. `<Suspense> boundary was found in the parent component tree. ` +
  8529. `A component with async setup() must be nested in a <Suspense> ` +
  8530. `in order to be rendered.`);
  8531. }
  8532. }
  8533. }
  8534. else {
  8535. handleSetupResult(instance, setupResult, isSSR);
  8536. }
  8537. }
  8538. else {
  8539. finishComponentSetup(instance, isSSR);
  8540. }
  8541. }
  8542. function handleSetupResult(instance, setupResult, isSSR) {
  8543. if (isFunction(setupResult)) {
  8544. // setup returned an inline render function
  8545. {
  8546. instance.render = setupResult;
  8547. }
  8548. }
  8549. else if (isObject(setupResult)) {
  8550. if (isVNode(setupResult)) {
  8551. warn$1(`setup() should not return VNodes directly - ` +
  8552. `return a render function instead.`);
  8553. }
  8554. // setup returned bindings.
  8555. // assuming a render function compiled from template is present.
  8556. {
  8557. instance.devtoolsRawSetupState = setupResult;
  8558. }
  8559. instance.setupState = proxyRefs(setupResult);
  8560. {
  8561. exposeSetupStateOnRenderContext(instance);
  8562. }
  8563. }
  8564. else if (setupResult !== undefined) {
  8565. warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
  8566. }
  8567. finishComponentSetup(instance, isSSR);
  8568. }
  8569. let compile;
  8570. let installWithProxy;
  8571. /**
  8572. * For runtime-dom to register the compiler.
  8573. * Note the exported method uses any to avoid d.ts relying on the compiler types.
  8574. */
  8575. function registerRuntimeCompiler(_compile) {
  8576. compile = _compile;
  8577. installWithProxy = i => {
  8578. if (i.render._rc) {
  8579. i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
  8580. }
  8581. };
  8582. }
  8583. // dev only
  8584. const isRuntimeOnly = () => !compile;
  8585. function finishComponentSetup(instance, isSSR, skipOptions) {
  8586. const Component = instance.type;
  8587. // template / render function normalization
  8588. // could be already set when returned from setup()
  8589. if (!instance.render) {
  8590. // only do on-the-fly compile if not in SSR - SSR on-the-fly compilation
  8591. // is done by server-renderer
  8592. if (!isSSR && compile && !Component.render) {
  8593. const template = Component.template;
  8594. if (template) {
  8595. {
  8596. startMeasure(instance, `compile`);
  8597. }
  8598. const { isCustomElement, compilerOptions } = instance.appContext.config;
  8599. const { delimiters, compilerOptions: componentCompilerOptions } = Component;
  8600. const finalCompilerOptions = extend(extend({
  8601. isCustomElement,
  8602. delimiters
  8603. }, compilerOptions), componentCompilerOptions);
  8604. Component.render = compile(template, finalCompilerOptions);
  8605. {
  8606. endMeasure(instance, `compile`);
  8607. }
  8608. }
  8609. }
  8610. instance.render = (Component.render || NOOP);
  8611. // for runtime-compiled render functions using `with` blocks, the render
  8612. // proxy used needs a different `has` handler which is more performant and
  8613. // also only allows a whitelist of globals to fallthrough.
  8614. if (installWithProxy) {
  8615. installWithProxy(instance);
  8616. }
  8617. }
  8618. // support for 2.x options
  8619. {
  8620. setCurrentInstance(instance);
  8621. pauseTracking();
  8622. applyOptions(instance);
  8623. resetTracking();
  8624. unsetCurrentInstance();
  8625. }
  8626. // warn missing template/render
  8627. // the runtime compilation of template in SSR is done by server-render
  8628. if (!Component.render && instance.render === NOOP && !isSSR) {
  8629. /* istanbul ignore if */
  8630. if (!compile && Component.template) {
  8631. warn$1(`Component provided template option but ` +
  8632. `runtime compilation is not supported in this build of Vue.` +
  8633. (` Use "vue.esm-browser.js" instead.`
  8634. ) /* should not happen */);
  8635. }
  8636. else {
  8637. warn$1(`Component is missing template or render function.`);
  8638. }
  8639. }
  8640. }
  8641. function createAttrsProxy(instance) {
  8642. return new Proxy(instance.attrs, {
  8643. get(target, key) {
  8644. markAttrsAccessed();
  8645. track(instance, "get" /* GET */, '$attrs');
  8646. return target[key];
  8647. },
  8648. set() {
  8649. warn$1(`setupContext.attrs is readonly.`);
  8650. return false;
  8651. },
  8652. deleteProperty() {
  8653. warn$1(`setupContext.attrs is readonly.`);
  8654. return false;
  8655. }
  8656. }
  8657. );
  8658. }
  8659. function createSetupContext(instance) {
  8660. const expose = exposed => {
  8661. if (instance.exposed) {
  8662. warn$1(`expose() should be called only once per setup().`);
  8663. }
  8664. instance.exposed = exposed || {};
  8665. };
  8666. let attrs;
  8667. {
  8668. // We use getters in dev in case libs like test-utils overwrite instance
  8669. // properties (overwrites should not be done in prod)
  8670. return Object.freeze({
  8671. get attrs() {
  8672. return attrs || (attrs = createAttrsProxy(instance));
  8673. },
  8674. get slots() {
  8675. return shallowReadonly(instance.slots);
  8676. },
  8677. get emit() {
  8678. return (event, ...args) => instance.emit(event, ...args);
  8679. },
  8680. expose
  8681. });
  8682. }
  8683. }
  8684. function getExposeProxy(instance) {
  8685. if (instance.exposed) {
  8686. return (instance.exposeProxy ||
  8687. (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
  8688. get(target, key) {
  8689. if (key in target) {
  8690. return target[key];
  8691. }
  8692. else if (key in publicPropertiesMap) {
  8693. return publicPropertiesMap[key](instance);
  8694. }
  8695. }
  8696. })));
  8697. }
  8698. }
  8699. const classifyRE = /(?:^|[-_])(\w)/g;
  8700. const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
  8701. function getComponentName(Component) {
  8702. return isFunction(Component)
  8703. ? Component.displayName || Component.name
  8704. : Component.name;
  8705. }
  8706. /* istanbul ignore next */
  8707. function formatComponentName(instance, Component, isRoot = false) {
  8708. let name = getComponentName(Component);
  8709. if (!name && Component.__file) {
  8710. const match = Component.__file.match(/([^/\\]+)\.\w+$/);
  8711. if (match) {
  8712. name = match[1];
  8713. }
  8714. }
  8715. if (!name && instance && instance.parent) {
  8716. // try to infer the name based on reverse resolution
  8717. const inferFromRegistry = (registry) => {
  8718. for (const key in registry) {
  8719. if (registry[key] === Component) {
  8720. return key;
  8721. }
  8722. }
  8723. };
  8724. name =
  8725. inferFromRegistry(instance.components ||
  8726. instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
  8727. }
  8728. return name ? classify(name) : isRoot ? `App` : `Anonymous`;
  8729. }
  8730. function isClassComponent(value) {
  8731. return isFunction(value) && '__vccOpts' in value;
  8732. }
  8733. const computed$1 = ((getterOrOptions, debugOptions) => {
  8734. // @ts-ignore
  8735. return computed(getterOrOptions, debugOptions, isInSSRComponentSetup);
  8736. });
  8737. // dev only
  8738. const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
  8739. `<script setup> of a single file component. Its arguments should be ` +
  8740. `compiled away and passing it at runtime has no effect.`);
  8741. // implementation
  8742. function defineProps() {
  8743. {
  8744. warnRuntimeUsage(`defineProps`);
  8745. }
  8746. return null;
  8747. }
  8748. // implementation
  8749. function defineEmits() {
  8750. {
  8751. warnRuntimeUsage(`defineEmits`);
  8752. }
  8753. return null;
  8754. }
  8755. /**
  8756. * Vue `<script setup>` compiler macro for declaring a component's exposed
  8757. * instance properties when it is accessed by a parent component via template
  8758. * refs.
  8759. *
  8760. * `<script setup>` components are closed by default - i.e. variables inside
  8761. * the `<script setup>` scope is not exposed to parent unless explicitly exposed
  8762. * via `defineExpose`.
  8763. *
  8764. * This is only usable inside `<script setup>`, is compiled away in the
  8765. * output and should **not** be actually called at runtime.
  8766. */
  8767. function defineExpose(exposed) {
  8768. {
  8769. warnRuntimeUsage(`defineExpose`);
  8770. }
  8771. }
  8772. /**
  8773. * Vue `<script setup>` compiler macro for providing props default values when
  8774. * using type-based `defineProps` declaration.
  8775. *
  8776. * Example usage:
  8777. * ```ts
  8778. * withDefaults(defineProps<{
  8779. * size?: number
  8780. * labels?: string[]
  8781. * }>(), {
  8782. * size: 3,
  8783. * labels: () => ['default label']
  8784. * })
  8785. * ```
  8786. *
  8787. * This is only usable inside `<script setup>`, is compiled away in the output
  8788. * and should **not** be actually called at runtime.
  8789. */
  8790. function withDefaults(props, defaults) {
  8791. {
  8792. warnRuntimeUsage(`withDefaults`);
  8793. }
  8794. return null;
  8795. }
  8796. function useSlots() {
  8797. return getContext().slots;
  8798. }
  8799. function useAttrs() {
  8800. return getContext().attrs;
  8801. }
  8802. function getContext() {
  8803. const i = getCurrentInstance();
  8804. if (!i) {
  8805. warn$1(`useContext() called without active instance.`);
  8806. }
  8807. return i.setupContext || (i.setupContext = createSetupContext(i));
  8808. }
  8809. /**
  8810. * Runtime helper for merging default declarations. Imported by compiled code
  8811. * only.
  8812. * @internal
  8813. */
  8814. function mergeDefaults(raw, defaults) {
  8815. const props = isArray(raw)
  8816. ? raw.reduce((normalized, p) => ((normalized[p] = {}), normalized), {})
  8817. : raw;
  8818. for (const key in defaults) {
  8819. const opt = props[key];
  8820. if (opt) {
  8821. if (isArray(opt) || isFunction(opt)) {
  8822. props[key] = { type: opt, default: defaults[key] };
  8823. }
  8824. else {
  8825. opt.default = defaults[key];
  8826. }
  8827. }
  8828. else if (opt === null) {
  8829. props[key] = { default: defaults[key] };
  8830. }
  8831. else {
  8832. warn$1(`props default key "${key}" has no corresponding declaration.`);
  8833. }
  8834. }
  8835. return props;
  8836. }
  8837. /**
  8838. * Used to create a proxy for the rest element when destructuring props with
  8839. * defineProps().
  8840. * @internal
  8841. */
  8842. function createPropsRestProxy(props, excludedKeys) {
  8843. const ret = {};
  8844. for (const key in props) {
  8845. if (!excludedKeys.includes(key)) {
  8846. Object.defineProperty(ret, key, {
  8847. enumerable: true,
  8848. get: () => props[key]
  8849. });
  8850. }
  8851. }
  8852. return ret;
  8853. }
  8854. /**
  8855. * `<script setup>` helper for persisting the current instance context over
  8856. * async/await flows.
  8857. *
  8858. * `@vue/compiler-sfc` converts the following:
  8859. *
  8860. * ```ts
  8861. * const x = await foo()
  8862. * ```
  8863. *
  8864. * into:
  8865. *
  8866. * ```ts
  8867. * let __temp, __restore
  8868. * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
  8869. * ```
  8870. * @internal
  8871. */
  8872. function withAsyncContext(getAwaitable) {
  8873. const ctx = getCurrentInstance();
  8874. if (!ctx) {
  8875. warn$1(`withAsyncContext called without active current instance. ` +
  8876. `This is likely a bug.`);
  8877. }
  8878. let awaitable = getAwaitable();
  8879. unsetCurrentInstance();
  8880. if (isPromise(awaitable)) {
  8881. awaitable = awaitable.catch(e => {
  8882. setCurrentInstance(ctx);
  8883. throw e;
  8884. });
  8885. }
  8886. return [awaitable, () => setCurrentInstance(ctx)];
  8887. }
  8888. // Actual implementation
  8889. function h(type, propsOrChildren, children) {
  8890. const l = arguments.length;
  8891. if (l === 2) {
  8892. if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
  8893. // single vnode without props
  8894. if (isVNode(propsOrChildren)) {
  8895. return createVNode(type, null, [propsOrChildren]);
  8896. }
  8897. // props without children
  8898. return createVNode(type, propsOrChildren);
  8899. }
  8900. else {
  8901. // omit props
  8902. return createVNode(type, null, propsOrChildren);
  8903. }
  8904. }
  8905. else {
  8906. if (l > 3) {
  8907. children = Array.prototype.slice.call(arguments, 2);
  8908. }
  8909. else if (l === 3 && isVNode(children)) {
  8910. children = [children];
  8911. }
  8912. return createVNode(type, propsOrChildren, children);
  8913. }
  8914. }
  8915. const ssrContextKey = Symbol(`ssrContext` );
  8916. const useSSRContext = () => {
  8917. {
  8918. const ctx = inject(ssrContextKey);
  8919. if (!ctx) {
  8920. warn$1(`Server rendering context not provided. Make sure to only call ` +
  8921. `useSSRContext() conditionally in the server build.`);
  8922. }
  8923. return ctx;
  8924. }
  8925. };
  8926. function initCustomFormatter() {
  8927. /* eslint-disable no-restricted-globals */
  8928. if (typeof window === 'undefined') {
  8929. return;
  8930. }
  8931. const vueStyle = { style: 'color:#3ba776' };
  8932. const numberStyle = { style: 'color:#0b1bc9' };
  8933. const stringStyle = { style: 'color:#b62e24' };
  8934. const keywordStyle = { style: 'color:#9d288c' };
  8935. // custom formatter for Chrome
  8936. // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
  8937. const formatter = {
  8938. header(obj) {
  8939. // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
  8940. if (!isObject(obj)) {
  8941. return null;
  8942. }
  8943. if (obj.__isVue) {
  8944. return ['div', vueStyle, `VueInstance`];
  8945. }
  8946. else if (isRef(obj)) {
  8947. return [
  8948. 'div',
  8949. {},
  8950. ['span', vueStyle, genRefFlag(obj)],
  8951. '<',
  8952. formatValue(obj.value),
  8953. `>`
  8954. ];
  8955. }
  8956. else if (isReactive(obj)) {
  8957. return [
  8958. 'div',
  8959. {},
  8960. ['span', vueStyle, isShallow(obj) ? 'ShallowReactive' : 'Reactive'],
  8961. '<',
  8962. formatValue(obj),
  8963. `>${isReadonly(obj) ? ` (readonly)` : ``}`
  8964. ];
  8965. }
  8966. else if (isReadonly(obj)) {
  8967. return [
  8968. 'div',
  8969. {},
  8970. ['span', vueStyle, isShallow(obj) ? 'ShallowReadonly' : 'Readonly'],
  8971. '<',
  8972. formatValue(obj),
  8973. '>'
  8974. ];
  8975. }
  8976. return null;
  8977. },
  8978. hasBody(obj) {
  8979. return obj && obj.__isVue;
  8980. },
  8981. body(obj) {
  8982. if (obj && obj.__isVue) {
  8983. return [
  8984. 'div',
  8985. {},
  8986. ...formatInstance(obj.$)
  8987. ];
  8988. }
  8989. }
  8990. };
  8991. function formatInstance(instance) {
  8992. const blocks = [];
  8993. if (instance.type.props && instance.props) {
  8994. blocks.push(createInstanceBlock('props', toRaw(instance.props)));
  8995. }
  8996. if (instance.setupState !== EMPTY_OBJ) {
  8997. blocks.push(createInstanceBlock('setup', instance.setupState));
  8998. }
  8999. if (instance.data !== EMPTY_OBJ) {
  9000. blocks.push(createInstanceBlock('data', toRaw(instance.data)));
  9001. }
  9002. const computed = extractKeys(instance, 'computed');
  9003. if (computed) {
  9004. blocks.push(createInstanceBlock('computed', computed));
  9005. }
  9006. const injected = extractKeys(instance, 'inject');
  9007. if (injected) {
  9008. blocks.push(createInstanceBlock('injected', injected));
  9009. }
  9010. blocks.push([
  9011. 'div',
  9012. {},
  9013. [
  9014. 'span',
  9015. {
  9016. style: keywordStyle.style + ';opacity:0.66'
  9017. },
  9018. '$ (internal): '
  9019. ],
  9020. ['object', { object: instance }]
  9021. ]);
  9022. return blocks;
  9023. }
  9024. function createInstanceBlock(type, target) {
  9025. target = extend({}, target);
  9026. if (!Object.keys(target).length) {
  9027. return ['span', {}];
  9028. }
  9029. return [
  9030. 'div',
  9031. { style: 'line-height:1.25em;margin-bottom:0.6em' },
  9032. [
  9033. 'div',
  9034. {
  9035. style: 'color:#476582'
  9036. },
  9037. type
  9038. ],
  9039. [
  9040. 'div',
  9041. {
  9042. style: 'padding-left:1.25em'
  9043. },
  9044. ...Object.keys(target).map(key => {
  9045. return [
  9046. 'div',
  9047. {},
  9048. ['span', keywordStyle, key + ': '],
  9049. formatValue(target[key], false)
  9050. ];
  9051. })
  9052. ]
  9053. ];
  9054. }
  9055. function formatValue(v, asRaw = true) {
  9056. if (typeof v === 'number') {
  9057. return ['span', numberStyle, v];
  9058. }
  9059. else if (typeof v === 'string') {
  9060. return ['span', stringStyle, JSON.stringify(v)];
  9061. }
  9062. else if (typeof v === 'boolean') {
  9063. return ['span', keywordStyle, v];
  9064. }
  9065. else if (isObject(v)) {
  9066. return ['object', { object: asRaw ? toRaw(v) : v }];
  9067. }
  9068. else {
  9069. return ['span', stringStyle, String(v)];
  9070. }
  9071. }
  9072. function extractKeys(instance, type) {
  9073. const Comp = instance.type;
  9074. if (isFunction(Comp)) {
  9075. return;
  9076. }
  9077. const extracted = {};
  9078. for (const key in instance.ctx) {
  9079. if (isKeyOfType(Comp, key, type)) {
  9080. extracted[key] = instance.ctx[key];
  9081. }
  9082. }
  9083. return extracted;
  9084. }
  9085. function isKeyOfType(Comp, key, type) {
  9086. const opts = Comp[type];
  9087. if ((isArray(opts) && opts.includes(key)) ||
  9088. (isObject(opts) && key in opts)) {
  9089. return true;
  9090. }
  9091. if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
  9092. return true;
  9093. }
  9094. if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
  9095. return true;
  9096. }
  9097. }
  9098. function genRefFlag(v) {
  9099. if (isShallow(v)) {
  9100. return `ShallowRef`;
  9101. }
  9102. if (v.effect) {
  9103. return `ComputedRef`;
  9104. }
  9105. return `Ref`;
  9106. }
  9107. if (window.devtoolsFormatters) {
  9108. window.devtoolsFormatters.push(formatter);
  9109. }
  9110. else {
  9111. window.devtoolsFormatters = [formatter];
  9112. }
  9113. }
  9114. function withMemo(memo, render, cache, index) {
  9115. const cached = cache[index];
  9116. if (cached && isMemoSame(cached, memo)) {
  9117. return cached;
  9118. }
  9119. const ret = render();
  9120. // shallow clone
  9121. ret.memo = memo.slice();
  9122. return (cache[index] = ret);
  9123. }
  9124. function isMemoSame(cached, memo) {
  9125. const prev = cached.memo;
  9126. if (prev.length != memo.length) {
  9127. return false;
  9128. }
  9129. for (let i = 0; i < prev.length; i++) {
  9130. if (prev[i] !== memo[i]) {
  9131. return false;
  9132. }
  9133. }
  9134. // make sure to let parent block track it when returning cached
  9135. if (isBlockTreeEnabled > 0 && currentBlock) {
  9136. currentBlock.push(cached);
  9137. }
  9138. return true;
  9139. }
  9140. // Core API ------------------------------------------------------------------
  9141. const version = "3.2.33";
  9142. /**
  9143. * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
  9144. * @internal
  9145. */
  9146. const ssrUtils = (null);
  9147. /**
  9148. * @internal only exposed in compat builds
  9149. */
  9150. const resolveFilter = null;
  9151. /**
  9152. * @internal only exposed in compat builds.
  9153. */
  9154. const compatUtils = (null);
  9155. const svgNS = 'http://www.w3.org/2000/svg';
  9156. const doc = (typeof document !== 'undefined' ? document : null);
  9157. const templateContainer = doc && /*#__PURE__*/ doc.createElement('template');
  9158. const nodeOps = {
  9159. insert: (child, parent, anchor) => {
  9160. parent.insertBefore(child, anchor || null);
  9161. },
  9162. remove: child => {
  9163. const parent = child.parentNode;
  9164. if (parent) {
  9165. parent.removeChild(child);
  9166. }
  9167. },
  9168. createElement: (tag, isSVG, is, props) => {
  9169. const el = isSVG
  9170. ? doc.createElementNS(svgNS, tag)
  9171. : doc.createElement(tag, is ? { is } : undefined);
  9172. if (tag === 'select' && props && props.multiple != null) {
  9173. el.setAttribute('multiple', props.multiple);
  9174. }
  9175. return el;
  9176. },
  9177. createText: text => doc.createTextNode(text),
  9178. createComment: text => doc.createComment(text),
  9179. setText: (node, text) => {
  9180. node.nodeValue = text;
  9181. },
  9182. setElementText: (el, text) => {
  9183. el.textContent = text;
  9184. },
  9185. parentNode: node => node.parentNode,
  9186. nextSibling: node => node.nextSibling,
  9187. querySelector: selector => doc.querySelector(selector),
  9188. setScopeId(el, id) {
  9189. el.setAttribute(id, '');
  9190. },
  9191. cloneNode(el) {
  9192. const cloned = el.cloneNode(true);
  9193. // #3072
  9194. // - in `patchDOMProp`, we store the actual value in the `el._value` property.
  9195. // - normally, elements using `:value` bindings will not be hoisted, but if
  9196. // the bound value is a constant, e.g. `:value="true"` - they do get
  9197. // hoisted.
  9198. // - in production, hoisted nodes are cloned when subsequent inserts, but
  9199. // cloneNode() does not copy the custom property we attached.
  9200. // - This may need to account for other custom DOM properties we attach to
  9201. // elements in addition to `_value` in the future.
  9202. if (`_value` in el) {
  9203. cloned._value = el._value;
  9204. }
  9205. return cloned;
  9206. },
  9207. // __UNSAFE__
  9208. // Reason: innerHTML.
  9209. // Static content here can only come from compiled templates.
  9210. // As long as the user only uses trusted templates, this is safe.
  9211. insertStaticContent(content, parent, anchor, isSVG, start, end) {
  9212. // <parent> before | first ... last | anchor </parent>
  9213. const before = anchor ? anchor.previousSibling : parent.lastChild;
  9214. // #5308 can only take cached path if:
  9215. // - has a single root node
  9216. // - nextSibling info is still available
  9217. if (start && (start === end || start.nextSibling)) {
  9218. // cached
  9219. while (true) {
  9220. parent.insertBefore(start.cloneNode(true), anchor);
  9221. if (start === end || !(start = start.nextSibling))
  9222. break;
  9223. }
  9224. }
  9225. else {
  9226. // fresh insert
  9227. templateContainer.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
  9228. const template = templateContainer.content;
  9229. if (isSVG) {
  9230. // remove outer svg wrapper
  9231. const wrapper = template.firstChild;
  9232. while (wrapper.firstChild) {
  9233. template.appendChild(wrapper.firstChild);
  9234. }
  9235. template.removeChild(wrapper);
  9236. }
  9237. parent.insertBefore(template, anchor);
  9238. }
  9239. return [
  9240. // first
  9241. before ? before.nextSibling : parent.firstChild,
  9242. // last
  9243. anchor ? anchor.previousSibling : parent.lastChild
  9244. ];
  9245. }
  9246. };
  9247. // compiler should normalize class + :class bindings on the same element
  9248. // into a single binding ['staticClass', dynamic]
  9249. function patchClass(el, value, isSVG) {
  9250. // directly setting className should be faster than setAttribute in theory
  9251. // if this is an element during a transition, take the temporary transition
  9252. // classes into account.
  9253. const transitionClasses = el._vtc;
  9254. if (transitionClasses) {
  9255. value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
  9256. }
  9257. if (value == null) {
  9258. el.removeAttribute('class');
  9259. }
  9260. else if (isSVG) {
  9261. el.setAttribute('class', value);
  9262. }
  9263. else {
  9264. el.className = value;
  9265. }
  9266. }
  9267. function patchStyle(el, prev, next) {
  9268. const style = el.style;
  9269. const isCssString = isString(next);
  9270. if (next && !isCssString) {
  9271. for (const key in next) {
  9272. setStyle(style, key, next[key]);
  9273. }
  9274. if (prev && !isString(prev)) {
  9275. for (const key in prev) {
  9276. if (next[key] == null) {
  9277. setStyle(style, key, '');
  9278. }
  9279. }
  9280. }
  9281. }
  9282. else {
  9283. const currentDisplay = style.display;
  9284. if (isCssString) {
  9285. if (prev !== next) {
  9286. style.cssText = next;
  9287. }
  9288. }
  9289. else if (prev) {
  9290. el.removeAttribute('style');
  9291. }
  9292. // indicates that the `display` of the element is controlled by `v-show`,
  9293. // so we always keep the current `display` value regardless of the `style`
  9294. // value, thus handing over control to `v-show`.
  9295. if ('_vod' in el) {
  9296. style.display = currentDisplay;
  9297. }
  9298. }
  9299. }
  9300. const importantRE = /\s*!important$/;
  9301. function setStyle(style, name, val) {
  9302. if (isArray(val)) {
  9303. val.forEach(v => setStyle(style, name, v));
  9304. }
  9305. else {
  9306. if (val == null)
  9307. val = '';
  9308. if (name.startsWith('--')) {
  9309. // custom property definition
  9310. style.setProperty(name, val);
  9311. }
  9312. else {
  9313. const prefixed = autoPrefix(style, name);
  9314. if (importantRE.test(val)) {
  9315. // !important
  9316. style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
  9317. }
  9318. else {
  9319. style[prefixed] = val;
  9320. }
  9321. }
  9322. }
  9323. }
  9324. const prefixes = ['Webkit', 'Moz', 'ms'];
  9325. const prefixCache = {};
  9326. function autoPrefix(style, rawName) {
  9327. const cached = prefixCache[rawName];
  9328. if (cached) {
  9329. return cached;
  9330. }
  9331. let name = camelize(rawName);
  9332. if (name !== 'filter' && name in style) {
  9333. return (prefixCache[rawName] = name);
  9334. }
  9335. name = capitalize(name);
  9336. for (let i = 0; i < prefixes.length; i++) {
  9337. const prefixed = prefixes[i] + name;
  9338. if (prefixed in style) {
  9339. return (prefixCache[rawName] = prefixed);
  9340. }
  9341. }
  9342. return rawName;
  9343. }
  9344. const xlinkNS = 'http://www.w3.org/1999/xlink';
  9345. function patchAttr(el, key, value, isSVG, instance) {
  9346. if (isSVG && key.startsWith('xlink:')) {
  9347. if (value == null) {
  9348. el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
  9349. }
  9350. else {
  9351. el.setAttributeNS(xlinkNS, key, value);
  9352. }
  9353. }
  9354. else {
  9355. // note we are only checking boolean attributes that don't have a
  9356. // corresponding dom prop of the same name here.
  9357. const isBoolean = isSpecialBooleanAttr(key);
  9358. if (value == null || (isBoolean && !includeBooleanAttr(value))) {
  9359. el.removeAttribute(key);
  9360. }
  9361. else {
  9362. el.setAttribute(key, isBoolean ? '' : value);
  9363. }
  9364. }
  9365. }
  9366. // __UNSAFE__
  9367. // functions. The user is responsible for using them with only trusted content.
  9368. function patchDOMProp(el, key, value,
  9369. // the following args are passed only due to potential innerHTML/textContent
  9370. // overriding existing VNodes, in which case the old tree must be properly
  9371. // unmounted.
  9372. prevChildren, parentComponent, parentSuspense, unmountChildren) {
  9373. if (key === 'innerHTML' || key === 'textContent') {
  9374. if (prevChildren) {
  9375. unmountChildren(prevChildren, parentComponent, parentSuspense);
  9376. }
  9377. el[key] = value == null ? '' : value;
  9378. return;
  9379. }
  9380. if (key === 'value' &&
  9381. el.tagName !== 'PROGRESS' &&
  9382. // custom elements may use _value internally
  9383. !el.tagName.includes('-')) {
  9384. // store value as _value as well since
  9385. // non-string values will be stringified.
  9386. el._value = value;
  9387. const newValue = value == null ? '' : value;
  9388. if (el.value !== newValue ||
  9389. // #4956: always set for OPTION elements because its value falls back to
  9390. // textContent if no value attribute is present. And setting .value for
  9391. // OPTION has no side effect
  9392. el.tagName === 'OPTION') {
  9393. el.value = newValue;
  9394. }
  9395. if (value == null) {
  9396. el.removeAttribute(key);
  9397. }
  9398. return;
  9399. }
  9400. let needRemove = false;
  9401. if (value === '' || value == null) {
  9402. const type = typeof el[key];
  9403. if (type === 'boolean') {
  9404. // e.g. <select multiple> compiles to { multiple: '' }
  9405. value = includeBooleanAttr(value);
  9406. }
  9407. else if (value == null && type === 'string') {
  9408. // e.g. <div :id="null">
  9409. value = '';
  9410. needRemove = true;
  9411. }
  9412. else if (type === 'number') {
  9413. // e.g. <img :width="null">
  9414. // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
  9415. value = 0;
  9416. needRemove = true;
  9417. }
  9418. }
  9419. // some properties perform value validation and throw,
  9420. // some properties has getter, no setter, will error in 'use strict'
  9421. // eg. <select :type="null"></select> <select :willValidate="null"></select>
  9422. try {
  9423. el[key] = value;
  9424. }
  9425. catch (e) {
  9426. {
  9427. warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
  9428. `value ${value} is invalid.`, e);
  9429. }
  9430. }
  9431. needRemove && el.removeAttribute(key);
  9432. }
  9433. // Async edge case fix requires storing an event listener's attach timestamp.
  9434. const [_getNow, skipTimestampCheck] = /*#__PURE__*/ (() => {
  9435. let _getNow = Date.now;
  9436. let skipTimestampCheck = false;
  9437. if (typeof window !== 'undefined') {
  9438. // Determine what event timestamp the browser is using. Annoyingly, the
  9439. // timestamp can either be hi-res (relative to page load) or low-res
  9440. // (relative to UNIX epoch), so in order to compare time we have to use the
  9441. // same timestamp type when saving the flush timestamp.
  9442. if (Date.now() > document.createEvent('Event').timeStamp) {
  9443. // if the low-res timestamp which is bigger than the event timestamp
  9444. // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
  9445. // and we need to use the hi-res version for event listeners as well.
  9446. _getNow = () => performance.now();
  9447. }
  9448. // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
  9449. // and does not fire microtasks in between event propagation, so safe to exclude.
  9450. const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
  9451. skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
  9452. }
  9453. return [_getNow, skipTimestampCheck];
  9454. })();
  9455. // To avoid the overhead of repeatedly calling performance.now(), we cache
  9456. // and use the same timestamp for all event listeners attached in the same tick.
  9457. let cachedNow = 0;
  9458. const p = /*#__PURE__*/ Promise.resolve();
  9459. const reset = () => {
  9460. cachedNow = 0;
  9461. };
  9462. const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
  9463. function addEventListener(el, event, handler, options) {
  9464. el.addEventListener(event, handler, options);
  9465. }
  9466. function removeEventListener(el, event, handler, options) {
  9467. el.removeEventListener(event, handler, options);
  9468. }
  9469. function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  9470. // vei = vue event invokers
  9471. const invokers = el._vei || (el._vei = {});
  9472. const existingInvoker = invokers[rawName];
  9473. if (nextValue && existingInvoker) {
  9474. // patch
  9475. existingInvoker.value = nextValue;
  9476. }
  9477. else {
  9478. const [name, options] = parseName(rawName);
  9479. if (nextValue) {
  9480. // add
  9481. const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
  9482. addEventListener(el, name, invoker, options);
  9483. }
  9484. else if (existingInvoker) {
  9485. // remove
  9486. removeEventListener(el, name, existingInvoker, options);
  9487. invokers[rawName] = undefined;
  9488. }
  9489. }
  9490. }
  9491. const optionsModifierRE = /(?:Once|Passive|Capture)$/;
  9492. function parseName(name) {
  9493. let options;
  9494. if (optionsModifierRE.test(name)) {
  9495. options = {};
  9496. let m;
  9497. while ((m = name.match(optionsModifierRE))) {
  9498. name = name.slice(0, name.length - m[0].length);
  9499. options[m[0].toLowerCase()] = true;
  9500. }
  9501. }
  9502. return [hyphenate(name.slice(2)), options];
  9503. }
  9504. function createInvoker(initialValue, instance) {
  9505. const invoker = (e) => {
  9506. // async edge case #6566: inner click event triggers patch, event handler
  9507. // attached to outer element during patch, and triggered again. This
  9508. // happens because browsers fire microtask ticks between event propagation.
  9509. // the solution is simple: we save the timestamp when a handler is attached,
  9510. // and the handler would only fire if the event passed to it was fired
  9511. // AFTER it was attached.
  9512. const timeStamp = e.timeStamp || _getNow();
  9513. if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
  9514. callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
  9515. }
  9516. };
  9517. invoker.value = initialValue;
  9518. invoker.attached = getNow();
  9519. return invoker;
  9520. }
  9521. function patchStopImmediatePropagation(e, value) {
  9522. if (isArray(value)) {
  9523. const originalStop = e.stopImmediatePropagation;
  9524. e.stopImmediatePropagation = () => {
  9525. originalStop.call(e);
  9526. e._stopped = true;
  9527. };
  9528. return value.map(fn => (e) => !e._stopped && fn && fn(e));
  9529. }
  9530. else {
  9531. return value;
  9532. }
  9533. }
  9534. const nativeOnRE = /^on[a-z]/;
  9535. const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
  9536. if (key === 'class') {
  9537. patchClass(el, nextValue, isSVG);
  9538. }
  9539. else if (key === 'style') {
  9540. patchStyle(el, prevValue, nextValue);
  9541. }
  9542. else if (isOn(key)) {
  9543. // ignore v-model listeners
  9544. if (!isModelListener(key)) {
  9545. patchEvent(el, key, prevValue, nextValue, parentComponent);
  9546. }
  9547. }
  9548. else if (key[0] === '.'
  9549. ? ((key = key.slice(1)), true)
  9550. : key[0] === '^'
  9551. ? ((key = key.slice(1)), false)
  9552. : shouldSetAsProp(el, key, nextValue, isSVG)) {
  9553. patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
  9554. }
  9555. else {
  9556. // special case for <input v-model type="checkbox"> with
  9557. // :true-value & :false-value
  9558. // store value as dom properties since non-string values will be
  9559. // stringified.
  9560. if (key === 'true-value') {
  9561. el._trueValue = nextValue;
  9562. }
  9563. else if (key === 'false-value') {
  9564. el._falseValue = nextValue;
  9565. }
  9566. patchAttr(el, key, nextValue, isSVG);
  9567. }
  9568. };
  9569. function shouldSetAsProp(el, key, value, isSVG) {
  9570. if (isSVG) {
  9571. // most keys must be set as attribute on svg elements to work
  9572. // ...except innerHTML & textContent
  9573. if (key === 'innerHTML' || key === 'textContent') {
  9574. return true;
  9575. }
  9576. // or native onclick with function values
  9577. if (key in el && nativeOnRE.test(key) && isFunction(value)) {
  9578. return true;
  9579. }
  9580. return false;
  9581. }
  9582. // these are enumerated attrs, however their corresponding DOM properties
  9583. // are actually booleans - this leads to setting it with a string "false"
  9584. // value leading it to be coerced to `true`, so we need to always treat
  9585. // them as attributes.
  9586. // Note that `contentEditable` doesn't have this problem: its DOM
  9587. // property is also enumerated string values.
  9588. if (key === 'spellcheck' || key === 'draggable' || key === 'translate') {
  9589. return false;
  9590. }
  9591. // #1787, #2840 form property on form elements is readonly and must be set as
  9592. // attribute.
  9593. if (key === 'form') {
  9594. return false;
  9595. }
  9596. // #1526 <input list> must be set as attribute
  9597. if (key === 'list' && el.tagName === 'INPUT') {
  9598. return false;
  9599. }
  9600. // #2766 <textarea type> must be set as attribute
  9601. if (key === 'type' && el.tagName === 'TEXTAREA') {
  9602. return false;
  9603. }
  9604. // native onclick with string value, must be set as attribute
  9605. if (nativeOnRE.test(key) && isString(value)) {
  9606. return false;
  9607. }
  9608. return key in el;
  9609. }
  9610. function defineCustomElement(options, hydate) {
  9611. const Comp = defineComponent(options);
  9612. class VueCustomElement extends VueElement {
  9613. constructor(initialProps) {
  9614. super(Comp, initialProps, hydate);
  9615. }
  9616. }
  9617. VueCustomElement.def = Comp;
  9618. return VueCustomElement;
  9619. }
  9620. const defineSSRCustomElement = ((options) => {
  9621. // @ts-ignore
  9622. return defineCustomElement(options, hydrate);
  9623. });
  9624. const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
  9625. });
  9626. class VueElement extends BaseClass {
  9627. constructor(_def, _props = {}, hydrate) {
  9628. super();
  9629. this._def = _def;
  9630. this._props = _props;
  9631. /**
  9632. * @internal
  9633. */
  9634. this._instance = null;
  9635. this._connected = false;
  9636. this._resolved = false;
  9637. this._numberProps = null;
  9638. if (this.shadowRoot && hydrate) {
  9639. hydrate(this._createVNode(), this.shadowRoot);
  9640. }
  9641. else {
  9642. if (this.shadowRoot) {
  9643. warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
  9644. `defined as hydratable. Use \`defineSSRCustomElement\`.`);
  9645. }
  9646. this.attachShadow({ mode: 'open' });
  9647. }
  9648. }
  9649. connectedCallback() {
  9650. this._connected = true;
  9651. if (!this._instance) {
  9652. this._resolveDef();
  9653. }
  9654. }
  9655. disconnectedCallback() {
  9656. this._connected = false;
  9657. nextTick(() => {
  9658. if (!this._connected) {
  9659. render(null, this.shadowRoot);
  9660. this._instance = null;
  9661. }
  9662. });
  9663. }
  9664. /**
  9665. * resolve inner component definition (handle possible async component)
  9666. */
  9667. _resolveDef() {
  9668. if (this._resolved) {
  9669. return;
  9670. }
  9671. this._resolved = true;
  9672. // set initial attrs
  9673. for (let i = 0; i < this.attributes.length; i++) {
  9674. this._setAttr(this.attributes[i].name);
  9675. }
  9676. // watch future attr changes
  9677. new MutationObserver(mutations => {
  9678. for (const m of mutations) {
  9679. this._setAttr(m.attributeName);
  9680. }
  9681. }).observe(this, { attributes: true });
  9682. const resolve = (def) => {
  9683. const { props, styles } = def;
  9684. const hasOptions = !isArray(props);
  9685. const rawKeys = props ? (hasOptions ? Object.keys(props) : props) : [];
  9686. // cast Number-type props set before resolve
  9687. let numberProps;
  9688. if (hasOptions) {
  9689. for (const key in this._props) {
  9690. const opt = props[key];
  9691. if (opt === Number || (opt && opt.type === Number)) {
  9692. this._props[key] = toNumber(this._props[key]);
  9693. (numberProps || (numberProps = Object.create(null)))[key] = true;
  9694. }
  9695. }
  9696. }
  9697. this._numberProps = numberProps;
  9698. // check if there are props set pre-upgrade or connect
  9699. for (const key of Object.keys(this)) {
  9700. if (key[0] !== '_') {
  9701. this._setProp(key, this[key], true, false);
  9702. }
  9703. }
  9704. // defining getter/setters on prototype
  9705. for (const key of rawKeys.map(camelize)) {
  9706. Object.defineProperty(this, key, {
  9707. get() {
  9708. return this._getProp(key);
  9709. },
  9710. set(val) {
  9711. this._setProp(key, val);
  9712. }
  9713. });
  9714. }
  9715. // apply CSS
  9716. this._applyStyles(styles);
  9717. // initial render
  9718. this._update();
  9719. };
  9720. const asyncDef = this._def.__asyncLoader;
  9721. if (asyncDef) {
  9722. asyncDef().then(resolve);
  9723. }
  9724. else {
  9725. resolve(this._def);
  9726. }
  9727. }
  9728. _setAttr(key) {
  9729. let value = this.getAttribute(key);
  9730. if (this._numberProps && this._numberProps[key]) {
  9731. value = toNumber(value);
  9732. }
  9733. this._setProp(camelize(key), value, false);
  9734. }
  9735. /**
  9736. * @internal
  9737. */
  9738. _getProp(key) {
  9739. return this._props[key];
  9740. }
  9741. /**
  9742. * @internal
  9743. */
  9744. _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
  9745. if (val !== this._props[key]) {
  9746. this._props[key] = val;
  9747. if (shouldUpdate && this._instance) {
  9748. this._update();
  9749. }
  9750. // reflect
  9751. if (shouldReflect) {
  9752. if (val === true) {
  9753. this.setAttribute(hyphenate(key), '');
  9754. }
  9755. else if (typeof val === 'string' || typeof val === 'number') {
  9756. this.setAttribute(hyphenate(key), val + '');
  9757. }
  9758. else if (!val) {
  9759. this.removeAttribute(hyphenate(key));
  9760. }
  9761. }
  9762. }
  9763. }
  9764. _update() {
  9765. render(this._createVNode(), this.shadowRoot);
  9766. }
  9767. _createVNode() {
  9768. const vnode = createVNode(this._def, extend({}, this._props));
  9769. if (!this._instance) {
  9770. vnode.ce = instance => {
  9771. this._instance = instance;
  9772. instance.isCE = true;
  9773. // HMR
  9774. {
  9775. instance.ceReload = newStyles => {
  9776. // always reset styles
  9777. if (this._styles) {
  9778. this._styles.forEach(s => this.shadowRoot.removeChild(s));
  9779. this._styles.length = 0;
  9780. }
  9781. this._applyStyles(newStyles);
  9782. // if this is an async component, ceReload is called from the inner
  9783. // component so no need to reload the async wrapper
  9784. if (!this._def.__asyncLoader) {
  9785. // reload
  9786. this._instance = null;
  9787. this._update();
  9788. }
  9789. };
  9790. }
  9791. // intercept emit
  9792. instance.emit = (event, ...args) => {
  9793. this.dispatchEvent(new CustomEvent(event, {
  9794. detail: args
  9795. }));
  9796. };
  9797. // locate nearest Vue custom element parent for provide/inject
  9798. let parent = this;
  9799. while ((parent =
  9800. parent && (parent.parentNode || parent.host))) {
  9801. if (parent instanceof VueElement) {
  9802. instance.parent = parent._instance;
  9803. break;
  9804. }
  9805. }
  9806. };
  9807. }
  9808. return vnode;
  9809. }
  9810. _applyStyles(styles) {
  9811. if (styles) {
  9812. styles.forEach(css => {
  9813. const s = document.createElement('style');
  9814. s.textContent = css;
  9815. this.shadowRoot.appendChild(s);
  9816. // record for HMR
  9817. {
  9818. (this._styles || (this._styles = [])).push(s);
  9819. }
  9820. });
  9821. }
  9822. }
  9823. }
  9824. function useCssModule(name = '$style') {
  9825. /* istanbul ignore else */
  9826. {
  9827. const instance = getCurrentInstance();
  9828. if (!instance) {
  9829. warn$1(`useCssModule must be called inside setup()`);
  9830. return EMPTY_OBJ;
  9831. }
  9832. const modules = instance.type.__cssModules;
  9833. if (!modules) {
  9834. warn$1(`Current instance does not have CSS modules injected.`);
  9835. return EMPTY_OBJ;
  9836. }
  9837. const mod = modules[name];
  9838. if (!mod) {
  9839. warn$1(`Current instance does not have CSS module named "${name}".`);
  9840. return EMPTY_OBJ;
  9841. }
  9842. return mod;
  9843. }
  9844. }
  9845. /**
  9846. * Runtime helper for SFC's CSS variable injection feature.
  9847. * @private
  9848. */
  9849. function useCssVars(getter) {
  9850. const instance = getCurrentInstance();
  9851. /* istanbul ignore next */
  9852. if (!instance) {
  9853. warn$1(`useCssVars is called without current active component instance.`);
  9854. return;
  9855. }
  9856. const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
  9857. watchPostEffect(setVars);
  9858. onMounted(() => {
  9859. const ob = new MutationObserver(setVars);
  9860. ob.observe(instance.subTree.el.parentNode, { childList: true });
  9861. onUnmounted(() => ob.disconnect());
  9862. });
  9863. }
  9864. function setVarsOnVNode(vnode, vars) {
  9865. if (vnode.shapeFlag & 128 /* SUSPENSE */) {
  9866. const suspense = vnode.suspense;
  9867. vnode = suspense.activeBranch;
  9868. if (suspense.pendingBranch && !suspense.isHydrating) {
  9869. suspense.effects.push(() => {
  9870. setVarsOnVNode(suspense.activeBranch, vars);
  9871. });
  9872. }
  9873. }
  9874. // drill down HOCs until it's a non-component vnode
  9875. while (vnode.component) {
  9876. vnode = vnode.component.subTree;
  9877. }
  9878. if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
  9879. setVarsOnNode(vnode.el, vars);
  9880. }
  9881. else if (vnode.type === Fragment) {
  9882. vnode.children.forEach(c => setVarsOnVNode(c, vars));
  9883. }
  9884. else if (vnode.type === Static) {
  9885. let { el, anchor } = vnode;
  9886. while (el) {
  9887. setVarsOnNode(el, vars);
  9888. if (el === anchor)
  9889. break;
  9890. el = el.nextSibling;
  9891. }
  9892. }
  9893. }
  9894. function setVarsOnNode(el, vars) {
  9895. if (el.nodeType === 1) {
  9896. const style = el.style;
  9897. for (const key in vars) {
  9898. style.setProperty(`--${key}`, vars[key]);
  9899. }
  9900. }
  9901. }
  9902. const TRANSITION = 'transition';
  9903. const ANIMATION = 'animation';
  9904. // DOM Transition is a higher-order-component based on the platform-agnostic
  9905. // base Transition component, with DOM-specific logic.
  9906. const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
  9907. Transition.displayName = 'Transition';
  9908. const DOMTransitionPropsValidators = {
  9909. name: String,
  9910. type: String,
  9911. css: {
  9912. type: Boolean,
  9913. default: true
  9914. },
  9915. duration: [String, Number, Object],
  9916. enterFromClass: String,
  9917. enterActiveClass: String,
  9918. enterToClass: String,
  9919. appearFromClass: String,
  9920. appearActiveClass: String,
  9921. appearToClass: String,
  9922. leaveFromClass: String,
  9923. leaveActiveClass: String,
  9924. leaveToClass: String
  9925. };
  9926. const TransitionPropsValidators = (Transition.props =
  9927. /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
  9928. /**
  9929. * #3227 Incoming hooks may be merged into arrays when wrapping Transition
  9930. * with custom HOCs.
  9931. */
  9932. const callHook$1 = (hook, args = []) => {
  9933. if (isArray(hook)) {
  9934. hook.forEach(h => h(...args));
  9935. }
  9936. else if (hook) {
  9937. hook(...args);
  9938. }
  9939. };
  9940. /**
  9941. * Check if a hook expects a callback (2nd arg), which means the user
  9942. * intends to explicitly control the end of the transition.
  9943. */
  9944. const hasExplicitCallback = (hook) => {
  9945. return hook
  9946. ? isArray(hook)
  9947. ? hook.some(h => h.length > 1)
  9948. : hook.length > 1
  9949. : false;
  9950. };
  9951. function resolveTransitionProps(rawProps) {
  9952. const baseProps = {};
  9953. for (const key in rawProps) {
  9954. if (!(key in DOMTransitionPropsValidators)) {
  9955. baseProps[key] = rawProps[key];
  9956. }
  9957. }
  9958. if (rawProps.css === false) {
  9959. return baseProps;
  9960. }
  9961. const { name = 'v', type, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps;
  9962. const durations = normalizeDuration(duration);
  9963. const enterDuration = durations && durations[0];
  9964. const leaveDuration = durations && durations[1];
  9965. const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
  9966. const finishEnter = (el, isAppear, done) => {
  9967. removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
  9968. removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
  9969. done && done();
  9970. };
  9971. const finishLeave = (el, done) => {
  9972. removeTransitionClass(el, leaveToClass);
  9973. removeTransitionClass(el, leaveActiveClass);
  9974. done && done();
  9975. };
  9976. const makeEnterHook = (isAppear) => {
  9977. return (el, done) => {
  9978. const hook = isAppear ? onAppear : onEnter;
  9979. const resolve = () => finishEnter(el, isAppear, done);
  9980. callHook$1(hook, [el, resolve]);
  9981. nextFrame(() => {
  9982. removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
  9983. addTransitionClass(el, isAppear ? appearToClass : enterToClass);
  9984. if (!hasExplicitCallback(hook)) {
  9985. whenTransitionEnds(el, type, enterDuration, resolve);
  9986. }
  9987. });
  9988. };
  9989. };
  9990. return extend(baseProps, {
  9991. onBeforeEnter(el) {
  9992. callHook$1(onBeforeEnter, [el]);
  9993. addTransitionClass(el, enterFromClass);
  9994. addTransitionClass(el, enterActiveClass);
  9995. },
  9996. onBeforeAppear(el) {
  9997. callHook$1(onBeforeAppear, [el]);
  9998. addTransitionClass(el, appearFromClass);
  9999. addTransitionClass(el, appearActiveClass);
  10000. },
  10001. onEnter: makeEnterHook(false),
  10002. onAppear: makeEnterHook(true),
  10003. onLeave(el, done) {
  10004. const resolve = () => finishLeave(el, done);
  10005. addTransitionClass(el, leaveFromClass);
  10006. // force reflow so *-leave-from classes immediately take effect (#2593)
  10007. forceReflow();
  10008. addTransitionClass(el, leaveActiveClass);
  10009. nextFrame(() => {
  10010. removeTransitionClass(el, leaveFromClass);
  10011. addTransitionClass(el, leaveToClass);
  10012. if (!hasExplicitCallback(onLeave)) {
  10013. whenTransitionEnds(el, type, leaveDuration, resolve);
  10014. }
  10015. });
  10016. callHook$1(onLeave, [el, resolve]);
  10017. },
  10018. onEnterCancelled(el) {
  10019. finishEnter(el, false);
  10020. callHook$1(onEnterCancelled, [el]);
  10021. },
  10022. onAppearCancelled(el) {
  10023. finishEnter(el, true);
  10024. callHook$1(onAppearCancelled, [el]);
  10025. },
  10026. onLeaveCancelled(el) {
  10027. finishLeave(el);
  10028. callHook$1(onLeaveCancelled, [el]);
  10029. }
  10030. });
  10031. }
  10032. function normalizeDuration(duration) {
  10033. if (duration == null) {
  10034. return null;
  10035. }
  10036. else if (isObject(duration)) {
  10037. return [NumberOf(duration.enter), NumberOf(duration.leave)];
  10038. }
  10039. else {
  10040. const n = NumberOf(duration);
  10041. return [n, n];
  10042. }
  10043. }
  10044. function NumberOf(val) {
  10045. const res = toNumber(val);
  10046. validateDuration(res);
  10047. return res;
  10048. }
  10049. function validateDuration(val) {
  10050. if (typeof val !== 'number') {
  10051. warn$1(`<transition> explicit duration is not a valid number - ` +
  10052. `got ${JSON.stringify(val)}.`);
  10053. }
  10054. else if (isNaN(val)) {
  10055. warn$1(`<transition> explicit duration is NaN - ` +
  10056. 'the duration expression might be incorrect.');
  10057. }
  10058. }
  10059. function addTransitionClass(el, cls) {
  10060. cls.split(/\s+/).forEach(c => c && el.classList.add(c));
  10061. (el._vtc ||
  10062. (el._vtc = new Set())).add(cls);
  10063. }
  10064. function removeTransitionClass(el, cls) {
  10065. cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
  10066. const { _vtc } = el;
  10067. if (_vtc) {
  10068. _vtc.delete(cls);
  10069. if (!_vtc.size) {
  10070. el._vtc = undefined;
  10071. }
  10072. }
  10073. }
  10074. function nextFrame(cb) {
  10075. requestAnimationFrame(() => {
  10076. requestAnimationFrame(cb);
  10077. });
  10078. }
  10079. let endId = 0;
  10080. function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
  10081. const id = (el._endId = ++endId);
  10082. const resolveIfNotStale = () => {
  10083. if (id === el._endId) {
  10084. resolve();
  10085. }
  10086. };
  10087. if (explicitTimeout) {
  10088. return setTimeout(resolveIfNotStale, explicitTimeout);
  10089. }
  10090. const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
  10091. if (!type) {
  10092. return resolve();
  10093. }
  10094. const endEvent = type + 'end';
  10095. let ended = 0;
  10096. const end = () => {
  10097. el.removeEventListener(endEvent, onEnd);
  10098. resolveIfNotStale();
  10099. };
  10100. const onEnd = (e) => {
  10101. if (e.target === el && ++ended >= propCount) {
  10102. end();
  10103. }
  10104. };
  10105. setTimeout(() => {
  10106. if (ended < propCount) {
  10107. end();
  10108. }
  10109. }, timeout + 1);
  10110. el.addEventListener(endEvent, onEnd);
  10111. }
  10112. function getTransitionInfo(el, expectedType) {
  10113. const styles = window.getComputedStyle(el);
  10114. // JSDOM may return undefined for transition properties
  10115. const getStyleProperties = (key) => (styles[key] || '').split(', ');
  10116. const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
  10117. const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
  10118. const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
  10119. const animationDelays = getStyleProperties(ANIMATION + 'Delay');
  10120. const animationDurations = getStyleProperties(ANIMATION + 'Duration');
  10121. const animationTimeout = getTimeout(animationDelays, animationDurations);
  10122. let type = null;
  10123. let timeout = 0;
  10124. let propCount = 0;
  10125. /* istanbul ignore if */
  10126. if (expectedType === TRANSITION) {
  10127. if (transitionTimeout > 0) {
  10128. type = TRANSITION;
  10129. timeout = transitionTimeout;
  10130. propCount = transitionDurations.length;
  10131. }
  10132. }
  10133. else if (expectedType === ANIMATION) {
  10134. if (animationTimeout > 0) {
  10135. type = ANIMATION;
  10136. timeout = animationTimeout;
  10137. propCount = animationDurations.length;
  10138. }
  10139. }
  10140. else {
  10141. timeout = Math.max(transitionTimeout, animationTimeout);
  10142. type =
  10143. timeout > 0
  10144. ? transitionTimeout > animationTimeout
  10145. ? TRANSITION
  10146. : ANIMATION
  10147. : null;
  10148. propCount = type
  10149. ? type === TRANSITION
  10150. ? transitionDurations.length
  10151. : animationDurations.length
  10152. : 0;
  10153. }
  10154. const hasTransform = type === TRANSITION &&
  10155. /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
  10156. return {
  10157. type,
  10158. timeout,
  10159. propCount,
  10160. hasTransform
  10161. };
  10162. }
  10163. function getTimeout(delays, durations) {
  10164. while (delays.length < durations.length) {
  10165. delays = delays.concat(delays);
  10166. }
  10167. return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
  10168. }
  10169. // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
  10170. // numbers in a locale-dependent way, using a comma instead of a dot.
  10171. // If comma is not replaced with a dot, the input will be rounded down
  10172. // (i.e. acting as a floor function) causing unexpected behaviors
  10173. function toMs(s) {
  10174. return Number(s.slice(0, -1).replace(',', '.')) * 1000;
  10175. }
  10176. // synchronously force layout to put elements into a certain state
  10177. function forceReflow() {
  10178. return document.body.offsetHeight;
  10179. }
  10180. const positionMap = new WeakMap();
  10181. const newPositionMap = new WeakMap();
  10182. const TransitionGroupImpl = {
  10183. name: 'TransitionGroup',
  10184. props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
  10185. tag: String,
  10186. moveClass: String
  10187. }),
  10188. setup(props, { slots }) {
  10189. const instance = getCurrentInstance();
  10190. const state = useTransitionState();
  10191. let prevChildren;
  10192. let children;
  10193. onUpdated(() => {
  10194. // children is guaranteed to exist after initial render
  10195. if (!prevChildren.length) {
  10196. return;
  10197. }
  10198. const moveClass = props.moveClass || `${props.name || 'v'}-move`;
  10199. if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
  10200. return;
  10201. }
  10202. // we divide the work into three loops to avoid mixing DOM reads and writes
  10203. // in each iteration - which helps prevent layout thrashing.
  10204. prevChildren.forEach(callPendingCbs);
  10205. prevChildren.forEach(recordPosition);
  10206. const movedChildren = prevChildren.filter(applyTranslation);
  10207. // force reflow to put everything in position
  10208. forceReflow();
  10209. movedChildren.forEach(c => {
  10210. const el = c.el;
  10211. const style = el.style;
  10212. addTransitionClass(el, moveClass);
  10213. style.transform = style.webkitTransform = style.transitionDuration = '';
  10214. const cb = (el._moveCb = (e) => {
  10215. if (e && e.target !== el) {
  10216. return;
  10217. }
  10218. if (!e || /transform$/.test(e.propertyName)) {
  10219. el.removeEventListener('transitionend', cb);
  10220. el._moveCb = null;
  10221. removeTransitionClass(el, moveClass);
  10222. }
  10223. });
  10224. el.addEventListener('transitionend', cb);
  10225. });
  10226. });
  10227. return () => {
  10228. const rawProps = toRaw(props);
  10229. const cssTransitionProps = resolveTransitionProps(rawProps);
  10230. let tag = rawProps.tag || Fragment;
  10231. prevChildren = children;
  10232. children = slots.default ? getTransitionRawChildren(slots.default()) : [];
  10233. for (let i = 0; i < children.length; i++) {
  10234. const child = children[i];
  10235. if (child.key != null) {
  10236. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  10237. }
  10238. else {
  10239. warn$1(`<TransitionGroup> children must be keyed.`);
  10240. }
  10241. }
  10242. if (prevChildren) {
  10243. for (let i = 0; i < prevChildren.length; i++) {
  10244. const child = prevChildren[i];
  10245. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  10246. positionMap.set(child, child.el.getBoundingClientRect());
  10247. }
  10248. }
  10249. return createVNode(tag, null, children);
  10250. };
  10251. }
  10252. };
  10253. const TransitionGroup = TransitionGroupImpl;
  10254. function callPendingCbs(c) {
  10255. const el = c.el;
  10256. if (el._moveCb) {
  10257. el._moveCb();
  10258. }
  10259. if (el._enterCb) {
  10260. el._enterCb();
  10261. }
  10262. }
  10263. function recordPosition(c) {
  10264. newPositionMap.set(c, c.el.getBoundingClientRect());
  10265. }
  10266. function applyTranslation(c) {
  10267. const oldPos = positionMap.get(c);
  10268. const newPos = newPositionMap.get(c);
  10269. const dx = oldPos.left - newPos.left;
  10270. const dy = oldPos.top - newPos.top;
  10271. if (dx || dy) {
  10272. const s = c.el.style;
  10273. s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
  10274. s.transitionDuration = '0s';
  10275. return c;
  10276. }
  10277. }
  10278. function hasCSSTransform(el, root, moveClass) {
  10279. // Detect whether an element with the move class applied has
  10280. // CSS transitions. Since the element may be inside an entering
  10281. // transition at this very moment, we make a clone of it and remove
  10282. // all other transition classes applied to ensure only the move class
  10283. // is applied.
  10284. const clone = el.cloneNode();
  10285. if (el._vtc) {
  10286. el._vtc.forEach(cls => {
  10287. cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
  10288. });
  10289. }
  10290. moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
  10291. clone.style.display = 'none';
  10292. const container = (root.nodeType === 1 ? root : root.parentNode);
  10293. container.appendChild(clone);
  10294. const { hasTransform } = getTransitionInfo(clone);
  10295. container.removeChild(clone);
  10296. return hasTransform;
  10297. }
  10298. const getModelAssigner = (vnode) => {
  10299. const fn = vnode.props['onUpdate:modelValue'];
  10300. return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
  10301. };
  10302. function onCompositionStart(e) {
  10303. e.target.composing = true;
  10304. }
  10305. function onCompositionEnd(e) {
  10306. const target = e.target;
  10307. if (target.composing) {
  10308. target.composing = false;
  10309. trigger$1(target, 'input');
  10310. }
  10311. }
  10312. function trigger$1(el, type) {
  10313. const e = document.createEvent('HTMLEvents');
  10314. e.initEvent(type, true, true);
  10315. el.dispatchEvent(e);
  10316. }
  10317. // We are exporting the v-model runtime directly as vnode hooks so that it can
  10318. // be tree-shaken in case v-model is never used.
  10319. const vModelText = {
  10320. created(el, { modifiers: { lazy, trim, number } }, vnode) {
  10321. el._assign = getModelAssigner(vnode);
  10322. const castToNumber = number || (vnode.props && vnode.props.type === 'number');
  10323. addEventListener(el, lazy ? 'change' : 'input', e => {
  10324. if (e.target.composing)
  10325. return;
  10326. let domValue = el.value;
  10327. if (trim) {
  10328. domValue = domValue.trim();
  10329. }
  10330. else if (castToNumber) {
  10331. domValue = toNumber(domValue);
  10332. }
  10333. el._assign(domValue);
  10334. });
  10335. if (trim) {
  10336. addEventListener(el, 'change', () => {
  10337. el.value = el.value.trim();
  10338. });
  10339. }
  10340. if (!lazy) {
  10341. addEventListener(el, 'compositionstart', onCompositionStart);
  10342. addEventListener(el, 'compositionend', onCompositionEnd);
  10343. // Safari < 10.2 & UIWebView doesn't fire compositionend when
  10344. // switching focus before confirming composition choice
  10345. // this also fixes the issue where some browsers e.g. iOS Chrome
  10346. // fires "change" instead of "input" on autocomplete.
  10347. addEventListener(el, 'change', onCompositionEnd);
  10348. }
  10349. },
  10350. // set value on mounted so it's after min/max for type="range"
  10351. mounted(el, { value }) {
  10352. el.value = value == null ? '' : value;
  10353. },
  10354. beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
  10355. el._assign = getModelAssigner(vnode);
  10356. // avoid clearing unresolved text. #2302
  10357. if (el.composing)
  10358. return;
  10359. if (document.activeElement === el) {
  10360. if (lazy) {
  10361. return;
  10362. }
  10363. if (trim && el.value.trim() === value) {
  10364. return;
  10365. }
  10366. if ((number || el.type === 'number') && toNumber(el.value) === value) {
  10367. return;
  10368. }
  10369. }
  10370. const newValue = value == null ? '' : value;
  10371. if (el.value !== newValue) {
  10372. el.value = newValue;
  10373. }
  10374. }
  10375. };
  10376. const vModelCheckbox = {
  10377. // #4096 array checkboxes need to be deep traversed
  10378. deep: true,
  10379. created(el, _, vnode) {
  10380. el._assign = getModelAssigner(vnode);
  10381. addEventListener(el, 'change', () => {
  10382. const modelValue = el._modelValue;
  10383. const elementValue = getValue(el);
  10384. const checked = el.checked;
  10385. const assign = el._assign;
  10386. if (isArray(modelValue)) {
  10387. const index = looseIndexOf(modelValue, elementValue);
  10388. const found = index !== -1;
  10389. if (checked && !found) {
  10390. assign(modelValue.concat(elementValue));
  10391. }
  10392. else if (!checked && found) {
  10393. const filtered = [...modelValue];
  10394. filtered.splice(index, 1);
  10395. assign(filtered);
  10396. }
  10397. }
  10398. else if (isSet(modelValue)) {
  10399. const cloned = new Set(modelValue);
  10400. if (checked) {
  10401. cloned.add(elementValue);
  10402. }
  10403. else {
  10404. cloned.delete(elementValue);
  10405. }
  10406. assign(cloned);
  10407. }
  10408. else {
  10409. assign(getCheckboxValue(el, checked));
  10410. }
  10411. });
  10412. },
  10413. // set initial checked on mount to wait for true-value/false-value
  10414. mounted: setChecked,
  10415. beforeUpdate(el, binding, vnode) {
  10416. el._assign = getModelAssigner(vnode);
  10417. setChecked(el, binding, vnode);
  10418. }
  10419. };
  10420. function setChecked(el, { value, oldValue }, vnode) {
  10421. el._modelValue = value;
  10422. if (isArray(value)) {
  10423. el.checked = looseIndexOf(value, vnode.props.value) > -1;
  10424. }
  10425. else if (isSet(value)) {
  10426. el.checked = value.has(vnode.props.value);
  10427. }
  10428. else if (value !== oldValue) {
  10429. el.checked = looseEqual(value, getCheckboxValue(el, true));
  10430. }
  10431. }
  10432. const vModelRadio = {
  10433. created(el, { value }, vnode) {
  10434. el.checked = looseEqual(value, vnode.props.value);
  10435. el._assign = getModelAssigner(vnode);
  10436. addEventListener(el, 'change', () => {
  10437. el._assign(getValue(el));
  10438. });
  10439. },
  10440. beforeUpdate(el, { value, oldValue }, vnode) {
  10441. el._assign = getModelAssigner(vnode);
  10442. if (value !== oldValue) {
  10443. el.checked = looseEqual(value, vnode.props.value);
  10444. }
  10445. }
  10446. };
  10447. const vModelSelect = {
  10448. // <select multiple> value need to be deep traversed
  10449. deep: true,
  10450. created(el, { value, modifiers: { number } }, vnode) {
  10451. const isSetModel = isSet(value);
  10452. addEventListener(el, 'change', () => {
  10453. const selectedVal = Array.prototype.filter
  10454. .call(el.options, (o) => o.selected)
  10455. .map((o) => number ? toNumber(getValue(o)) : getValue(o));
  10456. el._assign(el.multiple
  10457. ? isSetModel
  10458. ? new Set(selectedVal)
  10459. : selectedVal
  10460. : selectedVal[0]);
  10461. });
  10462. el._assign = getModelAssigner(vnode);
  10463. },
  10464. // set value in mounted & updated because <select> relies on its children
  10465. // <option>s.
  10466. mounted(el, { value }) {
  10467. setSelected(el, value);
  10468. },
  10469. beforeUpdate(el, _binding, vnode) {
  10470. el._assign = getModelAssigner(vnode);
  10471. },
  10472. updated(el, { value }) {
  10473. setSelected(el, value);
  10474. }
  10475. };
  10476. function setSelected(el, value) {
  10477. const isMultiple = el.multiple;
  10478. if (isMultiple && !isArray(value) && !isSet(value)) {
  10479. warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
  10480. `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
  10481. return;
  10482. }
  10483. for (let i = 0, l = el.options.length; i < l; i++) {
  10484. const option = el.options[i];
  10485. const optionValue = getValue(option);
  10486. if (isMultiple) {
  10487. if (isArray(value)) {
  10488. option.selected = looseIndexOf(value, optionValue) > -1;
  10489. }
  10490. else {
  10491. option.selected = value.has(optionValue);
  10492. }
  10493. }
  10494. else {
  10495. if (looseEqual(getValue(option), value)) {
  10496. if (el.selectedIndex !== i)
  10497. el.selectedIndex = i;
  10498. return;
  10499. }
  10500. }
  10501. }
  10502. if (!isMultiple && el.selectedIndex !== -1) {
  10503. el.selectedIndex = -1;
  10504. }
  10505. }
  10506. // retrieve raw value set via :value bindings
  10507. function getValue(el) {
  10508. return '_value' in el ? el._value : el.value;
  10509. }
  10510. // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
  10511. function getCheckboxValue(el, checked) {
  10512. const key = checked ? '_trueValue' : '_falseValue';
  10513. return key in el ? el[key] : checked;
  10514. }
  10515. const vModelDynamic = {
  10516. created(el, binding, vnode) {
  10517. callModelHook(el, binding, vnode, null, 'created');
  10518. },
  10519. mounted(el, binding, vnode) {
  10520. callModelHook(el, binding, vnode, null, 'mounted');
  10521. },
  10522. beforeUpdate(el, binding, vnode, prevVNode) {
  10523. callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
  10524. },
  10525. updated(el, binding, vnode, prevVNode) {
  10526. callModelHook(el, binding, vnode, prevVNode, 'updated');
  10527. }
  10528. };
  10529. function callModelHook(el, binding, vnode, prevVNode, hook) {
  10530. let modelToUse;
  10531. switch (el.tagName) {
  10532. case 'SELECT':
  10533. modelToUse = vModelSelect;
  10534. break;
  10535. case 'TEXTAREA':
  10536. modelToUse = vModelText;
  10537. break;
  10538. default:
  10539. switch (vnode.props && vnode.props.type) {
  10540. case 'checkbox':
  10541. modelToUse = vModelCheckbox;
  10542. break;
  10543. case 'radio':
  10544. modelToUse = vModelRadio;
  10545. break;
  10546. default:
  10547. modelToUse = vModelText;
  10548. }
  10549. }
  10550. const fn = modelToUse[hook];
  10551. fn && fn(el, binding, vnode, prevVNode);
  10552. }
  10553. const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
  10554. const modifierGuards = {
  10555. stop: e => e.stopPropagation(),
  10556. prevent: e => e.preventDefault(),
  10557. self: e => e.target !== e.currentTarget,
  10558. ctrl: e => !e.ctrlKey,
  10559. shift: e => !e.shiftKey,
  10560. alt: e => !e.altKey,
  10561. meta: e => !e.metaKey,
  10562. left: e => 'button' in e && e.button !== 0,
  10563. middle: e => 'button' in e && e.button !== 1,
  10564. right: e => 'button' in e && e.button !== 2,
  10565. exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
  10566. };
  10567. /**
  10568. * @private
  10569. */
  10570. const withModifiers = (fn, modifiers) => {
  10571. return (event, ...args) => {
  10572. for (let i = 0; i < modifiers.length; i++) {
  10573. const guard = modifierGuards[modifiers[i]];
  10574. if (guard && guard(event, modifiers))
  10575. return;
  10576. }
  10577. return fn(event, ...args);
  10578. };
  10579. };
  10580. // Kept for 2.x compat.
  10581. // Note: IE11 compat for `spacebar` and `del` is removed for now.
  10582. const keyNames = {
  10583. esc: 'escape',
  10584. space: ' ',
  10585. up: 'arrow-up',
  10586. left: 'arrow-left',
  10587. right: 'arrow-right',
  10588. down: 'arrow-down',
  10589. delete: 'backspace'
  10590. };
  10591. /**
  10592. * @private
  10593. */
  10594. const withKeys = (fn, modifiers) => {
  10595. return (event) => {
  10596. if (!('key' in event)) {
  10597. return;
  10598. }
  10599. const eventKey = hyphenate(event.key);
  10600. if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
  10601. return fn(event);
  10602. }
  10603. };
  10604. };
  10605. const vShow = {
  10606. beforeMount(el, { value }, { transition }) {
  10607. el._vod = el.style.display === 'none' ? '' : el.style.display;
  10608. if (transition && value) {
  10609. transition.beforeEnter(el);
  10610. }
  10611. else {
  10612. setDisplay(el, value);
  10613. }
  10614. },
  10615. mounted(el, { value }, { transition }) {
  10616. if (transition && value) {
  10617. transition.enter(el);
  10618. }
  10619. },
  10620. updated(el, { value, oldValue }, { transition }) {
  10621. if (!value === !oldValue)
  10622. return;
  10623. if (transition) {
  10624. if (value) {
  10625. transition.beforeEnter(el);
  10626. setDisplay(el, true);
  10627. transition.enter(el);
  10628. }
  10629. else {
  10630. transition.leave(el, () => {
  10631. setDisplay(el, false);
  10632. });
  10633. }
  10634. }
  10635. else {
  10636. setDisplay(el, value);
  10637. }
  10638. },
  10639. beforeUnmount(el, { value }) {
  10640. setDisplay(el, value);
  10641. }
  10642. };
  10643. function setDisplay(el, value) {
  10644. el.style.display = value ? el._vod : 'none';
  10645. }
  10646. const rendererOptions = /*#__PURE__*/ extend({ patchProp }, nodeOps);
  10647. // lazy create the renderer - this makes core renderer logic tree-shakable
  10648. // in case the user only imports reactivity utilities from Vue.
  10649. let renderer;
  10650. let enabledHydration = false;
  10651. function ensureRenderer() {
  10652. return (renderer ||
  10653. (renderer = createRenderer(rendererOptions)));
  10654. }
  10655. function ensureHydrationRenderer() {
  10656. renderer = enabledHydration
  10657. ? renderer
  10658. : createHydrationRenderer(rendererOptions);
  10659. enabledHydration = true;
  10660. return renderer;
  10661. }
  10662. // use explicit type casts here to avoid import() calls in rolled-up d.ts
  10663. const render = ((...args) => {
  10664. ensureRenderer().render(...args);
  10665. });
  10666. const hydrate = ((...args) => {
  10667. ensureHydrationRenderer().hydrate(...args);
  10668. });
  10669. const createApp = ((...args) => {
  10670. const app = ensureRenderer().createApp(...args);
  10671. {
  10672. injectNativeTagCheck(app);
  10673. injectCompilerOptionsCheck(app);
  10674. }
  10675. const { mount } = app;
  10676. app.mount = (containerOrSelector) => {
  10677. const container = normalizeContainer(containerOrSelector);
  10678. if (!container)
  10679. return;
  10680. const component = app._component;
  10681. if (!isFunction(component) && !component.render && !component.template) {
  10682. // __UNSAFE__
  10683. // Reason: potential execution of JS expressions in in-DOM template.
  10684. // The user must make sure the in-DOM template is trusted. If it's
  10685. // rendered by the server, the template should not contain any user data.
  10686. component.template = container.innerHTML;
  10687. }
  10688. // clear content before mounting
  10689. container.innerHTML = '';
  10690. const proxy = mount(container, false, container instanceof SVGElement);
  10691. if (container instanceof Element) {
  10692. container.removeAttribute('v-cloak');
  10693. container.setAttribute('data-v-app', '');
  10694. }
  10695. return proxy;
  10696. };
  10697. return app;
  10698. });
  10699. const createSSRApp = ((...args) => {
  10700. const app = ensureHydrationRenderer().createApp(...args);
  10701. {
  10702. injectNativeTagCheck(app);
  10703. injectCompilerOptionsCheck(app);
  10704. }
  10705. const { mount } = app;
  10706. app.mount = (containerOrSelector) => {
  10707. const container = normalizeContainer(containerOrSelector);
  10708. if (container) {
  10709. return mount(container, true, container instanceof SVGElement);
  10710. }
  10711. };
  10712. return app;
  10713. });
  10714. function injectNativeTagCheck(app) {
  10715. // Inject `isNativeTag`
  10716. // this is used for component name validation (dev only)
  10717. Object.defineProperty(app.config, 'isNativeTag', {
  10718. value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
  10719. writable: false
  10720. });
  10721. }
  10722. // dev only
  10723. function injectCompilerOptionsCheck(app) {
  10724. if (isRuntimeOnly()) {
  10725. const isCustomElement = app.config.isCustomElement;
  10726. Object.defineProperty(app.config, 'isCustomElement', {
  10727. get() {
  10728. return isCustomElement;
  10729. },
  10730. set() {
  10731. warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
  10732. `\`compilerOptions.isCustomElement\` instead.`);
  10733. }
  10734. });
  10735. const compilerOptions = app.config.compilerOptions;
  10736. const msg = `The \`compilerOptions\` config option is only respected when using ` +
  10737. `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
  10738. `Since you are using the runtime-only build, \`compilerOptions\` ` +
  10739. `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
  10740. `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
  10741. `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
  10742. `- For vite: pass it via @vitejs/plugin-vue options. See https://github.com/vitejs/vite/tree/main/packages/plugin-vue#example-for-passing-options-to-vuecompiler-dom`;
  10743. Object.defineProperty(app.config, 'compilerOptions', {
  10744. get() {
  10745. warn$1(msg);
  10746. return compilerOptions;
  10747. },
  10748. set() {
  10749. warn$1(msg);
  10750. }
  10751. });
  10752. }
  10753. }
  10754. function normalizeContainer(container) {
  10755. if (isString(container)) {
  10756. const res = document.querySelector(container);
  10757. if (!res) {
  10758. warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
  10759. }
  10760. return res;
  10761. }
  10762. if (window.ShadowRoot &&
  10763. container instanceof window.ShadowRoot &&
  10764. container.mode === 'closed') {
  10765. warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
  10766. }
  10767. return container;
  10768. }
  10769. /**
  10770. * @internal
  10771. */
  10772. const initDirectivesForSSR = NOOP;
  10773. var runtimeDom = /*#__PURE__*/Object.freeze({
  10774. __proto__: null,
  10775. render: render,
  10776. hydrate: hydrate,
  10777. createApp: createApp,
  10778. createSSRApp: createSSRApp,
  10779. initDirectivesForSSR: initDirectivesForSSR,
  10780. defineCustomElement: defineCustomElement,
  10781. defineSSRCustomElement: defineSSRCustomElement,
  10782. VueElement: VueElement,
  10783. useCssModule: useCssModule,
  10784. useCssVars: useCssVars,
  10785. Transition: Transition,
  10786. TransitionGroup: TransitionGroup,
  10787. vModelText: vModelText,
  10788. vModelCheckbox: vModelCheckbox,
  10789. vModelRadio: vModelRadio,
  10790. vModelSelect: vModelSelect,
  10791. vModelDynamic: vModelDynamic,
  10792. withModifiers: withModifiers,
  10793. withKeys: withKeys,
  10794. vShow: vShow,
  10795. reactive: reactive,
  10796. ref: ref,
  10797. readonly: readonly,
  10798. unref: unref,
  10799. proxyRefs: proxyRefs,
  10800. isRef: isRef,
  10801. toRef: toRef,
  10802. toRefs: toRefs,
  10803. isProxy: isProxy,
  10804. isReactive: isReactive,
  10805. isReadonly: isReadonly,
  10806. isShallow: isShallow,
  10807. customRef: customRef,
  10808. triggerRef: triggerRef,
  10809. shallowRef: shallowRef,
  10810. shallowReactive: shallowReactive,
  10811. shallowReadonly: shallowReadonly,
  10812. markRaw: markRaw,
  10813. toRaw: toRaw,
  10814. effect: effect,
  10815. stop: stop,
  10816. ReactiveEffect: ReactiveEffect,
  10817. effectScope: effectScope,
  10818. EffectScope: EffectScope,
  10819. getCurrentScope: getCurrentScope,
  10820. onScopeDispose: onScopeDispose,
  10821. computed: computed$1,
  10822. watch: watch,
  10823. watchEffect: watchEffect,
  10824. watchPostEffect: watchPostEffect,
  10825. watchSyncEffect: watchSyncEffect,
  10826. onBeforeMount: onBeforeMount,
  10827. onMounted: onMounted,
  10828. onBeforeUpdate: onBeforeUpdate,
  10829. onUpdated: onUpdated,
  10830. onBeforeUnmount: onBeforeUnmount,
  10831. onUnmounted: onUnmounted,
  10832. onActivated: onActivated,
  10833. onDeactivated: onDeactivated,
  10834. onRenderTracked: onRenderTracked,
  10835. onRenderTriggered: onRenderTriggered,
  10836. onErrorCaptured: onErrorCaptured,
  10837. onServerPrefetch: onServerPrefetch,
  10838. provide: provide,
  10839. inject: inject,
  10840. nextTick: nextTick,
  10841. defineComponent: defineComponent,
  10842. defineAsyncComponent: defineAsyncComponent,
  10843. useAttrs: useAttrs,
  10844. useSlots: useSlots,
  10845. defineProps: defineProps,
  10846. defineEmits: defineEmits,
  10847. defineExpose: defineExpose,
  10848. withDefaults: withDefaults,
  10849. mergeDefaults: mergeDefaults,
  10850. createPropsRestProxy: createPropsRestProxy,
  10851. withAsyncContext: withAsyncContext,
  10852. getCurrentInstance: getCurrentInstance,
  10853. h: h,
  10854. createVNode: createVNode,
  10855. cloneVNode: cloneVNode,
  10856. mergeProps: mergeProps,
  10857. isVNode: isVNode,
  10858. Fragment: Fragment,
  10859. Text: Text,
  10860. Comment: Comment,
  10861. Static: Static,
  10862. Teleport: Teleport,
  10863. Suspense: Suspense,
  10864. KeepAlive: KeepAlive,
  10865. BaseTransition: BaseTransition,
  10866. withDirectives: withDirectives,
  10867. useSSRContext: useSSRContext,
  10868. ssrContextKey: ssrContextKey,
  10869. createRenderer: createRenderer,
  10870. createHydrationRenderer: createHydrationRenderer,
  10871. queuePostFlushCb: queuePostFlushCb,
  10872. warn: warn$1,
  10873. handleError: handleError,
  10874. callWithErrorHandling: callWithErrorHandling,
  10875. callWithAsyncErrorHandling: callWithAsyncErrorHandling,
  10876. resolveComponent: resolveComponent,
  10877. resolveDirective: resolveDirective,
  10878. resolveDynamicComponent: resolveDynamicComponent,
  10879. registerRuntimeCompiler: registerRuntimeCompiler,
  10880. isRuntimeOnly: isRuntimeOnly,
  10881. useTransitionState: useTransitionState,
  10882. resolveTransitionHooks: resolveTransitionHooks,
  10883. setTransitionHooks: setTransitionHooks,
  10884. getTransitionRawChildren: getTransitionRawChildren,
  10885. initCustomFormatter: initCustomFormatter,
  10886. get devtools () { return devtools; },
  10887. setDevtoolsHook: setDevtoolsHook,
  10888. withCtx: withCtx,
  10889. pushScopeId: pushScopeId,
  10890. popScopeId: popScopeId,
  10891. withScopeId: withScopeId,
  10892. renderList: renderList,
  10893. toHandlers: toHandlers,
  10894. renderSlot: renderSlot,
  10895. createSlots: createSlots,
  10896. withMemo: withMemo,
  10897. isMemoSame: isMemoSame,
  10898. openBlock: openBlock,
  10899. createBlock: createBlock,
  10900. setBlockTracking: setBlockTracking,
  10901. createTextVNode: createTextVNode,
  10902. createCommentVNode: createCommentVNode,
  10903. createStaticVNode: createStaticVNode,
  10904. createElementVNode: createBaseVNode,
  10905. createElementBlock: createElementBlock,
  10906. guardReactiveProps: guardReactiveProps,
  10907. toDisplayString: toDisplayString,
  10908. camelize: camelize,
  10909. capitalize: capitalize,
  10910. toHandlerKey: toHandlerKey,
  10911. normalizeProps: normalizeProps,
  10912. normalizeClass: normalizeClass,
  10913. normalizeStyle: normalizeStyle,
  10914. transformVNodeArgs: transformVNodeArgs,
  10915. version: version,
  10916. ssrUtils: ssrUtils,
  10917. resolveFilter: resolveFilter,
  10918. compatUtils: compatUtils
  10919. });
  10920. function initDev() {
  10921. {
  10922. {
  10923. console.info(`You are running a development build of Vue.\n` +
  10924. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  10925. }
  10926. initCustomFormatter();
  10927. }
  10928. }
  10929. function defaultOnError(error) {
  10930. throw error;
  10931. }
  10932. function defaultOnWarn(msg) {
  10933. console.warn(`[Vue warn] ${msg.message}`);
  10934. }
  10935. function createCompilerError(code, loc, messages, additionalMessage) {
  10936. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  10937. ;
  10938. const error = new SyntaxError(String(msg));
  10939. error.code = code;
  10940. error.loc = loc;
  10941. return error;
  10942. }
  10943. const errorMessages = {
  10944. // parse errors
  10945. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  10946. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  10947. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  10948. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  10949. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  10950. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  10951. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  10952. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  10953. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  10954. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  10955. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  10956. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  10957. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  10958. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  10959. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  10960. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  10961. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  10962. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  10963. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  10964. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  10965. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  10966. [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  10967. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  10968. // Vue-specific parse errors
  10969. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  10970. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  10971. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  10972. [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  10973. 'Note that dynamic directive argument cannot contain spaces.',
  10974. [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  10975. // transform errors
  10976. [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  10977. [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  10978. [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  10979. [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  10980. [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  10981. [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  10982. [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  10983. [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  10984. [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  10985. [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  10986. `When there are multiple named slots, all slots should use <template> ` +
  10987. `syntax to avoid scope ambiguity.`,
  10988. [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  10989. [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  10990. `default slot. These children will be ignored.`,
  10991. [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  10992. [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  10993. [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  10994. [43 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  10995. [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  10996. [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  10997. // generic errors
  10998. [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  10999. [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  11000. [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  11001. [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  11002. // just to fulfill types
  11003. [50 /* __EXTEND_POINT__ */]: ``
  11004. };
  11005. const FRAGMENT = Symbol(`Fragment` );
  11006. const TELEPORT = Symbol(`Teleport` );
  11007. const SUSPENSE = Symbol(`Suspense` );
  11008. const KEEP_ALIVE = Symbol(`KeepAlive` );
  11009. const BASE_TRANSITION = Symbol(`BaseTransition` );
  11010. const OPEN_BLOCK = Symbol(`openBlock` );
  11011. const CREATE_BLOCK = Symbol(`createBlock` );
  11012. const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
  11013. const CREATE_VNODE = Symbol(`createVNode` );
  11014. const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
  11015. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  11016. const CREATE_TEXT = Symbol(`createTextVNode` );
  11017. const CREATE_STATIC = Symbol(`createStaticVNode` );
  11018. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  11019. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  11020. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  11021. const RESOLVE_FILTER = Symbol(`resolveFilter` );
  11022. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  11023. const RENDER_LIST = Symbol(`renderList` );
  11024. const RENDER_SLOT = Symbol(`renderSlot` );
  11025. const CREATE_SLOTS = Symbol(`createSlots` );
  11026. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  11027. const MERGE_PROPS = Symbol(`mergeProps` );
  11028. const NORMALIZE_CLASS = Symbol(`normalizeClass` );
  11029. const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
  11030. const NORMALIZE_PROPS = Symbol(`normalizeProps` );
  11031. const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
  11032. const TO_HANDLERS = Symbol(`toHandlers` );
  11033. const CAMELIZE = Symbol(`camelize` );
  11034. const CAPITALIZE = Symbol(`capitalize` );
  11035. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  11036. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  11037. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  11038. const POP_SCOPE_ID = Symbol(`popScopeId` );
  11039. const WITH_CTX = Symbol(`withCtx` );
  11040. const UNREF = Symbol(`unref` );
  11041. const IS_REF = Symbol(`isRef` );
  11042. const WITH_MEMO = Symbol(`withMemo` );
  11043. const IS_MEMO_SAME = Symbol(`isMemoSame` );
  11044. // Name mapping for runtime helpers that need to be imported from 'vue' in
  11045. // generated code. Make sure these are correctly exported in the runtime!
  11046. // Using `any` here because TS doesn't allow symbols as index type.
  11047. const helperNameMap = {
  11048. [FRAGMENT]: `Fragment`,
  11049. [TELEPORT]: `Teleport`,
  11050. [SUSPENSE]: `Suspense`,
  11051. [KEEP_ALIVE]: `KeepAlive`,
  11052. [BASE_TRANSITION]: `BaseTransition`,
  11053. [OPEN_BLOCK]: `openBlock`,
  11054. [CREATE_BLOCK]: `createBlock`,
  11055. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  11056. [CREATE_VNODE]: `createVNode`,
  11057. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  11058. [CREATE_COMMENT]: `createCommentVNode`,
  11059. [CREATE_TEXT]: `createTextVNode`,
  11060. [CREATE_STATIC]: `createStaticVNode`,
  11061. [RESOLVE_COMPONENT]: `resolveComponent`,
  11062. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  11063. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  11064. [RESOLVE_FILTER]: `resolveFilter`,
  11065. [WITH_DIRECTIVES]: `withDirectives`,
  11066. [RENDER_LIST]: `renderList`,
  11067. [RENDER_SLOT]: `renderSlot`,
  11068. [CREATE_SLOTS]: `createSlots`,
  11069. [TO_DISPLAY_STRING]: `toDisplayString`,
  11070. [MERGE_PROPS]: `mergeProps`,
  11071. [NORMALIZE_CLASS]: `normalizeClass`,
  11072. [NORMALIZE_STYLE]: `normalizeStyle`,
  11073. [NORMALIZE_PROPS]: `normalizeProps`,
  11074. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  11075. [TO_HANDLERS]: `toHandlers`,
  11076. [CAMELIZE]: `camelize`,
  11077. [CAPITALIZE]: `capitalize`,
  11078. [TO_HANDLER_KEY]: `toHandlerKey`,
  11079. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  11080. [PUSH_SCOPE_ID]: `pushScopeId`,
  11081. [POP_SCOPE_ID]: `popScopeId`,
  11082. [WITH_CTX]: `withCtx`,
  11083. [UNREF]: `unref`,
  11084. [IS_REF]: `isRef`,
  11085. [WITH_MEMO]: `withMemo`,
  11086. [IS_MEMO_SAME]: `isMemoSame`
  11087. };
  11088. function registerRuntimeHelpers(helpers) {
  11089. Object.getOwnPropertySymbols(helpers).forEach(s => {
  11090. helperNameMap[s] = helpers[s];
  11091. });
  11092. }
  11093. // AST Utilities ---------------------------------------------------------------
  11094. // Some expressions, e.g. sequence and conditional expressions, are never
  11095. // associated with template nodes, so their source locations are just a stub.
  11096. // Container types like CompoundExpression also don't need a real location.
  11097. const locStub = {
  11098. source: '',
  11099. start: { line: 1, column: 1, offset: 0 },
  11100. end: { line: 1, column: 1, offset: 0 }
  11101. };
  11102. function createRoot(children, loc = locStub) {
  11103. return {
  11104. type: 0 /* ROOT */,
  11105. children,
  11106. helpers: [],
  11107. components: [],
  11108. directives: [],
  11109. hoists: [],
  11110. imports: [],
  11111. cached: 0,
  11112. temps: 0,
  11113. codegenNode: undefined,
  11114. loc
  11115. };
  11116. }
  11117. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  11118. if (context) {
  11119. if (isBlock) {
  11120. context.helper(OPEN_BLOCK);
  11121. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  11122. }
  11123. else {
  11124. context.helper(getVNodeHelper(context.inSSR, isComponent));
  11125. }
  11126. if (directives) {
  11127. context.helper(WITH_DIRECTIVES);
  11128. }
  11129. }
  11130. return {
  11131. type: 13 /* VNODE_CALL */,
  11132. tag,
  11133. props,
  11134. children,
  11135. patchFlag,
  11136. dynamicProps,
  11137. directives,
  11138. isBlock,
  11139. disableTracking,
  11140. isComponent,
  11141. loc
  11142. };
  11143. }
  11144. function createArrayExpression(elements, loc = locStub) {
  11145. return {
  11146. type: 17 /* JS_ARRAY_EXPRESSION */,
  11147. loc,
  11148. elements
  11149. };
  11150. }
  11151. function createObjectExpression(properties, loc = locStub) {
  11152. return {
  11153. type: 15 /* JS_OBJECT_EXPRESSION */,
  11154. loc,
  11155. properties
  11156. };
  11157. }
  11158. function createObjectProperty(key, value) {
  11159. return {
  11160. type: 16 /* JS_PROPERTY */,
  11161. loc: locStub,
  11162. key: isString(key) ? createSimpleExpression(key, true) : key,
  11163. value
  11164. };
  11165. }
  11166. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
  11167. return {
  11168. type: 4 /* SIMPLE_EXPRESSION */,
  11169. loc,
  11170. content,
  11171. isStatic,
  11172. constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
  11173. };
  11174. }
  11175. function createCompoundExpression(children, loc = locStub) {
  11176. return {
  11177. type: 8 /* COMPOUND_EXPRESSION */,
  11178. loc,
  11179. children
  11180. };
  11181. }
  11182. function createCallExpression(callee, args = [], loc = locStub) {
  11183. return {
  11184. type: 14 /* JS_CALL_EXPRESSION */,
  11185. loc,
  11186. callee,
  11187. arguments: args
  11188. };
  11189. }
  11190. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  11191. return {
  11192. type: 18 /* JS_FUNCTION_EXPRESSION */,
  11193. params,
  11194. returns,
  11195. newline,
  11196. isSlot,
  11197. loc
  11198. };
  11199. }
  11200. function createConditionalExpression(test, consequent, alternate, newline = true) {
  11201. return {
  11202. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  11203. test,
  11204. consequent,
  11205. alternate,
  11206. newline,
  11207. loc: locStub
  11208. };
  11209. }
  11210. function createCacheExpression(index, value, isVNode = false) {
  11211. return {
  11212. type: 20 /* JS_CACHE_EXPRESSION */,
  11213. index,
  11214. value,
  11215. isVNode,
  11216. loc: locStub
  11217. };
  11218. }
  11219. function createBlockStatement(body) {
  11220. return {
  11221. type: 21 /* JS_BLOCK_STATEMENT */,
  11222. body,
  11223. loc: locStub
  11224. };
  11225. }
  11226. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  11227. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  11228. function isCoreComponent(tag) {
  11229. if (isBuiltInType(tag, 'Teleport')) {
  11230. return TELEPORT;
  11231. }
  11232. else if (isBuiltInType(tag, 'Suspense')) {
  11233. return SUSPENSE;
  11234. }
  11235. else if (isBuiltInType(tag, 'KeepAlive')) {
  11236. return KEEP_ALIVE;
  11237. }
  11238. else if (isBuiltInType(tag, 'BaseTransition')) {
  11239. return BASE_TRANSITION;
  11240. }
  11241. }
  11242. const nonIdentifierRE = /^\d|[^\$\w]/;
  11243. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  11244. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  11245. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  11246. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  11247. /**
  11248. * Simple lexer to check if an expression is a member expression. This is
  11249. * lax and only checks validity at the root level (i.e. does not validate exps
  11250. * inside square brackets), but it's ok since these are only used on template
  11251. * expressions and false positives are invalid expressions in the first place.
  11252. */
  11253. const isMemberExpressionBrowser = (path) => {
  11254. // remove whitespaces around . or [ first
  11255. path = path.trim().replace(whitespaceRE, s => s.trim());
  11256. let state = 0 /* inMemberExp */;
  11257. let stateStack = [];
  11258. let currentOpenBracketCount = 0;
  11259. let currentOpenParensCount = 0;
  11260. let currentStringType = null;
  11261. for (let i = 0; i < path.length; i++) {
  11262. const char = path.charAt(i);
  11263. switch (state) {
  11264. case 0 /* inMemberExp */:
  11265. if (char === '[') {
  11266. stateStack.push(state);
  11267. state = 1 /* inBrackets */;
  11268. currentOpenBracketCount++;
  11269. }
  11270. else if (char === '(') {
  11271. stateStack.push(state);
  11272. state = 2 /* inParens */;
  11273. currentOpenParensCount++;
  11274. }
  11275. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  11276. return false;
  11277. }
  11278. break;
  11279. case 1 /* inBrackets */:
  11280. if (char === `'` || char === `"` || char === '`') {
  11281. stateStack.push(state);
  11282. state = 3 /* inString */;
  11283. currentStringType = char;
  11284. }
  11285. else if (char === `[`) {
  11286. currentOpenBracketCount++;
  11287. }
  11288. else if (char === `]`) {
  11289. if (!--currentOpenBracketCount) {
  11290. state = stateStack.pop();
  11291. }
  11292. }
  11293. break;
  11294. case 2 /* inParens */:
  11295. if (char === `'` || char === `"` || char === '`') {
  11296. stateStack.push(state);
  11297. state = 3 /* inString */;
  11298. currentStringType = char;
  11299. }
  11300. else if (char === `(`) {
  11301. currentOpenParensCount++;
  11302. }
  11303. else if (char === `)`) {
  11304. // if the exp ends as a call then it should not be considered valid
  11305. if (i === path.length - 1) {
  11306. return false;
  11307. }
  11308. if (!--currentOpenParensCount) {
  11309. state = stateStack.pop();
  11310. }
  11311. }
  11312. break;
  11313. case 3 /* inString */:
  11314. if (char === currentStringType) {
  11315. state = stateStack.pop();
  11316. currentStringType = null;
  11317. }
  11318. break;
  11319. }
  11320. }
  11321. return !currentOpenBracketCount && !currentOpenParensCount;
  11322. };
  11323. const isMemberExpression = isMemberExpressionBrowser
  11324. ;
  11325. function getInnerRange(loc, offset, length) {
  11326. const source = loc.source.slice(offset, offset + length);
  11327. const newLoc = {
  11328. source,
  11329. start: advancePositionWithClone(loc.start, loc.source, offset),
  11330. end: loc.end
  11331. };
  11332. if (length != null) {
  11333. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  11334. }
  11335. return newLoc;
  11336. }
  11337. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  11338. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  11339. }
  11340. // advance by mutation without cloning (for performance reasons), since this
  11341. // gets called a lot in the parser
  11342. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  11343. let linesCount = 0;
  11344. let lastNewLinePos = -1;
  11345. for (let i = 0; i < numberOfCharacters; i++) {
  11346. if (source.charCodeAt(i) === 10 /* newline char code */) {
  11347. linesCount++;
  11348. lastNewLinePos = i;
  11349. }
  11350. }
  11351. pos.offset += numberOfCharacters;
  11352. pos.line += linesCount;
  11353. pos.column =
  11354. lastNewLinePos === -1
  11355. ? pos.column + numberOfCharacters
  11356. : numberOfCharacters - lastNewLinePos;
  11357. return pos;
  11358. }
  11359. function assert(condition, msg) {
  11360. /* istanbul ignore if */
  11361. if (!condition) {
  11362. throw new Error(msg || `unexpected compiler condition`);
  11363. }
  11364. }
  11365. function findDir(node, name, allowEmpty = false) {
  11366. for (let i = 0; i < node.props.length; i++) {
  11367. const p = node.props[i];
  11368. if (p.type === 7 /* DIRECTIVE */ &&
  11369. (allowEmpty || p.exp) &&
  11370. (isString(name) ? p.name === name : name.test(p.name))) {
  11371. return p;
  11372. }
  11373. }
  11374. }
  11375. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  11376. for (let i = 0; i < node.props.length; i++) {
  11377. const p = node.props[i];
  11378. if (p.type === 6 /* ATTRIBUTE */) {
  11379. if (dynamicOnly)
  11380. continue;
  11381. if (p.name === name && (p.value || allowEmpty)) {
  11382. return p;
  11383. }
  11384. }
  11385. else if (p.name === 'bind' &&
  11386. (p.exp || allowEmpty) &&
  11387. isStaticArgOf(p.arg, name)) {
  11388. return p;
  11389. }
  11390. }
  11391. }
  11392. function isStaticArgOf(arg, name) {
  11393. return !!(arg && isStaticExp(arg) && arg.content === name);
  11394. }
  11395. function hasDynamicKeyVBind(node) {
  11396. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  11397. p.name === 'bind' &&
  11398. (!p.arg || // v-bind="obj"
  11399. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  11400. !p.arg.isStatic) // v-bind:[foo]
  11401. );
  11402. }
  11403. function isText(node) {
  11404. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  11405. }
  11406. function isVSlot(p) {
  11407. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  11408. }
  11409. function isTemplateNode(node) {
  11410. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  11411. }
  11412. function isSlotOutlet(node) {
  11413. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  11414. }
  11415. function getVNodeHelper(ssr, isComponent) {
  11416. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  11417. }
  11418. function getVNodeBlockHelper(ssr, isComponent) {
  11419. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  11420. }
  11421. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  11422. function getUnnormalizedProps(props, callPath = []) {
  11423. if (props &&
  11424. !isString(props) &&
  11425. props.type === 14 /* JS_CALL_EXPRESSION */) {
  11426. const callee = props.callee;
  11427. if (!isString(callee) && propsHelperSet.has(callee)) {
  11428. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  11429. }
  11430. }
  11431. return [props, callPath];
  11432. }
  11433. function injectProp(node, prop, context) {
  11434. let propsWithInjection;
  11435. /**
  11436. * 1. mergeProps(...)
  11437. * 2. toHandlers(...)
  11438. * 3. normalizeProps(...)
  11439. * 4. normalizeProps(guardReactiveProps(...))
  11440. *
  11441. * we need to get the real props before normalization
  11442. */
  11443. let props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  11444. let callPath = [];
  11445. let parentCall;
  11446. if (props &&
  11447. !isString(props) &&
  11448. props.type === 14 /* JS_CALL_EXPRESSION */) {
  11449. const ret = getUnnormalizedProps(props);
  11450. props = ret[0];
  11451. callPath = ret[1];
  11452. parentCall = callPath[callPath.length - 1];
  11453. }
  11454. if (props == null || isString(props)) {
  11455. propsWithInjection = createObjectExpression([prop]);
  11456. }
  11457. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  11458. // merged props... add ours
  11459. // only inject key to object literal if it's the first argument so that
  11460. // if doesn't override user provided keys
  11461. const first = props.arguments[0];
  11462. if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  11463. first.properties.unshift(prop);
  11464. }
  11465. else {
  11466. if (props.callee === TO_HANDLERS) {
  11467. // #2366
  11468. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  11469. createObjectExpression([prop]),
  11470. props
  11471. ]);
  11472. }
  11473. else {
  11474. props.arguments.unshift(createObjectExpression([prop]));
  11475. }
  11476. }
  11477. !propsWithInjection && (propsWithInjection = props);
  11478. }
  11479. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  11480. let alreadyExists = false;
  11481. // check existing key to avoid overriding user provided keys
  11482. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  11483. const propKeyName = prop.key.content;
  11484. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  11485. p.key.content === propKeyName);
  11486. }
  11487. if (!alreadyExists) {
  11488. props.properties.unshift(prop);
  11489. }
  11490. propsWithInjection = props;
  11491. }
  11492. else {
  11493. // single v-bind with expression, return a merged replacement
  11494. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  11495. createObjectExpression([prop]),
  11496. props
  11497. ]);
  11498. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  11499. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  11500. // the `guardReactiveProps` will no longer be needed
  11501. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  11502. parentCall = callPath[callPath.length - 2];
  11503. }
  11504. }
  11505. if (node.type === 13 /* VNODE_CALL */) {
  11506. if (parentCall) {
  11507. parentCall.arguments[0] = propsWithInjection;
  11508. }
  11509. else {
  11510. node.props = propsWithInjection;
  11511. }
  11512. }
  11513. else {
  11514. if (parentCall) {
  11515. parentCall.arguments[0] = propsWithInjection;
  11516. }
  11517. else {
  11518. node.arguments[2] = propsWithInjection;
  11519. }
  11520. }
  11521. }
  11522. function toValidAssetId(name, type) {
  11523. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  11524. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  11525. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  11526. })}`;
  11527. }
  11528. function getMemoedVNodeCall(node) {
  11529. if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  11530. return node.arguments[1].returns;
  11531. }
  11532. else {
  11533. return node;
  11534. }
  11535. }
  11536. function makeBlock(node, { helper, removeHelper, inSSR }) {
  11537. if (!node.isBlock) {
  11538. node.isBlock = true;
  11539. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  11540. helper(OPEN_BLOCK);
  11541. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  11542. }
  11543. }
  11544. const deprecationData = {
  11545. ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
  11546. message: `Platform-native elements with "is" prop will no longer be ` +
  11547. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  11548. `prefixed with "vue:".`,
  11549. link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  11550. },
  11551. ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
  11552. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  11553. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  11554. `\`v-model:${key}\`.`,
  11555. link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  11556. },
  11557. ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
  11558. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  11559. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  11560. },
  11561. ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
  11562. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  11563. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  11564. `that appears before v-bind in the case of conflict. ` +
  11565. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  11566. `You can also suppress this warning if the usage is intended.`,
  11567. link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  11568. },
  11569. ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
  11570. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  11571. link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  11572. },
  11573. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  11574. message: `v-if / v-for precedence when used on the same element has changed ` +
  11575. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  11576. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  11577. `with <template> tags or use a computed property that filters v-for ` +
  11578. `data source.`,
  11579. link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  11580. },
  11581. ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
  11582. message: `<template> with no special directives will render as a native template ` +
  11583. `element instead of its inner content in Vue 3.`
  11584. },
  11585. ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
  11586. message: `"inline-template" has been removed in Vue 3.`,
  11587. link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  11588. },
  11589. ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
  11590. message: `filters have been removed in Vue 3. ` +
  11591. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  11592. `Use method calls or computed properties instead.`,
  11593. link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  11594. }
  11595. };
  11596. function getCompatValue(key, context) {
  11597. const config = context.options
  11598. ? context.options.compatConfig
  11599. : context.compatConfig;
  11600. const value = config && config[key];
  11601. if (key === 'MODE') {
  11602. return value || 3; // compiler defaults to v3 behavior
  11603. }
  11604. else {
  11605. return value;
  11606. }
  11607. }
  11608. function isCompatEnabled(key, context) {
  11609. const mode = getCompatValue('MODE', context);
  11610. const value = getCompatValue(key, context);
  11611. // in v3 mode, only enable if explicitly set to true
  11612. // otherwise enable for any non-false value
  11613. return mode === 3 ? value === true : value !== false;
  11614. }
  11615. function checkCompatEnabled(key, context, loc, ...args) {
  11616. const enabled = isCompatEnabled(key, context);
  11617. if (enabled) {
  11618. warnDeprecation(key, context, loc, ...args);
  11619. }
  11620. return enabled;
  11621. }
  11622. function warnDeprecation(key, context, loc, ...args) {
  11623. const val = getCompatValue(key, context);
  11624. if (val === 'suppress-warning') {
  11625. return;
  11626. }
  11627. const { message, link } = deprecationData[key];
  11628. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  11629. const err = new SyntaxError(msg);
  11630. err.code = key;
  11631. if (loc)
  11632. err.loc = loc;
  11633. context.onWarn(err);
  11634. }
  11635. // The default decoder only provides escapes for characters reserved as part of
  11636. // the template syntax, and is only used if the custom renderer did not provide
  11637. // a platform-specific decoder.
  11638. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  11639. const decodeMap = {
  11640. gt: '>',
  11641. lt: '<',
  11642. amp: '&',
  11643. apos: "'",
  11644. quot: '"'
  11645. };
  11646. const defaultParserOptions = {
  11647. delimiters: [`{{`, `}}`],
  11648. getNamespace: () => 0 /* HTML */,
  11649. getTextMode: () => 0 /* DATA */,
  11650. isVoidTag: NO,
  11651. isPreTag: NO,
  11652. isCustomElement: NO,
  11653. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  11654. onError: defaultOnError,
  11655. onWarn: defaultOnWarn,
  11656. comments: true
  11657. };
  11658. function baseParse(content, options = {}) {
  11659. const context = createParserContext(content, options);
  11660. const start = getCursor(context);
  11661. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  11662. }
  11663. function createParserContext(content, rawOptions) {
  11664. const options = extend({}, defaultParserOptions);
  11665. let key;
  11666. for (key in rawOptions) {
  11667. // @ts-ignore
  11668. options[key] =
  11669. rawOptions[key] === undefined
  11670. ? defaultParserOptions[key]
  11671. : rawOptions[key];
  11672. }
  11673. return {
  11674. options,
  11675. column: 1,
  11676. line: 1,
  11677. offset: 0,
  11678. originalSource: content,
  11679. source: content,
  11680. inPre: false,
  11681. inVPre: false,
  11682. onWarn: options.onWarn
  11683. };
  11684. }
  11685. function parseChildren(context, mode, ancestors) {
  11686. const parent = last(ancestors);
  11687. const ns = parent ? parent.ns : 0 /* HTML */;
  11688. const nodes = [];
  11689. while (!isEnd(context, mode, ancestors)) {
  11690. const s = context.source;
  11691. let node = undefined;
  11692. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  11693. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  11694. // '{{'
  11695. node = parseInterpolation(context, mode);
  11696. }
  11697. else if (mode === 0 /* DATA */ && s[0] === '<') {
  11698. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  11699. if (s.length === 1) {
  11700. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  11701. }
  11702. else if (s[1] === '!') {
  11703. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  11704. if (startsWith(s, '<!--')) {
  11705. node = parseComment(context);
  11706. }
  11707. else if (startsWith(s, '<!DOCTYPE')) {
  11708. // Ignore DOCTYPE by a limitation.
  11709. node = parseBogusComment(context);
  11710. }
  11711. else if (startsWith(s, '<![CDATA[')) {
  11712. if (ns !== 0 /* HTML */) {
  11713. node = parseCDATA(context, ancestors);
  11714. }
  11715. else {
  11716. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  11717. node = parseBogusComment(context);
  11718. }
  11719. }
  11720. else {
  11721. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  11722. node = parseBogusComment(context);
  11723. }
  11724. }
  11725. else if (s[1] === '/') {
  11726. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  11727. if (s.length === 2) {
  11728. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  11729. }
  11730. else if (s[2] === '>') {
  11731. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  11732. advanceBy(context, 3);
  11733. continue;
  11734. }
  11735. else if (/[a-z]/i.test(s[2])) {
  11736. emitError(context, 23 /* X_INVALID_END_TAG */);
  11737. parseTag(context, 1 /* End */, parent);
  11738. continue;
  11739. }
  11740. else {
  11741. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  11742. node = parseBogusComment(context);
  11743. }
  11744. }
  11745. else if (/[a-z]/i.test(s[1])) {
  11746. node = parseElement(context, ancestors);
  11747. }
  11748. else if (s[1] === '?') {
  11749. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  11750. node = parseBogusComment(context);
  11751. }
  11752. else {
  11753. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  11754. }
  11755. }
  11756. }
  11757. if (!node) {
  11758. node = parseText(context, mode);
  11759. }
  11760. if (isArray(node)) {
  11761. for (let i = 0; i < node.length; i++) {
  11762. pushNode(nodes, node[i]);
  11763. }
  11764. }
  11765. else {
  11766. pushNode(nodes, node);
  11767. }
  11768. }
  11769. // Whitespace handling strategy like v2
  11770. let removedWhitespace = false;
  11771. if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
  11772. const shouldCondense = context.options.whitespace !== 'preserve';
  11773. for (let i = 0; i < nodes.length; i++) {
  11774. const node = nodes[i];
  11775. if (!context.inPre && node.type === 2 /* TEXT */) {
  11776. if (!/[^\t\r\n\f ]/.test(node.content)) {
  11777. const prev = nodes[i - 1];
  11778. const next = nodes[i + 1];
  11779. // Remove if:
  11780. // - the whitespace is the first or last node, or:
  11781. // - (condense mode) the whitespace is adjacent to a comment, or:
  11782. // - (condense mode) the whitespace is between two elements AND contains newline
  11783. if (!prev ||
  11784. !next ||
  11785. (shouldCondense &&
  11786. (prev.type === 3 /* COMMENT */ ||
  11787. next.type === 3 /* COMMENT */ ||
  11788. (prev.type === 1 /* ELEMENT */ &&
  11789. next.type === 1 /* ELEMENT */ &&
  11790. /[\r\n]/.test(node.content))))) {
  11791. removedWhitespace = true;
  11792. nodes[i] = null;
  11793. }
  11794. else {
  11795. // Otherwise, the whitespace is condensed into a single space
  11796. node.content = ' ';
  11797. }
  11798. }
  11799. else if (shouldCondense) {
  11800. // in condense mode, consecutive whitespaces in text are condensed
  11801. // down to a single space.
  11802. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  11803. }
  11804. }
  11805. // Remove comment nodes if desired by configuration.
  11806. else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
  11807. removedWhitespace = true;
  11808. nodes[i] = null;
  11809. }
  11810. }
  11811. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  11812. // remove leading newline per html spec
  11813. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  11814. const first = nodes[0];
  11815. if (first && first.type === 2 /* TEXT */) {
  11816. first.content = first.content.replace(/^\r?\n/, '');
  11817. }
  11818. }
  11819. }
  11820. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  11821. }
  11822. function pushNode(nodes, node) {
  11823. if (node.type === 2 /* TEXT */) {
  11824. const prev = last(nodes);
  11825. // Merge if both this and the previous node are text and those are
  11826. // consecutive. This happens for cases like "a < b".
  11827. if (prev &&
  11828. prev.type === 2 /* TEXT */ &&
  11829. prev.loc.end.offset === node.loc.start.offset) {
  11830. prev.content += node.content;
  11831. prev.loc.end = node.loc.end;
  11832. prev.loc.source += node.loc.source;
  11833. return;
  11834. }
  11835. }
  11836. nodes.push(node);
  11837. }
  11838. function parseCDATA(context, ancestors) {
  11839. advanceBy(context, 9);
  11840. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  11841. if (context.source.length === 0) {
  11842. emitError(context, 6 /* EOF_IN_CDATA */);
  11843. }
  11844. else {
  11845. advanceBy(context, 3);
  11846. }
  11847. return nodes;
  11848. }
  11849. function parseComment(context) {
  11850. const start = getCursor(context);
  11851. let content;
  11852. // Regular comment.
  11853. const match = /--(\!)?>/.exec(context.source);
  11854. if (!match) {
  11855. content = context.source.slice(4);
  11856. advanceBy(context, context.source.length);
  11857. emitError(context, 7 /* EOF_IN_COMMENT */);
  11858. }
  11859. else {
  11860. if (match.index <= 3) {
  11861. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  11862. }
  11863. if (match[1]) {
  11864. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  11865. }
  11866. content = context.source.slice(4, match.index);
  11867. // Advancing with reporting nested comments.
  11868. const s = context.source.slice(0, match.index);
  11869. let prevIndex = 1, nestedIndex = 0;
  11870. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  11871. advanceBy(context, nestedIndex - prevIndex + 1);
  11872. if (nestedIndex + 4 < s.length) {
  11873. emitError(context, 16 /* NESTED_COMMENT */);
  11874. }
  11875. prevIndex = nestedIndex + 1;
  11876. }
  11877. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  11878. }
  11879. return {
  11880. type: 3 /* COMMENT */,
  11881. content,
  11882. loc: getSelection(context, start)
  11883. };
  11884. }
  11885. function parseBogusComment(context) {
  11886. const start = getCursor(context);
  11887. const contentStart = context.source[1] === '?' ? 1 : 2;
  11888. let content;
  11889. const closeIndex = context.source.indexOf('>');
  11890. if (closeIndex === -1) {
  11891. content = context.source.slice(contentStart);
  11892. advanceBy(context, context.source.length);
  11893. }
  11894. else {
  11895. content = context.source.slice(contentStart, closeIndex);
  11896. advanceBy(context, closeIndex + 1);
  11897. }
  11898. return {
  11899. type: 3 /* COMMENT */,
  11900. content,
  11901. loc: getSelection(context, start)
  11902. };
  11903. }
  11904. function parseElement(context, ancestors) {
  11905. // Start tag.
  11906. const wasInPre = context.inPre;
  11907. const wasInVPre = context.inVPre;
  11908. const parent = last(ancestors);
  11909. const element = parseTag(context, 0 /* Start */, parent);
  11910. const isPreBoundary = context.inPre && !wasInPre;
  11911. const isVPreBoundary = context.inVPre && !wasInVPre;
  11912. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  11913. // #4030 self-closing <pre> tag
  11914. if (isPreBoundary) {
  11915. context.inPre = false;
  11916. }
  11917. if (isVPreBoundary) {
  11918. context.inVPre = false;
  11919. }
  11920. return element;
  11921. }
  11922. // Children.
  11923. ancestors.push(element);
  11924. const mode = context.options.getTextMode(element, parent);
  11925. const children = parseChildren(context, mode, ancestors);
  11926. ancestors.pop();
  11927. element.children = children;
  11928. // End tag.
  11929. if (startsWithEndTagOpen(context.source, element.tag)) {
  11930. parseTag(context, 1 /* End */, parent);
  11931. }
  11932. else {
  11933. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  11934. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  11935. const first = children[0];
  11936. if (first && startsWith(first.loc.source, '<!--')) {
  11937. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  11938. }
  11939. }
  11940. }
  11941. element.loc = getSelection(context, element.loc.start);
  11942. if (isPreBoundary) {
  11943. context.inPre = false;
  11944. }
  11945. if (isVPreBoundary) {
  11946. context.inVPre = false;
  11947. }
  11948. return element;
  11949. }
  11950. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  11951. function parseTag(context, type, parent) {
  11952. // Tag open.
  11953. const start = getCursor(context);
  11954. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  11955. const tag = match[1];
  11956. const ns = context.options.getNamespace(tag, parent);
  11957. advanceBy(context, match[0].length);
  11958. advanceSpaces(context);
  11959. // save current state in case we need to re-parse attributes with v-pre
  11960. const cursor = getCursor(context);
  11961. const currentSource = context.source;
  11962. // check <pre> tag
  11963. if (context.options.isPreTag(tag)) {
  11964. context.inPre = true;
  11965. }
  11966. // Attributes.
  11967. let props = parseAttributes(context, type);
  11968. // check v-pre
  11969. if (type === 0 /* Start */ &&
  11970. !context.inVPre &&
  11971. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  11972. context.inVPre = true;
  11973. // reset context
  11974. extend(context, cursor);
  11975. context.source = currentSource;
  11976. // re-parse attrs and filter out v-pre itself
  11977. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  11978. }
  11979. // Tag close.
  11980. let isSelfClosing = false;
  11981. if (context.source.length === 0) {
  11982. emitError(context, 9 /* EOF_IN_TAG */);
  11983. }
  11984. else {
  11985. isSelfClosing = startsWith(context.source, '/>');
  11986. if (type === 1 /* End */ && isSelfClosing) {
  11987. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  11988. }
  11989. advanceBy(context, isSelfClosing ? 2 : 1);
  11990. }
  11991. if (type === 1 /* End */) {
  11992. return;
  11993. }
  11994. let tagType = 0 /* ELEMENT */;
  11995. if (!context.inVPre) {
  11996. if (tag === 'slot') {
  11997. tagType = 2 /* SLOT */;
  11998. }
  11999. else if (tag === 'template') {
  12000. if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  12001. tagType = 3 /* TEMPLATE */;
  12002. }
  12003. }
  12004. else if (isComponent(tag, props, context)) {
  12005. tagType = 1 /* COMPONENT */;
  12006. }
  12007. }
  12008. return {
  12009. type: 1 /* ELEMENT */,
  12010. ns,
  12011. tag,
  12012. tagType,
  12013. props,
  12014. isSelfClosing,
  12015. children: [],
  12016. loc: getSelection(context, start),
  12017. codegenNode: undefined // to be created during transform phase
  12018. };
  12019. }
  12020. function isComponent(tag, props, context) {
  12021. const options = context.options;
  12022. if (options.isCustomElement(tag)) {
  12023. return false;
  12024. }
  12025. if (tag === 'component' ||
  12026. /^[A-Z]/.test(tag) ||
  12027. isCoreComponent(tag) ||
  12028. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  12029. (options.isNativeTag && !options.isNativeTag(tag))) {
  12030. return true;
  12031. }
  12032. // at this point the tag should be a native tag, but check for potential "is"
  12033. // casting
  12034. for (let i = 0; i < props.length; i++) {
  12035. const p = props[i];
  12036. if (p.type === 6 /* ATTRIBUTE */) {
  12037. if (p.name === 'is' && p.value) {
  12038. if (p.value.content.startsWith('vue:')) {
  12039. return true;
  12040. }
  12041. }
  12042. }
  12043. else {
  12044. // directive
  12045. // v-is (TODO Deprecate)
  12046. if (p.name === 'is') {
  12047. return true;
  12048. }
  12049. else if (
  12050. // :is on plain element - only treat as component in compat mode
  12051. p.name === 'bind' &&
  12052. isStaticArgOf(p.arg, 'is') &&
  12053. false &&
  12054. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  12055. return true;
  12056. }
  12057. }
  12058. }
  12059. }
  12060. function parseAttributes(context, type) {
  12061. const props = [];
  12062. const attributeNames = new Set();
  12063. while (context.source.length > 0 &&
  12064. !startsWith(context.source, '>') &&
  12065. !startsWith(context.source, '/>')) {
  12066. if (startsWith(context.source, '/')) {
  12067. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  12068. advanceBy(context, 1);
  12069. advanceSpaces(context);
  12070. continue;
  12071. }
  12072. if (type === 1 /* End */) {
  12073. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  12074. }
  12075. const attr = parseAttribute(context, attributeNames);
  12076. // Trim whitespace between class
  12077. // https://github.com/vuejs/core/issues/4251
  12078. if (attr.type === 6 /* ATTRIBUTE */ &&
  12079. attr.value &&
  12080. attr.name === 'class') {
  12081. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  12082. }
  12083. if (type === 0 /* Start */) {
  12084. props.push(attr);
  12085. }
  12086. if (/^[^\t\r\n\f />]/.test(context.source)) {
  12087. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  12088. }
  12089. advanceSpaces(context);
  12090. }
  12091. return props;
  12092. }
  12093. function parseAttribute(context, nameSet) {
  12094. // Name.
  12095. const start = getCursor(context);
  12096. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  12097. const name = match[0];
  12098. if (nameSet.has(name)) {
  12099. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  12100. }
  12101. nameSet.add(name);
  12102. if (name[0] === '=') {
  12103. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  12104. }
  12105. {
  12106. const pattern = /["'<]/g;
  12107. let m;
  12108. while ((m = pattern.exec(name))) {
  12109. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  12110. }
  12111. }
  12112. advanceBy(context, name.length);
  12113. // Value
  12114. let value = undefined;
  12115. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  12116. advanceSpaces(context);
  12117. advanceBy(context, 1);
  12118. advanceSpaces(context);
  12119. value = parseAttributeValue(context);
  12120. if (!value) {
  12121. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  12122. }
  12123. }
  12124. const loc = getSelection(context, start);
  12125. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  12126. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  12127. let isPropShorthand = startsWith(name, '.');
  12128. let dirName = match[1] ||
  12129. (isPropShorthand || startsWith(name, ':')
  12130. ? 'bind'
  12131. : startsWith(name, '@')
  12132. ? 'on'
  12133. : 'slot');
  12134. let arg;
  12135. if (match[2]) {
  12136. const isSlot = dirName === 'slot';
  12137. const startOffset = name.lastIndexOf(match[2]);
  12138. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  12139. let content = match[2];
  12140. let isStatic = true;
  12141. if (content.startsWith('[')) {
  12142. isStatic = false;
  12143. if (!content.endsWith(']')) {
  12144. emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  12145. content = content.slice(1);
  12146. }
  12147. else {
  12148. content = content.slice(1, content.length - 1);
  12149. }
  12150. }
  12151. else if (isSlot) {
  12152. // #1241 special case for v-slot: vuetify relies extensively on slot
  12153. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  12154. // supports such usage so we are keeping it consistent with 2.x.
  12155. content += match[3] || '';
  12156. }
  12157. arg = {
  12158. type: 4 /* SIMPLE_EXPRESSION */,
  12159. content,
  12160. isStatic,
  12161. constType: isStatic
  12162. ? 3 /* CAN_STRINGIFY */
  12163. : 0 /* NOT_CONSTANT */,
  12164. loc
  12165. };
  12166. }
  12167. if (value && value.isQuoted) {
  12168. const valueLoc = value.loc;
  12169. valueLoc.start.offset++;
  12170. valueLoc.start.column++;
  12171. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  12172. valueLoc.source = valueLoc.source.slice(1, -1);
  12173. }
  12174. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  12175. if (isPropShorthand)
  12176. modifiers.push('prop');
  12177. return {
  12178. type: 7 /* DIRECTIVE */,
  12179. name: dirName,
  12180. exp: value && {
  12181. type: 4 /* SIMPLE_EXPRESSION */,
  12182. content: value.content,
  12183. isStatic: false,
  12184. // Treat as non-constant by default. This can be potentially set to
  12185. // other values by `transformExpression` to make it eligible for hoisting.
  12186. constType: 0 /* NOT_CONSTANT */,
  12187. loc: value.loc
  12188. },
  12189. arg,
  12190. modifiers,
  12191. loc
  12192. };
  12193. }
  12194. // missing directive name or illegal directive name
  12195. if (!context.inVPre && startsWith(name, 'v-')) {
  12196. emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
  12197. }
  12198. return {
  12199. type: 6 /* ATTRIBUTE */,
  12200. name,
  12201. value: value && {
  12202. type: 2 /* TEXT */,
  12203. content: value.content,
  12204. loc: value.loc
  12205. },
  12206. loc
  12207. };
  12208. }
  12209. function parseAttributeValue(context) {
  12210. const start = getCursor(context);
  12211. let content;
  12212. const quote = context.source[0];
  12213. const isQuoted = quote === `"` || quote === `'`;
  12214. if (isQuoted) {
  12215. // Quoted value.
  12216. advanceBy(context, 1);
  12217. const endIndex = context.source.indexOf(quote);
  12218. if (endIndex === -1) {
  12219. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  12220. }
  12221. else {
  12222. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  12223. advanceBy(context, 1);
  12224. }
  12225. }
  12226. else {
  12227. // Unquoted
  12228. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  12229. if (!match) {
  12230. return undefined;
  12231. }
  12232. const unexpectedChars = /["'<=`]/g;
  12233. let m;
  12234. while ((m = unexpectedChars.exec(match[0]))) {
  12235. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  12236. }
  12237. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  12238. }
  12239. return { content, isQuoted, loc: getSelection(context, start) };
  12240. }
  12241. function parseInterpolation(context, mode) {
  12242. const [open, close] = context.options.delimiters;
  12243. const closeIndex = context.source.indexOf(close, open.length);
  12244. if (closeIndex === -1) {
  12245. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  12246. return undefined;
  12247. }
  12248. const start = getCursor(context);
  12249. advanceBy(context, open.length);
  12250. const innerStart = getCursor(context);
  12251. const innerEnd = getCursor(context);
  12252. const rawContentLength = closeIndex - open.length;
  12253. const rawContent = context.source.slice(0, rawContentLength);
  12254. const preTrimContent = parseTextData(context, rawContentLength, mode);
  12255. const content = preTrimContent.trim();
  12256. const startOffset = preTrimContent.indexOf(content);
  12257. if (startOffset > 0) {
  12258. advancePositionWithMutation(innerStart, rawContent, startOffset);
  12259. }
  12260. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  12261. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  12262. advanceBy(context, close.length);
  12263. return {
  12264. type: 5 /* INTERPOLATION */,
  12265. content: {
  12266. type: 4 /* SIMPLE_EXPRESSION */,
  12267. isStatic: false,
  12268. // Set `isConstant` to false by default and will decide in transformExpression
  12269. constType: 0 /* NOT_CONSTANT */,
  12270. content,
  12271. loc: getSelection(context, innerStart, innerEnd)
  12272. },
  12273. loc: getSelection(context, start)
  12274. };
  12275. }
  12276. function parseText(context, mode) {
  12277. const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  12278. let endIndex = context.source.length;
  12279. for (let i = 0; i < endTokens.length; i++) {
  12280. const index = context.source.indexOf(endTokens[i], 1);
  12281. if (index !== -1 && endIndex > index) {
  12282. endIndex = index;
  12283. }
  12284. }
  12285. const start = getCursor(context);
  12286. const content = parseTextData(context, endIndex, mode);
  12287. return {
  12288. type: 2 /* TEXT */,
  12289. content,
  12290. loc: getSelection(context, start)
  12291. };
  12292. }
  12293. /**
  12294. * Get text data with a given length from the current location.
  12295. * This translates HTML entities in the text data.
  12296. */
  12297. function parseTextData(context, length, mode) {
  12298. const rawText = context.source.slice(0, length);
  12299. advanceBy(context, length);
  12300. if (mode === 2 /* RAWTEXT */ ||
  12301. mode === 3 /* CDATA */ ||
  12302. !rawText.includes('&')) {
  12303. return rawText;
  12304. }
  12305. else {
  12306. // DATA or RCDATA containing "&"". Entity decoding required.
  12307. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  12308. }
  12309. }
  12310. function getCursor(context) {
  12311. const { column, line, offset } = context;
  12312. return { column, line, offset };
  12313. }
  12314. function getSelection(context, start, end) {
  12315. end = end || getCursor(context);
  12316. return {
  12317. start,
  12318. end,
  12319. source: context.originalSource.slice(start.offset, end.offset)
  12320. };
  12321. }
  12322. function last(xs) {
  12323. return xs[xs.length - 1];
  12324. }
  12325. function startsWith(source, searchString) {
  12326. return source.startsWith(searchString);
  12327. }
  12328. function advanceBy(context, numberOfCharacters) {
  12329. const { source } = context;
  12330. advancePositionWithMutation(context, source, numberOfCharacters);
  12331. context.source = source.slice(numberOfCharacters);
  12332. }
  12333. function advanceSpaces(context) {
  12334. const match = /^[\t\r\n\f ]+/.exec(context.source);
  12335. if (match) {
  12336. advanceBy(context, match[0].length);
  12337. }
  12338. }
  12339. function getNewPosition(context, start, numberOfCharacters) {
  12340. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  12341. }
  12342. function emitError(context, code, offset, loc = getCursor(context)) {
  12343. if (offset) {
  12344. loc.offset += offset;
  12345. loc.column += offset;
  12346. }
  12347. context.options.onError(createCompilerError(code, {
  12348. start: loc,
  12349. end: loc,
  12350. source: ''
  12351. }));
  12352. }
  12353. function isEnd(context, mode, ancestors) {
  12354. const s = context.source;
  12355. switch (mode) {
  12356. case 0 /* DATA */:
  12357. if (startsWith(s, '</')) {
  12358. // TODO: probably bad performance
  12359. for (let i = ancestors.length - 1; i >= 0; --i) {
  12360. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  12361. return true;
  12362. }
  12363. }
  12364. }
  12365. break;
  12366. case 1 /* RCDATA */:
  12367. case 2 /* RAWTEXT */: {
  12368. const parent = last(ancestors);
  12369. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  12370. return true;
  12371. }
  12372. break;
  12373. }
  12374. case 3 /* CDATA */:
  12375. if (startsWith(s, ']]>')) {
  12376. return true;
  12377. }
  12378. break;
  12379. }
  12380. return !s;
  12381. }
  12382. function startsWithEndTagOpen(source, tag) {
  12383. return (startsWith(source, '</') &&
  12384. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  12385. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  12386. }
  12387. function hoistStatic(root, context) {
  12388. walk(root, context,
  12389. // Root node is unfortunately non-hoistable due to potential parent
  12390. // fallthrough attributes.
  12391. isSingleElementRoot(root, root.children[0]));
  12392. }
  12393. function isSingleElementRoot(root, child) {
  12394. const { children } = root;
  12395. return (children.length === 1 &&
  12396. child.type === 1 /* ELEMENT */ &&
  12397. !isSlotOutlet(child));
  12398. }
  12399. function walk(node, context, doNotHoistNode = false) {
  12400. const { children } = node;
  12401. const originalCount = children.length;
  12402. let hoistedCount = 0;
  12403. for (let i = 0; i < children.length; i++) {
  12404. const child = children[i];
  12405. // only plain elements & text calls are eligible for hoisting.
  12406. if (child.type === 1 /* ELEMENT */ &&
  12407. child.tagType === 0 /* ELEMENT */) {
  12408. const constantType = doNotHoistNode
  12409. ? 0 /* NOT_CONSTANT */
  12410. : getConstantType(child, context);
  12411. if (constantType > 0 /* NOT_CONSTANT */) {
  12412. if (constantType >= 2 /* CAN_HOIST */) {
  12413. child.codegenNode.patchFlag =
  12414. -1 /* HOISTED */ + (` /* HOISTED */` );
  12415. child.codegenNode = context.hoist(child.codegenNode);
  12416. hoistedCount++;
  12417. continue;
  12418. }
  12419. }
  12420. else {
  12421. // node may contain dynamic children, but its props may be eligible for
  12422. // hoisting.
  12423. const codegenNode = child.codegenNode;
  12424. if (codegenNode.type === 13 /* VNODE_CALL */) {
  12425. const flag = getPatchFlag(codegenNode);
  12426. if ((!flag ||
  12427. flag === 512 /* NEED_PATCH */ ||
  12428. flag === 1 /* TEXT */) &&
  12429. getGeneratedPropsConstantType(child, context) >=
  12430. 2 /* CAN_HOIST */) {
  12431. const props = getNodeProps(child);
  12432. if (props) {
  12433. codegenNode.props = context.hoist(props);
  12434. }
  12435. }
  12436. if (codegenNode.dynamicProps) {
  12437. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  12438. }
  12439. }
  12440. }
  12441. }
  12442. else if (child.type === 12 /* TEXT_CALL */ &&
  12443. getConstantType(child.content, context) >= 2 /* CAN_HOIST */) {
  12444. child.codegenNode = context.hoist(child.codegenNode);
  12445. hoistedCount++;
  12446. }
  12447. // walk further
  12448. if (child.type === 1 /* ELEMENT */) {
  12449. const isComponent = child.tagType === 1 /* COMPONENT */;
  12450. if (isComponent) {
  12451. context.scopes.vSlot++;
  12452. }
  12453. walk(child, context);
  12454. if (isComponent) {
  12455. context.scopes.vSlot--;
  12456. }
  12457. }
  12458. else if (child.type === 11 /* FOR */) {
  12459. // Do not hoist v-for single child because it has to be a block
  12460. walk(child, context, child.children.length === 1);
  12461. }
  12462. else if (child.type === 9 /* IF */) {
  12463. for (let i = 0; i < child.branches.length; i++) {
  12464. // Do not hoist v-if single child because it has to be a block
  12465. walk(child.branches[i], context, child.branches[i].children.length === 1);
  12466. }
  12467. }
  12468. }
  12469. if (hoistedCount && context.transformHoist) {
  12470. context.transformHoist(children, context, node);
  12471. }
  12472. // all children were hoisted - the entire children array is hoistable.
  12473. if (hoistedCount &&
  12474. hoistedCount === originalCount &&
  12475. node.type === 1 /* ELEMENT */ &&
  12476. node.tagType === 0 /* ELEMENT */ &&
  12477. node.codegenNode &&
  12478. node.codegenNode.type === 13 /* VNODE_CALL */ &&
  12479. isArray(node.codegenNode.children)) {
  12480. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  12481. }
  12482. }
  12483. function getConstantType(node, context) {
  12484. const { constantCache } = context;
  12485. switch (node.type) {
  12486. case 1 /* ELEMENT */:
  12487. if (node.tagType !== 0 /* ELEMENT */) {
  12488. return 0 /* NOT_CONSTANT */;
  12489. }
  12490. const cached = constantCache.get(node);
  12491. if (cached !== undefined) {
  12492. return cached;
  12493. }
  12494. const codegenNode = node.codegenNode;
  12495. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  12496. return 0 /* NOT_CONSTANT */;
  12497. }
  12498. if (codegenNode.isBlock &&
  12499. node.tag !== 'svg' &&
  12500. node.tag !== 'foreignObject') {
  12501. return 0 /* NOT_CONSTANT */;
  12502. }
  12503. const flag = getPatchFlag(codegenNode);
  12504. if (!flag) {
  12505. let returnType = 3 /* CAN_STRINGIFY */;
  12506. // Element itself has no patch flag. However we still need to check:
  12507. // 1. Even for a node with no patch flag, it is possible for it to contain
  12508. // non-hoistable expressions that refers to scope variables, e.g. compiler
  12509. // injected keys or cached event handlers. Therefore we need to always
  12510. // check the codegenNode's props to be sure.
  12511. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  12512. if (generatedPropsType === 0 /* NOT_CONSTANT */) {
  12513. constantCache.set(node, 0 /* NOT_CONSTANT */);
  12514. return 0 /* NOT_CONSTANT */;
  12515. }
  12516. if (generatedPropsType < returnType) {
  12517. returnType = generatedPropsType;
  12518. }
  12519. // 2. its children.
  12520. for (let i = 0; i < node.children.length; i++) {
  12521. const childType = getConstantType(node.children[i], context);
  12522. if (childType === 0 /* NOT_CONSTANT */) {
  12523. constantCache.set(node, 0 /* NOT_CONSTANT */);
  12524. return 0 /* NOT_CONSTANT */;
  12525. }
  12526. if (childType < returnType) {
  12527. returnType = childType;
  12528. }
  12529. }
  12530. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  12531. // type, check if any of the props can cause the type to be lowered
  12532. // we can skip can_patch because it's guaranteed by the absence of a
  12533. // patchFlag.
  12534. if (returnType > 1 /* CAN_SKIP_PATCH */) {
  12535. for (let i = 0; i < node.props.length; i++) {
  12536. const p = node.props[i];
  12537. if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
  12538. const expType = getConstantType(p.exp, context);
  12539. if (expType === 0 /* NOT_CONSTANT */) {
  12540. constantCache.set(node, 0 /* NOT_CONSTANT */);
  12541. return 0 /* NOT_CONSTANT */;
  12542. }
  12543. if (expType < returnType) {
  12544. returnType = expType;
  12545. }
  12546. }
  12547. }
  12548. }
  12549. // only svg/foreignObject could be block here, however if they are
  12550. // static then they don't need to be blocks since there will be no
  12551. // nested updates.
  12552. if (codegenNode.isBlock) {
  12553. context.removeHelper(OPEN_BLOCK);
  12554. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  12555. codegenNode.isBlock = false;
  12556. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  12557. }
  12558. constantCache.set(node, returnType);
  12559. return returnType;
  12560. }
  12561. else {
  12562. constantCache.set(node, 0 /* NOT_CONSTANT */);
  12563. return 0 /* NOT_CONSTANT */;
  12564. }
  12565. case 2 /* TEXT */:
  12566. case 3 /* COMMENT */:
  12567. return 3 /* CAN_STRINGIFY */;
  12568. case 9 /* IF */:
  12569. case 11 /* FOR */:
  12570. case 10 /* IF_BRANCH */:
  12571. return 0 /* NOT_CONSTANT */;
  12572. case 5 /* INTERPOLATION */:
  12573. case 12 /* TEXT_CALL */:
  12574. return getConstantType(node.content, context);
  12575. case 4 /* SIMPLE_EXPRESSION */:
  12576. return node.constType;
  12577. case 8 /* COMPOUND_EXPRESSION */:
  12578. let returnType = 3 /* CAN_STRINGIFY */;
  12579. for (let i = 0; i < node.children.length; i++) {
  12580. const child = node.children[i];
  12581. if (isString(child) || isSymbol(child)) {
  12582. continue;
  12583. }
  12584. const childType = getConstantType(child, context);
  12585. if (childType === 0 /* NOT_CONSTANT */) {
  12586. return 0 /* NOT_CONSTANT */;
  12587. }
  12588. else if (childType < returnType) {
  12589. returnType = childType;
  12590. }
  12591. }
  12592. return returnType;
  12593. default:
  12594. return 0 /* NOT_CONSTANT */;
  12595. }
  12596. }
  12597. const allowHoistedHelperSet = new Set([
  12598. NORMALIZE_CLASS,
  12599. NORMALIZE_STYLE,
  12600. NORMALIZE_PROPS,
  12601. GUARD_REACTIVE_PROPS
  12602. ]);
  12603. function getConstantTypeOfHelperCall(value, context) {
  12604. if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
  12605. !isString(value.callee) &&
  12606. allowHoistedHelperSet.has(value.callee)) {
  12607. const arg = value.arguments[0];
  12608. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  12609. return getConstantType(arg, context);
  12610. }
  12611. else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
  12612. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  12613. return getConstantTypeOfHelperCall(arg, context);
  12614. }
  12615. }
  12616. return 0 /* NOT_CONSTANT */;
  12617. }
  12618. function getGeneratedPropsConstantType(node, context) {
  12619. let returnType = 3 /* CAN_STRINGIFY */;
  12620. const props = getNodeProps(node);
  12621. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  12622. const { properties } = props;
  12623. for (let i = 0; i < properties.length; i++) {
  12624. const { key, value } = properties[i];
  12625. const keyType = getConstantType(key, context);
  12626. if (keyType === 0 /* NOT_CONSTANT */) {
  12627. return keyType;
  12628. }
  12629. if (keyType < returnType) {
  12630. returnType = keyType;
  12631. }
  12632. let valueType;
  12633. if (value.type === 4 /* SIMPLE_EXPRESSION */) {
  12634. valueType = getConstantType(value, context);
  12635. }
  12636. else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
  12637. // some helper calls can be hoisted,
  12638. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  12639. // in this case we need to respect the ConstantType of the helper's arguments
  12640. valueType = getConstantTypeOfHelperCall(value, context);
  12641. }
  12642. else {
  12643. valueType = 0 /* NOT_CONSTANT */;
  12644. }
  12645. if (valueType === 0 /* NOT_CONSTANT */) {
  12646. return valueType;
  12647. }
  12648. if (valueType < returnType) {
  12649. returnType = valueType;
  12650. }
  12651. }
  12652. }
  12653. return returnType;
  12654. }
  12655. function getNodeProps(node) {
  12656. const codegenNode = node.codegenNode;
  12657. if (codegenNode.type === 13 /* VNODE_CALL */) {
  12658. return codegenNode.props;
  12659. }
  12660. }
  12661. function getPatchFlag(node) {
  12662. const flag = node.patchFlag;
  12663. return flag ? parseInt(flag, 10) : undefined;
  12664. }
  12665. function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, slotted = true, ssr = false, inSSR = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError, onWarn = defaultOnWarn, compatConfig }) {
  12666. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  12667. const context = {
  12668. // options
  12669. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  12670. prefixIdentifiers,
  12671. hoistStatic,
  12672. cacheHandlers,
  12673. nodeTransforms,
  12674. directiveTransforms,
  12675. transformHoist,
  12676. isBuiltInComponent,
  12677. isCustomElement,
  12678. expressionPlugins,
  12679. scopeId,
  12680. slotted,
  12681. ssr,
  12682. inSSR,
  12683. ssrCssVars,
  12684. bindingMetadata,
  12685. inline,
  12686. isTS,
  12687. onError,
  12688. onWarn,
  12689. compatConfig,
  12690. // state
  12691. root,
  12692. helpers: new Map(),
  12693. components: new Set(),
  12694. directives: new Set(),
  12695. hoists: [],
  12696. imports: [],
  12697. constantCache: new Map(),
  12698. temps: 0,
  12699. cached: 0,
  12700. identifiers: Object.create(null),
  12701. scopes: {
  12702. vFor: 0,
  12703. vSlot: 0,
  12704. vPre: 0,
  12705. vOnce: 0
  12706. },
  12707. parent: null,
  12708. currentNode: root,
  12709. childIndex: 0,
  12710. inVOnce: false,
  12711. // methods
  12712. helper(name) {
  12713. const count = context.helpers.get(name) || 0;
  12714. context.helpers.set(name, count + 1);
  12715. return name;
  12716. },
  12717. removeHelper(name) {
  12718. const count = context.helpers.get(name);
  12719. if (count) {
  12720. const currentCount = count - 1;
  12721. if (!currentCount) {
  12722. context.helpers.delete(name);
  12723. }
  12724. else {
  12725. context.helpers.set(name, currentCount);
  12726. }
  12727. }
  12728. },
  12729. helperString(name) {
  12730. return `_${helperNameMap[context.helper(name)]}`;
  12731. },
  12732. replaceNode(node) {
  12733. /* istanbul ignore if */
  12734. {
  12735. if (!context.currentNode) {
  12736. throw new Error(`Node being replaced is already removed.`);
  12737. }
  12738. if (!context.parent) {
  12739. throw new Error(`Cannot replace root node.`);
  12740. }
  12741. }
  12742. context.parent.children[context.childIndex] = context.currentNode = node;
  12743. },
  12744. removeNode(node) {
  12745. if (!context.parent) {
  12746. throw new Error(`Cannot remove root node.`);
  12747. }
  12748. const list = context.parent.children;
  12749. const removalIndex = node
  12750. ? list.indexOf(node)
  12751. : context.currentNode
  12752. ? context.childIndex
  12753. : -1;
  12754. /* istanbul ignore if */
  12755. if (removalIndex < 0) {
  12756. throw new Error(`node being removed is not a child of current parent`);
  12757. }
  12758. if (!node || node === context.currentNode) {
  12759. // current node removed
  12760. context.currentNode = null;
  12761. context.onNodeRemoved();
  12762. }
  12763. else {
  12764. // sibling node removed
  12765. if (context.childIndex > removalIndex) {
  12766. context.childIndex--;
  12767. context.onNodeRemoved();
  12768. }
  12769. }
  12770. context.parent.children.splice(removalIndex, 1);
  12771. },
  12772. onNodeRemoved: () => { },
  12773. addIdentifiers(exp) {
  12774. },
  12775. removeIdentifiers(exp) {
  12776. },
  12777. hoist(exp) {
  12778. if (isString(exp))
  12779. exp = createSimpleExpression(exp);
  12780. context.hoists.push(exp);
  12781. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
  12782. identifier.hoisted = exp;
  12783. return identifier;
  12784. },
  12785. cache(exp, isVNode = false) {
  12786. return createCacheExpression(context.cached++, exp, isVNode);
  12787. }
  12788. };
  12789. return context;
  12790. }
  12791. function transform(root, options) {
  12792. const context = createTransformContext(root, options);
  12793. traverseNode(root, context);
  12794. if (options.hoistStatic) {
  12795. hoistStatic(root, context);
  12796. }
  12797. if (!options.ssr) {
  12798. createRootCodegen(root, context);
  12799. }
  12800. // finalize meta information
  12801. root.helpers = [...context.helpers.keys()];
  12802. root.components = [...context.components];
  12803. root.directives = [...context.directives];
  12804. root.imports = context.imports;
  12805. root.hoists = context.hoists;
  12806. root.temps = context.temps;
  12807. root.cached = context.cached;
  12808. }
  12809. function createRootCodegen(root, context) {
  12810. const { helper } = context;
  12811. const { children } = root;
  12812. if (children.length === 1) {
  12813. const child = children[0];
  12814. // if the single child is an element, turn it into a block.
  12815. if (isSingleElementRoot(root, child) && child.codegenNode) {
  12816. // single element root is never hoisted so codegenNode will never be
  12817. // SimpleExpressionNode
  12818. const codegenNode = child.codegenNode;
  12819. if (codegenNode.type === 13 /* VNODE_CALL */) {
  12820. makeBlock(codegenNode, context);
  12821. }
  12822. root.codegenNode = codegenNode;
  12823. }
  12824. else {
  12825. // - single <slot/>, IfNode, ForNode: already blocks.
  12826. // - single text node: always patched.
  12827. // root codegen falls through via genNode()
  12828. root.codegenNode = child;
  12829. }
  12830. }
  12831. else if (children.length > 1) {
  12832. // root has multiple nodes - return a fragment block.
  12833. let patchFlag = 64 /* STABLE_FRAGMENT */;
  12834. let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
  12835. // check if the fragment actually contains a single valid child with
  12836. // the rest being comments
  12837. if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
  12838. patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
  12839. patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
  12840. }
  12841. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
  12842. }
  12843. else ;
  12844. }
  12845. function traverseChildren(parent, context) {
  12846. let i = 0;
  12847. const nodeRemoved = () => {
  12848. i--;
  12849. };
  12850. for (; i < parent.children.length; i++) {
  12851. const child = parent.children[i];
  12852. if (isString(child))
  12853. continue;
  12854. context.parent = parent;
  12855. context.childIndex = i;
  12856. context.onNodeRemoved = nodeRemoved;
  12857. traverseNode(child, context);
  12858. }
  12859. }
  12860. function traverseNode(node, context) {
  12861. context.currentNode = node;
  12862. // apply transform plugins
  12863. const { nodeTransforms } = context;
  12864. const exitFns = [];
  12865. for (let i = 0; i < nodeTransforms.length; i++) {
  12866. const onExit = nodeTransforms[i](node, context);
  12867. if (onExit) {
  12868. if (isArray(onExit)) {
  12869. exitFns.push(...onExit);
  12870. }
  12871. else {
  12872. exitFns.push(onExit);
  12873. }
  12874. }
  12875. if (!context.currentNode) {
  12876. // node was removed
  12877. return;
  12878. }
  12879. else {
  12880. // node may have been replaced
  12881. node = context.currentNode;
  12882. }
  12883. }
  12884. switch (node.type) {
  12885. case 3 /* COMMENT */:
  12886. if (!context.ssr) {
  12887. // inject import for the Comment symbol, which is needed for creating
  12888. // comment nodes with `createVNode`
  12889. context.helper(CREATE_COMMENT);
  12890. }
  12891. break;
  12892. case 5 /* INTERPOLATION */:
  12893. // no need to traverse, but we need to inject toString helper
  12894. if (!context.ssr) {
  12895. context.helper(TO_DISPLAY_STRING);
  12896. }
  12897. break;
  12898. // for container types, further traverse downwards
  12899. case 9 /* IF */:
  12900. for (let i = 0; i < node.branches.length; i++) {
  12901. traverseNode(node.branches[i], context);
  12902. }
  12903. break;
  12904. case 10 /* IF_BRANCH */:
  12905. case 11 /* FOR */:
  12906. case 1 /* ELEMENT */:
  12907. case 0 /* ROOT */:
  12908. traverseChildren(node, context);
  12909. break;
  12910. }
  12911. // exit transforms
  12912. context.currentNode = node;
  12913. let i = exitFns.length;
  12914. while (i--) {
  12915. exitFns[i]();
  12916. }
  12917. }
  12918. function createStructuralDirectiveTransform(name, fn) {
  12919. const matches = isString(name)
  12920. ? (n) => n === name
  12921. : (n) => name.test(n);
  12922. return (node, context) => {
  12923. if (node.type === 1 /* ELEMENT */) {
  12924. const { props } = node;
  12925. // structural directive transforms are not concerned with slots
  12926. // as they are handled separately in vSlot.ts
  12927. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  12928. return;
  12929. }
  12930. const exitFns = [];
  12931. for (let i = 0; i < props.length; i++) {
  12932. const prop = props[i];
  12933. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  12934. // structural directives are removed to avoid infinite recursion
  12935. // also we remove them *before* applying so that it can further
  12936. // traverse itself in case it moves the node around
  12937. props.splice(i, 1);
  12938. i--;
  12939. const onExit = fn(node, prop, context);
  12940. if (onExit)
  12941. exitFns.push(onExit);
  12942. }
  12943. }
  12944. return exitFns;
  12945. }
  12946. };
  12947. }
  12948. const PURE_ANNOTATION = `/*#__PURE__*/`;
  12949. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssrRuntimeModuleName = 'vue/server-renderer', ssr = false, isTS = false, inSSR = false }) {
  12950. const context = {
  12951. mode,
  12952. prefixIdentifiers,
  12953. sourceMap,
  12954. filename,
  12955. scopeId,
  12956. optimizeImports,
  12957. runtimeGlobalName,
  12958. runtimeModuleName,
  12959. ssrRuntimeModuleName,
  12960. ssr,
  12961. isTS,
  12962. inSSR,
  12963. source: ast.loc.source,
  12964. code: ``,
  12965. column: 1,
  12966. line: 1,
  12967. offset: 0,
  12968. indentLevel: 0,
  12969. pure: false,
  12970. map: undefined,
  12971. helper(key) {
  12972. return `_${helperNameMap[key]}`;
  12973. },
  12974. push(code, node) {
  12975. context.code += code;
  12976. },
  12977. indent() {
  12978. newline(++context.indentLevel);
  12979. },
  12980. deindent(withoutNewLine = false) {
  12981. if (withoutNewLine) {
  12982. --context.indentLevel;
  12983. }
  12984. else {
  12985. newline(--context.indentLevel);
  12986. }
  12987. },
  12988. newline() {
  12989. newline(context.indentLevel);
  12990. }
  12991. };
  12992. function newline(n) {
  12993. context.push('\n' + ` `.repeat(n));
  12994. }
  12995. return context;
  12996. }
  12997. function generate(ast, options = {}) {
  12998. const context = createCodegenContext(ast, options);
  12999. if (options.onContextCreated)
  13000. options.onContextCreated(context);
  13001. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  13002. const hasHelpers = ast.helpers.length > 0;
  13003. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  13004. // preambles
  13005. // in setup() inline mode, the preamble is generated in a sub context
  13006. // and returned separately.
  13007. const preambleContext = context;
  13008. {
  13009. genFunctionPreamble(ast, preambleContext);
  13010. }
  13011. // enter render function
  13012. const functionName = ssr ? `ssrRender` : `render`;
  13013. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  13014. const signature = args.join(', ');
  13015. {
  13016. push(`function ${functionName}(${signature}) {`);
  13017. }
  13018. indent();
  13019. if (useWithBlock) {
  13020. push(`with (_ctx) {`);
  13021. indent();
  13022. // function mode const declarations should be inside with block
  13023. // also they should be renamed to avoid collision with user properties
  13024. if (hasHelpers) {
  13025. push(`const { ${ast.helpers
  13026. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  13027. .join(', ')} } = _Vue`);
  13028. push(`\n`);
  13029. newline();
  13030. }
  13031. }
  13032. // generate asset resolution statements
  13033. if (ast.components.length) {
  13034. genAssets(ast.components, 'component', context);
  13035. if (ast.directives.length || ast.temps > 0) {
  13036. newline();
  13037. }
  13038. }
  13039. if (ast.directives.length) {
  13040. genAssets(ast.directives, 'directive', context);
  13041. if (ast.temps > 0) {
  13042. newline();
  13043. }
  13044. }
  13045. if (ast.temps > 0) {
  13046. push(`let `);
  13047. for (let i = 0; i < ast.temps; i++) {
  13048. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  13049. }
  13050. }
  13051. if (ast.components.length || ast.directives.length || ast.temps) {
  13052. push(`\n`);
  13053. newline();
  13054. }
  13055. // generate the VNode tree expression
  13056. if (!ssr) {
  13057. push(`return `);
  13058. }
  13059. if (ast.codegenNode) {
  13060. genNode(ast.codegenNode, context);
  13061. }
  13062. else {
  13063. push(`null`);
  13064. }
  13065. if (useWithBlock) {
  13066. deindent();
  13067. push(`}`);
  13068. }
  13069. deindent();
  13070. push(`}`);
  13071. return {
  13072. ast,
  13073. code: context.code,
  13074. preamble: ``,
  13075. // SourceMapGenerator does have toJSON() method but it's not in the types
  13076. map: context.map ? context.map.toJSON() : undefined
  13077. };
  13078. }
  13079. function genFunctionPreamble(ast, context) {
  13080. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  13081. const VueBinding = runtimeGlobalName;
  13082. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  13083. // Generate const declaration for helpers
  13084. // In prefix mode, we place the const declaration at top so it's done
  13085. // only once; But if we not prefixing, we place the declaration inside the
  13086. // with block so it doesn't incur the `in` check cost for every helper access.
  13087. if (ast.helpers.length > 0) {
  13088. {
  13089. // "with" mode.
  13090. // save Vue in a separate variable to avoid collision
  13091. push(`const _Vue = ${VueBinding}\n`);
  13092. // in "with" mode, helpers are declared inside the with block to avoid
  13093. // has check cost, but hoists are lifted out of the function - we need
  13094. // to provide the helper here.
  13095. if (ast.hoists.length) {
  13096. const staticHelpers = [
  13097. CREATE_VNODE,
  13098. CREATE_ELEMENT_VNODE,
  13099. CREATE_COMMENT,
  13100. CREATE_TEXT,
  13101. CREATE_STATIC
  13102. ]
  13103. .filter(helper => ast.helpers.includes(helper))
  13104. .map(aliasHelper)
  13105. .join(', ');
  13106. push(`const { ${staticHelpers} } = _Vue\n`);
  13107. }
  13108. }
  13109. }
  13110. genHoists(ast.hoists, context);
  13111. newline();
  13112. push(`return `);
  13113. }
  13114. function genAssets(assets, type, { helper, push, newline, isTS }) {
  13115. const resolver = helper(type === 'component'
  13116. ? RESOLVE_COMPONENT
  13117. : RESOLVE_DIRECTIVE);
  13118. for (let i = 0; i < assets.length; i++) {
  13119. let id = assets[i];
  13120. // potential component implicit self-reference inferred from SFC filename
  13121. const maybeSelfReference = id.endsWith('__self');
  13122. if (maybeSelfReference) {
  13123. id = id.slice(0, -6);
  13124. }
  13125. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  13126. if (i < assets.length - 1) {
  13127. newline();
  13128. }
  13129. }
  13130. }
  13131. function genHoists(hoists, context) {
  13132. if (!hoists.length) {
  13133. return;
  13134. }
  13135. context.pure = true;
  13136. const { push, newline, helper, scopeId, mode } = context;
  13137. newline();
  13138. for (let i = 0; i < hoists.length; i++) {
  13139. const exp = hoists[i];
  13140. if (exp) {
  13141. push(`const _hoisted_${i + 1} = ${``}`);
  13142. genNode(exp, context);
  13143. newline();
  13144. }
  13145. }
  13146. context.pure = false;
  13147. }
  13148. function isText$1(n) {
  13149. return (isString(n) ||
  13150. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  13151. n.type === 2 /* TEXT */ ||
  13152. n.type === 5 /* INTERPOLATION */ ||
  13153. n.type === 8 /* COMPOUND_EXPRESSION */);
  13154. }
  13155. function genNodeListAsArray(nodes, context) {
  13156. const multilines = nodes.length > 3 ||
  13157. (nodes.some(n => isArray(n) || !isText$1(n)));
  13158. context.push(`[`);
  13159. multilines && context.indent();
  13160. genNodeList(nodes, context, multilines);
  13161. multilines && context.deindent();
  13162. context.push(`]`);
  13163. }
  13164. function genNodeList(nodes, context, multilines = false, comma = true) {
  13165. const { push, newline } = context;
  13166. for (let i = 0; i < nodes.length; i++) {
  13167. const node = nodes[i];
  13168. if (isString(node)) {
  13169. push(node);
  13170. }
  13171. else if (isArray(node)) {
  13172. genNodeListAsArray(node, context);
  13173. }
  13174. else {
  13175. genNode(node, context);
  13176. }
  13177. if (i < nodes.length - 1) {
  13178. if (multilines) {
  13179. comma && push(',');
  13180. newline();
  13181. }
  13182. else {
  13183. comma && push(', ');
  13184. }
  13185. }
  13186. }
  13187. }
  13188. function genNode(node, context) {
  13189. if (isString(node)) {
  13190. context.push(node);
  13191. return;
  13192. }
  13193. if (isSymbol(node)) {
  13194. context.push(context.helper(node));
  13195. return;
  13196. }
  13197. switch (node.type) {
  13198. case 1 /* ELEMENT */:
  13199. case 9 /* IF */:
  13200. case 11 /* FOR */:
  13201. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  13202. `Apply appropriate transforms first.`);
  13203. genNode(node.codegenNode, context);
  13204. break;
  13205. case 2 /* TEXT */:
  13206. genText(node, context);
  13207. break;
  13208. case 4 /* SIMPLE_EXPRESSION */:
  13209. genExpression(node, context);
  13210. break;
  13211. case 5 /* INTERPOLATION */:
  13212. genInterpolation(node, context);
  13213. break;
  13214. case 12 /* TEXT_CALL */:
  13215. genNode(node.codegenNode, context);
  13216. break;
  13217. case 8 /* COMPOUND_EXPRESSION */:
  13218. genCompoundExpression(node, context);
  13219. break;
  13220. case 3 /* COMMENT */:
  13221. genComment(node, context);
  13222. break;
  13223. case 13 /* VNODE_CALL */:
  13224. genVNodeCall(node, context);
  13225. break;
  13226. case 14 /* JS_CALL_EXPRESSION */:
  13227. genCallExpression(node, context);
  13228. break;
  13229. case 15 /* JS_OBJECT_EXPRESSION */:
  13230. genObjectExpression(node, context);
  13231. break;
  13232. case 17 /* JS_ARRAY_EXPRESSION */:
  13233. genArrayExpression(node, context);
  13234. break;
  13235. case 18 /* JS_FUNCTION_EXPRESSION */:
  13236. genFunctionExpression(node, context);
  13237. break;
  13238. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  13239. genConditionalExpression(node, context);
  13240. break;
  13241. case 20 /* JS_CACHE_EXPRESSION */:
  13242. genCacheExpression(node, context);
  13243. break;
  13244. case 21 /* JS_BLOCK_STATEMENT */:
  13245. genNodeList(node.body, context, true, false);
  13246. break;
  13247. // SSR only types
  13248. case 22 /* JS_TEMPLATE_LITERAL */:
  13249. break;
  13250. case 23 /* JS_IF_STATEMENT */:
  13251. break;
  13252. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  13253. break;
  13254. case 25 /* JS_SEQUENCE_EXPRESSION */:
  13255. break;
  13256. case 26 /* JS_RETURN_STATEMENT */:
  13257. break;
  13258. /* istanbul ignore next */
  13259. case 10 /* IF_BRANCH */:
  13260. // noop
  13261. break;
  13262. default:
  13263. {
  13264. assert(false, `unhandled codegen node type: ${node.type}`);
  13265. // make sure we exhaust all possible types
  13266. const exhaustiveCheck = node;
  13267. return exhaustiveCheck;
  13268. }
  13269. }
  13270. }
  13271. function genText(node, context) {
  13272. context.push(JSON.stringify(node.content), node);
  13273. }
  13274. function genExpression(node, context) {
  13275. const { content, isStatic } = node;
  13276. context.push(isStatic ? JSON.stringify(content) : content, node);
  13277. }
  13278. function genInterpolation(node, context) {
  13279. const { push, helper, pure } = context;
  13280. if (pure)
  13281. push(PURE_ANNOTATION);
  13282. push(`${helper(TO_DISPLAY_STRING)}(`);
  13283. genNode(node.content, context);
  13284. push(`)`);
  13285. }
  13286. function genCompoundExpression(node, context) {
  13287. for (let i = 0; i < node.children.length; i++) {
  13288. const child = node.children[i];
  13289. if (isString(child)) {
  13290. context.push(child);
  13291. }
  13292. else {
  13293. genNode(child, context);
  13294. }
  13295. }
  13296. }
  13297. function genExpressionAsPropertyKey(node, context) {
  13298. const { push } = context;
  13299. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  13300. push(`[`);
  13301. genCompoundExpression(node, context);
  13302. push(`]`);
  13303. }
  13304. else if (node.isStatic) {
  13305. // only quote keys if necessary
  13306. const text = isSimpleIdentifier(node.content)
  13307. ? node.content
  13308. : JSON.stringify(node.content);
  13309. push(text, node);
  13310. }
  13311. else {
  13312. push(`[${node.content}]`, node);
  13313. }
  13314. }
  13315. function genComment(node, context) {
  13316. const { push, helper, pure } = context;
  13317. if (pure) {
  13318. push(PURE_ANNOTATION);
  13319. }
  13320. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  13321. }
  13322. function genVNodeCall(node, context) {
  13323. const { push, helper, pure } = context;
  13324. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  13325. if (directives) {
  13326. push(helper(WITH_DIRECTIVES) + `(`);
  13327. }
  13328. if (isBlock) {
  13329. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  13330. }
  13331. if (pure) {
  13332. push(PURE_ANNOTATION);
  13333. }
  13334. const callHelper = isBlock
  13335. ? getVNodeBlockHelper(context.inSSR, isComponent)
  13336. : getVNodeHelper(context.inSSR, isComponent);
  13337. push(helper(callHelper) + `(`, node);
  13338. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  13339. push(`)`);
  13340. if (isBlock) {
  13341. push(`)`);
  13342. }
  13343. if (directives) {
  13344. push(`, `);
  13345. genNode(directives, context);
  13346. push(`)`);
  13347. }
  13348. }
  13349. function genNullableArgs(args) {
  13350. let i = args.length;
  13351. while (i--) {
  13352. if (args[i] != null)
  13353. break;
  13354. }
  13355. return args.slice(0, i + 1).map(arg => arg || `null`);
  13356. }
  13357. // JavaScript
  13358. function genCallExpression(node, context) {
  13359. const { push, helper, pure } = context;
  13360. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  13361. if (pure) {
  13362. push(PURE_ANNOTATION);
  13363. }
  13364. push(callee + `(`, node);
  13365. genNodeList(node.arguments, context);
  13366. push(`)`);
  13367. }
  13368. function genObjectExpression(node, context) {
  13369. const { push, indent, deindent, newline } = context;
  13370. const { properties } = node;
  13371. if (!properties.length) {
  13372. push(`{}`, node);
  13373. return;
  13374. }
  13375. const multilines = properties.length > 1 ||
  13376. (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  13377. push(multilines ? `{` : `{ `);
  13378. multilines && indent();
  13379. for (let i = 0; i < properties.length; i++) {
  13380. const { key, value } = properties[i];
  13381. // key
  13382. genExpressionAsPropertyKey(key, context);
  13383. push(`: `);
  13384. // value
  13385. genNode(value, context);
  13386. if (i < properties.length - 1) {
  13387. // will only reach this if it's multilines
  13388. push(`,`);
  13389. newline();
  13390. }
  13391. }
  13392. multilines && deindent();
  13393. push(multilines ? `}` : ` }`);
  13394. }
  13395. function genArrayExpression(node, context) {
  13396. genNodeListAsArray(node.elements, context);
  13397. }
  13398. function genFunctionExpression(node, context) {
  13399. const { push, indent, deindent } = context;
  13400. const { params, returns, body, newline, isSlot } = node;
  13401. if (isSlot) {
  13402. // wrap slot functions with owner context
  13403. push(`_${helperNameMap[WITH_CTX]}(`);
  13404. }
  13405. push(`(`, node);
  13406. if (isArray(params)) {
  13407. genNodeList(params, context);
  13408. }
  13409. else if (params) {
  13410. genNode(params, context);
  13411. }
  13412. push(`) => `);
  13413. if (newline || body) {
  13414. push(`{`);
  13415. indent();
  13416. }
  13417. if (returns) {
  13418. if (newline) {
  13419. push(`return `);
  13420. }
  13421. if (isArray(returns)) {
  13422. genNodeListAsArray(returns, context);
  13423. }
  13424. else {
  13425. genNode(returns, context);
  13426. }
  13427. }
  13428. else if (body) {
  13429. genNode(body, context);
  13430. }
  13431. if (newline || body) {
  13432. deindent();
  13433. push(`}`);
  13434. }
  13435. if (isSlot) {
  13436. push(`)`);
  13437. }
  13438. }
  13439. function genConditionalExpression(node, context) {
  13440. const { test, consequent, alternate, newline: needNewline } = node;
  13441. const { push, indent, deindent, newline } = context;
  13442. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  13443. const needsParens = !isSimpleIdentifier(test.content);
  13444. needsParens && push(`(`);
  13445. genExpression(test, context);
  13446. needsParens && push(`)`);
  13447. }
  13448. else {
  13449. push(`(`);
  13450. genNode(test, context);
  13451. push(`)`);
  13452. }
  13453. needNewline && indent();
  13454. context.indentLevel++;
  13455. needNewline || push(` `);
  13456. push(`? `);
  13457. genNode(consequent, context);
  13458. context.indentLevel--;
  13459. needNewline && newline();
  13460. needNewline || push(` `);
  13461. push(`: `);
  13462. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  13463. if (!isNested) {
  13464. context.indentLevel++;
  13465. }
  13466. genNode(alternate, context);
  13467. if (!isNested) {
  13468. context.indentLevel--;
  13469. }
  13470. needNewline && deindent(true /* without newline */);
  13471. }
  13472. function genCacheExpression(node, context) {
  13473. const { push, helper, indent, deindent, newline } = context;
  13474. push(`_cache[${node.index}] || (`);
  13475. if (node.isVNode) {
  13476. indent();
  13477. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  13478. newline();
  13479. }
  13480. push(`_cache[${node.index}] = `);
  13481. genNode(node.value, context);
  13482. if (node.isVNode) {
  13483. push(`,`);
  13484. newline();
  13485. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  13486. newline();
  13487. push(`_cache[${node.index}]`);
  13488. deindent();
  13489. }
  13490. push(`)`);
  13491. }
  13492. // these keywords should not appear inside expressions, but operators like
  13493. // typeof, instanceof and in are allowed
  13494. const prohibitedKeywordRE = new RegExp('\\b' +
  13495. ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
  13496. 'super,throw,while,yield,delete,export,import,return,switch,default,' +
  13497. 'extends,finally,continue,debugger,function,arguments,typeof,void')
  13498. .split(',')
  13499. .join('\\b|\\b') +
  13500. '\\b');
  13501. // strip strings in expressions
  13502. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  13503. /**
  13504. * Validate a non-prefixed expression.
  13505. * This is only called when using the in-browser runtime compiler since it
  13506. * doesn't prefix expressions.
  13507. */
  13508. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  13509. const exp = node.content;
  13510. // empty expressions are validated per-directive since some directives
  13511. // do allow empty expressions.
  13512. if (!exp.trim()) {
  13513. return;
  13514. }
  13515. try {
  13516. new Function(asRawStatements
  13517. ? ` ${exp} `
  13518. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  13519. }
  13520. catch (e) {
  13521. let message = e.message;
  13522. const keywordMatch = exp
  13523. .replace(stripStringRE, '')
  13524. .match(prohibitedKeywordRE);
  13525. if (keywordMatch) {
  13526. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  13527. }
  13528. context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
  13529. }
  13530. }
  13531. const transformExpression = (node, context) => {
  13532. if (node.type === 5 /* INTERPOLATION */) {
  13533. node.content = processExpression(node.content, context);
  13534. }
  13535. else if (node.type === 1 /* ELEMENT */) {
  13536. // handle directives on element
  13537. for (let i = 0; i < node.props.length; i++) {
  13538. const dir = node.props[i];
  13539. // do not process for v-on & v-for since they are special handled
  13540. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  13541. const exp = dir.exp;
  13542. const arg = dir.arg;
  13543. // do not process exp if this is v-on:arg - we need special handling
  13544. // for wrapping inline statements.
  13545. if (exp &&
  13546. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  13547. !(dir.name === 'on' && arg)) {
  13548. dir.exp = processExpression(exp, context,
  13549. // slot args must be processed as function params
  13550. dir.name === 'slot');
  13551. }
  13552. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  13553. dir.arg = processExpression(arg, context);
  13554. }
  13555. }
  13556. }
  13557. }
  13558. };
  13559. // Important: since this function uses Node.js only dependencies, it should
  13560. // always be used with a leading !true check so that it can be
  13561. // tree-shaken from the browser build.
  13562. function processExpression(node, context,
  13563. // some expressions like v-slot props & v-for aliases should be parsed as
  13564. // function params
  13565. asParams = false,
  13566. // v-on handler values may contain multiple statements
  13567. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  13568. {
  13569. {
  13570. // simple in-browser validation (same logic in 2.x)
  13571. validateBrowserExpression(node, context, asParams, asRawStatements);
  13572. }
  13573. return node;
  13574. }
  13575. }
  13576. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  13577. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  13578. // #1587: We need to dynamically increment the key based on the current
  13579. // node's sibling nodes, since chained v-if/else branches are
  13580. // rendered at the same depth
  13581. const siblings = context.parent.children;
  13582. let i = siblings.indexOf(ifNode);
  13583. let key = 0;
  13584. while (i-- >= 0) {
  13585. const sibling = siblings[i];
  13586. if (sibling && sibling.type === 9 /* IF */) {
  13587. key += sibling.branches.length;
  13588. }
  13589. }
  13590. // Exit callback. Complete the codegenNode when all children have been
  13591. // transformed.
  13592. return () => {
  13593. if (isRoot) {
  13594. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  13595. }
  13596. else {
  13597. // attach this branch's codegen node to the v-if root.
  13598. const parentCondition = getParentCondition(ifNode.codegenNode);
  13599. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  13600. }
  13601. };
  13602. });
  13603. });
  13604. // target-agnostic transform used for both Client and SSR
  13605. function processIf(node, dir, context, processCodegen) {
  13606. if (dir.name !== 'else' &&
  13607. (!dir.exp || !dir.exp.content.trim())) {
  13608. const loc = dir.exp ? dir.exp.loc : node.loc;
  13609. context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  13610. dir.exp = createSimpleExpression(`true`, false, loc);
  13611. }
  13612. if (dir.exp) {
  13613. validateBrowserExpression(dir.exp, context);
  13614. }
  13615. if (dir.name === 'if') {
  13616. const branch = createIfBranch(node, dir);
  13617. const ifNode = {
  13618. type: 9 /* IF */,
  13619. loc: node.loc,
  13620. branches: [branch]
  13621. };
  13622. context.replaceNode(ifNode);
  13623. if (processCodegen) {
  13624. return processCodegen(ifNode, branch, true);
  13625. }
  13626. }
  13627. else {
  13628. // locate the adjacent v-if
  13629. const siblings = context.parent.children;
  13630. const comments = [];
  13631. let i = siblings.indexOf(node);
  13632. while (i-- >= -1) {
  13633. const sibling = siblings[i];
  13634. if (sibling && sibling.type === 3 /* COMMENT */) {
  13635. context.removeNode(sibling);
  13636. comments.unshift(sibling);
  13637. continue;
  13638. }
  13639. if (sibling &&
  13640. sibling.type === 2 /* TEXT */ &&
  13641. !sibling.content.trim().length) {
  13642. context.removeNode(sibling);
  13643. continue;
  13644. }
  13645. if (sibling && sibling.type === 9 /* IF */) {
  13646. // Check if v-else was followed by v-else-if
  13647. if (dir.name === 'else-if' &&
  13648. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  13649. context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  13650. }
  13651. // move the node to the if node's branches
  13652. context.removeNode();
  13653. const branch = createIfBranch(node, dir);
  13654. if (comments.length &&
  13655. // #3619 ignore comments if the v-if is direct child of <transition>
  13656. !(context.parent &&
  13657. context.parent.type === 1 /* ELEMENT */ &&
  13658. isBuiltInType(context.parent.tag, 'transition'))) {
  13659. branch.children = [...comments, ...branch.children];
  13660. }
  13661. // check if user is forcing same key on different branches
  13662. {
  13663. const key = branch.userKey;
  13664. if (key) {
  13665. sibling.branches.forEach(({ userKey }) => {
  13666. if (isSameKey(userKey, key)) {
  13667. context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  13668. }
  13669. });
  13670. }
  13671. }
  13672. sibling.branches.push(branch);
  13673. const onExit = processCodegen && processCodegen(sibling, branch, false);
  13674. // since the branch was removed, it will not be traversed.
  13675. // make sure to traverse here.
  13676. traverseNode(branch, context);
  13677. // call on exit
  13678. if (onExit)
  13679. onExit();
  13680. // make sure to reset currentNode after traversal to indicate this
  13681. // node has been removed.
  13682. context.currentNode = null;
  13683. }
  13684. else {
  13685. context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  13686. }
  13687. break;
  13688. }
  13689. }
  13690. }
  13691. function createIfBranch(node, dir) {
  13692. return {
  13693. type: 10 /* IF_BRANCH */,
  13694. loc: node.loc,
  13695. condition: dir.name === 'else' ? undefined : dir.exp,
  13696. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  13697. ? node.children
  13698. : [node],
  13699. userKey: findProp(node, `key`)
  13700. };
  13701. }
  13702. function createCodegenNodeForBranch(branch, keyIndex, context) {
  13703. if (branch.condition) {
  13704. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  13705. // make sure to pass in asBlock: true so that the comment node call
  13706. // closes the current block.
  13707. createCallExpression(context.helper(CREATE_COMMENT), [
  13708. '"v-if"' ,
  13709. 'true'
  13710. ]));
  13711. }
  13712. else {
  13713. return createChildrenCodegenNode(branch, keyIndex, context);
  13714. }
  13715. }
  13716. function createChildrenCodegenNode(branch, keyIndex, context) {
  13717. const { helper } = context;
  13718. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
  13719. const { children } = branch;
  13720. const firstChild = children[0];
  13721. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  13722. if (needFragmentWrapper) {
  13723. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  13724. // optimize away nested fragments when child is a ForNode
  13725. const vnodeCall = firstChild.codegenNode;
  13726. injectProp(vnodeCall, keyProperty, context);
  13727. return vnodeCall;
  13728. }
  13729. else {
  13730. let patchFlag = 64 /* STABLE_FRAGMENT */;
  13731. let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
  13732. // check if the fragment actually contains a single valid child with
  13733. // the rest being comments
  13734. if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
  13735. patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
  13736. patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
  13737. }
  13738. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  13739. }
  13740. }
  13741. else {
  13742. const ret = firstChild.codegenNode;
  13743. const vnodeCall = getMemoedVNodeCall(ret);
  13744. // Change createVNode to createBlock.
  13745. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  13746. makeBlock(vnodeCall, context);
  13747. }
  13748. // inject branch key
  13749. injectProp(vnodeCall, keyProperty, context);
  13750. return ret;
  13751. }
  13752. }
  13753. function isSameKey(a, b) {
  13754. if (!a || a.type !== b.type) {
  13755. return false;
  13756. }
  13757. if (a.type === 6 /* ATTRIBUTE */) {
  13758. if (a.value.content !== b.value.content) {
  13759. return false;
  13760. }
  13761. }
  13762. else {
  13763. // directive
  13764. const exp = a.exp;
  13765. const branchExp = b.exp;
  13766. if (exp.type !== branchExp.type) {
  13767. return false;
  13768. }
  13769. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  13770. exp.isStatic !== branchExp.isStatic ||
  13771. exp.content !== branchExp.content) {
  13772. return false;
  13773. }
  13774. }
  13775. return true;
  13776. }
  13777. function getParentCondition(node) {
  13778. while (true) {
  13779. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  13780. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  13781. node = node.alternate;
  13782. }
  13783. else {
  13784. return node;
  13785. }
  13786. }
  13787. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  13788. node = node.value;
  13789. }
  13790. }
  13791. }
  13792. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  13793. const { helper, removeHelper } = context;
  13794. return processFor(node, dir, context, forNode => {
  13795. // create the loop render function expression now, and add the
  13796. // iterator on exit after all children have been traversed
  13797. const renderExp = createCallExpression(helper(RENDER_LIST), [
  13798. forNode.source
  13799. ]);
  13800. const isTemplate = isTemplateNode(node);
  13801. const memo = findDir(node, 'memo');
  13802. const keyProp = findProp(node, `key`);
  13803. const keyExp = keyProp &&
  13804. (keyProp.type === 6 /* ATTRIBUTE */
  13805. ? createSimpleExpression(keyProp.value.content, true)
  13806. : keyProp.exp);
  13807. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  13808. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  13809. forNode.source.constType > 0 /* NOT_CONSTANT */;
  13810. const fragmentFlag = isStableFragment
  13811. ? 64 /* STABLE_FRAGMENT */
  13812. : keyProp
  13813. ? 128 /* KEYED_FRAGMENT */
  13814. : 256 /* UNKEYED_FRAGMENT */;
  13815. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  13816. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  13817. return () => {
  13818. // finish the codegen now that all children have been traversed
  13819. let childBlock;
  13820. const { children } = forNode;
  13821. // check <template v-for> key placement
  13822. if (isTemplate) {
  13823. node.children.some(c => {
  13824. if (c.type === 1 /* ELEMENT */) {
  13825. const key = findProp(c, 'key');
  13826. if (key) {
  13827. context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  13828. return true;
  13829. }
  13830. }
  13831. });
  13832. }
  13833. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  13834. const slotOutlet = isSlotOutlet(node)
  13835. ? node
  13836. : isTemplate &&
  13837. node.children.length === 1 &&
  13838. isSlotOutlet(node.children[0])
  13839. ? node.children[0] // api-extractor somehow fails to infer this
  13840. : null;
  13841. if (slotOutlet) {
  13842. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  13843. childBlock = slotOutlet.codegenNode;
  13844. if (isTemplate && keyProperty) {
  13845. // <template v-for="..." :key="..."><slot/></template>
  13846. // we need to inject the key to the renderSlot() call.
  13847. // the props for renderSlot is passed as the 3rd argument.
  13848. injectProp(childBlock, keyProperty, context);
  13849. }
  13850. }
  13851. else if (needFragmentWrapper) {
  13852. // <template v-for="..."> with text or multi-elements
  13853. // should generate a fragment block for each loop
  13854. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
  13855. (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  13856. ), undefined, undefined, true, undefined, false /* isComponent */);
  13857. }
  13858. else {
  13859. // Normal element v-for. Directly use the child's codegenNode
  13860. // but mark it as a block.
  13861. childBlock = children[0]
  13862. .codegenNode;
  13863. if (isTemplate && keyProperty) {
  13864. injectProp(childBlock, keyProperty, context);
  13865. }
  13866. if (childBlock.isBlock !== !isStableFragment) {
  13867. if (childBlock.isBlock) {
  13868. // switch from block to vnode
  13869. removeHelper(OPEN_BLOCK);
  13870. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  13871. }
  13872. else {
  13873. // switch from vnode to block
  13874. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  13875. }
  13876. }
  13877. childBlock.isBlock = !isStableFragment;
  13878. if (childBlock.isBlock) {
  13879. helper(OPEN_BLOCK);
  13880. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  13881. }
  13882. else {
  13883. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  13884. }
  13885. }
  13886. if (memo) {
  13887. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  13888. createSimpleExpression(`_cached`)
  13889. ]));
  13890. loop.body = createBlockStatement([
  13891. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  13892. createCompoundExpression([
  13893. `if (_cached`,
  13894. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  13895. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  13896. ]),
  13897. createCompoundExpression([`const _item = `, childBlock]),
  13898. createSimpleExpression(`_item.memo = _memo`),
  13899. createSimpleExpression(`return _item`)
  13900. ]);
  13901. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  13902. }
  13903. else {
  13904. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  13905. }
  13906. };
  13907. });
  13908. });
  13909. // target-agnostic transform used for both Client and SSR
  13910. function processFor(node, dir, context, processCodegen) {
  13911. if (!dir.exp) {
  13912. context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  13913. return;
  13914. }
  13915. const parseResult = parseForExpression(
  13916. // can only be simple expression because vFor transform is applied
  13917. // before expression transform.
  13918. dir.exp, context);
  13919. if (!parseResult) {
  13920. context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  13921. return;
  13922. }
  13923. const { addIdentifiers, removeIdentifiers, scopes } = context;
  13924. const { source, value, key, index } = parseResult;
  13925. const forNode = {
  13926. type: 11 /* FOR */,
  13927. loc: dir.loc,
  13928. source,
  13929. valueAlias: value,
  13930. keyAlias: key,
  13931. objectIndexAlias: index,
  13932. parseResult,
  13933. children: isTemplateNode(node) ? node.children : [node]
  13934. };
  13935. context.replaceNode(forNode);
  13936. // bookkeeping
  13937. scopes.vFor++;
  13938. const onExit = processCodegen && processCodegen(forNode);
  13939. return () => {
  13940. scopes.vFor--;
  13941. if (onExit)
  13942. onExit();
  13943. };
  13944. }
  13945. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  13946. // This regex doesn't cover the case if key or index aliases have destructuring,
  13947. // but those do not make sense in the first place, so this works in practice.
  13948. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  13949. const stripParensRE = /^\(|\)$/g;
  13950. function parseForExpression(input, context) {
  13951. const loc = input.loc;
  13952. const exp = input.content;
  13953. const inMatch = exp.match(forAliasRE);
  13954. if (!inMatch)
  13955. return;
  13956. const [, LHS, RHS] = inMatch;
  13957. const result = {
  13958. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  13959. value: undefined,
  13960. key: undefined,
  13961. index: undefined
  13962. };
  13963. {
  13964. validateBrowserExpression(result.source, context);
  13965. }
  13966. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  13967. const trimmedOffset = LHS.indexOf(valueContent);
  13968. const iteratorMatch = valueContent.match(forIteratorRE);
  13969. if (iteratorMatch) {
  13970. valueContent = valueContent.replace(forIteratorRE, '').trim();
  13971. const keyContent = iteratorMatch[1].trim();
  13972. let keyOffset;
  13973. if (keyContent) {
  13974. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  13975. result.key = createAliasExpression(loc, keyContent, keyOffset);
  13976. {
  13977. validateBrowserExpression(result.key, context, true);
  13978. }
  13979. }
  13980. if (iteratorMatch[2]) {
  13981. const indexContent = iteratorMatch[2].trim();
  13982. if (indexContent) {
  13983. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  13984. ? keyOffset + keyContent.length
  13985. : trimmedOffset + valueContent.length));
  13986. {
  13987. validateBrowserExpression(result.index, context, true);
  13988. }
  13989. }
  13990. }
  13991. }
  13992. if (valueContent) {
  13993. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  13994. {
  13995. validateBrowserExpression(result.value, context, true);
  13996. }
  13997. }
  13998. return result;
  13999. }
  14000. function createAliasExpression(range, content, offset) {
  14001. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  14002. }
  14003. function createForLoopParams({ value, key, index }, memoArgs = []) {
  14004. return createParamsList([value, key, index, ...memoArgs]);
  14005. }
  14006. function createParamsList(args) {
  14007. let i = args.length;
  14008. while (i--) {
  14009. if (args[i])
  14010. break;
  14011. }
  14012. return args
  14013. .slice(0, i + 1)
  14014. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  14015. }
  14016. const defaultFallback = createSimpleExpression(`undefined`, false);
  14017. // A NodeTransform that:
  14018. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  14019. // by transformExpression. This is only applied in non-browser builds with
  14020. // { prefixIdentifiers: true }.
  14021. // 2. Track v-slot depths so that we know a slot is inside another slot.
  14022. // Note the exit callback is executed before buildSlots() on the same node,
  14023. // so only nested slots see positive numbers.
  14024. const trackSlotScopes = (node, context) => {
  14025. if (node.type === 1 /* ELEMENT */ &&
  14026. (node.tagType === 1 /* COMPONENT */ ||
  14027. node.tagType === 3 /* TEMPLATE */)) {
  14028. // We are only checking non-empty v-slot here
  14029. // since we only care about slots that introduce scope variables.
  14030. const vSlot = findDir(node, 'slot');
  14031. if (vSlot) {
  14032. vSlot.exp;
  14033. context.scopes.vSlot++;
  14034. return () => {
  14035. context.scopes.vSlot--;
  14036. };
  14037. }
  14038. }
  14039. };
  14040. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  14041. // Instead of being a DirectiveTransform, v-slot processing is called during
  14042. // transformElement to build the slots object for a component.
  14043. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  14044. context.helper(WITH_CTX);
  14045. const { children, loc } = node;
  14046. const slotsProperties = [];
  14047. const dynamicSlots = [];
  14048. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  14049. // since it likely uses a scope variable.
  14050. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  14051. // 1. Check for slot with slotProps on component itself.
  14052. // <Comp v-slot="{ prop }"/>
  14053. const onComponentSlot = findDir(node, 'slot', true);
  14054. if (onComponentSlot) {
  14055. const { arg, exp } = onComponentSlot;
  14056. if (arg && !isStaticExp(arg)) {
  14057. hasDynamicSlots = true;
  14058. }
  14059. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  14060. }
  14061. // 2. Iterate through children and check for template slots
  14062. // <template v-slot:foo="{ prop }">
  14063. let hasTemplateSlots = false;
  14064. let hasNamedDefaultSlot = false;
  14065. const implicitDefaultChildren = [];
  14066. const seenSlotNames = new Set();
  14067. for (let i = 0; i < children.length; i++) {
  14068. const slotElement = children[i];
  14069. let slotDir;
  14070. if (!isTemplateNode(slotElement) ||
  14071. !(slotDir = findDir(slotElement, 'slot', true))) {
  14072. // not a <template v-slot>, skip.
  14073. if (slotElement.type !== 3 /* COMMENT */) {
  14074. implicitDefaultChildren.push(slotElement);
  14075. }
  14076. continue;
  14077. }
  14078. if (onComponentSlot) {
  14079. // already has on-component slot - this is incorrect usage.
  14080. context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  14081. break;
  14082. }
  14083. hasTemplateSlots = true;
  14084. const { children: slotChildren, loc: slotLoc } = slotElement;
  14085. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  14086. // check if name is dynamic.
  14087. let staticSlotName;
  14088. if (isStaticExp(slotName)) {
  14089. staticSlotName = slotName ? slotName.content : `default`;
  14090. }
  14091. else {
  14092. hasDynamicSlots = true;
  14093. }
  14094. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  14095. // check if this slot is conditional (v-if/v-for)
  14096. let vIf;
  14097. let vElse;
  14098. let vFor;
  14099. if ((vIf = findDir(slotElement, 'if'))) {
  14100. hasDynamicSlots = true;
  14101. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  14102. }
  14103. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  14104. // find adjacent v-if
  14105. let j = i;
  14106. let prev;
  14107. while (j--) {
  14108. prev = children[j];
  14109. if (prev.type !== 3 /* COMMENT */) {
  14110. break;
  14111. }
  14112. }
  14113. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  14114. // remove node
  14115. children.splice(i, 1);
  14116. i--;
  14117. // attach this slot to previous conditional
  14118. let conditional = dynamicSlots[dynamicSlots.length - 1];
  14119. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  14120. conditional = conditional.alternate;
  14121. }
  14122. conditional.alternate = vElse.exp
  14123. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  14124. : buildDynamicSlot(slotName, slotFunction);
  14125. }
  14126. else {
  14127. context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  14128. }
  14129. }
  14130. else if ((vFor = findDir(slotElement, 'for'))) {
  14131. hasDynamicSlots = true;
  14132. const parseResult = vFor.parseResult ||
  14133. parseForExpression(vFor.exp, context);
  14134. if (parseResult) {
  14135. // Render the dynamic slots as an array and add it to the createSlot()
  14136. // args. The runtime knows how to handle it appropriately.
  14137. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  14138. parseResult.source,
  14139. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  14140. ]));
  14141. }
  14142. else {
  14143. context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  14144. }
  14145. }
  14146. else {
  14147. // check duplicate static names
  14148. if (staticSlotName) {
  14149. if (seenSlotNames.has(staticSlotName)) {
  14150. context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  14151. continue;
  14152. }
  14153. seenSlotNames.add(staticSlotName);
  14154. if (staticSlotName === 'default') {
  14155. hasNamedDefaultSlot = true;
  14156. }
  14157. }
  14158. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  14159. }
  14160. }
  14161. if (!onComponentSlot) {
  14162. const buildDefaultSlotProperty = (props, children) => {
  14163. const fn = buildSlotFn(props, children, loc);
  14164. return createObjectProperty(`default`, fn);
  14165. };
  14166. if (!hasTemplateSlots) {
  14167. // implicit default slot (on component)
  14168. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  14169. }
  14170. else if (implicitDefaultChildren.length &&
  14171. // #3766
  14172. // with whitespace: 'preserve', whitespaces between slots will end up in
  14173. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  14174. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  14175. // implicit default slot (mixed with named slots)
  14176. if (hasNamedDefaultSlot) {
  14177. context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  14178. }
  14179. else {
  14180. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  14181. }
  14182. }
  14183. }
  14184. const slotFlag = hasDynamicSlots
  14185. ? 2 /* DYNAMIC */
  14186. : hasForwardedSlots(node.children)
  14187. ? 3 /* FORWARDED */
  14188. : 1 /* STABLE */;
  14189. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  14190. // 2 = compiled but dynamic = can skip normalization, but must run diff
  14191. // 1 = compiled and static = can skip normalization AND diff as optimized
  14192. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  14193. if (dynamicSlots.length) {
  14194. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  14195. slots,
  14196. createArrayExpression(dynamicSlots)
  14197. ]);
  14198. }
  14199. return {
  14200. slots,
  14201. hasDynamicSlots
  14202. };
  14203. }
  14204. function buildDynamicSlot(name, fn) {
  14205. return createObjectExpression([
  14206. createObjectProperty(`name`, name),
  14207. createObjectProperty(`fn`, fn)
  14208. ]);
  14209. }
  14210. function hasForwardedSlots(children) {
  14211. for (let i = 0; i < children.length; i++) {
  14212. const child = children[i];
  14213. switch (child.type) {
  14214. case 1 /* ELEMENT */:
  14215. if (child.tagType === 2 /* SLOT */ ||
  14216. hasForwardedSlots(child.children)) {
  14217. return true;
  14218. }
  14219. break;
  14220. case 9 /* IF */:
  14221. if (hasForwardedSlots(child.branches))
  14222. return true;
  14223. break;
  14224. case 10 /* IF_BRANCH */:
  14225. case 11 /* FOR */:
  14226. if (hasForwardedSlots(child.children))
  14227. return true;
  14228. break;
  14229. }
  14230. }
  14231. return false;
  14232. }
  14233. function isNonWhitespaceContent(node) {
  14234. if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
  14235. return true;
  14236. return node.type === 2 /* TEXT */
  14237. ? !!node.content.trim()
  14238. : isNonWhitespaceContent(node.content);
  14239. }
  14240. // some directive transforms (e.g. v-model) may return a symbol for runtime
  14241. // import, which should be used instead of a resolveDirective call.
  14242. const directiveImportMap = new WeakMap();
  14243. // generate a JavaScript AST for this element's codegen
  14244. const transformElement = (node, context) => {
  14245. // perform the work on exit, after all child expressions have been
  14246. // processed and merged.
  14247. return function postTransformElement() {
  14248. node = context.currentNode;
  14249. if (!(node.type === 1 /* ELEMENT */ &&
  14250. (node.tagType === 0 /* ELEMENT */ ||
  14251. node.tagType === 1 /* COMPONENT */))) {
  14252. return;
  14253. }
  14254. const { tag, props } = node;
  14255. const isComponent = node.tagType === 1 /* COMPONENT */;
  14256. // The goal of the transform is to create a codegenNode implementing the
  14257. // VNodeCall interface.
  14258. let vnodeTag = isComponent
  14259. ? resolveComponentType(node, context)
  14260. : `"${tag}"`;
  14261. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  14262. let vnodeProps;
  14263. let vnodeChildren;
  14264. let vnodePatchFlag;
  14265. let patchFlag = 0;
  14266. let vnodeDynamicProps;
  14267. let dynamicPropNames;
  14268. let vnodeDirectives;
  14269. let shouldUseBlock =
  14270. // dynamic component may resolve to plain elements
  14271. isDynamicComponent ||
  14272. vnodeTag === TELEPORT ||
  14273. vnodeTag === SUSPENSE ||
  14274. (!isComponent &&
  14275. // <svg> and <foreignObject> must be forced into blocks so that block
  14276. // updates inside get proper isSVG flag at runtime. (#639, #643)
  14277. // This is technically web-specific, but splitting the logic out of core
  14278. // leads to too much unnecessary complexity.
  14279. (tag === 'svg' || tag === 'foreignObject'));
  14280. // props
  14281. if (props.length > 0) {
  14282. const propsBuildResult = buildProps(node, context);
  14283. vnodeProps = propsBuildResult.props;
  14284. patchFlag = propsBuildResult.patchFlag;
  14285. dynamicPropNames = propsBuildResult.dynamicPropNames;
  14286. const directives = propsBuildResult.directives;
  14287. vnodeDirectives =
  14288. directives && directives.length
  14289. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  14290. : undefined;
  14291. if (propsBuildResult.shouldUseBlock) {
  14292. shouldUseBlock = true;
  14293. }
  14294. }
  14295. // children
  14296. if (node.children.length > 0) {
  14297. if (vnodeTag === KEEP_ALIVE) {
  14298. // Although a built-in component, we compile KeepAlive with raw children
  14299. // instead of slot functions so that it can be used inside Transition
  14300. // or other Transition-wrapping HOCs.
  14301. // To ensure correct updates with block optimizations, we need to:
  14302. // 1. Force keep-alive into a block. This avoids its children being
  14303. // collected by a parent block.
  14304. shouldUseBlock = true;
  14305. // 2. Force keep-alive to always be updated, since it uses raw children.
  14306. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  14307. if (node.children.length > 1) {
  14308. context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  14309. start: node.children[0].loc.start,
  14310. end: node.children[node.children.length - 1].loc.end,
  14311. source: ''
  14312. }));
  14313. }
  14314. }
  14315. const shouldBuildAsSlots = isComponent &&
  14316. // Teleport is not a real component and has dedicated runtime handling
  14317. vnodeTag !== TELEPORT &&
  14318. // explained above.
  14319. vnodeTag !== KEEP_ALIVE;
  14320. if (shouldBuildAsSlots) {
  14321. const { slots, hasDynamicSlots } = buildSlots(node, context);
  14322. vnodeChildren = slots;
  14323. if (hasDynamicSlots) {
  14324. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  14325. }
  14326. }
  14327. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  14328. const child = node.children[0];
  14329. const type = child.type;
  14330. // check for dynamic text children
  14331. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  14332. type === 8 /* COMPOUND_EXPRESSION */;
  14333. if (hasDynamicTextChild &&
  14334. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  14335. patchFlag |= 1 /* TEXT */;
  14336. }
  14337. // pass directly if the only child is a text node
  14338. // (plain / interpolation / expression)
  14339. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  14340. vnodeChildren = child;
  14341. }
  14342. else {
  14343. vnodeChildren = node.children;
  14344. }
  14345. }
  14346. else {
  14347. vnodeChildren = node.children;
  14348. }
  14349. }
  14350. // patchFlag & dynamicPropNames
  14351. if (patchFlag !== 0) {
  14352. {
  14353. if (patchFlag < 0) {
  14354. // special flags (negative and mutually exclusive)
  14355. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  14356. }
  14357. else {
  14358. // bitwise flags
  14359. const flagNames = Object.keys(PatchFlagNames)
  14360. .map(Number)
  14361. .filter(n => n > 0 && patchFlag & n)
  14362. .map(n => PatchFlagNames[n])
  14363. .join(`, `);
  14364. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  14365. }
  14366. }
  14367. if (dynamicPropNames && dynamicPropNames.length) {
  14368. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  14369. }
  14370. }
  14371. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  14372. };
  14373. };
  14374. function resolveComponentType(node, context, ssr = false) {
  14375. let { tag } = node;
  14376. // 1. dynamic component
  14377. const isExplicitDynamic = isComponentTag(tag);
  14378. const isProp = findProp(node, 'is');
  14379. if (isProp) {
  14380. if (isExplicitDynamic ||
  14381. (false )) {
  14382. const exp = isProp.type === 6 /* ATTRIBUTE */
  14383. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  14384. : isProp.exp;
  14385. if (exp) {
  14386. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  14387. exp
  14388. ]);
  14389. }
  14390. }
  14391. else if (isProp.type === 6 /* ATTRIBUTE */ &&
  14392. isProp.value.content.startsWith('vue:')) {
  14393. // <button is="vue:xxx">
  14394. // if not <component>, only is value that starts with "vue:" will be
  14395. // treated as component by the parse phase and reach here, unless it's
  14396. // compat mode where all is values are considered components
  14397. tag = isProp.value.content.slice(4);
  14398. }
  14399. }
  14400. // 1.5 v-is (TODO: Deprecate)
  14401. const isDir = !isExplicitDynamic && findDir(node, 'is');
  14402. if (isDir && isDir.exp) {
  14403. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  14404. isDir.exp
  14405. ]);
  14406. }
  14407. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  14408. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  14409. if (builtIn) {
  14410. // built-ins are simply fallthroughs / have special handling during ssr
  14411. // so we don't need to import their runtime equivalents
  14412. if (!ssr)
  14413. context.helper(builtIn);
  14414. return builtIn;
  14415. }
  14416. // 5. user component (resolve)
  14417. context.helper(RESOLVE_COMPONENT);
  14418. context.components.add(tag);
  14419. return toValidAssetId(tag, `component`);
  14420. }
  14421. function buildProps(node, context, props = node.props, ssr = false) {
  14422. const { tag, loc: elementLoc, children } = node;
  14423. const isComponent = node.tagType === 1 /* COMPONENT */;
  14424. let properties = [];
  14425. const mergeArgs = [];
  14426. const runtimeDirectives = [];
  14427. const hasChildren = children.length > 0;
  14428. let shouldUseBlock = false;
  14429. // patchFlag analysis
  14430. let patchFlag = 0;
  14431. let hasRef = false;
  14432. let hasClassBinding = false;
  14433. let hasStyleBinding = false;
  14434. let hasHydrationEventBinding = false;
  14435. let hasDynamicKeys = false;
  14436. let hasVnodeHook = false;
  14437. const dynamicPropNames = [];
  14438. const analyzePatchFlag = ({ key, value }) => {
  14439. if (isStaticExp(key)) {
  14440. const name = key.content;
  14441. const isEventHandler = isOn(name);
  14442. if (!isComponent &&
  14443. isEventHandler &&
  14444. // omit the flag for click handlers because hydration gives click
  14445. // dedicated fast path.
  14446. name.toLowerCase() !== 'onclick' &&
  14447. // omit v-model handlers
  14448. name !== 'onUpdate:modelValue' &&
  14449. // omit onVnodeXXX hooks
  14450. !isReservedProp(name)) {
  14451. hasHydrationEventBinding = true;
  14452. }
  14453. if (isEventHandler && isReservedProp(name)) {
  14454. hasVnodeHook = true;
  14455. }
  14456. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  14457. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  14458. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  14459. getConstantType(value, context) > 0)) {
  14460. // skip if the prop is a cached handler or has constant value
  14461. return;
  14462. }
  14463. if (name === 'ref') {
  14464. hasRef = true;
  14465. }
  14466. else if (name === 'class') {
  14467. hasClassBinding = true;
  14468. }
  14469. else if (name === 'style') {
  14470. hasStyleBinding = true;
  14471. }
  14472. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  14473. dynamicPropNames.push(name);
  14474. }
  14475. // treat the dynamic class and style binding of the component as dynamic props
  14476. if (isComponent &&
  14477. (name === 'class' || name === 'style') &&
  14478. !dynamicPropNames.includes(name)) {
  14479. dynamicPropNames.push(name);
  14480. }
  14481. }
  14482. else {
  14483. hasDynamicKeys = true;
  14484. }
  14485. };
  14486. for (let i = 0; i < props.length; i++) {
  14487. // static attribute
  14488. const prop = props[i];
  14489. if (prop.type === 6 /* ATTRIBUTE */) {
  14490. const { loc, name, value } = prop;
  14491. let isStatic = true;
  14492. if (name === 'ref') {
  14493. hasRef = true;
  14494. if (context.scopes.vFor > 0) {
  14495. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  14496. }
  14497. }
  14498. // skip is on <component>, or is="vue:xxx"
  14499. if (name === 'is' &&
  14500. (isComponentTag(tag) ||
  14501. (value && value.content.startsWith('vue:')) ||
  14502. (false ))) {
  14503. continue;
  14504. }
  14505. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  14506. }
  14507. else {
  14508. // directives
  14509. const { name, arg, exp, loc } = prop;
  14510. const isVBind = name === 'bind';
  14511. const isVOn = name === 'on';
  14512. // skip v-slot - it is handled by its dedicated transform.
  14513. if (name === 'slot') {
  14514. if (!isComponent) {
  14515. context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
  14516. }
  14517. continue;
  14518. }
  14519. // skip v-once/v-memo - they are handled by dedicated transforms.
  14520. if (name === 'once' || name === 'memo') {
  14521. continue;
  14522. }
  14523. // skip v-is and :is on <component>
  14524. if (name === 'is' ||
  14525. (isVBind &&
  14526. isStaticArgOf(arg, 'is') &&
  14527. (isComponentTag(tag) ||
  14528. (false )))) {
  14529. continue;
  14530. }
  14531. // skip v-on in SSR compilation
  14532. if (isVOn && ssr) {
  14533. continue;
  14534. }
  14535. if (
  14536. // #938: elements with dynamic keys should be forced into blocks
  14537. (isVBind && isStaticArgOf(arg, 'key')) ||
  14538. // inline before-update hooks need to force block so that it is invoked
  14539. // before children
  14540. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  14541. shouldUseBlock = true;
  14542. }
  14543. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  14544. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  14545. }
  14546. // special case for v-bind and v-on with no argument
  14547. if (!arg && (isVBind || isVOn)) {
  14548. hasDynamicKeys = true;
  14549. if (exp) {
  14550. if (properties.length) {
  14551. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  14552. properties = [];
  14553. }
  14554. if (isVBind) {
  14555. mergeArgs.push(exp);
  14556. }
  14557. else {
  14558. // v-on="obj" -> toHandlers(obj)
  14559. mergeArgs.push({
  14560. type: 14 /* JS_CALL_EXPRESSION */,
  14561. loc,
  14562. callee: context.helper(TO_HANDLERS),
  14563. arguments: [exp]
  14564. });
  14565. }
  14566. }
  14567. else {
  14568. context.onError(createCompilerError(isVBind
  14569. ? 34 /* X_V_BIND_NO_EXPRESSION */
  14570. : 35 /* X_V_ON_NO_EXPRESSION */, loc));
  14571. }
  14572. continue;
  14573. }
  14574. const directiveTransform = context.directiveTransforms[name];
  14575. if (directiveTransform) {
  14576. // has built-in directive transform.
  14577. const { props, needRuntime } = directiveTransform(prop, node, context);
  14578. !ssr && props.forEach(analyzePatchFlag);
  14579. properties.push(...props);
  14580. if (needRuntime) {
  14581. runtimeDirectives.push(prop);
  14582. if (isSymbol(needRuntime)) {
  14583. directiveImportMap.set(prop, needRuntime);
  14584. }
  14585. }
  14586. }
  14587. else if (!isBuiltInDirective(name)) {
  14588. // no built-in transform, this is a user custom directive.
  14589. runtimeDirectives.push(prop);
  14590. // custom dirs may use beforeUpdate so they need to force blocks
  14591. // to ensure before-update gets called before children update
  14592. if (hasChildren) {
  14593. shouldUseBlock = true;
  14594. }
  14595. }
  14596. }
  14597. }
  14598. let propsExpression = undefined;
  14599. // has v-bind="object" or v-on="object", wrap with mergeProps
  14600. if (mergeArgs.length) {
  14601. if (properties.length) {
  14602. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  14603. }
  14604. if (mergeArgs.length > 1) {
  14605. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  14606. }
  14607. else {
  14608. // single v-bind with nothing else - no need for a mergeProps call
  14609. propsExpression = mergeArgs[0];
  14610. }
  14611. }
  14612. else if (properties.length) {
  14613. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  14614. }
  14615. // patchFlag analysis
  14616. if (hasDynamicKeys) {
  14617. patchFlag |= 16 /* FULL_PROPS */;
  14618. }
  14619. else {
  14620. if (hasClassBinding && !isComponent) {
  14621. patchFlag |= 2 /* CLASS */;
  14622. }
  14623. if (hasStyleBinding && !isComponent) {
  14624. patchFlag |= 4 /* STYLE */;
  14625. }
  14626. if (dynamicPropNames.length) {
  14627. patchFlag |= 8 /* PROPS */;
  14628. }
  14629. if (hasHydrationEventBinding) {
  14630. patchFlag |= 32 /* HYDRATE_EVENTS */;
  14631. }
  14632. }
  14633. if (!shouldUseBlock &&
  14634. (patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  14635. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  14636. patchFlag |= 512 /* NEED_PATCH */;
  14637. }
  14638. // pre-normalize props, SSR is skipped for now
  14639. if (!context.inSSR && propsExpression) {
  14640. switch (propsExpression.type) {
  14641. case 15 /* JS_OBJECT_EXPRESSION */:
  14642. // means that there is no v-bind,
  14643. // but still need to deal with dynamic key binding
  14644. let classKeyIndex = -1;
  14645. let styleKeyIndex = -1;
  14646. let hasDynamicKey = false;
  14647. for (let i = 0; i < propsExpression.properties.length; i++) {
  14648. const key = propsExpression.properties[i].key;
  14649. if (isStaticExp(key)) {
  14650. if (key.content === 'class') {
  14651. classKeyIndex = i;
  14652. }
  14653. else if (key.content === 'style') {
  14654. styleKeyIndex = i;
  14655. }
  14656. }
  14657. else if (!key.isHandlerKey) {
  14658. hasDynamicKey = true;
  14659. }
  14660. }
  14661. const classProp = propsExpression.properties[classKeyIndex];
  14662. const styleProp = propsExpression.properties[styleKeyIndex];
  14663. // no dynamic key
  14664. if (!hasDynamicKey) {
  14665. if (classProp && !isStaticExp(classProp.value)) {
  14666. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  14667. }
  14668. if (styleProp &&
  14669. !isStaticExp(styleProp.value) &&
  14670. // the static style is compiled into an object,
  14671. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  14672. (hasStyleBinding ||
  14673. // v-bind:style and style both exist,
  14674. // v-bind:style with static literal object
  14675. styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
  14676. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  14677. }
  14678. }
  14679. else {
  14680. // dynamic key binding, wrap with `normalizeProps`
  14681. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  14682. }
  14683. break;
  14684. case 14 /* JS_CALL_EXPRESSION */:
  14685. // mergeProps call, do nothing
  14686. break;
  14687. default:
  14688. // single v-bind
  14689. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  14690. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  14691. propsExpression
  14692. ])
  14693. ]);
  14694. break;
  14695. }
  14696. }
  14697. return {
  14698. props: propsExpression,
  14699. directives: runtimeDirectives,
  14700. patchFlag,
  14701. dynamicPropNames,
  14702. shouldUseBlock
  14703. };
  14704. }
  14705. // Dedupe props in an object literal.
  14706. // Literal duplicated attributes would have been warned during the parse phase,
  14707. // however, it's possible to encounter duplicated `onXXX` handlers with different
  14708. // modifiers. We also need to merge static and dynamic class / style attributes.
  14709. // - onXXX handlers / style: merge into array
  14710. // - class: merge into single expression with concatenation
  14711. function dedupeProperties(properties) {
  14712. const knownProps = new Map();
  14713. const deduped = [];
  14714. for (let i = 0; i < properties.length; i++) {
  14715. const prop = properties[i];
  14716. // dynamic keys are always allowed
  14717. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  14718. deduped.push(prop);
  14719. continue;
  14720. }
  14721. const name = prop.key.content;
  14722. const existing = knownProps.get(name);
  14723. if (existing) {
  14724. if (name === 'style' || name === 'class' || isOn(name)) {
  14725. mergeAsArray$1(existing, prop);
  14726. }
  14727. // unexpected duplicate, should have emitted error during parse
  14728. }
  14729. else {
  14730. knownProps.set(name, prop);
  14731. deduped.push(prop);
  14732. }
  14733. }
  14734. return deduped;
  14735. }
  14736. function mergeAsArray$1(existing, incoming) {
  14737. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  14738. existing.value.elements.push(incoming.value);
  14739. }
  14740. else {
  14741. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  14742. }
  14743. }
  14744. function buildDirectiveArgs(dir, context) {
  14745. const dirArgs = [];
  14746. const runtime = directiveImportMap.get(dir);
  14747. if (runtime) {
  14748. // built-in directive with runtime
  14749. dirArgs.push(context.helperString(runtime));
  14750. }
  14751. else {
  14752. {
  14753. // inject statement for resolving directive
  14754. context.helper(RESOLVE_DIRECTIVE);
  14755. context.directives.add(dir.name);
  14756. dirArgs.push(toValidAssetId(dir.name, `directive`));
  14757. }
  14758. }
  14759. const { loc } = dir;
  14760. if (dir.exp)
  14761. dirArgs.push(dir.exp);
  14762. if (dir.arg) {
  14763. if (!dir.exp) {
  14764. dirArgs.push(`void 0`);
  14765. }
  14766. dirArgs.push(dir.arg);
  14767. }
  14768. if (Object.keys(dir.modifiers).length) {
  14769. if (!dir.arg) {
  14770. if (!dir.exp) {
  14771. dirArgs.push(`void 0`);
  14772. }
  14773. dirArgs.push(`void 0`);
  14774. }
  14775. const trueExpression = createSimpleExpression(`true`, false, loc);
  14776. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  14777. }
  14778. return createArrayExpression(dirArgs, dir.loc);
  14779. }
  14780. function stringifyDynamicPropNames(props) {
  14781. let propsNamesString = `[`;
  14782. for (let i = 0, l = props.length; i < l; i++) {
  14783. propsNamesString += JSON.stringify(props[i]);
  14784. if (i < l - 1)
  14785. propsNamesString += ', ';
  14786. }
  14787. return propsNamesString + `]`;
  14788. }
  14789. function isComponentTag(tag) {
  14790. return tag === 'component' || tag === 'Component';
  14791. }
  14792. const transformSlotOutlet = (node, context) => {
  14793. if (isSlotOutlet(node)) {
  14794. const { children, loc } = node;
  14795. const { slotName, slotProps } = processSlotOutlet(node, context);
  14796. const slotArgs = [
  14797. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  14798. slotName,
  14799. '{}',
  14800. 'undefined',
  14801. 'true'
  14802. ];
  14803. let expectedLen = 2;
  14804. if (slotProps) {
  14805. slotArgs[2] = slotProps;
  14806. expectedLen = 3;
  14807. }
  14808. if (children.length) {
  14809. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  14810. expectedLen = 4;
  14811. }
  14812. if (context.scopeId && !context.slotted) {
  14813. expectedLen = 5;
  14814. }
  14815. slotArgs.splice(expectedLen); // remove unused arguments
  14816. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  14817. }
  14818. };
  14819. function processSlotOutlet(node, context) {
  14820. let slotName = `"default"`;
  14821. let slotProps = undefined;
  14822. const nonNameProps = [];
  14823. for (let i = 0; i < node.props.length; i++) {
  14824. const p = node.props[i];
  14825. if (p.type === 6 /* ATTRIBUTE */) {
  14826. if (p.value) {
  14827. if (p.name === 'name') {
  14828. slotName = JSON.stringify(p.value.content);
  14829. }
  14830. else {
  14831. p.name = camelize(p.name);
  14832. nonNameProps.push(p);
  14833. }
  14834. }
  14835. }
  14836. else {
  14837. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  14838. if (p.exp)
  14839. slotName = p.exp;
  14840. }
  14841. else {
  14842. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  14843. p.arg.content = camelize(p.arg.content);
  14844. }
  14845. nonNameProps.push(p);
  14846. }
  14847. }
  14848. }
  14849. if (nonNameProps.length > 0) {
  14850. const { props, directives } = buildProps(node, context, nonNameProps);
  14851. slotProps = props;
  14852. if (directives.length) {
  14853. context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  14854. }
  14855. }
  14856. return {
  14857. slotName,
  14858. slotProps
  14859. };
  14860. }
  14861. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  14862. const transformOn = (dir, node, context, augmentor) => {
  14863. const { loc, modifiers, arg } = dir;
  14864. if (!dir.exp && !modifiers.length) {
  14865. context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
  14866. }
  14867. let eventName;
  14868. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  14869. if (arg.isStatic) {
  14870. let rawName = arg.content;
  14871. // TODO deprecate @vnodeXXX usage
  14872. if (rawName.startsWith('vue:')) {
  14873. rawName = `vnode-${rawName.slice(4)}`;
  14874. }
  14875. // for all event listeners, auto convert it to camelCase. See issue #2249
  14876. eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
  14877. }
  14878. else {
  14879. // #2388
  14880. eventName = createCompoundExpression([
  14881. `${context.helperString(TO_HANDLER_KEY)}(`,
  14882. arg,
  14883. `)`
  14884. ]);
  14885. }
  14886. }
  14887. else {
  14888. // already a compound expression.
  14889. eventName = arg;
  14890. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  14891. eventName.children.push(`)`);
  14892. }
  14893. // handler processing
  14894. let exp = dir.exp;
  14895. if (exp && !exp.content.trim()) {
  14896. exp = undefined;
  14897. }
  14898. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  14899. if (exp) {
  14900. const isMemberExp = isMemberExpression(exp.content);
  14901. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  14902. const hasMultipleStatements = exp.content.includes(`;`);
  14903. {
  14904. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  14905. }
  14906. if (isInlineStatement || (shouldCache && isMemberExp)) {
  14907. // wrap inline statement in a function expression
  14908. exp = createCompoundExpression([
  14909. `${isInlineStatement
  14910. ? `$event`
  14911. : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  14912. exp,
  14913. hasMultipleStatements ? `}` : `)`
  14914. ]);
  14915. }
  14916. }
  14917. let ret = {
  14918. props: [
  14919. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  14920. ]
  14921. };
  14922. // apply extended compiler augmentor
  14923. if (augmentor) {
  14924. ret = augmentor(ret);
  14925. }
  14926. if (shouldCache) {
  14927. // cache handlers so that it's always the same handler being passed down.
  14928. // this avoids unnecessary re-renders when users use inline handlers on
  14929. // components.
  14930. ret.props[0].value = context.cache(ret.props[0].value);
  14931. }
  14932. // mark the key as handler for props normalization check
  14933. ret.props.forEach(p => (p.key.isHandlerKey = true));
  14934. return ret;
  14935. };
  14936. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  14937. // codegen for the entire props object. This transform here is only for v-bind
  14938. // *with* args.
  14939. const transformBind = (dir, _node, context) => {
  14940. const { exp, modifiers, loc } = dir;
  14941. const arg = dir.arg;
  14942. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  14943. arg.children.unshift(`(`);
  14944. arg.children.push(`) || ""`);
  14945. }
  14946. else if (!arg.isStatic) {
  14947. arg.content = `${arg.content} || ""`;
  14948. }
  14949. // .sync is replaced by v-model:arg
  14950. if (modifiers.includes('camel')) {
  14951. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  14952. if (arg.isStatic) {
  14953. arg.content = camelize(arg.content);
  14954. }
  14955. else {
  14956. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  14957. }
  14958. }
  14959. else {
  14960. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  14961. arg.children.push(`)`);
  14962. }
  14963. }
  14964. if (!context.inSSR) {
  14965. if (modifiers.includes('prop')) {
  14966. injectPrefix(arg, '.');
  14967. }
  14968. if (modifiers.includes('attr')) {
  14969. injectPrefix(arg, '^');
  14970. }
  14971. }
  14972. if (!exp ||
  14973. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  14974. context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
  14975. return {
  14976. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  14977. };
  14978. }
  14979. return {
  14980. props: [createObjectProperty(arg, exp)]
  14981. };
  14982. };
  14983. const injectPrefix = (arg, prefix) => {
  14984. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  14985. if (arg.isStatic) {
  14986. arg.content = prefix + arg.content;
  14987. }
  14988. else {
  14989. arg.content = `\`${prefix}\${${arg.content}}\``;
  14990. }
  14991. }
  14992. else {
  14993. arg.children.unshift(`'${prefix}' + (`);
  14994. arg.children.push(`)`);
  14995. }
  14996. };
  14997. // Merge adjacent text nodes and expressions into a single expression
  14998. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  14999. const transformText = (node, context) => {
  15000. if (node.type === 0 /* ROOT */ ||
  15001. node.type === 1 /* ELEMENT */ ||
  15002. node.type === 11 /* FOR */ ||
  15003. node.type === 10 /* IF_BRANCH */) {
  15004. // perform the transform on node exit so that all expressions have already
  15005. // been processed.
  15006. return () => {
  15007. const children = node.children;
  15008. let currentContainer = undefined;
  15009. let hasText = false;
  15010. for (let i = 0; i < children.length; i++) {
  15011. const child = children[i];
  15012. if (isText(child)) {
  15013. hasText = true;
  15014. for (let j = i + 1; j < children.length; j++) {
  15015. const next = children[j];
  15016. if (isText(next)) {
  15017. if (!currentContainer) {
  15018. currentContainer = children[i] = {
  15019. type: 8 /* COMPOUND_EXPRESSION */,
  15020. loc: child.loc,
  15021. children: [child]
  15022. };
  15023. }
  15024. // merge adjacent text node into current
  15025. currentContainer.children.push(` + `, next);
  15026. children.splice(j, 1);
  15027. j--;
  15028. }
  15029. else {
  15030. currentContainer = undefined;
  15031. break;
  15032. }
  15033. }
  15034. }
  15035. }
  15036. if (!hasText ||
  15037. // if this is a plain element with a single text child, leave it
  15038. // as-is since the runtime has dedicated fast path for this by directly
  15039. // setting textContent of the element.
  15040. // for component root it's always normalized anyway.
  15041. (children.length === 1 &&
  15042. (node.type === 0 /* ROOT */ ||
  15043. (node.type === 1 /* ELEMENT */ &&
  15044. node.tagType === 0 /* ELEMENT */ &&
  15045. // #3756
  15046. // custom directives can potentially add DOM elements arbitrarily,
  15047. // we need to avoid setting textContent of the element at runtime
  15048. // to avoid accidentally overwriting the DOM elements added
  15049. // by the user through custom directives.
  15050. !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
  15051. !context.directiveTransforms[p.name]) &&
  15052. // in compat mode, <template> tags with no special directives
  15053. // will be rendered as a fragment so its children must be
  15054. // converted into vnodes.
  15055. !(false ))))) {
  15056. return;
  15057. }
  15058. // pre-convert text nodes into createTextVNode(text) calls to avoid
  15059. // runtime normalization.
  15060. for (let i = 0; i < children.length; i++) {
  15061. const child = children[i];
  15062. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  15063. const callArgs = [];
  15064. // createTextVNode defaults to single whitespace, so if it is a
  15065. // single space the code could be an empty call to save bytes.
  15066. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  15067. callArgs.push(child);
  15068. }
  15069. // mark dynamic text with flag so it gets patched inside a block
  15070. if (!context.ssr &&
  15071. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  15072. callArgs.push(1 /* TEXT */ +
  15073. (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
  15074. }
  15075. children[i] = {
  15076. type: 12 /* TEXT_CALL */,
  15077. content: child,
  15078. loc: child.loc,
  15079. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  15080. };
  15081. }
  15082. }
  15083. };
  15084. }
  15085. };
  15086. const seen = new WeakSet();
  15087. const transformOnce = (node, context) => {
  15088. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  15089. if (seen.has(node) || context.inVOnce) {
  15090. return;
  15091. }
  15092. seen.add(node);
  15093. context.inVOnce = true;
  15094. context.helper(SET_BLOCK_TRACKING);
  15095. return () => {
  15096. context.inVOnce = false;
  15097. const cur = context.currentNode;
  15098. if (cur.codegenNode) {
  15099. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  15100. }
  15101. };
  15102. }
  15103. };
  15104. const transformModel = (dir, node, context) => {
  15105. const { exp, arg } = dir;
  15106. if (!exp) {
  15107. context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  15108. return createTransformProps();
  15109. }
  15110. const rawExp = exp.loc.source;
  15111. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  15112. // im SFC <script setup> inline mode, the exp may have been transformed into
  15113. // _unref(exp)
  15114. context.bindingMetadata[rawExp];
  15115. const maybeRef = !true /* SETUP_CONST */;
  15116. if (!expString.trim() ||
  15117. (!isMemberExpression(expString) && !maybeRef)) {
  15118. context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  15119. return createTransformProps();
  15120. }
  15121. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  15122. const eventName = arg
  15123. ? isStaticExp(arg)
  15124. ? `onUpdate:${arg.content}`
  15125. : createCompoundExpression(['"onUpdate:" + ', arg])
  15126. : `onUpdate:modelValue`;
  15127. let assignmentExp;
  15128. const eventArg = context.isTS ? `($event: any)` : `$event`;
  15129. {
  15130. assignmentExp = createCompoundExpression([
  15131. `${eventArg} => ((`,
  15132. exp,
  15133. `) = $event)`
  15134. ]);
  15135. }
  15136. const props = [
  15137. // modelValue: foo
  15138. createObjectProperty(propName, dir.exp),
  15139. // "onUpdate:modelValue": $event => (foo = $event)
  15140. createObjectProperty(eventName, assignmentExp)
  15141. ];
  15142. // modelModifiers: { foo: true, "bar-baz": true }
  15143. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  15144. const modifiers = dir.modifiers
  15145. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  15146. .join(`, `);
  15147. const modifiersKey = arg
  15148. ? isStaticExp(arg)
  15149. ? `${arg.content}Modifiers`
  15150. : createCompoundExpression([arg, ' + "Modifiers"'])
  15151. : `modelModifiers`;
  15152. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
  15153. }
  15154. return createTransformProps(props);
  15155. };
  15156. function createTransformProps(props = []) {
  15157. return { props };
  15158. }
  15159. const seen$1 = new WeakSet();
  15160. const transformMemo = (node, context) => {
  15161. if (node.type === 1 /* ELEMENT */) {
  15162. const dir = findDir(node, 'memo');
  15163. if (!dir || seen$1.has(node)) {
  15164. return;
  15165. }
  15166. seen$1.add(node);
  15167. return () => {
  15168. const codegenNode = node.codegenNode ||
  15169. context.currentNode.codegenNode;
  15170. if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
  15171. // non-component sub tree should be turned into a block
  15172. if (node.tagType !== 1 /* COMPONENT */) {
  15173. makeBlock(codegenNode, context);
  15174. }
  15175. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  15176. dir.exp,
  15177. createFunctionExpression(undefined, codegenNode),
  15178. `_cache`,
  15179. String(context.cached++)
  15180. ]);
  15181. }
  15182. };
  15183. }
  15184. };
  15185. function getBaseTransformPreset(prefixIdentifiers) {
  15186. return [
  15187. [
  15188. transformOnce,
  15189. transformIf,
  15190. transformMemo,
  15191. transformFor,
  15192. ...([]),
  15193. ...([transformExpression]
  15194. ),
  15195. transformSlotOutlet,
  15196. transformElement,
  15197. trackSlotScopes,
  15198. transformText
  15199. ],
  15200. {
  15201. on: transformOn,
  15202. bind: transformBind,
  15203. model: transformModel
  15204. }
  15205. ];
  15206. }
  15207. // we name it `baseCompile` so that higher order compilers like
  15208. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  15209. function baseCompile(template, options = {}) {
  15210. const onError = options.onError || defaultOnError;
  15211. const isModuleMode = options.mode === 'module';
  15212. /* istanbul ignore if */
  15213. {
  15214. if (options.prefixIdentifiers === true) {
  15215. onError(createCompilerError(46 /* X_PREFIX_ID_NOT_SUPPORTED */));
  15216. }
  15217. else if (isModuleMode) {
  15218. onError(createCompilerError(47 /* X_MODULE_MODE_NOT_SUPPORTED */));
  15219. }
  15220. }
  15221. const prefixIdentifiers = !true ;
  15222. if (options.cacheHandlers) {
  15223. onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  15224. }
  15225. if (options.scopeId && !isModuleMode) {
  15226. onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
  15227. }
  15228. const ast = isString(template) ? baseParse(template, options) : template;
  15229. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  15230. transform(ast, extend({}, options, {
  15231. prefixIdentifiers,
  15232. nodeTransforms: [
  15233. ...nodeTransforms,
  15234. ...(options.nodeTransforms || []) // user transforms
  15235. ],
  15236. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  15237. )
  15238. }));
  15239. return generate(ast, extend({}, options, {
  15240. prefixIdentifiers
  15241. }));
  15242. }
  15243. const noopDirectiveTransform = () => ({ props: [] });
  15244. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  15245. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  15246. const V_MODEL_TEXT = Symbol(`vModelText` );
  15247. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  15248. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  15249. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  15250. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  15251. const V_SHOW = Symbol(`vShow` );
  15252. const TRANSITION$1 = Symbol(`Transition` );
  15253. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  15254. registerRuntimeHelpers({
  15255. [V_MODEL_RADIO]: `vModelRadio`,
  15256. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  15257. [V_MODEL_TEXT]: `vModelText`,
  15258. [V_MODEL_SELECT]: `vModelSelect`,
  15259. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  15260. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  15261. [V_ON_WITH_KEYS]: `withKeys`,
  15262. [V_SHOW]: `vShow`,
  15263. [TRANSITION$1]: `Transition`,
  15264. [TRANSITION_GROUP]: `TransitionGroup`
  15265. });
  15266. /* eslint-disable no-restricted-globals */
  15267. let decoder;
  15268. function decodeHtmlBrowser(raw, asAttr = false) {
  15269. if (!decoder) {
  15270. decoder = document.createElement('div');
  15271. }
  15272. if (asAttr) {
  15273. decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
  15274. return decoder.children[0].getAttribute('foo');
  15275. }
  15276. else {
  15277. decoder.innerHTML = raw;
  15278. return decoder.textContent;
  15279. }
  15280. }
  15281. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  15282. const parserOptions = {
  15283. isVoidTag,
  15284. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  15285. isPreTag: tag => tag === 'pre',
  15286. decodeEntities: decodeHtmlBrowser ,
  15287. isBuiltInComponent: (tag) => {
  15288. if (isBuiltInType(tag, `Transition`)) {
  15289. return TRANSITION$1;
  15290. }
  15291. else if (isBuiltInType(tag, `TransitionGroup`)) {
  15292. return TRANSITION_GROUP;
  15293. }
  15294. },
  15295. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  15296. getNamespace(tag, parent) {
  15297. let ns = parent ? parent.ns : 0 /* HTML */;
  15298. if (parent && ns === 2 /* MATH_ML */) {
  15299. if (parent.tag === 'annotation-xml') {
  15300. if (tag === 'svg') {
  15301. return 1 /* SVG */;
  15302. }
  15303. if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
  15304. a.name === 'encoding' &&
  15305. a.value != null &&
  15306. (a.value.content === 'text/html' ||
  15307. a.value.content === 'application/xhtml+xml'))) {
  15308. ns = 0 /* HTML */;
  15309. }
  15310. }
  15311. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  15312. tag !== 'mglyph' &&
  15313. tag !== 'malignmark') {
  15314. ns = 0 /* HTML */;
  15315. }
  15316. }
  15317. else if (parent && ns === 1 /* SVG */) {
  15318. if (parent.tag === 'foreignObject' ||
  15319. parent.tag === 'desc' ||
  15320. parent.tag === 'title') {
  15321. ns = 0 /* HTML */;
  15322. }
  15323. }
  15324. if (ns === 0 /* HTML */) {
  15325. if (tag === 'svg') {
  15326. return 1 /* SVG */;
  15327. }
  15328. if (tag === 'math') {
  15329. return 2 /* MATH_ML */;
  15330. }
  15331. }
  15332. return ns;
  15333. },
  15334. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  15335. getTextMode({ tag, ns }) {
  15336. if (ns === 0 /* HTML */) {
  15337. if (tag === 'textarea' || tag === 'title') {
  15338. return 1 /* RCDATA */;
  15339. }
  15340. if (isRawTextContainer(tag)) {
  15341. return 2 /* RAWTEXT */;
  15342. }
  15343. }
  15344. return 0 /* DATA */;
  15345. }
  15346. };
  15347. // Parse inline CSS strings for static style attributes into an object.
  15348. // This is a NodeTransform since it works on the static `style` attribute and
  15349. // converts it into a dynamic equivalent:
  15350. // style="color: red" -> :style='{ "color": "red" }'
  15351. // It is then processed by `transformElement` and included in the generated
  15352. // props.
  15353. const transformStyle = node => {
  15354. if (node.type === 1 /* ELEMENT */) {
  15355. node.props.forEach((p, i) => {
  15356. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  15357. // replace p with an expression node
  15358. node.props[i] = {
  15359. type: 7 /* DIRECTIVE */,
  15360. name: `bind`,
  15361. arg: createSimpleExpression(`style`, true, p.loc),
  15362. exp: parseInlineCSS(p.value.content, p.loc),
  15363. modifiers: [],
  15364. loc: p.loc
  15365. };
  15366. }
  15367. });
  15368. }
  15369. };
  15370. const parseInlineCSS = (cssText, loc) => {
  15371. const normalized = parseStringStyle(cssText);
  15372. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
  15373. };
  15374. function createDOMCompilerError(code, loc) {
  15375. return createCompilerError(code, loc, DOMErrorMessages );
  15376. }
  15377. const DOMErrorMessages = {
  15378. [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  15379. [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  15380. [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  15381. [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  15382. [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  15383. [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  15384. [56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  15385. [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  15386. [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  15387. [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  15388. [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  15389. };
  15390. const transformVHtml = (dir, node, context) => {
  15391. const { exp, loc } = dir;
  15392. if (!exp) {
  15393. context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
  15394. }
  15395. if (node.children.length) {
  15396. context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
  15397. node.children.length = 0;
  15398. }
  15399. return {
  15400. props: [
  15401. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  15402. ]
  15403. };
  15404. };
  15405. const transformVText = (dir, node, context) => {
  15406. const { exp, loc } = dir;
  15407. if (!exp) {
  15408. context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
  15409. }
  15410. if (node.children.length) {
  15411. context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
  15412. node.children.length = 0;
  15413. }
  15414. return {
  15415. props: [
  15416. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  15417. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  15418. : createSimpleExpression('', true))
  15419. ]
  15420. };
  15421. };
  15422. const transformModel$1 = (dir, node, context) => {
  15423. const baseResult = transformModel(dir, node, context);
  15424. // base transform has errors OR component v-model (only need props)
  15425. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  15426. return baseResult;
  15427. }
  15428. if (dir.arg) {
  15429. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  15430. }
  15431. function checkDuplicatedValue() {
  15432. const value = findProp(node, 'value');
  15433. if (value) {
  15434. context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  15435. }
  15436. }
  15437. const { tag } = node;
  15438. const isCustomElement = context.isCustomElement(tag);
  15439. if (tag === 'input' ||
  15440. tag === 'textarea' ||
  15441. tag === 'select' ||
  15442. isCustomElement) {
  15443. let directiveToUse = V_MODEL_TEXT;
  15444. let isInvalidType = false;
  15445. if (tag === 'input' || isCustomElement) {
  15446. const type = findProp(node, `type`);
  15447. if (type) {
  15448. if (type.type === 7 /* DIRECTIVE */) {
  15449. // :type="foo"
  15450. directiveToUse = V_MODEL_DYNAMIC;
  15451. }
  15452. else if (type.value) {
  15453. switch (type.value.content) {
  15454. case 'radio':
  15455. directiveToUse = V_MODEL_RADIO;
  15456. break;
  15457. case 'checkbox':
  15458. directiveToUse = V_MODEL_CHECKBOX;
  15459. break;
  15460. case 'file':
  15461. isInvalidType = true;
  15462. context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  15463. break;
  15464. default:
  15465. // text type
  15466. checkDuplicatedValue();
  15467. break;
  15468. }
  15469. }
  15470. }
  15471. else if (hasDynamicKeyVBind(node)) {
  15472. // element has bindings with dynamic keys, which can possibly contain
  15473. // "type".
  15474. directiveToUse = V_MODEL_DYNAMIC;
  15475. }
  15476. else {
  15477. // text type
  15478. checkDuplicatedValue();
  15479. }
  15480. }
  15481. else if (tag === 'select') {
  15482. directiveToUse = V_MODEL_SELECT;
  15483. }
  15484. else {
  15485. // textarea
  15486. checkDuplicatedValue();
  15487. }
  15488. // inject runtime directive
  15489. // by returning the helper symbol via needRuntime
  15490. // the import will replaced a resolveDirective call.
  15491. if (!isInvalidType) {
  15492. baseResult.needRuntime = context.helper(directiveToUse);
  15493. }
  15494. }
  15495. else {
  15496. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  15497. }
  15498. // native vmodel doesn't need the `modelValue` props since they are also
  15499. // passed to the runtime as `binding.value`. removing it reduces code size.
  15500. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  15501. p.key.content === 'modelValue'));
  15502. return baseResult;
  15503. };
  15504. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  15505. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  15506. // event propagation management
  15507. `stop,prevent,self,` +
  15508. // system modifiers + exact
  15509. `ctrl,shift,alt,meta,exact,` +
  15510. // mouse
  15511. `middle`);
  15512. // left & right could be mouse or key modifiers based on event type
  15513. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  15514. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  15515. const resolveModifiers = (key, modifiers, context, loc) => {
  15516. const keyModifiers = [];
  15517. const nonKeyModifiers = [];
  15518. const eventOptionModifiers = [];
  15519. for (let i = 0; i < modifiers.length; i++) {
  15520. const modifier = modifiers[i];
  15521. if (isEventOptionModifier(modifier)) {
  15522. // eventOptionModifiers: modifiers for addEventListener() options,
  15523. // e.g. .passive & .capture
  15524. eventOptionModifiers.push(modifier);
  15525. }
  15526. else {
  15527. // runtimeModifiers: modifiers that needs runtime guards
  15528. if (maybeKeyModifier(modifier)) {
  15529. if (isStaticExp(key)) {
  15530. if (isKeyboardEvent(key.content)) {
  15531. keyModifiers.push(modifier);
  15532. }
  15533. else {
  15534. nonKeyModifiers.push(modifier);
  15535. }
  15536. }
  15537. else {
  15538. keyModifiers.push(modifier);
  15539. nonKeyModifiers.push(modifier);
  15540. }
  15541. }
  15542. else {
  15543. if (isNonKeyModifier(modifier)) {
  15544. nonKeyModifiers.push(modifier);
  15545. }
  15546. else {
  15547. keyModifiers.push(modifier);
  15548. }
  15549. }
  15550. }
  15551. }
  15552. return {
  15553. keyModifiers,
  15554. nonKeyModifiers,
  15555. eventOptionModifiers
  15556. };
  15557. };
  15558. const transformClick = (key, event) => {
  15559. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  15560. return isStaticClick
  15561. ? createSimpleExpression(event, true)
  15562. : key.type !== 4 /* SIMPLE_EXPRESSION */
  15563. ? createCompoundExpression([
  15564. `(`,
  15565. key,
  15566. `) === "onClick" ? "${event}" : (`,
  15567. key,
  15568. `)`
  15569. ])
  15570. : key;
  15571. };
  15572. const transformOn$1 = (dir, node, context) => {
  15573. return transformOn(dir, node, context, baseResult => {
  15574. const { modifiers } = dir;
  15575. if (!modifiers.length)
  15576. return baseResult;
  15577. let { key, value: handlerExp } = baseResult.props[0];
  15578. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  15579. // normalize click.right and click.middle since they don't actually fire
  15580. if (nonKeyModifiers.includes('right')) {
  15581. key = transformClick(key, `onContextmenu`);
  15582. }
  15583. if (nonKeyModifiers.includes('middle')) {
  15584. key = transformClick(key, `onMouseup`);
  15585. }
  15586. if (nonKeyModifiers.length) {
  15587. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  15588. handlerExp,
  15589. JSON.stringify(nonKeyModifiers)
  15590. ]);
  15591. }
  15592. if (keyModifiers.length &&
  15593. // if event name is dynamic, always wrap with keys guard
  15594. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  15595. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  15596. handlerExp,
  15597. JSON.stringify(keyModifiers)
  15598. ]);
  15599. }
  15600. if (eventOptionModifiers.length) {
  15601. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  15602. key = isStaticExp(key)
  15603. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  15604. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  15605. }
  15606. return {
  15607. props: [createObjectProperty(key, handlerExp)]
  15608. };
  15609. });
  15610. };
  15611. const transformShow = (dir, node, context) => {
  15612. const { exp, loc } = dir;
  15613. if (!exp) {
  15614. context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
  15615. }
  15616. return {
  15617. props: [],
  15618. needRuntime: context.helper(V_SHOW)
  15619. };
  15620. };
  15621. const warnTransitionChildren = (node, context) => {
  15622. if (node.type === 1 /* ELEMENT */ &&
  15623. node.tagType === 1 /* COMPONENT */) {
  15624. const component = context.isBuiltInComponent(node.tag);
  15625. if (component === TRANSITION$1) {
  15626. return () => {
  15627. if (node.children.length && hasMultipleChildren(node)) {
  15628. context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
  15629. start: node.children[0].loc.start,
  15630. end: node.children[node.children.length - 1].loc.end,
  15631. source: ''
  15632. }));
  15633. }
  15634. };
  15635. }
  15636. }
  15637. };
  15638. function hasMultipleChildren(node) {
  15639. // #1352 filter out potential comment nodes.
  15640. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */ &&
  15641. !(c.type === 2 /* TEXT */ && !c.content.trim())));
  15642. const child = children[0];
  15643. return (children.length !== 1 ||
  15644. child.type === 11 /* FOR */ ||
  15645. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  15646. }
  15647. const ignoreSideEffectTags = (node, context) => {
  15648. if (node.type === 1 /* ELEMENT */ &&
  15649. node.tagType === 0 /* ELEMENT */ &&
  15650. (node.tag === 'script' || node.tag === 'style')) {
  15651. context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  15652. context.removeNode();
  15653. }
  15654. };
  15655. const DOMNodeTransforms = [
  15656. transformStyle,
  15657. ...([warnTransitionChildren] )
  15658. ];
  15659. const DOMDirectiveTransforms = {
  15660. cloak: noopDirectiveTransform,
  15661. html: transformVHtml,
  15662. text: transformVText,
  15663. model: transformModel$1,
  15664. on: transformOn$1,
  15665. show: transformShow
  15666. };
  15667. function compile$1(template, options = {}) {
  15668. return baseCompile(template, extend({}, parserOptions, options, {
  15669. nodeTransforms: [
  15670. // ignore <script> and <tag>
  15671. // this is not put inside DOMNodeTransforms because that list is used
  15672. // by compiler-ssr to generate vnode fallback branches
  15673. ignoreSideEffectTags,
  15674. ...DOMNodeTransforms,
  15675. ...(options.nodeTransforms || [])
  15676. ],
  15677. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  15678. transformHoist: null
  15679. }));
  15680. }
  15681. // This entry is the "full-build" that includes both the runtime
  15682. {
  15683. initDev();
  15684. }
  15685. const compileCache = Object.create(null);
  15686. function compileToFunction(template, options) {
  15687. if (!isString(template)) {
  15688. if (template.nodeType) {
  15689. template = template.innerHTML;
  15690. }
  15691. else {
  15692. warn$1(`invalid template option: `, template);
  15693. return NOOP;
  15694. }
  15695. }
  15696. const key = template;
  15697. const cached = compileCache[key];
  15698. if (cached) {
  15699. return cached;
  15700. }
  15701. if (template[0] === '#') {
  15702. const el = document.querySelector(template);
  15703. if (!el) {
  15704. warn$1(`Template element not found or is empty: ${template}`);
  15705. }
  15706. // __UNSAFE__
  15707. // Reason: potential execution of JS expressions in in-DOM template.
  15708. // The user must make sure the in-DOM template is trusted. If it's rendered
  15709. // by the server, the template should not contain any user data.
  15710. template = el ? el.innerHTML : ``;
  15711. }
  15712. const { code } = compile$1(template, extend({
  15713. hoistStatic: true,
  15714. onError: onError ,
  15715. onWarn: e => onError(e, true)
  15716. }, options));
  15717. function onError(err, asWarning = false) {
  15718. const message = asWarning
  15719. ? err.message
  15720. : `Template compilation error: ${err.message}`;
  15721. const codeFrame = err.loc &&
  15722. generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
  15723. warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
  15724. }
  15725. // The wildcard import results in a huge object with every export
  15726. // with keys that cannot be mangled, and can be quite heavy size-wise.
  15727. // In the global build we know `Vue` is available globally so we can avoid
  15728. // the wildcard object.
  15729. const render = (new Function('Vue', code)(runtimeDom));
  15730. render._rc = true;
  15731. return (compileCache[key] = render);
  15732. }
  15733. registerRuntimeCompiler(compileToFunction);
  15734. export { BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compileToFunction as compile, computed$1 as computed, createApp, createBlock, createCommentVNode, createElementBlock, createBaseVNode as createElementVNode, createHydrationRenderer, createPropsRestProxy, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineCustomElement, defineEmits, defineExpose, defineProps, defineSSRCustomElement, devtools, effect, effectScope, getCurrentInstance, getCurrentScope, getTransitionRawChildren, guardReactiveProps, h, handleError, hydrate, initCustomFormatter, initDirectivesForSSR, inject, isMemoSame, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, isShallow, isVNode, markRaw, mergeDefaults, mergeProps, nextTick, normalizeClass, normalizeProps, normalizeStyle, onActivated, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onDeactivated, onErrorCaptured, onMounted, onRenderTracked, onRenderTriggered, onScopeDispose, onServerPrefetch, onUnmounted, onUpdated, openBlock, popScopeId, provide, proxyRefs, pushScopeId, queuePostFlushCb, reactive, readonly, ref, registerRuntimeCompiler, render, renderList, renderSlot, resolveComponent, resolveDirective, resolveDynamicComponent, resolveFilter, resolveTransitionHooks, setBlockTracking, setDevtoolsHook, setTransitionHooks, shallowReactive, shallowReadonly, shallowRef, ssrContextKey, ssrUtils, stop, toDisplayString, toHandlerKey, toHandlers, toRaw, toRef, toRefs, transformVNodeArgs, triggerRef, unref, useAttrs, useCssModule, useCssVars, useSSRContext, useSlots, useTransitionState, vModelCheckbox, vModelDynamic, vModelRadio, vModelSelect, vModelText, vShow, version, warn$1 as warn, watch, watchEffect, watchPostEffect, watchSyncEffect, withAsyncContext, withCtx, withDefaults, withDirectives, withKeys, withMemo, withModifiers, withScopeId };