vue.esm-browser.js 587 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718
  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. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  203. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  204. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  205. function looseCompareArrays(a, b) {
  206. if (a.length !== b.length)
  207. return false;
  208. let equal = true;
  209. for (let i = 0; equal && i < a.length; i++) {
  210. equal = looseEqual(a[i], b[i]);
  211. }
  212. return equal;
  213. }
  214. function looseEqual(a, b) {
  215. if (a === b)
  216. return true;
  217. let aValidType = isDate(a);
  218. let bValidType = isDate(b);
  219. if (aValidType || bValidType) {
  220. return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  221. }
  222. aValidType = isArray(a);
  223. bValidType = isArray(b);
  224. if (aValidType || bValidType) {
  225. return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  226. }
  227. aValidType = isObject(a);
  228. bValidType = isObject(b);
  229. if (aValidType || bValidType) {
  230. /* istanbul ignore if: this if will probably never be called */
  231. if (!aValidType || !bValidType) {
  232. return false;
  233. }
  234. const aKeysCount = Object.keys(a).length;
  235. const bKeysCount = Object.keys(b).length;
  236. if (aKeysCount !== bKeysCount) {
  237. return false;
  238. }
  239. for (const key in a) {
  240. const aHasKey = a.hasOwnProperty(key);
  241. const bHasKey = b.hasOwnProperty(key);
  242. if ((aHasKey && !bHasKey) ||
  243. (!aHasKey && bHasKey) ||
  244. !looseEqual(a[key], b[key])) {
  245. return false;
  246. }
  247. }
  248. }
  249. return String(a) === String(b);
  250. }
  251. function looseIndexOf(arr, val) {
  252. return arr.findIndex(item => looseEqual(item, val));
  253. }
  254. /**
  255. * For converting {{ interpolation }} values to displayed strings.
  256. * @private
  257. */
  258. const toDisplayString = (val) => {
  259. return val == null
  260. ? ''
  261. : isArray(val) ||
  262. (isObject(val) &&
  263. (val.toString === objectToString || !isFunction(val.toString)))
  264. ? JSON.stringify(val, replacer, 2)
  265. : String(val);
  266. };
  267. const replacer = (_key, val) => {
  268. // can't use isRef here since @vue/shared has no deps
  269. if (val && val.__v_isRef) {
  270. return replacer(_key, val.value);
  271. }
  272. else if (isMap(val)) {
  273. return {
  274. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  275. entries[`${key} =>`] = val;
  276. return entries;
  277. }, {})
  278. };
  279. }
  280. else if (isSet(val)) {
  281. return {
  282. [`Set(${val.size})`]: [...val.values()]
  283. };
  284. }
  285. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  286. return String(val);
  287. }
  288. return val;
  289. };
  290. const EMPTY_OBJ = Object.freeze({})
  291. ;
  292. const EMPTY_ARR = Object.freeze([]) ;
  293. const NOOP = () => { };
  294. /**
  295. * Always return false.
  296. */
  297. const NO = () => false;
  298. const onRE = /^on[^a-z]/;
  299. const isOn = (key) => onRE.test(key);
  300. const isModelListener = (key) => key.startsWith('onUpdate:');
  301. const extend = Object.assign;
  302. const remove = (arr, el) => {
  303. const i = arr.indexOf(el);
  304. if (i > -1) {
  305. arr.splice(i, 1);
  306. }
  307. };
  308. const hasOwnProperty = Object.prototype.hasOwnProperty;
  309. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  310. const isArray = Array.isArray;
  311. const isMap = (val) => toTypeString(val) === '[object Map]';
  312. const isSet = (val) => toTypeString(val) === '[object Set]';
  313. const isDate = (val) => val instanceof Date;
  314. const isFunction = (val) => typeof val === 'function';
  315. const isString = (val) => typeof val === 'string';
  316. const isSymbol = (val) => typeof val === 'symbol';
  317. const isObject = (val) => val !== null && typeof val === 'object';
  318. const isPromise = (val) => {
  319. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  320. };
  321. const objectToString = Object.prototype.toString;
  322. const toTypeString = (value) => objectToString.call(value);
  323. const toRawType = (value) => {
  324. // extract "RawType" from strings like "[object RawType]"
  325. return toTypeString(value).slice(8, -1);
  326. };
  327. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  328. const isIntegerKey = (key) => isString(key) &&
  329. key !== 'NaN' &&
  330. key[0] !== '-' &&
  331. '' + parseInt(key, 10) === key;
  332. const isReservedProp = /*#__PURE__*/ makeMap(
  333. // the leading comma is intentional so empty string "" is also included
  334. ',key,ref,ref_for,ref_key,' +
  335. 'onVnodeBeforeMount,onVnodeMounted,' +
  336. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  337. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  338. const cacheStringFunction = (fn) => {
  339. const cache = Object.create(null);
  340. return ((str) => {
  341. const hit = cache[str];
  342. return hit || (cache[str] = fn(str));
  343. });
  344. };
  345. const camelizeRE = /-(\w)/g;
  346. /**
  347. * @private
  348. */
  349. const camelize = cacheStringFunction((str) => {
  350. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  351. });
  352. const hyphenateRE = /\B([A-Z])/g;
  353. /**
  354. * @private
  355. */
  356. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  357. /**
  358. * @private
  359. */
  360. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  361. /**
  362. * @private
  363. */
  364. const toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
  365. // compare whether a value has changed, accounting for NaN.
  366. const hasChanged = (value, oldValue) => !Object.is(value, oldValue);
  367. const invokeArrayFns = (fns, arg) => {
  368. for (let i = 0; i < fns.length; i++) {
  369. fns[i](arg);
  370. }
  371. };
  372. const def = (obj, key, value) => {
  373. Object.defineProperty(obj, key, {
  374. configurable: true,
  375. enumerable: false,
  376. value
  377. });
  378. };
  379. const toNumber = (val) => {
  380. const n = parseFloat(val);
  381. return isNaN(n) ? val : n;
  382. };
  383. let _globalThis;
  384. const getGlobalThis = () => {
  385. return (_globalThis ||
  386. (_globalThis =
  387. typeof globalThis !== 'undefined'
  388. ? globalThis
  389. : typeof self !== 'undefined'
  390. ? self
  391. : typeof window !== 'undefined'
  392. ? window
  393. : typeof global !== 'undefined'
  394. ? global
  395. : {}));
  396. };
  397. function warn(msg, ...args) {
  398. console.warn(`[Vue warn] ${msg}`, ...args);
  399. }
  400. let activeEffectScope;
  401. const effectScopeStack = [];
  402. class EffectScope {
  403. constructor(detached = false) {
  404. this.active = true;
  405. this.effects = [];
  406. this.cleanups = [];
  407. if (!detached && activeEffectScope) {
  408. this.parent = activeEffectScope;
  409. this.index =
  410. (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
  411. }
  412. }
  413. run(fn) {
  414. if (this.active) {
  415. try {
  416. this.on();
  417. return fn();
  418. }
  419. finally {
  420. this.off();
  421. }
  422. }
  423. else {
  424. warn(`cannot run an inactive effect scope.`);
  425. }
  426. }
  427. on() {
  428. if (this.active) {
  429. effectScopeStack.push(this);
  430. activeEffectScope = this;
  431. }
  432. }
  433. off() {
  434. if (this.active) {
  435. effectScopeStack.pop();
  436. activeEffectScope = effectScopeStack[effectScopeStack.length - 1];
  437. }
  438. }
  439. stop(fromParent) {
  440. if (this.active) {
  441. this.effects.forEach(e => e.stop());
  442. this.cleanups.forEach(cleanup => cleanup());
  443. if (this.scopes) {
  444. this.scopes.forEach(e => e.stop(true));
  445. }
  446. // nested scope, dereference from parent to avoid memory leaks
  447. if (this.parent && !fromParent) {
  448. // optimized O(1) removal
  449. const last = this.parent.scopes.pop();
  450. if (last && last !== this) {
  451. this.parent.scopes[this.index] = last;
  452. last.index = this.index;
  453. }
  454. }
  455. this.active = false;
  456. }
  457. }
  458. }
  459. function effectScope(detached) {
  460. return new EffectScope(detached);
  461. }
  462. function recordEffectScope(effect, scope) {
  463. scope = scope || activeEffectScope;
  464. if (scope && scope.active) {
  465. scope.effects.push(effect);
  466. }
  467. }
  468. function getCurrentScope() {
  469. return activeEffectScope;
  470. }
  471. function onScopeDispose(fn) {
  472. if (activeEffectScope) {
  473. activeEffectScope.cleanups.push(fn);
  474. }
  475. else {
  476. warn(`onScopeDispose() is called when there is no active effect scope` +
  477. ` to be associated with.`);
  478. }
  479. }
  480. const createDep = (effects) => {
  481. const dep = new Set(effects);
  482. dep.w = 0;
  483. dep.n = 0;
  484. return dep;
  485. };
  486. const wasTracked = (dep) => (dep.w & trackOpBit) > 0;
  487. const newTracked = (dep) => (dep.n & trackOpBit) > 0;
  488. const initDepMarkers = ({ deps }) => {
  489. if (deps.length) {
  490. for (let i = 0; i < deps.length; i++) {
  491. deps[i].w |= trackOpBit; // set was tracked
  492. }
  493. }
  494. };
  495. const finalizeDepMarkers = (effect) => {
  496. const { deps } = effect;
  497. if (deps.length) {
  498. let ptr = 0;
  499. for (let i = 0; i < deps.length; i++) {
  500. const dep = deps[i];
  501. if (wasTracked(dep) && !newTracked(dep)) {
  502. dep.delete(effect);
  503. }
  504. else {
  505. deps[ptr++] = dep;
  506. }
  507. // clear bits
  508. dep.w &= ~trackOpBit;
  509. dep.n &= ~trackOpBit;
  510. }
  511. deps.length = ptr;
  512. }
  513. };
  514. const targetMap = new WeakMap();
  515. // The number of effects currently being tracked recursively.
  516. let effectTrackDepth = 0;
  517. let trackOpBit = 1;
  518. /**
  519. * The bitwise track markers support at most 30 levels of recursion.
  520. * This value is chosen to enable modern JS engines to use a SMI on all platforms.
  521. * When recursion depth is greater, fall back to using a full cleanup.
  522. */
  523. const maxMarkerBits = 30;
  524. const effectStack = [];
  525. let activeEffect;
  526. const ITERATE_KEY = Symbol('iterate' );
  527. const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
  528. class ReactiveEffect {
  529. constructor(fn, scheduler = null, scope) {
  530. this.fn = fn;
  531. this.scheduler = scheduler;
  532. this.active = true;
  533. this.deps = [];
  534. recordEffectScope(this, scope);
  535. }
  536. run() {
  537. if (!this.active) {
  538. return this.fn();
  539. }
  540. if (!effectStack.includes(this)) {
  541. try {
  542. effectStack.push((activeEffect = this));
  543. enableTracking();
  544. trackOpBit = 1 << ++effectTrackDepth;
  545. if (effectTrackDepth <= maxMarkerBits) {
  546. initDepMarkers(this);
  547. }
  548. else {
  549. cleanupEffect(this);
  550. }
  551. return this.fn();
  552. }
  553. finally {
  554. if (effectTrackDepth <= maxMarkerBits) {
  555. finalizeDepMarkers(this);
  556. }
  557. trackOpBit = 1 << --effectTrackDepth;
  558. resetTracking();
  559. effectStack.pop();
  560. const n = effectStack.length;
  561. activeEffect = n > 0 ? effectStack[n - 1] : undefined;
  562. }
  563. }
  564. }
  565. stop() {
  566. if (this.active) {
  567. cleanupEffect(this);
  568. if (this.onStop) {
  569. this.onStop();
  570. }
  571. this.active = false;
  572. }
  573. }
  574. }
  575. function cleanupEffect(effect) {
  576. const { deps } = effect;
  577. if (deps.length) {
  578. for (let i = 0; i < deps.length; i++) {
  579. deps[i].delete(effect);
  580. }
  581. deps.length = 0;
  582. }
  583. }
  584. function effect(fn, options) {
  585. if (fn.effect) {
  586. fn = fn.effect.fn;
  587. }
  588. const _effect = new ReactiveEffect(fn);
  589. if (options) {
  590. extend(_effect, options);
  591. if (options.scope)
  592. recordEffectScope(_effect, options.scope);
  593. }
  594. if (!options || !options.lazy) {
  595. _effect.run();
  596. }
  597. const runner = _effect.run.bind(_effect);
  598. runner.effect = _effect;
  599. return runner;
  600. }
  601. function stop(runner) {
  602. runner.effect.stop();
  603. }
  604. let shouldTrack = true;
  605. const trackStack = [];
  606. function pauseTracking() {
  607. trackStack.push(shouldTrack);
  608. shouldTrack = false;
  609. }
  610. function enableTracking() {
  611. trackStack.push(shouldTrack);
  612. shouldTrack = true;
  613. }
  614. function resetTracking() {
  615. const last = trackStack.pop();
  616. shouldTrack = last === undefined ? true : last;
  617. }
  618. function track(target, type, key) {
  619. if (!isTracking()) {
  620. return;
  621. }
  622. let depsMap = targetMap.get(target);
  623. if (!depsMap) {
  624. targetMap.set(target, (depsMap = new Map()));
  625. }
  626. let dep = depsMap.get(key);
  627. if (!dep) {
  628. depsMap.set(key, (dep = createDep()));
  629. }
  630. const eventInfo = { effect: activeEffect, target, type, key }
  631. ;
  632. trackEffects(dep, eventInfo);
  633. }
  634. function isTracking() {
  635. return shouldTrack && activeEffect !== undefined;
  636. }
  637. function trackEffects(dep, debuggerEventExtraInfo) {
  638. let shouldTrack = false;
  639. if (effectTrackDepth <= maxMarkerBits) {
  640. if (!newTracked(dep)) {
  641. dep.n |= trackOpBit; // set newly tracked
  642. shouldTrack = !wasTracked(dep);
  643. }
  644. }
  645. else {
  646. // Full cleanup mode.
  647. shouldTrack = !dep.has(activeEffect);
  648. }
  649. if (shouldTrack) {
  650. dep.add(activeEffect);
  651. activeEffect.deps.push(dep);
  652. if (activeEffect.onTrack) {
  653. activeEffect.onTrack(Object.assign({
  654. effect: activeEffect
  655. }, debuggerEventExtraInfo));
  656. }
  657. }
  658. }
  659. function trigger(target, type, key, newValue, oldValue, oldTarget) {
  660. const depsMap = targetMap.get(target);
  661. if (!depsMap) {
  662. // never been tracked
  663. return;
  664. }
  665. let deps = [];
  666. if (type === "clear" /* CLEAR */) {
  667. // collection being cleared
  668. // trigger all effects for target
  669. deps = [...depsMap.values()];
  670. }
  671. else if (key === 'length' && isArray(target)) {
  672. depsMap.forEach((dep, key) => {
  673. if (key === 'length' || key >= newValue) {
  674. deps.push(dep);
  675. }
  676. });
  677. }
  678. else {
  679. // schedule runs for SET | ADD | DELETE
  680. if (key !== void 0) {
  681. deps.push(depsMap.get(key));
  682. }
  683. // also run for iteration key on ADD | DELETE | Map.SET
  684. switch (type) {
  685. case "add" /* ADD */:
  686. if (!isArray(target)) {
  687. deps.push(depsMap.get(ITERATE_KEY));
  688. if (isMap(target)) {
  689. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  690. }
  691. }
  692. else if (isIntegerKey(key)) {
  693. // new index added to array -> length changes
  694. deps.push(depsMap.get('length'));
  695. }
  696. break;
  697. case "delete" /* DELETE */:
  698. if (!isArray(target)) {
  699. deps.push(depsMap.get(ITERATE_KEY));
  700. if (isMap(target)) {
  701. deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
  702. }
  703. }
  704. break;
  705. case "set" /* SET */:
  706. if (isMap(target)) {
  707. deps.push(depsMap.get(ITERATE_KEY));
  708. }
  709. break;
  710. }
  711. }
  712. const eventInfo = { target, type, key, newValue, oldValue, oldTarget }
  713. ;
  714. if (deps.length === 1) {
  715. if (deps[0]) {
  716. {
  717. triggerEffects(deps[0], eventInfo);
  718. }
  719. }
  720. }
  721. else {
  722. const effects = [];
  723. for (const dep of deps) {
  724. if (dep) {
  725. effects.push(...dep);
  726. }
  727. }
  728. {
  729. triggerEffects(createDep(effects), eventInfo);
  730. }
  731. }
  732. }
  733. function triggerEffects(dep, debuggerEventExtraInfo) {
  734. // spread into array for stabilization
  735. for (const effect of isArray(dep) ? dep : [...dep]) {
  736. if (effect !== activeEffect || effect.allowRecurse) {
  737. if (effect.onTrigger) {
  738. effect.onTrigger(extend({ effect }, debuggerEventExtraInfo));
  739. }
  740. if (effect.scheduler) {
  741. effect.scheduler();
  742. }
  743. else {
  744. effect.run();
  745. }
  746. }
  747. }
  748. }
  749. const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
  750. const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
  751. .map(key => Symbol[key])
  752. .filter(isSymbol));
  753. const get = /*#__PURE__*/ createGetter();
  754. const shallowGet = /*#__PURE__*/ createGetter(false, true);
  755. const readonlyGet = /*#__PURE__*/ createGetter(true);
  756. const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
  757. const arrayInstrumentations = /*#__PURE__*/ createArrayInstrumentations();
  758. function createArrayInstrumentations() {
  759. const instrumentations = {};
  760. ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
  761. instrumentations[key] = function (...args) {
  762. const arr = toRaw(this);
  763. for (let i = 0, l = this.length; i < l; i++) {
  764. track(arr, "get" /* GET */, i + '');
  765. }
  766. // we run the method using the original args first (which may be reactive)
  767. const res = arr[key](...args);
  768. if (res === -1 || res === false) {
  769. // if that didn't work, run it again using raw values.
  770. return arr[key](...args.map(toRaw));
  771. }
  772. else {
  773. return res;
  774. }
  775. };
  776. });
  777. ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
  778. instrumentations[key] = function (...args) {
  779. pauseTracking();
  780. const res = toRaw(this)[key].apply(this, args);
  781. resetTracking();
  782. return res;
  783. };
  784. });
  785. return instrumentations;
  786. }
  787. function createGetter(isReadonly = false, shallow = false) {
  788. return function get(target, key, receiver) {
  789. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  790. return !isReadonly;
  791. }
  792. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  793. return isReadonly;
  794. }
  795. else if (key === "__v_raw" /* RAW */ &&
  796. receiver ===
  797. (isReadonly
  798. ? shallow
  799. ? shallowReadonlyMap
  800. : readonlyMap
  801. : shallow
  802. ? shallowReactiveMap
  803. : reactiveMap).get(target)) {
  804. return target;
  805. }
  806. const targetIsArray = isArray(target);
  807. if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
  808. return Reflect.get(arrayInstrumentations, key, receiver);
  809. }
  810. const res = Reflect.get(target, key, receiver);
  811. if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
  812. return res;
  813. }
  814. if (!isReadonly) {
  815. track(target, "get" /* GET */, key);
  816. }
  817. if (shallow) {
  818. return res;
  819. }
  820. if (isRef(res)) {
  821. // ref unwrapping - does not apply for Array + integer key.
  822. const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
  823. return shouldUnwrap ? res.value : res;
  824. }
  825. if (isObject(res)) {
  826. // Convert returned value into a proxy as well. we do the isObject check
  827. // here to avoid invalid value warning. Also need to lazy access readonly
  828. // and reactive here to avoid circular dependency.
  829. return isReadonly ? readonly(res) : reactive(res);
  830. }
  831. return res;
  832. };
  833. }
  834. const set = /*#__PURE__*/ createSetter();
  835. const shallowSet = /*#__PURE__*/ createSetter(true);
  836. function createSetter(shallow = false) {
  837. return function set(target, key, value, receiver) {
  838. let oldValue = target[key];
  839. if (!shallow && !isReadonly(value)) {
  840. value = toRaw(value);
  841. oldValue = toRaw(oldValue);
  842. if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
  843. oldValue.value = value;
  844. return true;
  845. }
  846. }
  847. const hadKey = isArray(target) && isIntegerKey(key)
  848. ? Number(key) < target.length
  849. : hasOwn(target, key);
  850. const result = Reflect.set(target, key, value, receiver);
  851. // don't trigger if target is something up in the prototype chain of original
  852. if (target === toRaw(receiver)) {
  853. if (!hadKey) {
  854. trigger(target, "add" /* ADD */, key, value);
  855. }
  856. else if (hasChanged(value, oldValue)) {
  857. trigger(target, "set" /* SET */, key, value, oldValue);
  858. }
  859. }
  860. return result;
  861. };
  862. }
  863. function deleteProperty(target, key) {
  864. const hadKey = hasOwn(target, key);
  865. const oldValue = target[key];
  866. const result = Reflect.deleteProperty(target, key);
  867. if (result && hadKey) {
  868. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  869. }
  870. return result;
  871. }
  872. function has(target, key) {
  873. const result = Reflect.has(target, key);
  874. if (!isSymbol(key) || !builtInSymbols.has(key)) {
  875. track(target, "has" /* HAS */, key);
  876. }
  877. return result;
  878. }
  879. function ownKeys(target) {
  880. track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
  881. return Reflect.ownKeys(target);
  882. }
  883. const mutableHandlers = {
  884. get,
  885. set,
  886. deleteProperty,
  887. has,
  888. ownKeys
  889. };
  890. const readonlyHandlers = {
  891. get: readonlyGet,
  892. set(target, key) {
  893. {
  894. console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
  895. }
  896. return true;
  897. },
  898. deleteProperty(target, key) {
  899. {
  900. console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
  901. }
  902. return true;
  903. }
  904. };
  905. const shallowReactiveHandlers = /*#__PURE__*/ extend({}, mutableHandlers, {
  906. get: shallowGet,
  907. set: shallowSet
  908. });
  909. // Props handlers are special in the sense that it should not unwrap top-level
  910. // refs (in order to allow refs to be explicitly passed down), but should
  911. // retain the reactivity of the normal readonly object.
  912. const shallowReadonlyHandlers = /*#__PURE__*/ extend({}, readonlyHandlers, {
  913. get: shallowReadonlyGet
  914. });
  915. const toShallow = (value) => value;
  916. const getProto = (v) => Reflect.getPrototypeOf(v);
  917. function get$1(target, key, isReadonly = false, isShallow = false) {
  918. // #1772: readonly(reactive(Map)) should return readonly + reactive version
  919. // of the value
  920. target = target["__v_raw" /* RAW */];
  921. const rawTarget = toRaw(target);
  922. const rawKey = toRaw(key);
  923. if (key !== rawKey) {
  924. !isReadonly && track(rawTarget, "get" /* GET */, key);
  925. }
  926. !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
  927. const { has } = getProto(rawTarget);
  928. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  929. if (has.call(rawTarget, key)) {
  930. return wrap(target.get(key));
  931. }
  932. else if (has.call(rawTarget, rawKey)) {
  933. return wrap(target.get(rawKey));
  934. }
  935. else if (target !== rawTarget) {
  936. // #3602 readonly(reactive(Map))
  937. // ensure that the nested reactive `Map` can do tracking for itself
  938. target.get(key);
  939. }
  940. }
  941. function has$1(key, isReadonly = false) {
  942. const target = this["__v_raw" /* RAW */];
  943. const rawTarget = toRaw(target);
  944. const rawKey = toRaw(key);
  945. if (key !== rawKey) {
  946. !isReadonly && track(rawTarget, "has" /* HAS */, key);
  947. }
  948. !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
  949. return key === rawKey
  950. ? target.has(key)
  951. : target.has(key) || target.has(rawKey);
  952. }
  953. function size(target, isReadonly = false) {
  954. target = target["__v_raw" /* RAW */];
  955. !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
  956. return Reflect.get(target, 'size', target);
  957. }
  958. function add(value) {
  959. value = toRaw(value);
  960. const target = toRaw(this);
  961. const proto = getProto(target);
  962. const hadKey = proto.has.call(target, value);
  963. if (!hadKey) {
  964. target.add(value);
  965. trigger(target, "add" /* ADD */, value, value);
  966. }
  967. return this;
  968. }
  969. function set$1(key, value) {
  970. value = toRaw(value);
  971. const target = toRaw(this);
  972. const { has, get } = getProto(target);
  973. let hadKey = has.call(target, key);
  974. if (!hadKey) {
  975. key = toRaw(key);
  976. hadKey = has.call(target, key);
  977. }
  978. else {
  979. checkIdentityKeys(target, has, key);
  980. }
  981. const oldValue = get.call(target, key);
  982. target.set(key, value);
  983. if (!hadKey) {
  984. trigger(target, "add" /* ADD */, key, value);
  985. }
  986. else if (hasChanged(value, oldValue)) {
  987. trigger(target, "set" /* SET */, key, value, oldValue);
  988. }
  989. return this;
  990. }
  991. function deleteEntry(key) {
  992. const target = toRaw(this);
  993. const { has, get } = getProto(target);
  994. let hadKey = has.call(target, key);
  995. if (!hadKey) {
  996. key = toRaw(key);
  997. hadKey = has.call(target, key);
  998. }
  999. else {
  1000. checkIdentityKeys(target, has, key);
  1001. }
  1002. const oldValue = get ? get.call(target, key) : undefined;
  1003. // forward the operation before queueing reactions
  1004. const result = target.delete(key);
  1005. if (hadKey) {
  1006. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  1007. }
  1008. return result;
  1009. }
  1010. function clear() {
  1011. const target = toRaw(this);
  1012. const hadItems = target.size !== 0;
  1013. const oldTarget = isMap(target)
  1014. ? new Map(target)
  1015. : new Set(target)
  1016. ;
  1017. // forward the operation before queueing reactions
  1018. const result = target.clear();
  1019. if (hadItems) {
  1020. trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
  1021. }
  1022. return result;
  1023. }
  1024. function createForEach(isReadonly, isShallow) {
  1025. return function forEach(callback, thisArg) {
  1026. const observed = this;
  1027. const target = observed["__v_raw" /* RAW */];
  1028. const rawTarget = toRaw(target);
  1029. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  1030. !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
  1031. return target.forEach((value, key) => {
  1032. // important: make sure the callback is
  1033. // 1. invoked with the reactive map as `this` and 3rd arg
  1034. // 2. the value received should be a corresponding reactive/readonly.
  1035. return callback.call(thisArg, wrap(value), wrap(key), observed);
  1036. });
  1037. };
  1038. }
  1039. function createIterableMethod(method, isReadonly, isShallow) {
  1040. return function (...args) {
  1041. const target = this["__v_raw" /* RAW */];
  1042. const rawTarget = toRaw(target);
  1043. const targetIsMap = isMap(rawTarget);
  1044. const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
  1045. const isKeyOnly = method === 'keys' && targetIsMap;
  1046. const innerIterator = target[method](...args);
  1047. const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
  1048. !isReadonly &&
  1049. track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
  1050. // return a wrapped iterator which returns observed versions of the
  1051. // values emitted from the real iterator
  1052. return {
  1053. // iterator protocol
  1054. next() {
  1055. const { value, done } = innerIterator.next();
  1056. return done
  1057. ? { value, done }
  1058. : {
  1059. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  1060. done
  1061. };
  1062. },
  1063. // iterable protocol
  1064. [Symbol.iterator]() {
  1065. return this;
  1066. }
  1067. };
  1068. };
  1069. }
  1070. function createReadonlyMethod(type) {
  1071. return function (...args) {
  1072. {
  1073. const key = args[0] ? `on key "${args[0]}" ` : ``;
  1074. console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
  1075. }
  1076. return type === "delete" /* DELETE */ ? false : this;
  1077. };
  1078. }
  1079. function createInstrumentations() {
  1080. const mutableInstrumentations = {
  1081. get(key) {
  1082. return get$1(this, key);
  1083. },
  1084. get size() {
  1085. return size(this);
  1086. },
  1087. has: has$1,
  1088. add,
  1089. set: set$1,
  1090. delete: deleteEntry,
  1091. clear,
  1092. forEach: createForEach(false, false)
  1093. };
  1094. const shallowInstrumentations = {
  1095. get(key) {
  1096. return get$1(this, key, false, true);
  1097. },
  1098. get size() {
  1099. return size(this);
  1100. },
  1101. has: has$1,
  1102. add,
  1103. set: set$1,
  1104. delete: deleteEntry,
  1105. clear,
  1106. forEach: createForEach(false, true)
  1107. };
  1108. const readonlyInstrumentations = {
  1109. get(key) {
  1110. return get$1(this, key, true);
  1111. },
  1112. get size() {
  1113. return size(this, true);
  1114. },
  1115. has(key) {
  1116. return has$1.call(this, key, true);
  1117. },
  1118. add: createReadonlyMethod("add" /* ADD */),
  1119. set: createReadonlyMethod("set" /* SET */),
  1120. delete: createReadonlyMethod("delete" /* DELETE */),
  1121. clear: createReadonlyMethod("clear" /* CLEAR */),
  1122. forEach: createForEach(true, false)
  1123. };
  1124. const shallowReadonlyInstrumentations = {
  1125. get(key) {
  1126. return get$1(this, key, true, true);
  1127. },
  1128. get size() {
  1129. return size(this, true);
  1130. },
  1131. has(key) {
  1132. return has$1.call(this, key, true);
  1133. },
  1134. add: createReadonlyMethod("add" /* ADD */),
  1135. set: createReadonlyMethod("set" /* SET */),
  1136. delete: createReadonlyMethod("delete" /* DELETE */),
  1137. clear: createReadonlyMethod("clear" /* CLEAR */),
  1138. forEach: createForEach(true, true)
  1139. };
  1140. const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
  1141. iteratorMethods.forEach(method => {
  1142. mutableInstrumentations[method] = createIterableMethod(method, false, false);
  1143. readonlyInstrumentations[method] = createIterableMethod(method, true, false);
  1144. shallowInstrumentations[method] = createIterableMethod(method, false, true);
  1145. shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
  1146. });
  1147. return [
  1148. mutableInstrumentations,
  1149. readonlyInstrumentations,
  1150. shallowInstrumentations,
  1151. shallowReadonlyInstrumentations
  1152. ];
  1153. }
  1154. const [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/ createInstrumentations();
  1155. function createInstrumentationGetter(isReadonly, shallow) {
  1156. const instrumentations = shallow
  1157. ? isReadonly
  1158. ? shallowReadonlyInstrumentations
  1159. : shallowInstrumentations
  1160. : isReadonly
  1161. ? readonlyInstrumentations
  1162. : mutableInstrumentations;
  1163. return (target, key, receiver) => {
  1164. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  1165. return !isReadonly;
  1166. }
  1167. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  1168. return isReadonly;
  1169. }
  1170. else if (key === "__v_raw" /* RAW */) {
  1171. return target;
  1172. }
  1173. return Reflect.get(hasOwn(instrumentations, key) && key in target
  1174. ? instrumentations
  1175. : target, key, receiver);
  1176. };
  1177. }
  1178. const mutableCollectionHandlers = {
  1179. get: /*#__PURE__*/ createInstrumentationGetter(false, false)
  1180. };
  1181. const shallowCollectionHandlers = {
  1182. get: /*#__PURE__*/ createInstrumentationGetter(false, true)
  1183. };
  1184. const readonlyCollectionHandlers = {
  1185. get: /*#__PURE__*/ createInstrumentationGetter(true, false)
  1186. };
  1187. const shallowReadonlyCollectionHandlers = {
  1188. get: /*#__PURE__*/ createInstrumentationGetter(true, true)
  1189. };
  1190. function checkIdentityKeys(target, has, key) {
  1191. const rawKey = toRaw(key);
  1192. if (rawKey !== key && has.call(target, rawKey)) {
  1193. const type = toRawType(target);
  1194. console.warn(`Reactive ${type} contains both the raw and reactive ` +
  1195. `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
  1196. `which can lead to inconsistencies. ` +
  1197. `Avoid differentiating between the raw and reactive versions ` +
  1198. `of an object and only use the reactive version if possible.`);
  1199. }
  1200. }
  1201. const reactiveMap = new WeakMap();
  1202. const shallowReactiveMap = new WeakMap();
  1203. const readonlyMap = new WeakMap();
  1204. const shallowReadonlyMap = new WeakMap();
  1205. function targetTypeMap(rawType) {
  1206. switch (rawType) {
  1207. case 'Object':
  1208. case 'Array':
  1209. return 1 /* COMMON */;
  1210. case 'Map':
  1211. case 'Set':
  1212. case 'WeakMap':
  1213. case 'WeakSet':
  1214. return 2 /* COLLECTION */;
  1215. default:
  1216. return 0 /* INVALID */;
  1217. }
  1218. }
  1219. function getTargetType(value) {
  1220. return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
  1221. ? 0 /* INVALID */
  1222. : targetTypeMap(toRawType(value));
  1223. }
  1224. function reactive(target) {
  1225. // if trying to observe a readonly proxy, return the readonly version.
  1226. if (target && target["__v_isReadonly" /* IS_READONLY */]) {
  1227. return target;
  1228. }
  1229. return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
  1230. }
  1231. /**
  1232. * Return a shallowly-reactive copy of the original object, where only the root
  1233. * level properties are reactive. It also does not auto-unwrap refs (even at the
  1234. * root level).
  1235. */
  1236. function shallowReactive(target) {
  1237. return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
  1238. }
  1239. /**
  1240. * Creates a readonly copy of the original object. Note the returned copy is not
  1241. * made reactive, but `readonly` can be called on an already reactive object.
  1242. */
  1243. function readonly(target) {
  1244. return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
  1245. }
  1246. /**
  1247. * Returns a reactive-copy of the original object, where only the root level
  1248. * properties are readonly, and does NOT unwrap refs nor recursively convert
  1249. * returned properties.
  1250. * This is used for creating the props proxy object for stateful components.
  1251. */
  1252. function shallowReadonly(target) {
  1253. return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
  1254. }
  1255. function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
  1256. if (!isObject(target)) {
  1257. {
  1258. console.warn(`value cannot be made reactive: ${String(target)}`);
  1259. }
  1260. return target;
  1261. }
  1262. // target is already a Proxy, return it.
  1263. // exception: calling readonly() on a reactive object
  1264. if (target["__v_raw" /* RAW */] &&
  1265. !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
  1266. return target;
  1267. }
  1268. // target already has corresponding Proxy
  1269. const existingProxy = proxyMap.get(target);
  1270. if (existingProxy) {
  1271. return existingProxy;
  1272. }
  1273. // only a whitelist of value types can be observed.
  1274. const targetType = getTargetType(target);
  1275. if (targetType === 0 /* INVALID */) {
  1276. return target;
  1277. }
  1278. const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
  1279. proxyMap.set(target, proxy);
  1280. return proxy;
  1281. }
  1282. function isReactive(value) {
  1283. if (isReadonly(value)) {
  1284. return isReactive(value["__v_raw" /* RAW */]);
  1285. }
  1286. return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
  1287. }
  1288. function isReadonly(value) {
  1289. return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
  1290. }
  1291. function isProxy(value) {
  1292. return isReactive(value) || isReadonly(value);
  1293. }
  1294. function toRaw(observed) {
  1295. const raw = observed && observed["__v_raw" /* RAW */];
  1296. return raw ? toRaw(raw) : observed;
  1297. }
  1298. function markRaw(value) {
  1299. def(value, "__v_skip" /* SKIP */, true);
  1300. return value;
  1301. }
  1302. const toReactive = (value) => isObject(value) ? reactive(value) : value;
  1303. const toReadonly = (value) => isObject(value) ? readonly(value) : value;
  1304. function trackRefValue(ref) {
  1305. if (isTracking()) {
  1306. ref = toRaw(ref);
  1307. if (!ref.dep) {
  1308. ref.dep = createDep();
  1309. }
  1310. {
  1311. trackEffects(ref.dep, {
  1312. target: ref,
  1313. type: "get" /* GET */,
  1314. key: 'value'
  1315. });
  1316. }
  1317. }
  1318. }
  1319. function triggerRefValue(ref, newVal) {
  1320. ref = toRaw(ref);
  1321. if (ref.dep) {
  1322. {
  1323. triggerEffects(ref.dep, {
  1324. target: ref,
  1325. type: "set" /* SET */,
  1326. key: 'value',
  1327. newValue: newVal
  1328. });
  1329. }
  1330. }
  1331. }
  1332. function isRef(r) {
  1333. return Boolean(r && r.__v_isRef === true);
  1334. }
  1335. function ref(value) {
  1336. return createRef(value, false);
  1337. }
  1338. function shallowRef(value) {
  1339. return createRef(value, true);
  1340. }
  1341. function createRef(rawValue, shallow) {
  1342. if (isRef(rawValue)) {
  1343. return rawValue;
  1344. }
  1345. return new RefImpl(rawValue, shallow);
  1346. }
  1347. class RefImpl {
  1348. constructor(value, _shallow) {
  1349. this._shallow = _shallow;
  1350. this.dep = undefined;
  1351. this.__v_isRef = true;
  1352. this._rawValue = _shallow ? value : toRaw(value);
  1353. this._value = _shallow ? value : toReactive(value);
  1354. }
  1355. get value() {
  1356. trackRefValue(this);
  1357. return this._value;
  1358. }
  1359. set value(newVal) {
  1360. newVal = this._shallow ? newVal : toRaw(newVal);
  1361. if (hasChanged(newVal, this._rawValue)) {
  1362. this._rawValue = newVal;
  1363. this._value = this._shallow ? newVal : toReactive(newVal);
  1364. triggerRefValue(this, newVal);
  1365. }
  1366. }
  1367. }
  1368. function triggerRef(ref) {
  1369. triggerRefValue(ref, ref.value );
  1370. }
  1371. function unref(ref) {
  1372. return isRef(ref) ? ref.value : ref;
  1373. }
  1374. const shallowUnwrapHandlers = {
  1375. get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  1376. set: (target, key, value, receiver) => {
  1377. const oldValue = target[key];
  1378. if (isRef(oldValue) && !isRef(value)) {
  1379. oldValue.value = value;
  1380. return true;
  1381. }
  1382. else {
  1383. return Reflect.set(target, key, value, receiver);
  1384. }
  1385. }
  1386. };
  1387. function proxyRefs(objectWithRefs) {
  1388. return isReactive(objectWithRefs)
  1389. ? objectWithRefs
  1390. : new Proxy(objectWithRefs, shallowUnwrapHandlers);
  1391. }
  1392. class CustomRefImpl {
  1393. constructor(factory) {
  1394. this.dep = undefined;
  1395. this.__v_isRef = true;
  1396. const { get, set } = factory(() => trackRefValue(this), () => triggerRefValue(this));
  1397. this._get = get;
  1398. this._set = set;
  1399. }
  1400. get value() {
  1401. return this._get();
  1402. }
  1403. set value(newVal) {
  1404. this._set(newVal);
  1405. }
  1406. }
  1407. function customRef(factory) {
  1408. return new CustomRefImpl(factory);
  1409. }
  1410. function toRefs(object) {
  1411. if (!isProxy(object)) {
  1412. console.warn(`toRefs() expects a reactive object but received a plain one.`);
  1413. }
  1414. const ret = isArray(object) ? new Array(object.length) : {};
  1415. for (const key in object) {
  1416. ret[key] = toRef(object, key);
  1417. }
  1418. return ret;
  1419. }
  1420. class ObjectRefImpl {
  1421. constructor(_object, _key, _defaultValue) {
  1422. this._object = _object;
  1423. this._key = _key;
  1424. this._defaultValue = _defaultValue;
  1425. this.__v_isRef = true;
  1426. }
  1427. get value() {
  1428. const val = this._object[this._key];
  1429. return val === undefined ? this._defaultValue : val;
  1430. }
  1431. set value(newVal) {
  1432. this._object[this._key] = newVal;
  1433. }
  1434. }
  1435. function toRef(object, key, defaultValue) {
  1436. const val = object[key];
  1437. return isRef(val)
  1438. ? val
  1439. : new ObjectRefImpl(object, key, defaultValue);
  1440. }
  1441. class ComputedRefImpl {
  1442. constructor(getter, _setter, isReadonly) {
  1443. this._setter = _setter;
  1444. this.dep = undefined;
  1445. this._dirty = true;
  1446. this.__v_isRef = true;
  1447. this.effect = new ReactiveEffect(getter, () => {
  1448. if (!this._dirty) {
  1449. this._dirty = true;
  1450. triggerRefValue(this);
  1451. }
  1452. });
  1453. this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
  1454. }
  1455. get value() {
  1456. // the computed ref may get wrapped by other proxies e.g. readonly() #3376
  1457. const self = toRaw(this);
  1458. trackRefValue(self);
  1459. if (self._dirty) {
  1460. self._dirty = false;
  1461. self._value = self.effect.run();
  1462. }
  1463. return self._value;
  1464. }
  1465. set value(newValue) {
  1466. this._setter(newValue);
  1467. }
  1468. }
  1469. function computed(getterOrOptions, debugOptions) {
  1470. let getter;
  1471. let setter;
  1472. const onlyGetter = isFunction(getterOrOptions);
  1473. if (onlyGetter) {
  1474. getter = getterOrOptions;
  1475. setter = () => {
  1476. console.warn('Write operation failed: computed value is readonly');
  1477. }
  1478. ;
  1479. }
  1480. else {
  1481. getter = getterOrOptions.get;
  1482. setter = getterOrOptions.set;
  1483. }
  1484. const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter);
  1485. if (debugOptions) {
  1486. cRef.effect.onTrack = debugOptions.onTrack;
  1487. cRef.effect.onTrigger = debugOptions.onTrigger;
  1488. }
  1489. return cRef;
  1490. }
  1491. /* eslint-disable no-restricted-globals */
  1492. let isHmrUpdating = false;
  1493. const hmrDirtyComponents = new Set();
  1494. // Expose the HMR runtime on the global object
  1495. // This makes it entirely tree-shakable without polluting the exports and makes
  1496. // it easier to be used in toolings like vue-loader
  1497. // Note: for a component to be eligible for HMR it also needs the __hmrId option
  1498. // to be set so that its instances can be registered / removed.
  1499. {
  1500. getGlobalThis().__VUE_HMR_RUNTIME__ = {
  1501. createRecord: tryWrap(createRecord),
  1502. rerender: tryWrap(rerender),
  1503. reload: tryWrap(reload)
  1504. };
  1505. }
  1506. const map = new Map();
  1507. function registerHMR(instance) {
  1508. const id = instance.type.__hmrId;
  1509. let record = map.get(id);
  1510. if (!record) {
  1511. createRecord(id, instance.type);
  1512. record = map.get(id);
  1513. }
  1514. record.instances.add(instance);
  1515. }
  1516. function unregisterHMR(instance) {
  1517. map.get(instance.type.__hmrId).instances.delete(instance);
  1518. }
  1519. function createRecord(id, initialDef) {
  1520. if (map.has(id)) {
  1521. return false;
  1522. }
  1523. map.set(id, {
  1524. initialDef: normalizeClassComponent(initialDef),
  1525. instances: new Set()
  1526. });
  1527. return true;
  1528. }
  1529. function normalizeClassComponent(component) {
  1530. return isClassComponent(component) ? component.__vccOpts : component;
  1531. }
  1532. function rerender(id, newRender) {
  1533. const record = map.get(id);
  1534. if (!record) {
  1535. return;
  1536. }
  1537. // update initial record (for not-yet-rendered component)
  1538. record.initialDef.render = newRender;
  1539. [...record.instances].forEach(instance => {
  1540. if (newRender) {
  1541. instance.render = newRender;
  1542. normalizeClassComponent(instance.type).render = newRender;
  1543. }
  1544. instance.renderCache = [];
  1545. // this flag forces child components with slot content to update
  1546. isHmrUpdating = true;
  1547. instance.update();
  1548. isHmrUpdating = false;
  1549. });
  1550. }
  1551. function reload(id, newComp) {
  1552. const record = map.get(id);
  1553. if (!record)
  1554. return;
  1555. newComp = normalizeClassComponent(newComp);
  1556. // update initial def (for not-yet-rendered components)
  1557. updateComponentDef(record.initialDef, newComp);
  1558. // create a snapshot which avoids the set being mutated during updates
  1559. const instances = [...record.instances];
  1560. for (const instance of instances) {
  1561. const oldComp = normalizeClassComponent(instance.type);
  1562. if (!hmrDirtyComponents.has(oldComp)) {
  1563. // 1. Update existing comp definition to match new one
  1564. if (oldComp !== record.initialDef) {
  1565. updateComponentDef(oldComp, newComp);
  1566. }
  1567. // 2. mark definition dirty. This forces the renderer to replace the
  1568. // component on patch.
  1569. hmrDirtyComponents.add(oldComp);
  1570. }
  1571. // 3. invalidate options resolution cache
  1572. instance.appContext.optionsCache.delete(instance.type);
  1573. // 4. actually update
  1574. if (instance.ceReload) {
  1575. // custom element
  1576. hmrDirtyComponents.add(oldComp);
  1577. instance.ceReload(newComp.styles);
  1578. hmrDirtyComponents.delete(oldComp);
  1579. }
  1580. else if (instance.parent) {
  1581. // 4. Force the parent instance to re-render. This will cause all updated
  1582. // components to be unmounted and re-mounted. Queue the update so that we
  1583. // don't end up forcing the same parent to re-render multiple times.
  1584. queueJob(instance.parent.update);
  1585. // instance is the inner component of an async custom element
  1586. // invoke to reset styles
  1587. if (instance.parent.type.__asyncLoader &&
  1588. instance.parent.ceReload) {
  1589. instance.parent.ceReload(newComp.styles);
  1590. }
  1591. }
  1592. else if (instance.appContext.reload) {
  1593. // root instance mounted via createApp() has a reload method
  1594. instance.appContext.reload();
  1595. }
  1596. else if (typeof window !== 'undefined') {
  1597. // root instance inside tree created via raw render(). Force reload.
  1598. window.location.reload();
  1599. }
  1600. else {
  1601. console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
  1602. }
  1603. }
  1604. // 5. make sure to cleanup dirty hmr components after update
  1605. queuePostFlushCb(() => {
  1606. for (const instance of instances) {
  1607. hmrDirtyComponents.delete(normalizeClassComponent(instance.type));
  1608. }
  1609. });
  1610. }
  1611. function updateComponentDef(oldComp, newComp) {
  1612. extend(oldComp, newComp);
  1613. for (const key in oldComp) {
  1614. if (key !== '__file' && !(key in newComp)) {
  1615. delete oldComp[key];
  1616. }
  1617. }
  1618. }
  1619. function tryWrap(fn) {
  1620. return (id, arg) => {
  1621. try {
  1622. return fn(id, arg);
  1623. }
  1624. catch (e) {
  1625. console.error(e);
  1626. console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
  1627. `Full reload required.`);
  1628. }
  1629. };
  1630. }
  1631. let devtools;
  1632. let buffer = [];
  1633. let devtoolsNotInstalled = false;
  1634. function emit(event, ...args) {
  1635. if (devtools) {
  1636. devtools.emit(event, ...args);
  1637. }
  1638. else if (!devtoolsNotInstalled) {
  1639. buffer.push({ event, args });
  1640. }
  1641. }
  1642. function setDevtoolsHook(hook, target) {
  1643. var _a, _b;
  1644. devtools = hook;
  1645. if (devtools) {
  1646. devtools.enabled = true;
  1647. buffer.forEach(({ event, args }) => devtools.emit(event, ...args));
  1648. buffer = [];
  1649. }
  1650. else if (
  1651. // handle late devtools injection - only do this if we are in an actual
  1652. // browser environment to avoid the timer handle stalling test runner exit
  1653. // (#4815)
  1654. // eslint-disable-next-line no-restricted-globals
  1655. typeof window !== 'undefined' &&
  1656. // some envs mock window but not fully
  1657. window.HTMLElement &&
  1658. // also exclude jsdom
  1659. !((_b = (_a = window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent) === null || _b === void 0 ? void 0 : _b.includes('jsdom'))) {
  1660. const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ =
  1661. target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []);
  1662. replay.push((newHook) => {
  1663. setDevtoolsHook(newHook, target);
  1664. });
  1665. // clear buffer after 3s - the user probably doesn't have devtools installed
  1666. // at all, and keeping the buffer will cause memory leaks (#4738)
  1667. setTimeout(() => {
  1668. if (!devtools) {
  1669. target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null;
  1670. devtoolsNotInstalled = true;
  1671. buffer = [];
  1672. }
  1673. }, 3000);
  1674. }
  1675. else {
  1676. // non-browser env, assume not installed
  1677. devtoolsNotInstalled = true;
  1678. buffer = [];
  1679. }
  1680. }
  1681. function devtoolsInitApp(app, version) {
  1682. emit("app:init" /* APP_INIT */, app, version, {
  1683. Fragment,
  1684. Text,
  1685. Comment,
  1686. Static
  1687. });
  1688. }
  1689. function devtoolsUnmountApp(app) {
  1690. emit("app:unmount" /* APP_UNMOUNT */, app);
  1691. }
  1692. const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
  1693. const devtoolsComponentUpdated =
  1694. /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
  1695. const devtoolsComponentRemoved =
  1696. /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
  1697. function createDevtoolsComponentHook(hook) {
  1698. return (component) => {
  1699. emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
  1700. };
  1701. }
  1702. const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
  1703. const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
  1704. function createDevtoolsPerformanceHook(hook) {
  1705. return (component, type, time) => {
  1706. emit(hook, component.appContext.app, component.uid, component, type, time);
  1707. };
  1708. }
  1709. function devtoolsComponentEmit(component, event, params) {
  1710. emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
  1711. }
  1712. function emit$1(instance, event, ...rawArgs) {
  1713. const props = instance.vnode.props || EMPTY_OBJ;
  1714. {
  1715. const { emitsOptions, propsOptions: [propsOptions] } = instance;
  1716. if (emitsOptions) {
  1717. if (!(event in emitsOptions) &&
  1718. !(false )) {
  1719. if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
  1720. warn$1(`Component emitted event "${event}" but it is neither declared in ` +
  1721. `the emits option nor as an "${toHandlerKey(event)}" prop.`);
  1722. }
  1723. }
  1724. else {
  1725. const validator = emitsOptions[event];
  1726. if (isFunction(validator)) {
  1727. const isValid = validator(...rawArgs);
  1728. if (!isValid) {
  1729. warn$1(`Invalid event arguments: event validation failed for event "${event}".`);
  1730. }
  1731. }
  1732. }
  1733. }
  1734. }
  1735. let args = rawArgs;
  1736. const isModelListener = event.startsWith('update:');
  1737. // for v-model update:xxx events, apply modifiers on args
  1738. const modelArg = isModelListener && event.slice(7);
  1739. if (modelArg && modelArg in props) {
  1740. const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
  1741. const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
  1742. if (trim) {
  1743. args = rawArgs.map(a => a.trim());
  1744. }
  1745. else if (number) {
  1746. args = rawArgs.map(toNumber);
  1747. }
  1748. }
  1749. {
  1750. devtoolsComponentEmit(instance, event, args);
  1751. }
  1752. {
  1753. const lowerCaseEvent = event.toLowerCase();
  1754. if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
  1755. warn$1(`Event "${lowerCaseEvent}" is emitted in component ` +
  1756. `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
  1757. `Note that HTML attributes are case-insensitive and you cannot use ` +
  1758. `v-on to listen to camelCase events when using in-DOM templates. ` +
  1759. `You should probably use "${hyphenate(event)}" instead of "${event}".`);
  1760. }
  1761. }
  1762. let handlerName;
  1763. let handler = props[(handlerName = toHandlerKey(event))] ||
  1764. // also try camelCase event handler (#2249)
  1765. props[(handlerName = toHandlerKey(camelize(event)))];
  1766. // for v-model update:xxx events, also trigger kebab-case equivalent
  1767. // for props passed via kebab-case
  1768. if (!handler && isModelListener) {
  1769. handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
  1770. }
  1771. if (handler) {
  1772. callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
  1773. }
  1774. const onceHandler = props[handlerName + `Once`];
  1775. if (onceHandler) {
  1776. if (!instance.emitted) {
  1777. instance.emitted = {};
  1778. }
  1779. else if (instance.emitted[handlerName]) {
  1780. return;
  1781. }
  1782. instance.emitted[handlerName] = true;
  1783. callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
  1784. }
  1785. }
  1786. function normalizeEmitsOptions(comp, appContext, asMixin = false) {
  1787. const cache = appContext.emitsCache;
  1788. const cached = cache.get(comp);
  1789. if (cached !== undefined) {
  1790. return cached;
  1791. }
  1792. const raw = comp.emits;
  1793. let normalized = {};
  1794. // apply mixin/extends props
  1795. let hasExtends = false;
  1796. if (!isFunction(comp)) {
  1797. const extendEmits = (raw) => {
  1798. const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
  1799. if (normalizedFromExtend) {
  1800. hasExtends = true;
  1801. extend(normalized, normalizedFromExtend);
  1802. }
  1803. };
  1804. if (!asMixin && appContext.mixins.length) {
  1805. appContext.mixins.forEach(extendEmits);
  1806. }
  1807. if (comp.extends) {
  1808. extendEmits(comp.extends);
  1809. }
  1810. if (comp.mixins) {
  1811. comp.mixins.forEach(extendEmits);
  1812. }
  1813. }
  1814. if (!raw && !hasExtends) {
  1815. cache.set(comp, null);
  1816. return null;
  1817. }
  1818. if (isArray(raw)) {
  1819. raw.forEach(key => (normalized[key] = null));
  1820. }
  1821. else {
  1822. extend(normalized, raw);
  1823. }
  1824. cache.set(comp, normalized);
  1825. return normalized;
  1826. }
  1827. // Check if an incoming prop key is a declared emit event listener.
  1828. // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
  1829. // both considered matched listeners.
  1830. function isEmitListener(options, key) {
  1831. if (!options || !isOn(key)) {
  1832. return false;
  1833. }
  1834. key = key.slice(2).replace(/Once$/, '');
  1835. return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
  1836. hasOwn(options, hyphenate(key)) ||
  1837. hasOwn(options, key));
  1838. }
  1839. /**
  1840. * mark the current rendering instance for asset resolution (e.g.
  1841. * resolveComponent, resolveDirective) during render
  1842. */
  1843. let currentRenderingInstance = null;
  1844. let currentScopeId = null;
  1845. /**
  1846. * Note: rendering calls maybe nested. The function returns the parent rendering
  1847. * instance if present, which should be restored after the render is done:
  1848. *
  1849. * ```js
  1850. * const prev = setCurrentRenderingInstance(i)
  1851. * // ...render
  1852. * setCurrentRenderingInstance(prev)
  1853. * ```
  1854. */
  1855. function setCurrentRenderingInstance(instance) {
  1856. const prev = currentRenderingInstance;
  1857. currentRenderingInstance = instance;
  1858. currentScopeId = (instance && instance.type.__scopeId) || null;
  1859. return prev;
  1860. }
  1861. /**
  1862. * Set scope id when creating hoisted vnodes.
  1863. * @private compiler helper
  1864. */
  1865. function pushScopeId(id) {
  1866. currentScopeId = id;
  1867. }
  1868. /**
  1869. * Technically we no longer need this after 3.0.8 but we need to keep the same
  1870. * API for backwards compat w/ code generated by compilers.
  1871. * @private
  1872. */
  1873. function popScopeId() {
  1874. currentScopeId = null;
  1875. }
  1876. /**
  1877. * Only for backwards compat
  1878. * @private
  1879. */
  1880. const withScopeId = (_id) => withCtx;
  1881. /**
  1882. * Wrap a slot function to memoize current rendering instance
  1883. * @private compiler helper
  1884. */
  1885. function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
  1886. ) {
  1887. if (!ctx)
  1888. return fn;
  1889. // already normalized
  1890. if (fn._n) {
  1891. return fn;
  1892. }
  1893. const renderFnWithContext = (...args) => {
  1894. // If a user calls a compiled slot inside a template expression (#1745), it
  1895. // can mess up block tracking, so by default we disable block tracking and
  1896. // force bail out when invoking a compiled slot (indicated by the ._d flag).
  1897. // This isn't necessary if rendering a compiled `<slot>`, so we flip the
  1898. // ._d flag off when invoking the wrapped fn inside `renderSlot`.
  1899. if (renderFnWithContext._d) {
  1900. setBlockTracking(-1);
  1901. }
  1902. const prevInstance = setCurrentRenderingInstance(ctx);
  1903. const res = fn(...args);
  1904. setCurrentRenderingInstance(prevInstance);
  1905. if (renderFnWithContext._d) {
  1906. setBlockTracking(1);
  1907. }
  1908. {
  1909. devtoolsComponentUpdated(ctx);
  1910. }
  1911. return res;
  1912. };
  1913. // mark normalized to avoid duplicated wrapping
  1914. renderFnWithContext._n = true;
  1915. // mark this as compiled by default
  1916. // this is used in vnode.ts -> normalizeChildren() to set the slot
  1917. // rendering flag.
  1918. renderFnWithContext._c = true;
  1919. // disable block tracking by default
  1920. renderFnWithContext._d = true;
  1921. return renderFnWithContext;
  1922. }
  1923. /**
  1924. * dev only flag to track whether $attrs was used during render.
  1925. * If $attrs was used during render then the warning for failed attrs
  1926. * fallthrough can be suppressed.
  1927. */
  1928. let accessedAttrs = false;
  1929. function markAttrsAccessed() {
  1930. accessedAttrs = true;
  1931. }
  1932. function renderComponentRoot(instance) {
  1933. const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
  1934. let result;
  1935. let fallthroughAttrs;
  1936. const prev = setCurrentRenderingInstance(instance);
  1937. {
  1938. accessedAttrs = false;
  1939. }
  1940. try {
  1941. if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
  1942. // withProxy is a proxy with a different `has` trap only for
  1943. // runtime-compiled render functions using `with` block.
  1944. const proxyToUse = withProxy || proxy;
  1945. result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
  1946. fallthroughAttrs = attrs;
  1947. }
  1948. else {
  1949. // functional
  1950. const render = Component;
  1951. // in dev, mark attrs accessed if optional props (attrs === props)
  1952. if (true && attrs === props) {
  1953. markAttrsAccessed();
  1954. }
  1955. result = normalizeVNode(render.length > 1
  1956. ? render(props, true
  1957. ? {
  1958. get attrs() {
  1959. markAttrsAccessed();
  1960. return attrs;
  1961. },
  1962. slots,
  1963. emit
  1964. }
  1965. : { attrs, slots, emit })
  1966. : render(props, null /* we know it doesn't need it */));
  1967. fallthroughAttrs = Component.props
  1968. ? attrs
  1969. : getFunctionalFallthrough(attrs);
  1970. }
  1971. }
  1972. catch (err) {
  1973. blockStack.length = 0;
  1974. handleError(err, instance, 1 /* RENDER_FUNCTION */);
  1975. result = createVNode(Comment);
  1976. }
  1977. // attr merging
  1978. // in dev mode, comments are preserved, and it's possible for a template
  1979. // to have comments along side the root element which makes it a fragment
  1980. let root = result;
  1981. let setRoot = undefined;
  1982. if (result.patchFlag > 0 &&
  1983. result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
  1984. [root, setRoot] = getChildRoot(result);
  1985. }
  1986. if (fallthroughAttrs && inheritAttrs !== false) {
  1987. const keys = Object.keys(fallthroughAttrs);
  1988. const { shapeFlag } = root;
  1989. if (keys.length) {
  1990. if (shapeFlag & (1 /* ELEMENT */ | 6 /* COMPONENT */)) {
  1991. if (propsOptions && keys.some(isModelListener)) {
  1992. // If a v-model listener (onUpdate:xxx) has a corresponding declared
  1993. // prop, it indicates this component expects to handle v-model and
  1994. // it should not fallthrough.
  1995. // related: #1543, #1643, #1989
  1996. fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
  1997. }
  1998. root = cloneVNode(root, fallthroughAttrs);
  1999. }
  2000. else if (!accessedAttrs && root.type !== Comment) {
  2001. const allAttrs = Object.keys(attrs);
  2002. const eventAttrs = [];
  2003. const extraAttrs = [];
  2004. for (let i = 0, l = allAttrs.length; i < l; i++) {
  2005. const key = allAttrs[i];
  2006. if (isOn(key)) {
  2007. // ignore v-model handlers when they fail to fallthrough
  2008. if (!isModelListener(key)) {
  2009. // remove `on`, lowercase first letter to reflect event casing
  2010. // accurately
  2011. eventAttrs.push(key[2].toLowerCase() + key.slice(3));
  2012. }
  2013. }
  2014. else {
  2015. extraAttrs.push(key);
  2016. }
  2017. }
  2018. if (extraAttrs.length) {
  2019. warn$1(`Extraneous non-props attributes (` +
  2020. `${extraAttrs.join(', ')}) ` +
  2021. `were passed to component but could not be automatically inherited ` +
  2022. `because component renders fragment or text root nodes.`);
  2023. }
  2024. if (eventAttrs.length) {
  2025. warn$1(`Extraneous non-emits event listeners (` +
  2026. `${eventAttrs.join(', ')}) ` +
  2027. `were passed to component but could not be automatically inherited ` +
  2028. `because component renders fragment or text root nodes. ` +
  2029. `If the listener is intended to be a component custom event listener only, ` +
  2030. `declare it using the "emits" option.`);
  2031. }
  2032. }
  2033. }
  2034. }
  2035. // inherit directives
  2036. if (vnode.dirs) {
  2037. if (!isElementRoot(root)) {
  2038. warn$1(`Runtime directive used on component with non-element root node. ` +
  2039. `The directives will not function as intended.`);
  2040. }
  2041. root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
  2042. }
  2043. // inherit transition data
  2044. if (vnode.transition) {
  2045. if (!isElementRoot(root)) {
  2046. warn$1(`Component inside <Transition> renders non-element root node ` +
  2047. `that cannot be animated.`);
  2048. }
  2049. root.transition = vnode.transition;
  2050. }
  2051. if (setRoot) {
  2052. setRoot(root);
  2053. }
  2054. else {
  2055. result = root;
  2056. }
  2057. setCurrentRenderingInstance(prev);
  2058. return result;
  2059. }
  2060. /**
  2061. * dev only
  2062. * In dev mode, template root level comments are rendered, which turns the
  2063. * template into a fragment root, but we need to locate the single element
  2064. * root for attrs and scope id processing.
  2065. */
  2066. const getChildRoot = (vnode) => {
  2067. const rawChildren = vnode.children;
  2068. const dynamicChildren = vnode.dynamicChildren;
  2069. const childRoot = filterSingleRoot(rawChildren);
  2070. if (!childRoot) {
  2071. return [vnode, undefined];
  2072. }
  2073. const index = rawChildren.indexOf(childRoot);
  2074. const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
  2075. const setRoot = (updatedRoot) => {
  2076. rawChildren[index] = updatedRoot;
  2077. if (dynamicChildren) {
  2078. if (dynamicIndex > -1) {
  2079. dynamicChildren[dynamicIndex] = updatedRoot;
  2080. }
  2081. else if (updatedRoot.patchFlag > 0) {
  2082. vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
  2083. }
  2084. }
  2085. };
  2086. return [normalizeVNode(childRoot), setRoot];
  2087. };
  2088. function filterSingleRoot(children) {
  2089. let singleRoot;
  2090. for (let i = 0; i < children.length; i++) {
  2091. const child = children[i];
  2092. if (isVNode(child)) {
  2093. // ignore user comment
  2094. if (child.type !== Comment || child.children === 'v-if') {
  2095. if (singleRoot) {
  2096. // has more than 1 non-comment child, return now
  2097. return;
  2098. }
  2099. else {
  2100. singleRoot = child;
  2101. }
  2102. }
  2103. }
  2104. else {
  2105. return;
  2106. }
  2107. }
  2108. return singleRoot;
  2109. }
  2110. const getFunctionalFallthrough = (attrs) => {
  2111. let res;
  2112. for (const key in attrs) {
  2113. if (key === 'class' || key === 'style' || isOn(key)) {
  2114. (res || (res = {}))[key] = attrs[key];
  2115. }
  2116. }
  2117. return res;
  2118. };
  2119. const filterModelListeners = (attrs, props) => {
  2120. const res = {};
  2121. for (const key in attrs) {
  2122. if (!isModelListener(key) || !(key.slice(9) in props)) {
  2123. res[key] = attrs[key];
  2124. }
  2125. }
  2126. return res;
  2127. };
  2128. const isElementRoot = (vnode) => {
  2129. return (vnode.shapeFlag & (6 /* COMPONENT */ | 1 /* ELEMENT */) ||
  2130. vnode.type === Comment // potential v-if branch switch
  2131. );
  2132. };
  2133. function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
  2134. const { props: prevProps, children: prevChildren, component } = prevVNode;
  2135. const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
  2136. const emits = component.emitsOptions;
  2137. // Parent component's render function was hot-updated. Since this may have
  2138. // caused the child component's slots content to have changed, we need to
  2139. // force the child to update as well.
  2140. if ((prevChildren || nextChildren) && isHmrUpdating) {
  2141. return true;
  2142. }
  2143. // force child update for runtime directive or transition on component vnode.
  2144. if (nextVNode.dirs || nextVNode.transition) {
  2145. return true;
  2146. }
  2147. if (optimized && patchFlag >= 0) {
  2148. if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
  2149. // slot content that references values that might have changed,
  2150. // e.g. in a v-for
  2151. return true;
  2152. }
  2153. if (patchFlag & 16 /* FULL_PROPS */) {
  2154. if (!prevProps) {
  2155. return !!nextProps;
  2156. }
  2157. // presence of this flag indicates props are always non-null
  2158. return hasPropsChanged(prevProps, nextProps, emits);
  2159. }
  2160. else if (patchFlag & 8 /* PROPS */) {
  2161. const dynamicProps = nextVNode.dynamicProps;
  2162. for (let i = 0; i < dynamicProps.length; i++) {
  2163. const key = dynamicProps[i];
  2164. if (nextProps[key] !== prevProps[key] &&
  2165. !isEmitListener(emits, key)) {
  2166. return true;
  2167. }
  2168. }
  2169. }
  2170. }
  2171. else {
  2172. // this path is only taken by manually written render functions
  2173. // so presence of any children leads to a forced update
  2174. if (prevChildren || nextChildren) {
  2175. if (!nextChildren || !nextChildren.$stable) {
  2176. return true;
  2177. }
  2178. }
  2179. if (prevProps === nextProps) {
  2180. return false;
  2181. }
  2182. if (!prevProps) {
  2183. return !!nextProps;
  2184. }
  2185. if (!nextProps) {
  2186. return true;
  2187. }
  2188. return hasPropsChanged(prevProps, nextProps, emits);
  2189. }
  2190. return false;
  2191. }
  2192. function hasPropsChanged(prevProps, nextProps, emitsOptions) {
  2193. const nextKeys = Object.keys(nextProps);
  2194. if (nextKeys.length !== Object.keys(prevProps).length) {
  2195. return true;
  2196. }
  2197. for (let i = 0; i < nextKeys.length; i++) {
  2198. const key = nextKeys[i];
  2199. if (nextProps[key] !== prevProps[key] &&
  2200. !isEmitListener(emitsOptions, key)) {
  2201. return true;
  2202. }
  2203. }
  2204. return false;
  2205. }
  2206. function updateHOCHostEl({ vnode, parent }, el // HostNode
  2207. ) {
  2208. while (parent && parent.subTree === vnode) {
  2209. (vnode = parent.vnode).el = el;
  2210. parent = parent.parent;
  2211. }
  2212. }
  2213. const isSuspense = (type) => type.__isSuspense;
  2214. // Suspense exposes a component-like API, and is treated like a component
  2215. // in the compiler, but internally it's a special built-in type that hooks
  2216. // directly into the renderer.
  2217. const SuspenseImpl = {
  2218. name: 'Suspense',
  2219. // In order to make Suspense tree-shakable, we need to avoid importing it
  2220. // directly in the renderer. The renderer checks for the __isSuspense flag
  2221. // on a vnode's type and calls the `process` method, passing in renderer
  2222. // internals.
  2223. __isSuspense: true,
  2224. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
  2225. // platform-specific impl passed from renderer
  2226. rendererInternals) {
  2227. if (n1 == null) {
  2228. mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
  2229. }
  2230. else {
  2231. patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
  2232. }
  2233. },
  2234. hydrate: hydrateSuspense,
  2235. create: createSuspenseBoundary,
  2236. normalize: normalizeSuspenseChildren
  2237. };
  2238. // Force-casted public typing for h and TSX props inference
  2239. const Suspense = (SuspenseImpl );
  2240. function triggerEvent(vnode, name) {
  2241. const eventListener = vnode.props && vnode.props[name];
  2242. if (isFunction(eventListener)) {
  2243. eventListener();
  2244. }
  2245. }
  2246. function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
  2247. const { p: patch, o: { createElement } } = rendererInternals;
  2248. const hiddenContainer = createElement('div');
  2249. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
  2250. // start mounting the content subtree in an off-dom container
  2251. patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
  2252. // now check if we have encountered any async deps
  2253. if (suspense.deps > 0) {
  2254. // has async
  2255. // invoke @fallback event
  2256. triggerEvent(vnode, 'onPending');
  2257. triggerEvent(vnode, 'onFallback');
  2258. // mount the fallback tree
  2259. patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2260. isSVG, slotScopeIds);
  2261. setActiveBranch(suspense, vnode.ssFallback);
  2262. }
  2263. else {
  2264. // Suspense has no async deps. Just resolve.
  2265. suspense.resolve();
  2266. }
  2267. }
  2268. function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
  2269. const suspense = (n2.suspense = n1.suspense);
  2270. suspense.vnode = n2;
  2271. n2.el = n1.el;
  2272. const newBranch = n2.ssContent;
  2273. const newFallback = n2.ssFallback;
  2274. const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
  2275. if (pendingBranch) {
  2276. suspense.pendingBranch = newBranch;
  2277. if (isSameVNodeType(newBranch, pendingBranch)) {
  2278. // same root type but content may have changed.
  2279. patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2280. if (suspense.deps <= 0) {
  2281. suspense.resolve();
  2282. }
  2283. else if (isInFallback) {
  2284. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2285. isSVG, slotScopeIds, optimized);
  2286. setActiveBranch(suspense, newFallback);
  2287. }
  2288. }
  2289. else {
  2290. // toggled before pending tree is resolved
  2291. suspense.pendingId++;
  2292. if (isHydrating) {
  2293. // if toggled before hydration is finished, the current DOM tree is
  2294. // no longer valid. set it as the active branch so it will be unmounted
  2295. // when resolved
  2296. suspense.isHydrating = false;
  2297. suspense.activeBranch = pendingBranch;
  2298. }
  2299. else {
  2300. unmount(pendingBranch, parentComponent, suspense);
  2301. }
  2302. // increment pending ID. this is used to invalidate async callbacks
  2303. // reset suspense state
  2304. suspense.deps = 0;
  2305. // discard effects from pending branch
  2306. suspense.effects.length = 0;
  2307. // discard previous container
  2308. suspense.hiddenContainer = createElement('div');
  2309. if (isInFallback) {
  2310. // already in fallback state
  2311. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2312. if (suspense.deps <= 0) {
  2313. suspense.resolve();
  2314. }
  2315. else {
  2316. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2317. isSVG, slotScopeIds, optimized);
  2318. setActiveBranch(suspense, newFallback);
  2319. }
  2320. }
  2321. else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2322. // toggled "back" to current active branch
  2323. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2324. // force resolve
  2325. suspense.resolve(true);
  2326. }
  2327. else {
  2328. // switched to a 3rd branch
  2329. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2330. if (suspense.deps <= 0) {
  2331. suspense.resolve();
  2332. }
  2333. }
  2334. }
  2335. }
  2336. else {
  2337. if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2338. // root did not change, just normal patch
  2339. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2340. setActiveBranch(suspense, newBranch);
  2341. }
  2342. else {
  2343. // root node toggled
  2344. // invoke @pending event
  2345. triggerEvent(n2, 'onPending');
  2346. // mount pending branch in off-dom container
  2347. suspense.pendingBranch = newBranch;
  2348. suspense.pendingId++;
  2349. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
  2350. if (suspense.deps <= 0) {
  2351. // incoming branch has no async deps, resolve now.
  2352. suspense.resolve();
  2353. }
  2354. else {
  2355. const { timeout, pendingId } = suspense;
  2356. if (timeout > 0) {
  2357. setTimeout(() => {
  2358. if (suspense.pendingId === pendingId) {
  2359. suspense.fallback(newFallback);
  2360. }
  2361. }, timeout);
  2362. }
  2363. else if (timeout === 0) {
  2364. suspense.fallback(newFallback);
  2365. }
  2366. }
  2367. }
  2368. }
  2369. }
  2370. let hasWarned = false;
  2371. function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
  2372. /* istanbul ignore if */
  2373. if (!hasWarned) {
  2374. hasWarned = true;
  2375. // @ts-ignore `console.info` cannot be null error
  2376. console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
  2377. }
  2378. const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
  2379. const timeout = toNumber(vnode.props && vnode.props.timeout);
  2380. const suspense = {
  2381. vnode,
  2382. parent,
  2383. parentComponent,
  2384. isSVG,
  2385. container,
  2386. hiddenContainer,
  2387. anchor,
  2388. deps: 0,
  2389. pendingId: 0,
  2390. timeout: typeof timeout === 'number' ? timeout : -1,
  2391. activeBranch: null,
  2392. pendingBranch: null,
  2393. isInFallback: true,
  2394. isHydrating,
  2395. isUnmounted: false,
  2396. effects: [],
  2397. resolve(resume = false) {
  2398. {
  2399. if (!resume && !suspense.pendingBranch) {
  2400. throw new Error(`suspense.resolve() is called without a pending branch.`);
  2401. }
  2402. if (suspense.isUnmounted) {
  2403. throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
  2404. }
  2405. }
  2406. const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
  2407. if (suspense.isHydrating) {
  2408. suspense.isHydrating = false;
  2409. }
  2410. else if (!resume) {
  2411. const delayEnter = activeBranch &&
  2412. pendingBranch.transition &&
  2413. pendingBranch.transition.mode === 'out-in';
  2414. if (delayEnter) {
  2415. activeBranch.transition.afterLeave = () => {
  2416. if (pendingId === suspense.pendingId) {
  2417. move(pendingBranch, container, anchor, 0 /* ENTER */);
  2418. }
  2419. };
  2420. }
  2421. // this is initial anchor on mount
  2422. let { anchor } = suspense;
  2423. // unmount current active tree
  2424. if (activeBranch) {
  2425. // if the fallback tree was mounted, it may have been moved
  2426. // as part of a parent suspense. get the latest anchor for insertion
  2427. anchor = next(activeBranch);
  2428. unmount(activeBranch, parentComponent, suspense, true);
  2429. }
  2430. if (!delayEnter) {
  2431. // move content from off-dom container to actual container
  2432. move(pendingBranch, container, anchor, 0 /* ENTER */);
  2433. }
  2434. }
  2435. setActiveBranch(suspense, pendingBranch);
  2436. suspense.pendingBranch = null;
  2437. suspense.isInFallback = false;
  2438. // flush buffered effects
  2439. // check if there is a pending parent suspense
  2440. let parent = suspense.parent;
  2441. let hasUnresolvedAncestor = false;
  2442. while (parent) {
  2443. if (parent.pendingBranch) {
  2444. // found a pending parent suspense, merge buffered post jobs
  2445. // into that parent
  2446. parent.effects.push(...effects);
  2447. hasUnresolvedAncestor = true;
  2448. break;
  2449. }
  2450. parent = parent.parent;
  2451. }
  2452. // no pending parent suspense, flush all jobs
  2453. if (!hasUnresolvedAncestor) {
  2454. queuePostFlushCb(effects);
  2455. }
  2456. suspense.effects = [];
  2457. // invoke @resolve event
  2458. triggerEvent(vnode, 'onResolve');
  2459. },
  2460. fallback(fallbackVNode) {
  2461. if (!suspense.pendingBranch) {
  2462. return;
  2463. }
  2464. const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
  2465. // invoke @fallback event
  2466. triggerEvent(vnode, 'onFallback');
  2467. const anchor = next(activeBranch);
  2468. const mountFallback = () => {
  2469. if (!suspense.isInFallback) {
  2470. return;
  2471. }
  2472. // mount the fallback tree
  2473. patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2474. isSVG, slotScopeIds, optimized);
  2475. setActiveBranch(suspense, fallbackVNode);
  2476. };
  2477. const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
  2478. if (delayEnter) {
  2479. activeBranch.transition.afterLeave = mountFallback;
  2480. }
  2481. suspense.isInFallback = true;
  2482. // unmount current active branch
  2483. unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
  2484. true // shouldRemove
  2485. );
  2486. if (!delayEnter) {
  2487. mountFallback();
  2488. }
  2489. },
  2490. move(container, anchor, type) {
  2491. suspense.activeBranch &&
  2492. move(suspense.activeBranch, container, anchor, type);
  2493. suspense.container = container;
  2494. },
  2495. next() {
  2496. return suspense.activeBranch && next(suspense.activeBranch);
  2497. },
  2498. registerDep(instance, setupRenderEffect) {
  2499. const isInPendingSuspense = !!suspense.pendingBranch;
  2500. if (isInPendingSuspense) {
  2501. suspense.deps++;
  2502. }
  2503. const hydratedEl = instance.vnode.el;
  2504. instance
  2505. .asyncDep.catch(err => {
  2506. handleError(err, instance, 0 /* SETUP_FUNCTION */);
  2507. })
  2508. .then(asyncSetupResult => {
  2509. // retry when the setup() promise resolves.
  2510. // component may have been unmounted before resolve.
  2511. if (instance.isUnmounted ||
  2512. suspense.isUnmounted ||
  2513. suspense.pendingId !== instance.suspenseId) {
  2514. return;
  2515. }
  2516. // retry from this component
  2517. instance.asyncResolved = true;
  2518. const { vnode } = instance;
  2519. {
  2520. pushWarningContext(vnode);
  2521. }
  2522. handleSetupResult(instance, asyncSetupResult, false);
  2523. if (hydratedEl) {
  2524. // vnode may have been replaced if an update happened before the
  2525. // async dep is resolved.
  2526. vnode.el = hydratedEl;
  2527. }
  2528. const placeholder = !hydratedEl && instance.subTree.el;
  2529. setupRenderEffect(instance, vnode,
  2530. // component may have been moved before resolve.
  2531. // if this is not a hydration, instance.subTree will be the comment
  2532. // placeholder.
  2533. parentNode(hydratedEl || instance.subTree.el),
  2534. // anchor will not be used if this is hydration, so only need to
  2535. // consider the comment placeholder case.
  2536. hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
  2537. if (placeholder) {
  2538. remove(placeholder);
  2539. }
  2540. updateHOCHostEl(instance, vnode.el);
  2541. {
  2542. popWarningContext();
  2543. }
  2544. // only decrease deps count if suspense is not already resolved
  2545. if (isInPendingSuspense && --suspense.deps === 0) {
  2546. suspense.resolve();
  2547. }
  2548. });
  2549. },
  2550. unmount(parentSuspense, doRemove) {
  2551. suspense.isUnmounted = true;
  2552. if (suspense.activeBranch) {
  2553. unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
  2554. }
  2555. if (suspense.pendingBranch) {
  2556. unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
  2557. }
  2558. }
  2559. };
  2560. return suspense;
  2561. }
  2562. function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
  2563. /* eslint-disable no-restricted-globals */
  2564. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
  2565. // there are two possible scenarios for server-rendered suspense:
  2566. // - success: ssr content should be fully resolved
  2567. // - failure: ssr content should be the fallback branch.
  2568. // however, on the client we don't really know if it has failed or not
  2569. // attempt to hydrate the DOM assuming it has succeeded, but we still
  2570. // need to construct a suspense boundary first
  2571. const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
  2572. if (suspense.deps === 0) {
  2573. suspense.resolve();
  2574. }
  2575. return result;
  2576. /* eslint-enable no-restricted-globals */
  2577. }
  2578. function normalizeSuspenseChildren(vnode) {
  2579. const { shapeFlag, children } = vnode;
  2580. const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
  2581. vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
  2582. vnode.ssFallback = isSlotChildren
  2583. ? normalizeSuspenseSlot(children.fallback)
  2584. : createVNode(Comment);
  2585. }
  2586. function normalizeSuspenseSlot(s) {
  2587. let block;
  2588. if (isFunction(s)) {
  2589. const trackBlock = isBlockTreeEnabled && s._c;
  2590. if (trackBlock) {
  2591. // disableTracking: false
  2592. // allow block tracking for compiled slots
  2593. // (see ./componentRenderContext.ts)
  2594. s._d = false;
  2595. openBlock();
  2596. }
  2597. s = s();
  2598. if (trackBlock) {
  2599. s._d = true;
  2600. block = currentBlock;
  2601. closeBlock();
  2602. }
  2603. }
  2604. if (isArray(s)) {
  2605. const singleChild = filterSingleRoot(s);
  2606. if (!singleChild) {
  2607. warn$1(`<Suspense> slots expect a single root node.`);
  2608. }
  2609. s = singleChild;
  2610. }
  2611. s = normalizeVNode(s);
  2612. if (block && !s.dynamicChildren) {
  2613. s.dynamicChildren = block.filter(c => c !== s);
  2614. }
  2615. return s;
  2616. }
  2617. function queueEffectWithSuspense(fn, suspense) {
  2618. if (suspense && suspense.pendingBranch) {
  2619. if (isArray(fn)) {
  2620. suspense.effects.push(...fn);
  2621. }
  2622. else {
  2623. suspense.effects.push(fn);
  2624. }
  2625. }
  2626. else {
  2627. queuePostFlushCb(fn);
  2628. }
  2629. }
  2630. function setActiveBranch(suspense, branch) {
  2631. suspense.activeBranch = branch;
  2632. const { vnode, parentComponent } = suspense;
  2633. const el = (vnode.el = branch.el);
  2634. // in case suspense is the root node of a component,
  2635. // recursively update the HOC el
  2636. if (parentComponent && parentComponent.subTree === vnode) {
  2637. parentComponent.vnode.el = el;
  2638. updateHOCHostEl(parentComponent, el);
  2639. }
  2640. }
  2641. function provide(key, value) {
  2642. if (!currentInstance) {
  2643. {
  2644. warn$1(`provide() can only be used inside setup().`);
  2645. }
  2646. }
  2647. else {
  2648. let provides = currentInstance.provides;
  2649. // by default an instance inherits its parent's provides object
  2650. // but when it needs to provide values of its own, it creates its
  2651. // own provides object using parent provides object as prototype.
  2652. // this way in `inject` we can simply look up injections from direct
  2653. // parent and let the prototype chain do the work.
  2654. const parentProvides = currentInstance.parent && currentInstance.parent.provides;
  2655. if (parentProvides === provides) {
  2656. provides = currentInstance.provides = Object.create(parentProvides);
  2657. }
  2658. // TS doesn't allow symbol as index type
  2659. provides[key] = value;
  2660. }
  2661. }
  2662. function inject(key, defaultValue, treatDefaultAsFactory = false) {
  2663. // fallback to `currentRenderingInstance` so that this can be called in
  2664. // a functional component
  2665. const instance = currentInstance || currentRenderingInstance;
  2666. if (instance) {
  2667. // #2400
  2668. // to support `app.use` plugins,
  2669. // fallback to appContext's `provides` if the intance is at root
  2670. const provides = instance.parent == null
  2671. ? instance.vnode.appContext && instance.vnode.appContext.provides
  2672. : instance.parent.provides;
  2673. if (provides && key in provides) {
  2674. // TS doesn't allow symbol as index type
  2675. return provides[key];
  2676. }
  2677. else if (arguments.length > 1) {
  2678. return treatDefaultAsFactory && isFunction(defaultValue)
  2679. ? defaultValue.call(instance.proxy)
  2680. : defaultValue;
  2681. }
  2682. else {
  2683. warn$1(`injection "${String(key)}" not found.`);
  2684. }
  2685. }
  2686. else {
  2687. warn$1(`inject() can only be used inside setup() or functional components.`);
  2688. }
  2689. }
  2690. function useTransitionState() {
  2691. const state = {
  2692. isMounted: false,
  2693. isLeaving: false,
  2694. isUnmounting: false,
  2695. leavingVNodes: new Map()
  2696. };
  2697. onMounted(() => {
  2698. state.isMounted = true;
  2699. });
  2700. onBeforeUnmount(() => {
  2701. state.isUnmounting = true;
  2702. });
  2703. return state;
  2704. }
  2705. const TransitionHookValidator = [Function, Array];
  2706. const BaseTransitionImpl = {
  2707. name: `BaseTransition`,
  2708. props: {
  2709. mode: String,
  2710. appear: Boolean,
  2711. persisted: Boolean,
  2712. // enter
  2713. onBeforeEnter: TransitionHookValidator,
  2714. onEnter: TransitionHookValidator,
  2715. onAfterEnter: TransitionHookValidator,
  2716. onEnterCancelled: TransitionHookValidator,
  2717. // leave
  2718. onBeforeLeave: TransitionHookValidator,
  2719. onLeave: TransitionHookValidator,
  2720. onAfterLeave: TransitionHookValidator,
  2721. onLeaveCancelled: TransitionHookValidator,
  2722. // appear
  2723. onBeforeAppear: TransitionHookValidator,
  2724. onAppear: TransitionHookValidator,
  2725. onAfterAppear: TransitionHookValidator,
  2726. onAppearCancelled: TransitionHookValidator
  2727. },
  2728. setup(props, { slots }) {
  2729. const instance = getCurrentInstance();
  2730. const state = useTransitionState();
  2731. let prevTransitionKey;
  2732. return () => {
  2733. const children = slots.default && getTransitionRawChildren(slots.default(), true);
  2734. if (!children || !children.length) {
  2735. return;
  2736. }
  2737. // warn multiple elements
  2738. if (children.length > 1) {
  2739. warn$1('<transition> can only be used on a single element or component. Use ' +
  2740. '<transition-group> for lists.');
  2741. }
  2742. // there's no need to track reactivity for these props so use the raw
  2743. // props for a bit better perf
  2744. const rawProps = toRaw(props);
  2745. const { mode } = rawProps;
  2746. // check mode
  2747. if (mode &&
  2748. mode !== 'in-out' && mode !== 'out-in' && mode !== 'default') {
  2749. warn$1(`invalid <transition> mode: ${mode}`);
  2750. }
  2751. // at this point children has a guaranteed length of 1.
  2752. const child = children[0];
  2753. if (state.isLeaving) {
  2754. return emptyPlaceholder(child);
  2755. }
  2756. // in the case of <transition><keep-alive/></transition>, we need to
  2757. // compare the type of the kept-alive children.
  2758. const innerChild = getKeepAliveChild(child);
  2759. if (!innerChild) {
  2760. return emptyPlaceholder(child);
  2761. }
  2762. const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
  2763. setTransitionHooks(innerChild, enterHooks);
  2764. const oldChild = instance.subTree;
  2765. const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
  2766. let transitionKeyChanged = false;
  2767. const { getTransitionKey } = innerChild.type;
  2768. if (getTransitionKey) {
  2769. const key = getTransitionKey();
  2770. if (prevTransitionKey === undefined) {
  2771. prevTransitionKey = key;
  2772. }
  2773. else if (key !== prevTransitionKey) {
  2774. prevTransitionKey = key;
  2775. transitionKeyChanged = true;
  2776. }
  2777. }
  2778. // handle mode
  2779. if (oldInnerChild &&
  2780. oldInnerChild.type !== Comment &&
  2781. (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
  2782. const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
  2783. // update old tree's hooks in case of dynamic transition
  2784. setTransitionHooks(oldInnerChild, leavingHooks);
  2785. // switching between different views
  2786. if (mode === 'out-in') {
  2787. state.isLeaving = true;
  2788. // return placeholder node and queue update when leave finishes
  2789. leavingHooks.afterLeave = () => {
  2790. state.isLeaving = false;
  2791. instance.update();
  2792. };
  2793. return emptyPlaceholder(child);
  2794. }
  2795. else if (mode === 'in-out' && innerChild.type !== Comment) {
  2796. leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
  2797. const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
  2798. leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
  2799. // early removal callback
  2800. el._leaveCb = () => {
  2801. earlyRemove();
  2802. el._leaveCb = undefined;
  2803. delete enterHooks.delayedLeave;
  2804. };
  2805. enterHooks.delayedLeave = delayedLeave;
  2806. };
  2807. }
  2808. }
  2809. return child;
  2810. };
  2811. }
  2812. };
  2813. // export the public type for h/tsx inference
  2814. // also to avoid inline import() in generated d.ts files
  2815. const BaseTransition = BaseTransitionImpl;
  2816. function getLeavingNodesForType(state, vnode) {
  2817. const { leavingVNodes } = state;
  2818. let leavingVNodesCache = leavingVNodes.get(vnode.type);
  2819. if (!leavingVNodesCache) {
  2820. leavingVNodesCache = Object.create(null);
  2821. leavingVNodes.set(vnode.type, leavingVNodesCache);
  2822. }
  2823. return leavingVNodesCache;
  2824. }
  2825. // The transition hooks are attached to the vnode as vnode.transition
  2826. // and will be called at appropriate timing in the renderer.
  2827. function resolveTransitionHooks(vnode, props, state, instance) {
  2828. const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
  2829. const key = String(vnode.key);
  2830. const leavingVNodesCache = getLeavingNodesForType(state, vnode);
  2831. const callHook = (hook, args) => {
  2832. hook &&
  2833. callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
  2834. };
  2835. const hooks = {
  2836. mode,
  2837. persisted,
  2838. beforeEnter(el) {
  2839. let hook = onBeforeEnter;
  2840. if (!state.isMounted) {
  2841. if (appear) {
  2842. hook = onBeforeAppear || onBeforeEnter;
  2843. }
  2844. else {
  2845. return;
  2846. }
  2847. }
  2848. // for same element (v-show)
  2849. if (el._leaveCb) {
  2850. el._leaveCb(true /* cancelled */);
  2851. }
  2852. // for toggled element with same key (v-if)
  2853. const leavingVNode = leavingVNodesCache[key];
  2854. if (leavingVNode &&
  2855. isSameVNodeType(vnode, leavingVNode) &&
  2856. leavingVNode.el._leaveCb) {
  2857. // force early removal (not cancelled)
  2858. leavingVNode.el._leaveCb();
  2859. }
  2860. callHook(hook, [el]);
  2861. },
  2862. enter(el) {
  2863. let hook = onEnter;
  2864. let afterHook = onAfterEnter;
  2865. let cancelHook = onEnterCancelled;
  2866. if (!state.isMounted) {
  2867. if (appear) {
  2868. hook = onAppear || onEnter;
  2869. afterHook = onAfterAppear || onAfterEnter;
  2870. cancelHook = onAppearCancelled || onEnterCancelled;
  2871. }
  2872. else {
  2873. return;
  2874. }
  2875. }
  2876. let called = false;
  2877. const done = (el._enterCb = (cancelled) => {
  2878. if (called)
  2879. return;
  2880. called = true;
  2881. if (cancelled) {
  2882. callHook(cancelHook, [el]);
  2883. }
  2884. else {
  2885. callHook(afterHook, [el]);
  2886. }
  2887. if (hooks.delayedLeave) {
  2888. hooks.delayedLeave();
  2889. }
  2890. el._enterCb = undefined;
  2891. });
  2892. if (hook) {
  2893. hook(el, done);
  2894. if (hook.length <= 1) {
  2895. done();
  2896. }
  2897. }
  2898. else {
  2899. done();
  2900. }
  2901. },
  2902. leave(el, remove) {
  2903. const key = String(vnode.key);
  2904. if (el._enterCb) {
  2905. el._enterCb(true /* cancelled */);
  2906. }
  2907. if (state.isUnmounting) {
  2908. return remove();
  2909. }
  2910. callHook(onBeforeLeave, [el]);
  2911. let called = false;
  2912. const done = (el._leaveCb = (cancelled) => {
  2913. if (called)
  2914. return;
  2915. called = true;
  2916. remove();
  2917. if (cancelled) {
  2918. callHook(onLeaveCancelled, [el]);
  2919. }
  2920. else {
  2921. callHook(onAfterLeave, [el]);
  2922. }
  2923. el._leaveCb = undefined;
  2924. if (leavingVNodesCache[key] === vnode) {
  2925. delete leavingVNodesCache[key];
  2926. }
  2927. });
  2928. leavingVNodesCache[key] = vnode;
  2929. if (onLeave) {
  2930. onLeave(el, done);
  2931. if (onLeave.length <= 1) {
  2932. done();
  2933. }
  2934. }
  2935. else {
  2936. done();
  2937. }
  2938. },
  2939. clone(vnode) {
  2940. return resolveTransitionHooks(vnode, props, state, instance);
  2941. }
  2942. };
  2943. return hooks;
  2944. }
  2945. // the placeholder really only handles one special case: KeepAlive
  2946. // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
  2947. // placeholder with empty content to avoid the KeepAlive instance from being
  2948. // unmounted.
  2949. function emptyPlaceholder(vnode) {
  2950. if (isKeepAlive(vnode)) {
  2951. vnode = cloneVNode(vnode);
  2952. vnode.children = null;
  2953. return vnode;
  2954. }
  2955. }
  2956. function getKeepAliveChild(vnode) {
  2957. return isKeepAlive(vnode)
  2958. ? vnode.children
  2959. ? vnode.children[0]
  2960. : undefined
  2961. : vnode;
  2962. }
  2963. function setTransitionHooks(vnode, hooks) {
  2964. if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
  2965. setTransitionHooks(vnode.component.subTree, hooks);
  2966. }
  2967. else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
  2968. vnode.ssContent.transition = hooks.clone(vnode.ssContent);
  2969. vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
  2970. }
  2971. else {
  2972. vnode.transition = hooks;
  2973. }
  2974. }
  2975. function getTransitionRawChildren(children, keepComment = false) {
  2976. let ret = [];
  2977. let keyedFragmentCount = 0;
  2978. for (let i = 0; i < children.length; i++) {
  2979. const child = children[i];
  2980. // handle fragment children case, e.g. v-for
  2981. if (child.type === Fragment) {
  2982. if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
  2983. keyedFragmentCount++;
  2984. ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
  2985. }
  2986. // comment placeholders should be skipped, e.g. v-if
  2987. else if (keepComment || child.type !== Comment) {
  2988. ret.push(child);
  2989. }
  2990. }
  2991. // #1126 if a transition children list contains multiple sub fragments, these
  2992. // fragments will be merged into a flat children array. Since each v-for
  2993. // fragment may contain different static bindings inside, we need to de-op
  2994. // these children to force full diffs to ensure correct behavior.
  2995. if (keyedFragmentCount > 1) {
  2996. for (let i = 0; i < ret.length; i++) {
  2997. ret[i].patchFlag = -2 /* BAIL */;
  2998. }
  2999. }
  3000. return ret;
  3001. }
  3002. // implementation, close to no-op
  3003. function defineComponent(options) {
  3004. return isFunction(options) ? { setup: options, name: options.name } : options;
  3005. }
  3006. const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
  3007. function defineAsyncComponent(source) {
  3008. if (isFunction(source)) {
  3009. source = { loader: source };
  3010. }
  3011. const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
  3012. suspensible = true, onError: userOnError } = source;
  3013. let pendingRequest = null;
  3014. let resolvedComp;
  3015. let retries = 0;
  3016. const retry = () => {
  3017. retries++;
  3018. pendingRequest = null;
  3019. return load();
  3020. };
  3021. const load = () => {
  3022. let thisRequest;
  3023. return (pendingRequest ||
  3024. (thisRequest = pendingRequest =
  3025. loader()
  3026. .catch(err => {
  3027. err = err instanceof Error ? err : new Error(String(err));
  3028. if (userOnError) {
  3029. return new Promise((resolve, reject) => {
  3030. const userRetry = () => resolve(retry());
  3031. const userFail = () => reject(err);
  3032. userOnError(err, userRetry, userFail, retries + 1);
  3033. });
  3034. }
  3035. else {
  3036. throw err;
  3037. }
  3038. })
  3039. .then((comp) => {
  3040. if (thisRequest !== pendingRequest && pendingRequest) {
  3041. return pendingRequest;
  3042. }
  3043. if (!comp) {
  3044. warn$1(`Async component loader resolved to undefined. ` +
  3045. `If you are using retry(), make sure to return its return value.`);
  3046. }
  3047. // interop module default
  3048. if (comp &&
  3049. (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
  3050. comp = comp.default;
  3051. }
  3052. if (comp && !isObject(comp) && !isFunction(comp)) {
  3053. throw new Error(`Invalid async component load result: ${comp}`);
  3054. }
  3055. resolvedComp = comp;
  3056. return comp;
  3057. })));
  3058. };
  3059. return defineComponent({
  3060. name: 'AsyncComponentWrapper',
  3061. __asyncLoader: load,
  3062. get __asyncResolved() {
  3063. return resolvedComp;
  3064. },
  3065. setup() {
  3066. const instance = currentInstance;
  3067. // already resolved
  3068. if (resolvedComp) {
  3069. return () => createInnerComp(resolvedComp, instance);
  3070. }
  3071. const onError = (err) => {
  3072. pendingRequest = null;
  3073. handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
  3074. };
  3075. // suspense-controlled or SSR.
  3076. if ((suspensible && instance.suspense) ||
  3077. (false )) {
  3078. return load()
  3079. .then(comp => {
  3080. return () => createInnerComp(comp, instance);
  3081. })
  3082. .catch(err => {
  3083. onError(err);
  3084. return () => errorComponent
  3085. ? createVNode(errorComponent, {
  3086. error: err
  3087. })
  3088. : null;
  3089. });
  3090. }
  3091. const loaded = ref(false);
  3092. const error = ref();
  3093. const delayed = ref(!!delay);
  3094. if (delay) {
  3095. setTimeout(() => {
  3096. delayed.value = false;
  3097. }, delay);
  3098. }
  3099. if (timeout != null) {
  3100. setTimeout(() => {
  3101. if (!loaded.value && !error.value) {
  3102. const err = new Error(`Async component timed out after ${timeout}ms.`);
  3103. onError(err);
  3104. error.value = err;
  3105. }
  3106. }, timeout);
  3107. }
  3108. load()
  3109. .then(() => {
  3110. loaded.value = true;
  3111. if (instance.parent && isKeepAlive(instance.parent.vnode)) {
  3112. // parent is keep-alive, force update so the loaded component's
  3113. // name is taken into account
  3114. queueJob(instance.parent.update);
  3115. }
  3116. })
  3117. .catch(err => {
  3118. onError(err);
  3119. error.value = err;
  3120. });
  3121. return () => {
  3122. if (loaded.value && resolvedComp) {
  3123. return createInnerComp(resolvedComp, instance);
  3124. }
  3125. else if (error.value && errorComponent) {
  3126. return createVNode(errorComponent, {
  3127. error: error.value
  3128. });
  3129. }
  3130. else if (loadingComponent && !delayed.value) {
  3131. return createVNode(loadingComponent);
  3132. }
  3133. };
  3134. }
  3135. });
  3136. }
  3137. function createInnerComp(comp, { vnode: { ref, props, children } }) {
  3138. const vnode = createVNode(comp, props, children);
  3139. // ensure inner component inherits the async wrapper's ref owner
  3140. vnode.ref = ref;
  3141. return vnode;
  3142. }
  3143. const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
  3144. const KeepAliveImpl = {
  3145. name: `KeepAlive`,
  3146. // Marker for special handling inside the renderer. We are not using a ===
  3147. // check directly on KeepAlive in the renderer, because importing it directly
  3148. // would prevent it from being tree-shaken.
  3149. __isKeepAlive: true,
  3150. props: {
  3151. include: [String, RegExp, Array],
  3152. exclude: [String, RegExp, Array],
  3153. max: [String, Number]
  3154. },
  3155. setup(props, { slots }) {
  3156. const instance = getCurrentInstance();
  3157. // KeepAlive communicates with the instantiated renderer via the
  3158. // ctx where the renderer passes in its internals,
  3159. // and the KeepAlive instance exposes activate/deactivate implementations.
  3160. // The whole point of this is to avoid importing KeepAlive directly in the
  3161. // renderer to facilitate tree-shaking.
  3162. const sharedContext = instance.ctx;
  3163. // if the internal renderer is not registered, it indicates that this is server-side rendering,
  3164. // for KeepAlive, we just need to render its children
  3165. if (!sharedContext.renderer) {
  3166. return slots.default;
  3167. }
  3168. const cache = new Map();
  3169. const keys = new Set();
  3170. let current = null;
  3171. {
  3172. instance.__v_cache = cache;
  3173. }
  3174. const parentSuspense = instance.suspense;
  3175. const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
  3176. const storageContainer = createElement('div');
  3177. sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
  3178. const instance = vnode.component;
  3179. move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
  3180. // in case props have changed
  3181. patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
  3182. queuePostRenderEffect(() => {
  3183. instance.isDeactivated = false;
  3184. if (instance.a) {
  3185. invokeArrayFns(instance.a);
  3186. }
  3187. const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
  3188. if (vnodeHook) {
  3189. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3190. }
  3191. }, parentSuspense);
  3192. {
  3193. // Update components tree
  3194. devtoolsComponentAdded(instance);
  3195. }
  3196. };
  3197. sharedContext.deactivate = (vnode) => {
  3198. const instance = vnode.component;
  3199. move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
  3200. queuePostRenderEffect(() => {
  3201. if (instance.da) {
  3202. invokeArrayFns(instance.da);
  3203. }
  3204. const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
  3205. if (vnodeHook) {
  3206. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3207. }
  3208. instance.isDeactivated = true;
  3209. }, parentSuspense);
  3210. {
  3211. // Update components tree
  3212. devtoolsComponentAdded(instance);
  3213. }
  3214. };
  3215. function unmount(vnode) {
  3216. // reset the shapeFlag so it can be properly unmounted
  3217. resetShapeFlag(vnode);
  3218. _unmount(vnode, instance, parentSuspense);
  3219. }
  3220. function pruneCache(filter) {
  3221. cache.forEach((vnode, key) => {
  3222. const name = getComponentName(vnode.type);
  3223. if (name && (!filter || !filter(name))) {
  3224. pruneCacheEntry(key);
  3225. }
  3226. });
  3227. }
  3228. function pruneCacheEntry(key) {
  3229. const cached = cache.get(key);
  3230. if (!current || cached.type !== current.type) {
  3231. unmount(cached);
  3232. }
  3233. else if (current) {
  3234. // current active instance should no longer be kept-alive.
  3235. // we can't unmount it now but it might be later, so reset its flag now.
  3236. resetShapeFlag(current);
  3237. }
  3238. cache.delete(key);
  3239. keys.delete(key);
  3240. }
  3241. // prune cache on include/exclude prop change
  3242. watch(() => [props.include, props.exclude], ([include, exclude]) => {
  3243. include && pruneCache(name => matches(include, name));
  3244. exclude && pruneCache(name => !matches(exclude, name));
  3245. },
  3246. // prune post-render after `current` has been updated
  3247. { flush: 'post', deep: true });
  3248. // cache sub tree after render
  3249. let pendingCacheKey = null;
  3250. const cacheSubtree = () => {
  3251. // fix #1621, the pendingCacheKey could be 0
  3252. if (pendingCacheKey != null) {
  3253. cache.set(pendingCacheKey, getInnerChild(instance.subTree));
  3254. }
  3255. };
  3256. onMounted(cacheSubtree);
  3257. onUpdated(cacheSubtree);
  3258. onBeforeUnmount(() => {
  3259. cache.forEach(cached => {
  3260. const { subTree, suspense } = instance;
  3261. const vnode = getInnerChild(subTree);
  3262. if (cached.type === vnode.type) {
  3263. // current instance will be unmounted as part of keep-alive's unmount
  3264. resetShapeFlag(vnode);
  3265. // but invoke its deactivated hook here
  3266. const da = vnode.component.da;
  3267. da && queuePostRenderEffect(da, suspense);
  3268. return;
  3269. }
  3270. unmount(cached);
  3271. });
  3272. });
  3273. return () => {
  3274. pendingCacheKey = null;
  3275. if (!slots.default) {
  3276. return null;
  3277. }
  3278. const children = slots.default();
  3279. const rawVNode = children[0];
  3280. if (children.length > 1) {
  3281. {
  3282. warn$1(`KeepAlive should contain exactly one component child.`);
  3283. }
  3284. current = null;
  3285. return children;
  3286. }
  3287. else if (!isVNode(rawVNode) ||
  3288. (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
  3289. !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
  3290. current = null;
  3291. return rawVNode;
  3292. }
  3293. let vnode = getInnerChild(rawVNode);
  3294. const comp = vnode.type;
  3295. // for async components, name check should be based in its loaded
  3296. // inner component if available
  3297. const name = getComponentName(isAsyncWrapper(vnode)
  3298. ? vnode.type.__asyncResolved || {}
  3299. : comp);
  3300. const { include, exclude, max } = props;
  3301. if ((include && (!name || !matches(include, name))) ||
  3302. (exclude && name && matches(exclude, name))) {
  3303. current = vnode;
  3304. return rawVNode;
  3305. }
  3306. const key = vnode.key == null ? comp : vnode.key;
  3307. const cachedVNode = cache.get(key);
  3308. // clone vnode if it's reused because we are going to mutate it
  3309. if (vnode.el) {
  3310. vnode = cloneVNode(vnode);
  3311. if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
  3312. rawVNode.ssContent = vnode;
  3313. }
  3314. }
  3315. // #1513 it's possible for the returned vnode to be cloned due to attr
  3316. // fallthrough or scopeId, so the vnode here may not be the final vnode
  3317. // that is mounted. Instead of caching it directly, we store the pending
  3318. // key and cache `instance.subTree` (the normalized vnode) in
  3319. // beforeMount/beforeUpdate hooks.
  3320. pendingCacheKey = key;
  3321. if (cachedVNode) {
  3322. // copy over mounted state
  3323. vnode.el = cachedVNode.el;
  3324. vnode.component = cachedVNode.component;
  3325. if (vnode.transition) {
  3326. // recursively update transition hooks on subTree
  3327. setTransitionHooks(vnode, vnode.transition);
  3328. }
  3329. // avoid vnode being mounted as fresh
  3330. vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
  3331. // make this key the freshest
  3332. keys.delete(key);
  3333. keys.add(key);
  3334. }
  3335. else {
  3336. keys.add(key);
  3337. // prune oldest entry
  3338. if (max && keys.size > parseInt(max, 10)) {
  3339. pruneCacheEntry(keys.values().next().value);
  3340. }
  3341. }
  3342. // avoid vnode being unmounted
  3343. vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
  3344. current = vnode;
  3345. return rawVNode;
  3346. };
  3347. }
  3348. };
  3349. // export the public type for h/tsx inference
  3350. // also to avoid inline import() in generated d.ts files
  3351. const KeepAlive = KeepAliveImpl;
  3352. function matches(pattern, name) {
  3353. if (isArray(pattern)) {
  3354. return pattern.some((p) => matches(p, name));
  3355. }
  3356. else if (isString(pattern)) {
  3357. return pattern.split(',').indexOf(name) > -1;
  3358. }
  3359. else if (pattern.test) {
  3360. return pattern.test(name);
  3361. }
  3362. /* istanbul ignore next */
  3363. return false;
  3364. }
  3365. function onActivated(hook, target) {
  3366. registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
  3367. }
  3368. function onDeactivated(hook, target) {
  3369. registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
  3370. }
  3371. function registerKeepAliveHook(hook, type, target = currentInstance) {
  3372. // cache the deactivate branch check wrapper for injected hooks so the same
  3373. // hook can be properly deduped by the scheduler. "__wdc" stands for "with
  3374. // deactivation check".
  3375. const wrappedHook = hook.__wdc ||
  3376. (hook.__wdc = () => {
  3377. // only fire the hook if the target instance is NOT in a deactivated branch.
  3378. let current = target;
  3379. while (current) {
  3380. if (current.isDeactivated) {
  3381. return;
  3382. }
  3383. current = current.parent;
  3384. }
  3385. return hook();
  3386. });
  3387. injectHook(type, wrappedHook, target);
  3388. // In addition to registering it on the target instance, we walk up the parent
  3389. // chain and register it on all ancestor instances that are keep-alive roots.
  3390. // This avoids the need to walk the entire component tree when invoking these
  3391. // hooks, and more importantly, avoids the need to track child components in
  3392. // arrays.
  3393. if (target) {
  3394. let current = target.parent;
  3395. while (current && current.parent) {
  3396. if (isKeepAlive(current.parent.vnode)) {
  3397. injectToKeepAliveRoot(wrappedHook, type, target, current);
  3398. }
  3399. current = current.parent;
  3400. }
  3401. }
  3402. }
  3403. function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
  3404. // injectHook wraps the original for error handling, so make sure to remove
  3405. // the wrapped version.
  3406. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
  3407. onUnmounted(() => {
  3408. remove(keepAliveRoot[type], injected);
  3409. }, target);
  3410. }
  3411. function resetShapeFlag(vnode) {
  3412. let shapeFlag = vnode.shapeFlag;
  3413. if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  3414. shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
  3415. }
  3416. if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
  3417. shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
  3418. }
  3419. vnode.shapeFlag = shapeFlag;
  3420. }
  3421. function getInnerChild(vnode) {
  3422. return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
  3423. }
  3424. function injectHook(type, hook, target = currentInstance, prepend = false) {
  3425. if (target) {
  3426. const hooks = target[type] || (target[type] = []);
  3427. // cache the error handling wrapper for injected hooks so the same hook
  3428. // can be properly deduped by the scheduler. "__weh" stands for "with error
  3429. // handling".
  3430. const wrappedHook = hook.__weh ||
  3431. (hook.__weh = (...args) => {
  3432. if (target.isUnmounted) {
  3433. return;
  3434. }
  3435. // disable tracking inside all lifecycle hooks
  3436. // since they can potentially be called inside effects.
  3437. pauseTracking();
  3438. // Set currentInstance during hook invocation.
  3439. // This assumes the hook does not synchronously trigger other hooks, which
  3440. // can only be false when the user does something really funky.
  3441. setCurrentInstance(target);
  3442. const res = callWithAsyncErrorHandling(hook, target, type, args);
  3443. unsetCurrentInstance();
  3444. resetTracking();
  3445. return res;
  3446. });
  3447. if (prepend) {
  3448. hooks.unshift(wrappedHook);
  3449. }
  3450. else {
  3451. hooks.push(wrappedHook);
  3452. }
  3453. return wrappedHook;
  3454. }
  3455. else {
  3456. const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
  3457. warn$1(`${apiName} is called when there is no active component instance to be ` +
  3458. `associated with. ` +
  3459. `Lifecycle injection APIs can only be used during execution of setup().` +
  3460. (` If you are using async setup(), make sure to register lifecycle ` +
  3461. `hooks before the first await statement.`
  3462. ));
  3463. }
  3464. }
  3465. const createHook = (lifecycle) => (hook, target = currentInstance) =>
  3466. // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
  3467. (!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
  3468. injectHook(lifecycle, hook, target);
  3469. const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
  3470. const onMounted = createHook("m" /* MOUNTED */);
  3471. const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
  3472. const onUpdated = createHook("u" /* UPDATED */);
  3473. const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
  3474. const onUnmounted = createHook("um" /* UNMOUNTED */);
  3475. const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
  3476. const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
  3477. const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
  3478. function onErrorCaptured(hook, target = currentInstance) {
  3479. injectHook("ec" /* ERROR_CAPTURED */, hook, target);
  3480. }
  3481. function createDuplicateChecker() {
  3482. const cache = Object.create(null);
  3483. return (type, key) => {
  3484. if (cache[key]) {
  3485. warn$1(`${type} property "${key}" is already defined in ${cache[key]}.`);
  3486. }
  3487. else {
  3488. cache[key] = type;
  3489. }
  3490. };
  3491. }
  3492. let shouldCacheAccess = true;
  3493. function applyOptions(instance) {
  3494. const options = resolveMergedOptions(instance);
  3495. const publicThis = instance.proxy;
  3496. const ctx = instance.ctx;
  3497. // do not cache property access on public proxy during state initialization
  3498. shouldCacheAccess = false;
  3499. // call beforeCreate first before accessing other options since
  3500. // the hook may mutate resolved options (#2791)
  3501. if (options.beforeCreate) {
  3502. callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
  3503. }
  3504. const {
  3505. // state
  3506. data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
  3507. // lifecycle
  3508. created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
  3509. // public API
  3510. expose, inheritAttrs,
  3511. // assets
  3512. components, directives, filters } = options;
  3513. const checkDuplicateProperties = createDuplicateChecker() ;
  3514. {
  3515. const [propsOptions] = instance.propsOptions;
  3516. if (propsOptions) {
  3517. for (const key in propsOptions) {
  3518. checkDuplicateProperties("Props" /* PROPS */, key);
  3519. }
  3520. }
  3521. }
  3522. // options initialization order (to be consistent with Vue 2):
  3523. // - props (already done outside of this function)
  3524. // - inject
  3525. // - methods
  3526. // - data (deferred since it relies on `this` access)
  3527. // - computed
  3528. // - watch (deferred since it relies on `this` access)
  3529. if (injectOptions) {
  3530. resolveInjections(injectOptions, ctx, checkDuplicateProperties, instance.appContext.config.unwrapInjectedRef);
  3531. }
  3532. if (methods) {
  3533. for (const key in methods) {
  3534. const methodHandler = methods[key];
  3535. if (isFunction(methodHandler)) {
  3536. // In dev mode, we use the `createRenderContext` function to define
  3537. // methods to the proxy target, and those are read-only but
  3538. // reconfigurable, so it needs to be redefined here
  3539. {
  3540. Object.defineProperty(ctx, key, {
  3541. value: methodHandler.bind(publicThis),
  3542. configurable: true,
  3543. enumerable: true,
  3544. writable: true
  3545. });
  3546. }
  3547. {
  3548. checkDuplicateProperties("Methods" /* METHODS */, key);
  3549. }
  3550. }
  3551. else {
  3552. warn$1(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
  3553. `Did you reference the function correctly?`);
  3554. }
  3555. }
  3556. }
  3557. if (dataOptions) {
  3558. if (!isFunction(dataOptions)) {
  3559. warn$1(`The data option must be a function. ` +
  3560. `Plain object usage is no longer supported.`);
  3561. }
  3562. const data = dataOptions.call(publicThis, publicThis);
  3563. if (isPromise(data)) {
  3564. warn$1(`data() returned a Promise - note data() cannot be async; If you ` +
  3565. `intend to perform data fetching before component renders, use ` +
  3566. `async setup() + <Suspense>.`);
  3567. }
  3568. if (!isObject(data)) {
  3569. warn$1(`data() should return an object.`);
  3570. }
  3571. else {
  3572. instance.data = reactive(data);
  3573. {
  3574. for (const key in data) {
  3575. checkDuplicateProperties("Data" /* DATA */, key);
  3576. // expose data on ctx during dev
  3577. if (key[0] !== '$' && key[0] !== '_') {
  3578. Object.defineProperty(ctx, key, {
  3579. configurable: true,
  3580. enumerable: true,
  3581. get: () => data[key],
  3582. set: NOOP
  3583. });
  3584. }
  3585. }
  3586. }
  3587. }
  3588. }
  3589. // state initialization complete at this point - start caching access
  3590. shouldCacheAccess = true;
  3591. if (computedOptions) {
  3592. for (const key in computedOptions) {
  3593. const opt = computedOptions[key];
  3594. const get = isFunction(opt)
  3595. ? opt.bind(publicThis, publicThis)
  3596. : isFunction(opt.get)
  3597. ? opt.get.bind(publicThis, publicThis)
  3598. : NOOP;
  3599. if (get === NOOP) {
  3600. warn$1(`Computed property "${key}" has no getter.`);
  3601. }
  3602. const set = !isFunction(opt) && isFunction(opt.set)
  3603. ? opt.set.bind(publicThis)
  3604. : () => {
  3605. warn$1(`Write operation failed: computed property "${key}" is readonly.`);
  3606. }
  3607. ;
  3608. const c = computed({
  3609. get,
  3610. set
  3611. });
  3612. Object.defineProperty(ctx, key, {
  3613. enumerable: true,
  3614. configurable: true,
  3615. get: () => c.value,
  3616. set: v => (c.value = v)
  3617. });
  3618. {
  3619. checkDuplicateProperties("Computed" /* COMPUTED */, key);
  3620. }
  3621. }
  3622. }
  3623. if (watchOptions) {
  3624. for (const key in watchOptions) {
  3625. createWatcher(watchOptions[key], ctx, publicThis, key);
  3626. }
  3627. }
  3628. if (provideOptions) {
  3629. const provides = isFunction(provideOptions)
  3630. ? provideOptions.call(publicThis)
  3631. : provideOptions;
  3632. Reflect.ownKeys(provides).forEach(key => {
  3633. provide(key, provides[key]);
  3634. });
  3635. }
  3636. if (created) {
  3637. callHook(created, instance, "c" /* CREATED */);
  3638. }
  3639. function registerLifecycleHook(register, hook) {
  3640. if (isArray(hook)) {
  3641. hook.forEach(_hook => register(_hook.bind(publicThis)));
  3642. }
  3643. else if (hook) {
  3644. register(hook.bind(publicThis));
  3645. }
  3646. }
  3647. registerLifecycleHook(onBeforeMount, beforeMount);
  3648. registerLifecycleHook(onMounted, mounted);
  3649. registerLifecycleHook(onBeforeUpdate, beforeUpdate);
  3650. registerLifecycleHook(onUpdated, updated);
  3651. registerLifecycleHook(onActivated, activated);
  3652. registerLifecycleHook(onDeactivated, deactivated);
  3653. registerLifecycleHook(onErrorCaptured, errorCaptured);
  3654. registerLifecycleHook(onRenderTracked, renderTracked);
  3655. registerLifecycleHook(onRenderTriggered, renderTriggered);
  3656. registerLifecycleHook(onBeforeUnmount, beforeUnmount);
  3657. registerLifecycleHook(onUnmounted, unmounted);
  3658. registerLifecycleHook(onServerPrefetch, serverPrefetch);
  3659. if (isArray(expose)) {
  3660. if (expose.length) {
  3661. const exposed = instance.exposed || (instance.exposed = {});
  3662. expose.forEach(key => {
  3663. Object.defineProperty(exposed, key, {
  3664. get: () => publicThis[key],
  3665. set: val => (publicThis[key] = val)
  3666. });
  3667. });
  3668. }
  3669. else if (!instance.exposed) {
  3670. instance.exposed = {};
  3671. }
  3672. }
  3673. // options that are handled when creating the instance but also need to be
  3674. // applied from mixins
  3675. if (render && instance.render === NOOP) {
  3676. instance.render = render;
  3677. }
  3678. if (inheritAttrs != null) {
  3679. instance.inheritAttrs = inheritAttrs;
  3680. }
  3681. // asset options.
  3682. if (components)
  3683. instance.components = components;
  3684. if (directives)
  3685. instance.directives = directives;
  3686. }
  3687. function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP, unwrapRef = false) {
  3688. if (isArray(injectOptions)) {
  3689. injectOptions = normalizeInject(injectOptions);
  3690. }
  3691. for (const key in injectOptions) {
  3692. const opt = injectOptions[key];
  3693. let injected;
  3694. if (isObject(opt)) {
  3695. if ('default' in opt) {
  3696. injected = inject(opt.from || key, opt.default, true /* treat default function as factory */);
  3697. }
  3698. else {
  3699. injected = inject(opt.from || key);
  3700. }
  3701. }
  3702. else {
  3703. injected = inject(opt);
  3704. }
  3705. if (isRef(injected)) {
  3706. // TODO remove the check in 3.3
  3707. if (unwrapRef) {
  3708. Object.defineProperty(ctx, key, {
  3709. enumerable: true,
  3710. configurable: true,
  3711. get: () => injected.value,
  3712. set: v => (injected.value = v)
  3713. });
  3714. }
  3715. else {
  3716. {
  3717. warn$1(`injected property "${key}" is a ref and will be auto-unwrapped ` +
  3718. `and no longer needs \`.value\` in the next minor release. ` +
  3719. `To opt-in to the new behavior now, ` +
  3720. `set \`app.config.unwrapInjectedRef = true\` (this config is ` +
  3721. `temporary and will not be needed in the future.)`);
  3722. }
  3723. ctx[key] = injected;
  3724. }
  3725. }
  3726. else {
  3727. ctx[key] = injected;
  3728. }
  3729. {
  3730. checkDuplicateProperties("Inject" /* INJECT */, key);
  3731. }
  3732. }
  3733. }
  3734. function callHook(hook, instance, type) {
  3735. callWithAsyncErrorHandling(isArray(hook)
  3736. ? hook.map(h => h.bind(instance.proxy))
  3737. : hook.bind(instance.proxy), instance, type);
  3738. }
  3739. function createWatcher(raw, ctx, publicThis, key) {
  3740. const getter = key.includes('.')
  3741. ? createPathGetter(publicThis, key)
  3742. : () => publicThis[key];
  3743. if (isString(raw)) {
  3744. const handler = ctx[raw];
  3745. if (isFunction(handler)) {
  3746. watch(getter, handler);
  3747. }
  3748. else {
  3749. warn$1(`Invalid watch handler specified by key "${raw}"`, handler);
  3750. }
  3751. }
  3752. else if (isFunction(raw)) {
  3753. watch(getter, raw.bind(publicThis));
  3754. }
  3755. else if (isObject(raw)) {
  3756. if (isArray(raw)) {
  3757. raw.forEach(r => createWatcher(r, ctx, publicThis, key));
  3758. }
  3759. else {
  3760. const handler = isFunction(raw.handler)
  3761. ? raw.handler.bind(publicThis)
  3762. : ctx[raw.handler];
  3763. if (isFunction(handler)) {
  3764. watch(getter, handler, raw);
  3765. }
  3766. else {
  3767. warn$1(`Invalid watch handler specified by key "${raw.handler}"`, handler);
  3768. }
  3769. }
  3770. }
  3771. else {
  3772. warn$1(`Invalid watch option: "${key}"`, raw);
  3773. }
  3774. }
  3775. /**
  3776. * Resolve merged options and cache it on the component.
  3777. * This is done only once per-component since the merging does not involve
  3778. * instances.
  3779. */
  3780. function resolveMergedOptions(instance) {
  3781. const base = instance.type;
  3782. const { mixins, extends: extendsOptions } = base;
  3783. const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
  3784. const cached = cache.get(base);
  3785. let resolved;
  3786. if (cached) {
  3787. resolved = cached;
  3788. }
  3789. else if (!globalMixins.length && !mixins && !extendsOptions) {
  3790. {
  3791. resolved = base;
  3792. }
  3793. }
  3794. else {
  3795. resolved = {};
  3796. if (globalMixins.length) {
  3797. globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
  3798. }
  3799. mergeOptions(resolved, base, optionMergeStrategies);
  3800. }
  3801. cache.set(base, resolved);
  3802. return resolved;
  3803. }
  3804. function mergeOptions(to, from, strats, asMixin = false) {
  3805. const { mixins, extends: extendsOptions } = from;
  3806. if (extendsOptions) {
  3807. mergeOptions(to, extendsOptions, strats, true);
  3808. }
  3809. if (mixins) {
  3810. mixins.forEach((m) => mergeOptions(to, m, strats, true));
  3811. }
  3812. for (const key in from) {
  3813. if (asMixin && key === 'expose') {
  3814. warn$1(`"expose" option is ignored when declared in mixins or extends. ` +
  3815. `It should only be declared in the base component itself.`);
  3816. }
  3817. else {
  3818. const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
  3819. to[key] = strat ? strat(to[key], from[key]) : from[key];
  3820. }
  3821. }
  3822. return to;
  3823. }
  3824. const internalOptionMergeStrats = {
  3825. data: mergeDataFn,
  3826. props: mergeObjectOptions,
  3827. emits: mergeObjectOptions,
  3828. // objects
  3829. methods: mergeObjectOptions,
  3830. computed: mergeObjectOptions,
  3831. // lifecycle
  3832. beforeCreate: mergeAsArray,
  3833. created: mergeAsArray,
  3834. beforeMount: mergeAsArray,
  3835. mounted: mergeAsArray,
  3836. beforeUpdate: mergeAsArray,
  3837. updated: mergeAsArray,
  3838. beforeDestroy: mergeAsArray,
  3839. beforeUnmount: mergeAsArray,
  3840. destroyed: mergeAsArray,
  3841. unmounted: mergeAsArray,
  3842. activated: mergeAsArray,
  3843. deactivated: mergeAsArray,
  3844. errorCaptured: mergeAsArray,
  3845. serverPrefetch: mergeAsArray,
  3846. // assets
  3847. components: mergeObjectOptions,
  3848. directives: mergeObjectOptions,
  3849. // watch
  3850. watch: mergeWatchOptions,
  3851. // provide / inject
  3852. provide: mergeDataFn,
  3853. inject: mergeInject
  3854. };
  3855. function mergeDataFn(to, from) {
  3856. if (!from) {
  3857. return to;
  3858. }
  3859. if (!to) {
  3860. return from;
  3861. }
  3862. return function mergedDataFn() {
  3863. return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
  3864. };
  3865. }
  3866. function mergeInject(to, from) {
  3867. return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
  3868. }
  3869. function normalizeInject(raw) {
  3870. if (isArray(raw)) {
  3871. const res = {};
  3872. for (let i = 0; i < raw.length; i++) {
  3873. res[raw[i]] = raw[i];
  3874. }
  3875. return res;
  3876. }
  3877. return raw;
  3878. }
  3879. function mergeAsArray(to, from) {
  3880. return to ? [...new Set([].concat(to, from))] : from;
  3881. }
  3882. function mergeObjectOptions(to, from) {
  3883. return to ? extend(extend(Object.create(null), to), from) : from;
  3884. }
  3885. function mergeWatchOptions(to, from) {
  3886. if (!to)
  3887. return from;
  3888. if (!from)
  3889. return to;
  3890. const merged = extend(Object.create(null), to);
  3891. for (const key in from) {
  3892. merged[key] = mergeAsArray(to[key], from[key]);
  3893. }
  3894. return merged;
  3895. }
  3896. function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
  3897. isSSR = false) {
  3898. const props = {};
  3899. const attrs = {};
  3900. def(attrs, InternalObjectKey, 1);
  3901. instance.propsDefaults = Object.create(null);
  3902. setFullProps(instance, rawProps, props, attrs);
  3903. // ensure all declared prop keys are present
  3904. for (const key in instance.propsOptions[0]) {
  3905. if (!(key in props)) {
  3906. props[key] = undefined;
  3907. }
  3908. }
  3909. // validation
  3910. {
  3911. validateProps(rawProps || {}, props, instance);
  3912. }
  3913. if (isStateful) {
  3914. // stateful
  3915. instance.props = isSSR ? props : shallowReactive(props);
  3916. }
  3917. else {
  3918. if (!instance.type.props) {
  3919. // functional w/ optional props, props === attrs
  3920. instance.props = attrs;
  3921. }
  3922. else {
  3923. // functional w/ declared props
  3924. instance.props = props;
  3925. }
  3926. }
  3927. instance.attrs = attrs;
  3928. }
  3929. function updateProps(instance, rawProps, rawPrevProps, optimized) {
  3930. const { props, attrs, vnode: { patchFlag } } = instance;
  3931. const rawCurrentProps = toRaw(props);
  3932. const [options] = instance.propsOptions;
  3933. let hasAttrsChanged = false;
  3934. if (
  3935. // always force full diff in dev
  3936. // - #1942 if hmr is enabled with sfc component
  3937. // - vite#872 non-sfc component used by sfc component
  3938. !((instance.type.__hmrId ||
  3939. (instance.parent && instance.parent.type.__hmrId))) &&
  3940. (optimized || patchFlag > 0) &&
  3941. !(patchFlag & 16 /* FULL_PROPS */)) {
  3942. if (patchFlag & 8 /* PROPS */) {
  3943. // Compiler-generated props & no keys change, just set the updated
  3944. // the props.
  3945. const propsToUpdate = instance.vnode.dynamicProps;
  3946. for (let i = 0; i < propsToUpdate.length; i++) {
  3947. let key = propsToUpdate[i];
  3948. // PROPS flag guarantees rawProps to be non-null
  3949. const value = rawProps[key];
  3950. if (options) {
  3951. // attr / props separation was done on init and will be consistent
  3952. // in this code path, so just check if attrs have it.
  3953. if (hasOwn(attrs, key)) {
  3954. if (value !== attrs[key]) {
  3955. attrs[key] = value;
  3956. hasAttrsChanged = true;
  3957. }
  3958. }
  3959. else {
  3960. const camelizedKey = camelize(key);
  3961. props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
  3962. }
  3963. }
  3964. else {
  3965. if (value !== attrs[key]) {
  3966. attrs[key] = value;
  3967. hasAttrsChanged = true;
  3968. }
  3969. }
  3970. }
  3971. }
  3972. }
  3973. else {
  3974. // full props update.
  3975. if (setFullProps(instance, rawProps, props, attrs)) {
  3976. hasAttrsChanged = true;
  3977. }
  3978. // in case of dynamic props, check if we need to delete keys from
  3979. // the props object
  3980. let kebabKey;
  3981. for (const key in rawCurrentProps) {
  3982. if (!rawProps ||
  3983. // for camelCase
  3984. (!hasOwn(rawProps, key) &&
  3985. // it's possible the original props was passed in as kebab-case
  3986. // and converted to camelCase (#955)
  3987. ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
  3988. if (options) {
  3989. if (rawPrevProps &&
  3990. // for camelCase
  3991. (rawPrevProps[key] !== undefined ||
  3992. // for kebab-case
  3993. rawPrevProps[kebabKey] !== undefined)) {
  3994. props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
  3995. }
  3996. }
  3997. else {
  3998. delete props[key];
  3999. }
  4000. }
  4001. }
  4002. // in the case of functional component w/o props declaration, props and
  4003. // attrs point to the same object so it should already have been updated.
  4004. if (attrs !== rawCurrentProps) {
  4005. for (const key in attrs) {
  4006. if (!rawProps || !hasOwn(rawProps, key)) {
  4007. delete attrs[key];
  4008. hasAttrsChanged = true;
  4009. }
  4010. }
  4011. }
  4012. }
  4013. // trigger updates for $attrs in case it's used in component slots
  4014. if (hasAttrsChanged) {
  4015. trigger(instance, "set" /* SET */, '$attrs');
  4016. }
  4017. {
  4018. validateProps(rawProps || {}, props, instance);
  4019. }
  4020. }
  4021. function setFullProps(instance, rawProps, props, attrs) {
  4022. const [options, needCastKeys] = instance.propsOptions;
  4023. let hasAttrsChanged = false;
  4024. let rawCastValues;
  4025. if (rawProps) {
  4026. for (let key in rawProps) {
  4027. // key, ref are reserved and never passed down
  4028. if (isReservedProp(key)) {
  4029. continue;
  4030. }
  4031. const value = rawProps[key];
  4032. // prop option names are camelized during normalization, so to support
  4033. // kebab -> camel conversion here we need to camelize the key.
  4034. let camelKey;
  4035. if (options && hasOwn(options, (camelKey = camelize(key)))) {
  4036. if (!needCastKeys || !needCastKeys.includes(camelKey)) {
  4037. props[camelKey] = value;
  4038. }
  4039. else {
  4040. (rawCastValues || (rawCastValues = {}))[camelKey] = value;
  4041. }
  4042. }
  4043. else if (!isEmitListener(instance.emitsOptions, key)) {
  4044. if (!(key in attrs) || value !== attrs[key]) {
  4045. attrs[key] = value;
  4046. hasAttrsChanged = true;
  4047. }
  4048. }
  4049. }
  4050. }
  4051. if (needCastKeys) {
  4052. const rawCurrentProps = toRaw(props);
  4053. const castValues = rawCastValues || EMPTY_OBJ;
  4054. for (let i = 0; i < needCastKeys.length; i++) {
  4055. const key = needCastKeys[i];
  4056. props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
  4057. }
  4058. }
  4059. return hasAttrsChanged;
  4060. }
  4061. function resolvePropValue(options, props, key, value, instance, isAbsent) {
  4062. const opt = options[key];
  4063. if (opt != null) {
  4064. const hasDefault = hasOwn(opt, 'default');
  4065. // default values
  4066. if (hasDefault && value === undefined) {
  4067. const defaultValue = opt.default;
  4068. if (opt.type !== Function && isFunction(defaultValue)) {
  4069. const { propsDefaults } = instance;
  4070. if (key in propsDefaults) {
  4071. value = propsDefaults[key];
  4072. }
  4073. else {
  4074. setCurrentInstance(instance);
  4075. value = propsDefaults[key] = defaultValue.call(null, props);
  4076. unsetCurrentInstance();
  4077. }
  4078. }
  4079. else {
  4080. value = defaultValue;
  4081. }
  4082. }
  4083. // boolean casting
  4084. if (opt[0 /* shouldCast */]) {
  4085. if (isAbsent && !hasDefault) {
  4086. value = false;
  4087. }
  4088. else if (opt[1 /* shouldCastTrue */] &&
  4089. (value === '' || value === hyphenate(key))) {
  4090. value = true;
  4091. }
  4092. }
  4093. }
  4094. return value;
  4095. }
  4096. function normalizePropsOptions(comp, appContext, asMixin = false) {
  4097. const cache = appContext.propsCache;
  4098. const cached = cache.get(comp);
  4099. if (cached) {
  4100. return cached;
  4101. }
  4102. const raw = comp.props;
  4103. const normalized = {};
  4104. const needCastKeys = [];
  4105. // apply mixin/extends props
  4106. let hasExtends = false;
  4107. if (!isFunction(comp)) {
  4108. const extendProps = (raw) => {
  4109. hasExtends = true;
  4110. const [props, keys] = normalizePropsOptions(raw, appContext, true);
  4111. extend(normalized, props);
  4112. if (keys)
  4113. needCastKeys.push(...keys);
  4114. };
  4115. if (!asMixin && appContext.mixins.length) {
  4116. appContext.mixins.forEach(extendProps);
  4117. }
  4118. if (comp.extends) {
  4119. extendProps(comp.extends);
  4120. }
  4121. if (comp.mixins) {
  4122. comp.mixins.forEach(extendProps);
  4123. }
  4124. }
  4125. if (!raw && !hasExtends) {
  4126. cache.set(comp, EMPTY_ARR);
  4127. return EMPTY_ARR;
  4128. }
  4129. if (isArray(raw)) {
  4130. for (let i = 0; i < raw.length; i++) {
  4131. if (!isString(raw[i])) {
  4132. warn$1(`props must be strings when using array syntax.`, raw[i]);
  4133. }
  4134. const normalizedKey = camelize(raw[i]);
  4135. if (validatePropName(normalizedKey)) {
  4136. normalized[normalizedKey] = EMPTY_OBJ;
  4137. }
  4138. }
  4139. }
  4140. else if (raw) {
  4141. if (!isObject(raw)) {
  4142. warn$1(`invalid props options`, raw);
  4143. }
  4144. for (const key in raw) {
  4145. const normalizedKey = camelize(key);
  4146. if (validatePropName(normalizedKey)) {
  4147. const opt = raw[key];
  4148. const prop = (normalized[normalizedKey] =
  4149. isArray(opt) || isFunction(opt) ? { type: opt } : opt);
  4150. if (prop) {
  4151. const booleanIndex = getTypeIndex(Boolean, prop.type);
  4152. const stringIndex = getTypeIndex(String, prop.type);
  4153. prop[0 /* shouldCast */] = booleanIndex > -1;
  4154. prop[1 /* shouldCastTrue */] =
  4155. stringIndex < 0 || booleanIndex < stringIndex;
  4156. // if the prop needs boolean casting or default value
  4157. if (booleanIndex > -1 || hasOwn(prop, 'default')) {
  4158. needCastKeys.push(normalizedKey);
  4159. }
  4160. }
  4161. }
  4162. }
  4163. }
  4164. const res = [normalized, needCastKeys];
  4165. cache.set(comp, res);
  4166. return res;
  4167. }
  4168. function validatePropName(key) {
  4169. if (key[0] !== '$') {
  4170. return true;
  4171. }
  4172. else {
  4173. warn$1(`Invalid prop name: "${key}" is a reserved property.`);
  4174. }
  4175. return false;
  4176. }
  4177. // use function string name to check type constructors
  4178. // so that it works across vms / iframes.
  4179. function getType(ctor) {
  4180. const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
  4181. return match ? match[1] : ctor === null ? 'null' : '';
  4182. }
  4183. function isSameType(a, b) {
  4184. return getType(a) === getType(b);
  4185. }
  4186. function getTypeIndex(type, expectedTypes) {
  4187. if (isArray(expectedTypes)) {
  4188. return expectedTypes.findIndex(t => isSameType(t, type));
  4189. }
  4190. else if (isFunction(expectedTypes)) {
  4191. return isSameType(expectedTypes, type) ? 0 : -1;
  4192. }
  4193. return -1;
  4194. }
  4195. /**
  4196. * dev only
  4197. */
  4198. function validateProps(rawProps, props, instance) {
  4199. const resolvedValues = toRaw(props);
  4200. const options = instance.propsOptions[0];
  4201. for (const key in options) {
  4202. let opt = options[key];
  4203. if (opt == null)
  4204. continue;
  4205. validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
  4206. }
  4207. }
  4208. /**
  4209. * dev only
  4210. */
  4211. function validateProp(name, value, prop, isAbsent) {
  4212. const { type, required, validator } = prop;
  4213. // required!
  4214. if (required && isAbsent) {
  4215. warn$1('Missing required prop: "' + name + '"');
  4216. return;
  4217. }
  4218. // missing but optional
  4219. if (value == null && !prop.required) {
  4220. return;
  4221. }
  4222. // type check
  4223. if (type != null && type !== true) {
  4224. let isValid = false;
  4225. const types = isArray(type) ? type : [type];
  4226. const expectedTypes = [];
  4227. // value is valid as long as one of the specified types match
  4228. for (let i = 0; i < types.length && !isValid; i++) {
  4229. const { valid, expectedType } = assertType(value, types[i]);
  4230. expectedTypes.push(expectedType || '');
  4231. isValid = valid;
  4232. }
  4233. if (!isValid) {
  4234. warn$1(getInvalidTypeMessage(name, value, expectedTypes));
  4235. return;
  4236. }
  4237. }
  4238. // custom validator
  4239. if (validator && !validator(value)) {
  4240. warn$1('Invalid prop: custom validator check failed for prop "' + name + '".');
  4241. }
  4242. }
  4243. const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
  4244. /**
  4245. * dev only
  4246. */
  4247. function assertType(value, type) {
  4248. let valid;
  4249. const expectedType = getType(type);
  4250. if (isSimpleType(expectedType)) {
  4251. const t = typeof value;
  4252. valid = t === expectedType.toLowerCase();
  4253. // for primitive wrapper objects
  4254. if (!valid && t === 'object') {
  4255. valid = value instanceof type;
  4256. }
  4257. }
  4258. else if (expectedType === 'Object') {
  4259. valid = isObject(value);
  4260. }
  4261. else if (expectedType === 'Array') {
  4262. valid = isArray(value);
  4263. }
  4264. else if (expectedType === 'null') {
  4265. valid = value === null;
  4266. }
  4267. else {
  4268. valid = value instanceof type;
  4269. }
  4270. return {
  4271. valid,
  4272. expectedType
  4273. };
  4274. }
  4275. /**
  4276. * dev only
  4277. */
  4278. function getInvalidTypeMessage(name, value, expectedTypes) {
  4279. let message = `Invalid prop: type check failed for prop "${name}".` +
  4280. ` Expected ${expectedTypes.map(capitalize).join(' | ')}`;
  4281. const expectedType = expectedTypes[0];
  4282. const receivedType = toRawType(value);
  4283. const expectedValue = styleValue(value, expectedType);
  4284. const receivedValue = styleValue(value, receivedType);
  4285. // check if we need to specify expected value
  4286. if (expectedTypes.length === 1 &&
  4287. isExplicable(expectedType) &&
  4288. !isBoolean(expectedType, receivedType)) {
  4289. message += ` with value ${expectedValue}`;
  4290. }
  4291. message += `, got ${receivedType} `;
  4292. // check if we need to specify received value
  4293. if (isExplicable(receivedType)) {
  4294. message += `with value ${receivedValue}.`;
  4295. }
  4296. return message;
  4297. }
  4298. /**
  4299. * dev only
  4300. */
  4301. function styleValue(value, type) {
  4302. if (type === 'String') {
  4303. return `"${value}"`;
  4304. }
  4305. else if (type === 'Number') {
  4306. return `${Number(value)}`;
  4307. }
  4308. else {
  4309. return `${value}`;
  4310. }
  4311. }
  4312. /**
  4313. * dev only
  4314. */
  4315. function isExplicable(type) {
  4316. const explicitTypes = ['string', 'number', 'boolean'];
  4317. return explicitTypes.some(elem => type.toLowerCase() === elem);
  4318. }
  4319. /**
  4320. * dev only
  4321. */
  4322. function isBoolean(...args) {
  4323. return args.some(elem => elem.toLowerCase() === 'boolean');
  4324. }
  4325. const isInternalKey = (key) => key[0] === '_' || key === '$stable';
  4326. const normalizeSlotValue = (value) => isArray(value)
  4327. ? value.map(normalizeVNode)
  4328. : [normalizeVNode(value)];
  4329. const normalizeSlot = (key, rawSlot, ctx) => {
  4330. const normalized = withCtx((...args) => {
  4331. if (currentInstance) {
  4332. warn$1(`Slot "${key}" invoked outside of the render function: ` +
  4333. `this will not track dependencies used in the slot. ` +
  4334. `Invoke the slot function inside the render function instead.`);
  4335. }
  4336. return normalizeSlotValue(rawSlot(...args));
  4337. }, ctx);
  4338. normalized._c = false;
  4339. return normalized;
  4340. };
  4341. const normalizeObjectSlots = (rawSlots, slots, instance) => {
  4342. const ctx = rawSlots._ctx;
  4343. for (const key in rawSlots) {
  4344. if (isInternalKey(key))
  4345. continue;
  4346. const value = rawSlots[key];
  4347. if (isFunction(value)) {
  4348. slots[key] = normalizeSlot(key, value, ctx);
  4349. }
  4350. else if (value != null) {
  4351. {
  4352. warn$1(`Non-function value encountered for slot "${key}". ` +
  4353. `Prefer function slots for better performance.`);
  4354. }
  4355. const normalized = normalizeSlotValue(value);
  4356. slots[key] = () => normalized;
  4357. }
  4358. }
  4359. };
  4360. const normalizeVNodeSlots = (instance, children) => {
  4361. if (!isKeepAlive(instance.vnode) &&
  4362. !(false )) {
  4363. warn$1(`Non-function value encountered for default slot. ` +
  4364. `Prefer function slots for better performance.`);
  4365. }
  4366. const normalized = normalizeSlotValue(children);
  4367. instance.slots.default = () => normalized;
  4368. };
  4369. const initSlots = (instance, children) => {
  4370. if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
  4371. const type = children._;
  4372. if (type) {
  4373. // users can get the shallow readonly version of the slots object through `this.$slots`,
  4374. // we should avoid the proxy object polluting the slots of the internal instance
  4375. instance.slots = toRaw(children);
  4376. // make compiler marker non-enumerable
  4377. def(children, '_', type);
  4378. }
  4379. else {
  4380. normalizeObjectSlots(children, (instance.slots = {}));
  4381. }
  4382. }
  4383. else {
  4384. instance.slots = {};
  4385. if (children) {
  4386. normalizeVNodeSlots(instance, children);
  4387. }
  4388. }
  4389. def(instance.slots, InternalObjectKey, 1);
  4390. };
  4391. const updateSlots = (instance, children, optimized) => {
  4392. const { vnode, slots } = instance;
  4393. let needDeletionCheck = true;
  4394. let deletionComparisonTarget = EMPTY_OBJ;
  4395. if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
  4396. const type = children._;
  4397. if (type) {
  4398. // compiled slots.
  4399. if (isHmrUpdating) {
  4400. // Parent was HMR updated so slot content may have changed.
  4401. // force update slots and mark instance for hmr as well
  4402. extend(slots, children);
  4403. }
  4404. else if (optimized && type === 1 /* STABLE */) {
  4405. // compiled AND stable.
  4406. // no need to update, and skip stale slots removal.
  4407. needDeletionCheck = false;
  4408. }
  4409. else {
  4410. // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
  4411. // normalization.
  4412. extend(slots, children);
  4413. // #2893
  4414. // when rendering the optimized slots by manually written render function,
  4415. // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
  4416. // i.e. let the `renderSlot` create the bailed Fragment
  4417. if (!optimized && type === 1 /* STABLE */) {
  4418. delete slots._;
  4419. }
  4420. }
  4421. }
  4422. else {
  4423. needDeletionCheck = !children.$stable;
  4424. normalizeObjectSlots(children, slots);
  4425. }
  4426. deletionComparisonTarget = children;
  4427. }
  4428. else if (children) {
  4429. // non slot object children (direct value) passed to a component
  4430. normalizeVNodeSlots(instance, children);
  4431. deletionComparisonTarget = { default: 1 };
  4432. }
  4433. // delete stale slots
  4434. if (needDeletionCheck) {
  4435. for (const key in slots) {
  4436. if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
  4437. delete slots[key];
  4438. }
  4439. }
  4440. }
  4441. };
  4442. /**
  4443. Runtime helper for applying directives to a vnode. Example usage:
  4444. const comp = resolveComponent('comp')
  4445. const foo = resolveDirective('foo')
  4446. const bar = resolveDirective('bar')
  4447. return withDirectives(h(comp), [
  4448. [foo, this.x],
  4449. [bar, this.y]
  4450. ])
  4451. */
  4452. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo');
  4453. function validateDirectiveName(name) {
  4454. if (isBuiltInDirective(name)) {
  4455. warn$1('Do not use built-in directive ids as custom directive id: ' + name);
  4456. }
  4457. }
  4458. /**
  4459. * Adds directives to a VNode.
  4460. */
  4461. function withDirectives(vnode, directives) {
  4462. const internalInstance = currentRenderingInstance;
  4463. if (internalInstance === null) {
  4464. warn$1(`withDirectives can only be used inside render functions.`);
  4465. return vnode;
  4466. }
  4467. const instance = internalInstance.proxy;
  4468. const bindings = vnode.dirs || (vnode.dirs = []);
  4469. for (let i = 0; i < directives.length; i++) {
  4470. let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
  4471. if (isFunction(dir)) {
  4472. dir = {
  4473. mounted: dir,
  4474. updated: dir
  4475. };
  4476. }
  4477. if (dir.deep) {
  4478. traverse(value);
  4479. }
  4480. bindings.push({
  4481. dir,
  4482. instance,
  4483. value,
  4484. oldValue: void 0,
  4485. arg,
  4486. modifiers
  4487. });
  4488. }
  4489. return vnode;
  4490. }
  4491. function invokeDirectiveHook(vnode, prevVNode, instance, name) {
  4492. const bindings = vnode.dirs;
  4493. const oldBindings = prevVNode && prevVNode.dirs;
  4494. for (let i = 0; i < bindings.length; i++) {
  4495. const binding = bindings[i];
  4496. if (oldBindings) {
  4497. binding.oldValue = oldBindings[i].value;
  4498. }
  4499. let hook = binding.dir[name];
  4500. if (hook) {
  4501. // disable tracking inside all lifecycle hooks
  4502. // since they can potentially be called inside effects.
  4503. pauseTracking();
  4504. callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
  4505. vnode.el,
  4506. binding,
  4507. vnode,
  4508. prevVNode
  4509. ]);
  4510. resetTracking();
  4511. }
  4512. }
  4513. }
  4514. function createAppContext() {
  4515. return {
  4516. app: null,
  4517. config: {
  4518. isNativeTag: NO,
  4519. performance: false,
  4520. globalProperties: {},
  4521. optionMergeStrategies: {},
  4522. errorHandler: undefined,
  4523. warnHandler: undefined,
  4524. compilerOptions: {}
  4525. },
  4526. mixins: [],
  4527. components: {},
  4528. directives: {},
  4529. provides: Object.create(null),
  4530. optionsCache: new WeakMap(),
  4531. propsCache: new WeakMap(),
  4532. emitsCache: new WeakMap()
  4533. };
  4534. }
  4535. let uid = 0;
  4536. function createAppAPI(render, hydrate) {
  4537. return function createApp(rootComponent, rootProps = null) {
  4538. if (rootProps != null && !isObject(rootProps)) {
  4539. warn$1(`root props passed to app.mount() must be an object.`);
  4540. rootProps = null;
  4541. }
  4542. const context = createAppContext();
  4543. const installedPlugins = new Set();
  4544. let isMounted = false;
  4545. const app = (context.app = {
  4546. _uid: uid++,
  4547. _component: rootComponent,
  4548. _props: rootProps,
  4549. _container: null,
  4550. _context: context,
  4551. _instance: null,
  4552. version,
  4553. get config() {
  4554. return context.config;
  4555. },
  4556. set config(v) {
  4557. {
  4558. warn$1(`app.config cannot be replaced. Modify individual options instead.`);
  4559. }
  4560. },
  4561. use(plugin, ...options) {
  4562. if (installedPlugins.has(plugin)) {
  4563. warn$1(`Plugin has already been applied to target app.`);
  4564. }
  4565. else if (plugin && isFunction(plugin.install)) {
  4566. installedPlugins.add(plugin);
  4567. plugin.install(app, ...options);
  4568. }
  4569. else if (isFunction(plugin)) {
  4570. installedPlugins.add(plugin);
  4571. plugin(app, ...options);
  4572. }
  4573. else {
  4574. warn$1(`A plugin must either be a function or an object with an "install" ` +
  4575. `function.`);
  4576. }
  4577. return app;
  4578. },
  4579. mixin(mixin) {
  4580. {
  4581. if (!context.mixins.includes(mixin)) {
  4582. context.mixins.push(mixin);
  4583. }
  4584. else {
  4585. warn$1('Mixin has already been applied to target app' +
  4586. (mixin.name ? `: ${mixin.name}` : ''));
  4587. }
  4588. }
  4589. return app;
  4590. },
  4591. component(name, component) {
  4592. {
  4593. validateComponentName(name, context.config);
  4594. }
  4595. if (!component) {
  4596. return context.components[name];
  4597. }
  4598. if (context.components[name]) {
  4599. warn$1(`Component "${name}" has already been registered in target app.`);
  4600. }
  4601. context.components[name] = component;
  4602. return app;
  4603. },
  4604. directive(name, directive) {
  4605. {
  4606. validateDirectiveName(name);
  4607. }
  4608. if (!directive) {
  4609. return context.directives[name];
  4610. }
  4611. if (context.directives[name]) {
  4612. warn$1(`Directive "${name}" has already been registered in target app.`);
  4613. }
  4614. context.directives[name] = directive;
  4615. return app;
  4616. },
  4617. mount(rootContainer, isHydrate, isSVG) {
  4618. if (!isMounted) {
  4619. const vnode = createVNode(rootComponent, rootProps);
  4620. // store app context on the root VNode.
  4621. // this will be set on the root instance on initial mount.
  4622. vnode.appContext = context;
  4623. // HMR root reload
  4624. {
  4625. context.reload = () => {
  4626. render(cloneVNode(vnode), rootContainer, isSVG);
  4627. };
  4628. }
  4629. if (isHydrate && hydrate) {
  4630. hydrate(vnode, rootContainer);
  4631. }
  4632. else {
  4633. render(vnode, rootContainer, isSVG);
  4634. }
  4635. isMounted = true;
  4636. app._container = rootContainer;
  4637. rootContainer.__vue_app__ = app;
  4638. {
  4639. app._instance = vnode.component;
  4640. devtoolsInitApp(app, version);
  4641. }
  4642. return getExposeProxy(vnode.component) || vnode.component.proxy;
  4643. }
  4644. else {
  4645. warn$1(`App has already been mounted.\n` +
  4646. `If you want to remount the same app, move your app creation logic ` +
  4647. `into a factory function and create fresh app instances for each ` +
  4648. `mount - e.g. \`const createMyApp = () => createApp(App)\``);
  4649. }
  4650. },
  4651. unmount() {
  4652. if (isMounted) {
  4653. render(null, app._container);
  4654. {
  4655. app._instance = null;
  4656. devtoolsUnmountApp(app);
  4657. }
  4658. delete app._container.__vue_app__;
  4659. }
  4660. else {
  4661. warn$1(`Cannot unmount an app that is not mounted.`);
  4662. }
  4663. },
  4664. provide(key, value) {
  4665. if (key in context.provides) {
  4666. warn$1(`App already provides property with key "${String(key)}". ` +
  4667. `It will be overwritten with the new value.`);
  4668. }
  4669. // TypeScript doesn't allow symbols as index type
  4670. // https://github.com/Microsoft/TypeScript/issues/24587
  4671. context.provides[key] = value;
  4672. return app;
  4673. }
  4674. });
  4675. return app;
  4676. };
  4677. }
  4678. /**
  4679. * Function for handling a template ref
  4680. */
  4681. function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
  4682. if (isArray(rawRef)) {
  4683. rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
  4684. return;
  4685. }
  4686. if (isAsyncWrapper(vnode) && !isUnmount) {
  4687. // when mounting async components, nothing needs to be done,
  4688. // because the template ref is forwarded to inner component
  4689. return;
  4690. }
  4691. const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
  4692. ? getExposeProxy(vnode.component) || vnode.component.proxy
  4693. : vnode.el;
  4694. const value = isUnmount ? null : refValue;
  4695. const { i: owner, r: ref } = rawRef;
  4696. if (!owner) {
  4697. warn$1(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
  4698. `A vnode with ref must be created inside the render function.`);
  4699. return;
  4700. }
  4701. const oldRef = oldRawRef && oldRawRef.r;
  4702. const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
  4703. const setupState = owner.setupState;
  4704. // dynamic ref changed. unset old ref
  4705. if (oldRef != null && oldRef !== ref) {
  4706. if (isString(oldRef)) {
  4707. refs[oldRef] = null;
  4708. if (hasOwn(setupState, oldRef)) {
  4709. setupState[oldRef] = null;
  4710. }
  4711. }
  4712. else if (isRef(oldRef)) {
  4713. oldRef.value = null;
  4714. }
  4715. }
  4716. if (isFunction(ref)) {
  4717. callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
  4718. }
  4719. else {
  4720. const _isString = isString(ref);
  4721. const _isRef = isRef(ref);
  4722. if (_isString || _isRef) {
  4723. const doSet = () => {
  4724. if (rawRef.f) {
  4725. const existing = _isString ? refs[ref] : ref.value;
  4726. if (isUnmount) {
  4727. isArray(existing) && remove(existing, refValue);
  4728. }
  4729. else {
  4730. if (!isArray(existing)) {
  4731. if (_isString) {
  4732. refs[ref] = [refValue];
  4733. }
  4734. else {
  4735. ref.value = [refValue];
  4736. if (rawRef.k)
  4737. refs[rawRef.k] = ref.value;
  4738. }
  4739. }
  4740. else if (!existing.includes(refValue)) {
  4741. existing.push(refValue);
  4742. }
  4743. }
  4744. }
  4745. else if (_isString) {
  4746. refs[ref] = value;
  4747. if (hasOwn(setupState, ref)) {
  4748. setupState[ref] = value;
  4749. }
  4750. }
  4751. else if (isRef(ref)) {
  4752. ref.value = value;
  4753. if (rawRef.k)
  4754. refs[rawRef.k] = value;
  4755. }
  4756. else {
  4757. warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
  4758. }
  4759. };
  4760. if (value) {
  4761. doSet.id = -1;
  4762. queuePostRenderEffect(doSet, parentSuspense);
  4763. }
  4764. else {
  4765. doSet();
  4766. }
  4767. }
  4768. else {
  4769. warn$1('Invalid template ref type:', ref, `(${typeof ref})`);
  4770. }
  4771. }
  4772. }
  4773. let hasMismatch = false;
  4774. const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
  4775. const isComment = (node) => node.nodeType === 8 /* COMMENT */;
  4776. // Note: hydration is DOM-specific
  4777. // But we have to place it in core due to tight coupling with core - splitting
  4778. // it out creates a ton of unnecessary complexity.
  4779. // Hydration also depends on some renderer internal logic which needs to be
  4780. // passed in via arguments.
  4781. function createHydrationFunctions(rendererInternals) {
  4782. const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
  4783. const hydrate = (vnode, container) => {
  4784. if (!container.hasChildNodes()) {
  4785. warn$1(`Attempting to hydrate existing markup but container is empty. ` +
  4786. `Performing full mount instead.`);
  4787. patch(null, vnode, container);
  4788. flushPostFlushCbs();
  4789. return;
  4790. }
  4791. hasMismatch = false;
  4792. hydrateNode(container.firstChild, vnode, null, null, null);
  4793. flushPostFlushCbs();
  4794. if (hasMismatch && !false) {
  4795. // this error should show up in production
  4796. console.error(`Hydration completed but contains mismatches.`);
  4797. }
  4798. };
  4799. const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
  4800. const isFragmentStart = isComment(node) && node.data === '[';
  4801. const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
  4802. const { type, ref, shapeFlag } = vnode;
  4803. const domType = node.nodeType;
  4804. vnode.el = node;
  4805. let nextNode = null;
  4806. switch (type) {
  4807. case Text:
  4808. if (domType !== 3 /* TEXT */) {
  4809. nextNode = onMismatch();
  4810. }
  4811. else {
  4812. if (node.data !== vnode.children) {
  4813. hasMismatch = true;
  4814. warn$1(`Hydration text mismatch:` +
  4815. `\n- Client: ${JSON.stringify(node.data)}` +
  4816. `\n- Server: ${JSON.stringify(vnode.children)}`);
  4817. node.data = vnode.children;
  4818. }
  4819. nextNode = nextSibling(node);
  4820. }
  4821. break;
  4822. case Comment:
  4823. if (domType !== 8 /* COMMENT */ || isFragmentStart) {
  4824. nextNode = onMismatch();
  4825. }
  4826. else {
  4827. nextNode = nextSibling(node);
  4828. }
  4829. break;
  4830. case Static:
  4831. if (domType !== 1 /* ELEMENT */) {
  4832. nextNode = onMismatch();
  4833. }
  4834. else {
  4835. // determine anchor, adopt content
  4836. nextNode = node;
  4837. // if the static vnode has its content stripped during build,
  4838. // adopt it from the server-rendered HTML.
  4839. const needToAdoptContent = !vnode.children.length;
  4840. for (let i = 0; i < vnode.staticCount; i++) {
  4841. if (needToAdoptContent)
  4842. vnode.children += nextNode.outerHTML;
  4843. if (i === vnode.staticCount - 1) {
  4844. vnode.anchor = nextNode;
  4845. }
  4846. nextNode = nextSibling(nextNode);
  4847. }
  4848. return nextNode;
  4849. }
  4850. break;
  4851. case Fragment:
  4852. if (!isFragmentStart) {
  4853. nextNode = onMismatch();
  4854. }
  4855. else {
  4856. nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  4857. }
  4858. break;
  4859. default:
  4860. if (shapeFlag & 1 /* ELEMENT */) {
  4861. if (domType !== 1 /* ELEMENT */ ||
  4862. vnode.type.toLowerCase() !==
  4863. node.tagName.toLowerCase()) {
  4864. nextNode = onMismatch();
  4865. }
  4866. else {
  4867. nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  4868. }
  4869. }
  4870. else if (shapeFlag & 6 /* COMPONENT */) {
  4871. // when setting up the render effect, if the initial vnode already
  4872. // has .el set, the component will perform hydration instead of mount
  4873. // on its sub-tree.
  4874. vnode.slotScopeIds = slotScopeIds;
  4875. const container = parentNode(node);
  4876. mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
  4877. // component may be async, so in the case of fragments we cannot rely
  4878. // on component's rendered output to determine the end of the fragment
  4879. // instead, we do a lookahead to find the end anchor node.
  4880. nextNode = isFragmentStart
  4881. ? locateClosingAsyncAnchor(node)
  4882. : nextSibling(node);
  4883. // #3787
  4884. // if component is async, it may get moved / unmounted before its
  4885. // inner component is loaded, so we need to give it a placeholder
  4886. // vnode that matches its adopted DOM.
  4887. if (isAsyncWrapper(vnode)) {
  4888. let subTree;
  4889. if (isFragmentStart) {
  4890. subTree = createVNode(Fragment);
  4891. subTree.anchor = nextNode
  4892. ? nextNode.previousSibling
  4893. : container.lastChild;
  4894. }
  4895. else {
  4896. subTree =
  4897. node.nodeType === 3 ? createTextVNode('') : createVNode('div');
  4898. }
  4899. subTree.el = node;
  4900. vnode.component.subTree = subTree;
  4901. }
  4902. }
  4903. else if (shapeFlag & 64 /* TELEPORT */) {
  4904. if (domType !== 8 /* COMMENT */) {
  4905. nextNode = onMismatch();
  4906. }
  4907. else {
  4908. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
  4909. }
  4910. }
  4911. else if (shapeFlag & 128 /* SUSPENSE */) {
  4912. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
  4913. }
  4914. else {
  4915. warn$1('Invalid HostVNode type:', type, `(${typeof type})`);
  4916. }
  4917. }
  4918. if (ref != null) {
  4919. setRef(ref, null, parentSuspense, vnode);
  4920. }
  4921. return nextNode;
  4922. };
  4923. const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  4924. optimized = optimized || !!vnode.dynamicChildren;
  4925. const { type, props, patchFlag, shapeFlag, dirs } = vnode;
  4926. // #4006 for form elements with non-string v-model value bindings
  4927. // e.g. <option :value="obj">, <input type="checkbox" :true-value="1">
  4928. const forcePatchValue = (type === 'input' && dirs) || type === 'option';
  4929. // skip props & children if this is hoisted static nodes
  4930. if (forcePatchValue || patchFlag !== -1 /* HOISTED */) {
  4931. if (dirs) {
  4932. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  4933. }
  4934. // props
  4935. if (props) {
  4936. if (forcePatchValue ||
  4937. !optimized ||
  4938. patchFlag & (16 /* FULL_PROPS */ | 32 /* HYDRATE_EVENTS */)) {
  4939. for (const key in props) {
  4940. if ((forcePatchValue && key.endsWith('value')) ||
  4941. (isOn(key) && !isReservedProp(key))) {
  4942. patchProp(el, key, null, props[key], false, undefined, parentComponent);
  4943. }
  4944. }
  4945. }
  4946. else if (props.onClick) {
  4947. // Fast path for click listeners (which is most often) to avoid
  4948. // iterating through props.
  4949. patchProp(el, 'onClick', null, props.onClick, false, undefined, parentComponent);
  4950. }
  4951. }
  4952. // vnode / directive hooks
  4953. let vnodeHooks;
  4954. if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
  4955. invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  4956. }
  4957. if (dirs) {
  4958. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  4959. }
  4960. if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
  4961. queueEffectWithSuspense(() => {
  4962. vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  4963. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  4964. }, parentSuspense);
  4965. }
  4966. // children
  4967. if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
  4968. // skip if element has innerHTML / textContent
  4969. !(props && (props.innerHTML || props.textContent))) {
  4970. let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
  4971. let hasWarned = false;
  4972. while (next) {
  4973. hasMismatch = true;
  4974. if (!hasWarned) {
  4975. warn$1(`Hydration children mismatch in <${vnode.type}>: ` +
  4976. `server rendered element contains more child nodes than client vdom.`);
  4977. hasWarned = true;
  4978. }
  4979. // The SSRed DOM contains more nodes than it should. Remove them.
  4980. const cur = next;
  4981. next = next.nextSibling;
  4982. remove(cur);
  4983. }
  4984. }
  4985. else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  4986. if (el.textContent !== vnode.children) {
  4987. hasMismatch = true;
  4988. warn$1(`Hydration text content mismatch in <${vnode.type}>:\n` +
  4989. `- Client: ${el.textContent}\n` +
  4990. `- Server: ${vnode.children}`);
  4991. el.textContent = vnode.children;
  4992. }
  4993. }
  4994. }
  4995. return el.nextSibling;
  4996. };
  4997. const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  4998. optimized = optimized || !!parentVNode.dynamicChildren;
  4999. const children = parentVNode.children;
  5000. const l = children.length;
  5001. let hasWarned = false;
  5002. for (let i = 0; i < l; i++) {
  5003. const vnode = optimized
  5004. ? children[i]
  5005. : (children[i] = normalizeVNode(children[i]));
  5006. if (node) {
  5007. node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
  5008. }
  5009. else if (vnode.type === Text && !vnode.children) {
  5010. continue;
  5011. }
  5012. else {
  5013. hasMismatch = true;
  5014. if (!hasWarned) {
  5015. warn$1(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
  5016. `server rendered element contains fewer child nodes than client vdom.`);
  5017. hasWarned = true;
  5018. }
  5019. // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
  5020. patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
  5021. }
  5022. }
  5023. return node;
  5024. };
  5025. const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
  5026. const { slotScopeIds: fragmentSlotScopeIds } = vnode;
  5027. if (fragmentSlotScopeIds) {
  5028. slotScopeIds = slotScopeIds
  5029. ? slotScopeIds.concat(fragmentSlotScopeIds)
  5030. : fragmentSlotScopeIds;
  5031. }
  5032. const container = parentNode(node);
  5033. const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
  5034. if (next && isComment(next) && next.data === ']') {
  5035. return nextSibling((vnode.anchor = next));
  5036. }
  5037. else {
  5038. // fragment didn't hydrate successfully, since we didn't get a end anchor
  5039. // back. This should have led to node/children mismatch warnings.
  5040. hasMismatch = true;
  5041. // since the anchor is missing, we need to create one and insert it
  5042. insert((vnode.anchor = createComment(`]`)), container, next);
  5043. return next;
  5044. }
  5045. };
  5046. const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
  5047. hasMismatch = true;
  5048. warn$1(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
  5049. ? `(text)`
  5050. : isComment(node) && node.data === '['
  5051. ? `(start of fragment)`
  5052. : ``);
  5053. vnode.el = null;
  5054. if (isFragment) {
  5055. // remove excessive fragment nodes
  5056. const end = locateClosingAsyncAnchor(node);
  5057. while (true) {
  5058. const next = nextSibling(node);
  5059. if (next && next !== end) {
  5060. remove(next);
  5061. }
  5062. else {
  5063. break;
  5064. }
  5065. }
  5066. }
  5067. const next = nextSibling(node);
  5068. const container = parentNode(node);
  5069. remove(node);
  5070. patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
  5071. return next;
  5072. };
  5073. const locateClosingAsyncAnchor = (node) => {
  5074. let match = 0;
  5075. while (node) {
  5076. node = nextSibling(node);
  5077. if (node && isComment(node)) {
  5078. if (node.data === '[')
  5079. match++;
  5080. if (node.data === ']') {
  5081. if (match === 0) {
  5082. return nextSibling(node);
  5083. }
  5084. else {
  5085. match--;
  5086. }
  5087. }
  5088. }
  5089. }
  5090. return node;
  5091. };
  5092. return [hydrate, hydrateNode];
  5093. }
  5094. let supported;
  5095. let perf;
  5096. function startMeasure(instance, type) {
  5097. if (instance.appContext.config.performance && isSupported()) {
  5098. perf.mark(`vue-${type}-${instance.uid}`);
  5099. }
  5100. {
  5101. devtoolsPerfStart(instance, type, supported ? perf.now() : Date.now());
  5102. }
  5103. }
  5104. function endMeasure(instance, type) {
  5105. if (instance.appContext.config.performance && isSupported()) {
  5106. const startTag = `vue-${type}-${instance.uid}`;
  5107. const endTag = startTag + `:end`;
  5108. perf.mark(endTag);
  5109. perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
  5110. perf.clearMarks(startTag);
  5111. perf.clearMarks(endTag);
  5112. }
  5113. {
  5114. devtoolsPerfEnd(instance, type, supported ? perf.now() : Date.now());
  5115. }
  5116. }
  5117. function isSupported() {
  5118. if (supported !== undefined) {
  5119. return supported;
  5120. }
  5121. /* eslint-disable no-restricted-globals */
  5122. if (typeof window !== 'undefined' && window.performance) {
  5123. supported = true;
  5124. perf = window.performance;
  5125. }
  5126. else {
  5127. supported = false;
  5128. }
  5129. /* eslint-enable no-restricted-globals */
  5130. return supported;
  5131. }
  5132. const queuePostRenderEffect = queueEffectWithSuspense
  5133. ;
  5134. /**
  5135. * The createRenderer function accepts two generic arguments:
  5136. * HostNode and HostElement, corresponding to Node and Element types in the
  5137. * host environment. For example, for runtime-dom, HostNode would be the DOM
  5138. * `Node` interface and HostElement would be the DOM `Element` interface.
  5139. *
  5140. * Custom renderers can pass in the platform specific types like this:
  5141. *
  5142. * ``` js
  5143. * const { render, createApp } = createRenderer<Node, Element>({
  5144. * patchProp,
  5145. * ...nodeOps
  5146. * })
  5147. * ```
  5148. */
  5149. function createRenderer(options) {
  5150. return baseCreateRenderer(options);
  5151. }
  5152. // Separate API for creating hydration-enabled renderer.
  5153. // Hydration logic is only used when calling this function, making it
  5154. // tree-shakable.
  5155. function createHydrationRenderer(options) {
  5156. return baseCreateRenderer(options, createHydrationFunctions);
  5157. }
  5158. // implementation
  5159. function baseCreateRenderer(options, createHydrationFns) {
  5160. const target = getGlobalThis();
  5161. target.__VUE__ = true;
  5162. {
  5163. setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target);
  5164. }
  5165. 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;
  5166. // Note: functions inside this closure should use `const xxx = () => {}`
  5167. // style in order to prevent being inlined by minifiers.
  5168. const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = isHmrUpdating ? false : !!n2.dynamicChildren) => {
  5169. if (n1 === n2) {
  5170. return;
  5171. }
  5172. // patching & not same type, unmount old tree
  5173. if (n1 && !isSameVNodeType(n1, n2)) {
  5174. anchor = getNextHostNode(n1);
  5175. unmount(n1, parentComponent, parentSuspense, true);
  5176. n1 = null;
  5177. }
  5178. if (n2.patchFlag === -2 /* BAIL */) {
  5179. optimized = false;
  5180. n2.dynamicChildren = null;
  5181. }
  5182. const { type, ref, shapeFlag } = n2;
  5183. switch (type) {
  5184. case Text:
  5185. processText(n1, n2, container, anchor);
  5186. break;
  5187. case Comment:
  5188. processCommentNode(n1, n2, container, anchor);
  5189. break;
  5190. case Static:
  5191. if (n1 == null) {
  5192. mountStaticNode(n2, container, anchor, isSVG);
  5193. }
  5194. else {
  5195. patchStaticNode(n1, n2, container, isSVG);
  5196. }
  5197. break;
  5198. case Fragment:
  5199. processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5200. break;
  5201. default:
  5202. if (shapeFlag & 1 /* ELEMENT */) {
  5203. processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5204. }
  5205. else if (shapeFlag & 6 /* COMPONENT */) {
  5206. processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5207. }
  5208. else if (shapeFlag & 64 /* TELEPORT */) {
  5209. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
  5210. }
  5211. else if (shapeFlag & 128 /* SUSPENSE */) {
  5212. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
  5213. }
  5214. else {
  5215. warn$1('Invalid VNode type:', type, `(${typeof type})`);
  5216. }
  5217. }
  5218. // set ref
  5219. if (ref != null && parentComponent) {
  5220. setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
  5221. }
  5222. };
  5223. const processText = (n1, n2, container, anchor) => {
  5224. if (n1 == null) {
  5225. hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
  5226. }
  5227. else {
  5228. const el = (n2.el = n1.el);
  5229. if (n2.children !== n1.children) {
  5230. hostSetText(el, n2.children);
  5231. }
  5232. }
  5233. };
  5234. const processCommentNode = (n1, n2, container, anchor) => {
  5235. if (n1 == null) {
  5236. hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
  5237. }
  5238. else {
  5239. // there's no support for dynamic comments
  5240. n2.el = n1.el;
  5241. }
  5242. };
  5243. const mountStaticNode = (n2, container, anchor, isSVG) => {
  5244. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  5245. };
  5246. /**
  5247. * Dev / HMR only
  5248. */
  5249. const patchStaticNode = (n1, n2, container, isSVG) => {
  5250. // static nodes are only patched during dev for HMR
  5251. if (n2.children !== n1.children) {
  5252. const anchor = hostNextSibling(n1.anchor);
  5253. // remove existing
  5254. removeStaticNode(n1);
  5255. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  5256. }
  5257. else {
  5258. n2.el = n1.el;
  5259. n2.anchor = n1.anchor;
  5260. }
  5261. };
  5262. const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
  5263. let next;
  5264. while (el && el !== anchor) {
  5265. next = hostNextSibling(el);
  5266. hostInsert(el, container, nextSibling);
  5267. el = next;
  5268. }
  5269. hostInsert(anchor, container, nextSibling);
  5270. };
  5271. const removeStaticNode = ({ el, anchor }) => {
  5272. let next;
  5273. while (el && el !== anchor) {
  5274. next = hostNextSibling(el);
  5275. hostRemove(el);
  5276. el = next;
  5277. }
  5278. hostRemove(anchor);
  5279. };
  5280. const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  5281. isSVG = isSVG || n2.type === 'svg';
  5282. if (n1 == null) {
  5283. mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5284. }
  5285. else {
  5286. patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5287. }
  5288. };
  5289. const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  5290. let el;
  5291. let vnodeHook;
  5292. const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
  5293. {
  5294. el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
  5295. // mount children first, since some props may rely on child content
  5296. // being already rendered, e.g. `<select value>`
  5297. if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  5298. hostSetElementText(el, vnode.children);
  5299. }
  5300. else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5301. mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized);
  5302. }
  5303. if (dirs) {
  5304. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  5305. }
  5306. // props
  5307. if (props) {
  5308. for (const key in props) {
  5309. if (key !== 'value' && !isReservedProp(key)) {
  5310. hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  5311. }
  5312. }
  5313. /**
  5314. * Special case for setting value on DOM elements:
  5315. * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024)
  5316. * - it needs to be forced (#1471)
  5317. * #2353 proposes adding another renderer option to configure this, but
  5318. * the properties affects are so finite it is worth special casing it
  5319. * here to reduce the complexity. (Special casing it also should not
  5320. * affect non-DOM renderers)
  5321. */
  5322. if ('value' in props) {
  5323. hostPatchProp(el, 'value', null, props.value);
  5324. }
  5325. if ((vnodeHook = props.onVnodeBeforeMount)) {
  5326. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  5327. }
  5328. }
  5329. // scopeId
  5330. setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
  5331. }
  5332. {
  5333. Object.defineProperty(el, '__vnode', {
  5334. value: vnode,
  5335. enumerable: false
  5336. });
  5337. Object.defineProperty(el, '__vueParentComponent', {
  5338. value: parentComponent,
  5339. enumerable: false
  5340. });
  5341. }
  5342. if (dirs) {
  5343. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  5344. }
  5345. // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
  5346. // #1689 For inside suspense + suspense resolved case, just call it
  5347. const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
  5348. transition &&
  5349. !transition.persisted;
  5350. if (needCallTransitionHooks) {
  5351. transition.beforeEnter(el);
  5352. }
  5353. hostInsert(el, container, anchor);
  5354. if ((vnodeHook = props && props.onVnodeMounted) ||
  5355. needCallTransitionHooks ||
  5356. dirs) {
  5357. queuePostRenderEffect(() => {
  5358. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  5359. needCallTransitionHooks && transition.enter(el);
  5360. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  5361. }, parentSuspense);
  5362. }
  5363. };
  5364. const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
  5365. if (scopeId) {
  5366. hostSetScopeId(el, scopeId);
  5367. }
  5368. if (slotScopeIds) {
  5369. for (let i = 0; i < slotScopeIds.length; i++) {
  5370. hostSetScopeId(el, slotScopeIds[i]);
  5371. }
  5372. }
  5373. if (parentComponent) {
  5374. let subTree = parentComponent.subTree;
  5375. if (subTree.patchFlag > 0 &&
  5376. subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
  5377. subTree =
  5378. filterSingleRoot(subTree.children) || subTree;
  5379. }
  5380. if (vnode === subTree) {
  5381. const parentVNode = parentComponent.vnode;
  5382. setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
  5383. }
  5384. }
  5385. };
  5386. const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
  5387. for (let i = start; i < children.length; i++) {
  5388. const child = (children[i] = optimized
  5389. ? cloneIfMounted(children[i])
  5390. : normalizeVNode(children[i]));
  5391. patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5392. }
  5393. };
  5394. const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  5395. const el = (n2.el = n1.el);
  5396. let { patchFlag, dynamicChildren, dirs } = n2;
  5397. // #1426 take the old vnode's patch flag into account since user may clone a
  5398. // compiler-generated vnode, which de-opts to FULL_PROPS
  5399. patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
  5400. const oldProps = n1.props || EMPTY_OBJ;
  5401. const newProps = n2.props || EMPTY_OBJ;
  5402. let vnodeHook;
  5403. // disable recurse in beforeUpdate hooks
  5404. parentComponent && toggleRecurse(parentComponent, false);
  5405. if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
  5406. invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  5407. }
  5408. if (dirs) {
  5409. invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
  5410. }
  5411. parentComponent && toggleRecurse(parentComponent, true);
  5412. if (isHmrUpdating) {
  5413. // HMR updated, force full diff
  5414. patchFlag = 0;
  5415. optimized = false;
  5416. dynamicChildren = null;
  5417. }
  5418. const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
  5419. if (dynamicChildren) {
  5420. patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
  5421. if (parentComponent && parentComponent.type.__hmrId) {
  5422. traverseStaticChildren(n1, n2);
  5423. }
  5424. }
  5425. else if (!optimized) {
  5426. // full diff
  5427. patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
  5428. }
  5429. if (patchFlag > 0) {
  5430. // the presence of a patchFlag means this element's render code was
  5431. // generated by the compiler and can take the fast path.
  5432. // in this path old node and new node are guaranteed to have the same shape
  5433. // (i.e. at the exact same position in the source template)
  5434. if (patchFlag & 16 /* FULL_PROPS */) {
  5435. // element props contain dynamic keys, full diff needed
  5436. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  5437. }
  5438. else {
  5439. // class
  5440. // this flag is matched when the element has dynamic class bindings.
  5441. if (patchFlag & 2 /* CLASS */) {
  5442. if (oldProps.class !== newProps.class) {
  5443. hostPatchProp(el, 'class', null, newProps.class, isSVG);
  5444. }
  5445. }
  5446. // style
  5447. // this flag is matched when the element has dynamic style bindings
  5448. if (patchFlag & 4 /* STYLE */) {
  5449. hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
  5450. }
  5451. // props
  5452. // This flag is matched when the element has dynamic prop/attr bindings
  5453. // other than class and style. The keys of dynamic prop/attrs are saved for
  5454. // faster iteration.
  5455. // Note dynamic keys like :[foo]="bar" will cause this optimization to
  5456. // bail out and go through a full diff because we need to unset the old key
  5457. if (patchFlag & 8 /* PROPS */) {
  5458. // if the flag is present then dynamicProps must be non-null
  5459. const propsToUpdate = n2.dynamicProps;
  5460. for (let i = 0; i < propsToUpdate.length; i++) {
  5461. const key = propsToUpdate[i];
  5462. const prev = oldProps[key];
  5463. const next = newProps[key];
  5464. // #1471 force patch value
  5465. if (next !== prev || key === 'value') {
  5466. hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
  5467. }
  5468. }
  5469. }
  5470. }
  5471. // text
  5472. // This flag is matched when the element has only dynamic text children.
  5473. if (patchFlag & 1 /* TEXT */) {
  5474. if (n1.children !== n2.children) {
  5475. hostSetElementText(el, n2.children);
  5476. }
  5477. }
  5478. }
  5479. else if (!optimized && dynamicChildren == null) {
  5480. // unoptimized, full diff
  5481. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  5482. }
  5483. if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
  5484. queuePostRenderEffect(() => {
  5485. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  5486. dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
  5487. }, parentSuspense);
  5488. }
  5489. };
  5490. // The fast path for blocks.
  5491. const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
  5492. for (let i = 0; i < newChildren.length; i++) {
  5493. const oldVNode = oldChildren[i];
  5494. const newVNode = newChildren[i];
  5495. // Determine the container (parent element) for the patch.
  5496. const container =
  5497. // oldVNode may be an errored async setup() component inside Suspense
  5498. // which will not have a mounted element
  5499. oldVNode.el &&
  5500. // - In the case of a Fragment, we need to provide the actual parent
  5501. // of the Fragment itself so it can move its children.
  5502. (oldVNode.type === Fragment ||
  5503. // - In the case of different nodes, there is going to be a replacement
  5504. // which also requires the correct parent container
  5505. !isSameVNodeType(oldVNode, newVNode) ||
  5506. // - In the case of a component, it could contain anything.
  5507. oldVNode.shapeFlag & (6 /* COMPONENT */ | 64 /* TELEPORT */))
  5508. ? hostParentNode(oldVNode.el)
  5509. : // In other cases, the parent container is not actually used so we
  5510. // just pass the block element here to avoid a DOM parentNode call.
  5511. fallbackContainer;
  5512. patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
  5513. }
  5514. };
  5515. const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
  5516. if (oldProps !== newProps) {
  5517. for (const key in newProps) {
  5518. // empty string is not valid prop
  5519. if (isReservedProp(key))
  5520. continue;
  5521. const next = newProps[key];
  5522. const prev = oldProps[key];
  5523. // defer patching value
  5524. if (next !== prev && key !== 'value') {
  5525. hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  5526. }
  5527. }
  5528. if (oldProps !== EMPTY_OBJ) {
  5529. for (const key in oldProps) {
  5530. if (!isReservedProp(key) && !(key in newProps)) {
  5531. hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  5532. }
  5533. }
  5534. }
  5535. if ('value' in newProps) {
  5536. hostPatchProp(el, 'value', oldProps.value, newProps.value);
  5537. }
  5538. }
  5539. };
  5540. const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  5541. const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
  5542. const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
  5543. let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
  5544. if (isHmrUpdating) {
  5545. // HMR updated, force full diff
  5546. patchFlag = 0;
  5547. optimized = false;
  5548. dynamicChildren = null;
  5549. }
  5550. // check if this is a slot fragment with :slotted scope ids
  5551. if (fragmentSlotScopeIds) {
  5552. slotScopeIds = slotScopeIds
  5553. ? slotScopeIds.concat(fragmentSlotScopeIds)
  5554. : fragmentSlotScopeIds;
  5555. }
  5556. if (n1 == null) {
  5557. hostInsert(fragmentStartAnchor, container, anchor);
  5558. hostInsert(fragmentEndAnchor, container, anchor);
  5559. // a fragment can only have array children
  5560. // since they are either generated by the compiler, or implicitly created
  5561. // from arrays.
  5562. mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5563. }
  5564. else {
  5565. if (patchFlag > 0 &&
  5566. patchFlag & 64 /* STABLE_FRAGMENT */ &&
  5567. dynamicChildren &&
  5568. // #2715 the previous fragment could've been a BAILed one as a result
  5569. // of renderSlot() with no valid children
  5570. n1.dynamicChildren) {
  5571. // a stable fragment (template root or <template v-for>) doesn't need to
  5572. // patch children order, but it may contain dynamicChildren.
  5573. patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
  5574. if (parentComponent && parentComponent.type.__hmrId) {
  5575. traverseStaticChildren(n1, n2);
  5576. }
  5577. else if (
  5578. // #2080 if the stable fragment has a key, it's a <template v-for> that may
  5579. // get moved around. Make sure all root level vnodes inherit el.
  5580. // #2134 or if it's a component root, it may also get moved around
  5581. // as the component is being moved.
  5582. n2.key != null ||
  5583. (parentComponent && n2 === parentComponent.subTree)) {
  5584. traverseStaticChildren(n1, n2, true /* shallow */);
  5585. }
  5586. }
  5587. else {
  5588. // keyed / unkeyed, or manual fragments.
  5589. // for keyed & unkeyed, since they are compiler generated from v-for,
  5590. // each child is guaranteed to be a block so the fragment will never
  5591. // have dynamicChildren.
  5592. patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5593. }
  5594. }
  5595. };
  5596. const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  5597. n2.slotScopeIds = slotScopeIds;
  5598. if (n1 == null) {
  5599. if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
  5600. parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
  5601. }
  5602. else {
  5603. mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5604. }
  5605. }
  5606. else {
  5607. updateComponent(n1, n2, optimized);
  5608. }
  5609. };
  5610. const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5611. const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
  5612. if (instance.type.__hmrId) {
  5613. registerHMR(instance);
  5614. }
  5615. {
  5616. pushWarningContext(initialVNode);
  5617. startMeasure(instance, `mount`);
  5618. }
  5619. // inject renderer internals for keepAlive
  5620. if (isKeepAlive(initialVNode)) {
  5621. instance.ctx.renderer = internals;
  5622. }
  5623. // resolve props and slots for setup context
  5624. {
  5625. {
  5626. startMeasure(instance, `init`);
  5627. }
  5628. setupComponent(instance);
  5629. {
  5630. endMeasure(instance, `init`);
  5631. }
  5632. }
  5633. // setup() is async. This component relies on async logic to be resolved
  5634. // before proceeding
  5635. if (instance.asyncDep) {
  5636. parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
  5637. // Give it a placeholder if this is not hydration
  5638. // TODO handle self-defined fallback
  5639. if (!initialVNode.el) {
  5640. const placeholder = (instance.subTree = createVNode(Comment));
  5641. processCommentNode(null, placeholder, container, anchor);
  5642. }
  5643. return;
  5644. }
  5645. setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
  5646. {
  5647. popWarningContext();
  5648. endMeasure(instance, `mount`);
  5649. }
  5650. };
  5651. const updateComponent = (n1, n2, optimized) => {
  5652. const instance = (n2.component = n1.component);
  5653. if (shouldUpdateComponent(n1, n2, optimized)) {
  5654. if (instance.asyncDep &&
  5655. !instance.asyncResolved) {
  5656. // async & still pending - just update props and slots
  5657. // since the component's reactive effect for render isn't set-up yet
  5658. {
  5659. pushWarningContext(n2);
  5660. }
  5661. updateComponentPreRender(instance, n2, optimized);
  5662. {
  5663. popWarningContext();
  5664. }
  5665. return;
  5666. }
  5667. else {
  5668. // normal update
  5669. instance.next = n2;
  5670. // in case the child component is also queued, remove it to avoid
  5671. // double updating the same child component in the same flush.
  5672. invalidateJob(instance.update);
  5673. // instance.update is the reactive effect.
  5674. instance.update();
  5675. }
  5676. }
  5677. else {
  5678. // no update needed. just copy over properties
  5679. n2.component = n1.component;
  5680. n2.el = n1.el;
  5681. instance.vnode = n2;
  5682. }
  5683. };
  5684. const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
  5685. const componentUpdateFn = () => {
  5686. if (!instance.isMounted) {
  5687. let vnodeHook;
  5688. const { el, props } = initialVNode;
  5689. const { bm, m, parent } = instance;
  5690. const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
  5691. toggleRecurse(instance, false);
  5692. // beforeMount hook
  5693. if (bm) {
  5694. invokeArrayFns(bm);
  5695. }
  5696. // onVnodeBeforeMount
  5697. if (!isAsyncWrapperVNode &&
  5698. (vnodeHook = props && props.onVnodeBeforeMount)) {
  5699. invokeVNodeHook(vnodeHook, parent, initialVNode);
  5700. }
  5701. toggleRecurse(instance, true);
  5702. if (el && hydrateNode) {
  5703. // vnode has adopted host node - perform hydration instead of mount.
  5704. const hydrateSubTree = () => {
  5705. {
  5706. startMeasure(instance, `render`);
  5707. }
  5708. instance.subTree = renderComponentRoot(instance);
  5709. {
  5710. endMeasure(instance, `render`);
  5711. }
  5712. {
  5713. startMeasure(instance, `hydrate`);
  5714. }
  5715. hydrateNode(el, instance.subTree, instance, parentSuspense, null);
  5716. {
  5717. endMeasure(instance, `hydrate`);
  5718. }
  5719. };
  5720. if (isAsyncWrapperVNode) {
  5721. initialVNode.type.__asyncLoader().then(
  5722. // note: we are moving the render call into an async callback,
  5723. // which means it won't track dependencies - but it's ok because
  5724. // a server-rendered async wrapper is already in resolved state
  5725. // and it will never need to change.
  5726. () => !instance.isUnmounted && hydrateSubTree());
  5727. }
  5728. else {
  5729. hydrateSubTree();
  5730. }
  5731. }
  5732. else {
  5733. {
  5734. startMeasure(instance, `render`);
  5735. }
  5736. const subTree = (instance.subTree = renderComponentRoot(instance));
  5737. {
  5738. endMeasure(instance, `render`);
  5739. }
  5740. {
  5741. startMeasure(instance, `patch`);
  5742. }
  5743. patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
  5744. {
  5745. endMeasure(instance, `patch`);
  5746. }
  5747. initialVNode.el = subTree.el;
  5748. }
  5749. // mounted hook
  5750. if (m) {
  5751. queuePostRenderEffect(m, parentSuspense);
  5752. }
  5753. // onVnodeMounted
  5754. if (!isAsyncWrapperVNode &&
  5755. (vnodeHook = props && props.onVnodeMounted)) {
  5756. const scopedInitialVNode = initialVNode;
  5757. queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
  5758. }
  5759. // activated hook for keep-alive roots.
  5760. // #1742 activated hook must be accessed after first render
  5761. // since the hook may be injected by a child keep-alive
  5762. if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  5763. instance.a && queuePostRenderEffect(instance.a, parentSuspense);
  5764. }
  5765. instance.isMounted = true;
  5766. {
  5767. devtoolsComponentAdded(instance);
  5768. }
  5769. // #2458: deference mount-only object parameters to prevent memleaks
  5770. initialVNode = container = anchor = null;
  5771. }
  5772. else {
  5773. // updateComponent
  5774. // This is triggered by mutation of component's own state (next: null)
  5775. // OR parent calling processComponent (next: VNode)
  5776. let { next, bu, u, parent, vnode } = instance;
  5777. let originNext = next;
  5778. let vnodeHook;
  5779. {
  5780. pushWarningContext(next || instance.vnode);
  5781. }
  5782. // Disallow component effect recursion during pre-lifecycle hooks.
  5783. toggleRecurse(instance, false);
  5784. if (next) {
  5785. next.el = vnode.el;
  5786. updateComponentPreRender(instance, next, optimized);
  5787. }
  5788. else {
  5789. next = vnode;
  5790. }
  5791. // beforeUpdate hook
  5792. if (bu) {
  5793. invokeArrayFns(bu);
  5794. }
  5795. // onVnodeBeforeUpdate
  5796. if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
  5797. invokeVNodeHook(vnodeHook, parent, next, vnode);
  5798. }
  5799. toggleRecurse(instance, true);
  5800. // render
  5801. {
  5802. startMeasure(instance, `render`);
  5803. }
  5804. const nextTree = renderComponentRoot(instance);
  5805. {
  5806. endMeasure(instance, `render`);
  5807. }
  5808. const prevTree = instance.subTree;
  5809. instance.subTree = nextTree;
  5810. {
  5811. startMeasure(instance, `patch`);
  5812. }
  5813. patch(prevTree, nextTree,
  5814. // parent may have changed if it's in a teleport
  5815. hostParentNode(prevTree.el),
  5816. // anchor may have changed if it's in a fragment
  5817. getNextHostNode(prevTree), instance, parentSuspense, isSVG);
  5818. {
  5819. endMeasure(instance, `patch`);
  5820. }
  5821. next.el = nextTree.el;
  5822. if (originNext === null) {
  5823. // self-triggered update. In case of HOC, update parent component
  5824. // vnode el. HOC is indicated by parent instance's subTree pointing
  5825. // to child component's vnode
  5826. updateHOCHostEl(instance, nextTree.el);
  5827. }
  5828. // updated hook
  5829. if (u) {
  5830. queuePostRenderEffect(u, parentSuspense);
  5831. }
  5832. // onVnodeUpdated
  5833. if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
  5834. queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
  5835. }
  5836. {
  5837. devtoolsComponentUpdated(instance);
  5838. }
  5839. {
  5840. popWarningContext();
  5841. }
  5842. }
  5843. };
  5844. // create reactive effect for rendering
  5845. const effect = (instance.effect = new ReactiveEffect(componentUpdateFn, () => queueJob(instance.update), instance.scope // track it in component's effect scope
  5846. ));
  5847. const update = (instance.update = effect.run.bind(effect));
  5848. update.id = instance.uid;
  5849. // allowRecurse
  5850. // #1801, #2043 component render effects should allow recursive updates
  5851. toggleRecurse(instance, true);
  5852. {
  5853. effect.onTrack = instance.rtc
  5854. ? e => invokeArrayFns(instance.rtc, e)
  5855. : void 0;
  5856. effect.onTrigger = instance.rtg
  5857. ? e => invokeArrayFns(instance.rtg, e)
  5858. : void 0;
  5859. // @ts-ignore (for scheduler)
  5860. update.ownerInstance = instance;
  5861. }
  5862. update();
  5863. };
  5864. const updateComponentPreRender = (instance, nextVNode, optimized) => {
  5865. nextVNode.component = instance;
  5866. const prevProps = instance.vnode.props;
  5867. instance.vnode = nextVNode;
  5868. instance.next = null;
  5869. updateProps(instance, nextVNode.props, prevProps, optimized);
  5870. updateSlots(instance, nextVNode.children, optimized);
  5871. pauseTracking();
  5872. // props update may have triggered pre-flush watchers.
  5873. // flush them before the render update.
  5874. flushPreFlushCbs(undefined, instance.update);
  5875. resetTracking();
  5876. };
  5877. const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
  5878. const c1 = n1 && n1.children;
  5879. const prevShapeFlag = n1 ? n1.shapeFlag : 0;
  5880. const c2 = n2.children;
  5881. const { patchFlag, shapeFlag } = n2;
  5882. // fast path
  5883. if (patchFlag > 0) {
  5884. if (patchFlag & 128 /* KEYED_FRAGMENT */) {
  5885. // this could be either fully-keyed or mixed (some keyed some not)
  5886. // presence of patchFlag means children are guaranteed to be arrays
  5887. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5888. return;
  5889. }
  5890. else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
  5891. // unkeyed
  5892. patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5893. return;
  5894. }
  5895. }
  5896. // children has 3 possibilities: text, array or no children.
  5897. if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  5898. // text children fast path
  5899. if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
  5900. unmountChildren(c1, parentComponent, parentSuspense);
  5901. }
  5902. if (c2 !== c1) {
  5903. hostSetElementText(container, c2);
  5904. }
  5905. }
  5906. else {
  5907. if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
  5908. // prev children was array
  5909. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5910. // two arrays, cannot assume anything, do full diff
  5911. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5912. }
  5913. else {
  5914. // no new children, just unmount old
  5915. unmountChildren(c1, parentComponent, parentSuspense, true);
  5916. }
  5917. }
  5918. else {
  5919. // prev children was text OR null
  5920. // new children is array OR null
  5921. if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
  5922. hostSetElementText(container, '');
  5923. }
  5924. // mount new if array
  5925. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5926. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5927. }
  5928. }
  5929. }
  5930. };
  5931. const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  5932. c1 = c1 || EMPTY_ARR;
  5933. c2 = c2 || EMPTY_ARR;
  5934. const oldLength = c1.length;
  5935. const newLength = c2.length;
  5936. const commonLength = Math.min(oldLength, newLength);
  5937. let i;
  5938. for (i = 0; i < commonLength; i++) {
  5939. const nextChild = (c2[i] = optimized
  5940. ? cloneIfMounted(c2[i])
  5941. : normalizeVNode(c2[i]));
  5942. patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5943. }
  5944. if (oldLength > newLength) {
  5945. // remove old
  5946. unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
  5947. }
  5948. else {
  5949. // mount new
  5950. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
  5951. }
  5952. };
  5953. // can be all-keyed or mixed
  5954. const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
  5955. let i = 0;
  5956. const l2 = c2.length;
  5957. let e1 = c1.length - 1; // prev ending index
  5958. let e2 = l2 - 1; // next ending index
  5959. // 1. sync from start
  5960. // (a b) c
  5961. // (a b) d e
  5962. while (i <= e1 && i <= e2) {
  5963. const n1 = c1[i];
  5964. const n2 = (c2[i] = optimized
  5965. ? cloneIfMounted(c2[i])
  5966. : normalizeVNode(c2[i]));
  5967. if (isSameVNodeType(n1, n2)) {
  5968. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5969. }
  5970. else {
  5971. break;
  5972. }
  5973. i++;
  5974. }
  5975. // 2. sync from end
  5976. // a (b c)
  5977. // d e (b c)
  5978. while (i <= e1 && i <= e2) {
  5979. const n1 = c1[e1];
  5980. const n2 = (c2[e2] = optimized
  5981. ? cloneIfMounted(c2[e2])
  5982. : normalizeVNode(c2[e2]));
  5983. if (isSameVNodeType(n1, n2)) {
  5984. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  5985. }
  5986. else {
  5987. break;
  5988. }
  5989. e1--;
  5990. e2--;
  5991. }
  5992. // 3. common sequence + mount
  5993. // (a b)
  5994. // (a b) c
  5995. // i = 2, e1 = 1, e2 = 2
  5996. // (a b)
  5997. // c (a b)
  5998. // i = 0, e1 = -1, e2 = 0
  5999. if (i > e1) {
  6000. if (i <= e2) {
  6001. const nextPos = e2 + 1;
  6002. const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
  6003. while (i <= e2) {
  6004. patch(null, (c2[i] = optimized
  6005. ? cloneIfMounted(c2[i])
  6006. : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6007. i++;
  6008. }
  6009. }
  6010. }
  6011. // 4. common sequence + unmount
  6012. // (a b) c
  6013. // (a b)
  6014. // i = 2, e1 = 2, e2 = 1
  6015. // a (b c)
  6016. // (b c)
  6017. // i = 0, e1 = 0, e2 = -1
  6018. else if (i > e2) {
  6019. while (i <= e1) {
  6020. unmount(c1[i], parentComponent, parentSuspense, true);
  6021. i++;
  6022. }
  6023. }
  6024. // 5. unknown sequence
  6025. // [i ... e1 + 1]: a b [c d e] f g
  6026. // [i ... e2 + 1]: a b [e d c h] f g
  6027. // i = 2, e1 = 4, e2 = 5
  6028. else {
  6029. const s1 = i; // prev starting index
  6030. const s2 = i; // next starting index
  6031. // 5.1 build key:index map for newChildren
  6032. const keyToNewIndexMap = new Map();
  6033. for (i = s2; i <= e2; i++) {
  6034. const nextChild = (c2[i] = optimized
  6035. ? cloneIfMounted(c2[i])
  6036. : normalizeVNode(c2[i]));
  6037. if (nextChild.key != null) {
  6038. if (keyToNewIndexMap.has(nextChild.key)) {
  6039. warn$1(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
  6040. }
  6041. keyToNewIndexMap.set(nextChild.key, i);
  6042. }
  6043. }
  6044. // 5.2 loop through old children left to be patched and try to patch
  6045. // matching nodes & remove nodes that are no longer present
  6046. let j;
  6047. let patched = 0;
  6048. const toBePatched = e2 - s2 + 1;
  6049. let moved = false;
  6050. // used to track whether any node has moved
  6051. let maxNewIndexSoFar = 0;
  6052. // works as Map<newIndex, oldIndex>
  6053. // Note that oldIndex is offset by +1
  6054. // and oldIndex = 0 is a special value indicating the new node has
  6055. // no corresponding old node.
  6056. // used for determining longest stable subsequence
  6057. const newIndexToOldIndexMap = new Array(toBePatched);
  6058. for (i = 0; i < toBePatched; i++)
  6059. newIndexToOldIndexMap[i] = 0;
  6060. for (i = s1; i <= e1; i++) {
  6061. const prevChild = c1[i];
  6062. if (patched >= toBePatched) {
  6063. // all new children have been patched so this can only be a removal
  6064. unmount(prevChild, parentComponent, parentSuspense, true);
  6065. continue;
  6066. }
  6067. let newIndex;
  6068. if (prevChild.key != null) {
  6069. newIndex = keyToNewIndexMap.get(prevChild.key);
  6070. }
  6071. else {
  6072. // key-less node, try to locate a key-less node of the same type
  6073. for (j = s2; j <= e2; j++) {
  6074. if (newIndexToOldIndexMap[j - s2] === 0 &&
  6075. isSameVNodeType(prevChild, c2[j])) {
  6076. newIndex = j;
  6077. break;
  6078. }
  6079. }
  6080. }
  6081. if (newIndex === undefined) {
  6082. unmount(prevChild, parentComponent, parentSuspense, true);
  6083. }
  6084. else {
  6085. newIndexToOldIndexMap[newIndex - s2] = i + 1;
  6086. if (newIndex >= maxNewIndexSoFar) {
  6087. maxNewIndexSoFar = newIndex;
  6088. }
  6089. else {
  6090. moved = true;
  6091. }
  6092. patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6093. patched++;
  6094. }
  6095. }
  6096. // 5.3 move and mount
  6097. // generate longest stable subsequence only when nodes have moved
  6098. const increasingNewIndexSequence = moved
  6099. ? getSequence(newIndexToOldIndexMap)
  6100. : EMPTY_ARR;
  6101. j = increasingNewIndexSequence.length - 1;
  6102. // looping backwards so that we can use last patched node as anchor
  6103. for (i = toBePatched - 1; i >= 0; i--) {
  6104. const nextIndex = s2 + i;
  6105. const nextChild = c2[nextIndex];
  6106. const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
  6107. if (newIndexToOldIndexMap[i] === 0) {
  6108. // mount new
  6109. patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6110. }
  6111. else if (moved) {
  6112. // move if:
  6113. // There is no stable subsequence (e.g. a reverse)
  6114. // OR current node is not among the stable sequence
  6115. if (j < 0 || i !== increasingNewIndexSequence[j]) {
  6116. move(nextChild, container, anchor, 2 /* REORDER */);
  6117. }
  6118. else {
  6119. j--;
  6120. }
  6121. }
  6122. }
  6123. }
  6124. };
  6125. const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
  6126. const { el, type, transition, children, shapeFlag } = vnode;
  6127. if (shapeFlag & 6 /* COMPONENT */) {
  6128. move(vnode.component.subTree, container, anchor, moveType);
  6129. return;
  6130. }
  6131. if (shapeFlag & 128 /* SUSPENSE */) {
  6132. vnode.suspense.move(container, anchor, moveType);
  6133. return;
  6134. }
  6135. if (shapeFlag & 64 /* TELEPORT */) {
  6136. type.move(vnode, container, anchor, internals);
  6137. return;
  6138. }
  6139. if (type === Fragment) {
  6140. hostInsert(el, container, anchor);
  6141. for (let i = 0; i < children.length; i++) {
  6142. move(children[i], container, anchor, moveType);
  6143. }
  6144. hostInsert(vnode.anchor, container, anchor);
  6145. return;
  6146. }
  6147. if (type === Static) {
  6148. moveStaticNode(vnode, container, anchor);
  6149. return;
  6150. }
  6151. // single nodes
  6152. const needTransition = moveType !== 2 /* REORDER */ &&
  6153. shapeFlag & 1 /* ELEMENT */ &&
  6154. transition;
  6155. if (needTransition) {
  6156. if (moveType === 0 /* ENTER */) {
  6157. transition.beforeEnter(el);
  6158. hostInsert(el, container, anchor);
  6159. queuePostRenderEffect(() => transition.enter(el), parentSuspense);
  6160. }
  6161. else {
  6162. const { leave, delayLeave, afterLeave } = transition;
  6163. const remove = () => hostInsert(el, container, anchor);
  6164. const performLeave = () => {
  6165. leave(el, () => {
  6166. remove();
  6167. afterLeave && afterLeave();
  6168. });
  6169. };
  6170. if (delayLeave) {
  6171. delayLeave(el, remove, performLeave);
  6172. }
  6173. else {
  6174. performLeave();
  6175. }
  6176. }
  6177. }
  6178. else {
  6179. hostInsert(el, container, anchor);
  6180. }
  6181. };
  6182. const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
  6183. const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
  6184. // unset ref
  6185. if (ref != null) {
  6186. setRef(ref, null, parentSuspense, vnode, true);
  6187. }
  6188. if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  6189. parentComponent.ctx.deactivate(vnode);
  6190. return;
  6191. }
  6192. const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
  6193. const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
  6194. let vnodeHook;
  6195. if (shouldInvokeVnodeHook &&
  6196. (vnodeHook = props && props.onVnodeBeforeUnmount)) {
  6197. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  6198. }
  6199. if (shapeFlag & 6 /* COMPONENT */) {
  6200. unmountComponent(vnode.component, parentSuspense, doRemove);
  6201. }
  6202. else {
  6203. if (shapeFlag & 128 /* SUSPENSE */) {
  6204. vnode.suspense.unmount(parentSuspense, doRemove);
  6205. return;
  6206. }
  6207. if (shouldInvokeDirs) {
  6208. invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
  6209. }
  6210. if (shapeFlag & 64 /* TELEPORT */) {
  6211. vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
  6212. }
  6213. else if (dynamicChildren &&
  6214. // #1153: fast path should not be taken for non-stable (v-for) fragments
  6215. (type !== Fragment ||
  6216. (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
  6217. // fast path for block nodes: only need to unmount dynamic children.
  6218. unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
  6219. }
  6220. else if ((type === Fragment &&
  6221. patchFlag &
  6222. (128 /* KEYED_FRAGMENT */ | 256 /* UNKEYED_FRAGMENT */)) ||
  6223. (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
  6224. unmountChildren(children, parentComponent, parentSuspense);
  6225. }
  6226. if (doRemove) {
  6227. remove(vnode);
  6228. }
  6229. }
  6230. if ((shouldInvokeVnodeHook &&
  6231. (vnodeHook = props && props.onVnodeUnmounted)) ||
  6232. shouldInvokeDirs) {
  6233. queuePostRenderEffect(() => {
  6234. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  6235. shouldInvokeDirs &&
  6236. invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
  6237. }, parentSuspense);
  6238. }
  6239. };
  6240. const remove = vnode => {
  6241. const { type, el, anchor, transition } = vnode;
  6242. if (type === Fragment) {
  6243. removeFragment(el, anchor);
  6244. return;
  6245. }
  6246. if (type === Static) {
  6247. removeStaticNode(vnode);
  6248. return;
  6249. }
  6250. const performRemove = () => {
  6251. hostRemove(el);
  6252. if (transition && !transition.persisted && transition.afterLeave) {
  6253. transition.afterLeave();
  6254. }
  6255. };
  6256. if (vnode.shapeFlag & 1 /* ELEMENT */ &&
  6257. transition &&
  6258. !transition.persisted) {
  6259. const { leave, delayLeave } = transition;
  6260. const performLeave = () => leave(el, performRemove);
  6261. if (delayLeave) {
  6262. delayLeave(vnode.el, performRemove, performLeave);
  6263. }
  6264. else {
  6265. performLeave();
  6266. }
  6267. }
  6268. else {
  6269. performRemove();
  6270. }
  6271. };
  6272. const removeFragment = (cur, end) => {
  6273. // For fragments, directly remove all contained DOM nodes.
  6274. // (fragment child nodes cannot have transition)
  6275. let next;
  6276. while (cur !== end) {
  6277. next = hostNextSibling(cur);
  6278. hostRemove(cur);
  6279. cur = next;
  6280. }
  6281. hostRemove(end);
  6282. };
  6283. const unmountComponent = (instance, parentSuspense, doRemove) => {
  6284. if (instance.type.__hmrId) {
  6285. unregisterHMR(instance);
  6286. }
  6287. const { bum, scope, update, subTree, um } = instance;
  6288. // beforeUnmount hook
  6289. if (bum) {
  6290. invokeArrayFns(bum);
  6291. }
  6292. // stop effects in component scope
  6293. scope.stop();
  6294. // update may be null if a component is unmounted before its async
  6295. // setup has resolved.
  6296. if (update) {
  6297. // so that scheduler will no longer invoke it
  6298. update.active = false;
  6299. unmount(subTree, instance, parentSuspense, doRemove);
  6300. }
  6301. // unmounted hook
  6302. if (um) {
  6303. queuePostRenderEffect(um, parentSuspense);
  6304. }
  6305. queuePostRenderEffect(() => {
  6306. instance.isUnmounted = true;
  6307. }, parentSuspense);
  6308. // A component with async dep inside a pending suspense is unmounted before
  6309. // its async dep resolves. This should remove the dep from the suspense, and
  6310. // cause the suspense to resolve immediately if that was the last dep.
  6311. if (parentSuspense &&
  6312. parentSuspense.pendingBranch &&
  6313. !parentSuspense.isUnmounted &&
  6314. instance.asyncDep &&
  6315. !instance.asyncResolved &&
  6316. instance.suspenseId === parentSuspense.pendingId) {
  6317. parentSuspense.deps--;
  6318. if (parentSuspense.deps === 0) {
  6319. parentSuspense.resolve();
  6320. }
  6321. }
  6322. {
  6323. devtoolsComponentRemoved(instance);
  6324. }
  6325. };
  6326. const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
  6327. for (let i = start; i < children.length; i++) {
  6328. unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
  6329. }
  6330. };
  6331. const getNextHostNode = vnode => {
  6332. if (vnode.shapeFlag & 6 /* COMPONENT */) {
  6333. return getNextHostNode(vnode.component.subTree);
  6334. }
  6335. if (vnode.shapeFlag & 128 /* SUSPENSE */) {
  6336. return vnode.suspense.next();
  6337. }
  6338. return hostNextSibling((vnode.anchor || vnode.el));
  6339. };
  6340. const render = (vnode, container, isSVG) => {
  6341. if (vnode == null) {
  6342. if (container._vnode) {
  6343. unmount(container._vnode, null, null, true);
  6344. }
  6345. }
  6346. else {
  6347. patch(container._vnode || null, vnode, container, null, null, null, isSVG);
  6348. }
  6349. flushPostFlushCbs();
  6350. container._vnode = vnode;
  6351. };
  6352. const internals = {
  6353. p: patch,
  6354. um: unmount,
  6355. m: move,
  6356. r: remove,
  6357. mt: mountComponent,
  6358. mc: mountChildren,
  6359. pc: patchChildren,
  6360. pbc: patchBlockChildren,
  6361. n: getNextHostNode,
  6362. o: options
  6363. };
  6364. let hydrate;
  6365. let hydrateNode;
  6366. if (createHydrationFns) {
  6367. [hydrate, hydrateNode] = createHydrationFns(internals);
  6368. }
  6369. return {
  6370. render,
  6371. hydrate,
  6372. createApp: createAppAPI(render, hydrate)
  6373. };
  6374. }
  6375. function toggleRecurse({ effect, update }, allowed) {
  6376. effect.allowRecurse = update.allowRecurse = allowed;
  6377. }
  6378. /**
  6379. * #1156
  6380. * When a component is HMR-enabled, we need to make sure that all static nodes
  6381. * inside a block also inherit the DOM element from the previous tree so that
  6382. * HMR updates (which are full updates) can retrieve the element for patching.
  6383. *
  6384. * #2080
  6385. * Inside keyed `template` fragment static children, if a fragment is moved,
  6386. * the children will always be moved. Therefore, in order to ensure correct move
  6387. * position, el should be inherited from previous nodes.
  6388. */
  6389. function traverseStaticChildren(n1, n2, shallow = false) {
  6390. const ch1 = n1.children;
  6391. const ch2 = n2.children;
  6392. if (isArray(ch1) && isArray(ch2)) {
  6393. for (let i = 0; i < ch1.length; i++) {
  6394. // this is only called in the optimized path so array children are
  6395. // guaranteed to be vnodes
  6396. const c1 = ch1[i];
  6397. let c2 = ch2[i];
  6398. if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
  6399. if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
  6400. c2 = ch2[i] = cloneIfMounted(ch2[i]);
  6401. c2.el = c1.el;
  6402. }
  6403. if (!shallow)
  6404. traverseStaticChildren(c1, c2);
  6405. }
  6406. // also inherit for comment nodes, but not placeholders (e.g. v-if which
  6407. // would have received .el during block patch)
  6408. if (c2.type === Comment && !c2.el) {
  6409. c2.el = c1.el;
  6410. }
  6411. }
  6412. }
  6413. }
  6414. // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
  6415. function getSequence(arr) {
  6416. const p = arr.slice();
  6417. const result = [0];
  6418. let i, j, u, v, c;
  6419. const len = arr.length;
  6420. for (i = 0; i < len; i++) {
  6421. const arrI = arr[i];
  6422. if (arrI !== 0) {
  6423. j = result[result.length - 1];
  6424. if (arr[j] < arrI) {
  6425. p[i] = j;
  6426. result.push(i);
  6427. continue;
  6428. }
  6429. u = 0;
  6430. v = result.length - 1;
  6431. while (u < v) {
  6432. c = (u + v) >> 1;
  6433. if (arr[result[c]] < arrI) {
  6434. u = c + 1;
  6435. }
  6436. else {
  6437. v = c;
  6438. }
  6439. }
  6440. if (arrI < arr[result[u]]) {
  6441. if (u > 0) {
  6442. p[i] = result[u - 1];
  6443. }
  6444. result[u] = i;
  6445. }
  6446. }
  6447. }
  6448. u = result.length;
  6449. v = result[u - 1];
  6450. while (u-- > 0) {
  6451. result[u] = v;
  6452. v = p[v];
  6453. }
  6454. return result;
  6455. }
  6456. const isTeleport = (type) => type.__isTeleport;
  6457. const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
  6458. const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
  6459. const resolveTarget = (props, select) => {
  6460. const targetSelector = props && props.to;
  6461. if (isString(targetSelector)) {
  6462. if (!select) {
  6463. warn$1(`Current renderer does not support string target for Teleports. ` +
  6464. `(missing querySelector renderer option)`);
  6465. return null;
  6466. }
  6467. else {
  6468. const target = select(targetSelector);
  6469. if (!target) {
  6470. warn$1(`Failed to locate Teleport target with selector "${targetSelector}". ` +
  6471. `Note the target element must exist before the component is mounted - ` +
  6472. `i.e. the target cannot be rendered by the component itself, and ` +
  6473. `ideally should be outside of the entire Vue component tree.`);
  6474. }
  6475. return target;
  6476. }
  6477. }
  6478. else {
  6479. if (!targetSelector && !isTeleportDisabled(props)) {
  6480. warn$1(`Invalid Teleport target: ${targetSelector}`);
  6481. }
  6482. return targetSelector;
  6483. }
  6484. };
  6485. const TeleportImpl = {
  6486. __isTeleport: true,
  6487. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
  6488. const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
  6489. const disabled = isTeleportDisabled(n2.props);
  6490. let { shapeFlag, children, dynamicChildren } = n2;
  6491. // #3302
  6492. // HMR updated, force full diff
  6493. if (isHmrUpdating) {
  6494. optimized = false;
  6495. dynamicChildren = null;
  6496. }
  6497. if (n1 == null) {
  6498. // insert anchors in the main view
  6499. const placeholder = (n2.el = createComment('teleport start')
  6500. );
  6501. const mainAnchor = (n2.anchor = createComment('teleport end')
  6502. );
  6503. insert(placeholder, container, anchor);
  6504. insert(mainAnchor, container, anchor);
  6505. const target = (n2.target = resolveTarget(n2.props, querySelector));
  6506. const targetAnchor = (n2.targetAnchor = createText(''));
  6507. if (target) {
  6508. insert(targetAnchor, target);
  6509. // #2652 we could be teleporting from a non-SVG tree into an SVG tree
  6510. isSVG = isSVG || isTargetSVG(target);
  6511. }
  6512. else if (!disabled) {
  6513. warn$1('Invalid Teleport target on mount:', target, `(${typeof target})`);
  6514. }
  6515. const mount = (container, anchor) => {
  6516. // Teleport *always* has Array children. This is enforced in both the
  6517. // compiler and vnode children normalization.
  6518. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6519. mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
  6520. }
  6521. };
  6522. if (disabled) {
  6523. mount(container, mainAnchor);
  6524. }
  6525. else if (target) {
  6526. mount(target, targetAnchor);
  6527. }
  6528. }
  6529. else {
  6530. // update content
  6531. n2.el = n1.el;
  6532. const mainAnchor = (n2.anchor = n1.anchor);
  6533. const target = (n2.target = n1.target);
  6534. const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
  6535. const wasDisabled = isTeleportDisabled(n1.props);
  6536. const currentContainer = wasDisabled ? container : target;
  6537. const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
  6538. isSVG = isSVG || isTargetSVG(target);
  6539. if (dynamicChildren) {
  6540. // fast path when the teleport happens to be a block root
  6541. patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
  6542. // even in block tree mode we need to make sure all root-level nodes
  6543. // in the teleport inherit previous DOM references so that they can
  6544. // be moved in future patches.
  6545. traverseStaticChildren(n1, n2, true);
  6546. }
  6547. else if (!optimized) {
  6548. patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
  6549. }
  6550. if (disabled) {
  6551. if (!wasDisabled) {
  6552. // enabled -> disabled
  6553. // move into main container
  6554. moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
  6555. }
  6556. }
  6557. else {
  6558. // target changed
  6559. if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
  6560. const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
  6561. if (nextTarget) {
  6562. moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
  6563. }
  6564. else {
  6565. warn$1('Invalid Teleport target on update:', target, `(${typeof target})`);
  6566. }
  6567. }
  6568. else if (wasDisabled) {
  6569. // disabled -> enabled
  6570. // move into teleport target
  6571. moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
  6572. }
  6573. }
  6574. }
  6575. },
  6576. remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
  6577. const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
  6578. if (target) {
  6579. hostRemove(targetAnchor);
  6580. }
  6581. // an unmounted teleport should always remove its children if not disabled
  6582. if (doRemove || !isTeleportDisabled(props)) {
  6583. hostRemove(anchor);
  6584. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6585. for (let i = 0; i < children.length; i++) {
  6586. const child = children[i];
  6587. unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
  6588. }
  6589. }
  6590. }
  6591. },
  6592. move: moveTeleport,
  6593. hydrate: hydrateTeleport
  6594. };
  6595. function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
  6596. // move target anchor if this is a target change.
  6597. if (moveType === 0 /* TARGET_CHANGE */) {
  6598. insert(vnode.targetAnchor, container, parentAnchor);
  6599. }
  6600. const { el, anchor, shapeFlag, children, props } = vnode;
  6601. const isReorder = moveType === 2 /* REORDER */;
  6602. // move main view anchor if this is a re-order.
  6603. if (isReorder) {
  6604. insert(el, container, parentAnchor);
  6605. }
  6606. // if this is a re-order and teleport is enabled (content is in target)
  6607. // do not move children. So the opposite is: only move children if this
  6608. // is not a reorder, or the teleport is disabled
  6609. if (!isReorder || isTeleportDisabled(props)) {
  6610. // Teleport has either Array children or no children.
  6611. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6612. for (let i = 0; i < children.length; i++) {
  6613. move(children[i], container, parentAnchor, 2 /* REORDER */);
  6614. }
  6615. }
  6616. }
  6617. // move main view anchor if this is a re-order.
  6618. if (isReorder) {
  6619. insert(anchor, container, parentAnchor);
  6620. }
  6621. }
  6622. function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
  6623. const target = (vnode.target = resolveTarget(vnode.props, querySelector));
  6624. if (target) {
  6625. // if multiple teleports rendered to the same target element, we need to
  6626. // pick up from where the last teleport finished instead of the first node
  6627. const targetNode = target._lpa || target.firstChild;
  6628. if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6629. if (isTeleportDisabled(vnode.props)) {
  6630. vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
  6631. vnode.targetAnchor = targetNode;
  6632. }
  6633. else {
  6634. vnode.anchor = nextSibling(node);
  6635. vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
  6636. }
  6637. target._lpa =
  6638. vnode.targetAnchor && nextSibling(vnode.targetAnchor);
  6639. }
  6640. }
  6641. return vnode.anchor && nextSibling(vnode.anchor);
  6642. }
  6643. // Force-casted public typing for h and TSX props inference
  6644. const Teleport = TeleportImpl;
  6645. const COMPONENTS = 'components';
  6646. const DIRECTIVES = 'directives';
  6647. /**
  6648. * @private
  6649. */
  6650. function resolveComponent(name, maybeSelfReference) {
  6651. return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
  6652. }
  6653. const NULL_DYNAMIC_COMPONENT = Symbol();
  6654. /**
  6655. * @private
  6656. */
  6657. function resolveDynamicComponent(component) {
  6658. if (isString(component)) {
  6659. return resolveAsset(COMPONENTS, component, false) || component;
  6660. }
  6661. else {
  6662. // invalid types will fallthrough to createVNode and raise warning
  6663. return (component || NULL_DYNAMIC_COMPONENT);
  6664. }
  6665. }
  6666. /**
  6667. * @private
  6668. */
  6669. function resolveDirective(name) {
  6670. return resolveAsset(DIRECTIVES, name);
  6671. }
  6672. // implementation
  6673. function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
  6674. const instance = currentRenderingInstance || currentInstance;
  6675. if (instance) {
  6676. const Component = instance.type;
  6677. // explicit self name has highest priority
  6678. if (type === COMPONENTS) {
  6679. const selfName = getComponentName(Component);
  6680. if (selfName &&
  6681. (selfName === name ||
  6682. selfName === camelize(name) ||
  6683. selfName === capitalize(camelize(name)))) {
  6684. return Component;
  6685. }
  6686. }
  6687. const res =
  6688. // local registration
  6689. // check instance[type] first which is resolved for options API
  6690. resolve(instance[type] || Component[type], name) ||
  6691. // global registration
  6692. resolve(instance.appContext[type], name);
  6693. if (!res && maybeSelfReference) {
  6694. // fallback to implicit self-reference
  6695. return Component;
  6696. }
  6697. if (warnMissing && !res) {
  6698. const extra = type === COMPONENTS
  6699. ? `\nIf this is a native custom element, make sure to exclude it from ` +
  6700. `component resolution via compilerOptions.isCustomElement.`
  6701. : ``;
  6702. warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`);
  6703. }
  6704. return res;
  6705. }
  6706. else {
  6707. warn$1(`resolve${capitalize(type.slice(0, -1))} ` +
  6708. `can only be used in render() or setup().`);
  6709. }
  6710. }
  6711. function resolve(registry, name) {
  6712. return (registry &&
  6713. (registry[name] ||
  6714. registry[camelize(name)] ||
  6715. registry[capitalize(camelize(name))]));
  6716. }
  6717. const Fragment = Symbol('Fragment' );
  6718. const Text = Symbol('Text' );
  6719. const Comment = Symbol('Comment' );
  6720. const Static = Symbol('Static' );
  6721. // Since v-if and v-for are the two possible ways node structure can dynamically
  6722. // change, once we consider v-if branches and each v-for fragment a block, we
  6723. // can divide a template into nested blocks, and within each block the node
  6724. // structure would be stable. This allows us to skip most children diffing
  6725. // and only worry about the dynamic nodes (indicated by patch flags).
  6726. const blockStack = [];
  6727. let currentBlock = null;
  6728. /**
  6729. * Open a block.
  6730. * This must be called before `createBlock`. It cannot be part of `createBlock`
  6731. * because the children of the block are evaluated before `createBlock` itself
  6732. * is called. The generated code typically looks like this:
  6733. *
  6734. * ```js
  6735. * function render() {
  6736. * return (openBlock(),createBlock('div', null, [...]))
  6737. * }
  6738. * ```
  6739. * disableTracking is true when creating a v-for fragment block, since a v-for
  6740. * fragment always diffs its children.
  6741. *
  6742. * @private
  6743. */
  6744. function openBlock(disableTracking = false) {
  6745. blockStack.push((currentBlock = disableTracking ? null : []));
  6746. }
  6747. function closeBlock() {
  6748. blockStack.pop();
  6749. currentBlock = blockStack[blockStack.length - 1] || null;
  6750. }
  6751. // Whether we should be tracking dynamic child nodes inside a block.
  6752. // Only tracks when this value is > 0
  6753. // We are not using a simple boolean because this value may need to be
  6754. // incremented/decremented by nested usage of v-once (see below)
  6755. let isBlockTreeEnabled = 1;
  6756. /**
  6757. * Block tracking sometimes needs to be disabled, for example during the
  6758. * creation of a tree that needs to be cached by v-once. The compiler generates
  6759. * code like this:
  6760. *
  6761. * ``` js
  6762. * _cache[1] || (
  6763. * setBlockTracking(-1),
  6764. * _cache[1] = createVNode(...),
  6765. * setBlockTracking(1),
  6766. * _cache[1]
  6767. * )
  6768. * ```
  6769. *
  6770. * @private
  6771. */
  6772. function setBlockTracking(value) {
  6773. isBlockTreeEnabled += value;
  6774. }
  6775. function setupBlock(vnode) {
  6776. // save current block children on the block vnode
  6777. vnode.dynamicChildren =
  6778. isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
  6779. // close block
  6780. closeBlock();
  6781. // a block is always going to be patched, so track it as a child of its
  6782. // parent block
  6783. if (isBlockTreeEnabled > 0 && currentBlock) {
  6784. currentBlock.push(vnode);
  6785. }
  6786. return vnode;
  6787. }
  6788. /**
  6789. * @private
  6790. */
  6791. function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
  6792. return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true /* isBlock */));
  6793. }
  6794. /**
  6795. * Create a block root vnode. Takes the same exact arguments as `createVNode`.
  6796. * A block root keeps track of dynamic nodes within the block in the
  6797. * `dynamicChildren` array.
  6798. *
  6799. * @private
  6800. */
  6801. function createBlock(type, props, children, patchFlag, dynamicProps) {
  6802. return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */));
  6803. }
  6804. function isVNode(value) {
  6805. return value ? value.__v_isVNode === true : false;
  6806. }
  6807. function isSameVNodeType(n1, n2) {
  6808. if (n2.shapeFlag & 6 /* COMPONENT */ &&
  6809. hmrDirtyComponents.has(n2.type)) {
  6810. // HMR only: if the component has been hot-updated, force a reload.
  6811. return false;
  6812. }
  6813. return n1.type === n2.type && n1.key === n2.key;
  6814. }
  6815. let vnodeArgsTransformer;
  6816. /**
  6817. * Internal API for registering an arguments transform for createVNode
  6818. * used for creating stubs in the test-utils
  6819. * It is *internal* but needs to be exposed for test-utils to pick up proper
  6820. * typings
  6821. */
  6822. function transformVNodeArgs(transformer) {
  6823. vnodeArgsTransformer = transformer;
  6824. }
  6825. const createVNodeWithArgsTransform = (...args) => {
  6826. return _createVNode(...(vnodeArgsTransformer
  6827. ? vnodeArgsTransformer(args, currentRenderingInstance)
  6828. : args));
  6829. };
  6830. const InternalObjectKey = `__vInternal`;
  6831. const normalizeKey = ({ key }) => key != null ? key : null;
  6832. const normalizeRef = ({ ref, ref_key, ref_for }) => {
  6833. return (ref != null
  6834. ? isString(ref) || isRef(ref) || isFunction(ref)
  6835. ? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
  6836. : ref
  6837. : null);
  6838. };
  6839. function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1 /* ELEMENT */, isBlockNode = false, needFullChildrenNormalization = false) {
  6840. const vnode = {
  6841. __v_isVNode: true,
  6842. __v_skip: true,
  6843. type,
  6844. props,
  6845. key: props && normalizeKey(props),
  6846. ref: props && normalizeRef(props),
  6847. scopeId: currentScopeId,
  6848. slotScopeIds: null,
  6849. children,
  6850. component: null,
  6851. suspense: null,
  6852. ssContent: null,
  6853. ssFallback: null,
  6854. dirs: null,
  6855. transition: null,
  6856. el: null,
  6857. anchor: null,
  6858. target: null,
  6859. targetAnchor: null,
  6860. staticCount: 0,
  6861. shapeFlag,
  6862. patchFlag,
  6863. dynamicProps,
  6864. dynamicChildren: null,
  6865. appContext: null
  6866. };
  6867. if (needFullChildrenNormalization) {
  6868. normalizeChildren(vnode, children);
  6869. // normalize suspense children
  6870. if (shapeFlag & 128 /* SUSPENSE */) {
  6871. type.normalize(vnode);
  6872. }
  6873. }
  6874. else if (children) {
  6875. // compiled element vnode - if children is passed, only possible types are
  6876. // string or Array.
  6877. vnode.shapeFlag |= isString(children)
  6878. ? 8 /* TEXT_CHILDREN */
  6879. : 16 /* ARRAY_CHILDREN */;
  6880. }
  6881. // validate key
  6882. if (vnode.key !== vnode.key) {
  6883. warn$1(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
  6884. }
  6885. // track vnode for block tree
  6886. if (isBlockTreeEnabled > 0 &&
  6887. // avoid a block node from tracking itself
  6888. !isBlockNode &&
  6889. // has current parent block
  6890. currentBlock &&
  6891. // presence of a patch flag indicates this node needs patching on updates.
  6892. // component nodes also should always be patched, because even if the
  6893. // component doesn't need to update, it needs to persist the instance on to
  6894. // the next vnode so that it can be properly unmounted later.
  6895. (vnode.patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
  6896. // the EVENTS flag is only for hydration and if it is the only flag, the
  6897. // vnode should not be considered dynamic due to handler caching.
  6898. vnode.patchFlag !== 32 /* HYDRATE_EVENTS */) {
  6899. currentBlock.push(vnode);
  6900. }
  6901. return vnode;
  6902. }
  6903. const createVNode = (createVNodeWithArgsTransform );
  6904. function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
  6905. if (!type || type === NULL_DYNAMIC_COMPONENT) {
  6906. if (!type) {
  6907. warn$1(`Invalid vnode type when creating vnode: ${type}.`);
  6908. }
  6909. type = Comment;
  6910. }
  6911. if (isVNode(type)) {
  6912. // createVNode receiving an existing vnode. This happens in cases like
  6913. // <component :is="vnode"/>
  6914. // #2078 make sure to merge refs during the clone instead of overwriting it
  6915. const cloned = cloneVNode(type, props, true /* mergeRef: true */);
  6916. if (children) {
  6917. normalizeChildren(cloned, children);
  6918. }
  6919. return cloned;
  6920. }
  6921. // class component normalization.
  6922. if (isClassComponent(type)) {
  6923. type = type.__vccOpts;
  6924. }
  6925. // class & style normalization.
  6926. if (props) {
  6927. // for reactive or proxy objects, we need to clone it to enable mutation.
  6928. props = guardReactiveProps(props);
  6929. let { class: klass, style } = props;
  6930. if (klass && !isString(klass)) {
  6931. props.class = normalizeClass(klass);
  6932. }
  6933. if (isObject(style)) {
  6934. // reactive state objects need to be cloned since they are likely to be
  6935. // mutated
  6936. if (isProxy(style) && !isArray(style)) {
  6937. style = extend({}, style);
  6938. }
  6939. props.style = normalizeStyle(style);
  6940. }
  6941. }
  6942. // encode the vnode type information into a bitmap
  6943. const shapeFlag = isString(type)
  6944. ? 1 /* ELEMENT */
  6945. : isSuspense(type)
  6946. ? 128 /* SUSPENSE */
  6947. : isTeleport(type)
  6948. ? 64 /* TELEPORT */
  6949. : isObject(type)
  6950. ? 4 /* STATEFUL_COMPONENT */
  6951. : isFunction(type)
  6952. ? 2 /* FUNCTIONAL_COMPONENT */
  6953. : 0;
  6954. if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
  6955. type = toRaw(type);
  6956. warn$1(`Vue received a Component which was made a reactive object. This can ` +
  6957. `lead to unnecessary performance overhead, and should be avoided by ` +
  6958. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  6959. `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
  6960. }
  6961. return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
  6962. }
  6963. function guardReactiveProps(props) {
  6964. if (!props)
  6965. return null;
  6966. return isProxy(props) || InternalObjectKey in props
  6967. ? extend({}, props)
  6968. : props;
  6969. }
  6970. function cloneVNode(vnode, extraProps, mergeRef = false) {
  6971. // This is intentionally NOT using spread or extend to avoid the runtime
  6972. // key enumeration cost.
  6973. const { props, ref, patchFlag, children } = vnode;
  6974. const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
  6975. const cloned = {
  6976. __v_isVNode: true,
  6977. __v_skip: true,
  6978. type: vnode.type,
  6979. props: mergedProps,
  6980. key: mergedProps && normalizeKey(mergedProps),
  6981. ref: extraProps && extraProps.ref
  6982. ? // #2078 in the case of <component :is="vnode" ref="extra"/>
  6983. // if the vnode itself already has a ref, cloneVNode will need to merge
  6984. // the refs so the single vnode can be set on multiple refs
  6985. mergeRef && ref
  6986. ? isArray(ref)
  6987. ? ref.concat(normalizeRef(extraProps))
  6988. : [ref, normalizeRef(extraProps)]
  6989. : normalizeRef(extraProps)
  6990. : ref,
  6991. scopeId: vnode.scopeId,
  6992. slotScopeIds: vnode.slotScopeIds,
  6993. children: patchFlag === -1 /* HOISTED */ && isArray(children)
  6994. ? children.map(deepCloneVNode)
  6995. : children,
  6996. target: vnode.target,
  6997. targetAnchor: vnode.targetAnchor,
  6998. staticCount: vnode.staticCount,
  6999. shapeFlag: vnode.shapeFlag,
  7000. // if the vnode is cloned with extra props, we can no longer assume its
  7001. // existing patch flag to be reliable and need to add the FULL_PROPS flag.
  7002. // note: perserve flag for fragments since they use the flag for children
  7003. // fast paths only.
  7004. patchFlag: extraProps && vnode.type !== Fragment
  7005. ? patchFlag === -1 // hoisted node
  7006. ? 16 /* FULL_PROPS */
  7007. : patchFlag | 16 /* FULL_PROPS */
  7008. : patchFlag,
  7009. dynamicProps: vnode.dynamicProps,
  7010. dynamicChildren: vnode.dynamicChildren,
  7011. appContext: vnode.appContext,
  7012. dirs: vnode.dirs,
  7013. transition: vnode.transition,
  7014. // These should technically only be non-null on mounted VNodes. However,
  7015. // they *should* be copied for kept-alive vnodes. So we just always copy
  7016. // them since them being non-null during a mount doesn't affect the logic as
  7017. // they will simply be overwritten.
  7018. component: vnode.component,
  7019. suspense: vnode.suspense,
  7020. ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
  7021. ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
  7022. el: vnode.el,
  7023. anchor: vnode.anchor
  7024. };
  7025. return cloned;
  7026. }
  7027. /**
  7028. * Dev only, for HMR of hoisted vnodes reused in v-for
  7029. * https://github.com/vitejs/vite/issues/2022
  7030. */
  7031. function deepCloneVNode(vnode) {
  7032. const cloned = cloneVNode(vnode);
  7033. if (isArray(vnode.children)) {
  7034. cloned.children = vnode.children.map(deepCloneVNode);
  7035. }
  7036. return cloned;
  7037. }
  7038. /**
  7039. * @private
  7040. */
  7041. function createTextVNode(text = ' ', flag = 0) {
  7042. return createVNode(Text, null, text, flag);
  7043. }
  7044. /**
  7045. * @private
  7046. */
  7047. function createStaticVNode(content, numberOfNodes) {
  7048. // A static vnode can contain multiple stringified elements, and the number
  7049. // of elements is necessary for hydration.
  7050. const vnode = createVNode(Static, null, content);
  7051. vnode.staticCount = numberOfNodes;
  7052. return vnode;
  7053. }
  7054. /**
  7055. * @private
  7056. */
  7057. function createCommentVNode(text = '',
  7058. // when used as the v-else branch, the comment node must be created as a
  7059. // block to ensure correct updates.
  7060. asBlock = false) {
  7061. return asBlock
  7062. ? (openBlock(), createBlock(Comment, null, text))
  7063. : createVNode(Comment, null, text);
  7064. }
  7065. function normalizeVNode(child) {
  7066. if (child == null || typeof child === 'boolean') {
  7067. // empty placeholder
  7068. return createVNode(Comment);
  7069. }
  7070. else if (isArray(child)) {
  7071. // fragment
  7072. return createVNode(Fragment, null,
  7073. // #3666, avoid reference pollution when reusing vnode
  7074. child.slice());
  7075. }
  7076. else if (typeof child === 'object') {
  7077. // already vnode, this should be the most common since compiled templates
  7078. // always produce all-vnode children arrays
  7079. return cloneIfMounted(child);
  7080. }
  7081. else {
  7082. // strings and numbers
  7083. return createVNode(Text, null, String(child));
  7084. }
  7085. }
  7086. // optimized normalization for template-compiled render fns
  7087. function cloneIfMounted(child) {
  7088. return child.el === null || child.memo ? child : cloneVNode(child);
  7089. }
  7090. function normalizeChildren(vnode, children) {
  7091. let type = 0;
  7092. const { shapeFlag } = vnode;
  7093. if (children == null) {
  7094. children = null;
  7095. }
  7096. else if (isArray(children)) {
  7097. type = 16 /* ARRAY_CHILDREN */;
  7098. }
  7099. else if (typeof children === 'object') {
  7100. if (shapeFlag & (1 /* ELEMENT */ | 64 /* TELEPORT */)) {
  7101. // Normalize slot to plain children for plain element and Teleport
  7102. const slot = children.default;
  7103. if (slot) {
  7104. // _c marker is added by withCtx() indicating this is a compiled slot
  7105. slot._c && (slot._d = false);
  7106. normalizeChildren(vnode, slot());
  7107. slot._c && (slot._d = true);
  7108. }
  7109. return;
  7110. }
  7111. else {
  7112. type = 32 /* SLOTS_CHILDREN */;
  7113. const slotFlag = children._;
  7114. if (!slotFlag && !(InternalObjectKey in children)) {
  7115. children._ctx = currentRenderingInstance;
  7116. }
  7117. else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
  7118. // a child component receives forwarded slots from the parent.
  7119. // its slot type is determined by its parent's slot type.
  7120. if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
  7121. children._ = 1 /* STABLE */;
  7122. }
  7123. else {
  7124. children._ = 2 /* DYNAMIC */;
  7125. vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  7126. }
  7127. }
  7128. }
  7129. }
  7130. else if (isFunction(children)) {
  7131. children = { default: children, _ctx: currentRenderingInstance };
  7132. type = 32 /* SLOTS_CHILDREN */;
  7133. }
  7134. else {
  7135. children = String(children);
  7136. // force teleport children to array so it can be moved around
  7137. if (shapeFlag & 64 /* TELEPORT */) {
  7138. type = 16 /* ARRAY_CHILDREN */;
  7139. children = [createTextVNode(children)];
  7140. }
  7141. else {
  7142. type = 8 /* TEXT_CHILDREN */;
  7143. }
  7144. }
  7145. vnode.children = children;
  7146. vnode.shapeFlag |= type;
  7147. }
  7148. function mergeProps(...args) {
  7149. const ret = {};
  7150. for (let i = 0; i < args.length; i++) {
  7151. const toMerge = args[i];
  7152. for (const key in toMerge) {
  7153. if (key === 'class') {
  7154. if (ret.class !== toMerge.class) {
  7155. ret.class = normalizeClass([ret.class, toMerge.class]);
  7156. }
  7157. }
  7158. else if (key === 'style') {
  7159. ret.style = normalizeStyle([ret.style, toMerge.style]);
  7160. }
  7161. else if (isOn(key)) {
  7162. const existing = ret[key];
  7163. const incoming = toMerge[key];
  7164. if (existing !== incoming &&
  7165. !(isArray(existing) && existing.includes(incoming))) {
  7166. ret[key] = existing
  7167. ? [].concat(existing, incoming)
  7168. : incoming;
  7169. }
  7170. }
  7171. else if (key !== '') {
  7172. ret[key] = toMerge[key];
  7173. }
  7174. }
  7175. }
  7176. return ret;
  7177. }
  7178. function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
  7179. callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
  7180. vnode,
  7181. prevVNode
  7182. ]);
  7183. }
  7184. /**
  7185. * Actual implementation
  7186. */
  7187. function renderList(source, renderItem, cache, index) {
  7188. let ret;
  7189. const cached = (cache && cache[index]);
  7190. if (isArray(source) || isString(source)) {
  7191. ret = new Array(source.length);
  7192. for (let i = 0, l = source.length; i < l; i++) {
  7193. ret[i] = renderItem(source[i], i, undefined, cached && cached[i]);
  7194. }
  7195. }
  7196. else if (typeof source === 'number') {
  7197. if (!Number.isInteger(source)) {
  7198. warn$1(`The v-for range expect an integer value but got ${source}.`);
  7199. return [];
  7200. }
  7201. ret = new Array(source);
  7202. for (let i = 0; i < source; i++) {
  7203. ret[i] = renderItem(i + 1, i, undefined, cached && cached[i]);
  7204. }
  7205. }
  7206. else if (isObject(source)) {
  7207. if (source[Symbol.iterator]) {
  7208. ret = Array.from(source, (item, i) => renderItem(item, i, undefined, cached && cached[i]));
  7209. }
  7210. else {
  7211. const keys = Object.keys(source);
  7212. ret = new Array(keys.length);
  7213. for (let i = 0, l = keys.length; i < l; i++) {
  7214. const key = keys[i];
  7215. ret[i] = renderItem(source[key], key, i, cached && cached[i]);
  7216. }
  7217. }
  7218. }
  7219. else {
  7220. ret = [];
  7221. }
  7222. if (cache) {
  7223. cache[index] = ret;
  7224. }
  7225. return ret;
  7226. }
  7227. /**
  7228. * Compiler runtime helper for creating dynamic slots object
  7229. * @private
  7230. */
  7231. function createSlots(slots, dynamicSlots) {
  7232. for (let i = 0; i < dynamicSlots.length; i++) {
  7233. const slot = dynamicSlots[i];
  7234. // array of dynamic slot generated by <template v-for="..." #[...]>
  7235. if (isArray(slot)) {
  7236. for (let j = 0; j < slot.length; j++) {
  7237. slots[slot[j].name] = slot[j].fn;
  7238. }
  7239. }
  7240. else if (slot) {
  7241. // conditional single slot generated by <template v-if="..." #foo>
  7242. slots[slot.name] = slot.fn;
  7243. }
  7244. }
  7245. return slots;
  7246. }
  7247. /**
  7248. * Compiler runtime helper for rendering `<slot/>`
  7249. * @private
  7250. */
  7251. function renderSlot(slots, name, props = {},
  7252. // this is not a user-facing function, so the fallback is always generated by
  7253. // the compiler and guaranteed to be a function returning an array
  7254. fallback, noSlotted) {
  7255. if (currentRenderingInstance.isCE) {
  7256. return createVNode('slot', name === 'default' ? null : { name }, fallback && fallback());
  7257. }
  7258. let slot = slots[name];
  7259. if (slot && slot.length > 1) {
  7260. warn$1(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
  7261. `function. You need to mark this component with $dynamic-slots in the ` +
  7262. `parent template.`);
  7263. slot = () => [];
  7264. }
  7265. // a compiled slot disables block tracking by default to avoid manual
  7266. // invocation interfering with template-based block tracking, but in
  7267. // `renderSlot` we can be sure that it's template-based so we can force
  7268. // enable it.
  7269. if (slot && slot._c) {
  7270. slot._d = false;
  7271. }
  7272. openBlock();
  7273. const validSlotContent = slot && ensureValidVNode(slot(props));
  7274. const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
  7275. ? 64 /* STABLE_FRAGMENT */
  7276. : -2 /* BAIL */);
  7277. if (!noSlotted && rendered.scopeId) {
  7278. rendered.slotScopeIds = [rendered.scopeId + '-s'];
  7279. }
  7280. if (slot && slot._c) {
  7281. slot._d = true;
  7282. }
  7283. return rendered;
  7284. }
  7285. function ensureValidVNode(vnodes) {
  7286. return vnodes.some(child => {
  7287. if (!isVNode(child))
  7288. return true;
  7289. if (child.type === Comment)
  7290. return false;
  7291. if (child.type === Fragment &&
  7292. !ensureValidVNode(child.children))
  7293. return false;
  7294. return true;
  7295. })
  7296. ? vnodes
  7297. : null;
  7298. }
  7299. /**
  7300. * For prefixing keys in v-on="obj" with "on"
  7301. * @private
  7302. */
  7303. function toHandlers(obj) {
  7304. const ret = {};
  7305. if (!isObject(obj)) {
  7306. warn$1(`v-on with no argument expects an object value.`);
  7307. return ret;
  7308. }
  7309. for (const key in obj) {
  7310. ret[toHandlerKey(key)] = obj[key];
  7311. }
  7312. return ret;
  7313. }
  7314. /**
  7315. * #2437 In Vue 3, functional components do not have a public instance proxy but
  7316. * they exist in the internal parent chain. For code that relies on traversing
  7317. * public $parent chains, skip functional ones and go to the parent instead.
  7318. */
  7319. const getPublicInstance = (i) => {
  7320. if (!i)
  7321. return null;
  7322. if (isStatefulComponent(i))
  7323. return getExposeProxy(i) || i.proxy;
  7324. return getPublicInstance(i.parent);
  7325. };
  7326. const publicPropertiesMap = extend(Object.create(null), {
  7327. $: i => i,
  7328. $el: i => i.vnode.el,
  7329. $data: i => i.data,
  7330. $props: i => (shallowReadonly(i.props) ),
  7331. $attrs: i => (shallowReadonly(i.attrs) ),
  7332. $slots: i => (shallowReadonly(i.slots) ),
  7333. $refs: i => (shallowReadonly(i.refs) ),
  7334. $parent: i => getPublicInstance(i.parent),
  7335. $root: i => getPublicInstance(i.root),
  7336. $emit: i => i.emit,
  7337. $options: i => (resolveMergedOptions(i) ),
  7338. $forceUpdate: i => () => queueJob(i.update),
  7339. $nextTick: i => nextTick.bind(i.proxy),
  7340. $watch: i => (instanceWatch.bind(i) )
  7341. });
  7342. const PublicInstanceProxyHandlers = {
  7343. get({ _: instance }, key) {
  7344. const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
  7345. // for internal formatters to know that this is a Vue instance
  7346. if (key === '__isVue') {
  7347. return true;
  7348. }
  7349. // prioritize <script setup> bindings during dev.
  7350. // this allows even properties that start with _ or $ to be used - so that
  7351. // it aligns with the production behavior where the render fn is inlined and
  7352. // indeed has access to all declared variables.
  7353. if (setupState !== EMPTY_OBJ &&
  7354. setupState.__isScriptSetup &&
  7355. hasOwn(setupState, key)) {
  7356. return setupState[key];
  7357. }
  7358. // data / props / ctx
  7359. // This getter gets called for every property access on the render context
  7360. // during render and is a major hotspot. The most expensive part of this
  7361. // is the multiple hasOwn() calls. It's much faster to do a simple property
  7362. // access on a plain object, so we use an accessCache object (with null
  7363. // prototype) to memoize what access type a key corresponds to.
  7364. let normalizedProps;
  7365. if (key[0] !== '$') {
  7366. const n = accessCache[key];
  7367. if (n !== undefined) {
  7368. switch (n) {
  7369. case 1 /* SETUP */:
  7370. return setupState[key];
  7371. case 2 /* DATA */:
  7372. return data[key];
  7373. case 4 /* CONTEXT */:
  7374. return ctx[key];
  7375. case 3 /* PROPS */:
  7376. return props[key];
  7377. // default: just fallthrough
  7378. }
  7379. }
  7380. else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  7381. accessCache[key] = 1 /* SETUP */;
  7382. return setupState[key];
  7383. }
  7384. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  7385. accessCache[key] = 2 /* DATA */;
  7386. return data[key];
  7387. }
  7388. else if (
  7389. // only cache other properties when instance has declared (thus stable)
  7390. // props
  7391. (normalizedProps = instance.propsOptions[0]) &&
  7392. hasOwn(normalizedProps, key)) {
  7393. accessCache[key] = 3 /* PROPS */;
  7394. return props[key];
  7395. }
  7396. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  7397. accessCache[key] = 4 /* CONTEXT */;
  7398. return ctx[key];
  7399. }
  7400. else if (shouldCacheAccess) {
  7401. accessCache[key] = 0 /* OTHER */;
  7402. }
  7403. }
  7404. const publicGetter = publicPropertiesMap[key];
  7405. let cssModule, globalProperties;
  7406. // public $xxx properties
  7407. if (publicGetter) {
  7408. if (key === '$attrs') {
  7409. track(instance, "get" /* GET */, key);
  7410. markAttrsAccessed();
  7411. }
  7412. return publicGetter(instance);
  7413. }
  7414. else if (
  7415. // css module (injected by vue-loader)
  7416. (cssModule = type.__cssModules) &&
  7417. (cssModule = cssModule[key])) {
  7418. return cssModule;
  7419. }
  7420. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  7421. // user may set custom properties to `this` that start with `$`
  7422. accessCache[key] = 4 /* CONTEXT */;
  7423. return ctx[key];
  7424. }
  7425. else if (
  7426. // global properties
  7427. ((globalProperties = appContext.config.globalProperties),
  7428. hasOwn(globalProperties, key))) {
  7429. {
  7430. return globalProperties[key];
  7431. }
  7432. }
  7433. else if (currentRenderingInstance &&
  7434. (!isString(key) ||
  7435. // #1091 avoid internal isRef/isVNode checks on component instance leading
  7436. // to infinite warning loop
  7437. key.indexOf('__v') !== 0)) {
  7438. if (data !== EMPTY_OBJ &&
  7439. (key[0] === '$' || key[0] === '_') &&
  7440. hasOwn(data, key)) {
  7441. warn$1(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
  7442. `character ("$" or "_") and is not proxied on the render context.`);
  7443. }
  7444. else if (instance === currentRenderingInstance) {
  7445. warn$1(`Property ${JSON.stringify(key)} was accessed during render ` +
  7446. `but is not defined on instance.`);
  7447. }
  7448. }
  7449. },
  7450. set({ _: instance }, key, value) {
  7451. const { data, setupState, ctx } = instance;
  7452. if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  7453. setupState[key] = value;
  7454. }
  7455. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  7456. data[key] = value;
  7457. }
  7458. else if (hasOwn(instance.props, key)) {
  7459. warn$1(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
  7460. return false;
  7461. }
  7462. if (key[0] === '$' && key.slice(1) in instance) {
  7463. warn$1(`Attempting to mutate public property "${key}". ` +
  7464. `Properties starting with $ are reserved and readonly.`, instance);
  7465. return false;
  7466. }
  7467. else {
  7468. if (key in instance.appContext.config.globalProperties) {
  7469. Object.defineProperty(ctx, key, {
  7470. enumerable: true,
  7471. configurable: true,
  7472. value
  7473. });
  7474. }
  7475. else {
  7476. ctx[key] = value;
  7477. }
  7478. }
  7479. return true;
  7480. },
  7481. has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
  7482. let normalizedProps;
  7483. return (!!accessCache[key] ||
  7484. (data !== EMPTY_OBJ && hasOwn(data, key)) ||
  7485. (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
  7486. ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
  7487. hasOwn(ctx, key) ||
  7488. hasOwn(publicPropertiesMap, key) ||
  7489. hasOwn(appContext.config.globalProperties, key));
  7490. }
  7491. };
  7492. {
  7493. PublicInstanceProxyHandlers.ownKeys = (target) => {
  7494. warn$1(`Avoid app logic that relies on enumerating keys on a component instance. ` +
  7495. `The keys will be empty in production mode to avoid performance overhead.`);
  7496. return Reflect.ownKeys(target);
  7497. };
  7498. }
  7499. const RuntimeCompiledPublicInstanceProxyHandlers = /*#__PURE__*/ extend({}, PublicInstanceProxyHandlers, {
  7500. get(target, key) {
  7501. // fast path for unscopables when using `with` block
  7502. if (key === Symbol.unscopables) {
  7503. return;
  7504. }
  7505. return PublicInstanceProxyHandlers.get(target, key, target);
  7506. },
  7507. has(_, key) {
  7508. const has = key[0] !== '_' && !isGloballyWhitelisted(key);
  7509. if (!has && PublicInstanceProxyHandlers.has(_, key)) {
  7510. warn$1(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
  7511. }
  7512. return has;
  7513. }
  7514. });
  7515. // dev only
  7516. // In dev mode, the proxy target exposes the same properties as seen on `this`
  7517. // for easier console inspection. In prod mode it will be an empty object so
  7518. // these properties definitions can be skipped.
  7519. function createDevRenderContext(instance) {
  7520. const target = {};
  7521. // expose internal instance for proxy handlers
  7522. Object.defineProperty(target, `_`, {
  7523. configurable: true,
  7524. enumerable: false,
  7525. get: () => instance
  7526. });
  7527. // expose public properties
  7528. Object.keys(publicPropertiesMap).forEach(key => {
  7529. Object.defineProperty(target, key, {
  7530. configurable: true,
  7531. enumerable: false,
  7532. get: () => publicPropertiesMap[key](instance),
  7533. // intercepted by the proxy so no need for implementation,
  7534. // but needed to prevent set errors
  7535. set: NOOP
  7536. });
  7537. });
  7538. return target;
  7539. }
  7540. // dev only
  7541. function exposePropsOnRenderContext(instance) {
  7542. const { ctx, propsOptions: [propsOptions] } = instance;
  7543. if (propsOptions) {
  7544. Object.keys(propsOptions).forEach(key => {
  7545. Object.defineProperty(ctx, key, {
  7546. enumerable: true,
  7547. configurable: true,
  7548. get: () => instance.props[key],
  7549. set: NOOP
  7550. });
  7551. });
  7552. }
  7553. }
  7554. // dev only
  7555. function exposeSetupStateOnRenderContext(instance) {
  7556. const { ctx, setupState } = instance;
  7557. Object.keys(toRaw(setupState)).forEach(key => {
  7558. if (!setupState.__isScriptSetup) {
  7559. if (key[0] === '$' || key[0] === '_') {
  7560. warn$1(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
  7561. `which are reserved prefixes for Vue internals.`);
  7562. return;
  7563. }
  7564. Object.defineProperty(ctx, key, {
  7565. enumerable: true,
  7566. configurable: true,
  7567. get: () => setupState[key],
  7568. set: NOOP
  7569. });
  7570. }
  7571. });
  7572. }
  7573. const emptyAppContext = createAppContext();
  7574. let uid$1 = 0;
  7575. function createComponentInstance(vnode, parent, suspense) {
  7576. const type = vnode.type;
  7577. // inherit parent app context - or - if root, adopt from root vnode
  7578. const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
  7579. const instance = {
  7580. uid: uid$1++,
  7581. vnode,
  7582. type,
  7583. parent,
  7584. appContext,
  7585. root: null,
  7586. next: null,
  7587. subTree: null,
  7588. effect: null,
  7589. update: null,
  7590. scope: new EffectScope(true /* detached */),
  7591. render: null,
  7592. proxy: null,
  7593. exposed: null,
  7594. exposeProxy: null,
  7595. withProxy: null,
  7596. provides: parent ? parent.provides : Object.create(appContext.provides),
  7597. accessCache: null,
  7598. renderCache: [],
  7599. // local resovled assets
  7600. components: null,
  7601. directives: null,
  7602. // resolved props and emits options
  7603. propsOptions: normalizePropsOptions(type, appContext),
  7604. emitsOptions: normalizeEmitsOptions(type, appContext),
  7605. // emit
  7606. emit: null,
  7607. emitted: null,
  7608. // props default value
  7609. propsDefaults: EMPTY_OBJ,
  7610. // inheritAttrs
  7611. inheritAttrs: type.inheritAttrs,
  7612. // state
  7613. ctx: EMPTY_OBJ,
  7614. data: EMPTY_OBJ,
  7615. props: EMPTY_OBJ,
  7616. attrs: EMPTY_OBJ,
  7617. slots: EMPTY_OBJ,
  7618. refs: EMPTY_OBJ,
  7619. setupState: EMPTY_OBJ,
  7620. setupContext: null,
  7621. // suspense related
  7622. suspense,
  7623. suspenseId: suspense ? suspense.pendingId : 0,
  7624. asyncDep: null,
  7625. asyncResolved: false,
  7626. // lifecycle hooks
  7627. // not using enums here because it results in computed properties
  7628. isMounted: false,
  7629. isUnmounted: false,
  7630. isDeactivated: false,
  7631. bc: null,
  7632. c: null,
  7633. bm: null,
  7634. m: null,
  7635. bu: null,
  7636. u: null,
  7637. um: null,
  7638. bum: null,
  7639. da: null,
  7640. a: null,
  7641. rtg: null,
  7642. rtc: null,
  7643. ec: null,
  7644. sp: null
  7645. };
  7646. {
  7647. instance.ctx = createDevRenderContext(instance);
  7648. }
  7649. instance.root = parent ? parent.root : instance;
  7650. instance.emit = emit$1.bind(null, instance);
  7651. // apply custom element special handling
  7652. if (vnode.ce) {
  7653. vnode.ce(instance);
  7654. }
  7655. return instance;
  7656. }
  7657. let currentInstance = null;
  7658. const getCurrentInstance = () => currentInstance || currentRenderingInstance;
  7659. const setCurrentInstance = (instance) => {
  7660. currentInstance = instance;
  7661. instance.scope.on();
  7662. };
  7663. const unsetCurrentInstance = () => {
  7664. currentInstance && currentInstance.scope.off();
  7665. currentInstance = null;
  7666. };
  7667. const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
  7668. function validateComponentName(name, config) {
  7669. const appIsNativeTag = config.isNativeTag || NO;
  7670. if (isBuiltInTag(name) || appIsNativeTag(name)) {
  7671. warn$1('Do not use built-in or reserved HTML elements as component id: ' + name);
  7672. }
  7673. }
  7674. function isStatefulComponent(instance) {
  7675. return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
  7676. }
  7677. let isInSSRComponentSetup = false;
  7678. function setupComponent(instance, isSSR = false) {
  7679. isInSSRComponentSetup = isSSR;
  7680. const { props, children } = instance.vnode;
  7681. const isStateful = isStatefulComponent(instance);
  7682. initProps(instance, props, isStateful, isSSR);
  7683. initSlots(instance, children);
  7684. const setupResult = isStateful
  7685. ? setupStatefulComponent(instance, isSSR)
  7686. : undefined;
  7687. isInSSRComponentSetup = false;
  7688. return setupResult;
  7689. }
  7690. function setupStatefulComponent(instance, isSSR) {
  7691. const Component = instance.type;
  7692. {
  7693. if (Component.name) {
  7694. validateComponentName(Component.name, instance.appContext.config);
  7695. }
  7696. if (Component.components) {
  7697. const names = Object.keys(Component.components);
  7698. for (let i = 0; i < names.length; i++) {
  7699. validateComponentName(names[i], instance.appContext.config);
  7700. }
  7701. }
  7702. if (Component.directives) {
  7703. const names = Object.keys(Component.directives);
  7704. for (let i = 0; i < names.length; i++) {
  7705. validateDirectiveName(names[i]);
  7706. }
  7707. }
  7708. if (Component.compilerOptions && isRuntimeOnly()) {
  7709. warn$1(`"compilerOptions" is only supported when using a build of Vue that ` +
  7710. `includes the runtime compiler. Since you are using a runtime-only ` +
  7711. `build, the options should be passed via your build tool config instead.`);
  7712. }
  7713. }
  7714. // 0. create render proxy property access cache
  7715. instance.accessCache = Object.create(null);
  7716. // 1. create public instance / render proxy
  7717. // also mark it raw so it's never observed
  7718. instance.proxy = markRaw(new Proxy(instance.ctx, PublicInstanceProxyHandlers));
  7719. {
  7720. exposePropsOnRenderContext(instance);
  7721. }
  7722. // 2. call setup()
  7723. const { setup } = Component;
  7724. if (setup) {
  7725. const setupContext = (instance.setupContext =
  7726. setup.length > 1 ? createSetupContext(instance) : null);
  7727. setCurrentInstance(instance);
  7728. pauseTracking();
  7729. const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
  7730. resetTracking();
  7731. unsetCurrentInstance();
  7732. if (isPromise(setupResult)) {
  7733. setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
  7734. if (isSSR) {
  7735. // return the promise so server-renderer can wait on it
  7736. return setupResult
  7737. .then((resolvedResult) => {
  7738. handleSetupResult(instance, resolvedResult, isSSR);
  7739. })
  7740. .catch(e => {
  7741. handleError(e, instance, 0 /* SETUP_FUNCTION */);
  7742. });
  7743. }
  7744. else {
  7745. // async setup returned Promise.
  7746. // bail here and wait for re-entry.
  7747. instance.asyncDep = setupResult;
  7748. }
  7749. }
  7750. else {
  7751. handleSetupResult(instance, setupResult, isSSR);
  7752. }
  7753. }
  7754. else {
  7755. finishComponentSetup(instance, isSSR);
  7756. }
  7757. }
  7758. function handleSetupResult(instance, setupResult, isSSR) {
  7759. if (isFunction(setupResult)) {
  7760. // setup returned an inline render function
  7761. {
  7762. instance.render = setupResult;
  7763. }
  7764. }
  7765. else if (isObject(setupResult)) {
  7766. if (isVNode(setupResult)) {
  7767. warn$1(`setup() should not return VNodes directly - ` +
  7768. `return a render function instead.`);
  7769. }
  7770. // setup returned bindings.
  7771. // assuming a render function compiled from template is present.
  7772. {
  7773. instance.devtoolsRawSetupState = setupResult;
  7774. }
  7775. instance.setupState = proxyRefs(setupResult);
  7776. {
  7777. exposeSetupStateOnRenderContext(instance);
  7778. }
  7779. }
  7780. else if (setupResult !== undefined) {
  7781. warn$1(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
  7782. }
  7783. finishComponentSetup(instance, isSSR);
  7784. }
  7785. let compile;
  7786. let installWithProxy;
  7787. /**
  7788. * For runtime-dom to register the compiler.
  7789. * Note the exported method uses any to avoid d.ts relying on the compiler types.
  7790. */
  7791. function registerRuntimeCompiler(_compile) {
  7792. compile = _compile;
  7793. installWithProxy = i => {
  7794. if (i.render._rc) {
  7795. i.withProxy = new Proxy(i.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
  7796. }
  7797. };
  7798. }
  7799. // dev only
  7800. const isRuntimeOnly = () => !compile;
  7801. function finishComponentSetup(instance, isSSR, skipOptions) {
  7802. const Component = instance.type;
  7803. // template / render function normalization
  7804. // could be already set when returned from setup()
  7805. if (!instance.render) {
  7806. // only do on-the-fly compile if not in SSR - SSR on-the-fly compliation
  7807. // is done by server-renderer
  7808. if (!isSSR && compile && !Component.render) {
  7809. const template = Component.template;
  7810. if (template) {
  7811. {
  7812. startMeasure(instance, `compile`);
  7813. }
  7814. const { isCustomElement, compilerOptions } = instance.appContext.config;
  7815. const { delimiters, compilerOptions: componentCompilerOptions } = Component;
  7816. const finalCompilerOptions = extend(extend({
  7817. isCustomElement,
  7818. delimiters
  7819. }, compilerOptions), componentCompilerOptions);
  7820. Component.render = compile(template, finalCompilerOptions);
  7821. {
  7822. endMeasure(instance, `compile`);
  7823. }
  7824. }
  7825. }
  7826. instance.render = (Component.render || NOOP);
  7827. // for runtime-compiled render functions using `with` blocks, the render
  7828. // proxy used needs a different `has` handler which is more performant and
  7829. // also only allows a whitelist of globals to fallthrough.
  7830. if (installWithProxy) {
  7831. installWithProxy(instance);
  7832. }
  7833. }
  7834. // support for 2.x options
  7835. {
  7836. setCurrentInstance(instance);
  7837. pauseTracking();
  7838. applyOptions(instance);
  7839. resetTracking();
  7840. unsetCurrentInstance();
  7841. }
  7842. // warn missing template/render
  7843. // the runtime compilation of template in SSR is done by server-render
  7844. if (!Component.render && instance.render === NOOP && !isSSR) {
  7845. /* istanbul ignore if */
  7846. if (!compile && Component.template) {
  7847. warn$1(`Component provided template option but ` +
  7848. `runtime compilation is not supported in this build of Vue.` +
  7849. (` Use "vue.esm-browser.js" instead.`
  7850. ) /* should not happen */);
  7851. }
  7852. else {
  7853. warn$1(`Component is missing template or render function.`);
  7854. }
  7855. }
  7856. }
  7857. function createAttrsProxy(instance) {
  7858. return new Proxy(instance.attrs, {
  7859. get(target, key) {
  7860. markAttrsAccessed();
  7861. track(instance, "get" /* GET */, '$attrs');
  7862. return target[key];
  7863. },
  7864. set() {
  7865. warn$1(`setupContext.attrs is readonly.`);
  7866. return false;
  7867. },
  7868. deleteProperty() {
  7869. warn$1(`setupContext.attrs is readonly.`);
  7870. return false;
  7871. }
  7872. }
  7873. );
  7874. }
  7875. function createSetupContext(instance) {
  7876. const expose = exposed => {
  7877. if (instance.exposed) {
  7878. warn$1(`expose() should be called only once per setup().`);
  7879. }
  7880. instance.exposed = exposed || {};
  7881. };
  7882. let attrs;
  7883. {
  7884. // We use getters in dev in case libs like test-utils overwrite instance
  7885. // properties (overwrites should not be done in prod)
  7886. return Object.freeze({
  7887. get attrs() {
  7888. return attrs || (attrs = createAttrsProxy(instance));
  7889. },
  7890. get slots() {
  7891. return shallowReadonly(instance.slots);
  7892. },
  7893. get emit() {
  7894. return (event, ...args) => instance.emit(event, ...args);
  7895. },
  7896. expose
  7897. });
  7898. }
  7899. }
  7900. function getExposeProxy(instance) {
  7901. if (instance.exposed) {
  7902. return (instance.exposeProxy ||
  7903. (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
  7904. get(target, key) {
  7905. if (key in target) {
  7906. return target[key];
  7907. }
  7908. else if (key in publicPropertiesMap) {
  7909. return publicPropertiesMap[key](instance);
  7910. }
  7911. }
  7912. })));
  7913. }
  7914. }
  7915. const classifyRE = /(?:^|[-_])(\w)/g;
  7916. const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
  7917. function getComponentName(Component) {
  7918. return isFunction(Component)
  7919. ? Component.displayName || Component.name
  7920. : Component.name;
  7921. }
  7922. /* istanbul ignore next */
  7923. function formatComponentName(instance, Component, isRoot = false) {
  7924. let name = getComponentName(Component);
  7925. if (!name && Component.__file) {
  7926. const match = Component.__file.match(/([^/\\]+)\.\w+$/);
  7927. if (match) {
  7928. name = match[1];
  7929. }
  7930. }
  7931. if (!name && instance && instance.parent) {
  7932. // try to infer the name based on reverse resolution
  7933. const inferFromRegistry = (registry) => {
  7934. for (const key in registry) {
  7935. if (registry[key] === Component) {
  7936. return key;
  7937. }
  7938. }
  7939. };
  7940. name =
  7941. inferFromRegistry(instance.components ||
  7942. instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
  7943. }
  7944. return name ? classify(name) : isRoot ? `App` : `Anonymous`;
  7945. }
  7946. function isClassComponent(value) {
  7947. return isFunction(value) && '__vccOpts' in value;
  7948. }
  7949. const stack = [];
  7950. function pushWarningContext(vnode) {
  7951. stack.push(vnode);
  7952. }
  7953. function popWarningContext() {
  7954. stack.pop();
  7955. }
  7956. function warn$1(msg, ...args) {
  7957. // avoid props formatting or warn handler tracking deps that might be mutated
  7958. // during patch, leading to infinite recursion.
  7959. pauseTracking();
  7960. const instance = stack.length ? stack[stack.length - 1].component : null;
  7961. const appWarnHandler = instance && instance.appContext.config.warnHandler;
  7962. const trace = getComponentTrace();
  7963. if (appWarnHandler) {
  7964. callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
  7965. msg + args.join(''),
  7966. instance && instance.proxy,
  7967. trace
  7968. .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
  7969. .join('\n'),
  7970. trace
  7971. ]);
  7972. }
  7973. else {
  7974. const warnArgs = [`[Vue warn]: ${msg}`, ...args];
  7975. /* istanbul ignore if */
  7976. if (trace.length &&
  7977. // avoid spamming console during tests
  7978. !false) {
  7979. warnArgs.push(`\n`, ...formatTrace(trace));
  7980. }
  7981. console.warn(...warnArgs);
  7982. }
  7983. resetTracking();
  7984. }
  7985. function getComponentTrace() {
  7986. let currentVNode = stack[stack.length - 1];
  7987. if (!currentVNode) {
  7988. return [];
  7989. }
  7990. // we can't just use the stack because it will be incomplete during updates
  7991. // that did not start from the root. Re-construct the parent chain using
  7992. // instance parent pointers.
  7993. const normalizedStack = [];
  7994. while (currentVNode) {
  7995. const last = normalizedStack[0];
  7996. if (last && last.vnode === currentVNode) {
  7997. last.recurseCount++;
  7998. }
  7999. else {
  8000. normalizedStack.push({
  8001. vnode: currentVNode,
  8002. recurseCount: 0
  8003. });
  8004. }
  8005. const parentInstance = currentVNode.component && currentVNode.component.parent;
  8006. currentVNode = parentInstance && parentInstance.vnode;
  8007. }
  8008. return normalizedStack;
  8009. }
  8010. /* istanbul ignore next */
  8011. function formatTrace(trace) {
  8012. const logs = [];
  8013. trace.forEach((entry, i) => {
  8014. logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
  8015. });
  8016. return logs;
  8017. }
  8018. function formatTraceEntry({ vnode, recurseCount }) {
  8019. const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
  8020. const isRoot = vnode.component ? vnode.component.parent == null : false;
  8021. const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
  8022. const close = `>` + postfix;
  8023. return vnode.props
  8024. ? [open, ...formatProps(vnode.props), close]
  8025. : [open + close];
  8026. }
  8027. /* istanbul ignore next */
  8028. function formatProps(props) {
  8029. const res = [];
  8030. const keys = Object.keys(props);
  8031. keys.slice(0, 3).forEach(key => {
  8032. res.push(...formatProp(key, props[key]));
  8033. });
  8034. if (keys.length > 3) {
  8035. res.push(` ...`);
  8036. }
  8037. return res;
  8038. }
  8039. /* istanbul ignore next */
  8040. function formatProp(key, value, raw) {
  8041. if (isString(value)) {
  8042. value = JSON.stringify(value);
  8043. return raw ? value : [`${key}=${value}`];
  8044. }
  8045. else if (typeof value === 'number' ||
  8046. typeof value === 'boolean' ||
  8047. value == null) {
  8048. return raw ? value : [`${key}=${value}`];
  8049. }
  8050. else if (isRef(value)) {
  8051. value = formatProp(key, toRaw(value.value), true);
  8052. return raw ? value : [`${key}=Ref<`, value, `>`];
  8053. }
  8054. else if (isFunction(value)) {
  8055. return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
  8056. }
  8057. else {
  8058. value = toRaw(value);
  8059. return raw ? value : [`${key}=`, value];
  8060. }
  8061. }
  8062. const ErrorTypeStrings = {
  8063. ["sp" /* SERVER_PREFETCH */]: 'serverPrefetch hook',
  8064. ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
  8065. ["c" /* CREATED */]: 'created hook',
  8066. ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
  8067. ["m" /* MOUNTED */]: 'mounted hook',
  8068. ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
  8069. ["u" /* UPDATED */]: 'updated',
  8070. ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
  8071. ["um" /* UNMOUNTED */]: 'unmounted hook',
  8072. ["a" /* ACTIVATED */]: 'activated hook',
  8073. ["da" /* DEACTIVATED */]: 'deactivated hook',
  8074. ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
  8075. ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
  8076. ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
  8077. [0 /* SETUP_FUNCTION */]: 'setup function',
  8078. [1 /* RENDER_FUNCTION */]: 'render function',
  8079. [2 /* WATCH_GETTER */]: 'watcher getter',
  8080. [3 /* WATCH_CALLBACK */]: 'watcher callback',
  8081. [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
  8082. [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
  8083. [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
  8084. [7 /* VNODE_HOOK */]: 'vnode hook',
  8085. [8 /* DIRECTIVE_HOOK */]: 'directive hook',
  8086. [9 /* TRANSITION_HOOK */]: 'transition hook',
  8087. [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
  8088. [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
  8089. [12 /* FUNCTION_REF */]: 'ref function',
  8090. [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
  8091. [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
  8092. 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
  8093. };
  8094. function callWithErrorHandling(fn, instance, type, args) {
  8095. let res;
  8096. try {
  8097. res = args ? fn(...args) : fn();
  8098. }
  8099. catch (err) {
  8100. handleError(err, instance, type);
  8101. }
  8102. return res;
  8103. }
  8104. function callWithAsyncErrorHandling(fn, instance, type, args) {
  8105. if (isFunction(fn)) {
  8106. const res = callWithErrorHandling(fn, instance, type, args);
  8107. if (res && isPromise(res)) {
  8108. res.catch(err => {
  8109. handleError(err, instance, type);
  8110. });
  8111. }
  8112. return res;
  8113. }
  8114. const values = [];
  8115. for (let i = 0; i < fn.length; i++) {
  8116. values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
  8117. }
  8118. return values;
  8119. }
  8120. function handleError(err, instance, type, throwInDev = true) {
  8121. const contextVNode = instance ? instance.vnode : null;
  8122. if (instance) {
  8123. let cur = instance.parent;
  8124. // the exposed instance is the render proxy to keep it consistent with 2.x
  8125. const exposedInstance = instance.proxy;
  8126. // in production the hook receives only the error code
  8127. const errorInfo = ErrorTypeStrings[type] ;
  8128. while (cur) {
  8129. const errorCapturedHooks = cur.ec;
  8130. if (errorCapturedHooks) {
  8131. for (let i = 0; i < errorCapturedHooks.length; i++) {
  8132. if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
  8133. return;
  8134. }
  8135. }
  8136. }
  8137. cur = cur.parent;
  8138. }
  8139. // app-level handling
  8140. const appErrorHandler = instance.appContext.config.errorHandler;
  8141. if (appErrorHandler) {
  8142. callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
  8143. return;
  8144. }
  8145. }
  8146. logError(err, type, contextVNode, throwInDev);
  8147. }
  8148. function logError(err, type, contextVNode, throwInDev = true) {
  8149. {
  8150. const info = ErrorTypeStrings[type];
  8151. if (contextVNode) {
  8152. pushWarningContext(contextVNode);
  8153. }
  8154. warn$1(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
  8155. if (contextVNode) {
  8156. popWarningContext();
  8157. }
  8158. // crash in dev by default so it's more noticeable
  8159. if (throwInDev) {
  8160. throw err;
  8161. }
  8162. else {
  8163. console.error(err);
  8164. }
  8165. }
  8166. }
  8167. let isFlushing = false;
  8168. let isFlushPending = false;
  8169. const queue = [];
  8170. let flushIndex = 0;
  8171. const pendingPreFlushCbs = [];
  8172. let activePreFlushCbs = null;
  8173. let preFlushIndex = 0;
  8174. const pendingPostFlushCbs = [];
  8175. let activePostFlushCbs = null;
  8176. let postFlushIndex = 0;
  8177. const resolvedPromise = Promise.resolve();
  8178. let currentFlushPromise = null;
  8179. let currentPreFlushParentJob = null;
  8180. const RECURSION_LIMIT = 100;
  8181. function nextTick(fn) {
  8182. const p = currentFlushPromise || resolvedPromise;
  8183. return fn ? p.then(this ? fn.bind(this) : fn) : p;
  8184. }
  8185. // #2768
  8186. // Use binary-search to find a suitable position in the queue,
  8187. // so that the queue maintains the increasing order of job's id,
  8188. // which can prevent the job from being skipped and also can avoid repeated patching.
  8189. function findInsertionIndex(id) {
  8190. // the start index should be `flushIndex + 1`
  8191. let start = flushIndex + 1;
  8192. let end = queue.length;
  8193. while (start < end) {
  8194. const middle = (start + end) >>> 1;
  8195. const middleJobId = getId(queue[middle]);
  8196. middleJobId < id ? (start = middle + 1) : (end = middle);
  8197. }
  8198. return start;
  8199. }
  8200. function queueJob(job) {
  8201. // the dedupe search uses the startIndex argument of Array.includes()
  8202. // by default the search index includes the current job that is being run
  8203. // so it cannot recursively trigger itself again.
  8204. // if the job is a watch() callback, the search will start with a +1 index to
  8205. // allow it recursively trigger itself - it is the user's responsibility to
  8206. // ensure it doesn't end up in an infinite loop.
  8207. if ((!queue.length ||
  8208. !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
  8209. job !== currentPreFlushParentJob) {
  8210. if (job.id == null) {
  8211. queue.push(job);
  8212. }
  8213. else {
  8214. queue.splice(findInsertionIndex(job.id), 0, job);
  8215. }
  8216. queueFlush();
  8217. }
  8218. }
  8219. function queueFlush() {
  8220. if (!isFlushing && !isFlushPending) {
  8221. isFlushPending = true;
  8222. currentFlushPromise = resolvedPromise.then(flushJobs);
  8223. }
  8224. }
  8225. function invalidateJob(job) {
  8226. const i = queue.indexOf(job);
  8227. if (i > flushIndex) {
  8228. queue.splice(i, 1);
  8229. }
  8230. }
  8231. function queueCb(cb, activeQueue, pendingQueue, index) {
  8232. if (!isArray(cb)) {
  8233. if (!activeQueue ||
  8234. !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
  8235. pendingQueue.push(cb);
  8236. }
  8237. }
  8238. else {
  8239. // if cb is an array, it is a component lifecycle hook which can only be
  8240. // triggered by a job, which is already deduped in the main queue, so
  8241. // we can skip duplicate check here to improve perf
  8242. pendingQueue.push(...cb);
  8243. }
  8244. queueFlush();
  8245. }
  8246. function queuePreFlushCb(cb) {
  8247. queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
  8248. }
  8249. function queuePostFlushCb(cb) {
  8250. queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
  8251. }
  8252. function flushPreFlushCbs(seen, parentJob = null) {
  8253. if (pendingPreFlushCbs.length) {
  8254. currentPreFlushParentJob = parentJob;
  8255. activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
  8256. pendingPreFlushCbs.length = 0;
  8257. {
  8258. seen = seen || new Map();
  8259. }
  8260. for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
  8261. if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
  8262. continue;
  8263. }
  8264. activePreFlushCbs[preFlushIndex]();
  8265. }
  8266. activePreFlushCbs = null;
  8267. preFlushIndex = 0;
  8268. currentPreFlushParentJob = null;
  8269. // recursively flush until it drains
  8270. flushPreFlushCbs(seen, parentJob);
  8271. }
  8272. }
  8273. function flushPostFlushCbs(seen) {
  8274. if (pendingPostFlushCbs.length) {
  8275. const deduped = [...new Set(pendingPostFlushCbs)];
  8276. pendingPostFlushCbs.length = 0;
  8277. // #1947 already has active queue, nested flushPostFlushCbs call
  8278. if (activePostFlushCbs) {
  8279. activePostFlushCbs.push(...deduped);
  8280. return;
  8281. }
  8282. activePostFlushCbs = deduped;
  8283. {
  8284. seen = seen || new Map();
  8285. }
  8286. activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
  8287. for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
  8288. if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
  8289. continue;
  8290. }
  8291. activePostFlushCbs[postFlushIndex]();
  8292. }
  8293. activePostFlushCbs = null;
  8294. postFlushIndex = 0;
  8295. }
  8296. }
  8297. const getId = (job) => job.id == null ? Infinity : job.id;
  8298. function flushJobs(seen) {
  8299. isFlushPending = false;
  8300. isFlushing = true;
  8301. {
  8302. seen = seen || new Map();
  8303. }
  8304. flushPreFlushCbs(seen);
  8305. // Sort queue before flush.
  8306. // This ensures that:
  8307. // 1. Components are updated from parent to child. (because parent is always
  8308. // created before the child so its render effect will have smaller
  8309. // priority number)
  8310. // 2. If a component is unmounted during a parent component's update,
  8311. // its update can be skipped.
  8312. queue.sort((a, b) => getId(a) - getId(b));
  8313. // conditional usage of checkRecursiveUpdate must be determined out of
  8314. // try ... catch block since Rollup by default de-optimizes treeshaking
  8315. // inside try-catch. This can leave all warning code unshaked. Although
  8316. // they would get eventually shaken by a minifier like terser, some minifiers
  8317. // would fail to do that (e.g. https://github.com/evanw/esbuild/issues/1610)
  8318. const check = (job) => checkRecursiveUpdates(seen, job)
  8319. ;
  8320. try {
  8321. for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
  8322. const job = queue[flushIndex];
  8323. if (job && job.active !== false) {
  8324. if (true && check(job)) {
  8325. continue;
  8326. }
  8327. // console.log(`running:`, job.id)
  8328. callWithErrorHandling(job, null, 14 /* SCHEDULER */);
  8329. }
  8330. }
  8331. }
  8332. finally {
  8333. flushIndex = 0;
  8334. queue.length = 0;
  8335. flushPostFlushCbs(seen);
  8336. isFlushing = false;
  8337. currentFlushPromise = null;
  8338. // some postFlushCb queued jobs!
  8339. // keep flushing until it drains.
  8340. if (queue.length ||
  8341. pendingPreFlushCbs.length ||
  8342. pendingPostFlushCbs.length) {
  8343. flushJobs(seen);
  8344. }
  8345. }
  8346. }
  8347. function checkRecursiveUpdates(seen, fn) {
  8348. if (!seen.has(fn)) {
  8349. seen.set(fn, 1);
  8350. }
  8351. else {
  8352. const count = seen.get(fn);
  8353. if (count > RECURSION_LIMIT) {
  8354. const instance = fn.ownerInstance;
  8355. const componentName = instance && getComponentName(instance.type);
  8356. warn$1(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
  8357. `This means you have a reactive effect that is mutating its own ` +
  8358. `dependencies and thus recursively triggering itself. Possible sources ` +
  8359. `include component template, render function, updated hook or ` +
  8360. `watcher source function.`);
  8361. return true;
  8362. }
  8363. else {
  8364. seen.set(fn, count + 1);
  8365. }
  8366. }
  8367. }
  8368. // Simple effect.
  8369. function watchEffect(effect, options) {
  8370. return doWatch(effect, null, options);
  8371. }
  8372. function watchPostEffect(effect, options) {
  8373. return doWatch(effect, null, (Object.assign(options || {}, { flush: 'post' })
  8374. ));
  8375. }
  8376. function watchSyncEffect(effect, options) {
  8377. return doWatch(effect, null, (Object.assign(options || {}, { flush: 'sync' })
  8378. ));
  8379. }
  8380. // initial value for watchers to trigger on undefined initial values
  8381. const INITIAL_WATCHER_VALUE = {};
  8382. // implementation
  8383. function watch(source, cb, options) {
  8384. if (!isFunction(cb)) {
  8385. warn$1(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
  8386. `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
  8387. `supports \`watch(source, cb, options?) signature.`);
  8388. }
  8389. return doWatch(source, cb, options);
  8390. }
  8391. function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) {
  8392. if (!cb) {
  8393. if (immediate !== undefined) {
  8394. warn$1(`watch() "immediate" option is only respected when using the ` +
  8395. `watch(source, callback, options?) signature.`);
  8396. }
  8397. if (deep !== undefined) {
  8398. warn$1(`watch() "deep" option is only respected when using the ` +
  8399. `watch(source, callback, options?) signature.`);
  8400. }
  8401. }
  8402. const warnInvalidSource = (s) => {
  8403. warn$1(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
  8404. `a reactive object, or an array of these types.`);
  8405. };
  8406. const instance = currentInstance;
  8407. let getter;
  8408. let forceTrigger = false;
  8409. let isMultiSource = false;
  8410. if (isRef(source)) {
  8411. getter = () => source.value;
  8412. forceTrigger = !!source._shallow;
  8413. }
  8414. else if (isReactive(source)) {
  8415. getter = () => source;
  8416. deep = true;
  8417. }
  8418. else if (isArray(source)) {
  8419. isMultiSource = true;
  8420. forceTrigger = source.some(isReactive);
  8421. getter = () => source.map(s => {
  8422. if (isRef(s)) {
  8423. return s.value;
  8424. }
  8425. else if (isReactive(s)) {
  8426. return traverse(s);
  8427. }
  8428. else if (isFunction(s)) {
  8429. return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
  8430. }
  8431. else {
  8432. warnInvalidSource(s);
  8433. }
  8434. });
  8435. }
  8436. else if (isFunction(source)) {
  8437. if (cb) {
  8438. // getter with cb
  8439. getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
  8440. }
  8441. else {
  8442. // no cb -> simple effect
  8443. getter = () => {
  8444. if (instance && instance.isUnmounted) {
  8445. return;
  8446. }
  8447. if (cleanup) {
  8448. cleanup();
  8449. }
  8450. return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
  8451. };
  8452. }
  8453. }
  8454. else {
  8455. getter = NOOP;
  8456. warnInvalidSource(source);
  8457. }
  8458. if (cb && deep) {
  8459. const baseGetter = getter;
  8460. getter = () => traverse(baseGetter());
  8461. }
  8462. let cleanup;
  8463. let onInvalidate = (fn) => {
  8464. cleanup = effect.onStop = () => {
  8465. callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
  8466. };
  8467. };
  8468. let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
  8469. const job = () => {
  8470. if (!effect.active) {
  8471. return;
  8472. }
  8473. if (cb) {
  8474. // watch(source, cb)
  8475. const newValue = effect.run();
  8476. if (deep ||
  8477. forceTrigger ||
  8478. (isMultiSource
  8479. ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
  8480. : hasChanged(newValue, oldValue)) ||
  8481. (false )) {
  8482. // cleanup before running cb again
  8483. if (cleanup) {
  8484. cleanup();
  8485. }
  8486. callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
  8487. newValue,
  8488. // pass undefined as the old value when it's changed for the first time
  8489. oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
  8490. onInvalidate
  8491. ]);
  8492. oldValue = newValue;
  8493. }
  8494. }
  8495. else {
  8496. // watchEffect
  8497. effect.run();
  8498. }
  8499. };
  8500. // important: mark the job as a watcher callback so that scheduler knows
  8501. // it is allowed to self-trigger (#1727)
  8502. job.allowRecurse = !!cb;
  8503. let scheduler;
  8504. if (flush === 'sync') {
  8505. scheduler = job; // the scheduler function gets called directly
  8506. }
  8507. else if (flush === 'post') {
  8508. scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
  8509. }
  8510. else {
  8511. // default: 'pre'
  8512. scheduler = () => {
  8513. if (!instance || instance.isMounted) {
  8514. queuePreFlushCb(job);
  8515. }
  8516. else {
  8517. // with 'pre' option, the first call must happen before
  8518. // the component is mounted so it is called synchronously.
  8519. job();
  8520. }
  8521. };
  8522. }
  8523. const effect = new ReactiveEffect(getter, scheduler);
  8524. {
  8525. effect.onTrack = onTrack;
  8526. effect.onTrigger = onTrigger;
  8527. }
  8528. // initial run
  8529. if (cb) {
  8530. if (immediate) {
  8531. job();
  8532. }
  8533. else {
  8534. oldValue = effect.run();
  8535. }
  8536. }
  8537. else if (flush === 'post') {
  8538. queuePostRenderEffect(effect.run.bind(effect), instance && instance.suspense);
  8539. }
  8540. else {
  8541. effect.run();
  8542. }
  8543. return () => {
  8544. effect.stop();
  8545. if (instance && instance.scope) {
  8546. remove(instance.scope.effects, effect);
  8547. }
  8548. };
  8549. }
  8550. // this.$watch
  8551. function instanceWatch(source, value, options) {
  8552. const publicThis = this.proxy;
  8553. const getter = isString(source)
  8554. ? source.includes('.')
  8555. ? createPathGetter(publicThis, source)
  8556. : () => publicThis[source]
  8557. : source.bind(publicThis, publicThis);
  8558. let cb;
  8559. if (isFunction(value)) {
  8560. cb = value;
  8561. }
  8562. else {
  8563. cb = value.handler;
  8564. options = value;
  8565. }
  8566. const cur = currentInstance;
  8567. setCurrentInstance(this);
  8568. const res = doWatch(getter, cb.bind(publicThis), options);
  8569. if (cur) {
  8570. setCurrentInstance(cur);
  8571. }
  8572. else {
  8573. unsetCurrentInstance();
  8574. }
  8575. return res;
  8576. }
  8577. function createPathGetter(ctx, path) {
  8578. const segments = path.split('.');
  8579. return () => {
  8580. let cur = ctx;
  8581. for (let i = 0; i < segments.length && cur; i++) {
  8582. cur = cur[segments[i]];
  8583. }
  8584. return cur;
  8585. };
  8586. }
  8587. function traverse(value, seen) {
  8588. if (!isObject(value) || value["__v_skip" /* SKIP */]) {
  8589. return value;
  8590. }
  8591. seen = seen || new Set();
  8592. if (seen.has(value)) {
  8593. return value;
  8594. }
  8595. seen.add(value);
  8596. if (isRef(value)) {
  8597. traverse(value.value, seen);
  8598. }
  8599. else if (isArray(value)) {
  8600. for (let i = 0; i < value.length; i++) {
  8601. traverse(value[i], seen);
  8602. }
  8603. }
  8604. else if (isSet(value) || isMap(value)) {
  8605. value.forEach((v) => {
  8606. traverse(v, seen);
  8607. });
  8608. }
  8609. else if (isPlainObject(value)) {
  8610. for (const key in value) {
  8611. traverse(value[key], seen);
  8612. }
  8613. }
  8614. return value;
  8615. }
  8616. // dev only
  8617. const warnRuntimeUsage = (method) => warn$1(`${method}() is a compiler-hint helper that is only usable inside ` +
  8618. `<script setup> of a single file component. Its arguments should be ` +
  8619. `compiled away and passing it at runtime has no effect.`);
  8620. // implementation
  8621. function defineProps() {
  8622. {
  8623. warnRuntimeUsage(`defineProps`);
  8624. }
  8625. return null;
  8626. }
  8627. // implementation
  8628. function defineEmits() {
  8629. {
  8630. warnRuntimeUsage(`defineEmits`);
  8631. }
  8632. return null;
  8633. }
  8634. /**
  8635. * Vue `<script setup>` compiler macro for declaring a component's exposed
  8636. * instance properties when it is accessed by a parent component via template
  8637. * refs.
  8638. *
  8639. * `<script setup>` components are closed by default - i.e. varaibles inside
  8640. * the `<script setup>` scope is not exposed to parent unless explicitly exposed
  8641. * via `defineExpose`.
  8642. *
  8643. * This is only usable inside `<script setup>`, is compiled away in the
  8644. * output and should **not** be actually called at runtime.
  8645. */
  8646. function defineExpose(exposed) {
  8647. {
  8648. warnRuntimeUsage(`defineExpose`);
  8649. }
  8650. }
  8651. /**
  8652. * Vue `<script setup>` compiler macro for providing props default values when
  8653. * using type-based `defineProps` declaration.
  8654. *
  8655. * Example usage:
  8656. * ```ts
  8657. * withDefaults(defineProps<{
  8658. * size?: number
  8659. * labels?: string[]
  8660. * }>(), {
  8661. * size: 3,
  8662. * labels: () => ['default label']
  8663. * })
  8664. * ```
  8665. *
  8666. * This is only usable inside `<script setup>`, is compiled away in the output
  8667. * and should **not** be actually called at runtime.
  8668. */
  8669. function withDefaults(props, defaults) {
  8670. {
  8671. warnRuntimeUsage(`withDefaults`);
  8672. }
  8673. return null;
  8674. }
  8675. function useSlots() {
  8676. return getContext().slots;
  8677. }
  8678. function useAttrs() {
  8679. return getContext().attrs;
  8680. }
  8681. function getContext() {
  8682. const i = getCurrentInstance();
  8683. if (!i) {
  8684. warn$1(`useContext() called without active instance.`);
  8685. }
  8686. return i.setupContext || (i.setupContext = createSetupContext(i));
  8687. }
  8688. /**
  8689. * Runtime helper for merging default declarations. Imported by compiled code
  8690. * only.
  8691. * @internal
  8692. */
  8693. function mergeDefaults(raw, defaults) {
  8694. const props = isArray(raw)
  8695. ? raw.reduce((normalized, p) => ((normalized[p] = {}), normalized), {})
  8696. : raw;
  8697. for (const key in defaults) {
  8698. const opt = props[key];
  8699. if (opt) {
  8700. if (isArray(opt) || isFunction(opt)) {
  8701. props[key] = { type: opt, default: defaults[key] };
  8702. }
  8703. else {
  8704. opt.default = defaults[key];
  8705. }
  8706. }
  8707. else if (opt === null) {
  8708. props[key] = { default: defaults[key] };
  8709. }
  8710. else {
  8711. warn$1(`props default key "${key}" has no corresponding declaration.`);
  8712. }
  8713. }
  8714. return props;
  8715. }
  8716. /**
  8717. * Used to create a proxy for the rest element when destructuring props with
  8718. * defineProps().
  8719. * @internal
  8720. */
  8721. function createPropsRestProxy(props, excludedKeys) {
  8722. const ret = {};
  8723. for (const key in props) {
  8724. if (!excludedKeys.includes(key)) {
  8725. Object.defineProperty(ret, key, {
  8726. enumerable: true,
  8727. get: () => props[key]
  8728. });
  8729. }
  8730. }
  8731. return ret;
  8732. }
  8733. /**
  8734. * `<script setup>` helper for persisting the current instance context over
  8735. * async/await flows.
  8736. *
  8737. * `@vue/compiler-sfc` converts the following:
  8738. *
  8739. * ```ts
  8740. * const x = await foo()
  8741. * ```
  8742. *
  8743. * into:
  8744. *
  8745. * ```ts
  8746. * let __temp, __restore
  8747. * const x = (([__temp, __restore] = withAsyncContext(() => foo())),__temp=await __temp,__restore(),__temp)
  8748. * ```
  8749. * @internal
  8750. */
  8751. function withAsyncContext(getAwaitable) {
  8752. const ctx = getCurrentInstance();
  8753. if (!ctx) {
  8754. warn$1(`withAsyncContext called without active current instance. ` +
  8755. `This is likely a bug.`);
  8756. }
  8757. let awaitable = getAwaitable();
  8758. unsetCurrentInstance();
  8759. if (isPromise(awaitable)) {
  8760. awaitable = awaitable.catch(e => {
  8761. setCurrentInstance(ctx);
  8762. throw e;
  8763. });
  8764. }
  8765. return [awaitable, () => setCurrentInstance(ctx)];
  8766. }
  8767. // Actual implementation
  8768. function h(type, propsOrChildren, children) {
  8769. const l = arguments.length;
  8770. if (l === 2) {
  8771. if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
  8772. // single vnode without props
  8773. if (isVNode(propsOrChildren)) {
  8774. return createVNode(type, null, [propsOrChildren]);
  8775. }
  8776. // props without children
  8777. return createVNode(type, propsOrChildren);
  8778. }
  8779. else {
  8780. // omit props
  8781. return createVNode(type, null, propsOrChildren);
  8782. }
  8783. }
  8784. else {
  8785. if (l > 3) {
  8786. children = Array.prototype.slice.call(arguments, 2);
  8787. }
  8788. else if (l === 3 && isVNode(children)) {
  8789. children = [children];
  8790. }
  8791. return createVNode(type, propsOrChildren, children);
  8792. }
  8793. }
  8794. const ssrContextKey = Symbol(`ssrContext` );
  8795. const useSSRContext = () => {
  8796. {
  8797. const ctx = inject(ssrContextKey);
  8798. if (!ctx) {
  8799. warn$1(`Server rendering context not provided. Make sure to only call ` +
  8800. `useSSRContext() conditionally in the server build.`);
  8801. }
  8802. return ctx;
  8803. }
  8804. };
  8805. function initCustomFormatter() {
  8806. /* eslint-disable no-restricted-globals */
  8807. if (typeof window === 'undefined') {
  8808. return;
  8809. }
  8810. const vueStyle = { style: 'color:#3ba776' };
  8811. const numberStyle = { style: 'color:#0b1bc9' };
  8812. const stringStyle = { style: 'color:#b62e24' };
  8813. const keywordStyle = { style: 'color:#9d288c' };
  8814. // custom formatter for Chrome
  8815. // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
  8816. const formatter = {
  8817. header(obj) {
  8818. // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
  8819. if (!isObject(obj)) {
  8820. return null;
  8821. }
  8822. if (obj.__isVue) {
  8823. return ['div', vueStyle, `VueInstance`];
  8824. }
  8825. else if (isRef(obj)) {
  8826. return [
  8827. 'div',
  8828. {},
  8829. ['span', vueStyle, genRefFlag(obj)],
  8830. '<',
  8831. formatValue(obj.value),
  8832. `>`
  8833. ];
  8834. }
  8835. else if (isReactive(obj)) {
  8836. return [
  8837. 'div',
  8838. {},
  8839. ['span', vueStyle, 'Reactive'],
  8840. '<',
  8841. formatValue(obj),
  8842. `>${isReadonly(obj) ? ` (readonly)` : ``}`
  8843. ];
  8844. }
  8845. else if (isReadonly(obj)) {
  8846. return [
  8847. 'div',
  8848. {},
  8849. ['span', vueStyle, 'Readonly'],
  8850. '<',
  8851. formatValue(obj),
  8852. '>'
  8853. ];
  8854. }
  8855. return null;
  8856. },
  8857. hasBody(obj) {
  8858. return obj && obj.__isVue;
  8859. },
  8860. body(obj) {
  8861. if (obj && obj.__isVue) {
  8862. return [
  8863. 'div',
  8864. {},
  8865. ...formatInstance(obj.$)
  8866. ];
  8867. }
  8868. }
  8869. };
  8870. function formatInstance(instance) {
  8871. const blocks = [];
  8872. if (instance.type.props && instance.props) {
  8873. blocks.push(createInstanceBlock('props', toRaw(instance.props)));
  8874. }
  8875. if (instance.setupState !== EMPTY_OBJ) {
  8876. blocks.push(createInstanceBlock('setup', instance.setupState));
  8877. }
  8878. if (instance.data !== EMPTY_OBJ) {
  8879. blocks.push(createInstanceBlock('data', toRaw(instance.data)));
  8880. }
  8881. const computed = extractKeys(instance, 'computed');
  8882. if (computed) {
  8883. blocks.push(createInstanceBlock('computed', computed));
  8884. }
  8885. const injected = extractKeys(instance, 'inject');
  8886. if (injected) {
  8887. blocks.push(createInstanceBlock('injected', injected));
  8888. }
  8889. blocks.push([
  8890. 'div',
  8891. {},
  8892. [
  8893. 'span',
  8894. {
  8895. style: keywordStyle.style + ';opacity:0.66'
  8896. },
  8897. '$ (internal): '
  8898. ],
  8899. ['object', { object: instance }]
  8900. ]);
  8901. return blocks;
  8902. }
  8903. function createInstanceBlock(type, target) {
  8904. target = extend({}, target);
  8905. if (!Object.keys(target).length) {
  8906. return ['span', {}];
  8907. }
  8908. return [
  8909. 'div',
  8910. { style: 'line-height:1.25em;margin-bottom:0.6em' },
  8911. [
  8912. 'div',
  8913. {
  8914. style: 'color:#476582'
  8915. },
  8916. type
  8917. ],
  8918. [
  8919. 'div',
  8920. {
  8921. style: 'padding-left:1.25em'
  8922. },
  8923. ...Object.keys(target).map(key => {
  8924. return [
  8925. 'div',
  8926. {},
  8927. ['span', keywordStyle, key + ': '],
  8928. formatValue(target[key], false)
  8929. ];
  8930. })
  8931. ]
  8932. ];
  8933. }
  8934. function formatValue(v, asRaw = true) {
  8935. if (typeof v === 'number') {
  8936. return ['span', numberStyle, v];
  8937. }
  8938. else if (typeof v === 'string') {
  8939. return ['span', stringStyle, JSON.stringify(v)];
  8940. }
  8941. else if (typeof v === 'boolean') {
  8942. return ['span', keywordStyle, v];
  8943. }
  8944. else if (isObject(v)) {
  8945. return ['object', { object: asRaw ? toRaw(v) : v }];
  8946. }
  8947. else {
  8948. return ['span', stringStyle, String(v)];
  8949. }
  8950. }
  8951. function extractKeys(instance, type) {
  8952. const Comp = instance.type;
  8953. if (isFunction(Comp)) {
  8954. return;
  8955. }
  8956. const extracted = {};
  8957. for (const key in instance.ctx) {
  8958. if (isKeyOfType(Comp, key, type)) {
  8959. extracted[key] = instance.ctx[key];
  8960. }
  8961. }
  8962. return extracted;
  8963. }
  8964. function isKeyOfType(Comp, key, type) {
  8965. const opts = Comp[type];
  8966. if ((isArray(opts) && opts.includes(key)) ||
  8967. (isObject(opts) && key in opts)) {
  8968. return true;
  8969. }
  8970. if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
  8971. return true;
  8972. }
  8973. if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
  8974. return true;
  8975. }
  8976. }
  8977. function genRefFlag(v) {
  8978. if (v._shallow) {
  8979. return `ShallowRef`;
  8980. }
  8981. if (v.effect) {
  8982. return `ComputedRef`;
  8983. }
  8984. return `Ref`;
  8985. }
  8986. if (window.devtoolsFormatters) {
  8987. window.devtoolsFormatters.push(formatter);
  8988. }
  8989. else {
  8990. window.devtoolsFormatters = [formatter];
  8991. }
  8992. }
  8993. function withMemo(memo, render, cache, index) {
  8994. const cached = cache[index];
  8995. if (cached && isMemoSame(cached, memo)) {
  8996. return cached;
  8997. }
  8998. const ret = render();
  8999. // shallow clone
  9000. ret.memo = memo.slice();
  9001. return (cache[index] = ret);
  9002. }
  9003. function isMemoSame(cached, memo) {
  9004. const prev = cached.memo;
  9005. if (prev.length != memo.length) {
  9006. return false;
  9007. }
  9008. for (let i = 0; i < prev.length; i++) {
  9009. if (prev[i] !== memo[i]) {
  9010. return false;
  9011. }
  9012. }
  9013. // make sure to let parent block track it when returning cached
  9014. if (isBlockTreeEnabled > 0 && currentBlock) {
  9015. currentBlock.push(cached);
  9016. }
  9017. return true;
  9018. }
  9019. // Core API ------------------------------------------------------------------
  9020. const version = "3.2.25";
  9021. /**
  9022. * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
  9023. * @internal
  9024. */
  9025. const ssrUtils = (null);
  9026. /**
  9027. * @internal only exposed in compat builds
  9028. */
  9029. const resolveFilter = null;
  9030. /**
  9031. * @internal only exposed in compat builds.
  9032. */
  9033. const compatUtils = (null);
  9034. const svgNS = 'http://www.w3.org/2000/svg';
  9035. const doc = (typeof document !== 'undefined' ? document : null);
  9036. const staticTemplateCache = new Map();
  9037. const nodeOps = {
  9038. insert: (child, parent, anchor) => {
  9039. parent.insertBefore(child, anchor || null);
  9040. },
  9041. remove: child => {
  9042. const parent = child.parentNode;
  9043. if (parent) {
  9044. parent.removeChild(child);
  9045. }
  9046. },
  9047. createElement: (tag, isSVG, is, props) => {
  9048. const el = isSVG
  9049. ? doc.createElementNS(svgNS, tag)
  9050. : doc.createElement(tag, is ? { is } : undefined);
  9051. if (tag === 'select' && props && props.multiple != null) {
  9052. el.setAttribute('multiple', props.multiple);
  9053. }
  9054. return el;
  9055. },
  9056. createText: text => doc.createTextNode(text),
  9057. createComment: text => doc.createComment(text),
  9058. setText: (node, text) => {
  9059. node.nodeValue = text;
  9060. },
  9061. setElementText: (el, text) => {
  9062. el.textContent = text;
  9063. },
  9064. parentNode: node => node.parentNode,
  9065. nextSibling: node => node.nextSibling,
  9066. querySelector: selector => doc.querySelector(selector),
  9067. setScopeId(el, id) {
  9068. el.setAttribute(id, '');
  9069. },
  9070. cloneNode(el) {
  9071. const cloned = el.cloneNode(true);
  9072. // #3072
  9073. // - in `patchDOMProp`, we store the actual value in the `el._value` property.
  9074. // - normally, elements using `:value` bindings will not be hoisted, but if
  9075. // the bound value is a constant, e.g. `:value="true"` - they do get
  9076. // hoisted.
  9077. // - in production, hoisted nodes are cloned when subsequent inserts, but
  9078. // cloneNode() does not copy the custom property we attached.
  9079. // - This may need to account for other custom DOM properties we attach to
  9080. // elements in addition to `_value` in the future.
  9081. if (`_value` in el) {
  9082. cloned._value = el._value;
  9083. }
  9084. return cloned;
  9085. },
  9086. // __UNSAFE__
  9087. // Reason: innerHTML.
  9088. // Static content here can only come from compiled templates.
  9089. // As long as the user only uses trusted templates, this is safe.
  9090. insertStaticContent(content, parent, anchor, isSVG) {
  9091. // <parent> before | first ... last | anchor </parent>
  9092. const before = anchor ? anchor.previousSibling : parent.lastChild;
  9093. let template = staticTemplateCache.get(content);
  9094. if (!template) {
  9095. const t = doc.createElement('template');
  9096. t.innerHTML = isSVG ? `<svg>${content}</svg>` : content;
  9097. template = t.content;
  9098. if (isSVG) {
  9099. // remove outer svg wrapper
  9100. const wrapper = template.firstChild;
  9101. while (wrapper.firstChild) {
  9102. template.appendChild(wrapper.firstChild);
  9103. }
  9104. template.removeChild(wrapper);
  9105. }
  9106. staticTemplateCache.set(content, template);
  9107. }
  9108. parent.insertBefore(template.cloneNode(true), anchor);
  9109. return [
  9110. // first
  9111. before ? before.nextSibling : parent.firstChild,
  9112. // last
  9113. anchor ? anchor.previousSibling : parent.lastChild
  9114. ];
  9115. }
  9116. };
  9117. // compiler should normalize class + :class bindings on the same element
  9118. // into a single binding ['staticClass', dynamic]
  9119. function patchClass(el, value, isSVG) {
  9120. // directly setting className should be faster than setAttribute in theory
  9121. // if this is an element during a transition, take the temporary transition
  9122. // classes into account.
  9123. const transitionClasses = el._vtc;
  9124. if (transitionClasses) {
  9125. value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(' ');
  9126. }
  9127. if (value == null) {
  9128. el.removeAttribute('class');
  9129. }
  9130. else if (isSVG) {
  9131. el.setAttribute('class', value);
  9132. }
  9133. else {
  9134. el.className = value;
  9135. }
  9136. }
  9137. function patchStyle(el, prev, next) {
  9138. const style = el.style;
  9139. const isCssString = isString(next);
  9140. if (next && !isCssString) {
  9141. for (const key in next) {
  9142. setStyle(style, key, next[key]);
  9143. }
  9144. if (prev && !isString(prev)) {
  9145. for (const key in prev) {
  9146. if (next[key] == null) {
  9147. setStyle(style, key, '');
  9148. }
  9149. }
  9150. }
  9151. }
  9152. else {
  9153. const currentDisplay = style.display;
  9154. if (isCssString) {
  9155. if (prev !== next) {
  9156. style.cssText = next;
  9157. }
  9158. }
  9159. else if (prev) {
  9160. el.removeAttribute('style');
  9161. }
  9162. // indicates that the `display` of the element is controlled by `v-show`,
  9163. // so we always keep the current `display` value regardless of the `style`
  9164. // value, thus handing over control to `v-show`.
  9165. if ('_vod' in el) {
  9166. style.display = currentDisplay;
  9167. }
  9168. }
  9169. }
  9170. const importantRE = /\s*!important$/;
  9171. function setStyle(style, name, val) {
  9172. if (isArray(val)) {
  9173. val.forEach(v => setStyle(style, name, v));
  9174. }
  9175. else {
  9176. if (name.startsWith('--')) {
  9177. // custom property definition
  9178. style.setProperty(name, val);
  9179. }
  9180. else {
  9181. const prefixed = autoPrefix(style, name);
  9182. if (importantRE.test(val)) {
  9183. // !important
  9184. style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
  9185. }
  9186. else {
  9187. style[prefixed] = val;
  9188. }
  9189. }
  9190. }
  9191. }
  9192. const prefixes = ['Webkit', 'Moz', 'ms'];
  9193. const prefixCache = {};
  9194. function autoPrefix(style, rawName) {
  9195. const cached = prefixCache[rawName];
  9196. if (cached) {
  9197. return cached;
  9198. }
  9199. let name = camelize(rawName);
  9200. if (name !== 'filter' && name in style) {
  9201. return (prefixCache[rawName] = name);
  9202. }
  9203. name = capitalize(name);
  9204. for (let i = 0; i < prefixes.length; i++) {
  9205. const prefixed = prefixes[i] + name;
  9206. if (prefixed in style) {
  9207. return (prefixCache[rawName] = prefixed);
  9208. }
  9209. }
  9210. return rawName;
  9211. }
  9212. const xlinkNS = 'http://www.w3.org/1999/xlink';
  9213. function patchAttr(el, key, value, isSVG, instance) {
  9214. if (isSVG && key.startsWith('xlink:')) {
  9215. if (value == null) {
  9216. el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
  9217. }
  9218. else {
  9219. el.setAttributeNS(xlinkNS, key, value);
  9220. }
  9221. }
  9222. else {
  9223. // note we are only checking boolean attributes that don't have a
  9224. // corresponding dom prop of the same name here.
  9225. const isBoolean = isSpecialBooleanAttr(key);
  9226. if (value == null || (isBoolean && !includeBooleanAttr(value))) {
  9227. el.removeAttribute(key);
  9228. }
  9229. else {
  9230. el.setAttribute(key, isBoolean ? '' : value);
  9231. }
  9232. }
  9233. }
  9234. // __UNSAFE__
  9235. // functions. The user is responsible for using them with only trusted content.
  9236. function patchDOMProp(el, key, value,
  9237. // the following args are passed only due to potential innerHTML/textContent
  9238. // overriding existing VNodes, in which case the old tree must be properly
  9239. // unmounted.
  9240. prevChildren, parentComponent, parentSuspense, unmountChildren) {
  9241. if (key === 'innerHTML' || key === 'textContent') {
  9242. if (prevChildren) {
  9243. unmountChildren(prevChildren, parentComponent, parentSuspense);
  9244. }
  9245. el[key] = value == null ? '' : value;
  9246. return;
  9247. }
  9248. if (key === 'value' &&
  9249. el.tagName !== 'PROGRESS' &&
  9250. // custom elements may use _value internally
  9251. !el.tagName.includes('-')) {
  9252. // store value as _value as well since
  9253. // non-string values will be stringified.
  9254. el._value = value;
  9255. const newValue = value == null ? '' : value;
  9256. if (el.value !== newValue ||
  9257. // #4956: always set for OPTION elements because its value falls back to
  9258. // textContent if no value attribute is present. And setting .value for
  9259. // OPTION has no side effect
  9260. el.tagName === 'OPTION') {
  9261. el.value = newValue;
  9262. }
  9263. if (value == null) {
  9264. el.removeAttribute(key);
  9265. }
  9266. return;
  9267. }
  9268. if (value === '' || value == null) {
  9269. const type = typeof el[key];
  9270. if (type === 'boolean') {
  9271. // e.g. <select multiple> compiles to { multiple: '' }
  9272. el[key] = includeBooleanAttr(value);
  9273. return;
  9274. }
  9275. else if (value == null && type === 'string') {
  9276. // e.g. <div :id="null">
  9277. el[key] = '';
  9278. el.removeAttribute(key);
  9279. return;
  9280. }
  9281. else if (type === 'number') {
  9282. // e.g. <img :width="null">
  9283. // the value of some IDL attr must be greater than 0, e.g. input.size = 0 -> error
  9284. try {
  9285. el[key] = 0;
  9286. }
  9287. catch (_a) { }
  9288. el.removeAttribute(key);
  9289. return;
  9290. }
  9291. }
  9292. // some properties perform value validation and throw
  9293. try {
  9294. el[key] = value;
  9295. }
  9296. catch (e) {
  9297. {
  9298. warn$1(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
  9299. `value ${value} is invalid.`, e);
  9300. }
  9301. }
  9302. }
  9303. // Async edge case fix requires storing an event listener's attach timestamp.
  9304. let _getNow = Date.now;
  9305. let skipTimestampCheck = false;
  9306. if (typeof window !== 'undefined') {
  9307. // Determine what event timestamp the browser is using. Annoyingly, the
  9308. // timestamp can either be hi-res (relative to page load) or low-res
  9309. // (relative to UNIX epoch), so in order to compare time we have to use the
  9310. // same timestamp type when saving the flush timestamp.
  9311. if (_getNow() > document.createEvent('Event').timeStamp) {
  9312. // if the low-res timestamp which is bigger than the event timestamp
  9313. // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
  9314. // and we need to use the hi-res version for event listeners as well.
  9315. _getNow = () => performance.now();
  9316. }
  9317. // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
  9318. // and does not fire microtasks in between event propagation, so safe to exclude.
  9319. const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
  9320. skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
  9321. }
  9322. // To avoid the overhead of repeatedly calling performance.now(), we cache
  9323. // and use the same timestamp for all event listeners attached in the same tick.
  9324. let cachedNow = 0;
  9325. const p = Promise.resolve();
  9326. const reset = () => {
  9327. cachedNow = 0;
  9328. };
  9329. const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
  9330. function addEventListener(el, event, handler, options) {
  9331. el.addEventListener(event, handler, options);
  9332. }
  9333. function removeEventListener(el, event, handler, options) {
  9334. el.removeEventListener(event, handler, options);
  9335. }
  9336. function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  9337. // vei = vue event invokers
  9338. const invokers = el._vei || (el._vei = {});
  9339. const existingInvoker = invokers[rawName];
  9340. if (nextValue && existingInvoker) {
  9341. // patch
  9342. existingInvoker.value = nextValue;
  9343. }
  9344. else {
  9345. const [name, options] = parseName(rawName);
  9346. if (nextValue) {
  9347. // add
  9348. const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
  9349. addEventListener(el, name, invoker, options);
  9350. }
  9351. else if (existingInvoker) {
  9352. // remove
  9353. removeEventListener(el, name, existingInvoker, options);
  9354. invokers[rawName] = undefined;
  9355. }
  9356. }
  9357. }
  9358. const optionsModifierRE = /(?:Once|Passive|Capture)$/;
  9359. function parseName(name) {
  9360. let options;
  9361. if (optionsModifierRE.test(name)) {
  9362. options = {};
  9363. let m;
  9364. while ((m = name.match(optionsModifierRE))) {
  9365. name = name.slice(0, name.length - m[0].length);
  9366. options[m[0].toLowerCase()] = true;
  9367. }
  9368. }
  9369. return [hyphenate(name.slice(2)), options];
  9370. }
  9371. function createInvoker(initialValue, instance) {
  9372. const invoker = (e) => {
  9373. // async edge case #6566: inner click event triggers patch, event handler
  9374. // attached to outer element during patch, and triggered again. This
  9375. // happens because browsers fire microtask ticks between event propagation.
  9376. // the solution is simple: we save the timestamp when a handler is attached,
  9377. // and the handler would only fire if the event passed to it was fired
  9378. // AFTER it was attached.
  9379. const timeStamp = e.timeStamp || _getNow();
  9380. if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
  9381. callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
  9382. }
  9383. };
  9384. invoker.value = initialValue;
  9385. invoker.attached = getNow();
  9386. return invoker;
  9387. }
  9388. function patchStopImmediatePropagation(e, value) {
  9389. if (isArray(value)) {
  9390. const originalStop = e.stopImmediatePropagation;
  9391. e.stopImmediatePropagation = () => {
  9392. originalStop.call(e);
  9393. e._stopped = true;
  9394. };
  9395. return value.map(fn => (e) => !e._stopped && fn(e));
  9396. }
  9397. else {
  9398. return value;
  9399. }
  9400. }
  9401. const nativeOnRE = /^on[a-z]/;
  9402. const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
  9403. if (key === 'class') {
  9404. patchClass(el, nextValue, isSVG);
  9405. }
  9406. else if (key === 'style') {
  9407. patchStyle(el, prevValue, nextValue);
  9408. }
  9409. else if (isOn(key)) {
  9410. // ignore v-model listeners
  9411. if (!isModelListener(key)) {
  9412. patchEvent(el, key, prevValue, nextValue, parentComponent);
  9413. }
  9414. }
  9415. else if (key[0] === '.'
  9416. ? ((key = key.slice(1)), true)
  9417. : key[0] === '^'
  9418. ? ((key = key.slice(1)), false)
  9419. : shouldSetAsProp(el, key, nextValue, isSVG)) {
  9420. patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
  9421. }
  9422. else {
  9423. // special case for <input v-model type="checkbox"> with
  9424. // :true-value & :false-value
  9425. // store value as dom properties since non-string values will be
  9426. // stringified.
  9427. if (key === 'true-value') {
  9428. el._trueValue = nextValue;
  9429. }
  9430. else if (key === 'false-value') {
  9431. el._falseValue = nextValue;
  9432. }
  9433. patchAttr(el, key, nextValue, isSVG);
  9434. }
  9435. };
  9436. function shouldSetAsProp(el, key, value, isSVG) {
  9437. if (isSVG) {
  9438. // most keys must be set as attribute on svg elements to work
  9439. // ...except innerHTML & textContent
  9440. if (key === 'innerHTML' || key === 'textContent') {
  9441. return true;
  9442. }
  9443. // or native onclick with function values
  9444. if (key in el && nativeOnRE.test(key) && isFunction(value)) {
  9445. return true;
  9446. }
  9447. return false;
  9448. }
  9449. // spellcheck and draggable are numerated attrs, however their
  9450. // corresponding DOM properties are actually booleans - this leads to
  9451. // setting it with a string "false" value leading it to be coerced to
  9452. // `true`, so we need to always treat them as attributes.
  9453. // Note that `contentEditable` doesn't have this problem: its DOM
  9454. // property is also enumerated string values.
  9455. if (key === 'spellcheck' || key === 'draggable') {
  9456. return false;
  9457. }
  9458. // #1787, #2840 form property on form elements is readonly and must be set as
  9459. // attribute.
  9460. if (key === 'form') {
  9461. return false;
  9462. }
  9463. // #1526 <input list> must be set as attribute
  9464. if (key === 'list' && el.tagName === 'INPUT') {
  9465. return false;
  9466. }
  9467. // #2766 <textarea type> must be set as attribute
  9468. if (key === 'type' && el.tagName === 'TEXTAREA') {
  9469. return false;
  9470. }
  9471. // native onclick with string value, must be set as attribute
  9472. if (nativeOnRE.test(key) && isString(value)) {
  9473. return false;
  9474. }
  9475. return key in el;
  9476. }
  9477. function defineCustomElement(options, hydate) {
  9478. const Comp = defineComponent(options);
  9479. class VueCustomElement extends VueElement {
  9480. constructor(initialProps) {
  9481. super(Comp, initialProps, hydate);
  9482. }
  9483. }
  9484. VueCustomElement.def = Comp;
  9485. return VueCustomElement;
  9486. }
  9487. const defineSSRCustomElement = ((options) => {
  9488. // @ts-ignore
  9489. return defineCustomElement(options, hydrate);
  9490. });
  9491. const BaseClass = (typeof HTMLElement !== 'undefined' ? HTMLElement : class {
  9492. });
  9493. class VueElement extends BaseClass {
  9494. constructor(_def, _props = {}, hydrate) {
  9495. super();
  9496. this._def = _def;
  9497. this._props = _props;
  9498. /**
  9499. * @internal
  9500. */
  9501. this._instance = null;
  9502. this._connected = false;
  9503. this._resolved = false;
  9504. this._numberProps = null;
  9505. if (this.shadowRoot && hydrate) {
  9506. hydrate(this._createVNode(), this.shadowRoot);
  9507. }
  9508. else {
  9509. if (this.shadowRoot) {
  9510. warn$1(`Custom element has pre-rendered declarative shadow root but is not ` +
  9511. `defined as hydratable. Use \`defineSSRCustomElement\`.`);
  9512. }
  9513. this.attachShadow({ mode: 'open' });
  9514. }
  9515. }
  9516. connectedCallback() {
  9517. this._connected = true;
  9518. if (!this._instance) {
  9519. this._resolveDef();
  9520. }
  9521. }
  9522. disconnectedCallback() {
  9523. this._connected = false;
  9524. nextTick(() => {
  9525. if (!this._connected) {
  9526. render(null, this.shadowRoot);
  9527. this._instance = null;
  9528. }
  9529. });
  9530. }
  9531. /**
  9532. * resolve inner component definition (handle possible async component)
  9533. */
  9534. _resolveDef() {
  9535. if (this._resolved) {
  9536. return;
  9537. }
  9538. this._resolved = true;
  9539. // set initial attrs
  9540. for (let i = 0; i < this.attributes.length; i++) {
  9541. this._setAttr(this.attributes[i].name);
  9542. }
  9543. // watch future attr changes
  9544. new MutationObserver(mutations => {
  9545. for (const m of mutations) {
  9546. this._setAttr(m.attributeName);
  9547. }
  9548. }).observe(this, { attributes: true });
  9549. const resolve = (def) => {
  9550. const { props, styles } = def;
  9551. const hasOptions = !isArray(props);
  9552. const rawKeys = props ? (hasOptions ? Object.keys(props) : props) : [];
  9553. // cast Number-type props set before resolve
  9554. let numberProps;
  9555. if (hasOptions) {
  9556. for (const key in this._props) {
  9557. const opt = props[key];
  9558. if (opt === Number || (opt && opt.type === Number)) {
  9559. this._props[key] = toNumber(this._props[key]);
  9560. (numberProps || (numberProps = Object.create(null)))[key] = true;
  9561. }
  9562. }
  9563. }
  9564. this._numberProps = numberProps;
  9565. // check if there are props set pre-upgrade or connect
  9566. for (const key of Object.keys(this)) {
  9567. if (key[0] !== '_') {
  9568. this._setProp(key, this[key], true, false);
  9569. }
  9570. }
  9571. // defining getter/setters on prototype
  9572. for (const key of rawKeys.map(camelize)) {
  9573. Object.defineProperty(this, key, {
  9574. get() {
  9575. return this._getProp(key);
  9576. },
  9577. set(val) {
  9578. this._setProp(key, val);
  9579. }
  9580. });
  9581. }
  9582. // apply CSS
  9583. this._applyStyles(styles);
  9584. // initial render
  9585. this._update();
  9586. };
  9587. const asyncDef = this._def.__asyncLoader;
  9588. if (asyncDef) {
  9589. asyncDef().then(resolve);
  9590. }
  9591. else {
  9592. resolve(this._def);
  9593. }
  9594. }
  9595. _setAttr(key) {
  9596. let value = this.getAttribute(key);
  9597. if (this._numberProps && this._numberProps[key]) {
  9598. value = toNumber(value);
  9599. }
  9600. this._setProp(camelize(key), value, false);
  9601. }
  9602. /**
  9603. * @internal
  9604. */
  9605. _getProp(key) {
  9606. return this._props[key];
  9607. }
  9608. /**
  9609. * @internal
  9610. */
  9611. _setProp(key, val, shouldReflect = true, shouldUpdate = true) {
  9612. if (val !== this._props[key]) {
  9613. this._props[key] = val;
  9614. if (shouldUpdate && this._instance) {
  9615. this._update();
  9616. }
  9617. // reflect
  9618. if (shouldReflect) {
  9619. if (val === true) {
  9620. this.setAttribute(hyphenate(key), '');
  9621. }
  9622. else if (typeof val === 'string' || typeof val === 'number') {
  9623. this.setAttribute(hyphenate(key), val + '');
  9624. }
  9625. else if (!val) {
  9626. this.removeAttribute(hyphenate(key));
  9627. }
  9628. }
  9629. }
  9630. }
  9631. _update() {
  9632. render(this._createVNode(), this.shadowRoot);
  9633. }
  9634. _createVNode() {
  9635. const vnode = createVNode(this._def, extend({}, this._props));
  9636. if (!this._instance) {
  9637. vnode.ce = instance => {
  9638. this._instance = instance;
  9639. instance.isCE = true;
  9640. // HMR
  9641. {
  9642. instance.ceReload = newStyles => {
  9643. // always reset styles
  9644. if (this._styles) {
  9645. this._styles.forEach(s => this.shadowRoot.removeChild(s));
  9646. this._styles.length = 0;
  9647. }
  9648. this._applyStyles(newStyles);
  9649. // if this is an async component, ceReload is called from the inner
  9650. // component so no need to reload the async wrapper
  9651. if (!this._def.__asyncLoader) {
  9652. // reload
  9653. this._instance = null;
  9654. this._update();
  9655. }
  9656. };
  9657. }
  9658. // intercept emit
  9659. instance.emit = (event, ...args) => {
  9660. this.dispatchEvent(new CustomEvent(event, {
  9661. detail: args
  9662. }));
  9663. };
  9664. // locate nearest Vue custom element parent for provide/inject
  9665. let parent = this;
  9666. while ((parent =
  9667. parent && (parent.parentNode || parent.host))) {
  9668. if (parent instanceof VueElement) {
  9669. instance.parent = parent._instance;
  9670. break;
  9671. }
  9672. }
  9673. };
  9674. }
  9675. return vnode;
  9676. }
  9677. _applyStyles(styles) {
  9678. if (styles) {
  9679. styles.forEach(css => {
  9680. const s = document.createElement('style');
  9681. s.textContent = css;
  9682. this.shadowRoot.appendChild(s);
  9683. // record for HMR
  9684. {
  9685. (this._styles || (this._styles = [])).push(s);
  9686. }
  9687. });
  9688. }
  9689. }
  9690. }
  9691. function useCssModule(name = '$style') {
  9692. /* istanbul ignore else */
  9693. {
  9694. const instance = getCurrentInstance();
  9695. if (!instance) {
  9696. warn$1(`useCssModule must be called inside setup()`);
  9697. return EMPTY_OBJ;
  9698. }
  9699. const modules = instance.type.__cssModules;
  9700. if (!modules) {
  9701. warn$1(`Current instance does not have CSS modules injected.`);
  9702. return EMPTY_OBJ;
  9703. }
  9704. const mod = modules[name];
  9705. if (!mod) {
  9706. warn$1(`Current instance does not have CSS module named "${name}".`);
  9707. return EMPTY_OBJ;
  9708. }
  9709. return mod;
  9710. }
  9711. }
  9712. /**
  9713. * Runtime helper for SFC's CSS variable injection feature.
  9714. * @private
  9715. */
  9716. function useCssVars(getter) {
  9717. const instance = getCurrentInstance();
  9718. /* istanbul ignore next */
  9719. if (!instance) {
  9720. warn$1(`useCssVars is called without current active component instance.`);
  9721. return;
  9722. }
  9723. const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
  9724. watchPostEffect(setVars);
  9725. onMounted(() => {
  9726. const ob = new MutationObserver(setVars);
  9727. ob.observe(instance.subTree.el.parentNode, { childList: true });
  9728. onUnmounted(() => ob.disconnect());
  9729. });
  9730. }
  9731. function setVarsOnVNode(vnode, vars) {
  9732. if (vnode.shapeFlag & 128 /* SUSPENSE */) {
  9733. const suspense = vnode.suspense;
  9734. vnode = suspense.activeBranch;
  9735. if (suspense.pendingBranch && !suspense.isHydrating) {
  9736. suspense.effects.push(() => {
  9737. setVarsOnVNode(suspense.activeBranch, vars);
  9738. });
  9739. }
  9740. }
  9741. // drill down HOCs until it's a non-component vnode
  9742. while (vnode.component) {
  9743. vnode = vnode.component.subTree;
  9744. }
  9745. if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
  9746. setVarsOnNode(vnode.el, vars);
  9747. }
  9748. else if (vnode.type === Fragment) {
  9749. vnode.children.forEach(c => setVarsOnVNode(c, vars));
  9750. }
  9751. else if (vnode.type === Static) {
  9752. let { el, anchor } = vnode;
  9753. while (el) {
  9754. setVarsOnNode(el, vars);
  9755. if (el === anchor)
  9756. break;
  9757. el = el.nextSibling;
  9758. }
  9759. }
  9760. }
  9761. function setVarsOnNode(el, vars) {
  9762. if (el.nodeType === 1) {
  9763. const style = el.style;
  9764. for (const key in vars) {
  9765. style.setProperty(`--${key}`, vars[key]);
  9766. }
  9767. }
  9768. }
  9769. const TRANSITION = 'transition';
  9770. const ANIMATION = 'animation';
  9771. // DOM Transition is a higher-order-component based on the platform-agnostic
  9772. // base Transition component, with DOM-specific logic.
  9773. const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
  9774. Transition.displayName = 'Transition';
  9775. const DOMTransitionPropsValidators = {
  9776. name: String,
  9777. type: String,
  9778. css: {
  9779. type: Boolean,
  9780. default: true
  9781. },
  9782. duration: [String, Number, Object],
  9783. enterFromClass: String,
  9784. enterActiveClass: String,
  9785. enterToClass: String,
  9786. appearFromClass: String,
  9787. appearActiveClass: String,
  9788. appearToClass: String,
  9789. leaveFromClass: String,
  9790. leaveActiveClass: String,
  9791. leaveToClass: String
  9792. };
  9793. const TransitionPropsValidators = (Transition.props =
  9794. /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
  9795. /**
  9796. * #3227 Incoming hooks may be merged into arrays when wrapping Transition
  9797. * with custom HOCs.
  9798. */
  9799. const callHook$1 = (hook, args = []) => {
  9800. if (isArray(hook)) {
  9801. hook.forEach(h => h(...args));
  9802. }
  9803. else if (hook) {
  9804. hook(...args);
  9805. }
  9806. };
  9807. /**
  9808. * Check if a hook expects a callback (2nd arg), which means the user
  9809. * intends to explicitly control the end of the transition.
  9810. */
  9811. const hasExplicitCallback = (hook) => {
  9812. return hook
  9813. ? isArray(hook)
  9814. ? hook.some(h => h.length > 1)
  9815. : hook.length > 1
  9816. : false;
  9817. };
  9818. function resolveTransitionProps(rawProps) {
  9819. const baseProps = {};
  9820. for (const key in rawProps) {
  9821. if (!(key in DOMTransitionPropsValidators)) {
  9822. baseProps[key] = rawProps[key];
  9823. }
  9824. }
  9825. if (rawProps.css === false) {
  9826. return baseProps;
  9827. }
  9828. 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;
  9829. const durations = normalizeDuration(duration);
  9830. const enterDuration = durations && durations[0];
  9831. const leaveDuration = durations && durations[1];
  9832. const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
  9833. const finishEnter = (el, isAppear, done) => {
  9834. removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
  9835. removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
  9836. done && done();
  9837. };
  9838. const finishLeave = (el, done) => {
  9839. removeTransitionClass(el, leaveToClass);
  9840. removeTransitionClass(el, leaveActiveClass);
  9841. done && done();
  9842. };
  9843. const makeEnterHook = (isAppear) => {
  9844. return (el, done) => {
  9845. const hook = isAppear ? onAppear : onEnter;
  9846. const resolve = () => finishEnter(el, isAppear, done);
  9847. callHook$1(hook, [el, resolve]);
  9848. nextFrame(() => {
  9849. removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
  9850. addTransitionClass(el, isAppear ? appearToClass : enterToClass);
  9851. if (!hasExplicitCallback(hook)) {
  9852. whenTransitionEnds(el, type, enterDuration, resolve);
  9853. }
  9854. });
  9855. };
  9856. };
  9857. return extend(baseProps, {
  9858. onBeforeEnter(el) {
  9859. callHook$1(onBeforeEnter, [el]);
  9860. addTransitionClass(el, enterFromClass);
  9861. addTransitionClass(el, enterActiveClass);
  9862. },
  9863. onBeforeAppear(el) {
  9864. callHook$1(onBeforeAppear, [el]);
  9865. addTransitionClass(el, appearFromClass);
  9866. addTransitionClass(el, appearActiveClass);
  9867. },
  9868. onEnter: makeEnterHook(false),
  9869. onAppear: makeEnterHook(true),
  9870. onLeave(el, done) {
  9871. const resolve = () => finishLeave(el, done);
  9872. addTransitionClass(el, leaveFromClass);
  9873. // force reflow so *-leave-from classes immediately take effect (#2593)
  9874. forceReflow();
  9875. addTransitionClass(el, leaveActiveClass);
  9876. nextFrame(() => {
  9877. removeTransitionClass(el, leaveFromClass);
  9878. addTransitionClass(el, leaveToClass);
  9879. if (!hasExplicitCallback(onLeave)) {
  9880. whenTransitionEnds(el, type, leaveDuration, resolve);
  9881. }
  9882. });
  9883. callHook$1(onLeave, [el, resolve]);
  9884. },
  9885. onEnterCancelled(el) {
  9886. finishEnter(el, false);
  9887. callHook$1(onEnterCancelled, [el]);
  9888. },
  9889. onAppearCancelled(el) {
  9890. finishEnter(el, true);
  9891. callHook$1(onAppearCancelled, [el]);
  9892. },
  9893. onLeaveCancelled(el) {
  9894. finishLeave(el);
  9895. callHook$1(onLeaveCancelled, [el]);
  9896. }
  9897. });
  9898. }
  9899. function normalizeDuration(duration) {
  9900. if (duration == null) {
  9901. return null;
  9902. }
  9903. else if (isObject(duration)) {
  9904. return [NumberOf(duration.enter), NumberOf(duration.leave)];
  9905. }
  9906. else {
  9907. const n = NumberOf(duration);
  9908. return [n, n];
  9909. }
  9910. }
  9911. function NumberOf(val) {
  9912. const res = toNumber(val);
  9913. validateDuration(res);
  9914. return res;
  9915. }
  9916. function validateDuration(val) {
  9917. if (typeof val !== 'number') {
  9918. warn$1(`<transition> explicit duration is not a valid number - ` +
  9919. `got ${JSON.stringify(val)}.`);
  9920. }
  9921. else if (isNaN(val)) {
  9922. warn$1(`<transition> explicit duration is NaN - ` +
  9923. 'the duration expression might be incorrect.');
  9924. }
  9925. }
  9926. function addTransitionClass(el, cls) {
  9927. cls.split(/\s+/).forEach(c => c && el.classList.add(c));
  9928. (el._vtc ||
  9929. (el._vtc = new Set())).add(cls);
  9930. }
  9931. function removeTransitionClass(el, cls) {
  9932. cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
  9933. const { _vtc } = el;
  9934. if (_vtc) {
  9935. _vtc.delete(cls);
  9936. if (!_vtc.size) {
  9937. el._vtc = undefined;
  9938. }
  9939. }
  9940. }
  9941. function nextFrame(cb) {
  9942. requestAnimationFrame(() => {
  9943. requestAnimationFrame(cb);
  9944. });
  9945. }
  9946. let endId = 0;
  9947. function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
  9948. const id = (el._endId = ++endId);
  9949. const resolveIfNotStale = () => {
  9950. if (id === el._endId) {
  9951. resolve();
  9952. }
  9953. };
  9954. if (explicitTimeout) {
  9955. return setTimeout(resolveIfNotStale, explicitTimeout);
  9956. }
  9957. const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
  9958. if (!type) {
  9959. return resolve();
  9960. }
  9961. const endEvent = type + 'end';
  9962. let ended = 0;
  9963. const end = () => {
  9964. el.removeEventListener(endEvent, onEnd);
  9965. resolveIfNotStale();
  9966. };
  9967. const onEnd = (e) => {
  9968. if (e.target === el && ++ended >= propCount) {
  9969. end();
  9970. }
  9971. };
  9972. setTimeout(() => {
  9973. if (ended < propCount) {
  9974. end();
  9975. }
  9976. }, timeout + 1);
  9977. el.addEventListener(endEvent, onEnd);
  9978. }
  9979. function getTransitionInfo(el, expectedType) {
  9980. const styles = window.getComputedStyle(el);
  9981. // JSDOM may return undefined for transition properties
  9982. const getStyleProperties = (key) => (styles[key] || '').split(', ');
  9983. const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
  9984. const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
  9985. const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
  9986. const animationDelays = getStyleProperties(ANIMATION + 'Delay');
  9987. const animationDurations = getStyleProperties(ANIMATION + 'Duration');
  9988. const animationTimeout = getTimeout(animationDelays, animationDurations);
  9989. let type = null;
  9990. let timeout = 0;
  9991. let propCount = 0;
  9992. /* istanbul ignore if */
  9993. if (expectedType === TRANSITION) {
  9994. if (transitionTimeout > 0) {
  9995. type = TRANSITION;
  9996. timeout = transitionTimeout;
  9997. propCount = transitionDurations.length;
  9998. }
  9999. }
  10000. else if (expectedType === ANIMATION) {
  10001. if (animationTimeout > 0) {
  10002. type = ANIMATION;
  10003. timeout = animationTimeout;
  10004. propCount = animationDurations.length;
  10005. }
  10006. }
  10007. else {
  10008. timeout = Math.max(transitionTimeout, animationTimeout);
  10009. type =
  10010. timeout > 0
  10011. ? transitionTimeout > animationTimeout
  10012. ? TRANSITION
  10013. : ANIMATION
  10014. : null;
  10015. propCount = type
  10016. ? type === TRANSITION
  10017. ? transitionDurations.length
  10018. : animationDurations.length
  10019. : 0;
  10020. }
  10021. const hasTransform = type === TRANSITION &&
  10022. /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
  10023. return {
  10024. type,
  10025. timeout,
  10026. propCount,
  10027. hasTransform
  10028. };
  10029. }
  10030. function getTimeout(delays, durations) {
  10031. while (delays.length < durations.length) {
  10032. delays = delays.concat(delays);
  10033. }
  10034. return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
  10035. }
  10036. // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
  10037. // numbers in a locale-dependent way, using a comma instead of a dot.
  10038. // If comma is not replaced with a dot, the input will be rounded down
  10039. // (i.e. acting as a floor function) causing unexpected behaviors
  10040. function toMs(s) {
  10041. return Number(s.slice(0, -1).replace(',', '.')) * 1000;
  10042. }
  10043. // synchronously force layout to put elements into a certain state
  10044. function forceReflow() {
  10045. return document.body.offsetHeight;
  10046. }
  10047. const positionMap = new WeakMap();
  10048. const newPositionMap = new WeakMap();
  10049. const TransitionGroupImpl = {
  10050. name: 'TransitionGroup',
  10051. props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
  10052. tag: String,
  10053. moveClass: String
  10054. }),
  10055. setup(props, { slots }) {
  10056. const instance = getCurrentInstance();
  10057. const state = useTransitionState();
  10058. let prevChildren;
  10059. let children;
  10060. onUpdated(() => {
  10061. // children is guaranteed to exist after initial render
  10062. if (!prevChildren.length) {
  10063. return;
  10064. }
  10065. const moveClass = props.moveClass || `${props.name || 'v'}-move`;
  10066. if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
  10067. return;
  10068. }
  10069. // we divide the work into three loops to avoid mixing DOM reads and writes
  10070. // in each iteration - which helps prevent layout thrashing.
  10071. prevChildren.forEach(callPendingCbs);
  10072. prevChildren.forEach(recordPosition);
  10073. const movedChildren = prevChildren.filter(applyTranslation);
  10074. // force reflow to put everything in position
  10075. forceReflow();
  10076. movedChildren.forEach(c => {
  10077. const el = c.el;
  10078. const style = el.style;
  10079. addTransitionClass(el, moveClass);
  10080. style.transform = style.webkitTransform = style.transitionDuration = '';
  10081. const cb = (el._moveCb = (e) => {
  10082. if (e && e.target !== el) {
  10083. return;
  10084. }
  10085. if (!e || /transform$/.test(e.propertyName)) {
  10086. el.removeEventListener('transitionend', cb);
  10087. el._moveCb = null;
  10088. removeTransitionClass(el, moveClass);
  10089. }
  10090. });
  10091. el.addEventListener('transitionend', cb);
  10092. });
  10093. });
  10094. return () => {
  10095. const rawProps = toRaw(props);
  10096. const cssTransitionProps = resolveTransitionProps(rawProps);
  10097. let tag = rawProps.tag || Fragment;
  10098. prevChildren = children;
  10099. children = slots.default ? getTransitionRawChildren(slots.default()) : [];
  10100. for (let i = 0; i < children.length; i++) {
  10101. const child = children[i];
  10102. if (child.key != null) {
  10103. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  10104. }
  10105. else {
  10106. warn$1(`<TransitionGroup> children must be keyed.`);
  10107. }
  10108. }
  10109. if (prevChildren) {
  10110. for (let i = 0; i < prevChildren.length; i++) {
  10111. const child = prevChildren[i];
  10112. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  10113. positionMap.set(child, child.el.getBoundingClientRect());
  10114. }
  10115. }
  10116. return createVNode(tag, null, children);
  10117. };
  10118. }
  10119. };
  10120. const TransitionGroup = TransitionGroupImpl;
  10121. function callPendingCbs(c) {
  10122. const el = c.el;
  10123. if (el._moveCb) {
  10124. el._moveCb();
  10125. }
  10126. if (el._enterCb) {
  10127. el._enterCb();
  10128. }
  10129. }
  10130. function recordPosition(c) {
  10131. newPositionMap.set(c, c.el.getBoundingClientRect());
  10132. }
  10133. function applyTranslation(c) {
  10134. const oldPos = positionMap.get(c);
  10135. const newPos = newPositionMap.get(c);
  10136. const dx = oldPos.left - newPos.left;
  10137. const dy = oldPos.top - newPos.top;
  10138. if (dx || dy) {
  10139. const s = c.el.style;
  10140. s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
  10141. s.transitionDuration = '0s';
  10142. return c;
  10143. }
  10144. }
  10145. function hasCSSTransform(el, root, moveClass) {
  10146. // Detect whether an element with the move class applied has
  10147. // CSS transitions. Since the element may be inside an entering
  10148. // transition at this very moment, we make a clone of it and remove
  10149. // all other transition classes applied to ensure only the move class
  10150. // is applied.
  10151. const clone = el.cloneNode();
  10152. if (el._vtc) {
  10153. el._vtc.forEach(cls => {
  10154. cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
  10155. });
  10156. }
  10157. moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
  10158. clone.style.display = 'none';
  10159. const container = (root.nodeType === 1 ? root : root.parentNode);
  10160. container.appendChild(clone);
  10161. const { hasTransform } = getTransitionInfo(clone);
  10162. container.removeChild(clone);
  10163. return hasTransform;
  10164. }
  10165. const getModelAssigner = (vnode) => {
  10166. const fn = vnode.props['onUpdate:modelValue'];
  10167. return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
  10168. };
  10169. function onCompositionStart(e) {
  10170. e.target.composing = true;
  10171. }
  10172. function onCompositionEnd(e) {
  10173. const target = e.target;
  10174. if (target.composing) {
  10175. target.composing = false;
  10176. trigger$1(target, 'input');
  10177. }
  10178. }
  10179. function trigger$1(el, type) {
  10180. const e = document.createEvent('HTMLEvents');
  10181. e.initEvent(type, true, true);
  10182. el.dispatchEvent(e);
  10183. }
  10184. // We are exporting the v-model runtime directly as vnode hooks so that it can
  10185. // be tree-shaken in case v-model is never used.
  10186. const vModelText = {
  10187. created(el, { modifiers: { lazy, trim, number } }, vnode) {
  10188. el._assign = getModelAssigner(vnode);
  10189. const castToNumber = number || (vnode.props && vnode.props.type === 'number');
  10190. addEventListener(el, lazy ? 'change' : 'input', e => {
  10191. if (e.target.composing)
  10192. return;
  10193. let domValue = el.value;
  10194. if (trim) {
  10195. domValue = domValue.trim();
  10196. }
  10197. else if (castToNumber) {
  10198. domValue = toNumber(domValue);
  10199. }
  10200. el._assign(domValue);
  10201. });
  10202. if (trim) {
  10203. addEventListener(el, 'change', () => {
  10204. el.value = el.value.trim();
  10205. });
  10206. }
  10207. if (!lazy) {
  10208. addEventListener(el, 'compositionstart', onCompositionStart);
  10209. addEventListener(el, 'compositionend', onCompositionEnd);
  10210. // Safari < 10.2 & UIWebView doesn't fire compositionend when
  10211. // switching focus before confirming composition choice
  10212. // this also fixes the issue where some browsers e.g. iOS Chrome
  10213. // fires "change" instead of "input" on autocomplete.
  10214. addEventListener(el, 'change', onCompositionEnd);
  10215. }
  10216. },
  10217. // set value on mounted so it's after min/max for type="range"
  10218. mounted(el, { value }) {
  10219. el.value = value == null ? '' : value;
  10220. },
  10221. beforeUpdate(el, { value, modifiers: { lazy, trim, number } }, vnode) {
  10222. el._assign = getModelAssigner(vnode);
  10223. // avoid clearing unresolved text. #2302
  10224. if (el.composing)
  10225. return;
  10226. if (document.activeElement === el) {
  10227. if (lazy) {
  10228. return;
  10229. }
  10230. if (trim && el.value.trim() === value) {
  10231. return;
  10232. }
  10233. if ((number || el.type === 'number') && toNumber(el.value) === value) {
  10234. return;
  10235. }
  10236. }
  10237. const newValue = value == null ? '' : value;
  10238. if (el.value !== newValue) {
  10239. el.value = newValue;
  10240. }
  10241. }
  10242. };
  10243. const vModelCheckbox = {
  10244. // #4096 array checkboxes need to be deep traversed
  10245. deep: true,
  10246. created(el, _, vnode) {
  10247. el._assign = getModelAssigner(vnode);
  10248. addEventListener(el, 'change', () => {
  10249. const modelValue = el._modelValue;
  10250. const elementValue = getValue(el);
  10251. const checked = el.checked;
  10252. const assign = el._assign;
  10253. if (isArray(modelValue)) {
  10254. const index = looseIndexOf(modelValue, elementValue);
  10255. const found = index !== -1;
  10256. if (checked && !found) {
  10257. assign(modelValue.concat(elementValue));
  10258. }
  10259. else if (!checked && found) {
  10260. const filtered = [...modelValue];
  10261. filtered.splice(index, 1);
  10262. assign(filtered);
  10263. }
  10264. }
  10265. else if (isSet(modelValue)) {
  10266. const cloned = new Set(modelValue);
  10267. if (checked) {
  10268. cloned.add(elementValue);
  10269. }
  10270. else {
  10271. cloned.delete(elementValue);
  10272. }
  10273. assign(cloned);
  10274. }
  10275. else {
  10276. assign(getCheckboxValue(el, checked));
  10277. }
  10278. });
  10279. },
  10280. // set initial checked on mount to wait for true-value/false-value
  10281. mounted: setChecked,
  10282. beforeUpdate(el, binding, vnode) {
  10283. el._assign = getModelAssigner(vnode);
  10284. setChecked(el, binding, vnode);
  10285. }
  10286. };
  10287. function setChecked(el, { value, oldValue }, vnode) {
  10288. el._modelValue = value;
  10289. if (isArray(value)) {
  10290. el.checked = looseIndexOf(value, vnode.props.value) > -1;
  10291. }
  10292. else if (isSet(value)) {
  10293. el.checked = value.has(vnode.props.value);
  10294. }
  10295. else if (value !== oldValue) {
  10296. el.checked = looseEqual(value, getCheckboxValue(el, true));
  10297. }
  10298. }
  10299. const vModelRadio = {
  10300. created(el, { value }, vnode) {
  10301. el.checked = looseEqual(value, vnode.props.value);
  10302. el._assign = getModelAssigner(vnode);
  10303. addEventListener(el, 'change', () => {
  10304. el._assign(getValue(el));
  10305. });
  10306. },
  10307. beforeUpdate(el, { value, oldValue }, vnode) {
  10308. el._assign = getModelAssigner(vnode);
  10309. if (value !== oldValue) {
  10310. el.checked = looseEqual(value, vnode.props.value);
  10311. }
  10312. }
  10313. };
  10314. const vModelSelect = {
  10315. // <select multiple> value need to be deep traversed
  10316. deep: true,
  10317. created(el, { value, modifiers: { number } }, vnode) {
  10318. const isSetModel = isSet(value);
  10319. addEventListener(el, 'change', () => {
  10320. const selectedVal = Array.prototype.filter
  10321. .call(el.options, (o) => o.selected)
  10322. .map((o) => number ? toNumber(getValue(o)) : getValue(o));
  10323. el._assign(el.multiple
  10324. ? isSetModel
  10325. ? new Set(selectedVal)
  10326. : selectedVal
  10327. : selectedVal[0]);
  10328. });
  10329. el._assign = getModelAssigner(vnode);
  10330. },
  10331. // set value in mounted & updated because <select> relies on its children
  10332. // <option>s.
  10333. mounted(el, { value }) {
  10334. setSelected(el, value);
  10335. },
  10336. beforeUpdate(el, _binding, vnode) {
  10337. el._assign = getModelAssigner(vnode);
  10338. },
  10339. updated(el, { value }) {
  10340. setSelected(el, value);
  10341. }
  10342. };
  10343. function setSelected(el, value) {
  10344. const isMultiple = el.multiple;
  10345. if (isMultiple && !isArray(value) && !isSet(value)) {
  10346. warn$1(`<select multiple v-model> expects an Array or Set value for its binding, ` +
  10347. `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
  10348. return;
  10349. }
  10350. for (let i = 0, l = el.options.length; i < l; i++) {
  10351. const option = el.options[i];
  10352. const optionValue = getValue(option);
  10353. if (isMultiple) {
  10354. if (isArray(value)) {
  10355. option.selected = looseIndexOf(value, optionValue) > -1;
  10356. }
  10357. else {
  10358. option.selected = value.has(optionValue);
  10359. }
  10360. }
  10361. else {
  10362. if (looseEqual(getValue(option), value)) {
  10363. if (el.selectedIndex !== i)
  10364. el.selectedIndex = i;
  10365. return;
  10366. }
  10367. }
  10368. }
  10369. if (!isMultiple && el.selectedIndex !== -1) {
  10370. el.selectedIndex = -1;
  10371. }
  10372. }
  10373. // retrieve raw value set via :value bindings
  10374. function getValue(el) {
  10375. return '_value' in el ? el._value : el.value;
  10376. }
  10377. // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
  10378. function getCheckboxValue(el, checked) {
  10379. const key = checked ? '_trueValue' : '_falseValue';
  10380. return key in el ? el[key] : checked;
  10381. }
  10382. const vModelDynamic = {
  10383. created(el, binding, vnode) {
  10384. callModelHook(el, binding, vnode, null, 'created');
  10385. },
  10386. mounted(el, binding, vnode) {
  10387. callModelHook(el, binding, vnode, null, 'mounted');
  10388. },
  10389. beforeUpdate(el, binding, vnode, prevVNode) {
  10390. callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
  10391. },
  10392. updated(el, binding, vnode, prevVNode) {
  10393. callModelHook(el, binding, vnode, prevVNode, 'updated');
  10394. }
  10395. };
  10396. function callModelHook(el, binding, vnode, prevVNode, hook) {
  10397. let modelToUse;
  10398. switch (el.tagName) {
  10399. case 'SELECT':
  10400. modelToUse = vModelSelect;
  10401. break;
  10402. case 'TEXTAREA':
  10403. modelToUse = vModelText;
  10404. break;
  10405. default:
  10406. switch (vnode.props && vnode.props.type) {
  10407. case 'checkbox':
  10408. modelToUse = vModelCheckbox;
  10409. break;
  10410. case 'radio':
  10411. modelToUse = vModelRadio;
  10412. break;
  10413. default:
  10414. modelToUse = vModelText;
  10415. }
  10416. }
  10417. const fn = modelToUse[hook];
  10418. fn && fn(el, binding, vnode, prevVNode);
  10419. }
  10420. const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
  10421. const modifierGuards = {
  10422. stop: e => e.stopPropagation(),
  10423. prevent: e => e.preventDefault(),
  10424. self: e => e.target !== e.currentTarget,
  10425. ctrl: e => !e.ctrlKey,
  10426. shift: e => !e.shiftKey,
  10427. alt: e => !e.altKey,
  10428. meta: e => !e.metaKey,
  10429. left: e => 'button' in e && e.button !== 0,
  10430. middle: e => 'button' in e && e.button !== 1,
  10431. right: e => 'button' in e && e.button !== 2,
  10432. exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
  10433. };
  10434. /**
  10435. * @private
  10436. */
  10437. const withModifiers = (fn, modifiers) => {
  10438. return (event, ...args) => {
  10439. for (let i = 0; i < modifiers.length; i++) {
  10440. const guard = modifierGuards[modifiers[i]];
  10441. if (guard && guard(event, modifiers))
  10442. return;
  10443. }
  10444. return fn(event, ...args);
  10445. };
  10446. };
  10447. // Kept for 2.x compat.
  10448. // Note: IE11 compat for `spacebar` and `del` is removed for now.
  10449. const keyNames = {
  10450. esc: 'escape',
  10451. space: ' ',
  10452. up: 'arrow-up',
  10453. left: 'arrow-left',
  10454. right: 'arrow-right',
  10455. down: 'arrow-down',
  10456. delete: 'backspace'
  10457. };
  10458. /**
  10459. * @private
  10460. */
  10461. const withKeys = (fn, modifiers) => {
  10462. return (event) => {
  10463. if (!('key' in event)) {
  10464. return;
  10465. }
  10466. const eventKey = hyphenate(event.key);
  10467. if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
  10468. return fn(event);
  10469. }
  10470. };
  10471. };
  10472. const vShow = {
  10473. beforeMount(el, { value }, { transition }) {
  10474. el._vod = el.style.display === 'none' ? '' : el.style.display;
  10475. if (transition && value) {
  10476. transition.beforeEnter(el);
  10477. }
  10478. else {
  10479. setDisplay(el, value);
  10480. }
  10481. },
  10482. mounted(el, { value }, { transition }) {
  10483. if (transition && value) {
  10484. transition.enter(el);
  10485. }
  10486. },
  10487. updated(el, { value, oldValue }, { transition }) {
  10488. if (!value === !oldValue)
  10489. return;
  10490. if (transition) {
  10491. if (value) {
  10492. transition.beforeEnter(el);
  10493. setDisplay(el, true);
  10494. transition.enter(el);
  10495. }
  10496. else {
  10497. transition.leave(el, () => {
  10498. setDisplay(el, false);
  10499. });
  10500. }
  10501. }
  10502. else {
  10503. setDisplay(el, value);
  10504. }
  10505. },
  10506. beforeUnmount(el, { value }) {
  10507. setDisplay(el, value);
  10508. }
  10509. };
  10510. function setDisplay(el, value) {
  10511. el.style.display = value ? el._vod : 'none';
  10512. }
  10513. const rendererOptions = extend({ patchProp }, nodeOps);
  10514. // lazy create the renderer - this makes core renderer logic tree-shakable
  10515. // in case the user only imports reactivity utilities from Vue.
  10516. let renderer;
  10517. let enabledHydration = false;
  10518. function ensureRenderer() {
  10519. return (renderer ||
  10520. (renderer = createRenderer(rendererOptions)));
  10521. }
  10522. function ensureHydrationRenderer() {
  10523. renderer = enabledHydration
  10524. ? renderer
  10525. : createHydrationRenderer(rendererOptions);
  10526. enabledHydration = true;
  10527. return renderer;
  10528. }
  10529. // use explicit type casts here to avoid import() calls in rolled-up d.ts
  10530. const render = ((...args) => {
  10531. ensureRenderer().render(...args);
  10532. });
  10533. const hydrate = ((...args) => {
  10534. ensureHydrationRenderer().hydrate(...args);
  10535. });
  10536. const createApp = ((...args) => {
  10537. const app = ensureRenderer().createApp(...args);
  10538. {
  10539. injectNativeTagCheck(app);
  10540. injectCompilerOptionsCheck(app);
  10541. }
  10542. const { mount } = app;
  10543. app.mount = (containerOrSelector) => {
  10544. const container = normalizeContainer(containerOrSelector);
  10545. if (!container)
  10546. return;
  10547. const component = app._component;
  10548. if (!isFunction(component) && !component.render && !component.template) {
  10549. // __UNSAFE__
  10550. // Reason: potential execution of JS expressions in in-DOM template.
  10551. // The user must make sure the in-DOM template is trusted. If it's
  10552. // rendered by the server, the template should not contain any user data.
  10553. component.template = container.innerHTML;
  10554. }
  10555. // clear content before mounting
  10556. container.innerHTML = '';
  10557. const proxy = mount(container, false, container instanceof SVGElement);
  10558. if (container instanceof Element) {
  10559. container.removeAttribute('v-cloak');
  10560. container.setAttribute('data-v-app', '');
  10561. }
  10562. return proxy;
  10563. };
  10564. return app;
  10565. });
  10566. const createSSRApp = ((...args) => {
  10567. const app = ensureHydrationRenderer().createApp(...args);
  10568. {
  10569. injectNativeTagCheck(app);
  10570. injectCompilerOptionsCheck(app);
  10571. }
  10572. const { mount } = app;
  10573. app.mount = (containerOrSelector) => {
  10574. const container = normalizeContainer(containerOrSelector);
  10575. if (container) {
  10576. return mount(container, true, container instanceof SVGElement);
  10577. }
  10578. };
  10579. return app;
  10580. });
  10581. function injectNativeTagCheck(app) {
  10582. // Inject `isNativeTag`
  10583. // this is used for component name validation (dev only)
  10584. Object.defineProperty(app.config, 'isNativeTag', {
  10585. value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
  10586. writable: false
  10587. });
  10588. }
  10589. // dev only
  10590. function injectCompilerOptionsCheck(app) {
  10591. if (isRuntimeOnly()) {
  10592. const isCustomElement = app.config.isCustomElement;
  10593. Object.defineProperty(app.config, 'isCustomElement', {
  10594. get() {
  10595. return isCustomElement;
  10596. },
  10597. set() {
  10598. warn$1(`The \`isCustomElement\` config option is deprecated. Use ` +
  10599. `\`compilerOptions.isCustomElement\` instead.`);
  10600. }
  10601. });
  10602. const compilerOptions = app.config.compilerOptions;
  10603. const msg = `The \`compilerOptions\` config option is only respected when using ` +
  10604. `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
  10605. `Since you are using the runtime-only build, \`compilerOptions\` ` +
  10606. `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
  10607. `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
  10608. `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
  10609. `- 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`;
  10610. Object.defineProperty(app.config, 'compilerOptions', {
  10611. get() {
  10612. warn$1(msg);
  10613. return compilerOptions;
  10614. },
  10615. set() {
  10616. warn$1(msg);
  10617. }
  10618. });
  10619. }
  10620. }
  10621. function normalizeContainer(container) {
  10622. if (isString(container)) {
  10623. const res = document.querySelector(container);
  10624. if (!res) {
  10625. warn$1(`Failed to mount app: mount target selector "${container}" returned null.`);
  10626. }
  10627. return res;
  10628. }
  10629. if (window.ShadowRoot &&
  10630. container instanceof window.ShadowRoot &&
  10631. container.mode === 'closed') {
  10632. warn$1(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
  10633. }
  10634. return container;
  10635. }
  10636. /**
  10637. * @internal
  10638. */
  10639. const initDirectivesForSSR = NOOP;
  10640. var runtimeDom = /*#__PURE__*/Object.freeze({
  10641. __proto__: null,
  10642. render: render,
  10643. hydrate: hydrate,
  10644. createApp: createApp,
  10645. createSSRApp: createSSRApp,
  10646. initDirectivesForSSR: initDirectivesForSSR,
  10647. defineCustomElement: defineCustomElement,
  10648. defineSSRCustomElement: defineSSRCustomElement,
  10649. VueElement: VueElement,
  10650. useCssModule: useCssModule,
  10651. useCssVars: useCssVars,
  10652. Transition: Transition,
  10653. TransitionGroup: TransitionGroup,
  10654. vModelText: vModelText,
  10655. vModelCheckbox: vModelCheckbox,
  10656. vModelRadio: vModelRadio,
  10657. vModelSelect: vModelSelect,
  10658. vModelDynamic: vModelDynamic,
  10659. withModifiers: withModifiers,
  10660. withKeys: withKeys,
  10661. vShow: vShow,
  10662. computed: computed,
  10663. reactive: reactive,
  10664. ref: ref,
  10665. readonly: readonly,
  10666. unref: unref,
  10667. proxyRefs: proxyRefs,
  10668. isRef: isRef,
  10669. toRef: toRef,
  10670. toRefs: toRefs,
  10671. isProxy: isProxy,
  10672. isReactive: isReactive,
  10673. isReadonly: isReadonly,
  10674. customRef: customRef,
  10675. triggerRef: triggerRef,
  10676. shallowRef: shallowRef,
  10677. shallowReactive: shallowReactive,
  10678. shallowReadonly: shallowReadonly,
  10679. markRaw: markRaw,
  10680. toRaw: toRaw,
  10681. effect: effect,
  10682. stop: stop,
  10683. ReactiveEffect: ReactiveEffect,
  10684. effectScope: effectScope,
  10685. EffectScope: EffectScope,
  10686. getCurrentScope: getCurrentScope,
  10687. onScopeDispose: onScopeDispose,
  10688. watch: watch,
  10689. watchEffect: watchEffect,
  10690. watchPostEffect: watchPostEffect,
  10691. watchSyncEffect: watchSyncEffect,
  10692. onBeforeMount: onBeforeMount,
  10693. onMounted: onMounted,
  10694. onBeforeUpdate: onBeforeUpdate,
  10695. onUpdated: onUpdated,
  10696. onBeforeUnmount: onBeforeUnmount,
  10697. onUnmounted: onUnmounted,
  10698. onActivated: onActivated,
  10699. onDeactivated: onDeactivated,
  10700. onRenderTracked: onRenderTracked,
  10701. onRenderTriggered: onRenderTriggered,
  10702. onErrorCaptured: onErrorCaptured,
  10703. onServerPrefetch: onServerPrefetch,
  10704. provide: provide,
  10705. inject: inject,
  10706. nextTick: nextTick,
  10707. defineComponent: defineComponent,
  10708. defineAsyncComponent: defineAsyncComponent,
  10709. useAttrs: useAttrs,
  10710. useSlots: useSlots,
  10711. defineProps: defineProps,
  10712. defineEmits: defineEmits,
  10713. defineExpose: defineExpose,
  10714. withDefaults: withDefaults,
  10715. mergeDefaults: mergeDefaults,
  10716. createPropsRestProxy: createPropsRestProxy,
  10717. withAsyncContext: withAsyncContext,
  10718. getCurrentInstance: getCurrentInstance,
  10719. h: h,
  10720. createVNode: createVNode,
  10721. cloneVNode: cloneVNode,
  10722. mergeProps: mergeProps,
  10723. isVNode: isVNode,
  10724. Fragment: Fragment,
  10725. Text: Text,
  10726. Comment: Comment,
  10727. Static: Static,
  10728. Teleport: Teleport,
  10729. Suspense: Suspense,
  10730. KeepAlive: KeepAlive,
  10731. BaseTransition: BaseTransition,
  10732. withDirectives: withDirectives,
  10733. useSSRContext: useSSRContext,
  10734. ssrContextKey: ssrContextKey,
  10735. createRenderer: createRenderer,
  10736. createHydrationRenderer: createHydrationRenderer,
  10737. queuePostFlushCb: queuePostFlushCb,
  10738. warn: warn$1,
  10739. handleError: handleError,
  10740. callWithErrorHandling: callWithErrorHandling,
  10741. callWithAsyncErrorHandling: callWithAsyncErrorHandling,
  10742. resolveComponent: resolveComponent,
  10743. resolveDirective: resolveDirective,
  10744. resolveDynamicComponent: resolveDynamicComponent,
  10745. registerRuntimeCompiler: registerRuntimeCompiler,
  10746. isRuntimeOnly: isRuntimeOnly,
  10747. useTransitionState: useTransitionState,
  10748. resolveTransitionHooks: resolveTransitionHooks,
  10749. setTransitionHooks: setTransitionHooks,
  10750. getTransitionRawChildren: getTransitionRawChildren,
  10751. initCustomFormatter: initCustomFormatter,
  10752. get devtools () { return devtools; },
  10753. setDevtoolsHook: setDevtoolsHook,
  10754. withCtx: withCtx,
  10755. pushScopeId: pushScopeId,
  10756. popScopeId: popScopeId,
  10757. withScopeId: withScopeId,
  10758. renderList: renderList,
  10759. toHandlers: toHandlers,
  10760. renderSlot: renderSlot,
  10761. createSlots: createSlots,
  10762. withMemo: withMemo,
  10763. isMemoSame: isMemoSame,
  10764. openBlock: openBlock,
  10765. createBlock: createBlock,
  10766. setBlockTracking: setBlockTracking,
  10767. createTextVNode: createTextVNode,
  10768. createCommentVNode: createCommentVNode,
  10769. createStaticVNode: createStaticVNode,
  10770. createElementVNode: createBaseVNode,
  10771. createElementBlock: createElementBlock,
  10772. guardReactiveProps: guardReactiveProps,
  10773. toDisplayString: toDisplayString,
  10774. camelize: camelize,
  10775. capitalize: capitalize,
  10776. toHandlerKey: toHandlerKey,
  10777. normalizeProps: normalizeProps,
  10778. normalizeClass: normalizeClass,
  10779. normalizeStyle: normalizeStyle,
  10780. transformVNodeArgs: transformVNodeArgs,
  10781. version: version,
  10782. ssrUtils: ssrUtils,
  10783. resolveFilter: resolveFilter,
  10784. compatUtils: compatUtils
  10785. });
  10786. function initDev() {
  10787. {
  10788. {
  10789. console.info(`You are running a development build of Vue.\n` +
  10790. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  10791. }
  10792. initCustomFormatter();
  10793. }
  10794. }
  10795. function defaultOnError(error) {
  10796. throw error;
  10797. }
  10798. function defaultOnWarn(msg) {
  10799. console.warn(`[Vue warn] ${msg.message}`);
  10800. }
  10801. function createCompilerError(code, loc, messages, additionalMessage) {
  10802. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  10803. ;
  10804. const error = new SyntaxError(String(msg));
  10805. error.code = code;
  10806. error.loc = loc;
  10807. return error;
  10808. }
  10809. const errorMessages = {
  10810. // parse errors
  10811. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  10812. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  10813. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  10814. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  10815. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  10816. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  10817. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  10818. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  10819. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  10820. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  10821. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  10822. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  10823. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  10824. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  10825. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  10826. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  10827. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  10828. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  10829. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  10830. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  10831. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  10832. [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null character.`,
  10833. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  10834. // Vue-specific parse errors
  10835. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  10836. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  10837. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  10838. [27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  10839. 'Note that dynamic directive argument cannot contain spaces.',
  10840. [26 /* X_MISSING_DIRECTIVE_NAME */]: 'Legal directive name was expected.',
  10841. // transform errors
  10842. [28 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  10843. [29 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  10844. [30 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  10845. [31 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  10846. [32 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  10847. [33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  10848. [34 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  10849. [35 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  10850. [36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  10851. [37 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  10852. `When there are multiple named slots, all slots should use <template> ` +
  10853. `syntax to avoid scope ambiguity.`,
  10854. [38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  10855. [39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  10856. `default slot. These children will be ignored.`,
  10857. [40 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  10858. [41 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  10859. [42 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  10860. [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.`,
  10861. [44 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  10862. [45 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  10863. // generic errors
  10864. [46 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  10865. [47 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  10866. [48 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  10867. [49 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
  10868. // just to fulfill types
  10869. [50 /* __EXTEND_POINT__ */]: ``
  10870. };
  10871. const FRAGMENT = Symbol(`Fragment` );
  10872. const TELEPORT = Symbol(`Teleport` );
  10873. const SUSPENSE = Symbol(`Suspense` );
  10874. const KEEP_ALIVE = Symbol(`KeepAlive` );
  10875. const BASE_TRANSITION = Symbol(`BaseTransition` );
  10876. const OPEN_BLOCK = Symbol(`openBlock` );
  10877. const CREATE_BLOCK = Symbol(`createBlock` );
  10878. const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock` );
  10879. const CREATE_VNODE = Symbol(`createVNode` );
  10880. const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode` );
  10881. const CREATE_COMMENT = Symbol(`createCommentVNode` );
  10882. const CREATE_TEXT = Symbol(`createTextVNode` );
  10883. const CREATE_STATIC = Symbol(`createStaticVNode` );
  10884. const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
  10885. const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
  10886. const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
  10887. const RESOLVE_FILTER = Symbol(`resolveFilter` );
  10888. const WITH_DIRECTIVES = Symbol(`withDirectives` );
  10889. const RENDER_LIST = Symbol(`renderList` );
  10890. const RENDER_SLOT = Symbol(`renderSlot` );
  10891. const CREATE_SLOTS = Symbol(`createSlots` );
  10892. const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
  10893. const MERGE_PROPS = Symbol(`mergeProps` );
  10894. const NORMALIZE_CLASS = Symbol(`normalizeClass` );
  10895. const NORMALIZE_STYLE = Symbol(`normalizeStyle` );
  10896. const NORMALIZE_PROPS = Symbol(`normalizeProps` );
  10897. const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps` );
  10898. const TO_HANDLERS = Symbol(`toHandlers` );
  10899. const CAMELIZE = Symbol(`camelize` );
  10900. const CAPITALIZE = Symbol(`capitalize` );
  10901. const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
  10902. const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
  10903. const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
  10904. const POP_SCOPE_ID = Symbol(`popScopeId` );
  10905. const WITH_CTX = Symbol(`withCtx` );
  10906. const UNREF = Symbol(`unref` );
  10907. const IS_REF = Symbol(`isRef` );
  10908. const WITH_MEMO = Symbol(`withMemo` );
  10909. const IS_MEMO_SAME = Symbol(`isMemoSame` );
  10910. // Name mapping for runtime helpers that need to be imported from 'vue' in
  10911. // generated code. Make sure these are correctly exported in the runtime!
  10912. // Using `any` here because TS doesn't allow symbols as index type.
  10913. const helperNameMap = {
  10914. [FRAGMENT]: `Fragment`,
  10915. [TELEPORT]: `Teleport`,
  10916. [SUSPENSE]: `Suspense`,
  10917. [KEEP_ALIVE]: `KeepAlive`,
  10918. [BASE_TRANSITION]: `BaseTransition`,
  10919. [OPEN_BLOCK]: `openBlock`,
  10920. [CREATE_BLOCK]: `createBlock`,
  10921. [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  10922. [CREATE_VNODE]: `createVNode`,
  10923. [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  10924. [CREATE_COMMENT]: `createCommentVNode`,
  10925. [CREATE_TEXT]: `createTextVNode`,
  10926. [CREATE_STATIC]: `createStaticVNode`,
  10927. [RESOLVE_COMPONENT]: `resolveComponent`,
  10928. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  10929. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  10930. [RESOLVE_FILTER]: `resolveFilter`,
  10931. [WITH_DIRECTIVES]: `withDirectives`,
  10932. [RENDER_LIST]: `renderList`,
  10933. [RENDER_SLOT]: `renderSlot`,
  10934. [CREATE_SLOTS]: `createSlots`,
  10935. [TO_DISPLAY_STRING]: `toDisplayString`,
  10936. [MERGE_PROPS]: `mergeProps`,
  10937. [NORMALIZE_CLASS]: `normalizeClass`,
  10938. [NORMALIZE_STYLE]: `normalizeStyle`,
  10939. [NORMALIZE_PROPS]: `normalizeProps`,
  10940. [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  10941. [TO_HANDLERS]: `toHandlers`,
  10942. [CAMELIZE]: `camelize`,
  10943. [CAPITALIZE]: `capitalize`,
  10944. [TO_HANDLER_KEY]: `toHandlerKey`,
  10945. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  10946. [PUSH_SCOPE_ID]: `pushScopeId`,
  10947. [POP_SCOPE_ID]: `popScopeId`,
  10948. [WITH_CTX]: `withCtx`,
  10949. [UNREF]: `unref`,
  10950. [IS_REF]: `isRef`,
  10951. [WITH_MEMO]: `withMemo`,
  10952. [IS_MEMO_SAME]: `isMemoSame`
  10953. };
  10954. function registerRuntimeHelpers(helpers) {
  10955. Object.getOwnPropertySymbols(helpers).forEach(s => {
  10956. helperNameMap[s] = helpers[s];
  10957. });
  10958. }
  10959. // AST Utilities ---------------------------------------------------------------
  10960. // Some expressions, e.g. sequence and conditional expressions, are never
  10961. // associated with template nodes, so their source locations are just a stub.
  10962. // Container types like CompoundExpression also don't need a real location.
  10963. const locStub = {
  10964. source: '',
  10965. start: { line: 1, column: 1, offset: 0 },
  10966. end: { line: 1, column: 1, offset: 0 }
  10967. };
  10968. function createRoot(children, loc = locStub) {
  10969. return {
  10970. type: 0 /* ROOT */,
  10971. children,
  10972. helpers: [],
  10973. components: [],
  10974. directives: [],
  10975. hoists: [],
  10976. imports: [],
  10977. cached: 0,
  10978. temps: 0,
  10979. codegenNode: undefined,
  10980. loc
  10981. };
  10982. }
  10983. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent = false, loc = locStub) {
  10984. if (context) {
  10985. if (isBlock) {
  10986. context.helper(OPEN_BLOCK);
  10987. context.helper(getVNodeBlockHelper(context.inSSR, isComponent));
  10988. }
  10989. else {
  10990. context.helper(getVNodeHelper(context.inSSR, isComponent));
  10991. }
  10992. if (directives) {
  10993. context.helper(WITH_DIRECTIVES);
  10994. }
  10995. }
  10996. return {
  10997. type: 13 /* VNODE_CALL */,
  10998. tag,
  10999. props,
  11000. children,
  11001. patchFlag,
  11002. dynamicProps,
  11003. directives,
  11004. isBlock,
  11005. disableTracking,
  11006. isComponent,
  11007. loc
  11008. };
  11009. }
  11010. function createArrayExpression(elements, loc = locStub) {
  11011. return {
  11012. type: 17 /* JS_ARRAY_EXPRESSION */,
  11013. loc,
  11014. elements
  11015. };
  11016. }
  11017. function createObjectExpression(properties, loc = locStub) {
  11018. return {
  11019. type: 15 /* JS_OBJECT_EXPRESSION */,
  11020. loc,
  11021. properties
  11022. };
  11023. }
  11024. function createObjectProperty(key, value) {
  11025. return {
  11026. type: 16 /* JS_PROPERTY */,
  11027. loc: locStub,
  11028. key: isString(key) ? createSimpleExpression(key, true) : key,
  11029. value
  11030. };
  11031. }
  11032. function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
  11033. return {
  11034. type: 4 /* SIMPLE_EXPRESSION */,
  11035. loc,
  11036. content,
  11037. isStatic,
  11038. constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
  11039. };
  11040. }
  11041. function createCompoundExpression(children, loc = locStub) {
  11042. return {
  11043. type: 8 /* COMPOUND_EXPRESSION */,
  11044. loc,
  11045. children
  11046. };
  11047. }
  11048. function createCallExpression(callee, args = [], loc = locStub) {
  11049. return {
  11050. type: 14 /* JS_CALL_EXPRESSION */,
  11051. loc,
  11052. callee,
  11053. arguments: args
  11054. };
  11055. }
  11056. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  11057. return {
  11058. type: 18 /* JS_FUNCTION_EXPRESSION */,
  11059. params,
  11060. returns,
  11061. newline,
  11062. isSlot,
  11063. loc
  11064. };
  11065. }
  11066. function createConditionalExpression(test, consequent, alternate, newline = true) {
  11067. return {
  11068. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  11069. test,
  11070. consequent,
  11071. alternate,
  11072. newline,
  11073. loc: locStub
  11074. };
  11075. }
  11076. function createCacheExpression(index, value, isVNode = false) {
  11077. return {
  11078. type: 20 /* JS_CACHE_EXPRESSION */,
  11079. index,
  11080. value,
  11081. isVNode,
  11082. loc: locStub
  11083. };
  11084. }
  11085. function createBlockStatement(body) {
  11086. return {
  11087. type: 21 /* JS_BLOCK_STATEMENT */,
  11088. body,
  11089. loc: locStub
  11090. };
  11091. }
  11092. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  11093. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  11094. function isCoreComponent(tag) {
  11095. if (isBuiltInType(tag, 'Teleport')) {
  11096. return TELEPORT;
  11097. }
  11098. else if (isBuiltInType(tag, 'Suspense')) {
  11099. return SUSPENSE;
  11100. }
  11101. else if (isBuiltInType(tag, 'KeepAlive')) {
  11102. return KEEP_ALIVE;
  11103. }
  11104. else if (isBuiltInType(tag, 'BaseTransition')) {
  11105. return BASE_TRANSITION;
  11106. }
  11107. }
  11108. const nonIdentifierRE = /^\d|[^\$\w]/;
  11109. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  11110. const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
  11111. const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
  11112. const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
  11113. /**
  11114. * Simple lexer to check if an expression is a member expression. This is
  11115. * lax and only checks validity at the root level (i.e. does not validate exps
  11116. * inside square brackets), but it's ok since these are only used on template
  11117. * expressions and false positives are invalid expressions in the first place.
  11118. */
  11119. const isMemberExpressionBrowser = (path) => {
  11120. // remove whitespaces around . or [ first
  11121. path = path.trim().replace(whitespaceRE, s => s.trim());
  11122. let state = 0 /* inMemberExp */;
  11123. let stateStack = [];
  11124. let currentOpenBracketCount = 0;
  11125. let currentOpenParensCount = 0;
  11126. let currentStringType = null;
  11127. for (let i = 0; i < path.length; i++) {
  11128. const char = path.charAt(i);
  11129. switch (state) {
  11130. case 0 /* inMemberExp */:
  11131. if (char === '[') {
  11132. stateStack.push(state);
  11133. state = 1 /* inBrackets */;
  11134. currentOpenBracketCount++;
  11135. }
  11136. else if (char === '(') {
  11137. stateStack.push(state);
  11138. state = 2 /* inParens */;
  11139. currentOpenParensCount++;
  11140. }
  11141. else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
  11142. return false;
  11143. }
  11144. break;
  11145. case 1 /* inBrackets */:
  11146. if (char === `'` || char === `"` || char === '`') {
  11147. stateStack.push(state);
  11148. state = 3 /* inString */;
  11149. currentStringType = char;
  11150. }
  11151. else if (char === `[`) {
  11152. currentOpenBracketCount++;
  11153. }
  11154. else if (char === `]`) {
  11155. if (!--currentOpenBracketCount) {
  11156. state = stateStack.pop();
  11157. }
  11158. }
  11159. break;
  11160. case 2 /* inParens */:
  11161. if (char === `'` || char === `"` || char === '`') {
  11162. stateStack.push(state);
  11163. state = 3 /* inString */;
  11164. currentStringType = char;
  11165. }
  11166. else if (char === `(`) {
  11167. currentOpenParensCount++;
  11168. }
  11169. else if (char === `)`) {
  11170. // if the exp ends as a call then it should not be considered valid
  11171. if (i === path.length - 1) {
  11172. return false;
  11173. }
  11174. if (!--currentOpenParensCount) {
  11175. state = stateStack.pop();
  11176. }
  11177. }
  11178. break;
  11179. case 3 /* inString */:
  11180. if (char === currentStringType) {
  11181. state = stateStack.pop();
  11182. currentStringType = null;
  11183. }
  11184. break;
  11185. }
  11186. }
  11187. return !currentOpenBracketCount && !currentOpenParensCount;
  11188. };
  11189. const isMemberExpression = isMemberExpressionBrowser
  11190. ;
  11191. function getInnerRange(loc, offset, length) {
  11192. const source = loc.source.slice(offset, offset + length);
  11193. const newLoc = {
  11194. source,
  11195. start: advancePositionWithClone(loc.start, loc.source, offset),
  11196. end: loc.end
  11197. };
  11198. if (length != null) {
  11199. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  11200. }
  11201. return newLoc;
  11202. }
  11203. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  11204. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  11205. }
  11206. // advance by mutation without cloning (for performance reasons), since this
  11207. // gets called a lot in the parser
  11208. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  11209. let linesCount = 0;
  11210. let lastNewLinePos = -1;
  11211. for (let i = 0; i < numberOfCharacters; i++) {
  11212. if (source.charCodeAt(i) === 10 /* newline char code */) {
  11213. linesCount++;
  11214. lastNewLinePos = i;
  11215. }
  11216. }
  11217. pos.offset += numberOfCharacters;
  11218. pos.line += linesCount;
  11219. pos.column =
  11220. lastNewLinePos === -1
  11221. ? pos.column + numberOfCharacters
  11222. : numberOfCharacters - lastNewLinePos;
  11223. return pos;
  11224. }
  11225. function assert(condition, msg) {
  11226. /* istanbul ignore if */
  11227. if (!condition) {
  11228. throw new Error(msg || `unexpected compiler condition`);
  11229. }
  11230. }
  11231. function findDir(node, name, allowEmpty = false) {
  11232. for (let i = 0; i < node.props.length; i++) {
  11233. const p = node.props[i];
  11234. if (p.type === 7 /* DIRECTIVE */ &&
  11235. (allowEmpty || p.exp) &&
  11236. (isString(name) ? p.name === name : name.test(p.name))) {
  11237. return p;
  11238. }
  11239. }
  11240. }
  11241. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  11242. for (let i = 0; i < node.props.length; i++) {
  11243. const p = node.props[i];
  11244. if (p.type === 6 /* ATTRIBUTE */) {
  11245. if (dynamicOnly)
  11246. continue;
  11247. if (p.name === name && (p.value || allowEmpty)) {
  11248. return p;
  11249. }
  11250. }
  11251. else if (p.name === 'bind' &&
  11252. (p.exp || allowEmpty) &&
  11253. isStaticArgOf(p.arg, name)) {
  11254. return p;
  11255. }
  11256. }
  11257. }
  11258. function isStaticArgOf(arg, name) {
  11259. return !!(arg && isStaticExp(arg) && arg.content === name);
  11260. }
  11261. function hasDynamicKeyVBind(node) {
  11262. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  11263. p.name === 'bind' &&
  11264. (!p.arg || // v-bind="obj"
  11265. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  11266. !p.arg.isStatic) // v-bind:[foo]
  11267. );
  11268. }
  11269. function isText(node) {
  11270. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  11271. }
  11272. function isVSlot(p) {
  11273. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  11274. }
  11275. function isTemplateNode(node) {
  11276. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  11277. }
  11278. function isSlotOutlet(node) {
  11279. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  11280. }
  11281. function getVNodeHelper(ssr, isComponent) {
  11282. return ssr || isComponent ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
  11283. }
  11284. function getVNodeBlockHelper(ssr, isComponent) {
  11285. return ssr || isComponent ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
  11286. }
  11287. const propsHelperSet = new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
  11288. function getUnnormalizedProps(props, callPath = []) {
  11289. if (props &&
  11290. !isString(props) &&
  11291. props.type === 14 /* JS_CALL_EXPRESSION */) {
  11292. const callee = props.callee;
  11293. if (!isString(callee) && propsHelperSet.has(callee)) {
  11294. return getUnnormalizedProps(props.arguments[0], callPath.concat(props));
  11295. }
  11296. }
  11297. return [props, callPath];
  11298. }
  11299. function injectProp(node, prop, context) {
  11300. let propsWithInjection;
  11301. /**
  11302. * 1. mergeProps(...)
  11303. * 2. toHandlers(...)
  11304. * 3. normalizeProps(...)
  11305. * 4. normalizeProps(guardReactiveProps(...))
  11306. *
  11307. * we need to get the real props before normalization
  11308. */
  11309. let props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  11310. let callPath = [];
  11311. let parentCall;
  11312. if (props &&
  11313. !isString(props) &&
  11314. props.type === 14 /* JS_CALL_EXPRESSION */) {
  11315. const ret = getUnnormalizedProps(props);
  11316. props = ret[0];
  11317. callPath = ret[1];
  11318. parentCall = callPath[callPath.length - 1];
  11319. }
  11320. if (props == null || isString(props)) {
  11321. propsWithInjection = createObjectExpression([prop]);
  11322. }
  11323. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  11324. // merged props... add ours
  11325. // only inject key to object literal if it's the first argument so that
  11326. // if doesn't override user provided keys
  11327. const first = props.arguments[0];
  11328. if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  11329. first.properties.unshift(prop);
  11330. }
  11331. else {
  11332. if (props.callee === TO_HANDLERS) {
  11333. // #2366
  11334. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  11335. createObjectExpression([prop]),
  11336. props
  11337. ]);
  11338. }
  11339. else {
  11340. props.arguments.unshift(createObjectExpression([prop]));
  11341. }
  11342. }
  11343. !propsWithInjection && (propsWithInjection = props);
  11344. }
  11345. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  11346. let alreadyExists = false;
  11347. // check existing key to avoid overriding user provided keys
  11348. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  11349. const propKeyName = prop.key.content;
  11350. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  11351. p.key.content === propKeyName);
  11352. }
  11353. if (!alreadyExists) {
  11354. props.properties.unshift(prop);
  11355. }
  11356. propsWithInjection = props;
  11357. }
  11358. else {
  11359. // single v-bind with expression, return a merged replacement
  11360. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  11361. createObjectExpression([prop]),
  11362. props
  11363. ]);
  11364. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(props))`,
  11365. // it will be rewritten as `normalizeProps(mergeProps({ key: 0 }, props))`,
  11366. // the `guardReactiveProps` will no longer be needed
  11367. if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
  11368. parentCall = callPath[callPath.length - 2];
  11369. }
  11370. }
  11371. if (node.type === 13 /* VNODE_CALL */) {
  11372. if (parentCall) {
  11373. parentCall.arguments[0] = propsWithInjection;
  11374. }
  11375. else {
  11376. node.props = propsWithInjection;
  11377. }
  11378. }
  11379. else {
  11380. if (parentCall) {
  11381. parentCall.arguments[0] = propsWithInjection;
  11382. }
  11383. else {
  11384. node.arguments[2] = propsWithInjection;
  11385. }
  11386. }
  11387. }
  11388. function toValidAssetId(name, type) {
  11389. // see issue#4422, we need adding identifier on validAssetId if variable `name` has specific character
  11390. return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
  11391. return searchValue === '-' ? '_' : name.charCodeAt(replaceValue).toString();
  11392. })}`;
  11393. }
  11394. function getMemoedVNodeCall(node) {
  11395. if (node.type === 14 /* JS_CALL_EXPRESSION */ && node.callee === WITH_MEMO) {
  11396. return node.arguments[1].returns;
  11397. }
  11398. else {
  11399. return node;
  11400. }
  11401. }
  11402. function makeBlock(node, { helper, removeHelper, inSSR }) {
  11403. if (!node.isBlock) {
  11404. node.isBlock = true;
  11405. removeHelper(getVNodeHelper(inSSR, node.isComponent));
  11406. helper(OPEN_BLOCK);
  11407. helper(getVNodeBlockHelper(inSSR, node.isComponent));
  11408. }
  11409. }
  11410. const deprecationData = {
  11411. ["COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */]: {
  11412. message: `Platform-native elements with "is" prop will no longer be ` +
  11413. `treated as components in Vue 3 unless the "is" value is explicitly ` +
  11414. `prefixed with "vue:".`,
  11415. link: `https://v3.vuejs.org/guide/migration/custom-elements-interop.html`
  11416. },
  11417. ["COMPILER_V_BIND_SYNC" /* COMPILER_V_BIND_SYNC */]: {
  11418. message: key => `.sync modifier for v-bind has been removed. Use v-model with ` +
  11419. `argument instead. \`v-bind:${key}.sync\` should be changed to ` +
  11420. `\`v-model:${key}\`.`,
  11421. link: `https://v3.vuejs.org/guide/migration/v-model.html`
  11422. },
  11423. ["COMPILER_V_BIND_PROP" /* COMPILER_V_BIND_PROP */]: {
  11424. message: `.prop modifier for v-bind has been removed and no longer necessary. ` +
  11425. `Vue 3 will automatically set a binding as DOM property when appropriate.`
  11426. },
  11427. ["COMPILER_V_BIND_OBJECT_ORDER" /* COMPILER_V_BIND_OBJECT_ORDER */]: {
  11428. message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript ` +
  11429. `object spread: it will now overwrite an existing non-mergeable attribute ` +
  11430. `that appears before v-bind in the case of conflict. ` +
  11431. `To retain 2.x behavior, move v-bind to make it the first attribute. ` +
  11432. `You can also suppress this warning if the usage is intended.`,
  11433. link: `https://v3.vuejs.org/guide/migration/v-bind.html`
  11434. },
  11435. ["COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */]: {
  11436. message: `.native modifier for v-on has been removed as is no longer necessary.`,
  11437. link: `https://v3.vuejs.org/guide/migration/v-on-native-modifier-removed.html`
  11438. },
  11439. ["COMPILER_V_IF_V_FOR_PRECEDENCE" /* COMPILER_V_IF_V_FOR_PRECEDENCE */]: {
  11440. message: `v-if / v-for precedence when used on the same element has changed ` +
  11441. `in Vue 3: v-if now takes higher precedence and will no longer have ` +
  11442. `access to v-for scope variables. It is best to avoid the ambiguity ` +
  11443. `with <template> tags or use a computed property that filters v-for ` +
  11444. `data source.`,
  11445. link: `https://v3.vuejs.org/guide/migration/v-if-v-for.html`
  11446. },
  11447. ["COMPILER_NATIVE_TEMPLATE" /* COMPILER_NATIVE_TEMPLATE */]: {
  11448. message: `<template> with no special directives will render as a native template ` +
  11449. `element instead of its inner content in Vue 3.`
  11450. },
  11451. ["COMPILER_INLINE_TEMPLATE" /* COMPILER_INLINE_TEMPLATE */]: {
  11452. message: `"inline-template" has been removed in Vue 3.`,
  11453. link: `https://v3.vuejs.org/guide/migration/inline-template-attribute.html`
  11454. },
  11455. ["COMPILER_FILTER" /* COMPILER_FILTERS */]: {
  11456. message: `filters have been removed in Vue 3. ` +
  11457. `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
  11458. `Use method calls or computed properties instead.`,
  11459. link: `https://v3.vuejs.org/guide/migration/filters.html`
  11460. }
  11461. };
  11462. function getCompatValue(key, context) {
  11463. const config = context.options
  11464. ? context.options.compatConfig
  11465. : context.compatConfig;
  11466. const value = config && config[key];
  11467. if (key === 'MODE') {
  11468. return value || 3; // compiler defaults to v3 behavior
  11469. }
  11470. else {
  11471. return value;
  11472. }
  11473. }
  11474. function isCompatEnabled(key, context) {
  11475. const mode = getCompatValue('MODE', context);
  11476. const value = getCompatValue(key, context);
  11477. // in v3 mode, only enable if explicitly set to true
  11478. // otherwise enable for any non-false value
  11479. return mode === 3 ? value === true : value !== false;
  11480. }
  11481. function checkCompatEnabled(key, context, loc, ...args) {
  11482. const enabled = isCompatEnabled(key, context);
  11483. if (enabled) {
  11484. warnDeprecation(key, context, loc, ...args);
  11485. }
  11486. return enabled;
  11487. }
  11488. function warnDeprecation(key, context, loc, ...args) {
  11489. const val = getCompatValue(key, context);
  11490. if (val === 'suppress-warning') {
  11491. return;
  11492. }
  11493. const { message, link } = deprecationData[key];
  11494. const msg = `(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`;
  11495. const err = new SyntaxError(msg);
  11496. err.code = key;
  11497. if (loc)
  11498. err.loc = loc;
  11499. context.onWarn(err);
  11500. }
  11501. // The default decoder only provides escapes for characters reserved as part of
  11502. // the template syntax, and is only used if the custom renderer did not provide
  11503. // a platform-specific decoder.
  11504. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  11505. const decodeMap = {
  11506. gt: '>',
  11507. lt: '<',
  11508. amp: '&',
  11509. apos: "'",
  11510. quot: '"'
  11511. };
  11512. const defaultParserOptions = {
  11513. delimiters: [`{{`, `}}`],
  11514. getNamespace: () => 0 /* HTML */,
  11515. getTextMode: () => 0 /* DATA */,
  11516. isVoidTag: NO,
  11517. isPreTag: NO,
  11518. isCustomElement: NO,
  11519. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  11520. onError: defaultOnError,
  11521. onWarn: defaultOnWarn,
  11522. comments: true
  11523. };
  11524. function baseParse(content, options = {}) {
  11525. const context = createParserContext(content, options);
  11526. const start = getCursor(context);
  11527. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  11528. }
  11529. function createParserContext(content, rawOptions) {
  11530. const options = extend({}, defaultParserOptions);
  11531. let key;
  11532. for (key in rawOptions) {
  11533. // @ts-ignore
  11534. options[key] =
  11535. rawOptions[key] === undefined
  11536. ? defaultParserOptions[key]
  11537. : rawOptions[key];
  11538. }
  11539. return {
  11540. options,
  11541. column: 1,
  11542. line: 1,
  11543. offset: 0,
  11544. originalSource: content,
  11545. source: content,
  11546. inPre: false,
  11547. inVPre: false,
  11548. onWarn: options.onWarn
  11549. };
  11550. }
  11551. function parseChildren(context, mode, ancestors) {
  11552. const parent = last(ancestors);
  11553. const ns = parent ? parent.ns : 0 /* HTML */;
  11554. const nodes = [];
  11555. while (!isEnd(context, mode, ancestors)) {
  11556. const s = context.source;
  11557. let node = undefined;
  11558. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  11559. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  11560. // '{{'
  11561. node = parseInterpolation(context, mode);
  11562. }
  11563. else if (mode === 0 /* DATA */ && s[0] === '<') {
  11564. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  11565. if (s.length === 1) {
  11566. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  11567. }
  11568. else if (s[1] === '!') {
  11569. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  11570. if (startsWith(s, '<!--')) {
  11571. node = parseComment(context);
  11572. }
  11573. else if (startsWith(s, '<!DOCTYPE')) {
  11574. // Ignore DOCTYPE by a limitation.
  11575. node = parseBogusComment(context);
  11576. }
  11577. else if (startsWith(s, '<![CDATA[')) {
  11578. if (ns !== 0 /* HTML */) {
  11579. node = parseCDATA(context, ancestors);
  11580. }
  11581. else {
  11582. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  11583. node = parseBogusComment(context);
  11584. }
  11585. }
  11586. else {
  11587. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  11588. node = parseBogusComment(context);
  11589. }
  11590. }
  11591. else if (s[1] === '/') {
  11592. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  11593. if (s.length === 2) {
  11594. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  11595. }
  11596. else if (s[2] === '>') {
  11597. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  11598. advanceBy(context, 3);
  11599. continue;
  11600. }
  11601. else if (/[a-z]/i.test(s[2])) {
  11602. emitError(context, 23 /* X_INVALID_END_TAG */);
  11603. parseTag(context, 1 /* End */, parent);
  11604. continue;
  11605. }
  11606. else {
  11607. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  11608. node = parseBogusComment(context);
  11609. }
  11610. }
  11611. else if (/[a-z]/i.test(s[1])) {
  11612. node = parseElement(context, ancestors);
  11613. }
  11614. else if (s[1] === '?') {
  11615. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  11616. node = parseBogusComment(context);
  11617. }
  11618. else {
  11619. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  11620. }
  11621. }
  11622. }
  11623. if (!node) {
  11624. node = parseText(context, mode);
  11625. }
  11626. if (isArray(node)) {
  11627. for (let i = 0; i < node.length; i++) {
  11628. pushNode(nodes, node[i]);
  11629. }
  11630. }
  11631. else {
  11632. pushNode(nodes, node);
  11633. }
  11634. }
  11635. // Whitespace handling strategy like v2
  11636. let removedWhitespace = false;
  11637. if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
  11638. const shouldCondense = context.options.whitespace !== 'preserve';
  11639. for (let i = 0; i < nodes.length; i++) {
  11640. const node = nodes[i];
  11641. if (!context.inPre && node.type === 2 /* TEXT */) {
  11642. if (!/[^\t\r\n\f ]/.test(node.content)) {
  11643. const prev = nodes[i - 1];
  11644. const next = nodes[i + 1];
  11645. // Remove if:
  11646. // - the whitespace is the first or last node, or:
  11647. // - (condense mode) the whitespace is adjacent to a comment, or:
  11648. // - (condense mode) the whitespace is between two elements AND contains newline
  11649. if (!prev ||
  11650. !next ||
  11651. (shouldCondense &&
  11652. (prev.type === 3 /* COMMENT */ ||
  11653. next.type === 3 /* COMMENT */ ||
  11654. (prev.type === 1 /* ELEMENT */ &&
  11655. next.type === 1 /* ELEMENT */ &&
  11656. /[\r\n]/.test(node.content))))) {
  11657. removedWhitespace = true;
  11658. nodes[i] = null;
  11659. }
  11660. else {
  11661. // Otherwise, the whitespace is condensed into a single space
  11662. node.content = ' ';
  11663. }
  11664. }
  11665. else if (shouldCondense) {
  11666. // in condense mode, consecutive whitespaces in text are condensed
  11667. // down to a single space.
  11668. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  11669. }
  11670. }
  11671. // Remove comment nodes if desired by configuration.
  11672. else if (node.type === 3 /* COMMENT */ && !context.options.comments) {
  11673. removedWhitespace = true;
  11674. nodes[i] = null;
  11675. }
  11676. }
  11677. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  11678. // remove leading newline per html spec
  11679. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  11680. const first = nodes[0];
  11681. if (first && first.type === 2 /* TEXT */) {
  11682. first.content = first.content.replace(/^\r?\n/, '');
  11683. }
  11684. }
  11685. }
  11686. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  11687. }
  11688. function pushNode(nodes, node) {
  11689. if (node.type === 2 /* TEXT */) {
  11690. const prev = last(nodes);
  11691. // Merge if both this and the previous node are text and those are
  11692. // consecutive. This happens for cases like "a < b".
  11693. if (prev &&
  11694. prev.type === 2 /* TEXT */ &&
  11695. prev.loc.end.offset === node.loc.start.offset) {
  11696. prev.content += node.content;
  11697. prev.loc.end = node.loc.end;
  11698. prev.loc.source += node.loc.source;
  11699. return;
  11700. }
  11701. }
  11702. nodes.push(node);
  11703. }
  11704. function parseCDATA(context, ancestors) {
  11705. advanceBy(context, 9);
  11706. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  11707. if (context.source.length === 0) {
  11708. emitError(context, 6 /* EOF_IN_CDATA */);
  11709. }
  11710. else {
  11711. advanceBy(context, 3);
  11712. }
  11713. return nodes;
  11714. }
  11715. function parseComment(context) {
  11716. const start = getCursor(context);
  11717. let content;
  11718. // Regular comment.
  11719. const match = /--(\!)?>/.exec(context.source);
  11720. if (!match) {
  11721. content = context.source.slice(4);
  11722. advanceBy(context, context.source.length);
  11723. emitError(context, 7 /* EOF_IN_COMMENT */);
  11724. }
  11725. else {
  11726. if (match.index <= 3) {
  11727. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  11728. }
  11729. if (match[1]) {
  11730. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  11731. }
  11732. content = context.source.slice(4, match.index);
  11733. // Advancing with reporting nested comments.
  11734. const s = context.source.slice(0, match.index);
  11735. let prevIndex = 1, nestedIndex = 0;
  11736. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  11737. advanceBy(context, nestedIndex - prevIndex + 1);
  11738. if (nestedIndex + 4 < s.length) {
  11739. emitError(context, 16 /* NESTED_COMMENT */);
  11740. }
  11741. prevIndex = nestedIndex + 1;
  11742. }
  11743. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  11744. }
  11745. return {
  11746. type: 3 /* COMMENT */,
  11747. content,
  11748. loc: getSelection(context, start)
  11749. };
  11750. }
  11751. function parseBogusComment(context) {
  11752. const start = getCursor(context);
  11753. const contentStart = context.source[1] === '?' ? 1 : 2;
  11754. let content;
  11755. const closeIndex = context.source.indexOf('>');
  11756. if (closeIndex === -1) {
  11757. content = context.source.slice(contentStart);
  11758. advanceBy(context, context.source.length);
  11759. }
  11760. else {
  11761. content = context.source.slice(contentStart, closeIndex);
  11762. advanceBy(context, closeIndex + 1);
  11763. }
  11764. return {
  11765. type: 3 /* COMMENT */,
  11766. content,
  11767. loc: getSelection(context, start)
  11768. };
  11769. }
  11770. function parseElement(context, ancestors) {
  11771. // Start tag.
  11772. const wasInPre = context.inPre;
  11773. const wasInVPre = context.inVPre;
  11774. const parent = last(ancestors);
  11775. const element = parseTag(context, 0 /* Start */, parent);
  11776. const isPreBoundary = context.inPre && !wasInPre;
  11777. const isVPreBoundary = context.inVPre && !wasInVPre;
  11778. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  11779. // #4030 self-closing <pre> tag
  11780. if (isPreBoundary) {
  11781. context.inPre = false;
  11782. }
  11783. if (isVPreBoundary) {
  11784. context.inVPre = false;
  11785. }
  11786. return element;
  11787. }
  11788. // Children.
  11789. ancestors.push(element);
  11790. const mode = context.options.getTextMode(element, parent);
  11791. const children = parseChildren(context, mode, ancestors);
  11792. ancestors.pop();
  11793. element.children = children;
  11794. // End tag.
  11795. if (startsWithEndTagOpen(context.source, element.tag)) {
  11796. parseTag(context, 1 /* End */, parent);
  11797. }
  11798. else {
  11799. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  11800. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  11801. const first = children[0];
  11802. if (first && startsWith(first.loc.source, '<!--')) {
  11803. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  11804. }
  11805. }
  11806. }
  11807. element.loc = getSelection(context, element.loc.start);
  11808. if (isPreBoundary) {
  11809. context.inPre = false;
  11810. }
  11811. if (isVPreBoundary) {
  11812. context.inVPre = false;
  11813. }
  11814. return element;
  11815. }
  11816. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  11817. function parseTag(context, type, parent) {
  11818. // Tag open.
  11819. const start = getCursor(context);
  11820. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  11821. const tag = match[1];
  11822. const ns = context.options.getNamespace(tag, parent);
  11823. advanceBy(context, match[0].length);
  11824. advanceSpaces(context);
  11825. // save current state in case we need to re-parse attributes with v-pre
  11826. const cursor = getCursor(context);
  11827. const currentSource = context.source;
  11828. // check <pre> tag
  11829. if (context.options.isPreTag(tag)) {
  11830. context.inPre = true;
  11831. }
  11832. // Attributes.
  11833. let props = parseAttributes(context, type);
  11834. // check v-pre
  11835. if (type === 0 /* Start */ &&
  11836. !context.inVPre &&
  11837. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  11838. context.inVPre = true;
  11839. // reset context
  11840. extend(context, cursor);
  11841. context.source = currentSource;
  11842. // re-parse attrs and filter out v-pre itself
  11843. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  11844. }
  11845. // Tag close.
  11846. let isSelfClosing = false;
  11847. if (context.source.length === 0) {
  11848. emitError(context, 9 /* EOF_IN_TAG */);
  11849. }
  11850. else {
  11851. isSelfClosing = startsWith(context.source, '/>');
  11852. if (type === 1 /* End */ && isSelfClosing) {
  11853. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  11854. }
  11855. advanceBy(context, isSelfClosing ? 2 : 1);
  11856. }
  11857. if (type === 1 /* End */) {
  11858. return;
  11859. }
  11860. let tagType = 0 /* ELEMENT */;
  11861. if (!context.inVPre) {
  11862. if (tag === 'slot') {
  11863. tagType = 2 /* SLOT */;
  11864. }
  11865. else if (tag === 'template') {
  11866. if (props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
  11867. tagType = 3 /* TEMPLATE */;
  11868. }
  11869. }
  11870. else if (isComponent(tag, props, context)) {
  11871. tagType = 1 /* COMPONENT */;
  11872. }
  11873. }
  11874. return {
  11875. type: 1 /* ELEMENT */,
  11876. ns,
  11877. tag,
  11878. tagType,
  11879. props,
  11880. isSelfClosing,
  11881. children: [],
  11882. loc: getSelection(context, start),
  11883. codegenNode: undefined // to be created during transform phase
  11884. };
  11885. }
  11886. function isComponent(tag, props, context) {
  11887. const options = context.options;
  11888. if (options.isCustomElement(tag)) {
  11889. return false;
  11890. }
  11891. if (tag === 'component' ||
  11892. /^[A-Z]/.test(tag) ||
  11893. isCoreComponent(tag) ||
  11894. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  11895. (options.isNativeTag && !options.isNativeTag(tag))) {
  11896. return true;
  11897. }
  11898. // at this point the tag should be a native tag, but check for potential "is"
  11899. // casting
  11900. for (let i = 0; i < props.length; i++) {
  11901. const p = props[i];
  11902. if (p.type === 6 /* ATTRIBUTE */) {
  11903. if (p.name === 'is' && p.value) {
  11904. if (p.value.content.startsWith('vue:')) {
  11905. return true;
  11906. }
  11907. }
  11908. }
  11909. else {
  11910. // directive
  11911. // v-is (TODO Deprecate)
  11912. if (p.name === 'is') {
  11913. return true;
  11914. }
  11915. else if (
  11916. // :is on plain element - only treat as component in compat mode
  11917. p.name === 'bind' &&
  11918. isStaticArgOf(p.arg, 'is') &&
  11919. false &&
  11920. checkCompatEnabled("COMPILER_IS_ON_ELEMENT" /* COMPILER_IS_ON_ELEMENT */, context, p.loc)) {
  11921. return true;
  11922. }
  11923. }
  11924. }
  11925. }
  11926. function parseAttributes(context, type) {
  11927. const props = [];
  11928. const attributeNames = new Set();
  11929. while (context.source.length > 0 &&
  11930. !startsWith(context.source, '>') &&
  11931. !startsWith(context.source, '/>')) {
  11932. if (startsWith(context.source, '/')) {
  11933. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  11934. advanceBy(context, 1);
  11935. advanceSpaces(context);
  11936. continue;
  11937. }
  11938. if (type === 1 /* End */) {
  11939. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  11940. }
  11941. const attr = parseAttribute(context, attributeNames);
  11942. // Trim whitespace between class
  11943. // https://github.com/vuejs/vue-next/issues/4251
  11944. if (attr.type === 6 /* ATTRIBUTE */ &&
  11945. attr.value &&
  11946. attr.name === 'class') {
  11947. attr.value.content = attr.value.content.replace(/\s+/g, ' ').trim();
  11948. }
  11949. if (type === 0 /* Start */) {
  11950. props.push(attr);
  11951. }
  11952. if (/^[^\t\r\n\f />]/.test(context.source)) {
  11953. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  11954. }
  11955. advanceSpaces(context);
  11956. }
  11957. return props;
  11958. }
  11959. function parseAttribute(context, nameSet) {
  11960. // Name.
  11961. const start = getCursor(context);
  11962. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  11963. const name = match[0];
  11964. if (nameSet.has(name)) {
  11965. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  11966. }
  11967. nameSet.add(name);
  11968. if (name[0] === '=') {
  11969. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  11970. }
  11971. {
  11972. const pattern = /["'<]/g;
  11973. let m;
  11974. while ((m = pattern.exec(name))) {
  11975. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  11976. }
  11977. }
  11978. advanceBy(context, name.length);
  11979. // Value
  11980. let value = undefined;
  11981. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  11982. advanceSpaces(context);
  11983. advanceBy(context, 1);
  11984. advanceSpaces(context);
  11985. value = parseAttributeValue(context);
  11986. if (!value) {
  11987. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  11988. }
  11989. }
  11990. const loc = getSelection(context, start);
  11991. if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
  11992. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  11993. let isPropShorthand = startsWith(name, '.');
  11994. let dirName = match[1] ||
  11995. (isPropShorthand || startsWith(name, ':')
  11996. ? 'bind'
  11997. : startsWith(name, '@')
  11998. ? 'on'
  11999. : 'slot');
  12000. let arg;
  12001. if (match[2]) {
  12002. const isSlot = dirName === 'slot';
  12003. const startOffset = name.lastIndexOf(match[2]);
  12004. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  12005. let content = match[2];
  12006. let isStatic = true;
  12007. if (content.startsWith('[')) {
  12008. isStatic = false;
  12009. if (!content.endsWith(']')) {
  12010. emitError(context, 27 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  12011. content = content.slice(1);
  12012. }
  12013. else {
  12014. content = content.slice(1, content.length - 1);
  12015. }
  12016. }
  12017. else if (isSlot) {
  12018. // #1241 special case for v-slot: vuetify relies extensively on slot
  12019. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  12020. // supports such usage so we are keeping it consistent with 2.x.
  12021. content += match[3] || '';
  12022. }
  12023. arg = {
  12024. type: 4 /* SIMPLE_EXPRESSION */,
  12025. content,
  12026. isStatic,
  12027. constType: isStatic
  12028. ? 3 /* CAN_STRINGIFY */
  12029. : 0 /* NOT_CONSTANT */,
  12030. loc
  12031. };
  12032. }
  12033. if (value && value.isQuoted) {
  12034. const valueLoc = value.loc;
  12035. valueLoc.start.offset++;
  12036. valueLoc.start.column++;
  12037. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  12038. valueLoc.source = valueLoc.source.slice(1, -1);
  12039. }
  12040. const modifiers = match[3] ? match[3].slice(1).split('.') : [];
  12041. if (isPropShorthand)
  12042. modifiers.push('prop');
  12043. return {
  12044. type: 7 /* DIRECTIVE */,
  12045. name: dirName,
  12046. exp: value && {
  12047. type: 4 /* SIMPLE_EXPRESSION */,
  12048. content: value.content,
  12049. isStatic: false,
  12050. // Treat as non-constant by default. This can be potentially set to
  12051. // other values by `transformExpression` to make it eligible for hoisting.
  12052. constType: 0 /* NOT_CONSTANT */,
  12053. loc: value.loc
  12054. },
  12055. arg,
  12056. modifiers,
  12057. loc
  12058. };
  12059. }
  12060. // missing directive name or illegal directive name
  12061. if (!context.inVPre && startsWith(name, 'v-')) {
  12062. emitError(context, 26 /* X_MISSING_DIRECTIVE_NAME */);
  12063. }
  12064. return {
  12065. type: 6 /* ATTRIBUTE */,
  12066. name,
  12067. value: value && {
  12068. type: 2 /* TEXT */,
  12069. content: value.content,
  12070. loc: value.loc
  12071. },
  12072. loc
  12073. };
  12074. }
  12075. function parseAttributeValue(context) {
  12076. const start = getCursor(context);
  12077. let content;
  12078. const quote = context.source[0];
  12079. const isQuoted = quote === `"` || quote === `'`;
  12080. if (isQuoted) {
  12081. // Quoted value.
  12082. advanceBy(context, 1);
  12083. const endIndex = context.source.indexOf(quote);
  12084. if (endIndex === -1) {
  12085. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  12086. }
  12087. else {
  12088. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  12089. advanceBy(context, 1);
  12090. }
  12091. }
  12092. else {
  12093. // Unquoted
  12094. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  12095. if (!match) {
  12096. return undefined;
  12097. }
  12098. const unexpectedChars = /["'<=`]/g;
  12099. let m;
  12100. while ((m = unexpectedChars.exec(match[0]))) {
  12101. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  12102. }
  12103. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  12104. }
  12105. return { content, isQuoted, loc: getSelection(context, start) };
  12106. }
  12107. function parseInterpolation(context, mode) {
  12108. const [open, close] = context.options.delimiters;
  12109. const closeIndex = context.source.indexOf(close, open.length);
  12110. if (closeIndex === -1) {
  12111. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  12112. return undefined;
  12113. }
  12114. const start = getCursor(context);
  12115. advanceBy(context, open.length);
  12116. const innerStart = getCursor(context);
  12117. const innerEnd = getCursor(context);
  12118. const rawContentLength = closeIndex - open.length;
  12119. const rawContent = context.source.slice(0, rawContentLength);
  12120. const preTrimContent = parseTextData(context, rawContentLength, mode);
  12121. const content = preTrimContent.trim();
  12122. const startOffset = preTrimContent.indexOf(content);
  12123. if (startOffset > 0) {
  12124. advancePositionWithMutation(innerStart, rawContent, startOffset);
  12125. }
  12126. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  12127. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  12128. advanceBy(context, close.length);
  12129. return {
  12130. type: 5 /* INTERPOLATION */,
  12131. content: {
  12132. type: 4 /* SIMPLE_EXPRESSION */,
  12133. isStatic: false,
  12134. // Set `isConstant` to false by default and will decide in transformExpression
  12135. constType: 0 /* NOT_CONSTANT */,
  12136. content,
  12137. loc: getSelection(context, innerStart, innerEnd)
  12138. },
  12139. loc: getSelection(context, start)
  12140. };
  12141. }
  12142. function parseText(context, mode) {
  12143. const endTokens = mode === 3 /* CDATA */ ? [']]>'] : ['<', context.options.delimiters[0]];
  12144. let endIndex = context.source.length;
  12145. for (let i = 0; i < endTokens.length; i++) {
  12146. const index = context.source.indexOf(endTokens[i], 1);
  12147. if (index !== -1 && endIndex > index) {
  12148. endIndex = index;
  12149. }
  12150. }
  12151. const start = getCursor(context);
  12152. const content = parseTextData(context, endIndex, mode);
  12153. return {
  12154. type: 2 /* TEXT */,
  12155. content,
  12156. loc: getSelection(context, start)
  12157. };
  12158. }
  12159. /**
  12160. * Get text data with a given length from the current location.
  12161. * This translates HTML entities in the text data.
  12162. */
  12163. function parseTextData(context, length, mode) {
  12164. const rawText = context.source.slice(0, length);
  12165. advanceBy(context, length);
  12166. if (mode === 2 /* RAWTEXT */ ||
  12167. mode === 3 /* CDATA */ ||
  12168. rawText.indexOf('&') === -1) {
  12169. return rawText;
  12170. }
  12171. else {
  12172. // DATA or RCDATA containing "&"". Entity decoding required.
  12173. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  12174. }
  12175. }
  12176. function getCursor(context) {
  12177. const { column, line, offset } = context;
  12178. return { column, line, offset };
  12179. }
  12180. function getSelection(context, start, end) {
  12181. end = end || getCursor(context);
  12182. return {
  12183. start,
  12184. end,
  12185. source: context.originalSource.slice(start.offset, end.offset)
  12186. };
  12187. }
  12188. function last(xs) {
  12189. return xs[xs.length - 1];
  12190. }
  12191. function startsWith(source, searchString) {
  12192. return source.startsWith(searchString);
  12193. }
  12194. function advanceBy(context, numberOfCharacters) {
  12195. const { source } = context;
  12196. advancePositionWithMutation(context, source, numberOfCharacters);
  12197. context.source = source.slice(numberOfCharacters);
  12198. }
  12199. function advanceSpaces(context) {
  12200. const match = /^[\t\r\n\f ]+/.exec(context.source);
  12201. if (match) {
  12202. advanceBy(context, match[0].length);
  12203. }
  12204. }
  12205. function getNewPosition(context, start, numberOfCharacters) {
  12206. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  12207. }
  12208. function emitError(context, code, offset, loc = getCursor(context)) {
  12209. if (offset) {
  12210. loc.offset += offset;
  12211. loc.column += offset;
  12212. }
  12213. context.options.onError(createCompilerError(code, {
  12214. start: loc,
  12215. end: loc,
  12216. source: ''
  12217. }));
  12218. }
  12219. function isEnd(context, mode, ancestors) {
  12220. const s = context.source;
  12221. switch (mode) {
  12222. case 0 /* DATA */:
  12223. if (startsWith(s, '</')) {
  12224. // TODO: probably bad performance
  12225. for (let i = ancestors.length - 1; i >= 0; --i) {
  12226. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  12227. return true;
  12228. }
  12229. }
  12230. }
  12231. break;
  12232. case 1 /* RCDATA */:
  12233. case 2 /* RAWTEXT */: {
  12234. const parent = last(ancestors);
  12235. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  12236. return true;
  12237. }
  12238. break;
  12239. }
  12240. case 3 /* CDATA */:
  12241. if (startsWith(s, ']]>')) {
  12242. return true;
  12243. }
  12244. break;
  12245. }
  12246. return !s;
  12247. }
  12248. function startsWithEndTagOpen(source, tag) {
  12249. return (startsWith(source, '</') &&
  12250. source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() &&
  12251. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  12252. }
  12253. function hoistStatic(root, context) {
  12254. walk(root, context,
  12255. // Root node is unfortunately non-hoistable due to potential parent
  12256. // fallthrough attributes.
  12257. isSingleElementRoot(root, root.children[0]));
  12258. }
  12259. function isSingleElementRoot(root, child) {
  12260. const { children } = root;
  12261. return (children.length === 1 &&
  12262. child.type === 1 /* ELEMENT */ &&
  12263. !isSlotOutlet(child));
  12264. }
  12265. function walk(node, context, doNotHoistNode = false) {
  12266. const { children } = node;
  12267. const originalCount = children.length;
  12268. let hoistedCount = 0;
  12269. for (let i = 0; i < children.length; i++) {
  12270. const child = children[i];
  12271. // only plain elements & text calls are eligible for hoisting.
  12272. if (child.type === 1 /* ELEMENT */ &&
  12273. child.tagType === 0 /* ELEMENT */) {
  12274. const constantType = doNotHoistNode
  12275. ? 0 /* NOT_CONSTANT */
  12276. : getConstantType(child, context);
  12277. if (constantType > 0 /* NOT_CONSTANT */) {
  12278. if (constantType >= 2 /* CAN_HOIST */) {
  12279. child.codegenNode.patchFlag =
  12280. -1 /* HOISTED */ + (` /* HOISTED */` );
  12281. child.codegenNode = context.hoist(child.codegenNode);
  12282. hoistedCount++;
  12283. continue;
  12284. }
  12285. }
  12286. else {
  12287. // node may contain dynamic children, but its props may be eligible for
  12288. // hoisting.
  12289. const codegenNode = child.codegenNode;
  12290. if (codegenNode.type === 13 /* VNODE_CALL */) {
  12291. const flag = getPatchFlag(codegenNode);
  12292. if ((!flag ||
  12293. flag === 512 /* NEED_PATCH */ ||
  12294. flag === 1 /* TEXT */) &&
  12295. getGeneratedPropsConstantType(child, context) >=
  12296. 2 /* CAN_HOIST */) {
  12297. const props = getNodeProps(child);
  12298. if (props) {
  12299. codegenNode.props = context.hoist(props);
  12300. }
  12301. }
  12302. if (codegenNode.dynamicProps) {
  12303. codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
  12304. }
  12305. }
  12306. }
  12307. }
  12308. else if (child.type === 12 /* TEXT_CALL */ &&
  12309. getConstantType(child.content, context) >= 2 /* CAN_HOIST */) {
  12310. child.codegenNode = context.hoist(child.codegenNode);
  12311. hoistedCount++;
  12312. }
  12313. // walk further
  12314. if (child.type === 1 /* ELEMENT */) {
  12315. const isComponent = child.tagType === 1 /* COMPONENT */;
  12316. if (isComponent) {
  12317. context.scopes.vSlot++;
  12318. }
  12319. walk(child, context);
  12320. if (isComponent) {
  12321. context.scopes.vSlot--;
  12322. }
  12323. }
  12324. else if (child.type === 11 /* FOR */) {
  12325. // Do not hoist v-for single child because it has to be a block
  12326. walk(child, context, child.children.length === 1);
  12327. }
  12328. else if (child.type === 9 /* IF */) {
  12329. for (let i = 0; i < child.branches.length; i++) {
  12330. // Do not hoist v-if single child because it has to be a block
  12331. walk(child.branches[i], context, child.branches[i].children.length === 1);
  12332. }
  12333. }
  12334. }
  12335. if (hoistedCount && context.transformHoist) {
  12336. context.transformHoist(children, context, node);
  12337. }
  12338. // all children were hoisted - the entire children array is hoistable.
  12339. if (hoistedCount &&
  12340. hoistedCount === originalCount &&
  12341. node.type === 1 /* ELEMENT */ &&
  12342. node.tagType === 0 /* ELEMENT */ &&
  12343. node.codegenNode &&
  12344. node.codegenNode.type === 13 /* VNODE_CALL */ &&
  12345. isArray(node.codegenNode.children)) {
  12346. node.codegenNode.children = context.hoist(createArrayExpression(node.codegenNode.children));
  12347. }
  12348. }
  12349. function getConstantType(node, context) {
  12350. const { constantCache } = context;
  12351. switch (node.type) {
  12352. case 1 /* ELEMENT */:
  12353. if (node.tagType !== 0 /* ELEMENT */) {
  12354. return 0 /* NOT_CONSTANT */;
  12355. }
  12356. const cached = constantCache.get(node);
  12357. if (cached !== undefined) {
  12358. return cached;
  12359. }
  12360. const codegenNode = node.codegenNode;
  12361. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  12362. return 0 /* NOT_CONSTANT */;
  12363. }
  12364. if (codegenNode.isBlock &&
  12365. node.tag !== 'svg' &&
  12366. node.tag !== 'foreignObject') {
  12367. return 0 /* NOT_CONSTANT */;
  12368. }
  12369. const flag = getPatchFlag(codegenNode);
  12370. if (!flag) {
  12371. let returnType = 3 /* CAN_STRINGIFY */;
  12372. // Element itself has no patch flag. However we still need to check:
  12373. // 1. Even for a node with no patch flag, it is possible for it to contain
  12374. // non-hoistable expressions that refers to scope variables, e.g. compiler
  12375. // injected keys or cached event handlers. Therefore we need to always
  12376. // check the codegenNode's props to be sure.
  12377. const generatedPropsType = getGeneratedPropsConstantType(node, context);
  12378. if (generatedPropsType === 0 /* NOT_CONSTANT */) {
  12379. constantCache.set(node, 0 /* NOT_CONSTANT */);
  12380. return 0 /* NOT_CONSTANT */;
  12381. }
  12382. if (generatedPropsType < returnType) {
  12383. returnType = generatedPropsType;
  12384. }
  12385. // 2. its children.
  12386. for (let i = 0; i < node.children.length; i++) {
  12387. const childType = getConstantType(node.children[i], context);
  12388. if (childType === 0 /* NOT_CONSTANT */) {
  12389. constantCache.set(node, 0 /* NOT_CONSTANT */);
  12390. return 0 /* NOT_CONSTANT */;
  12391. }
  12392. if (childType < returnType) {
  12393. returnType = childType;
  12394. }
  12395. }
  12396. // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
  12397. // type, check if any of the props can cause the type to be lowered
  12398. // we can skip can_patch because it's guaranteed by the absence of a
  12399. // patchFlag.
  12400. if (returnType > 1 /* CAN_SKIP_PATCH */) {
  12401. for (let i = 0; i < node.props.length; i++) {
  12402. const p = node.props[i];
  12403. if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
  12404. const expType = getConstantType(p.exp, context);
  12405. if (expType === 0 /* NOT_CONSTANT */) {
  12406. constantCache.set(node, 0 /* NOT_CONSTANT */);
  12407. return 0 /* NOT_CONSTANT */;
  12408. }
  12409. if (expType < returnType) {
  12410. returnType = expType;
  12411. }
  12412. }
  12413. }
  12414. }
  12415. // only svg/foreignObject could be block here, however if they are
  12416. // static then they don't need to be blocks since there will be no
  12417. // nested updates.
  12418. if (codegenNode.isBlock) {
  12419. context.removeHelper(OPEN_BLOCK);
  12420. context.removeHelper(getVNodeBlockHelper(context.inSSR, codegenNode.isComponent));
  12421. codegenNode.isBlock = false;
  12422. context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
  12423. }
  12424. constantCache.set(node, returnType);
  12425. return returnType;
  12426. }
  12427. else {
  12428. constantCache.set(node, 0 /* NOT_CONSTANT */);
  12429. return 0 /* NOT_CONSTANT */;
  12430. }
  12431. case 2 /* TEXT */:
  12432. case 3 /* COMMENT */:
  12433. return 3 /* CAN_STRINGIFY */;
  12434. case 9 /* IF */:
  12435. case 11 /* FOR */:
  12436. case 10 /* IF_BRANCH */:
  12437. return 0 /* NOT_CONSTANT */;
  12438. case 5 /* INTERPOLATION */:
  12439. case 12 /* TEXT_CALL */:
  12440. return getConstantType(node.content, context);
  12441. case 4 /* SIMPLE_EXPRESSION */:
  12442. return node.constType;
  12443. case 8 /* COMPOUND_EXPRESSION */:
  12444. let returnType = 3 /* CAN_STRINGIFY */;
  12445. for (let i = 0; i < node.children.length; i++) {
  12446. const child = node.children[i];
  12447. if (isString(child) || isSymbol(child)) {
  12448. continue;
  12449. }
  12450. const childType = getConstantType(child, context);
  12451. if (childType === 0 /* NOT_CONSTANT */) {
  12452. return 0 /* NOT_CONSTANT */;
  12453. }
  12454. else if (childType < returnType) {
  12455. returnType = childType;
  12456. }
  12457. }
  12458. return returnType;
  12459. default:
  12460. return 0 /* NOT_CONSTANT */;
  12461. }
  12462. }
  12463. const allowHoistedHelperSet = new Set([
  12464. NORMALIZE_CLASS,
  12465. NORMALIZE_STYLE,
  12466. NORMALIZE_PROPS,
  12467. GUARD_REACTIVE_PROPS
  12468. ]);
  12469. function getConstantTypeOfHelperCall(value, context) {
  12470. if (value.type === 14 /* JS_CALL_EXPRESSION */ &&
  12471. !isString(value.callee) &&
  12472. allowHoistedHelperSet.has(value.callee)) {
  12473. const arg = value.arguments[0];
  12474. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  12475. return getConstantType(arg, context);
  12476. }
  12477. else if (arg.type === 14 /* JS_CALL_EXPRESSION */) {
  12478. // in the case of nested helper call, e.g. `normalizeProps(guardReactiveProps(exp))`
  12479. return getConstantTypeOfHelperCall(arg, context);
  12480. }
  12481. }
  12482. return 0 /* NOT_CONSTANT */;
  12483. }
  12484. function getGeneratedPropsConstantType(node, context) {
  12485. let returnType = 3 /* CAN_STRINGIFY */;
  12486. const props = getNodeProps(node);
  12487. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  12488. const { properties } = props;
  12489. for (let i = 0; i < properties.length; i++) {
  12490. const { key, value } = properties[i];
  12491. const keyType = getConstantType(key, context);
  12492. if (keyType === 0 /* NOT_CONSTANT */) {
  12493. return keyType;
  12494. }
  12495. if (keyType < returnType) {
  12496. returnType = keyType;
  12497. }
  12498. let valueType;
  12499. if (value.type === 4 /* SIMPLE_EXPRESSION */) {
  12500. valueType = getConstantType(value, context);
  12501. }
  12502. else if (value.type === 14 /* JS_CALL_EXPRESSION */) {
  12503. // some helper calls can be hoisted,
  12504. // such as the `normalizeProps` generated by the compiler for pre-normalize class,
  12505. // in this case we need to respect the ConstantType of the helper's arguments
  12506. valueType = getConstantTypeOfHelperCall(value, context);
  12507. }
  12508. else {
  12509. valueType = 0 /* NOT_CONSTANT */;
  12510. }
  12511. if (valueType === 0 /* NOT_CONSTANT */) {
  12512. return valueType;
  12513. }
  12514. if (valueType < returnType) {
  12515. returnType = valueType;
  12516. }
  12517. }
  12518. }
  12519. return returnType;
  12520. }
  12521. function getNodeProps(node) {
  12522. const codegenNode = node.codegenNode;
  12523. if (codegenNode.type === 13 /* VNODE_CALL */) {
  12524. return codegenNode.props;
  12525. }
  12526. }
  12527. function getPatchFlag(node) {
  12528. const flag = node.patchFlag;
  12529. return flag ? parseInt(flag, 10) : undefined;
  12530. }
  12531. 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 }) {
  12532. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
  12533. const context = {
  12534. // options
  12535. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  12536. prefixIdentifiers,
  12537. hoistStatic,
  12538. cacheHandlers,
  12539. nodeTransforms,
  12540. directiveTransforms,
  12541. transformHoist,
  12542. isBuiltInComponent,
  12543. isCustomElement,
  12544. expressionPlugins,
  12545. scopeId,
  12546. slotted,
  12547. ssr,
  12548. inSSR,
  12549. ssrCssVars,
  12550. bindingMetadata,
  12551. inline,
  12552. isTS,
  12553. onError,
  12554. onWarn,
  12555. compatConfig,
  12556. // state
  12557. root,
  12558. helpers: new Map(),
  12559. components: new Set(),
  12560. directives: new Set(),
  12561. hoists: [],
  12562. imports: [],
  12563. constantCache: new Map(),
  12564. temps: 0,
  12565. cached: 0,
  12566. identifiers: Object.create(null),
  12567. scopes: {
  12568. vFor: 0,
  12569. vSlot: 0,
  12570. vPre: 0,
  12571. vOnce: 0
  12572. },
  12573. parent: null,
  12574. currentNode: root,
  12575. childIndex: 0,
  12576. inVOnce: false,
  12577. // methods
  12578. helper(name) {
  12579. const count = context.helpers.get(name) || 0;
  12580. context.helpers.set(name, count + 1);
  12581. return name;
  12582. },
  12583. removeHelper(name) {
  12584. const count = context.helpers.get(name);
  12585. if (count) {
  12586. const currentCount = count - 1;
  12587. if (!currentCount) {
  12588. context.helpers.delete(name);
  12589. }
  12590. else {
  12591. context.helpers.set(name, currentCount);
  12592. }
  12593. }
  12594. },
  12595. helperString(name) {
  12596. return `_${helperNameMap[context.helper(name)]}`;
  12597. },
  12598. replaceNode(node) {
  12599. /* istanbul ignore if */
  12600. {
  12601. if (!context.currentNode) {
  12602. throw new Error(`Node being replaced is already removed.`);
  12603. }
  12604. if (!context.parent) {
  12605. throw new Error(`Cannot replace root node.`);
  12606. }
  12607. }
  12608. context.parent.children[context.childIndex] = context.currentNode = node;
  12609. },
  12610. removeNode(node) {
  12611. if (!context.parent) {
  12612. throw new Error(`Cannot remove root node.`);
  12613. }
  12614. const list = context.parent.children;
  12615. const removalIndex = node
  12616. ? list.indexOf(node)
  12617. : context.currentNode
  12618. ? context.childIndex
  12619. : -1;
  12620. /* istanbul ignore if */
  12621. if (removalIndex < 0) {
  12622. throw new Error(`node being removed is not a child of current parent`);
  12623. }
  12624. if (!node || node === context.currentNode) {
  12625. // current node removed
  12626. context.currentNode = null;
  12627. context.onNodeRemoved();
  12628. }
  12629. else {
  12630. // sibling node removed
  12631. if (context.childIndex > removalIndex) {
  12632. context.childIndex--;
  12633. context.onNodeRemoved();
  12634. }
  12635. }
  12636. context.parent.children.splice(removalIndex, 1);
  12637. },
  12638. onNodeRemoved: () => { },
  12639. addIdentifiers(exp) {
  12640. },
  12641. removeIdentifiers(exp) {
  12642. },
  12643. hoist(exp) {
  12644. if (isString(exp))
  12645. exp = createSimpleExpression(exp);
  12646. context.hoists.push(exp);
  12647. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
  12648. identifier.hoisted = exp;
  12649. return identifier;
  12650. },
  12651. cache(exp, isVNode = false) {
  12652. return createCacheExpression(context.cached++, exp, isVNode);
  12653. }
  12654. };
  12655. return context;
  12656. }
  12657. function transform(root, options) {
  12658. const context = createTransformContext(root, options);
  12659. traverseNode(root, context);
  12660. if (options.hoistStatic) {
  12661. hoistStatic(root, context);
  12662. }
  12663. if (!options.ssr) {
  12664. createRootCodegen(root, context);
  12665. }
  12666. // finalize meta information
  12667. root.helpers = [...context.helpers.keys()];
  12668. root.components = [...context.components];
  12669. root.directives = [...context.directives];
  12670. root.imports = context.imports;
  12671. root.hoists = context.hoists;
  12672. root.temps = context.temps;
  12673. root.cached = context.cached;
  12674. }
  12675. function createRootCodegen(root, context) {
  12676. const { helper } = context;
  12677. const { children } = root;
  12678. if (children.length === 1) {
  12679. const child = children[0];
  12680. // if the single child is an element, turn it into a block.
  12681. if (isSingleElementRoot(root, child) && child.codegenNode) {
  12682. // single element root is never hoisted so codegenNode will never be
  12683. // SimpleExpressionNode
  12684. const codegenNode = child.codegenNode;
  12685. if (codegenNode.type === 13 /* VNODE_CALL */) {
  12686. makeBlock(codegenNode, context);
  12687. }
  12688. root.codegenNode = codegenNode;
  12689. }
  12690. else {
  12691. // - single <slot/>, IfNode, ForNode: already blocks.
  12692. // - single text node: always patched.
  12693. // root codegen falls through via genNode()
  12694. root.codegenNode = child;
  12695. }
  12696. }
  12697. else if (children.length > 1) {
  12698. // root has multiple nodes - return a fragment block.
  12699. let patchFlag = 64 /* STABLE_FRAGMENT */;
  12700. let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
  12701. // check if the fragment actually contains a single valid child with
  12702. // the rest being comments
  12703. if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
  12704. patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
  12705. patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
  12706. }
  12707. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, undefined, false /* isComponent */);
  12708. }
  12709. else ;
  12710. }
  12711. function traverseChildren(parent, context) {
  12712. let i = 0;
  12713. const nodeRemoved = () => {
  12714. i--;
  12715. };
  12716. for (; i < parent.children.length; i++) {
  12717. const child = parent.children[i];
  12718. if (isString(child))
  12719. continue;
  12720. context.parent = parent;
  12721. context.childIndex = i;
  12722. context.onNodeRemoved = nodeRemoved;
  12723. traverseNode(child, context);
  12724. }
  12725. }
  12726. function traverseNode(node, context) {
  12727. context.currentNode = node;
  12728. // apply transform plugins
  12729. const { nodeTransforms } = context;
  12730. const exitFns = [];
  12731. for (let i = 0; i < nodeTransforms.length; i++) {
  12732. const onExit = nodeTransforms[i](node, context);
  12733. if (onExit) {
  12734. if (isArray(onExit)) {
  12735. exitFns.push(...onExit);
  12736. }
  12737. else {
  12738. exitFns.push(onExit);
  12739. }
  12740. }
  12741. if (!context.currentNode) {
  12742. // node was removed
  12743. return;
  12744. }
  12745. else {
  12746. // node may have been replaced
  12747. node = context.currentNode;
  12748. }
  12749. }
  12750. switch (node.type) {
  12751. case 3 /* COMMENT */:
  12752. if (!context.ssr) {
  12753. // inject import for the Comment symbol, which is needed for creating
  12754. // comment nodes with `createVNode`
  12755. context.helper(CREATE_COMMENT);
  12756. }
  12757. break;
  12758. case 5 /* INTERPOLATION */:
  12759. // no need to traverse, but we need to inject toString helper
  12760. if (!context.ssr) {
  12761. context.helper(TO_DISPLAY_STRING);
  12762. }
  12763. break;
  12764. // for container types, further traverse downwards
  12765. case 9 /* IF */:
  12766. for (let i = 0; i < node.branches.length; i++) {
  12767. traverseNode(node.branches[i], context);
  12768. }
  12769. break;
  12770. case 10 /* IF_BRANCH */:
  12771. case 11 /* FOR */:
  12772. case 1 /* ELEMENT */:
  12773. case 0 /* ROOT */:
  12774. traverseChildren(node, context);
  12775. break;
  12776. }
  12777. // exit transforms
  12778. context.currentNode = node;
  12779. let i = exitFns.length;
  12780. while (i--) {
  12781. exitFns[i]();
  12782. }
  12783. }
  12784. function createStructuralDirectiveTransform(name, fn) {
  12785. const matches = isString(name)
  12786. ? (n) => n === name
  12787. : (n) => name.test(n);
  12788. return (node, context) => {
  12789. if (node.type === 1 /* ELEMENT */) {
  12790. const { props } = node;
  12791. // structural directive transforms are not concerned with slots
  12792. // as they are handled separately in vSlot.ts
  12793. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  12794. return;
  12795. }
  12796. const exitFns = [];
  12797. for (let i = 0; i < props.length; i++) {
  12798. const prop = props[i];
  12799. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  12800. // structural directives are removed to avoid infinite recursion
  12801. // also we remove them *before* applying so that it can further
  12802. // traverse itself in case it moves the node around
  12803. props.splice(i, 1);
  12804. i--;
  12805. const onExit = fn(node, prop, context);
  12806. if (onExit)
  12807. exitFns.push(onExit);
  12808. }
  12809. }
  12810. return exitFns;
  12811. }
  12812. };
  12813. }
  12814. const PURE_ANNOTATION = `/*#__PURE__*/`;
  12815. 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 }) {
  12816. const context = {
  12817. mode,
  12818. prefixIdentifiers,
  12819. sourceMap,
  12820. filename,
  12821. scopeId,
  12822. optimizeImports,
  12823. runtimeGlobalName,
  12824. runtimeModuleName,
  12825. ssrRuntimeModuleName,
  12826. ssr,
  12827. isTS,
  12828. inSSR,
  12829. source: ast.loc.source,
  12830. code: ``,
  12831. column: 1,
  12832. line: 1,
  12833. offset: 0,
  12834. indentLevel: 0,
  12835. pure: false,
  12836. map: undefined,
  12837. helper(key) {
  12838. return `_${helperNameMap[key]}`;
  12839. },
  12840. push(code, node) {
  12841. context.code += code;
  12842. },
  12843. indent() {
  12844. newline(++context.indentLevel);
  12845. },
  12846. deindent(withoutNewLine = false) {
  12847. if (withoutNewLine) {
  12848. --context.indentLevel;
  12849. }
  12850. else {
  12851. newline(--context.indentLevel);
  12852. }
  12853. },
  12854. newline() {
  12855. newline(context.indentLevel);
  12856. }
  12857. };
  12858. function newline(n) {
  12859. context.push('\n' + ` `.repeat(n));
  12860. }
  12861. return context;
  12862. }
  12863. function generate(ast, options = {}) {
  12864. const context = createCodegenContext(ast, options);
  12865. if (options.onContextCreated)
  12866. options.onContextCreated(context);
  12867. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  12868. const hasHelpers = ast.helpers.length > 0;
  12869. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  12870. // preambles
  12871. // in setup() inline mode, the preamble is generated in a sub context
  12872. // and returned separately.
  12873. const preambleContext = context;
  12874. {
  12875. genFunctionPreamble(ast, preambleContext);
  12876. }
  12877. // enter render function
  12878. const functionName = ssr ? `ssrRender` : `render`;
  12879. const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
  12880. const signature = args.join(', ');
  12881. {
  12882. push(`function ${functionName}(${signature}) {`);
  12883. }
  12884. indent();
  12885. if (useWithBlock) {
  12886. push(`with (_ctx) {`);
  12887. indent();
  12888. // function mode const declarations should be inside with block
  12889. // also they should be renamed to avoid collision with user properties
  12890. if (hasHelpers) {
  12891. push(`const { ${ast.helpers
  12892. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  12893. .join(', ')} } = _Vue`);
  12894. push(`\n`);
  12895. newline();
  12896. }
  12897. }
  12898. // generate asset resolution statements
  12899. if (ast.components.length) {
  12900. genAssets(ast.components, 'component', context);
  12901. if (ast.directives.length || ast.temps > 0) {
  12902. newline();
  12903. }
  12904. }
  12905. if (ast.directives.length) {
  12906. genAssets(ast.directives, 'directive', context);
  12907. if (ast.temps > 0) {
  12908. newline();
  12909. }
  12910. }
  12911. if (ast.temps > 0) {
  12912. push(`let `);
  12913. for (let i = 0; i < ast.temps; i++) {
  12914. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  12915. }
  12916. }
  12917. if (ast.components.length || ast.directives.length || ast.temps) {
  12918. push(`\n`);
  12919. newline();
  12920. }
  12921. // generate the VNode tree expression
  12922. if (!ssr) {
  12923. push(`return `);
  12924. }
  12925. if (ast.codegenNode) {
  12926. genNode(ast.codegenNode, context);
  12927. }
  12928. else {
  12929. push(`null`);
  12930. }
  12931. if (useWithBlock) {
  12932. deindent();
  12933. push(`}`);
  12934. }
  12935. deindent();
  12936. push(`}`);
  12937. return {
  12938. ast,
  12939. code: context.code,
  12940. preamble: ``,
  12941. // SourceMapGenerator does have toJSON() method but it's not in the types
  12942. map: context.map ? context.map.toJSON() : undefined
  12943. };
  12944. }
  12945. function genFunctionPreamble(ast, context) {
  12946. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName, ssrRuntimeModuleName } = context;
  12947. const VueBinding = runtimeGlobalName;
  12948. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  12949. // Generate const declaration for helpers
  12950. // In prefix mode, we place the const declaration at top so it's done
  12951. // only once; But if we not prefixing, we place the declaration inside the
  12952. // with block so it doesn't incur the `in` check cost for every helper access.
  12953. if (ast.helpers.length > 0) {
  12954. {
  12955. // "with" mode.
  12956. // save Vue in a separate variable to avoid collision
  12957. push(`const _Vue = ${VueBinding}\n`);
  12958. // in "with" mode, helpers are declared inside the with block to avoid
  12959. // has check cost, but hoists are lifted out of the function - we need
  12960. // to provide the helper here.
  12961. if (ast.hoists.length) {
  12962. const staticHelpers = [
  12963. CREATE_VNODE,
  12964. CREATE_ELEMENT_VNODE,
  12965. CREATE_COMMENT,
  12966. CREATE_TEXT,
  12967. CREATE_STATIC
  12968. ]
  12969. .filter(helper => ast.helpers.includes(helper))
  12970. .map(aliasHelper)
  12971. .join(', ');
  12972. push(`const { ${staticHelpers} } = _Vue\n`);
  12973. }
  12974. }
  12975. }
  12976. genHoists(ast.hoists, context);
  12977. newline();
  12978. push(`return `);
  12979. }
  12980. function genAssets(assets, type, { helper, push, newline, isTS }) {
  12981. const resolver = helper(type === 'component'
  12982. ? RESOLVE_COMPONENT
  12983. : RESOLVE_DIRECTIVE);
  12984. for (let i = 0; i < assets.length; i++) {
  12985. let id = assets[i];
  12986. // potential component implicit self-reference inferred from SFC filename
  12987. const maybeSelfReference = id.endsWith('__self');
  12988. if (maybeSelfReference) {
  12989. id = id.slice(0, -6);
  12990. }
  12991. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`);
  12992. if (i < assets.length - 1) {
  12993. newline();
  12994. }
  12995. }
  12996. }
  12997. function genHoists(hoists, context) {
  12998. if (!hoists.length) {
  12999. return;
  13000. }
  13001. context.pure = true;
  13002. const { push, newline, helper, scopeId, mode } = context;
  13003. newline();
  13004. for (let i = 0; i < hoists.length; i++) {
  13005. const exp = hoists[i];
  13006. if (exp) {
  13007. push(`const _hoisted_${i + 1} = ${``}`);
  13008. genNode(exp, context);
  13009. newline();
  13010. }
  13011. }
  13012. context.pure = false;
  13013. }
  13014. function isText$1(n) {
  13015. return (isString(n) ||
  13016. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  13017. n.type === 2 /* TEXT */ ||
  13018. n.type === 5 /* INTERPOLATION */ ||
  13019. n.type === 8 /* COMPOUND_EXPRESSION */);
  13020. }
  13021. function genNodeListAsArray(nodes, context) {
  13022. const multilines = nodes.length > 3 ||
  13023. (nodes.some(n => isArray(n) || !isText$1(n)));
  13024. context.push(`[`);
  13025. multilines && context.indent();
  13026. genNodeList(nodes, context, multilines);
  13027. multilines && context.deindent();
  13028. context.push(`]`);
  13029. }
  13030. function genNodeList(nodes, context, multilines = false, comma = true) {
  13031. const { push, newline } = context;
  13032. for (let i = 0; i < nodes.length; i++) {
  13033. const node = nodes[i];
  13034. if (isString(node)) {
  13035. push(node);
  13036. }
  13037. else if (isArray(node)) {
  13038. genNodeListAsArray(node, context);
  13039. }
  13040. else {
  13041. genNode(node, context);
  13042. }
  13043. if (i < nodes.length - 1) {
  13044. if (multilines) {
  13045. comma && push(',');
  13046. newline();
  13047. }
  13048. else {
  13049. comma && push(', ');
  13050. }
  13051. }
  13052. }
  13053. }
  13054. function genNode(node, context) {
  13055. if (isString(node)) {
  13056. context.push(node);
  13057. return;
  13058. }
  13059. if (isSymbol(node)) {
  13060. context.push(context.helper(node));
  13061. return;
  13062. }
  13063. switch (node.type) {
  13064. case 1 /* ELEMENT */:
  13065. case 9 /* IF */:
  13066. case 11 /* FOR */:
  13067. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  13068. `Apply appropriate transforms first.`);
  13069. genNode(node.codegenNode, context);
  13070. break;
  13071. case 2 /* TEXT */:
  13072. genText(node, context);
  13073. break;
  13074. case 4 /* SIMPLE_EXPRESSION */:
  13075. genExpression(node, context);
  13076. break;
  13077. case 5 /* INTERPOLATION */:
  13078. genInterpolation(node, context);
  13079. break;
  13080. case 12 /* TEXT_CALL */:
  13081. genNode(node.codegenNode, context);
  13082. break;
  13083. case 8 /* COMPOUND_EXPRESSION */:
  13084. genCompoundExpression(node, context);
  13085. break;
  13086. case 3 /* COMMENT */:
  13087. genComment(node, context);
  13088. break;
  13089. case 13 /* VNODE_CALL */:
  13090. genVNodeCall(node, context);
  13091. break;
  13092. case 14 /* JS_CALL_EXPRESSION */:
  13093. genCallExpression(node, context);
  13094. break;
  13095. case 15 /* JS_OBJECT_EXPRESSION */:
  13096. genObjectExpression(node, context);
  13097. break;
  13098. case 17 /* JS_ARRAY_EXPRESSION */:
  13099. genArrayExpression(node, context);
  13100. break;
  13101. case 18 /* JS_FUNCTION_EXPRESSION */:
  13102. genFunctionExpression(node, context);
  13103. break;
  13104. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  13105. genConditionalExpression(node, context);
  13106. break;
  13107. case 20 /* JS_CACHE_EXPRESSION */:
  13108. genCacheExpression(node, context);
  13109. break;
  13110. case 21 /* JS_BLOCK_STATEMENT */:
  13111. genNodeList(node.body, context, true, false);
  13112. break;
  13113. // SSR only types
  13114. case 22 /* JS_TEMPLATE_LITERAL */:
  13115. break;
  13116. case 23 /* JS_IF_STATEMENT */:
  13117. break;
  13118. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  13119. break;
  13120. case 25 /* JS_SEQUENCE_EXPRESSION */:
  13121. break;
  13122. case 26 /* JS_RETURN_STATEMENT */:
  13123. break;
  13124. /* istanbul ignore next */
  13125. case 10 /* IF_BRANCH */:
  13126. // noop
  13127. break;
  13128. default:
  13129. {
  13130. assert(false, `unhandled codegen node type: ${node.type}`);
  13131. // make sure we exhaust all possible types
  13132. const exhaustiveCheck = node;
  13133. return exhaustiveCheck;
  13134. }
  13135. }
  13136. }
  13137. function genText(node, context) {
  13138. context.push(JSON.stringify(node.content), node);
  13139. }
  13140. function genExpression(node, context) {
  13141. const { content, isStatic } = node;
  13142. context.push(isStatic ? JSON.stringify(content) : content, node);
  13143. }
  13144. function genInterpolation(node, context) {
  13145. const { push, helper, pure } = context;
  13146. if (pure)
  13147. push(PURE_ANNOTATION);
  13148. push(`${helper(TO_DISPLAY_STRING)}(`);
  13149. genNode(node.content, context);
  13150. push(`)`);
  13151. }
  13152. function genCompoundExpression(node, context) {
  13153. for (let i = 0; i < node.children.length; i++) {
  13154. const child = node.children[i];
  13155. if (isString(child)) {
  13156. context.push(child);
  13157. }
  13158. else {
  13159. genNode(child, context);
  13160. }
  13161. }
  13162. }
  13163. function genExpressionAsPropertyKey(node, context) {
  13164. const { push } = context;
  13165. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  13166. push(`[`);
  13167. genCompoundExpression(node, context);
  13168. push(`]`);
  13169. }
  13170. else if (node.isStatic) {
  13171. // only quote keys if necessary
  13172. const text = isSimpleIdentifier(node.content)
  13173. ? node.content
  13174. : JSON.stringify(node.content);
  13175. push(text, node);
  13176. }
  13177. else {
  13178. push(`[${node.content}]`, node);
  13179. }
  13180. }
  13181. function genComment(node, context) {
  13182. const { push, helper, pure } = context;
  13183. if (pure) {
  13184. push(PURE_ANNOTATION);
  13185. }
  13186. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  13187. }
  13188. function genVNodeCall(node, context) {
  13189. const { push, helper, pure } = context;
  13190. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking, isComponent } = node;
  13191. if (directives) {
  13192. push(helper(WITH_DIRECTIVES) + `(`);
  13193. }
  13194. if (isBlock) {
  13195. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  13196. }
  13197. if (pure) {
  13198. push(PURE_ANNOTATION);
  13199. }
  13200. const callHelper = isBlock
  13201. ? getVNodeBlockHelper(context.inSSR, isComponent)
  13202. : getVNodeHelper(context.inSSR, isComponent);
  13203. push(helper(callHelper) + `(`, node);
  13204. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  13205. push(`)`);
  13206. if (isBlock) {
  13207. push(`)`);
  13208. }
  13209. if (directives) {
  13210. push(`, `);
  13211. genNode(directives, context);
  13212. push(`)`);
  13213. }
  13214. }
  13215. function genNullableArgs(args) {
  13216. let i = args.length;
  13217. while (i--) {
  13218. if (args[i] != null)
  13219. break;
  13220. }
  13221. return args.slice(0, i + 1).map(arg => arg || `null`);
  13222. }
  13223. // JavaScript
  13224. function genCallExpression(node, context) {
  13225. const { push, helper, pure } = context;
  13226. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  13227. if (pure) {
  13228. push(PURE_ANNOTATION);
  13229. }
  13230. push(callee + `(`, node);
  13231. genNodeList(node.arguments, context);
  13232. push(`)`);
  13233. }
  13234. function genObjectExpression(node, context) {
  13235. const { push, indent, deindent, newline } = context;
  13236. const { properties } = node;
  13237. if (!properties.length) {
  13238. push(`{}`, node);
  13239. return;
  13240. }
  13241. const multilines = properties.length > 1 ||
  13242. (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  13243. push(multilines ? `{` : `{ `);
  13244. multilines && indent();
  13245. for (let i = 0; i < properties.length; i++) {
  13246. const { key, value } = properties[i];
  13247. // key
  13248. genExpressionAsPropertyKey(key, context);
  13249. push(`: `);
  13250. // value
  13251. genNode(value, context);
  13252. if (i < properties.length - 1) {
  13253. // will only reach this if it's multilines
  13254. push(`,`);
  13255. newline();
  13256. }
  13257. }
  13258. multilines && deindent();
  13259. push(multilines ? `}` : ` }`);
  13260. }
  13261. function genArrayExpression(node, context) {
  13262. genNodeListAsArray(node.elements, context);
  13263. }
  13264. function genFunctionExpression(node, context) {
  13265. const { push, indent, deindent } = context;
  13266. const { params, returns, body, newline, isSlot } = node;
  13267. if (isSlot) {
  13268. // wrap slot functions with owner context
  13269. push(`_${helperNameMap[WITH_CTX]}(`);
  13270. }
  13271. push(`(`, node);
  13272. if (isArray(params)) {
  13273. genNodeList(params, context);
  13274. }
  13275. else if (params) {
  13276. genNode(params, context);
  13277. }
  13278. push(`) => `);
  13279. if (newline || body) {
  13280. push(`{`);
  13281. indent();
  13282. }
  13283. if (returns) {
  13284. if (newline) {
  13285. push(`return `);
  13286. }
  13287. if (isArray(returns)) {
  13288. genNodeListAsArray(returns, context);
  13289. }
  13290. else {
  13291. genNode(returns, context);
  13292. }
  13293. }
  13294. else if (body) {
  13295. genNode(body, context);
  13296. }
  13297. if (newline || body) {
  13298. deindent();
  13299. push(`}`);
  13300. }
  13301. if (isSlot) {
  13302. push(`)`);
  13303. }
  13304. }
  13305. function genConditionalExpression(node, context) {
  13306. const { test, consequent, alternate, newline: needNewline } = node;
  13307. const { push, indent, deindent, newline } = context;
  13308. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  13309. const needsParens = !isSimpleIdentifier(test.content);
  13310. needsParens && push(`(`);
  13311. genExpression(test, context);
  13312. needsParens && push(`)`);
  13313. }
  13314. else {
  13315. push(`(`);
  13316. genNode(test, context);
  13317. push(`)`);
  13318. }
  13319. needNewline && indent();
  13320. context.indentLevel++;
  13321. needNewline || push(` `);
  13322. push(`? `);
  13323. genNode(consequent, context);
  13324. context.indentLevel--;
  13325. needNewline && newline();
  13326. needNewline || push(` `);
  13327. push(`: `);
  13328. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  13329. if (!isNested) {
  13330. context.indentLevel++;
  13331. }
  13332. genNode(alternate, context);
  13333. if (!isNested) {
  13334. context.indentLevel--;
  13335. }
  13336. needNewline && deindent(true /* without newline */);
  13337. }
  13338. function genCacheExpression(node, context) {
  13339. const { push, helper, indent, deindent, newline } = context;
  13340. push(`_cache[${node.index}] || (`);
  13341. if (node.isVNode) {
  13342. indent();
  13343. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  13344. newline();
  13345. }
  13346. push(`_cache[${node.index}] = `);
  13347. genNode(node.value, context);
  13348. if (node.isVNode) {
  13349. push(`,`);
  13350. newline();
  13351. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  13352. newline();
  13353. push(`_cache[${node.index}]`);
  13354. deindent();
  13355. }
  13356. push(`)`);
  13357. }
  13358. // these keywords should not appear inside expressions, but operators like
  13359. // typeof, instanceof and in are allowed
  13360. const prohibitedKeywordRE = new RegExp('\\b' +
  13361. ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
  13362. 'super,throw,while,yield,delete,export,import,return,switch,default,' +
  13363. 'extends,finally,continue,debugger,function,arguments,typeof,void')
  13364. .split(',')
  13365. .join('\\b|\\b') +
  13366. '\\b');
  13367. // strip strings in expressions
  13368. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  13369. /**
  13370. * Validate a non-prefixed expression.
  13371. * This is only called when using the in-browser runtime compiler since it
  13372. * doesn't prefix expressions.
  13373. */
  13374. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  13375. const exp = node.content;
  13376. // empty expressions are validated per-directive since some directives
  13377. // do allow empty expressions.
  13378. if (!exp.trim()) {
  13379. return;
  13380. }
  13381. try {
  13382. new Function(asRawStatements
  13383. ? ` ${exp} `
  13384. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  13385. }
  13386. catch (e) {
  13387. let message = e.message;
  13388. const keywordMatch = exp
  13389. .replace(stripStringRE, '')
  13390. .match(prohibitedKeywordRE);
  13391. if (keywordMatch) {
  13392. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  13393. }
  13394. context.onError(createCompilerError(44 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
  13395. }
  13396. }
  13397. const transformExpression = (node, context) => {
  13398. if (node.type === 5 /* INTERPOLATION */) {
  13399. node.content = processExpression(node.content, context);
  13400. }
  13401. else if (node.type === 1 /* ELEMENT */) {
  13402. // handle directives on element
  13403. for (let i = 0; i < node.props.length; i++) {
  13404. const dir = node.props[i];
  13405. // do not process for v-on & v-for since they are special handled
  13406. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  13407. const exp = dir.exp;
  13408. const arg = dir.arg;
  13409. // do not process exp if this is v-on:arg - we need special handling
  13410. // for wrapping inline statements.
  13411. if (exp &&
  13412. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  13413. !(dir.name === 'on' && arg)) {
  13414. dir.exp = processExpression(exp, context,
  13415. // slot args must be processed as function params
  13416. dir.name === 'slot');
  13417. }
  13418. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  13419. dir.arg = processExpression(arg, context);
  13420. }
  13421. }
  13422. }
  13423. }
  13424. };
  13425. // Important: since this function uses Node.js only dependencies, it should
  13426. // always be used with a leading !true check so that it can be
  13427. // tree-shaken from the browser build.
  13428. function processExpression(node, context,
  13429. // some expressions like v-slot props & v-for aliases should be parsed as
  13430. // function params
  13431. asParams = false,
  13432. // v-on handler values may contain multiple statements
  13433. asRawStatements = false, localVars = Object.create(context.identifiers)) {
  13434. {
  13435. {
  13436. // simple in-browser validation (same logic in 2.x)
  13437. validateBrowserExpression(node, context, asParams, asRawStatements);
  13438. }
  13439. return node;
  13440. }
  13441. }
  13442. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  13443. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  13444. // #1587: We need to dynamically increment the key based on the current
  13445. // node's sibling nodes, since chained v-if/else branches are
  13446. // rendered at the same depth
  13447. const siblings = context.parent.children;
  13448. let i = siblings.indexOf(ifNode);
  13449. let key = 0;
  13450. while (i-- >= 0) {
  13451. const sibling = siblings[i];
  13452. if (sibling && sibling.type === 9 /* IF */) {
  13453. key += sibling.branches.length;
  13454. }
  13455. }
  13456. // Exit callback. Complete the codegenNode when all children have been
  13457. // transformed.
  13458. return () => {
  13459. if (isRoot) {
  13460. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  13461. }
  13462. else {
  13463. // attach this branch's codegen node to the v-if root.
  13464. const parentCondition = getParentCondition(ifNode.codegenNode);
  13465. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  13466. }
  13467. };
  13468. });
  13469. });
  13470. // target-agnostic transform used for both Client and SSR
  13471. function processIf(node, dir, context, processCodegen) {
  13472. if (dir.name !== 'else' &&
  13473. (!dir.exp || !dir.exp.content.trim())) {
  13474. const loc = dir.exp ? dir.exp.loc : node.loc;
  13475. context.onError(createCompilerError(28 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  13476. dir.exp = createSimpleExpression(`true`, false, loc);
  13477. }
  13478. if (dir.exp) {
  13479. validateBrowserExpression(dir.exp, context);
  13480. }
  13481. if (dir.name === 'if') {
  13482. const branch = createIfBranch(node, dir);
  13483. const ifNode = {
  13484. type: 9 /* IF */,
  13485. loc: node.loc,
  13486. branches: [branch]
  13487. };
  13488. context.replaceNode(ifNode);
  13489. if (processCodegen) {
  13490. return processCodegen(ifNode, branch, true);
  13491. }
  13492. }
  13493. else {
  13494. // locate the adjacent v-if
  13495. const siblings = context.parent.children;
  13496. const comments = [];
  13497. let i = siblings.indexOf(node);
  13498. while (i-- >= -1) {
  13499. const sibling = siblings[i];
  13500. if (sibling && sibling.type === 3 /* COMMENT */) {
  13501. context.removeNode(sibling);
  13502. comments.unshift(sibling);
  13503. continue;
  13504. }
  13505. if (sibling &&
  13506. sibling.type === 2 /* TEXT */ &&
  13507. !sibling.content.trim().length) {
  13508. context.removeNode(sibling);
  13509. continue;
  13510. }
  13511. if (sibling && sibling.type === 9 /* IF */) {
  13512. // Check if v-else was followed by v-else-if
  13513. if (dir.name === 'else-if' &&
  13514. sibling.branches[sibling.branches.length - 1].condition === undefined) {
  13515. context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  13516. }
  13517. // move the node to the if node's branches
  13518. context.removeNode();
  13519. const branch = createIfBranch(node, dir);
  13520. if (comments.length &&
  13521. // #3619 ignore comments if the v-if is direct child of <transition>
  13522. !(context.parent &&
  13523. context.parent.type === 1 /* ELEMENT */ &&
  13524. isBuiltInType(context.parent.tag, 'transition'))) {
  13525. branch.children = [...comments, ...branch.children];
  13526. }
  13527. // check if user is forcing same key on different branches
  13528. {
  13529. const key = branch.userKey;
  13530. if (key) {
  13531. sibling.branches.forEach(({ userKey }) => {
  13532. if (isSameKey(userKey, key)) {
  13533. context.onError(createCompilerError(29 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  13534. }
  13535. });
  13536. }
  13537. }
  13538. sibling.branches.push(branch);
  13539. const onExit = processCodegen && processCodegen(sibling, branch, false);
  13540. // since the branch was removed, it will not be traversed.
  13541. // make sure to traverse here.
  13542. traverseNode(branch, context);
  13543. // call on exit
  13544. if (onExit)
  13545. onExit();
  13546. // make sure to reset currentNode after traversal to indicate this
  13547. // node has been removed.
  13548. context.currentNode = null;
  13549. }
  13550. else {
  13551. context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  13552. }
  13553. break;
  13554. }
  13555. }
  13556. }
  13557. function createIfBranch(node, dir) {
  13558. return {
  13559. type: 10 /* IF_BRANCH */,
  13560. loc: node.loc,
  13561. condition: dir.name === 'else' ? undefined : dir.exp,
  13562. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  13563. ? node.children
  13564. : [node],
  13565. userKey: findProp(node, `key`)
  13566. };
  13567. }
  13568. function createCodegenNodeForBranch(branch, keyIndex, context) {
  13569. if (branch.condition) {
  13570. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  13571. // make sure to pass in asBlock: true so that the comment node call
  13572. // closes the current block.
  13573. createCallExpression(context.helper(CREATE_COMMENT), [
  13574. '"v-if"' ,
  13575. 'true'
  13576. ]));
  13577. }
  13578. else {
  13579. return createChildrenCodegenNode(branch, keyIndex, context);
  13580. }
  13581. }
  13582. function createChildrenCodegenNode(branch, keyIndex, context) {
  13583. const { helper } = context;
  13584. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
  13585. const { children } = branch;
  13586. const firstChild = children[0];
  13587. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  13588. if (needFragmentWrapper) {
  13589. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  13590. // optimize away nested fragments when child is a ForNode
  13591. const vnodeCall = firstChild.codegenNode;
  13592. injectProp(vnodeCall, keyProperty, context);
  13593. return vnodeCall;
  13594. }
  13595. else {
  13596. let patchFlag = 64 /* STABLE_FRAGMENT */;
  13597. let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
  13598. // check if the fragment actually contains a single valid child with
  13599. // the rest being comments
  13600. if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
  13601. patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
  13602. patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
  13603. }
  13604. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, false /* isComponent */, branch.loc);
  13605. }
  13606. }
  13607. else {
  13608. const ret = firstChild.codegenNode;
  13609. const vnodeCall = getMemoedVNodeCall(ret);
  13610. // Change createVNode to createBlock.
  13611. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  13612. makeBlock(vnodeCall, context);
  13613. }
  13614. // inject branch key
  13615. injectProp(vnodeCall, keyProperty, context);
  13616. return ret;
  13617. }
  13618. }
  13619. function isSameKey(a, b) {
  13620. if (!a || a.type !== b.type) {
  13621. return false;
  13622. }
  13623. if (a.type === 6 /* ATTRIBUTE */) {
  13624. if (a.value.content !== b.value.content) {
  13625. return false;
  13626. }
  13627. }
  13628. else {
  13629. // directive
  13630. const exp = a.exp;
  13631. const branchExp = b.exp;
  13632. if (exp.type !== branchExp.type) {
  13633. return false;
  13634. }
  13635. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  13636. exp.isStatic !== branchExp.isStatic ||
  13637. exp.content !== branchExp.content) {
  13638. return false;
  13639. }
  13640. }
  13641. return true;
  13642. }
  13643. function getParentCondition(node) {
  13644. while (true) {
  13645. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  13646. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  13647. node = node.alternate;
  13648. }
  13649. else {
  13650. return node;
  13651. }
  13652. }
  13653. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  13654. node = node.value;
  13655. }
  13656. }
  13657. }
  13658. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  13659. const { helper, removeHelper } = context;
  13660. return processFor(node, dir, context, forNode => {
  13661. // create the loop render function expression now, and add the
  13662. // iterator on exit after all children have been traversed
  13663. const renderExp = createCallExpression(helper(RENDER_LIST), [
  13664. forNode.source
  13665. ]);
  13666. const memo = findDir(node, 'memo');
  13667. const keyProp = findProp(node, `key`);
  13668. const keyExp = keyProp &&
  13669. (keyProp.type === 6 /* ATTRIBUTE */
  13670. ? createSimpleExpression(keyProp.value.content, true)
  13671. : keyProp.exp);
  13672. const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
  13673. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  13674. forNode.source.constType > 0 /* NOT_CONSTANT */;
  13675. const fragmentFlag = isStableFragment
  13676. ? 64 /* STABLE_FRAGMENT */
  13677. : keyProp
  13678. ? 128 /* KEYED_FRAGMENT */
  13679. : 256 /* UNKEYED_FRAGMENT */;
  13680. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
  13681. (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, false /* isComponent */, node.loc);
  13682. return () => {
  13683. // finish the codegen now that all children have been traversed
  13684. let childBlock;
  13685. const isTemplate = isTemplateNode(node);
  13686. const { children } = forNode;
  13687. // check <template v-for> key placement
  13688. if (isTemplate) {
  13689. node.children.some(c => {
  13690. if (c.type === 1 /* ELEMENT */) {
  13691. const key = findProp(c, 'key');
  13692. if (key) {
  13693. context.onError(createCompilerError(33 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  13694. return true;
  13695. }
  13696. }
  13697. });
  13698. }
  13699. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  13700. const slotOutlet = isSlotOutlet(node)
  13701. ? node
  13702. : isTemplate &&
  13703. node.children.length === 1 &&
  13704. isSlotOutlet(node.children[0])
  13705. ? node.children[0] // api-extractor somehow fails to infer this
  13706. : null;
  13707. if (slotOutlet) {
  13708. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  13709. childBlock = slotOutlet.codegenNode;
  13710. if (isTemplate && keyProperty) {
  13711. // <template v-for="..." :key="..."><slot/></template>
  13712. // we need to inject the key to the renderSlot() call.
  13713. // the props for renderSlot is passed as the 3rd argument.
  13714. injectProp(childBlock, keyProperty, context);
  13715. }
  13716. }
  13717. else if (needFragmentWrapper) {
  13718. // <template v-for="..."> with text or multi-elements
  13719. // should generate a fragment block for each loop
  13720. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
  13721. (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
  13722. ), undefined, undefined, true, undefined, false /* isComponent */);
  13723. }
  13724. else {
  13725. // Normal element v-for. Directly use the child's codegenNode
  13726. // but mark it as a block.
  13727. childBlock = children[0]
  13728. .codegenNode;
  13729. if (isTemplate && keyProperty) {
  13730. injectProp(childBlock, keyProperty, context);
  13731. }
  13732. if (childBlock.isBlock !== !isStableFragment) {
  13733. if (childBlock.isBlock) {
  13734. // switch from block to vnode
  13735. removeHelper(OPEN_BLOCK);
  13736. removeHelper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  13737. }
  13738. else {
  13739. // switch from vnode to block
  13740. removeHelper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  13741. }
  13742. }
  13743. childBlock.isBlock = !isStableFragment;
  13744. if (childBlock.isBlock) {
  13745. helper(OPEN_BLOCK);
  13746. helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
  13747. }
  13748. else {
  13749. helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
  13750. }
  13751. }
  13752. if (memo) {
  13753. const loop = createFunctionExpression(createForLoopParams(forNode.parseResult, [
  13754. createSimpleExpression(`_cached`)
  13755. ]));
  13756. loop.body = createBlockStatement([
  13757. createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
  13758. createCompoundExpression([
  13759. `if (_cached`,
  13760. ...(keyExp ? [` && _cached.key === `, keyExp] : []),
  13761. ` && ${context.helperString(IS_MEMO_SAME)}(_cached, _memo)) return _cached`
  13762. ]),
  13763. createCompoundExpression([`const _item = `, childBlock]),
  13764. createSimpleExpression(`_item.memo = _memo`),
  13765. createSimpleExpression(`return _item`)
  13766. ]);
  13767. renderExp.arguments.push(loop, createSimpleExpression(`_cache`), createSimpleExpression(String(context.cached++)));
  13768. }
  13769. else {
  13770. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  13771. }
  13772. };
  13773. });
  13774. });
  13775. // target-agnostic transform used for both Client and SSR
  13776. function processFor(node, dir, context, processCodegen) {
  13777. if (!dir.exp) {
  13778. context.onError(createCompilerError(31 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  13779. return;
  13780. }
  13781. const parseResult = parseForExpression(
  13782. // can only be simple expression because vFor transform is applied
  13783. // before expression transform.
  13784. dir.exp, context);
  13785. if (!parseResult) {
  13786. context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  13787. return;
  13788. }
  13789. const { addIdentifiers, removeIdentifiers, scopes } = context;
  13790. const { source, value, key, index } = parseResult;
  13791. const forNode = {
  13792. type: 11 /* FOR */,
  13793. loc: dir.loc,
  13794. source,
  13795. valueAlias: value,
  13796. keyAlias: key,
  13797. objectIndexAlias: index,
  13798. parseResult,
  13799. children: isTemplateNode(node) ? node.children : [node]
  13800. };
  13801. context.replaceNode(forNode);
  13802. // bookkeeping
  13803. scopes.vFor++;
  13804. const onExit = processCodegen && processCodegen(forNode);
  13805. return () => {
  13806. scopes.vFor--;
  13807. if (onExit)
  13808. onExit();
  13809. };
  13810. }
  13811. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  13812. // This regex doesn't cover the case if key or index aliases have destructuring,
  13813. // but those do not make sense in the first place, so this works in practice.
  13814. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  13815. const stripParensRE = /^\(|\)$/g;
  13816. function parseForExpression(input, context) {
  13817. const loc = input.loc;
  13818. const exp = input.content;
  13819. const inMatch = exp.match(forAliasRE);
  13820. if (!inMatch)
  13821. return;
  13822. const [, LHS, RHS] = inMatch;
  13823. const result = {
  13824. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  13825. value: undefined,
  13826. key: undefined,
  13827. index: undefined
  13828. };
  13829. {
  13830. validateBrowserExpression(result.source, context);
  13831. }
  13832. let valueContent = LHS.trim().replace(stripParensRE, '').trim();
  13833. const trimmedOffset = LHS.indexOf(valueContent);
  13834. const iteratorMatch = valueContent.match(forIteratorRE);
  13835. if (iteratorMatch) {
  13836. valueContent = valueContent.replace(forIteratorRE, '').trim();
  13837. const keyContent = iteratorMatch[1].trim();
  13838. let keyOffset;
  13839. if (keyContent) {
  13840. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  13841. result.key = createAliasExpression(loc, keyContent, keyOffset);
  13842. {
  13843. validateBrowserExpression(result.key, context, true);
  13844. }
  13845. }
  13846. if (iteratorMatch[2]) {
  13847. const indexContent = iteratorMatch[2].trim();
  13848. if (indexContent) {
  13849. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  13850. ? keyOffset + keyContent.length
  13851. : trimmedOffset + valueContent.length));
  13852. {
  13853. validateBrowserExpression(result.index, context, true);
  13854. }
  13855. }
  13856. }
  13857. }
  13858. if (valueContent) {
  13859. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  13860. {
  13861. validateBrowserExpression(result.value, context, true);
  13862. }
  13863. }
  13864. return result;
  13865. }
  13866. function createAliasExpression(range, content, offset) {
  13867. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  13868. }
  13869. function createForLoopParams({ value, key, index }, memoArgs = []) {
  13870. return createParamsList([value, key, index, ...memoArgs]);
  13871. }
  13872. function createParamsList(args) {
  13873. let i = args.length;
  13874. while (i--) {
  13875. if (args[i])
  13876. break;
  13877. }
  13878. return args
  13879. .slice(0, i + 1)
  13880. .map((arg, i) => arg || createSimpleExpression(`_`.repeat(i + 1), false));
  13881. }
  13882. const defaultFallback = createSimpleExpression(`undefined`, false);
  13883. // A NodeTransform that:
  13884. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  13885. // by transformExpression. This is only applied in non-browser builds with
  13886. // { prefixIdentifiers: true }.
  13887. // 2. Track v-slot depths so that we know a slot is inside another slot.
  13888. // Note the exit callback is executed before buildSlots() on the same node,
  13889. // so only nested slots see positive numbers.
  13890. const trackSlotScopes = (node, context) => {
  13891. if (node.type === 1 /* ELEMENT */ &&
  13892. (node.tagType === 1 /* COMPONENT */ ||
  13893. node.tagType === 3 /* TEMPLATE */)) {
  13894. // We are only checking non-empty v-slot here
  13895. // since we only care about slots that introduce scope variables.
  13896. const vSlot = findDir(node, 'slot');
  13897. if (vSlot) {
  13898. vSlot.exp;
  13899. context.scopes.vSlot++;
  13900. return () => {
  13901. context.scopes.vSlot--;
  13902. };
  13903. }
  13904. }
  13905. };
  13906. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  13907. // Instead of being a DirectiveTransform, v-slot processing is called during
  13908. // transformElement to build the slots object for a component.
  13909. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  13910. context.helper(WITH_CTX);
  13911. const { children, loc } = node;
  13912. const slotsProperties = [];
  13913. const dynamicSlots = [];
  13914. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  13915. // since it likely uses a scope variable.
  13916. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  13917. // 1. Check for slot with slotProps on component itself.
  13918. // <Comp v-slot="{ prop }"/>
  13919. const onComponentSlot = findDir(node, 'slot', true);
  13920. if (onComponentSlot) {
  13921. const { arg, exp } = onComponentSlot;
  13922. if (arg && !isStaticExp(arg)) {
  13923. hasDynamicSlots = true;
  13924. }
  13925. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  13926. }
  13927. // 2. Iterate through children and check for template slots
  13928. // <template v-slot:foo="{ prop }">
  13929. let hasTemplateSlots = false;
  13930. let hasNamedDefaultSlot = false;
  13931. const implicitDefaultChildren = [];
  13932. const seenSlotNames = new Set();
  13933. for (let i = 0; i < children.length; i++) {
  13934. const slotElement = children[i];
  13935. let slotDir;
  13936. if (!isTemplateNode(slotElement) ||
  13937. !(slotDir = findDir(slotElement, 'slot', true))) {
  13938. // not a <template v-slot>, skip.
  13939. if (slotElement.type !== 3 /* COMMENT */) {
  13940. implicitDefaultChildren.push(slotElement);
  13941. }
  13942. continue;
  13943. }
  13944. if (onComponentSlot) {
  13945. // already has on-component slot - this is incorrect usage.
  13946. context.onError(createCompilerError(37 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  13947. break;
  13948. }
  13949. hasTemplateSlots = true;
  13950. const { children: slotChildren, loc: slotLoc } = slotElement;
  13951. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  13952. // check if name is dynamic.
  13953. let staticSlotName;
  13954. if (isStaticExp(slotName)) {
  13955. staticSlotName = slotName ? slotName.content : `default`;
  13956. }
  13957. else {
  13958. hasDynamicSlots = true;
  13959. }
  13960. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  13961. // check if this slot is conditional (v-if/v-for)
  13962. let vIf;
  13963. let vElse;
  13964. let vFor;
  13965. if ((vIf = findDir(slotElement, 'if'))) {
  13966. hasDynamicSlots = true;
  13967. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  13968. }
  13969. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  13970. // find adjacent v-if
  13971. let j = i;
  13972. let prev;
  13973. while (j--) {
  13974. prev = children[j];
  13975. if (prev.type !== 3 /* COMMENT */) {
  13976. break;
  13977. }
  13978. }
  13979. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  13980. // remove node
  13981. children.splice(i, 1);
  13982. i--;
  13983. // attach this slot to previous conditional
  13984. let conditional = dynamicSlots[dynamicSlots.length - 1];
  13985. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  13986. conditional = conditional.alternate;
  13987. }
  13988. conditional.alternate = vElse.exp
  13989. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  13990. : buildDynamicSlot(slotName, slotFunction);
  13991. }
  13992. else {
  13993. context.onError(createCompilerError(30 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  13994. }
  13995. }
  13996. else if ((vFor = findDir(slotElement, 'for'))) {
  13997. hasDynamicSlots = true;
  13998. const parseResult = vFor.parseResult ||
  13999. parseForExpression(vFor.exp, context);
  14000. if (parseResult) {
  14001. // Render the dynamic slots as an array and add it to the createSlot()
  14002. // args. The runtime knows how to handle it appropriately.
  14003. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  14004. parseResult.source,
  14005. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  14006. ]));
  14007. }
  14008. else {
  14009. context.onError(createCompilerError(32 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  14010. }
  14011. }
  14012. else {
  14013. // check duplicate static names
  14014. if (staticSlotName) {
  14015. if (seenSlotNames.has(staticSlotName)) {
  14016. context.onError(createCompilerError(38 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  14017. continue;
  14018. }
  14019. seenSlotNames.add(staticSlotName);
  14020. if (staticSlotName === 'default') {
  14021. hasNamedDefaultSlot = true;
  14022. }
  14023. }
  14024. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  14025. }
  14026. }
  14027. if (!onComponentSlot) {
  14028. const buildDefaultSlotProperty = (props, children) => {
  14029. const fn = buildSlotFn(props, children, loc);
  14030. return createObjectProperty(`default`, fn);
  14031. };
  14032. if (!hasTemplateSlots) {
  14033. // implicit default slot (on component)
  14034. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  14035. }
  14036. else if (implicitDefaultChildren.length &&
  14037. // #3766
  14038. // with whitespace: 'preserve', whitespaces between slots will end up in
  14039. // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
  14040. implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
  14041. // implicit default slot (mixed with named slots)
  14042. if (hasNamedDefaultSlot) {
  14043. context.onError(createCompilerError(39 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  14044. }
  14045. else {
  14046. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  14047. }
  14048. }
  14049. }
  14050. const slotFlag = hasDynamicSlots
  14051. ? 2 /* DYNAMIC */
  14052. : hasForwardedSlots(node.children)
  14053. ? 3 /* FORWARDED */
  14054. : 1 /* STABLE */;
  14055. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  14056. // 2 = compiled but dynamic = can skip normalization, but must run diff
  14057. // 1 = compiled and static = can skip normalization AND diff as optimized
  14058. createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
  14059. if (dynamicSlots.length) {
  14060. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  14061. slots,
  14062. createArrayExpression(dynamicSlots)
  14063. ]);
  14064. }
  14065. return {
  14066. slots,
  14067. hasDynamicSlots
  14068. };
  14069. }
  14070. function buildDynamicSlot(name, fn) {
  14071. return createObjectExpression([
  14072. createObjectProperty(`name`, name),
  14073. createObjectProperty(`fn`, fn)
  14074. ]);
  14075. }
  14076. function hasForwardedSlots(children) {
  14077. for (let i = 0; i < children.length; i++) {
  14078. const child = children[i];
  14079. switch (child.type) {
  14080. case 1 /* ELEMENT */:
  14081. if (child.tagType === 2 /* SLOT */ ||
  14082. hasForwardedSlots(child.children)) {
  14083. return true;
  14084. }
  14085. break;
  14086. case 9 /* IF */:
  14087. if (hasForwardedSlots(child.branches))
  14088. return true;
  14089. break;
  14090. case 10 /* IF_BRANCH */:
  14091. case 11 /* FOR */:
  14092. if (hasForwardedSlots(child.children))
  14093. return true;
  14094. break;
  14095. }
  14096. }
  14097. return false;
  14098. }
  14099. function isNonWhitespaceContent(node) {
  14100. if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
  14101. return true;
  14102. return node.type === 2 /* TEXT */
  14103. ? !!node.content.trim()
  14104. : isNonWhitespaceContent(node.content);
  14105. }
  14106. // some directive transforms (e.g. v-model) may return a symbol for runtime
  14107. // import, which should be used instead of a resolveDirective call.
  14108. const directiveImportMap = new WeakMap();
  14109. // generate a JavaScript AST for this element's codegen
  14110. const transformElement = (node, context) => {
  14111. // perform the work on exit, after all child expressions have been
  14112. // processed and merged.
  14113. return function postTransformElement() {
  14114. node = context.currentNode;
  14115. if (!(node.type === 1 /* ELEMENT */ &&
  14116. (node.tagType === 0 /* ELEMENT */ ||
  14117. node.tagType === 1 /* COMPONENT */))) {
  14118. return;
  14119. }
  14120. const { tag, props } = node;
  14121. const isComponent = node.tagType === 1 /* COMPONENT */;
  14122. // The goal of the transform is to create a codegenNode implementing the
  14123. // VNodeCall interface.
  14124. let vnodeTag = isComponent
  14125. ? resolveComponentType(node, context)
  14126. : `"${tag}"`;
  14127. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  14128. let vnodeProps;
  14129. let vnodeChildren;
  14130. let vnodePatchFlag;
  14131. let patchFlag = 0;
  14132. let vnodeDynamicProps;
  14133. let dynamicPropNames;
  14134. let vnodeDirectives;
  14135. let shouldUseBlock =
  14136. // dynamic component may resolve to plain elements
  14137. isDynamicComponent ||
  14138. vnodeTag === TELEPORT ||
  14139. vnodeTag === SUSPENSE ||
  14140. (!isComponent &&
  14141. // <svg> and <foreignObject> must be forced into blocks so that block
  14142. // updates inside get proper isSVG flag at runtime. (#639, #643)
  14143. // This is technically web-specific, but splitting the logic out of core
  14144. // leads to too much unnecessary complexity.
  14145. (tag === 'svg' || tag === 'foreignObject'));
  14146. // props
  14147. if (props.length > 0) {
  14148. const propsBuildResult = buildProps(node, context);
  14149. vnodeProps = propsBuildResult.props;
  14150. patchFlag = propsBuildResult.patchFlag;
  14151. dynamicPropNames = propsBuildResult.dynamicPropNames;
  14152. const directives = propsBuildResult.directives;
  14153. vnodeDirectives =
  14154. directives && directives.length
  14155. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  14156. : undefined;
  14157. if (propsBuildResult.shouldUseBlock) {
  14158. shouldUseBlock = true;
  14159. }
  14160. }
  14161. // children
  14162. if (node.children.length > 0) {
  14163. if (vnodeTag === KEEP_ALIVE) {
  14164. // Although a built-in component, we compile KeepAlive with raw children
  14165. // instead of slot functions so that it can be used inside Transition
  14166. // or other Transition-wrapping HOCs.
  14167. // To ensure correct updates with block optimizations, we need to:
  14168. // 1. Force keep-alive into a block. This avoids its children being
  14169. // collected by a parent block.
  14170. shouldUseBlock = true;
  14171. // 2. Force keep-alive to always be updated, since it uses raw children.
  14172. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  14173. if (node.children.length > 1) {
  14174. context.onError(createCompilerError(45 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  14175. start: node.children[0].loc.start,
  14176. end: node.children[node.children.length - 1].loc.end,
  14177. source: ''
  14178. }));
  14179. }
  14180. }
  14181. const shouldBuildAsSlots = isComponent &&
  14182. // Teleport is not a real component and has dedicated runtime handling
  14183. vnodeTag !== TELEPORT &&
  14184. // explained above.
  14185. vnodeTag !== KEEP_ALIVE;
  14186. if (shouldBuildAsSlots) {
  14187. const { slots, hasDynamicSlots } = buildSlots(node, context);
  14188. vnodeChildren = slots;
  14189. if (hasDynamicSlots) {
  14190. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  14191. }
  14192. }
  14193. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  14194. const child = node.children[0];
  14195. const type = child.type;
  14196. // check for dynamic text children
  14197. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  14198. type === 8 /* COMPOUND_EXPRESSION */;
  14199. if (hasDynamicTextChild &&
  14200. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  14201. patchFlag |= 1 /* TEXT */;
  14202. }
  14203. // pass directly if the only child is a text node
  14204. // (plain / interpolation / expression)
  14205. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  14206. vnodeChildren = child;
  14207. }
  14208. else {
  14209. vnodeChildren = node.children;
  14210. }
  14211. }
  14212. else {
  14213. vnodeChildren = node.children;
  14214. }
  14215. }
  14216. // patchFlag & dynamicPropNames
  14217. if (patchFlag !== 0) {
  14218. {
  14219. if (patchFlag < 0) {
  14220. // special flags (negative and mutually exclusive)
  14221. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  14222. }
  14223. else {
  14224. // bitwise flags
  14225. const flagNames = Object.keys(PatchFlagNames)
  14226. .map(Number)
  14227. .filter(n => n > 0 && patchFlag & n)
  14228. .map(n => PatchFlagNames[n])
  14229. .join(`, `);
  14230. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  14231. }
  14232. }
  14233. if (dynamicPropNames && dynamicPropNames.length) {
  14234. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  14235. }
  14236. }
  14237. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc);
  14238. };
  14239. };
  14240. function resolveComponentType(node, context, ssr = false) {
  14241. let { tag } = node;
  14242. // 1. dynamic component
  14243. const isExplicitDynamic = isComponentTag(tag);
  14244. const isProp = findProp(node, 'is');
  14245. if (isProp) {
  14246. if (isExplicitDynamic ||
  14247. (false )) {
  14248. const exp = isProp.type === 6 /* ATTRIBUTE */
  14249. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  14250. : isProp.exp;
  14251. if (exp) {
  14252. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  14253. exp
  14254. ]);
  14255. }
  14256. }
  14257. else if (isProp.type === 6 /* ATTRIBUTE */ &&
  14258. isProp.value.content.startsWith('vue:')) {
  14259. // <button is="vue:xxx">
  14260. // if not <component>, only is value that starts with "vue:" will be
  14261. // treated as component by the parse phase and reach here, unless it's
  14262. // compat mode where all is values are considered components
  14263. tag = isProp.value.content.slice(4);
  14264. }
  14265. }
  14266. // 1.5 v-is (TODO: Deprecate)
  14267. const isDir = !isExplicitDynamic && findDir(node, 'is');
  14268. if (isDir && isDir.exp) {
  14269. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  14270. isDir.exp
  14271. ]);
  14272. }
  14273. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  14274. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  14275. if (builtIn) {
  14276. // built-ins are simply fallthroughs / have special handling during ssr
  14277. // so we don't need to import their runtime equivalents
  14278. if (!ssr)
  14279. context.helper(builtIn);
  14280. return builtIn;
  14281. }
  14282. // 5. user component (resolve)
  14283. context.helper(RESOLVE_COMPONENT);
  14284. context.components.add(tag);
  14285. return toValidAssetId(tag, `component`);
  14286. }
  14287. function buildProps(node, context, props = node.props, ssr = false) {
  14288. const { tag, loc: elementLoc, children } = node;
  14289. const isComponent = node.tagType === 1 /* COMPONENT */;
  14290. let properties = [];
  14291. const mergeArgs = [];
  14292. const runtimeDirectives = [];
  14293. const hasChildren = children.length > 0;
  14294. let shouldUseBlock = false;
  14295. // patchFlag analysis
  14296. let patchFlag = 0;
  14297. let hasRef = false;
  14298. let hasClassBinding = false;
  14299. let hasStyleBinding = false;
  14300. let hasHydrationEventBinding = false;
  14301. let hasDynamicKeys = false;
  14302. let hasVnodeHook = false;
  14303. const dynamicPropNames = [];
  14304. const analyzePatchFlag = ({ key, value }) => {
  14305. if (isStaticExp(key)) {
  14306. const name = key.content;
  14307. const isEventHandler = isOn(name);
  14308. if (!isComponent &&
  14309. isEventHandler &&
  14310. // omit the flag for click handlers because hydration gives click
  14311. // dedicated fast path.
  14312. name.toLowerCase() !== 'onclick' &&
  14313. // omit v-model handlers
  14314. name !== 'onUpdate:modelValue' &&
  14315. // omit onVnodeXXX hooks
  14316. !isReservedProp(name)) {
  14317. hasHydrationEventBinding = true;
  14318. }
  14319. if (isEventHandler && isReservedProp(name)) {
  14320. hasVnodeHook = true;
  14321. }
  14322. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  14323. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  14324. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  14325. getConstantType(value, context) > 0)) {
  14326. // skip if the prop is a cached handler or has constant value
  14327. return;
  14328. }
  14329. if (name === 'ref') {
  14330. hasRef = true;
  14331. }
  14332. else if (name === 'class') {
  14333. hasClassBinding = true;
  14334. }
  14335. else if (name === 'style') {
  14336. hasStyleBinding = true;
  14337. }
  14338. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  14339. dynamicPropNames.push(name);
  14340. }
  14341. // treat the dynamic class and style binding of the component as dynamic props
  14342. if (isComponent &&
  14343. (name === 'class' || name === 'style') &&
  14344. !dynamicPropNames.includes(name)) {
  14345. dynamicPropNames.push(name);
  14346. }
  14347. }
  14348. else {
  14349. hasDynamicKeys = true;
  14350. }
  14351. };
  14352. for (let i = 0; i < props.length; i++) {
  14353. // static attribute
  14354. const prop = props[i];
  14355. if (prop.type === 6 /* ATTRIBUTE */) {
  14356. const { loc, name, value } = prop;
  14357. let isStatic = true;
  14358. if (name === 'ref') {
  14359. hasRef = true;
  14360. if (context.scopes.vFor > 0) {
  14361. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  14362. }
  14363. }
  14364. // skip is on <component>, or is="vue:xxx"
  14365. if (name === 'is' &&
  14366. (isComponentTag(tag) ||
  14367. (value && value.content.startsWith('vue:')) ||
  14368. (false ))) {
  14369. continue;
  14370. }
  14371. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
  14372. }
  14373. else {
  14374. // directives
  14375. const { name, arg, exp, loc } = prop;
  14376. const isVBind = name === 'bind';
  14377. const isVOn = name === 'on';
  14378. // skip v-slot - it is handled by its dedicated transform.
  14379. if (name === 'slot') {
  14380. if (!isComponent) {
  14381. context.onError(createCompilerError(40 /* X_V_SLOT_MISPLACED */, loc));
  14382. }
  14383. continue;
  14384. }
  14385. // skip v-once/v-memo - they are handled by dedicated transforms.
  14386. if (name === 'once' || name === 'memo') {
  14387. continue;
  14388. }
  14389. // skip v-is and :is on <component>
  14390. if (name === 'is' ||
  14391. (isVBind &&
  14392. isStaticArgOf(arg, 'is') &&
  14393. (isComponentTag(tag) ||
  14394. (false )))) {
  14395. continue;
  14396. }
  14397. // skip v-on in SSR compilation
  14398. if (isVOn && ssr) {
  14399. continue;
  14400. }
  14401. if (
  14402. // #938: elements with dynamic keys should be forced into blocks
  14403. (isVBind && isStaticArgOf(arg, 'key')) ||
  14404. // inline before-update hooks need to force block so that it is invoked
  14405. // before children
  14406. (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update'))) {
  14407. shouldUseBlock = true;
  14408. }
  14409. if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) {
  14410. properties.push(createObjectProperty(createSimpleExpression('ref_for', true), createSimpleExpression('true')));
  14411. }
  14412. // special case for v-bind and v-on with no argument
  14413. if (!arg && (isVBind || isVOn)) {
  14414. hasDynamicKeys = true;
  14415. if (exp) {
  14416. if (properties.length) {
  14417. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  14418. properties = [];
  14419. }
  14420. if (isVBind) {
  14421. mergeArgs.push(exp);
  14422. }
  14423. else {
  14424. // v-on="obj" -> toHandlers(obj)
  14425. mergeArgs.push({
  14426. type: 14 /* JS_CALL_EXPRESSION */,
  14427. loc,
  14428. callee: context.helper(TO_HANDLERS),
  14429. arguments: [exp]
  14430. });
  14431. }
  14432. }
  14433. else {
  14434. context.onError(createCompilerError(isVBind
  14435. ? 34 /* X_V_BIND_NO_EXPRESSION */
  14436. : 35 /* X_V_ON_NO_EXPRESSION */, loc));
  14437. }
  14438. continue;
  14439. }
  14440. const directiveTransform = context.directiveTransforms[name];
  14441. if (directiveTransform) {
  14442. // has built-in directive transform.
  14443. const { props, needRuntime } = directiveTransform(prop, node, context);
  14444. !ssr && props.forEach(analyzePatchFlag);
  14445. properties.push(...props);
  14446. if (needRuntime) {
  14447. runtimeDirectives.push(prop);
  14448. if (isSymbol(needRuntime)) {
  14449. directiveImportMap.set(prop, needRuntime);
  14450. }
  14451. }
  14452. }
  14453. else {
  14454. // no built-in transform, this is a user custom directive.
  14455. runtimeDirectives.push(prop);
  14456. // custom dirs may use beforeUpdate so they need to force blocks
  14457. // to ensure before-update gets called before children update
  14458. if (hasChildren) {
  14459. shouldUseBlock = true;
  14460. }
  14461. }
  14462. }
  14463. }
  14464. let propsExpression = undefined;
  14465. // has v-bind="object" or v-on="object", wrap with mergeProps
  14466. if (mergeArgs.length) {
  14467. if (properties.length) {
  14468. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  14469. }
  14470. if (mergeArgs.length > 1) {
  14471. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  14472. }
  14473. else {
  14474. // single v-bind with nothing else - no need for a mergeProps call
  14475. propsExpression = mergeArgs[0];
  14476. }
  14477. }
  14478. else if (properties.length) {
  14479. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  14480. }
  14481. // patchFlag analysis
  14482. if (hasDynamicKeys) {
  14483. patchFlag |= 16 /* FULL_PROPS */;
  14484. }
  14485. else {
  14486. if (hasClassBinding && !isComponent) {
  14487. patchFlag |= 2 /* CLASS */;
  14488. }
  14489. if (hasStyleBinding && !isComponent) {
  14490. patchFlag |= 4 /* STYLE */;
  14491. }
  14492. if (dynamicPropNames.length) {
  14493. patchFlag |= 8 /* PROPS */;
  14494. }
  14495. if (hasHydrationEventBinding) {
  14496. patchFlag |= 32 /* HYDRATE_EVENTS */;
  14497. }
  14498. }
  14499. if (!shouldUseBlock &&
  14500. (patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  14501. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  14502. patchFlag |= 512 /* NEED_PATCH */;
  14503. }
  14504. // pre-normalize props, SSR is skipped for now
  14505. if (!context.inSSR && propsExpression) {
  14506. switch (propsExpression.type) {
  14507. case 15 /* JS_OBJECT_EXPRESSION */:
  14508. // means that there is no v-bind,
  14509. // but still need to deal with dynamic key binding
  14510. let classKeyIndex = -1;
  14511. let styleKeyIndex = -1;
  14512. let hasDynamicKey = false;
  14513. for (let i = 0; i < propsExpression.properties.length; i++) {
  14514. const key = propsExpression.properties[i].key;
  14515. if (isStaticExp(key)) {
  14516. if (key.content === 'class') {
  14517. classKeyIndex = i;
  14518. }
  14519. else if (key.content === 'style') {
  14520. styleKeyIndex = i;
  14521. }
  14522. }
  14523. else if (!key.isHandlerKey) {
  14524. hasDynamicKey = true;
  14525. }
  14526. }
  14527. const classProp = propsExpression.properties[classKeyIndex];
  14528. const styleProp = propsExpression.properties[styleKeyIndex];
  14529. // no dynamic key
  14530. if (!hasDynamicKey) {
  14531. if (classProp && !isStaticExp(classProp.value)) {
  14532. classProp.value = createCallExpression(context.helper(NORMALIZE_CLASS), [classProp.value]);
  14533. }
  14534. if (styleProp &&
  14535. !isStaticExp(styleProp.value) &&
  14536. // the static style is compiled into an object,
  14537. // so use `hasStyleBinding` to ensure that it is a dynamic style binding
  14538. (hasStyleBinding ||
  14539. // v-bind:style and style both exist,
  14540. // v-bind:style with static literal object
  14541. styleProp.value.type === 17 /* JS_ARRAY_EXPRESSION */)) {
  14542. styleProp.value = createCallExpression(context.helper(NORMALIZE_STYLE), [styleProp.value]);
  14543. }
  14544. }
  14545. else {
  14546. // dynamic key binding, wrap with `normalizeProps`
  14547. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [propsExpression]);
  14548. }
  14549. break;
  14550. case 14 /* JS_CALL_EXPRESSION */:
  14551. // mergeProps call, do nothing
  14552. break;
  14553. default:
  14554. // single v-bind
  14555. propsExpression = createCallExpression(context.helper(NORMALIZE_PROPS), [
  14556. createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
  14557. propsExpression
  14558. ])
  14559. ]);
  14560. break;
  14561. }
  14562. }
  14563. return {
  14564. props: propsExpression,
  14565. directives: runtimeDirectives,
  14566. patchFlag,
  14567. dynamicPropNames,
  14568. shouldUseBlock
  14569. };
  14570. }
  14571. // Dedupe props in an object literal.
  14572. // Literal duplicated attributes would have been warned during the parse phase,
  14573. // however, it's possible to encounter duplicated `onXXX` handlers with different
  14574. // modifiers. We also need to merge static and dynamic class / style attributes.
  14575. // - onXXX handlers / style: merge into array
  14576. // - class: merge into single expression with concatenation
  14577. function dedupeProperties(properties) {
  14578. const knownProps = new Map();
  14579. const deduped = [];
  14580. for (let i = 0; i < properties.length; i++) {
  14581. const prop = properties[i];
  14582. // dynamic keys are always allowed
  14583. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  14584. deduped.push(prop);
  14585. continue;
  14586. }
  14587. const name = prop.key.content;
  14588. const existing = knownProps.get(name);
  14589. if (existing) {
  14590. if (name === 'style' || name === 'class' || isOn(name)) {
  14591. mergeAsArray$1(existing, prop);
  14592. }
  14593. // unexpected duplicate, should have emitted error during parse
  14594. }
  14595. else {
  14596. knownProps.set(name, prop);
  14597. deduped.push(prop);
  14598. }
  14599. }
  14600. return deduped;
  14601. }
  14602. function mergeAsArray$1(existing, incoming) {
  14603. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  14604. existing.value.elements.push(incoming.value);
  14605. }
  14606. else {
  14607. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  14608. }
  14609. }
  14610. function buildDirectiveArgs(dir, context) {
  14611. const dirArgs = [];
  14612. const runtime = directiveImportMap.get(dir);
  14613. if (runtime) {
  14614. // built-in directive with runtime
  14615. dirArgs.push(context.helperString(runtime));
  14616. }
  14617. else {
  14618. {
  14619. // inject statement for resolving directive
  14620. context.helper(RESOLVE_DIRECTIVE);
  14621. context.directives.add(dir.name);
  14622. dirArgs.push(toValidAssetId(dir.name, `directive`));
  14623. }
  14624. }
  14625. const { loc } = dir;
  14626. if (dir.exp)
  14627. dirArgs.push(dir.exp);
  14628. if (dir.arg) {
  14629. if (!dir.exp) {
  14630. dirArgs.push(`void 0`);
  14631. }
  14632. dirArgs.push(dir.arg);
  14633. }
  14634. if (Object.keys(dir.modifiers).length) {
  14635. if (!dir.arg) {
  14636. if (!dir.exp) {
  14637. dirArgs.push(`void 0`);
  14638. }
  14639. dirArgs.push(`void 0`);
  14640. }
  14641. const trueExpression = createSimpleExpression(`true`, false, loc);
  14642. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  14643. }
  14644. return createArrayExpression(dirArgs, dir.loc);
  14645. }
  14646. function stringifyDynamicPropNames(props) {
  14647. let propsNamesString = `[`;
  14648. for (let i = 0, l = props.length; i < l; i++) {
  14649. propsNamesString += JSON.stringify(props[i]);
  14650. if (i < l - 1)
  14651. propsNamesString += ', ';
  14652. }
  14653. return propsNamesString + `]`;
  14654. }
  14655. function isComponentTag(tag) {
  14656. return tag === 'component' || tag === 'Component';
  14657. }
  14658. const transformSlotOutlet = (node, context) => {
  14659. if (isSlotOutlet(node)) {
  14660. const { children, loc } = node;
  14661. const { slotName, slotProps } = processSlotOutlet(node, context);
  14662. const slotArgs = [
  14663. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  14664. slotName,
  14665. '{}',
  14666. 'undefined',
  14667. 'true'
  14668. ];
  14669. let expectedLen = 2;
  14670. if (slotProps) {
  14671. slotArgs[2] = slotProps;
  14672. expectedLen = 3;
  14673. }
  14674. if (children.length) {
  14675. slotArgs[3] = createFunctionExpression([], children, false, false, loc);
  14676. expectedLen = 4;
  14677. }
  14678. if (context.scopeId && !context.slotted) {
  14679. expectedLen = 5;
  14680. }
  14681. slotArgs.splice(expectedLen); // remove unused arguments
  14682. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  14683. }
  14684. };
  14685. function processSlotOutlet(node, context) {
  14686. let slotName = `"default"`;
  14687. let slotProps = undefined;
  14688. const nonNameProps = [];
  14689. for (let i = 0; i < node.props.length; i++) {
  14690. const p = node.props[i];
  14691. if (p.type === 6 /* ATTRIBUTE */) {
  14692. if (p.value) {
  14693. if (p.name === 'name') {
  14694. slotName = JSON.stringify(p.value.content);
  14695. }
  14696. else {
  14697. p.name = camelize(p.name);
  14698. nonNameProps.push(p);
  14699. }
  14700. }
  14701. }
  14702. else {
  14703. if (p.name === 'bind' && isStaticArgOf(p.arg, 'name')) {
  14704. if (p.exp)
  14705. slotName = p.exp;
  14706. }
  14707. else {
  14708. if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
  14709. p.arg.content = camelize(p.arg.content);
  14710. }
  14711. nonNameProps.push(p);
  14712. }
  14713. }
  14714. }
  14715. if (nonNameProps.length > 0) {
  14716. const { props, directives } = buildProps(node, context, nonNameProps);
  14717. slotProps = props;
  14718. if (directives.length) {
  14719. context.onError(createCompilerError(36 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  14720. }
  14721. }
  14722. return {
  14723. slotName,
  14724. slotProps
  14725. };
  14726. }
  14727. const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
  14728. const transformOn = (dir, node, context, augmentor) => {
  14729. const { loc, modifiers, arg } = dir;
  14730. if (!dir.exp && !modifiers.length) {
  14731. context.onError(createCompilerError(35 /* X_V_ON_NO_EXPRESSION */, loc));
  14732. }
  14733. let eventName;
  14734. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  14735. if (arg.isStatic) {
  14736. let rawName = arg.content;
  14737. // TODO deprecate @vnodeXXX usage
  14738. if (rawName.startsWith('vue:')) {
  14739. rawName = `vnode-${rawName.slice(4)}`;
  14740. }
  14741. // for all event listeners, auto convert it to camelCase. See issue #2249
  14742. eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
  14743. }
  14744. else {
  14745. // #2388
  14746. eventName = createCompoundExpression([
  14747. `${context.helperString(TO_HANDLER_KEY)}(`,
  14748. arg,
  14749. `)`
  14750. ]);
  14751. }
  14752. }
  14753. else {
  14754. // already a compound expression.
  14755. eventName = arg;
  14756. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  14757. eventName.children.push(`)`);
  14758. }
  14759. // handler processing
  14760. let exp = dir.exp;
  14761. if (exp && !exp.content.trim()) {
  14762. exp = undefined;
  14763. }
  14764. let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  14765. if (exp) {
  14766. const isMemberExp = isMemberExpression(exp.content);
  14767. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  14768. const hasMultipleStatements = exp.content.includes(`;`);
  14769. {
  14770. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  14771. }
  14772. if (isInlineStatement || (shouldCache && isMemberExp)) {
  14773. // wrap inline statement in a function expression
  14774. exp = createCompoundExpression([
  14775. `${isInlineStatement
  14776. ? `$event`
  14777. : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  14778. exp,
  14779. hasMultipleStatements ? `}` : `)`
  14780. ]);
  14781. }
  14782. }
  14783. let ret = {
  14784. props: [
  14785. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  14786. ]
  14787. };
  14788. // apply extended compiler augmentor
  14789. if (augmentor) {
  14790. ret = augmentor(ret);
  14791. }
  14792. if (shouldCache) {
  14793. // cache handlers so that it's always the same handler being passed down.
  14794. // this avoids unnecessary re-renders when users use inline handlers on
  14795. // components.
  14796. ret.props[0].value = context.cache(ret.props[0].value);
  14797. }
  14798. // mark the key as handler for props normalization check
  14799. ret.props.forEach(p => (p.key.isHandlerKey = true));
  14800. return ret;
  14801. };
  14802. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  14803. // codegen for the entire props object. This transform here is only for v-bind
  14804. // *with* args.
  14805. const transformBind = (dir, _node, context) => {
  14806. const { exp, modifiers, loc } = dir;
  14807. const arg = dir.arg;
  14808. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  14809. arg.children.unshift(`(`);
  14810. arg.children.push(`) || ""`);
  14811. }
  14812. else if (!arg.isStatic) {
  14813. arg.content = `${arg.content} || ""`;
  14814. }
  14815. // .sync is replaced by v-model:arg
  14816. if (modifiers.includes('camel')) {
  14817. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  14818. if (arg.isStatic) {
  14819. arg.content = camelize(arg.content);
  14820. }
  14821. else {
  14822. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  14823. }
  14824. }
  14825. else {
  14826. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  14827. arg.children.push(`)`);
  14828. }
  14829. }
  14830. if (!context.inSSR) {
  14831. if (modifiers.includes('prop')) {
  14832. injectPrefix(arg, '.');
  14833. }
  14834. if (modifiers.includes('attr')) {
  14835. injectPrefix(arg, '^');
  14836. }
  14837. }
  14838. if (!exp ||
  14839. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  14840. context.onError(createCompilerError(34 /* X_V_BIND_NO_EXPRESSION */, loc));
  14841. return {
  14842. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  14843. };
  14844. }
  14845. return {
  14846. props: [createObjectProperty(arg, exp)]
  14847. };
  14848. };
  14849. const injectPrefix = (arg, prefix) => {
  14850. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  14851. if (arg.isStatic) {
  14852. arg.content = prefix + arg.content;
  14853. }
  14854. else {
  14855. arg.content = `\`${prefix}\${${arg.content}}\``;
  14856. }
  14857. }
  14858. else {
  14859. arg.children.unshift(`'${prefix}' + (`);
  14860. arg.children.push(`)`);
  14861. }
  14862. };
  14863. // Merge adjacent text nodes and expressions into a single expression
  14864. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  14865. const transformText = (node, context) => {
  14866. if (node.type === 0 /* ROOT */ ||
  14867. node.type === 1 /* ELEMENT */ ||
  14868. node.type === 11 /* FOR */ ||
  14869. node.type === 10 /* IF_BRANCH */) {
  14870. // perform the transform on node exit so that all expressions have already
  14871. // been processed.
  14872. return () => {
  14873. const children = node.children;
  14874. let currentContainer = undefined;
  14875. let hasText = false;
  14876. for (let i = 0; i < children.length; i++) {
  14877. const child = children[i];
  14878. if (isText(child)) {
  14879. hasText = true;
  14880. for (let j = i + 1; j < children.length; j++) {
  14881. const next = children[j];
  14882. if (isText(next)) {
  14883. if (!currentContainer) {
  14884. currentContainer = children[i] = {
  14885. type: 8 /* COMPOUND_EXPRESSION */,
  14886. loc: child.loc,
  14887. children: [child]
  14888. };
  14889. }
  14890. // merge adjacent text node into current
  14891. currentContainer.children.push(` + `, next);
  14892. children.splice(j, 1);
  14893. j--;
  14894. }
  14895. else {
  14896. currentContainer = undefined;
  14897. break;
  14898. }
  14899. }
  14900. }
  14901. }
  14902. if (!hasText ||
  14903. // if this is a plain element with a single text child, leave it
  14904. // as-is since the runtime has dedicated fast path for this by directly
  14905. // setting textContent of the element.
  14906. // for component root it's always normalized anyway.
  14907. (children.length === 1 &&
  14908. (node.type === 0 /* ROOT */ ||
  14909. (node.type === 1 /* ELEMENT */ &&
  14910. node.tagType === 0 /* ELEMENT */ &&
  14911. // #3756
  14912. // custom directives can potentially add DOM elements arbitrarily,
  14913. // we need to avoid setting textContent of the element at runtime
  14914. // to avoid accidentally overwriting the DOM elements added
  14915. // by the user through custom directives.
  14916. !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
  14917. !context.directiveTransforms[p.name]) &&
  14918. // in compat mode, <template> tags with no special directives
  14919. // will be rendered as a fragment so its children must be
  14920. // converted into vnodes.
  14921. !(false ))))) {
  14922. return;
  14923. }
  14924. // pre-convert text nodes into createTextVNode(text) calls to avoid
  14925. // runtime normalization.
  14926. for (let i = 0; i < children.length; i++) {
  14927. const child = children[i];
  14928. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  14929. const callArgs = [];
  14930. // createTextVNode defaults to single whitespace, so if it is a
  14931. // single space the code could be an empty call to save bytes.
  14932. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  14933. callArgs.push(child);
  14934. }
  14935. // mark dynamic text with flag so it gets patched inside a block
  14936. if (!context.ssr &&
  14937. getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
  14938. callArgs.push(1 /* TEXT */ +
  14939. (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
  14940. }
  14941. children[i] = {
  14942. type: 12 /* TEXT_CALL */,
  14943. content: child,
  14944. loc: child.loc,
  14945. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  14946. };
  14947. }
  14948. }
  14949. };
  14950. }
  14951. };
  14952. const seen = new WeakSet();
  14953. const transformOnce = (node, context) => {
  14954. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  14955. if (seen.has(node) || context.inVOnce) {
  14956. return;
  14957. }
  14958. seen.add(node);
  14959. context.inVOnce = true;
  14960. context.helper(SET_BLOCK_TRACKING);
  14961. return () => {
  14962. context.inVOnce = false;
  14963. const cur = context.currentNode;
  14964. if (cur.codegenNode) {
  14965. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  14966. }
  14967. };
  14968. }
  14969. };
  14970. const transformModel = (dir, node, context) => {
  14971. const { exp, arg } = dir;
  14972. if (!exp) {
  14973. context.onError(createCompilerError(41 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  14974. return createTransformProps();
  14975. }
  14976. const rawExp = exp.loc.source;
  14977. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
  14978. // im SFC <script setup> inline mode, the exp may have been transformed into
  14979. // _unref(exp)
  14980. context.bindingMetadata[rawExp];
  14981. const maybeRef = !true /* SETUP_CONST */;
  14982. if (!expString.trim() ||
  14983. (!isMemberExpression(expString) && !maybeRef)) {
  14984. context.onError(createCompilerError(42 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  14985. return createTransformProps();
  14986. }
  14987. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  14988. const eventName = arg
  14989. ? isStaticExp(arg)
  14990. ? `onUpdate:${arg.content}`
  14991. : createCompoundExpression(['"onUpdate:" + ', arg])
  14992. : `onUpdate:modelValue`;
  14993. let assignmentExp;
  14994. const eventArg = context.isTS ? `($event: any)` : `$event`;
  14995. {
  14996. assignmentExp = createCompoundExpression([
  14997. `${eventArg} => ((`,
  14998. exp,
  14999. `) = $event)`
  15000. ]);
  15001. }
  15002. const props = [
  15003. // modelValue: foo
  15004. createObjectProperty(propName, dir.exp),
  15005. // "onUpdate:modelValue": $event => (foo = $event)
  15006. createObjectProperty(eventName, assignmentExp)
  15007. ];
  15008. // modelModifiers: { foo: true, "bar-baz": true }
  15009. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  15010. const modifiers = dir.modifiers
  15011. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  15012. .join(`, `);
  15013. const modifiersKey = arg
  15014. ? isStaticExp(arg)
  15015. ? `${arg.content}Modifiers`
  15016. : createCompoundExpression([arg, ' + "Modifiers"'])
  15017. : `modelModifiers`;
  15018. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
  15019. }
  15020. return createTransformProps(props);
  15021. };
  15022. function createTransformProps(props = []) {
  15023. return { props };
  15024. }
  15025. const seen$1 = new WeakSet();
  15026. const transformMemo = (node, context) => {
  15027. if (node.type === 1 /* ELEMENT */) {
  15028. const dir = findDir(node, 'memo');
  15029. if (!dir || seen$1.has(node)) {
  15030. return;
  15031. }
  15032. seen$1.add(node);
  15033. return () => {
  15034. const codegenNode = node.codegenNode ||
  15035. context.currentNode.codegenNode;
  15036. if (codegenNode && codegenNode.type === 13 /* VNODE_CALL */) {
  15037. // non-component sub tree should be turned into a block
  15038. if (node.tagType !== 1 /* COMPONENT */) {
  15039. makeBlock(codegenNode, context);
  15040. }
  15041. node.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
  15042. dir.exp,
  15043. createFunctionExpression(undefined, codegenNode),
  15044. `_cache`,
  15045. String(context.cached++)
  15046. ]);
  15047. }
  15048. };
  15049. }
  15050. };
  15051. function getBaseTransformPreset(prefixIdentifiers) {
  15052. return [
  15053. [
  15054. transformOnce,
  15055. transformIf,
  15056. transformMemo,
  15057. transformFor,
  15058. ...([]),
  15059. ...([transformExpression]
  15060. ),
  15061. transformSlotOutlet,
  15062. transformElement,
  15063. trackSlotScopes,
  15064. transformText
  15065. ],
  15066. {
  15067. on: transformOn,
  15068. bind: transformBind,
  15069. model: transformModel
  15070. }
  15071. ];
  15072. }
  15073. // we name it `baseCompile` so that higher order compilers like
  15074. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  15075. function baseCompile(template, options = {}) {
  15076. const onError = options.onError || defaultOnError;
  15077. const isModuleMode = options.mode === 'module';
  15078. /* istanbul ignore if */
  15079. {
  15080. if (options.prefixIdentifiers === true) {
  15081. onError(createCompilerError(46 /* X_PREFIX_ID_NOT_SUPPORTED */));
  15082. }
  15083. else if (isModuleMode) {
  15084. onError(createCompilerError(47 /* X_MODULE_MODE_NOT_SUPPORTED */));
  15085. }
  15086. }
  15087. const prefixIdentifiers = !true ;
  15088. if (options.cacheHandlers) {
  15089. onError(createCompilerError(48 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  15090. }
  15091. if (options.scopeId && !isModuleMode) {
  15092. onError(createCompilerError(49 /* X_SCOPE_ID_NOT_SUPPORTED */));
  15093. }
  15094. const ast = isString(template) ? baseParse(template, options) : template;
  15095. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  15096. transform(ast, extend({}, options, {
  15097. prefixIdentifiers,
  15098. nodeTransforms: [
  15099. ...nodeTransforms,
  15100. ...(options.nodeTransforms || []) // user transforms
  15101. ],
  15102. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  15103. )
  15104. }));
  15105. return generate(ast, extend({}, options, {
  15106. prefixIdentifiers
  15107. }));
  15108. }
  15109. const noopDirectiveTransform = () => ({ props: [] });
  15110. const V_MODEL_RADIO = Symbol(`vModelRadio` );
  15111. const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
  15112. const V_MODEL_TEXT = Symbol(`vModelText` );
  15113. const V_MODEL_SELECT = Symbol(`vModelSelect` );
  15114. const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
  15115. const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
  15116. const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
  15117. const V_SHOW = Symbol(`vShow` );
  15118. const TRANSITION$1 = Symbol(`Transition` );
  15119. const TRANSITION_GROUP = Symbol(`TransitionGroup` );
  15120. registerRuntimeHelpers({
  15121. [V_MODEL_RADIO]: `vModelRadio`,
  15122. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  15123. [V_MODEL_TEXT]: `vModelText`,
  15124. [V_MODEL_SELECT]: `vModelSelect`,
  15125. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  15126. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  15127. [V_ON_WITH_KEYS]: `withKeys`,
  15128. [V_SHOW]: `vShow`,
  15129. [TRANSITION$1]: `Transition`,
  15130. [TRANSITION_GROUP]: `TransitionGroup`
  15131. });
  15132. /* eslint-disable no-restricted-globals */
  15133. let decoder;
  15134. function decodeHtmlBrowser(raw, asAttr = false) {
  15135. if (!decoder) {
  15136. decoder = document.createElement('div');
  15137. }
  15138. if (asAttr) {
  15139. decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
  15140. return decoder.children[0].getAttribute('foo');
  15141. }
  15142. else {
  15143. decoder.innerHTML = raw;
  15144. return decoder.textContent;
  15145. }
  15146. }
  15147. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  15148. const parserOptions = {
  15149. isVoidTag,
  15150. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  15151. isPreTag: tag => tag === 'pre',
  15152. decodeEntities: decodeHtmlBrowser ,
  15153. isBuiltInComponent: (tag) => {
  15154. if (isBuiltInType(tag, `Transition`)) {
  15155. return TRANSITION$1;
  15156. }
  15157. else if (isBuiltInType(tag, `TransitionGroup`)) {
  15158. return TRANSITION_GROUP;
  15159. }
  15160. },
  15161. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  15162. getNamespace(tag, parent) {
  15163. let ns = parent ? parent.ns : 0 /* HTML */;
  15164. if (parent && ns === 2 /* MATH_ML */) {
  15165. if (parent.tag === 'annotation-xml') {
  15166. if (tag === 'svg') {
  15167. return 1 /* SVG */;
  15168. }
  15169. if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
  15170. a.name === 'encoding' &&
  15171. a.value != null &&
  15172. (a.value.content === 'text/html' ||
  15173. a.value.content === 'application/xhtml+xml'))) {
  15174. ns = 0 /* HTML */;
  15175. }
  15176. }
  15177. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  15178. tag !== 'mglyph' &&
  15179. tag !== 'malignmark') {
  15180. ns = 0 /* HTML */;
  15181. }
  15182. }
  15183. else if (parent && ns === 1 /* SVG */) {
  15184. if (parent.tag === 'foreignObject' ||
  15185. parent.tag === 'desc' ||
  15186. parent.tag === 'title') {
  15187. ns = 0 /* HTML */;
  15188. }
  15189. }
  15190. if (ns === 0 /* HTML */) {
  15191. if (tag === 'svg') {
  15192. return 1 /* SVG */;
  15193. }
  15194. if (tag === 'math') {
  15195. return 2 /* MATH_ML */;
  15196. }
  15197. }
  15198. return ns;
  15199. },
  15200. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  15201. getTextMode({ tag, ns }) {
  15202. if (ns === 0 /* HTML */) {
  15203. if (tag === 'textarea' || tag === 'title') {
  15204. return 1 /* RCDATA */;
  15205. }
  15206. if (isRawTextContainer(tag)) {
  15207. return 2 /* RAWTEXT */;
  15208. }
  15209. }
  15210. return 0 /* DATA */;
  15211. }
  15212. };
  15213. // Parse inline CSS strings for static style attributes into an object.
  15214. // This is a NodeTransform since it works on the static `style` attribute and
  15215. // converts it into a dynamic equivalent:
  15216. // style="color: red" -> :style='{ "color": "red" }'
  15217. // It is then processed by `transformElement` and included in the generated
  15218. // props.
  15219. const transformStyle = node => {
  15220. if (node.type === 1 /* ELEMENT */) {
  15221. node.props.forEach((p, i) => {
  15222. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  15223. // replace p with an expression node
  15224. node.props[i] = {
  15225. type: 7 /* DIRECTIVE */,
  15226. name: `bind`,
  15227. arg: createSimpleExpression(`style`, true, p.loc),
  15228. exp: parseInlineCSS(p.value.content, p.loc),
  15229. modifiers: [],
  15230. loc: p.loc
  15231. };
  15232. }
  15233. });
  15234. }
  15235. };
  15236. const parseInlineCSS = (cssText, loc) => {
  15237. const normalized = parseStringStyle(cssText);
  15238. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
  15239. };
  15240. function createDOMCompilerError(code, loc) {
  15241. return createCompilerError(code, loc, DOMErrorMessages );
  15242. }
  15243. const DOMErrorMessages = {
  15244. [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  15245. [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  15246. [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  15247. [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  15248. [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  15249. [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  15250. [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.`,
  15251. [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  15252. [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  15253. [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  15254. [60 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  15255. };
  15256. const transformVHtml = (dir, node, context) => {
  15257. const { exp, loc } = dir;
  15258. if (!exp) {
  15259. context.onError(createDOMCompilerError(50 /* X_V_HTML_NO_EXPRESSION */, loc));
  15260. }
  15261. if (node.children.length) {
  15262. context.onError(createDOMCompilerError(51 /* X_V_HTML_WITH_CHILDREN */, loc));
  15263. node.children.length = 0;
  15264. }
  15265. return {
  15266. props: [
  15267. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  15268. ]
  15269. };
  15270. };
  15271. const transformVText = (dir, node, context) => {
  15272. const { exp, loc } = dir;
  15273. if (!exp) {
  15274. context.onError(createDOMCompilerError(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
  15275. }
  15276. if (node.children.length) {
  15277. context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
  15278. node.children.length = 0;
  15279. }
  15280. return {
  15281. props: [
  15282. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  15283. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  15284. : createSimpleExpression('', true))
  15285. ]
  15286. };
  15287. };
  15288. const transformModel$1 = (dir, node, context) => {
  15289. const baseResult = transformModel(dir, node, context);
  15290. // base transform has errors OR component v-model (only need props)
  15291. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  15292. return baseResult;
  15293. }
  15294. if (dir.arg) {
  15295. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  15296. }
  15297. function checkDuplicatedValue() {
  15298. const value = findProp(node, 'value');
  15299. if (value) {
  15300. context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  15301. }
  15302. }
  15303. const { tag } = node;
  15304. const isCustomElement = context.isCustomElement(tag);
  15305. if (tag === 'input' ||
  15306. tag === 'textarea' ||
  15307. tag === 'select' ||
  15308. isCustomElement) {
  15309. let directiveToUse = V_MODEL_TEXT;
  15310. let isInvalidType = false;
  15311. if (tag === 'input' || isCustomElement) {
  15312. const type = findProp(node, `type`);
  15313. if (type) {
  15314. if (type.type === 7 /* DIRECTIVE */) {
  15315. // :type="foo"
  15316. directiveToUse = V_MODEL_DYNAMIC;
  15317. }
  15318. else if (type.value) {
  15319. switch (type.value.content) {
  15320. case 'radio':
  15321. directiveToUse = V_MODEL_RADIO;
  15322. break;
  15323. case 'checkbox':
  15324. directiveToUse = V_MODEL_CHECKBOX;
  15325. break;
  15326. case 'file':
  15327. isInvalidType = true;
  15328. context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  15329. break;
  15330. default:
  15331. // text type
  15332. checkDuplicatedValue();
  15333. break;
  15334. }
  15335. }
  15336. }
  15337. else if (hasDynamicKeyVBind(node)) {
  15338. // element has bindings with dynamic keys, which can possibly contain
  15339. // "type".
  15340. directiveToUse = V_MODEL_DYNAMIC;
  15341. }
  15342. else {
  15343. // text type
  15344. checkDuplicatedValue();
  15345. }
  15346. }
  15347. else if (tag === 'select') {
  15348. directiveToUse = V_MODEL_SELECT;
  15349. }
  15350. else {
  15351. // textarea
  15352. checkDuplicatedValue();
  15353. }
  15354. // inject runtime directive
  15355. // by returning the helper symbol via needRuntime
  15356. // the import will replaced a resolveDirective call.
  15357. if (!isInvalidType) {
  15358. baseResult.needRuntime = context.helper(directiveToUse);
  15359. }
  15360. }
  15361. else {
  15362. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  15363. }
  15364. // native vmodel doesn't need the `modelValue` props since they are also
  15365. // passed to the runtime as `binding.value`. removing it reduces code size.
  15366. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  15367. p.key.content === 'modelValue'));
  15368. return baseResult;
  15369. };
  15370. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  15371. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  15372. // event propagation management
  15373. `stop,prevent,self,` +
  15374. // system modifiers + exact
  15375. `ctrl,shift,alt,meta,exact,` +
  15376. // mouse
  15377. `middle`);
  15378. // left & right could be mouse or key modifiers based on event type
  15379. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  15380. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  15381. const resolveModifiers = (key, modifiers, context, loc) => {
  15382. const keyModifiers = [];
  15383. const nonKeyModifiers = [];
  15384. const eventOptionModifiers = [];
  15385. for (let i = 0; i < modifiers.length; i++) {
  15386. const modifier = modifiers[i];
  15387. if (isEventOptionModifier(modifier)) {
  15388. // eventOptionModifiers: modifiers for addEventListener() options,
  15389. // e.g. .passive & .capture
  15390. eventOptionModifiers.push(modifier);
  15391. }
  15392. else {
  15393. // runtimeModifiers: modifiers that needs runtime guards
  15394. if (maybeKeyModifier(modifier)) {
  15395. if (isStaticExp(key)) {
  15396. if (isKeyboardEvent(key.content)) {
  15397. keyModifiers.push(modifier);
  15398. }
  15399. else {
  15400. nonKeyModifiers.push(modifier);
  15401. }
  15402. }
  15403. else {
  15404. keyModifiers.push(modifier);
  15405. nonKeyModifiers.push(modifier);
  15406. }
  15407. }
  15408. else {
  15409. if (isNonKeyModifier(modifier)) {
  15410. nonKeyModifiers.push(modifier);
  15411. }
  15412. else {
  15413. keyModifiers.push(modifier);
  15414. }
  15415. }
  15416. }
  15417. }
  15418. return {
  15419. keyModifiers,
  15420. nonKeyModifiers,
  15421. eventOptionModifiers
  15422. };
  15423. };
  15424. const transformClick = (key, event) => {
  15425. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  15426. return isStaticClick
  15427. ? createSimpleExpression(event, true)
  15428. : key.type !== 4 /* SIMPLE_EXPRESSION */
  15429. ? createCompoundExpression([
  15430. `(`,
  15431. key,
  15432. `) === "onClick" ? "${event}" : (`,
  15433. key,
  15434. `)`
  15435. ])
  15436. : key;
  15437. };
  15438. const transformOn$1 = (dir, node, context) => {
  15439. return transformOn(dir, node, context, baseResult => {
  15440. const { modifiers } = dir;
  15441. if (!modifiers.length)
  15442. return baseResult;
  15443. let { key, value: handlerExp } = baseResult.props[0];
  15444. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  15445. // normalize click.right and click.middle since they don't actually fire
  15446. if (nonKeyModifiers.includes('right')) {
  15447. key = transformClick(key, `onContextmenu`);
  15448. }
  15449. if (nonKeyModifiers.includes('middle')) {
  15450. key = transformClick(key, `onMouseup`);
  15451. }
  15452. if (nonKeyModifiers.length) {
  15453. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  15454. handlerExp,
  15455. JSON.stringify(nonKeyModifiers)
  15456. ]);
  15457. }
  15458. if (keyModifiers.length &&
  15459. // if event name is dynamic, always wrap with keys guard
  15460. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  15461. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  15462. handlerExp,
  15463. JSON.stringify(keyModifiers)
  15464. ]);
  15465. }
  15466. if (eventOptionModifiers.length) {
  15467. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  15468. key = isStaticExp(key)
  15469. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  15470. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  15471. }
  15472. return {
  15473. props: [createObjectProperty(key, handlerExp)]
  15474. };
  15475. });
  15476. };
  15477. const transformShow = (dir, node, context) => {
  15478. const { exp, loc } = dir;
  15479. if (!exp) {
  15480. context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
  15481. }
  15482. return {
  15483. props: [],
  15484. needRuntime: context.helper(V_SHOW)
  15485. };
  15486. };
  15487. const warnTransitionChildren = (node, context) => {
  15488. if (node.type === 1 /* ELEMENT */ &&
  15489. node.tagType === 1 /* COMPONENT */) {
  15490. const component = context.isBuiltInComponent(node.tag);
  15491. if (component === TRANSITION$1) {
  15492. return () => {
  15493. if (node.children.length && hasMultipleChildren(node)) {
  15494. context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
  15495. start: node.children[0].loc.start,
  15496. end: node.children[node.children.length - 1].loc.end,
  15497. source: ''
  15498. }));
  15499. }
  15500. };
  15501. }
  15502. }
  15503. };
  15504. function hasMultipleChildren(node) {
  15505. // #1352 filter out potential comment nodes.
  15506. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */ &&
  15507. !(c.type === 2 /* TEXT */ && !c.content.trim())));
  15508. const child = children[0];
  15509. return (children.length !== 1 ||
  15510. child.type === 11 /* FOR */ ||
  15511. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  15512. }
  15513. const ignoreSideEffectTags = (node, context) => {
  15514. if (node.type === 1 /* ELEMENT */ &&
  15515. node.tagType === 0 /* ELEMENT */ &&
  15516. (node.tag === 'script' || node.tag === 'style')) {
  15517. context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  15518. context.removeNode();
  15519. }
  15520. };
  15521. const DOMNodeTransforms = [
  15522. transformStyle,
  15523. ...([warnTransitionChildren] )
  15524. ];
  15525. const DOMDirectiveTransforms = {
  15526. cloak: noopDirectiveTransform,
  15527. html: transformVHtml,
  15528. text: transformVText,
  15529. model: transformModel$1,
  15530. on: transformOn$1,
  15531. show: transformShow
  15532. };
  15533. function compile$1(template, options = {}) {
  15534. return baseCompile(template, extend({}, parserOptions, options, {
  15535. nodeTransforms: [
  15536. // ignore <script> and <tag>
  15537. // this is not put inside DOMNodeTransforms because that list is used
  15538. // by compiler-ssr to generate vnode fallback branches
  15539. ignoreSideEffectTags,
  15540. ...DOMNodeTransforms,
  15541. ...(options.nodeTransforms || [])
  15542. ],
  15543. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  15544. transformHoist: null
  15545. }));
  15546. }
  15547. // This entry is the "full-build" that includes both the runtime
  15548. {
  15549. initDev();
  15550. }
  15551. const compileCache = Object.create(null);
  15552. function compileToFunction(template, options) {
  15553. if (!isString(template)) {
  15554. if (template.nodeType) {
  15555. template = template.innerHTML;
  15556. }
  15557. else {
  15558. warn$1(`invalid template option: `, template);
  15559. return NOOP;
  15560. }
  15561. }
  15562. const key = template;
  15563. const cached = compileCache[key];
  15564. if (cached) {
  15565. return cached;
  15566. }
  15567. if (template[0] === '#') {
  15568. const el = document.querySelector(template);
  15569. if (!el) {
  15570. warn$1(`Template element not found or is empty: ${template}`);
  15571. }
  15572. // __UNSAFE__
  15573. // Reason: potential execution of JS expressions in in-DOM template.
  15574. // The user must make sure the in-DOM template is trusted. If it's rendered
  15575. // by the server, the template should not contain any user data.
  15576. template = el ? el.innerHTML : ``;
  15577. }
  15578. const { code } = compile$1(template, extend({
  15579. hoistStatic: true,
  15580. onError: onError ,
  15581. onWarn: e => onError(e, true)
  15582. }, options));
  15583. function onError(err, asWarning = false) {
  15584. const message = asWarning
  15585. ? err.message
  15586. : `Template compilation error: ${err.message}`;
  15587. const codeFrame = err.loc &&
  15588. generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
  15589. warn$1(codeFrame ? `${message}\n${codeFrame}` : message);
  15590. }
  15591. // The wildcard import results in a huge object with every export
  15592. // with keys that cannot be mangled, and can be quite heavy size-wise.
  15593. // In the global build we know `Vue` is available globally so we can avoid
  15594. // the wildcard object.
  15595. const render = (new Function('Vue', code)(runtimeDom));
  15596. render._rc = true;
  15597. return (compileCache[key] = render);
  15598. }
  15599. registerRuntimeCompiler(compileToFunction);
  15600. export { BaseTransition, Comment, EffectScope, Fragment, KeepAlive, ReactiveEffect, Static, Suspense, Teleport, Text, Transition, TransitionGroup, VueElement, callWithAsyncErrorHandling, callWithErrorHandling, camelize, capitalize, cloneVNode, compatUtils, compileToFunction as compile, computed, createApp, createBlock, createCommentVNode, createElementBlock, createBaseVNode as createElementVNode, createHydrationRenderer, createPropsRestProxy, createRenderer, createSSRApp, createSlots, createStaticVNode, createTextVNode, createVNode, customRef, defineAsyncComponent, defineComponent, defineCustomElement, defineEmits, defineExpose, defineProps, defineSSRCustomElement, devtools, effect, effectScope, getCurrentInstance, getCurrentScope, getTransitionRawChildren, guardReactiveProps, h, handleError, hydrate, initCustomFormatter, initDirectivesForSSR, inject, isMemoSame, isProxy, isReactive, isReadonly, isRef, isRuntimeOnly, 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 };