vue-i18n.esm-browser.js 227 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541
  1. /*!
  2. * vue-i18n v9.8.0
  3. * (c) 2023 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. import { createVNode, Text, ref, computed, watch, getCurrentInstance, Fragment, defineComponent, h, effectScope, inject, onMounted, onUnmounted, shallowRef, onBeforeMount, isRef } from 'vue';
  7. /**
  8. * Original Utilities
  9. * written by kazuya kawaguchi
  10. */
  11. const inBrowser = typeof window !== 'undefined';
  12. let mark;
  13. let measure;
  14. {
  15. const perf = inBrowser && window.performance;
  16. if (perf &&
  17. perf.mark &&
  18. perf.measure &&
  19. perf.clearMarks &&
  20. // @ts-ignore browser compat
  21. perf.clearMeasures) {
  22. mark = (tag) => {
  23. perf.mark(tag);
  24. };
  25. measure = (name, startTag, endTag) => {
  26. perf.measure(name, startTag, endTag);
  27. perf.clearMarks(startTag);
  28. perf.clearMarks(endTag);
  29. };
  30. }
  31. }
  32. const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
  33. /* eslint-disable */
  34. function format$1(message, ...args) {
  35. if (args.length === 1 && isObject(args[0])) {
  36. args = args[0];
  37. }
  38. if (!args || !args.hasOwnProperty) {
  39. args = {};
  40. }
  41. return message.replace(RE_ARGS, (match, identifier) => {
  42. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  43. });
  44. }
  45. const makeSymbol = (name, shareable = false) => !shareable ? Symbol(name) : Symbol.for(name);
  46. const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
  47. const friendlyJSONstringify = (json) => JSON.stringify(json)
  48. .replace(/\u2028/g, '\\u2028')
  49. .replace(/\u2029/g, '\\u2029')
  50. .replace(/\u0027/g, '\\u0027');
  51. const isNumber = (val) => typeof val === 'number' && isFinite(val);
  52. const isDate = (val) => toTypeString(val) === '[object Date]';
  53. const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
  54. const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
  55. const assign = Object.assign;
  56. let _globalThis;
  57. const getGlobalThis = () => {
  58. // prettier-ignore
  59. return (_globalThis ||
  60. (_globalThis =
  61. typeof globalThis !== 'undefined'
  62. ? globalThis
  63. : typeof self !== 'undefined'
  64. ? self
  65. : typeof window !== 'undefined'
  66. ? window
  67. : typeof global !== 'undefined'
  68. ? global
  69. : {}));
  70. };
  71. function escapeHtml(rawText) {
  72. return rawText
  73. .replace(/</g, '&lt;')
  74. .replace(/>/g, '&gt;')
  75. .replace(/"/g, '&quot;')
  76. .replace(/'/g, '&apos;');
  77. }
  78. const hasOwnProperty = Object.prototype.hasOwnProperty;
  79. function hasOwn(obj, key) {
  80. return hasOwnProperty.call(obj, key);
  81. }
  82. /* eslint-enable */
  83. /**
  84. * Useful Utilities By Evan you
  85. * Modified by kazuya kawaguchi
  86. * MIT License
  87. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
  88. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
  89. */
  90. const isArray = Array.isArray;
  91. const isFunction = (val) => typeof val === 'function';
  92. const isString = (val) => typeof val === 'string';
  93. const isBoolean = (val) => typeof val === 'boolean';
  94. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  95. const isObject = (val) => val !== null && typeof val === 'object';
  96. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  97. const isPromise = (val) => {
  98. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  99. };
  100. const objectToString = Object.prototype.toString;
  101. const toTypeString = (value) => objectToString.call(value);
  102. const isPlainObject = (val) => {
  103. if (!isObject(val))
  104. return false;
  105. const proto = Object.getPrototypeOf(val);
  106. return proto === null || proto.constructor === Object;
  107. };
  108. // for converting list and named values to displayed strings.
  109. const toDisplayString = (val) => {
  110. return val == null
  111. ? ''
  112. : isArray(val) || (isPlainObject(val) && val.toString === objectToString)
  113. ? JSON.stringify(val, null, 2)
  114. : String(val);
  115. };
  116. function join(items, separator = '') {
  117. return items.reduce((str, item, index) => (index === 0 ? str + item : str + separator + item), '');
  118. }
  119. const RANGE = 2;
  120. function generateCodeFrame(source, start = 0, end = source.length) {
  121. const lines = source.split(/\r?\n/);
  122. let count = 0;
  123. const res = [];
  124. for (let i = 0; i < lines.length; i++) {
  125. count += lines[i].length + 1;
  126. if (count >= start) {
  127. for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
  128. if (j < 0 || j >= lines.length)
  129. continue;
  130. const line = j + 1;
  131. res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
  132. const lineLength = lines[j].length;
  133. if (j === i) {
  134. // push underline
  135. const pad = start - (count - lineLength) + 1;
  136. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  137. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  138. }
  139. else if (j > i) {
  140. if (end > count) {
  141. const length = Math.max(Math.min(end - count, lineLength), 1);
  142. res.push(` | ` + '^'.repeat(length));
  143. }
  144. count += lineLength + 1;
  145. }
  146. }
  147. break;
  148. }
  149. }
  150. return res.join('\n');
  151. }
  152. function incrementer(code) {
  153. let current = code;
  154. return () => ++current;
  155. }
  156. function warn(msg, err) {
  157. if (typeof console !== 'undefined') {
  158. console.warn(`[intlify] ` + msg);
  159. /* istanbul ignore if */
  160. if (err) {
  161. console.warn(err.stack);
  162. }
  163. }
  164. }
  165. const hasWarned = {};
  166. function warnOnce(msg) {
  167. if (!hasWarned[msg]) {
  168. hasWarned[msg] = true;
  169. warn(msg);
  170. }
  171. }
  172. /**
  173. * Event emitter, forked from the below:
  174. * - original repository url: https://github.com/developit/mitt
  175. * - code url: https://github.com/developit/mitt/blob/master/src/index.ts
  176. * - author: Jason Miller (https://github.com/developit)
  177. * - license: MIT
  178. */
  179. /**
  180. * Create a event emitter
  181. *
  182. * @returns An event emitter
  183. */
  184. function createEmitter() {
  185. const events = new Map();
  186. const emitter = {
  187. events,
  188. on(event, handler) {
  189. const handlers = events.get(event);
  190. const added = handlers && handlers.push(handler);
  191. if (!added) {
  192. events.set(event, [handler]);
  193. }
  194. },
  195. off(event, handler) {
  196. const handlers = events.get(event);
  197. if (handlers) {
  198. handlers.splice(handlers.indexOf(handler) >>> 0, 1);
  199. }
  200. },
  201. emit(event, payload) {
  202. (events.get(event) || [])
  203. .slice()
  204. .map(handler => handler(payload));
  205. (events.get('*') || [])
  206. .slice()
  207. .map(handler => handler(event, payload));
  208. }
  209. };
  210. return emitter;
  211. }
  212. const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
  213. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  214. function deepCopy(src, des) {
  215. // src and des should both be objects, and none of them can be a array
  216. if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
  217. throw new Error('Invalid value');
  218. }
  219. for (const key in src) {
  220. if (hasOwn(src, key)) {
  221. if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
  222. // replace with src[key] when:
  223. // src[key] or des[key] is not an object, or
  224. // src[key] or des[key] is an array
  225. des[key] = src[key];
  226. }
  227. else {
  228. // src[key] and des[key] are both objects, merge them
  229. deepCopy(src[key], des[key]);
  230. }
  231. }
  232. }
  233. }
  234. function createPosition(line, column, offset) {
  235. return { line, column, offset };
  236. }
  237. function createLocation(start, end, source) {
  238. const loc = { start, end };
  239. if (source != null) {
  240. loc.source = source;
  241. }
  242. return loc;
  243. }
  244. const CompileErrorCodes = {
  245. // tokenizer error codes
  246. EXPECTED_TOKEN: 1,
  247. INVALID_TOKEN_IN_PLACEHOLDER: 2,
  248. UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
  249. UNKNOWN_ESCAPE_SEQUENCE: 4,
  250. INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
  251. UNBALANCED_CLOSING_BRACE: 6,
  252. UNTERMINATED_CLOSING_BRACE: 7,
  253. EMPTY_PLACEHOLDER: 8,
  254. NOT_ALLOW_NEST_PLACEHOLDER: 9,
  255. INVALID_LINKED_FORMAT: 10,
  256. // parser error codes
  257. MUST_HAVE_MESSAGES_IN_PLURAL: 11,
  258. UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
  259. UNEXPECTED_EMPTY_LINKED_KEY: 13,
  260. UNEXPECTED_LEXICAL_ANALYSIS: 14,
  261. // generator error codes
  262. UNHANDLED_CODEGEN_NODE_TYPE: 15,
  263. // minifier error codes
  264. UNHANDLED_MINIFIER_NODE_TYPE: 16,
  265. // Special value for higher-order compilers to pick up the last code
  266. // to avoid collision of error codes. This should always be kept as the last
  267. // item.
  268. __EXTEND_POINT__: 17
  269. };
  270. /** @internal */
  271. const errorMessages$2 = {
  272. // tokenizer error messages
  273. [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
  274. [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
  275. [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
  276. [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
  277. [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
  278. [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
  279. [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
  280. [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
  281. [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
  282. [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
  283. // parser error messages
  284. [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
  285. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
  286. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
  287. [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
  288. // generator error messages
  289. [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
  290. // minimizer error messages
  291. [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
  292. };
  293. function createCompileError(code, loc, options = {}) {
  294. const { domain, messages, args } = options;
  295. const msg = format$1((messages || errorMessages$2)[code] || '', ...(args || []))
  296. ;
  297. const error = new SyntaxError(String(msg));
  298. error.code = code;
  299. if (loc) {
  300. error.location = loc;
  301. }
  302. error.domain = domain;
  303. return error;
  304. }
  305. /** @internal */
  306. function defaultOnError(error) {
  307. throw error;
  308. }
  309. const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
  310. const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
  311. const CHAR_SP = ' ';
  312. const CHAR_CR = '\r';
  313. const CHAR_LF = '\n';
  314. const CHAR_LS = String.fromCharCode(0x2028);
  315. const CHAR_PS = String.fromCharCode(0x2029);
  316. function createScanner(str) {
  317. const _buf = str;
  318. let _index = 0;
  319. let _line = 1;
  320. let _column = 1;
  321. let _peekOffset = 0;
  322. const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
  323. const isLF = (index) => _buf[index] === CHAR_LF;
  324. const isPS = (index) => _buf[index] === CHAR_PS;
  325. const isLS = (index) => _buf[index] === CHAR_LS;
  326. const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
  327. const index = () => _index;
  328. const line = () => _line;
  329. const column = () => _column;
  330. const peekOffset = () => _peekOffset;
  331. const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
  332. const currentChar = () => charAt(_index);
  333. const currentPeek = () => charAt(_index + _peekOffset);
  334. function next() {
  335. _peekOffset = 0;
  336. if (isLineEnd(_index)) {
  337. _line++;
  338. _column = 0;
  339. }
  340. if (isCRLF(_index)) {
  341. _index++;
  342. }
  343. _index++;
  344. _column++;
  345. return _buf[_index];
  346. }
  347. function peek() {
  348. if (isCRLF(_index + _peekOffset)) {
  349. _peekOffset++;
  350. }
  351. _peekOffset++;
  352. return _buf[_index + _peekOffset];
  353. }
  354. function reset() {
  355. _index = 0;
  356. _line = 1;
  357. _column = 1;
  358. _peekOffset = 0;
  359. }
  360. function resetPeek(offset = 0) {
  361. _peekOffset = offset;
  362. }
  363. function skipToPeek() {
  364. const target = _index + _peekOffset;
  365. // eslint-disable-next-line no-unmodified-loop-condition
  366. while (target !== _index) {
  367. next();
  368. }
  369. _peekOffset = 0;
  370. }
  371. return {
  372. index,
  373. line,
  374. column,
  375. peekOffset,
  376. charAt,
  377. currentChar,
  378. currentPeek,
  379. next,
  380. peek,
  381. reset,
  382. resetPeek,
  383. skipToPeek
  384. };
  385. }
  386. const EOF = undefined;
  387. const DOT = '.';
  388. const LITERAL_DELIMITER = "'";
  389. const ERROR_DOMAIN$3 = 'tokenizer';
  390. function createTokenizer(source, options = {}) {
  391. const location = options.location !== false;
  392. const _scnr = createScanner(source);
  393. const currentOffset = () => _scnr.index();
  394. const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
  395. const _initLoc = currentPosition();
  396. const _initOffset = currentOffset();
  397. const _context = {
  398. currentType: 14 /* TokenTypes.EOF */,
  399. offset: _initOffset,
  400. startLoc: _initLoc,
  401. endLoc: _initLoc,
  402. lastType: 14 /* TokenTypes.EOF */,
  403. lastOffset: _initOffset,
  404. lastStartLoc: _initLoc,
  405. lastEndLoc: _initLoc,
  406. braceNest: 0,
  407. inLinked: false,
  408. text: ''
  409. };
  410. const context = () => _context;
  411. const { onError } = options;
  412. function emitError(code, pos, offset, ...args) {
  413. const ctx = context();
  414. pos.column += offset;
  415. pos.offset += offset;
  416. if (onError) {
  417. const loc = location ? createLocation(ctx.startLoc, pos) : null;
  418. const err = createCompileError(code, loc, {
  419. domain: ERROR_DOMAIN$3,
  420. args
  421. });
  422. onError(err);
  423. }
  424. }
  425. function getToken(context, type, value) {
  426. context.endLoc = currentPosition();
  427. context.currentType = type;
  428. const token = { type };
  429. if (location) {
  430. token.loc = createLocation(context.startLoc, context.endLoc);
  431. }
  432. if (value != null) {
  433. token.value = value;
  434. }
  435. return token;
  436. }
  437. const getEndToken = (context) => getToken(context, 14 /* TokenTypes.EOF */);
  438. function eat(scnr, ch) {
  439. if (scnr.currentChar() === ch) {
  440. scnr.next();
  441. return ch;
  442. }
  443. else {
  444. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  445. return '';
  446. }
  447. }
  448. function peekSpaces(scnr) {
  449. let buf = '';
  450. while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
  451. buf += scnr.currentPeek();
  452. scnr.peek();
  453. }
  454. return buf;
  455. }
  456. function skipSpaces(scnr) {
  457. const buf = peekSpaces(scnr);
  458. scnr.skipToPeek();
  459. return buf;
  460. }
  461. function isIdentifierStart(ch) {
  462. if (ch === EOF) {
  463. return false;
  464. }
  465. const cc = ch.charCodeAt(0);
  466. return ((cc >= 97 && cc <= 122) || // a-z
  467. (cc >= 65 && cc <= 90) || // A-Z
  468. cc === 95 // _
  469. );
  470. }
  471. function isNumberStart(ch) {
  472. if (ch === EOF) {
  473. return false;
  474. }
  475. const cc = ch.charCodeAt(0);
  476. return cc >= 48 && cc <= 57; // 0-9
  477. }
  478. function isNamedIdentifierStart(scnr, context) {
  479. const { currentType } = context;
  480. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  481. return false;
  482. }
  483. peekSpaces(scnr);
  484. const ret = isIdentifierStart(scnr.currentPeek());
  485. scnr.resetPeek();
  486. return ret;
  487. }
  488. function isListIdentifierStart(scnr, context) {
  489. const { currentType } = context;
  490. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  491. return false;
  492. }
  493. peekSpaces(scnr);
  494. const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
  495. const ret = isNumberStart(ch);
  496. scnr.resetPeek();
  497. return ret;
  498. }
  499. function isLiteralStart(scnr, context) {
  500. const { currentType } = context;
  501. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  502. return false;
  503. }
  504. peekSpaces(scnr);
  505. const ret = scnr.currentPeek() === LITERAL_DELIMITER;
  506. scnr.resetPeek();
  507. return ret;
  508. }
  509. function isLinkedDotStart(scnr, context) {
  510. const { currentType } = context;
  511. if (currentType !== 8 /* TokenTypes.LinkedAlias */) {
  512. return false;
  513. }
  514. peekSpaces(scnr);
  515. const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
  516. scnr.resetPeek();
  517. return ret;
  518. }
  519. function isLinkedModifierStart(scnr, context) {
  520. const { currentType } = context;
  521. if (currentType !== 9 /* TokenTypes.LinkedDot */) {
  522. return false;
  523. }
  524. peekSpaces(scnr);
  525. const ret = isIdentifierStart(scnr.currentPeek());
  526. scnr.resetPeek();
  527. return ret;
  528. }
  529. function isLinkedDelimiterStart(scnr, context) {
  530. const { currentType } = context;
  531. if (!(currentType === 8 /* TokenTypes.LinkedAlias */ ||
  532. currentType === 12 /* TokenTypes.LinkedModifier */)) {
  533. return false;
  534. }
  535. peekSpaces(scnr);
  536. const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
  537. scnr.resetPeek();
  538. return ret;
  539. }
  540. function isLinkedReferStart(scnr, context) {
  541. const { currentType } = context;
  542. if (currentType !== 10 /* TokenTypes.LinkedDelimiter */) {
  543. return false;
  544. }
  545. const fn = () => {
  546. const ch = scnr.currentPeek();
  547. if (ch === "{" /* TokenChars.BraceLeft */) {
  548. return isIdentifierStart(scnr.peek());
  549. }
  550. else if (ch === "@" /* TokenChars.LinkedAlias */ ||
  551. ch === "%" /* TokenChars.Modulo */ ||
  552. ch === "|" /* TokenChars.Pipe */ ||
  553. ch === ":" /* TokenChars.LinkedDelimiter */ ||
  554. ch === "." /* TokenChars.LinkedDot */ ||
  555. ch === CHAR_SP ||
  556. !ch) {
  557. return false;
  558. }
  559. else if (ch === CHAR_LF) {
  560. scnr.peek();
  561. return fn();
  562. }
  563. else {
  564. // other characters
  565. return isIdentifierStart(ch);
  566. }
  567. };
  568. const ret = fn();
  569. scnr.resetPeek();
  570. return ret;
  571. }
  572. function isPluralStart(scnr) {
  573. peekSpaces(scnr);
  574. const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
  575. scnr.resetPeek();
  576. return ret;
  577. }
  578. function detectModuloStart(scnr) {
  579. const spaces = peekSpaces(scnr);
  580. const ret = scnr.currentPeek() === "%" /* TokenChars.Modulo */ &&
  581. scnr.peek() === "{" /* TokenChars.BraceLeft */;
  582. scnr.resetPeek();
  583. return {
  584. isModulo: ret,
  585. hasSpace: spaces.length > 0
  586. };
  587. }
  588. function isTextStart(scnr, reset = true) {
  589. const fn = (hasSpace = false, prev = '', detectModulo = false) => {
  590. const ch = scnr.currentPeek();
  591. if (ch === "{" /* TokenChars.BraceLeft */) {
  592. return prev === "%" /* TokenChars.Modulo */ ? false : hasSpace;
  593. }
  594. else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
  595. return prev === "%" /* TokenChars.Modulo */ ? true : hasSpace;
  596. }
  597. else if (ch === "%" /* TokenChars.Modulo */) {
  598. scnr.peek();
  599. return fn(hasSpace, "%" /* TokenChars.Modulo */, true);
  600. }
  601. else if (ch === "|" /* TokenChars.Pipe */) {
  602. return prev === "%" /* TokenChars.Modulo */ || detectModulo
  603. ? true
  604. : !(prev === CHAR_SP || prev === CHAR_LF);
  605. }
  606. else if (ch === CHAR_SP) {
  607. scnr.peek();
  608. return fn(true, CHAR_SP, detectModulo);
  609. }
  610. else if (ch === CHAR_LF) {
  611. scnr.peek();
  612. return fn(true, CHAR_LF, detectModulo);
  613. }
  614. else {
  615. return true;
  616. }
  617. };
  618. const ret = fn();
  619. reset && scnr.resetPeek();
  620. return ret;
  621. }
  622. function takeChar(scnr, fn) {
  623. const ch = scnr.currentChar();
  624. if (ch === EOF) {
  625. return EOF;
  626. }
  627. if (fn(ch)) {
  628. scnr.next();
  629. return ch;
  630. }
  631. return null;
  632. }
  633. function takeIdentifierChar(scnr) {
  634. const closure = (ch) => {
  635. const cc = ch.charCodeAt(0);
  636. return ((cc >= 97 && cc <= 122) || // a-z
  637. (cc >= 65 && cc <= 90) || // A-Z
  638. (cc >= 48 && cc <= 57) || // 0-9
  639. cc === 95 || // _
  640. cc === 36 // $
  641. );
  642. };
  643. return takeChar(scnr, closure);
  644. }
  645. function takeDigit(scnr) {
  646. const closure = (ch) => {
  647. const cc = ch.charCodeAt(0);
  648. return cc >= 48 && cc <= 57; // 0-9
  649. };
  650. return takeChar(scnr, closure);
  651. }
  652. function takeHexDigit(scnr) {
  653. const closure = (ch) => {
  654. const cc = ch.charCodeAt(0);
  655. return ((cc >= 48 && cc <= 57) || // 0-9
  656. (cc >= 65 && cc <= 70) || // A-F
  657. (cc >= 97 && cc <= 102)); // a-f
  658. };
  659. return takeChar(scnr, closure);
  660. }
  661. function getDigits(scnr) {
  662. let ch = '';
  663. let num = '';
  664. while ((ch = takeDigit(scnr))) {
  665. num += ch;
  666. }
  667. return num;
  668. }
  669. function readModulo(scnr) {
  670. skipSpaces(scnr);
  671. const ch = scnr.currentChar();
  672. if (ch !== "%" /* TokenChars.Modulo */) {
  673. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  674. }
  675. scnr.next();
  676. return "%" /* TokenChars.Modulo */;
  677. }
  678. function readText(scnr) {
  679. let buf = '';
  680. while (true) {
  681. const ch = scnr.currentChar();
  682. if (ch === "{" /* TokenChars.BraceLeft */ ||
  683. ch === "}" /* TokenChars.BraceRight */ ||
  684. ch === "@" /* TokenChars.LinkedAlias */ ||
  685. ch === "|" /* TokenChars.Pipe */ ||
  686. !ch) {
  687. break;
  688. }
  689. else if (ch === "%" /* TokenChars.Modulo */) {
  690. if (isTextStart(scnr)) {
  691. buf += ch;
  692. scnr.next();
  693. }
  694. else {
  695. break;
  696. }
  697. }
  698. else if (ch === CHAR_SP || ch === CHAR_LF) {
  699. if (isTextStart(scnr)) {
  700. buf += ch;
  701. scnr.next();
  702. }
  703. else if (isPluralStart(scnr)) {
  704. break;
  705. }
  706. else {
  707. buf += ch;
  708. scnr.next();
  709. }
  710. }
  711. else {
  712. buf += ch;
  713. scnr.next();
  714. }
  715. }
  716. return buf;
  717. }
  718. function readNamedIdentifier(scnr) {
  719. skipSpaces(scnr);
  720. let ch = '';
  721. let name = '';
  722. while ((ch = takeIdentifierChar(scnr))) {
  723. name += ch;
  724. }
  725. if (scnr.currentChar() === EOF) {
  726. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  727. }
  728. return name;
  729. }
  730. function readListIdentifier(scnr) {
  731. skipSpaces(scnr);
  732. let value = '';
  733. if (scnr.currentChar() === '-') {
  734. scnr.next();
  735. value += `-${getDigits(scnr)}`;
  736. }
  737. else {
  738. value += getDigits(scnr);
  739. }
  740. if (scnr.currentChar() === EOF) {
  741. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  742. }
  743. return value;
  744. }
  745. function readLiteral(scnr) {
  746. skipSpaces(scnr);
  747. eat(scnr, `\'`);
  748. let ch = '';
  749. let literal = '';
  750. const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
  751. while ((ch = takeChar(scnr, fn))) {
  752. if (ch === '\\') {
  753. literal += readEscapeSequence(scnr);
  754. }
  755. else {
  756. literal += ch;
  757. }
  758. }
  759. const current = scnr.currentChar();
  760. if (current === CHAR_LF || current === EOF) {
  761. emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
  762. // TODO: Is it correct really?
  763. if (current === CHAR_LF) {
  764. scnr.next();
  765. eat(scnr, `\'`);
  766. }
  767. return literal;
  768. }
  769. eat(scnr, `\'`);
  770. return literal;
  771. }
  772. function readEscapeSequence(scnr) {
  773. const ch = scnr.currentChar();
  774. switch (ch) {
  775. case '\\':
  776. case `\'`:
  777. scnr.next();
  778. return `\\${ch}`;
  779. case 'u':
  780. return readUnicodeEscapeSequence(scnr, ch, 4);
  781. case 'U':
  782. return readUnicodeEscapeSequence(scnr, ch, 6);
  783. default:
  784. emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
  785. return '';
  786. }
  787. }
  788. function readUnicodeEscapeSequence(scnr, unicode, digits) {
  789. eat(scnr, unicode);
  790. let sequence = '';
  791. for (let i = 0; i < digits; i++) {
  792. const ch = takeHexDigit(scnr);
  793. if (!ch) {
  794. emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
  795. break;
  796. }
  797. sequence += ch;
  798. }
  799. return `\\${unicode}${sequence}`;
  800. }
  801. function readInvalidIdentifier(scnr) {
  802. skipSpaces(scnr);
  803. let ch = '';
  804. let identifiers = '';
  805. const closure = (ch) => ch !== "{" /* TokenChars.BraceLeft */ &&
  806. ch !== "}" /* TokenChars.BraceRight */ &&
  807. ch !== CHAR_SP &&
  808. ch !== CHAR_LF;
  809. while ((ch = takeChar(scnr, closure))) {
  810. identifiers += ch;
  811. }
  812. return identifiers;
  813. }
  814. function readLinkedModifier(scnr) {
  815. let ch = '';
  816. let name = '';
  817. while ((ch = takeIdentifierChar(scnr))) {
  818. name += ch;
  819. }
  820. return name;
  821. }
  822. function readLinkedRefer(scnr) {
  823. const fn = (detect = false, buf) => {
  824. const ch = scnr.currentChar();
  825. if (ch === "{" /* TokenChars.BraceLeft */ ||
  826. ch === "%" /* TokenChars.Modulo */ ||
  827. ch === "@" /* TokenChars.LinkedAlias */ ||
  828. ch === "|" /* TokenChars.Pipe */ ||
  829. ch === "(" /* TokenChars.ParenLeft */ ||
  830. ch === ")" /* TokenChars.ParenRight */ ||
  831. !ch) {
  832. return buf;
  833. }
  834. else if (ch === CHAR_SP) {
  835. return buf;
  836. }
  837. else if (ch === CHAR_LF || ch === DOT) {
  838. buf += ch;
  839. scnr.next();
  840. return fn(detect, buf);
  841. }
  842. else {
  843. buf += ch;
  844. scnr.next();
  845. return fn(true, buf);
  846. }
  847. };
  848. return fn(false, '');
  849. }
  850. function readPlural(scnr) {
  851. skipSpaces(scnr);
  852. const plural = eat(scnr, "|" /* TokenChars.Pipe */);
  853. skipSpaces(scnr);
  854. return plural;
  855. }
  856. // TODO: We need refactoring of token parsing ...
  857. function readTokenInPlaceholder(scnr, context) {
  858. let token = null;
  859. const ch = scnr.currentChar();
  860. switch (ch) {
  861. case "{" /* TokenChars.BraceLeft */:
  862. if (context.braceNest >= 1) {
  863. emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
  864. }
  865. scnr.next();
  866. token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
  867. skipSpaces(scnr);
  868. context.braceNest++;
  869. return token;
  870. case "}" /* TokenChars.BraceRight */:
  871. if (context.braceNest > 0 &&
  872. context.currentType === 2 /* TokenTypes.BraceLeft */) {
  873. emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
  874. }
  875. scnr.next();
  876. token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  877. context.braceNest--;
  878. context.braceNest > 0 && skipSpaces(scnr);
  879. if (context.inLinked && context.braceNest === 0) {
  880. context.inLinked = false;
  881. }
  882. return token;
  883. case "@" /* TokenChars.LinkedAlias */:
  884. if (context.braceNest > 0) {
  885. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  886. }
  887. token = readTokenInLinked(scnr, context) || getEndToken(context);
  888. context.braceNest = 0;
  889. return token;
  890. default:
  891. let validNamedIdentifier = true;
  892. let validListIdentifier = true;
  893. let validLiteral = true;
  894. if (isPluralStart(scnr)) {
  895. if (context.braceNest > 0) {
  896. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  897. }
  898. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  899. // reset
  900. context.braceNest = 0;
  901. context.inLinked = false;
  902. return token;
  903. }
  904. if (context.braceNest > 0 &&
  905. (context.currentType === 5 /* TokenTypes.Named */ ||
  906. context.currentType === 6 /* TokenTypes.List */ ||
  907. context.currentType === 7 /* TokenTypes.Literal */)) {
  908. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  909. context.braceNest = 0;
  910. return readToken(scnr, context);
  911. }
  912. if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
  913. token = getToken(context, 5 /* TokenTypes.Named */, readNamedIdentifier(scnr));
  914. skipSpaces(scnr);
  915. return token;
  916. }
  917. if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
  918. token = getToken(context, 6 /* TokenTypes.List */, readListIdentifier(scnr));
  919. skipSpaces(scnr);
  920. return token;
  921. }
  922. if ((validLiteral = isLiteralStart(scnr, context))) {
  923. token = getToken(context, 7 /* TokenTypes.Literal */, readLiteral(scnr));
  924. skipSpaces(scnr);
  925. return token;
  926. }
  927. if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
  928. // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
  929. token = getToken(context, 13 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
  930. emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
  931. skipSpaces(scnr);
  932. return token;
  933. }
  934. break;
  935. }
  936. return token;
  937. }
  938. // TODO: We need refactoring of token parsing ...
  939. function readTokenInLinked(scnr, context) {
  940. const { currentType } = context;
  941. let token = null;
  942. const ch = scnr.currentChar();
  943. if ((currentType === 8 /* TokenTypes.LinkedAlias */ ||
  944. currentType === 9 /* TokenTypes.LinkedDot */ ||
  945. currentType === 12 /* TokenTypes.LinkedModifier */ ||
  946. currentType === 10 /* TokenTypes.LinkedDelimiter */) &&
  947. (ch === CHAR_LF || ch === CHAR_SP)) {
  948. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  949. }
  950. switch (ch) {
  951. case "@" /* TokenChars.LinkedAlias */:
  952. scnr.next();
  953. token = getToken(context, 8 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
  954. context.inLinked = true;
  955. return token;
  956. case "." /* TokenChars.LinkedDot */:
  957. skipSpaces(scnr);
  958. scnr.next();
  959. return getToken(context, 9 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
  960. case ":" /* TokenChars.LinkedDelimiter */:
  961. skipSpaces(scnr);
  962. scnr.next();
  963. return getToken(context, 10 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
  964. default:
  965. if (isPluralStart(scnr)) {
  966. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  967. // reset
  968. context.braceNest = 0;
  969. context.inLinked = false;
  970. return token;
  971. }
  972. if (isLinkedDotStart(scnr, context) ||
  973. isLinkedDelimiterStart(scnr, context)) {
  974. skipSpaces(scnr);
  975. return readTokenInLinked(scnr, context);
  976. }
  977. if (isLinkedModifierStart(scnr, context)) {
  978. skipSpaces(scnr);
  979. return getToken(context, 12 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
  980. }
  981. if (isLinkedReferStart(scnr, context)) {
  982. skipSpaces(scnr);
  983. if (ch === "{" /* TokenChars.BraceLeft */) {
  984. // scan the placeholder
  985. return readTokenInPlaceholder(scnr, context) || token;
  986. }
  987. else {
  988. return getToken(context, 11 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
  989. }
  990. }
  991. if (currentType === 8 /* TokenTypes.LinkedAlias */) {
  992. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  993. }
  994. context.braceNest = 0;
  995. context.inLinked = false;
  996. return readToken(scnr, context);
  997. }
  998. }
  999. // TODO: We need refactoring of token parsing ...
  1000. function readToken(scnr, context) {
  1001. let token = { type: 14 /* TokenTypes.EOF */ };
  1002. if (context.braceNest > 0) {
  1003. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  1004. }
  1005. if (context.inLinked) {
  1006. return readTokenInLinked(scnr, context) || getEndToken(context);
  1007. }
  1008. const ch = scnr.currentChar();
  1009. switch (ch) {
  1010. case "{" /* TokenChars.BraceLeft */:
  1011. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  1012. case "}" /* TokenChars.BraceRight */:
  1013. emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
  1014. scnr.next();
  1015. return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  1016. case "@" /* TokenChars.LinkedAlias */:
  1017. return readTokenInLinked(scnr, context) || getEndToken(context);
  1018. default:
  1019. if (isPluralStart(scnr)) {
  1020. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  1021. // reset
  1022. context.braceNest = 0;
  1023. context.inLinked = false;
  1024. return token;
  1025. }
  1026. const { isModulo, hasSpace } = detectModuloStart(scnr);
  1027. if (isModulo) {
  1028. return hasSpace
  1029. ? getToken(context, 0 /* TokenTypes.Text */, readText(scnr))
  1030. : getToken(context, 4 /* TokenTypes.Modulo */, readModulo(scnr));
  1031. }
  1032. if (isTextStart(scnr)) {
  1033. return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
  1034. }
  1035. break;
  1036. }
  1037. return token;
  1038. }
  1039. function nextToken() {
  1040. const { currentType, offset, startLoc, endLoc } = _context;
  1041. _context.lastType = currentType;
  1042. _context.lastOffset = offset;
  1043. _context.lastStartLoc = startLoc;
  1044. _context.lastEndLoc = endLoc;
  1045. _context.offset = currentOffset();
  1046. _context.startLoc = currentPosition();
  1047. if (_scnr.currentChar() === EOF) {
  1048. return getToken(_context, 14 /* TokenTypes.EOF */);
  1049. }
  1050. return readToken(_scnr, _context);
  1051. }
  1052. return {
  1053. nextToken,
  1054. currentOffset,
  1055. currentPosition,
  1056. context
  1057. };
  1058. }
  1059. const ERROR_DOMAIN$2 = 'parser';
  1060. // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
  1061. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
  1062. function fromEscapeSequence(match, codePoint4, codePoint6) {
  1063. switch (match) {
  1064. case `\\\\`:
  1065. return `\\`;
  1066. case `\\\'`:
  1067. return `\'`;
  1068. default: {
  1069. const codePoint = parseInt(codePoint4 || codePoint6, 16);
  1070. if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
  1071. return String.fromCodePoint(codePoint);
  1072. }
  1073. // invalid ...
  1074. // Replace them with U+FFFD REPLACEMENT CHARACTER.
  1075. return '�';
  1076. }
  1077. }
  1078. }
  1079. function createParser(options = {}) {
  1080. const location = options.location !== false;
  1081. const { onError } = options;
  1082. function emitError(tokenzer, code, start, offset, ...args) {
  1083. const end = tokenzer.currentPosition();
  1084. end.offset += offset;
  1085. end.column += offset;
  1086. if (onError) {
  1087. const loc = location ? createLocation(start, end) : null;
  1088. const err = createCompileError(code, loc, {
  1089. domain: ERROR_DOMAIN$2,
  1090. args
  1091. });
  1092. onError(err);
  1093. }
  1094. }
  1095. function startNode(type, offset, loc) {
  1096. const node = { type };
  1097. if (location) {
  1098. node.start = offset;
  1099. node.end = offset;
  1100. node.loc = { start: loc, end: loc };
  1101. }
  1102. return node;
  1103. }
  1104. function endNode(node, offset, pos, type) {
  1105. if (type) {
  1106. node.type = type;
  1107. }
  1108. if (location) {
  1109. node.end = offset;
  1110. if (node.loc) {
  1111. node.loc.end = pos;
  1112. }
  1113. }
  1114. }
  1115. function parseText(tokenizer, value) {
  1116. const context = tokenizer.context();
  1117. const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
  1118. node.value = value;
  1119. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1120. return node;
  1121. }
  1122. function parseList(tokenizer, index) {
  1123. const context = tokenizer.context();
  1124. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1125. const node = startNode(5 /* NodeTypes.List */, offset, loc);
  1126. node.index = parseInt(index, 10);
  1127. tokenizer.nextToken(); // skip brach right
  1128. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1129. return node;
  1130. }
  1131. function parseNamed(tokenizer, key) {
  1132. const context = tokenizer.context();
  1133. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1134. const node = startNode(4 /* NodeTypes.Named */, offset, loc);
  1135. node.key = key;
  1136. tokenizer.nextToken(); // skip brach right
  1137. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1138. return node;
  1139. }
  1140. function parseLiteral(tokenizer, value) {
  1141. const context = tokenizer.context();
  1142. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  1143. const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
  1144. node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
  1145. tokenizer.nextToken(); // skip brach right
  1146. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1147. return node;
  1148. }
  1149. function parseLinkedModifier(tokenizer) {
  1150. const token = tokenizer.nextToken();
  1151. const context = tokenizer.context();
  1152. const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
  1153. const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
  1154. if (token.type !== 12 /* TokenTypes.LinkedModifier */) {
  1155. // empty modifier
  1156. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
  1157. node.value = '';
  1158. endNode(node, offset, loc);
  1159. return {
  1160. nextConsumeToken: token,
  1161. node
  1162. };
  1163. }
  1164. // check token
  1165. if (token.value == null) {
  1166. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1167. }
  1168. node.value = token.value || '';
  1169. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1170. return {
  1171. node
  1172. };
  1173. }
  1174. function parseLinkedKey(tokenizer, value) {
  1175. const context = tokenizer.context();
  1176. const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
  1177. node.value = value;
  1178. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1179. return node;
  1180. }
  1181. function parseLinked(tokenizer) {
  1182. const context = tokenizer.context();
  1183. const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
  1184. let token = tokenizer.nextToken();
  1185. if (token.type === 9 /* TokenTypes.LinkedDot */) {
  1186. const parsed = parseLinkedModifier(tokenizer);
  1187. linkedNode.modifier = parsed.node;
  1188. token = parsed.nextConsumeToken || tokenizer.nextToken();
  1189. }
  1190. // asset check token
  1191. if (token.type !== 10 /* TokenTypes.LinkedDelimiter */) {
  1192. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1193. }
  1194. token = tokenizer.nextToken();
  1195. // skip brace left
  1196. if (token.type === 2 /* TokenTypes.BraceLeft */) {
  1197. token = tokenizer.nextToken();
  1198. }
  1199. switch (token.type) {
  1200. case 11 /* TokenTypes.LinkedKey */:
  1201. if (token.value == null) {
  1202. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1203. }
  1204. linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
  1205. break;
  1206. case 5 /* TokenTypes.Named */:
  1207. if (token.value == null) {
  1208. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1209. }
  1210. linkedNode.key = parseNamed(tokenizer, token.value || '');
  1211. break;
  1212. case 6 /* TokenTypes.List */:
  1213. if (token.value == null) {
  1214. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1215. }
  1216. linkedNode.key = parseList(tokenizer, token.value || '');
  1217. break;
  1218. case 7 /* TokenTypes.Literal */:
  1219. if (token.value == null) {
  1220. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1221. }
  1222. linkedNode.key = parseLiteral(tokenizer, token.value || '');
  1223. break;
  1224. default:
  1225. // empty key
  1226. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
  1227. const nextContext = tokenizer.context();
  1228. const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
  1229. emptyLinkedKeyNode.value = '';
  1230. endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
  1231. linkedNode.key = emptyLinkedKeyNode;
  1232. endNode(linkedNode, nextContext.offset, nextContext.startLoc);
  1233. return {
  1234. nextConsumeToken: token,
  1235. node: linkedNode
  1236. };
  1237. }
  1238. endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
  1239. return {
  1240. node: linkedNode
  1241. };
  1242. }
  1243. function parseMessage(tokenizer) {
  1244. const context = tokenizer.context();
  1245. const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1246. ? tokenizer.currentOffset()
  1247. : context.offset;
  1248. const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1249. ? context.endLoc
  1250. : context.startLoc;
  1251. const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
  1252. node.items = [];
  1253. let nextToken = null;
  1254. do {
  1255. const token = nextToken || tokenizer.nextToken();
  1256. nextToken = null;
  1257. switch (token.type) {
  1258. case 0 /* TokenTypes.Text */:
  1259. if (token.value == null) {
  1260. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1261. }
  1262. node.items.push(parseText(tokenizer, token.value || ''));
  1263. break;
  1264. case 6 /* TokenTypes.List */:
  1265. if (token.value == null) {
  1266. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1267. }
  1268. node.items.push(parseList(tokenizer, token.value || ''));
  1269. break;
  1270. case 5 /* TokenTypes.Named */:
  1271. if (token.value == null) {
  1272. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1273. }
  1274. node.items.push(parseNamed(tokenizer, token.value || ''));
  1275. break;
  1276. case 7 /* TokenTypes.Literal */:
  1277. if (token.value == null) {
  1278. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1279. }
  1280. node.items.push(parseLiteral(tokenizer, token.value || ''));
  1281. break;
  1282. case 8 /* TokenTypes.LinkedAlias */:
  1283. const parsed = parseLinked(tokenizer);
  1284. node.items.push(parsed.node);
  1285. nextToken = parsed.nextConsumeToken || null;
  1286. break;
  1287. }
  1288. } while (context.currentType !== 14 /* TokenTypes.EOF */ &&
  1289. context.currentType !== 1 /* TokenTypes.Pipe */);
  1290. // adjust message node loc
  1291. const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1292. ? context.lastOffset
  1293. : tokenizer.currentOffset();
  1294. const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1295. ? context.lastEndLoc
  1296. : tokenizer.currentPosition();
  1297. endNode(node, endOffset, endLoc);
  1298. return node;
  1299. }
  1300. function parsePlural(tokenizer, offset, loc, msgNode) {
  1301. const context = tokenizer.context();
  1302. let hasEmptyMessage = msgNode.items.length === 0;
  1303. const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
  1304. node.cases = [];
  1305. node.cases.push(msgNode);
  1306. do {
  1307. const msg = parseMessage(tokenizer);
  1308. if (!hasEmptyMessage) {
  1309. hasEmptyMessage = msg.items.length === 0;
  1310. }
  1311. node.cases.push(msg);
  1312. } while (context.currentType !== 14 /* TokenTypes.EOF */);
  1313. if (hasEmptyMessage) {
  1314. emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
  1315. }
  1316. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1317. return node;
  1318. }
  1319. function parseResource(tokenizer) {
  1320. const context = tokenizer.context();
  1321. const { offset, startLoc } = context;
  1322. const msgNode = parseMessage(tokenizer);
  1323. if (context.currentType === 14 /* TokenTypes.EOF */) {
  1324. return msgNode;
  1325. }
  1326. else {
  1327. return parsePlural(tokenizer, offset, startLoc, msgNode);
  1328. }
  1329. }
  1330. function parse(source) {
  1331. const tokenizer = createTokenizer(source, assign({}, options));
  1332. const context = tokenizer.context();
  1333. const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
  1334. if (location && node.loc) {
  1335. node.loc.source = source;
  1336. }
  1337. node.body = parseResource(tokenizer);
  1338. if (options.onCacheKey) {
  1339. node.cacheKey = options.onCacheKey(source);
  1340. }
  1341. // assert whether achieved to EOF
  1342. if (context.currentType !== 14 /* TokenTypes.EOF */) {
  1343. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
  1344. }
  1345. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1346. return node;
  1347. }
  1348. return { parse };
  1349. }
  1350. function getTokenCaption(token) {
  1351. if (token.type === 14 /* TokenTypes.EOF */) {
  1352. return 'EOF';
  1353. }
  1354. const name = (token.value || '').replace(/\r?\n/gu, '\\n');
  1355. return name.length > 10 ? name.slice(0, 9) + '…' : name;
  1356. }
  1357. function createTransformer(ast, options = {} // eslint-disable-line
  1358. ) {
  1359. const _context = {
  1360. ast,
  1361. helpers: new Set()
  1362. };
  1363. const context = () => _context;
  1364. const helper = (name) => {
  1365. _context.helpers.add(name);
  1366. return name;
  1367. };
  1368. return { context, helper };
  1369. }
  1370. function traverseNodes(nodes, transformer) {
  1371. for (let i = 0; i < nodes.length; i++) {
  1372. traverseNode(nodes[i], transformer);
  1373. }
  1374. }
  1375. function traverseNode(node, transformer) {
  1376. // TODO: if we need pre-hook of transform, should be implemented to here
  1377. switch (node.type) {
  1378. case 1 /* NodeTypes.Plural */:
  1379. traverseNodes(node.cases, transformer);
  1380. transformer.helper("plural" /* HelperNameMap.PLURAL */);
  1381. break;
  1382. case 2 /* NodeTypes.Message */:
  1383. traverseNodes(node.items, transformer);
  1384. break;
  1385. case 6 /* NodeTypes.Linked */:
  1386. const linked = node;
  1387. traverseNode(linked.key, transformer);
  1388. transformer.helper("linked" /* HelperNameMap.LINKED */);
  1389. transformer.helper("type" /* HelperNameMap.TYPE */);
  1390. break;
  1391. case 5 /* NodeTypes.List */:
  1392. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1393. transformer.helper("list" /* HelperNameMap.LIST */);
  1394. break;
  1395. case 4 /* NodeTypes.Named */:
  1396. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1397. transformer.helper("named" /* HelperNameMap.NAMED */);
  1398. break;
  1399. }
  1400. // TODO: if we need post-hook of transform, should be implemented to here
  1401. }
  1402. // transform AST
  1403. function transform(ast, options = {} // eslint-disable-line
  1404. ) {
  1405. const transformer = createTransformer(ast);
  1406. transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
  1407. // traverse
  1408. ast.body && traverseNode(ast.body, transformer);
  1409. // set meta information
  1410. const context = transformer.context();
  1411. ast.helpers = Array.from(context.helpers);
  1412. }
  1413. function optimize(ast) {
  1414. const body = ast.body;
  1415. if (body.type === 2 /* NodeTypes.Message */) {
  1416. optimizeMessageNode(body);
  1417. }
  1418. else {
  1419. body.cases.forEach(c => optimizeMessageNode(c));
  1420. }
  1421. return ast;
  1422. }
  1423. function optimizeMessageNode(message) {
  1424. if (message.items.length === 1) {
  1425. const item = message.items[0];
  1426. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1427. message.static = item.value;
  1428. delete item.value; // optimization for size
  1429. }
  1430. }
  1431. else {
  1432. const values = [];
  1433. for (let i = 0; i < message.items.length; i++) {
  1434. const item = message.items[i];
  1435. if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
  1436. break;
  1437. }
  1438. if (item.value == null) {
  1439. break;
  1440. }
  1441. values.push(item.value);
  1442. }
  1443. if (values.length === message.items.length) {
  1444. message.static = join(values);
  1445. for (let i = 0; i < message.items.length; i++) {
  1446. const item = message.items[i];
  1447. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1448. delete item.value; // optimization for size
  1449. }
  1450. }
  1451. }
  1452. }
  1453. }
  1454. const ERROR_DOMAIN$1 = 'minifier';
  1455. /* eslint-disable @typescript-eslint/no-explicit-any */
  1456. function minify(node) {
  1457. node.t = node.type;
  1458. switch (node.type) {
  1459. case 0 /* NodeTypes.Resource */:
  1460. const resource = node;
  1461. minify(resource.body);
  1462. resource.b = resource.body;
  1463. delete resource.body;
  1464. break;
  1465. case 1 /* NodeTypes.Plural */:
  1466. const plural = node;
  1467. const cases = plural.cases;
  1468. for (let i = 0; i < cases.length; i++) {
  1469. minify(cases[i]);
  1470. }
  1471. plural.c = cases;
  1472. delete plural.cases;
  1473. break;
  1474. case 2 /* NodeTypes.Message */:
  1475. const message = node;
  1476. const items = message.items;
  1477. for (let i = 0; i < items.length; i++) {
  1478. minify(items[i]);
  1479. }
  1480. message.i = items;
  1481. delete message.items;
  1482. if (message.static) {
  1483. message.s = message.static;
  1484. delete message.static;
  1485. }
  1486. break;
  1487. case 3 /* NodeTypes.Text */:
  1488. case 9 /* NodeTypes.Literal */:
  1489. case 8 /* NodeTypes.LinkedModifier */:
  1490. case 7 /* NodeTypes.LinkedKey */:
  1491. const valueNode = node;
  1492. if (valueNode.value) {
  1493. valueNode.v = valueNode.value;
  1494. delete valueNode.value;
  1495. }
  1496. break;
  1497. case 6 /* NodeTypes.Linked */:
  1498. const linked = node;
  1499. minify(linked.key);
  1500. linked.k = linked.key;
  1501. delete linked.key;
  1502. if (linked.modifier) {
  1503. minify(linked.modifier);
  1504. linked.m = linked.modifier;
  1505. delete linked.modifier;
  1506. }
  1507. break;
  1508. case 5 /* NodeTypes.List */:
  1509. const list = node;
  1510. list.i = list.index;
  1511. delete list.index;
  1512. break;
  1513. case 4 /* NodeTypes.Named */:
  1514. const named = node;
  1515. named.k = named.key;
  1516. delete named.key;
  1517. break;
  1518. default:
  1519. {
  1520. throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
  1521. domain: ERROR_DOMAIN$1,
  1522. args: [node.type]
  1523. });
  1524. }
  1525. }
  1526. delete node.type;
  1527. }
  1528. /* eslint-enable @typescript-eslint/no-explicit-any */
  1529. const ERROR_DOMAIN = 'parser';
  1530. function createCodeGenerator(ast, options) {
  1531. const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
  1532. const location = options.location !== false;
  1533. const _context = {
  1534. filename,
  1535. code: '',
  1536. column: 1,
  1537. line: 1,
  1538. offset: 0,
  1539. map: undefined,
  1540. breakLineCode,
  1541. needIndent: _needIndent,
  1542. indentLevel: 0
  1543. };
  1544. if (location && ast.loc) {
  1545. _context.source = ast.loc.source;
  1546. }
  1547. const context = () => _context;
  1548. function push(code, node) {
  1549. _context.code += code;
  1550. }
  1551. function _newline(n, withBreakLine = true) {
  1552. const _breakLineCode = withBreakLine ? breakLineCode : '';
  1553. push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
  1554. }
  1555. function indent(withNewLine = true) {
  1556. const level = ++_context.indentLevel;
  1557. withNewLine && _newline(level);
  1558. }
  1559. function deindent(withNewLine = true) {
  1560. const level = --_context.indentLevel;
  1561. withNewLine && _newline(level);
  1562. }
  1563. function newline() {
  1564. _newline(_context.indentLevel);
  1565. }
  1566. const helper = (key) => `_${key}`;
  1567. const needIndent = () => _context.needIndent;
  1568. return {
  1569. context,
  1570. push,
  1571. indent,
  1572. deindent,
  1573. newline,
  1574. helper,
  1575. needIndent
  1576. };
  1577. }
  1578. function generateLinkedNode(generator, node) {
  1579. const { helper } = generator;
  1580. generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
  1581. generateNode(generator, node.key);
  1582. if (node.modifier) {
  1583. generator.push(`, `);
  1584. generateNode(generator, node.modifier);
  1585. generator.push(`, _type`);
  1586. }
  1587. else {
  1588. generator.push(`, undefined, _type`);
  1589. }
  1590. generator.push(`)`);
  1591. }
  1592. function generateMessageNode(generator, node) {
  1593. const { helper, needIndent } = generator;
  1594. generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
  1595. generator.indent(needIndent());
  1596. const length = node.items.length;
  1597. for (let i = 0; i < length; i++) {
  1598. generateNode(generator, node.items[i]);
  1599. if (i === length - 1) {
  1600. break;
  1601. }
  1602. generator.push(', ');
  1603. }
  1604. generator.deindent(needIndent());
  1605. generator.push('])');
  1606. }
  1607. function generatePluralNode(generator, node) {
  1608. const { helper, needIndent } = generator;
  1609. if (node.cases.length > 1) {
  1610. generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
  1611. generator.indent(needIndent());
  1612. const length = node.cases.length;
  1613. for (let i = 0; i < length; i++) {
  1614. generateNode(generator, node.cases[i]);
  1615. if (i === length - 1) {
  1616. break;
  1617. }
  1618. generator.push(', ');
  1619. }
  1620. generator.deindent(needIndent());
  1621. generator.push(`])`);
  1622. }
  1623. }
  1624. function generateResource(generator, node) {
  1625. if (node.body) {
  1626. generateNode(generator, node.body);
  1627. }
  1628. else {
  1629. generator.push('null');
  1630. }
  1631. }
  1632. function generateNode(generator, node) {
  1633. const { helper } = generator;
  1634. switch (node.type) {
  1635. case 0 /* NodeTypes.Resource */:
  1636. generateResource(generator, node);
  1637. break;
  1638. case 1 /* NodeTypes.Plural */:
  1639. generatePluralNode(generator, node);
  1640. break;
  1641. case 2 /* NodeTypes.Message */:
  1642. generateMessageNode(generator, node);
  1643. break;
  1644. case 6 /* NodeTypes.Linked */:
  1645. generateLinkedNode(generator, node);
  1646. break;
  1647. case 8 /* NodeTypes.LinkedModifier */:
  1648. generator.push(JSON.stringify(node.value), node);
  1649. break;
  1650. case 7 /* NodeTypes.LinkedKey */:
  1651. generator.push(JSON.stringify(node.value), node);
  1652. break;
  1653. case 5 /* NodeTypes.List */:
  1654. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
  1655. break;
  1656. case 4 /* NodeTypes.Named */:
  1657. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
  1658. break;
  1659. case 9 /* NodeTypes.Literal */:
  1660. generator.push(JSON.stringify(node.value), node);
  1661. break;
  1662. case 3 /* NodeTypes.Text */:
  1663. generator.push(JSON.stringify(node.value), node);
  1664. break;
  1665. default:
  1666. {
  1667. throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
  1668. domain: ERROR_DOMAIN,
  1669. args: [node.type]
  1670. });
  1671. }
  1672. }
  1673. }
  1674. // generate code from AST
  1675. const generate = (ast, options = {} // eslint-disable-line
  1676. ) => {
  1677. const mode = isString(options.mode) ? options.mode : 'normal';
  1678. const filename = isString(options.filename)
  1679. ? options.filename
  1680. : 'message.intl';
  1681. const sourceMap = !!options.sourceMap;
  1682. // prettier-ignore
  1683. const breakLineCode = options.breakLineCode != null
  1684. ? options.breakLineCode
  1685. : mode === 'arrow'
  1686. ? ';'
  1687. : '\n';
  1688. const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
  1689. const helpers = ast.helpers || [];
  1690. const generator = createCodeGenerator(ast, {
  1691. mode,
  1692. filename,
  1693. sourceMap,
  1694. breakLineCode,
  1695. needIndent
  1696. });
  1697. generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
  1698. generator.indent(needIndent);
  1699. if (helpers.length > 0) {
  1700. generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
  1701. generator.newline();
  1702. }
  1703. generator.push(`return `);
  1704. generateNode(generator, ast);
  1705. generator.deindent(needIndent);
  1706. generator.push(`}`);
  1707. delete ast.helpers;
  1708. const { code, map } = generator.context();
  1709. return {
  1710. ast,
  1711. code,
  1712. map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
  1713. };
  1714. };
  1715. function baseCompile$1(source, options = {}) {
  1716. const assignedOptions = assign({}, options);
  1717. const jit = !!assignedOptions.jit;
  1718. const enalbeMinify = !!assignedOptions.minify;
  1719. const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
  1720. // parse source codes
  1721. const parser = createParser(assignedOptions);
  1722. const ast = parser.parse(source);
  1723. if (!jit) {
  1724. // transform ASTs
  1725. transform(ast, assignedOptions);
  1726. // generate javascript codes
  1727. return generate(ast, assignedOptions);
  1728. }
  1729. else {
  1730. // optimize ASTs
  1731. enambeOptimize && optimize(ast);
  1732. // minimize ASTs
  1733. enalbeMinify && minify(ast);
  1734. // In JIT mode, no ast transform, no code generation.
  1735. return { ast, code: '' };
  1736. }
  1737. }
  1738. const pathStateMachine = [];
  1739. pathStateMachine[0 /* States.BEFORE_PATH */] = {
  1740. ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
  1741. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1742. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  1743. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  1744. };
  1745. pathStateMachine[1 /* States.IN_PATH */] = {
  1746. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
  1747. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
  1748. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  1749. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  1750. };
  1751. pathStateMachine[2 /* States.BEFORE_IDENT */] = {
  1752. ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
  1753. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1754. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
  1755. };
  1756. pathStateMachine[3 /* States.IN_IDENT */] = {
  1757. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1758. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  1759. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
  1760. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
  1761. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
  1762. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
  1763. };
  1764. pathStateMachine[4 /* States.IN_SUB_PATH */] = {
  1765. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
  1766. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
  1767. ["[" /* PathCharTypes.LEFT_BRACKET */]: [
  1768. 4 /* States.IN_SUB_PATH */,
  1769. 2 /* Actions.INC_SUB_PATH_DEPTH */
  1770. ],
  1771. ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
  1772. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  1773. ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
  1774. };
  1775. pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
  1776. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  1777. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  1778. ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
  1779. };
  1780. pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
  1781. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  1782. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  1783. ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
  1784. };
  1785. /**
  1786. * Check if an expression is a literal value.
  1787. */
  1788. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  1789. function isLiteral(exp) {
  1790. return literalValueRE.test(exp);
  1791. }
  1792. /**
  1793. * Strip quotes from a string
  1794. */
  1795. function stripQuotes(str) {
  1796. const a = str.charCodeAt(0);
  1797. const b = str.charCodeAt(str.length - 1);
  1798. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  1799. }
  1800. /**
  1801. * Determine the type of a character in a keypath.
  1802. */
  1803. function getPathCharType(ch) {
  1804. if (ch === undefined || ch === null) {
  1805. return "o" /* PathCharTypes.END_OF_FAIL */;
  1806. }
  1807. const code = ch.charCodeAt(0);
  1808. switch (code) {
  1809. case 0x5b: // [
  1810. case 0x5d: // ]
  1811. case 0x2e: // .
  1812. case 0x22: // "
  1813. case 0x27: // '
  1814. return ch;
  1815. case 0x5f: // _
  1816. case 0x24: // $
  1817. case 0x2d: // -
  1818. return "i" /* PathCharTypes.IDENT */;
  1819. case 0x09: // Tab (HT)
  1820. case 0x0a: // Newline (LF)
  1821. case 0x0d: // Return (CR)
  1822. case 0xa0: // No-break space (NBSP)
  1823. case 0xfeff: // Byte Order Mark (BOM)
  1824. case 0x2028: // Line Separator (LS)
  1825. case 0x2029: // Paragraph Separator (PS)
  1826. return "w" /* PathCharTypes.WORKSPACE */;
  1827. }
  1828. return "i" /* PathCharTypes.IDENT */;
  1829. }
  1830. /**
  1831. * Format a subPath, return its plain form if it is
  1832. * a literal string or number. Otherwise prepend the
  1833. * dynamic indicator (*).
  1834. */
  1835. function formatSubPath(path) {
  1836. const trimmed = path.trim();
  1837. // invalid leading 0
  1838. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  1839. return false;
  1840. }
  1841. return isLiteral(trimmed)
  1842. ? stripQuotes(trimmed)
  1843. : "*" /* PathCharTypes.ASTARISK */ + trimmed;
  1844. }
  1845. /**
  1846. * Parse a string path into an array of segments
  1847. */
  1848. function parse(path) {
  1849. const keys = [];
  1850. let index = -1;
  1851. let mode = 0 /* States.BEFORE_PATH */;
  1852. let subPathDepth = 0;
  1853. let c;
  1854. let key; // eslint-disable-line
  1855. let newChar;
  1856. let type;
  1857. let transition;
  1858. let action;
  1859. let typeMap;
  1860. const actions = [];
  1861. actions[0 /* Actions.APPEND */] = () => {
  1862. if (key === undefined) {
  1863. key = newChar;
  1864. }
  1865. else {
  1866. key += newChar;
  1867. }
  1868. };
  1869. actions[1 /* Actions.PUSH */] = () => {
  1870. if (key !== undefined) {
  1871. keys.push(key);
  1872. key = undefined;
  1873. }
  1874. };
  1875. actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
  1876. actions[0 /* Actions.APPEND */]();
  1877. subPathDepth++;
  1878. };
  1879. actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
  1880. if (subPathDepth > 0) {
  1881. subPathDepth--;
  1882. mode = 4 /* States.IN_SUB_PATH */;
  1883. actions[0 /* Actions.APPEND */]();
  1884. }
  1885. else {
  1886. subPathDepth = 0;
  1887. if (key === undefined) {
  1888. return false;
  1889. }
  1890. key = formatSubPath(key);
  1891. if (key === false) {
  1892. return false;
  1893. }
  1894. else {
  1895. actions[1 /* Actions.PUSH */]();
  1896. }
  1897. }
  1898. };
  1899. function maybeUnescapeQuote() {
  1900. const nextChar = path[index + 1];
  1901. if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
  1902. nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
  1903. (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
  1904. nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
  1905. index++;
  1906. newChar = '\\' + nextChar;
  1907. actions[0 /* Actions.APPEND */]();
  1908. return true;
  1909. }
  1910. }
  1911. while (mode !== null) {
  1912. index++;
  1913. c = path[index];
  1914. if (c === '\\' && maybeUnescapeQuote()) {
  1915. continue;
  1916. }
  1917. type = getPathCharType(c);
  1918. typeMap = pathStateMachine[mode];
  1919. transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
  1920. // check parse error
  1921. if (transition === 8 /* States.ERROR */) {
  1922. return;
  1923. }
  1924. mode = transition[0];
  1925. if (transition[1] !== undefined) {
  1926. action = actions[transition[1]];
  1927. if (action) {
  1928. newChar = c;
  1929. if (action() === false) {
  1930. return;
  1931. }
  1932. }
  1933. }
  1934. // check parse finish
  1935. if (mode === 7 /* States.AFTER_PATH */) {
  1936. return keys;
  1937. }
  1938. }
  1939. }
  1940. // path token cache
  1941. const cache = new Map();
  1942. /**
  1943. * key-value message resolver
  1944. *
  1945. * @remarks
  1946. * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
  1947. *
  1948. * @param obj - A target object to be resolved with path
  1949. * @param path - A {@link Path | path} to resolve the value of message
  1950. *
  1951. * @returns A resolved {@link PathValue | path value}
  1952. *
  1953. * @VueI18nGeneral
  1954. */
  1955. function resolveWithKeyValue(obj, path) {
  1956. return isObject(obj) ? obj[path] : null;
  1957. }
  1958. /**
  1959. * message resolver
  1960. *
  1961. * @remarks
  1962. * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
  1963. *
  1964. * @param obj - A target object to be resolved with path
  1965. * @param path - A {@link Path | path} to resolve the value of message
  1966. *
  1967. * @returns A resolved {@link PathValue | path value}
  1968. *
  1969. * @VueI18nGeneral
  1970. */
  1971. function resolveValue(obj, path) {
  1972. // check object
  1973. if (!isObject(obj)) {
  1974. return null;
  1975. }
  1976. // parse path
  1977. let hit = cache.get(path);
  1978. if (!hit) {
  1979. hit = parse(path);
  1980. if (hit) {
  1981. cache.set(path, hit);
  1982. }
  1983. }
  1984. // check hit
  1985. if (!hit) {
  1986. return null;
  1987. }
  1988. // resolve path value
  1989. const len = hit.length;
  1990. let last = obj;
  1991. let i = 0;
  1992. while (i < len) {
  1993. const val = last[hit[i]];
  1994. if (val === undefined) {
  1995. return null;
  1996. }
  1997. if (isFunction(last)) {
  1998. return null;
  1999. }
  2000. last = val;
  2001. i++;
  2002. }
  2003. return last;
  2004. }
  2005. const DEFAULT_MODIFIER = (str) => str;
  2006. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  2007. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  2008. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
  2009. const DEFAULT_INTERPOLATE = toDisplayString;
  2010. function pluralDefault(choice, choicesLength) {
  2011. choice = Math.abs(choice);
  2012. if (choicesLength === 2) {
  2013. // prettier-ignore
  2014. return choice
  2015. ? choice > 1
  2016. ? 1
  2017. : 0
  2018. : 1;
  2019. }
  2020. return choice ? Math.min(choice, 2) : 0;
  2021. }
  2022. function getPluralIndex(options) {
  2023. // prettier-ignore
  2024. const index = isNumber(options.pluralIndex)
  2025. ? options.pluralIndex
  2026. : -1;
  2027. // prettier-ignore
  2028. return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
  2029. ? isNumber(options.named.count)
  2030. ? options.named.count
  2031. : isNumber(options.named.n)
  2032. ? options.named.n
  2033. : index
  2034. : index;
  2035. }
  2036. function normalizeNamed(pluralIndex, props) {
  2037. if (!props.count) {
  2038. props.count = pluralIndex;
  2039. }
  2040. if (!props.n) {
  2041. props.n = pluralIndex;
  2042. }
  2043. }
  2044. function createMessageContext(options = {}) {
  2045. const locale = options.locale;
  2046. const pluralIndex = getPluralIndex(options);
  2047. const pluralRule = isObject(options.pluralRules) &&
  2048. isString(locale) &&
  2049. isFunction(options.pluralRules[locale])
  2050. ? options.pluralRules[locale]
  2051. : pluralDefault;
  2052. const orgPluralRule = isObject(options.pluralRules) &&
  2053. isString(locale) &&
  2054. isFunction(options.pluralRules[locale])
  2055. ? pluralDefault
  2056. : undefined;
  2057. const plural = (messages) => {
  2058. return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  2059. };
  2060. const _list = options.list || [];
  2061. const list = (index) => _list[index];
  2062. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2063. const _named = options.named || {};
  2064. isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  2065. const named = (key) => _named[key];
  2066. function message(key) {
  2067. // prettier-ignore
  2068. const msg = isFunction(options.messages)
  2069. ? options.messages(key)
  2070. : isObject(options.messages)
  2071. ? options.messages[key]
  2072. : false;
  2073. return !msg
  2074. ? options.parent
  2075. ? options.parent.message(key) // resolve from parent messages
  2076. : DEFAULT_MESSAGE
  2077. : msg;
  2078. }
  2079. const _modifier = (name) => options.modifiers
  2080. ? options.modifiers[name]
  2081. : DEFAULT_MODIFIER;
  2082. const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
  2083. ? options.processor.normalize
  2084. : DEFAULT_NORMALIZE;
  2085. const interpolate = isPlainObject(options.processor) &&
  2086. isFunction(options.processor.interpolate)
  2087. ? options.processor.interpolate
  2088. : DEFAULT_INTERPOLATE;
  2089. const type = isPlainObject(options.processor) && isString(options.processor.type)
  2090. ? options.processor.type
  2091. : DEFAULT_MESSAGE_DATA_TYPE;
  2092. const linked = (key, ...args) => {
  2093. const [arg1, arg2] = args;
  2094. let type = 'text';
  2095. let modifier = '';
  2096. if (args.length === 1) {
  2097. if (isObject(arg1)) {
  2098. modifier = arg1.modifier || modifier;
  2099. type = arg1.type || type;
  2100. }
  2101. else if (isString(arg1)) {
  2102. modifier = arg1 || modifier;
  2103. }
  2104. }
  2105. else if (args.length === 2) {
  2106. if (isString(arg1)) {
  2107. modifier = arg1 || modifier;
  2108. }
  2109. if (isString(arg2)) {
  2110. type = arg2 || type;
  2111. }
  2112. }
  2113. const ret = message(key)(ctx);
  2114. const msg =
  2115. // The message in vnode resolved with linked are returned as an array by processor.nomalize
  2116. type === 'vnode' && isArray(ret) && modifier
  2117. ? ret[0]
  2118. : ret;
  2119. return modifier ? _modifier(modifier)(msg, type) : msg;
  2120. };
  2121. const ctx = {
  2122. ["list" /* HelperNameMap.LIST */]: list,
  2123. ["named" /* HelperNameMap.NAMED */]: named,
  2124. ["plural" /* HelperNameMap.PLURAL */]: plural,
  2125. ["linked" /* HelperNameMap.LINKED */]: linked,
  2126. ["message" /* HelperNameMap.MESSAGE */]: message,
  2127. ["type" /* HelperNameMap.TYPE */]: type,
  2128. ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
  2129. ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
  2130. ["values" /* HelperNameMap.VALUES */]: assign({}, _list, _named)
  2131. };
  2132. return ctx;
  2133. }
  2134. let devtools = null;
  2135. function setDevToolsHook(hook) {
  2136. devtools = hook;
  2137. }
  2138. function initI18nDevTools(i18n, version, meta) {
  2139. // TODO: queue if devtools is undefined
  2140. devtools &&
  2141. devtools.emit("i18n:init" /* IntlifyDevToolsHooks.I18nInit */, {
  2142. timestamp: Date.now(),
  2143. i18n,
  2144. version,
  2145. meta
  2146. });
  2147. }
  2148. const translateDevTools = /* #__PURE__*/ createDevToolsHook("function:translate" /* IntlifyDevToolsHooks.FunctionTranslate */);
  2149. function createDevToolsHook(hook) {
  2150. return (payloads) => devtools && devtools.emit(hook, payloads);
  2151. }
  2152. const CoreWarnCodes = {
  2153. NOT_FOUND_KEY: 1,
  2154. FALLBACK_TO_TRANSLATE: 2,
  2155. CANNOT_FORMAT_NUMBER: 3,
  2156. FALLBACK_TO_NUMBER_FORMAT: 4,
  2157. CANNOT_FORMAT_DATE: 5,
  2158. FALLBACK_TO_DATE_FORMAT: 6,
  2159. EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: 7,
  2160. __EXTEND_POINT__: 8
  2161. };
  2162. /** @internal */
  2163. const warnMessages$1 = {
  2164. [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
  2165. [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
  2166. [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  2167. [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
  2168. [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  2169. [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
  2170. [CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER]: `This project is using Custom Message Compiler, which is an experimental feature. It may receive breaking changes or be removed in the future.`
  2171. };
  2172. function getWarnMessage$1(code, ...args) {
  2173. return format$1(warnMessages$1[code], ...args);
  2174. }
  2175. const code$2 = CompileErrorCodes.__EXTEND_POINT__;
  2176. const inc$2 = incrementer(code$2);
  2177. const CoreErrorCodes = {
  2178. INVALID_ARGUMENT: code$2,
  2179. INVALID_DATE_ARGUMENT: inc$2(),
  2180. INVALID_ISO_DATE_ARGUMENT: inc$2(),
  2181. NOT_SUPPORT_NON_STRING_MESSAGE: inc$2(),
  2182. NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc$2(),
  2183. NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc$2(),
  2184. NOT_SUPPORT_LOCALE_TYPE: inc$2(),
  2185. __EXTEND_POINT__: inc$2() // 25
  2186. };
  2187. function createCoreError(code) {
  2188. return createCompileError(code, null, { messages: errorMessages$1 } );
  2189. }
  2190. /** @internal */
  2191. const errorMessages$1 = {
  2192. [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
  2193. [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
  2194. 'Make sure your Date represents a valid date.',
  2195. [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
  2196. [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
  2197. [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
  2198. [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
  2199. [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
  2200. };
  2201. /** @internal */
  2202. function getLocale(context, options) {
  2203. return options.locale != null
  2204. ? resolveLocale(options.locale)
  2205. : resolveLocale(context.locale);
  2206. }
  2207. let _resolveLocale;
  2208. /** @internal */
  2209. function resolveLocale(locale) {
  2210. if (isString(locale)) {
  2211. return locale;
  2212. }
  2213. else {
  2214. if (isFunction(locale)) {
  2215. if (locale.resolvedOnce && _resolveLocale != null) {
  2216. return _resolveLocale;
  2217. }
  2218. else if (locale.constructor.name === 'Function') {
  2219. const resolve = locale();
  2220. if (isPromise(resolve)) {
  2221. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
  2222. }
  2223. return (_resolveLocale = resolve);
  2224. }
  2225. else {
  2226. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
  2227. }
  2228. }
  2229. else {
  2230. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
  2231. }
  2232. }
  2233. }
  2234. /**
  2235. * Fallback with simple implemenation
  2236. *
  2237. * @remarks
  2238. * A fallback locale function implemented with a simple fallback algorithm.
  2239. *
  2240. * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
  2241. *
  2242. * @param ctx - A {@link CoreContext | context}
  2243. * @param fallback - A {@link FallbackLocale | fallback locale}
  2244. * @param start - A starting {@link Locale | locale}
  2245. *
  2246. * @returns Fallback locales
  2247. *
  2248. * @VueI18nGeneral
  2249. */
  2250. function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
  2251. ) {
  2252. // prettier-ignore
  2253. return [...new Set([
  2254. start,
  2255. ...(isArray(fallback)
  2256. ? fallback
  2257. : isObject(fallback)
  2258. ? Object.keys(fallback)
  2259. : isString(fallback)
  2260. ? [fallback]
  2261. : [start])
  2262. ])];
  2263. }
  2264. /**
  2265. * Fallback with locale chain
  2266. *
  2267. * @remarks
  2268. * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
  2269. *
  2270. * @param ctx - A {@link CoreContext | context}
  2271. * @param fallback - A {@link FallbackLocale | fallback locale}
  2272. * @param start - A starting {@link Locale | locale}
  2273. *
  2274. * @returns Fallback locales
  2275. *
  2276. * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
  2277. *
  2278. * @VueI18nGeneral
  2279. */
  2280. function fallbackWithLocaleChain(ctx, fallback, start) {
  2281. const startLocale = isString(start) ? start : DEFAULT_LOCALE;
  2282. const context = ctx;
  2283. if (!context.__localeChainCache) {
  2284. context.__localeChainCache = new Map();
  2285. }
  2286. let chain = context.__localeChainCache.get(startLocale);
  2287. if (!chain) {
  2288. chain = [];
  2289. // first block defined by start
  2290. let block = [start];
  2291. // while any intervening block found
  2292. while (isArray(block)) {
  2293. block = appendBlockToChain(chain, block, fallback);
  2294. }
  2295. // prettier-ignore
  2296. // last block defined by default
  2297. const defaults = isArray(fallback) || !isPlainObject(fallback)
  2298. ? fallback
  2299. : fallback['default']
  2300. ? fallback['default']
  2301. : null;
  2302. // convert defaults to array
  2303. block = isString(defaults) ? [defaults] : defaults;
  2304. if (isArray(block)) {
  2305. appendBlockToChain(chain, block, false);
  2306. }
  2307. context.__localeChainCache.set(startLocale, chain);
  2308. }
  2309. return chain;
  2310. }
  2311. function appendBlockToChain(chain, block, blocks) {
  2312. let follow = true;
  2313. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  2314. const locale = block[i];
  2315. if (isString(locale)) {
  2316. follow = appendLocaleToChain(chain, block[i], blocks);
  2317. }
  2318. }
  2319. return follow;
  2320. }
  2321. function appendLocaleToChain(chain, locale, blocks) {
  2322. let follow;
  2323. const tokens = locale.split('-');
  2324. do {
  2325. const target = tokens.join('-');
  2326. follow = appendItemToChain(chain, target, blocks);
  2327. tokens.splice(-1, 1);
  2328. } while (tokens.length && follow === true);
  2329. return follow;
  2330. }
  2331. function appendItemToChain(chain, target, blocks) {
  2332. let follow = false;
  2333. if (!chain.includes(target)) {
  2334. follow = true;
  2335. if (target) {
  2336. follow = target[target.length - 1] !== '!';
  2337. const locale = target.replace(/!/g, '');
  2338. chain.push(locale);
  2339. if ((isArray(blocks) || isPlainObject(blocks)) &&
  2340. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  2341. ) {
  2342. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2343. follow = blocks[locale];
  2344. }
  2345. }
  2346. }
  2347. return follow;
  2348. }
  2349. /* eslint-disable @typescript-eslint/no-explicit-any */
  2350. /**
  2351. * Intlify core-base version
  2352. * @internal
  2353. */
  2354. const VERSION$1 = '9.8.0';
  2355. const NOT_REOSLVED = -1;
  2356. const DEFAULT_LOCALE = 'en-US';
  2357. const MISSING_RESOLVE_VALUE = '';
  2358. const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
  2359. function getDefaultLinkedModifiers() {
  2360. return {
  2361. upper: (val, type) => {
  2362. // prettier-ignore
  2363. return type === 'text' && isString(val)
  2364. ? val.toUpperCase()
  2365. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2366. ? val.children.toUpperCase()
  2367. : val;
  2368. },
  2369. lower: (val, type) => {
  2370. // prettier-ignore
  2371. return type === 'text' && isString(val)
  2372. ? val.toLowerCase()
  2373. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2374. ? val.children.toLowerCase()
  2375. : val;
  2376. },
  2377. capitalize: (val, type) => {
  2378. // prettier-ignore
  2379. return (type === 'text' && isString(val)
  2380. ? capitalize(val)
  2381. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  2382. ? capitalize(val.children)
  2383. : val);
  2384. }
  2385. };
  2386. }
  2387. let _compiler;
  2388. function registerMessageCompiler(compiler) {
  2389. _compiler = compiler;
  2390. }
  2391. let _resolver;
  2392. /**
  2393. * Register the message resolver
  2394. *
  2395. * @param resolver - A {@link MessageResolver} function
  2396. *
  2397. * @VueI18nGeneral
  2398. */
  2399. function registerMessageResolver(resolver) {
  2400. _resolver = resolver;
  2401. }
  2402. let _fallbacker;
  2403. /**
  2404. * Register the locale fallbacker
  2405. *
  2406. * @param fallbacker - A {@link LocaleFallbacker} function
  2407. *
  2408. * @VueI18nGeneral
  2409. */
  2410. function registerLocaleFallbacker(fallbacker) {
  2411. _fallbacker = fallbacker;
  2412. }
  2413. // Additional Meta for Intlify DevTools
  2414. let _additionalMeta = null;
  2415. /* #__NO_SIDE_EFFECTS__ */
  2416. const setAdditionalMeta = (meta) => {
  2417. _additionalMeta = meta;
  2418. };
  2419. /* #__NO_SIDE_EFFECTS__ */
  2420. const getAdditionalMeta = () => _additionalMeta;
  2421. let _fallbackContext = null;
  2422. const setFallbackContext = (context) => {
  2423. _fallbackContext = context;
  2424. };
  2425. const getFallbackContext = () => _fallbackContext;
  2426. // ID for CoreContext
  2427. let _cid = 0;
  2428. function createCoreContext(options = {}) {
  2429. // setup options
  2430. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  2431. const version = isString(options.version) ? options.version : VERSION$1;
  2432. const locale = isString(options.locale) || isFunction(options.locale)
  2433. ? options.locale
  2434. : DEFAULT_LOCALE;
  2435. const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
  2436. const fallbackLocale = isArray(options.fallbackLocale) ||
  2437. isPlainObject(options.fallbackLocale) ||
  2438. isString(options.fallbackLocale) ||
  2439. options.fallbackLocale === false
  2440. ? options.fallbackLocale
  2441. : _locale;
  2442. const messages = isPlainObject(options.messages)
  2443. ? options.messages
  2444. : { [_locale]: {} };
  2445. const datetimeFormats = isPlainObject(options.datetimeFormats)
  2446. ? options.datetimeFormats
  2447. : { [_locale]: {} }
  2448. ;
  2449. const numberFormats = isPlainObject(options.numberFormats)
  2450. ? options.numberFormats
  2451. : { [_locale]: {} }
  2452. ;
  2453. const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
  2454. const pluralRules = options.pluralRules || {};
  2455. const missing = isFunction(options.missing) ? options.missing : null;
  2456. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  2457. ? options.missingWarn
  2458. : true;
  2459. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  2460. ? options.fallbackWarn
  2461. : true;
  2462. const fallbackFormat = !!options.fallbackFormat;
  2463. const unresolving = !!options.unresolving;
  2464. const postTranslation = isFunction(options.postTranslation)
  2465. ? options.postTranslation
  2466. : null;
  2467. const processor = isPlainObject(options.processor) ? options.processor : null;
  2468. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  2469. ? options.warnHtmlMessage
  2470. : true;
  2471. const escapeParameter = !!options.escapeParameter;
  2472. const messageCompiler = isFunction(options.messageCompiler)
  2473. ? options.messageCompiler
  2474. : _compiler;
  2475. if (isFunction(options.messageCompiler)) {
  2476. warnOnce(getWarnMessage$1(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));
  2477. }
  2478. const messageResolver = isFunction(options.messageResolver)
  2479. ? options.messageResolver
  2480. : _resolver || resolveWithKeyValue;
  2481. const localeFallbacker = isFunction(options.localeFallbacker)
  2482. ? options.localeFallbacker
  2483. : _fallbacker || fallbackWithSimple;
  2484. const fallbackContext = isObject(options.fallbackContext)
  2485. ? options.fallbackContext
  2486. : undefined;
  2487. // setup internal options
  2488. const internalOptions = options;
  2489. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  2490. ? internalOptions.__datetimeFormatters
  2491. : new Map()
  2492. ;
  2493. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  2494. ? internalOptions.__numberFormatters
  2495. : new Map()
  2496. ;
  2497. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  2498. _cid++;
  2499. const context = {
  2500. version,
  2501. cid: _cid,
  2502. locale,
  2503. fallbackLocale,
  2504. messages,
  2505. modifiers,
  2506. pluralRules,
  2507. missing,
  2508. missingWarn,
  2509. fallbackWarn,
  2510. fallbackFormat,
  2511. unresolving,
  2512. postTranslation,
  2513. processor,
  2514. warnHtmlMessage,
  2515. escapeParameter,
  2516. messageCompiler,
  2517. messageResolver,
  2518. localeFallbacker,
  2519. fallbackContext,
  2520. onWarn,
  2521. __meta
  2522. };
  2523. {
  2524. context.datetimeFormats = datetimeFormats;
  2525. context.numberFormats = numberFormats;
  2526. context.__datetimeFormatters = __datetimeFormatters;
  2527. context.__numberFormatters = __numberFormatters;
  2528. }
  2529. // for vue-devtools timeline event
  2530. {
  2531. context.__v_emitter =
  2532. internalOptions.__v_emitter != null
  2533. ? internalOptions.__v_emitter
  2534. : undefined;
  2535. }
  2536. // NOTE: experimental !!
  2537. {
  2538. initI18nDevTools(context, version, __meta);
  2539. }
  2540. return context;
  2541. }
  2542. /** @internal */
  2543. function isTranslateFallbackWarn(fallback, key) {
  2544. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  2545. }
  2546. /** @internal */
  2547. function isTranslateMissingWarn(missing, key) {
  2548. return missing instanceof RegExp ? missing.test(key) : missing;
  2549. }
  2550. /** @internal */
  2551. function handleMissing(context, key, locale, missingWarn, type) {
  2552. const { missing, onWarn } = context;
  2553. // for vue-devtools timeline event
  2554. {
  2555. const emitter = context.__v_emitter;
  2556. if (emitter) {
  2557. emitter.emit("missing" /* VueDevToolsTimelineEvents.MISSING */, {
  2558. locale,
  2559. key,
  2560. type,
  2561. groupId: `${type}:${key}`
  2562. });
  2563. }
  2564. }
  2565. if (missing !== null) {
  2566. const ret = missing(context, locale, key, type);
  2567. return isString(ret) ? ret : key;
  2568. }
  2569. else {
  2570. if (isTranslateMissingWarn(missingWarn, key)) {
  2571. onWarn(getWarnMessage$1(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
  2572. }
  2573. return key;
  2574. }
  2575. }
  2576. /** @internal */
  2577. function updateFallbackLocale(ctx, locale, fallback) {
  2578. const context = ctx;
  2579. context.__localeChainCache = new Map();
  2580. ctx.localeFallbacker(ctx, fallback, locale);
  2581. }
  2582. /* eslint-enable @typescript-eslint/no-explicit-any */
  2583. function format(ast) {
  2584. const msg = (ctx) => formatParts(ctx, ast);
  2585. return msg;
  2586. }
  2587. function formatParts(ctx, ast) {
  2588. const body = ast.b || ast.body;
  2589. if ((body.t || body.type) === 1 /* NodeTypes.Plural */) {
  2590. const plural = body;
  2591. const cases = plural.c || plural.cases;
  2592. return ctx.plural(cases.reduce((messages, c) => [
  2593. ...messages,
  2594. formatMessageParts(ctx, c)
  2595. ], []));
  2596. }
  2597. else {
  2598. return formatMessageParts(ctx, body);
  2599. }
  2600. }
  2601. function formatMessageParts(ctx, node) {
  2602. const _static = node.s || node.static;
  2603. if (_static) {
  2604. return ctx.type === 'text'
  2605. ? _static
  2606. : ctx.normalize([_static]);
  2607. }
  2608. else {
  2609. const messages = (node.i || node.items).reduce((acm, c) => [...acm, formatMessagePart(ctx, c)], []);
  2610. return ctx.normalize(messages);
  2611. }
  2612. }
  2613. function formatMessagePart(ctx, node) {
  2614. const type = node.t || node.type;
  2615. switch (type) {
  2616. case 3 /* NodeTypes.Text */:
  2617. const text = node;
  2618. return (text.v || text.value);
  2619. case 9 /* NodeTypes.Literal */:
  2620. const literal = node;
  2621. return (literal.v || literal.value);
  2622. case 4 /* NodeTypes.Named */:
  2623. const named = node;
  2624. return ctx.interpolate(ctx.named(named.k || named.key));
  2625. case 5 /* NodeTypes.List */:
  2626. const list = node;
  2627. return ctx.interpolate(ctx.list(list.i != null ? list.i : list.index));
  2628. case 6 /* NodeTypes.Linked */:
  2629. const linked = node;
  2630. const modifier = linked.m || linked.modifier;
  2631. return ctx.linked(formatMessagePart(ctx, linked.k || linked.key), modifier ? formatMessagePart(ctx, modifier) : undefined, ctx.type);
  2632. case 7 /* NodeTypes.LinkedKey */:
  2633. const linkedKey = node;
  2634. return (linkedKey.v || linkedKey.value);
  2635. case 8 /* NodeTypes.LinkedModifier */:
  2636. const linkedModifier = node;
  2637. return (linkedModifier.v || linkedModifier.value);
  2638. default:
  2639. throw new Error(`unhandled node type on format message part: ${type}`);
  2640. }
  2641. }
  2642. const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
  2643. function checkHtmlMessage(source, warnHtmlMessage) {
  2644. if (warnHtmlMessage && detectHtmlTag(source)) {
  2645. warn(format$1(WARN_MESSAGE, { source }));
  2646. }
  2647. }
  2648. const defaultOnCacheKey = (message) => message;
  2649. let compileCache = Object.create(null);
  2650. const isMessageAST = (val) => isObject(val) &&
  2651. (val.t === 0 || val.type === 0) &&
  2652. ('b' in val || 'body' in val);
  2653. function baseCompile(message, options = {}) {
  2654. // error detecting on compile
  2655. let detectError = false;
  2656. const onError = options.onError || defaultOnError;
  2657. options.onError = (err) => {
  2658. detectError = true;
  2659. onError(err);
  2660. };
  2661. // compile with mesasge-compiler
  2662. return { ...baseCompile$1(message, options), detectError };
  2663. }
  2664. function compile(message, context) {
  2665. if (isString(message)) {
  2666. // check HTML message
  2667. const warnHtmlMessage = isBoolean(context.warnHtmlMessage)
  2668. ? context.warnHtmlMessage
  2669. : true;
  2670. checkHtmlMessage(message, warnHtmlMessage);
  2671. // check caches
  2672. const onCacheKey = context.onCacheKey || defaultOnCacheKey;
  2673. const cacheKey = onCacheKey(message);
  2674. const cached = compileCache[cacheKey];
  2675. if (cached) {
  2676. return cached;
  2677. }
  2678. // compile with JIT mode
  2679. const { ast, detectError } = baseCompile(message, {
  2680. ...context,
  2681. location: true,
  2682. jit: true
  2683. });
  2684. // compose message function from AST
  2685. const msg = format(ast);
  2686. // if occurred compile error, don't cache
  2687. return !detectError
  2688. ? (compileCache[cacheKey] = msg)
  2689. : msg;
  2690. }
  2691. else {
  2692. if (!isMessageAST(message)) {
  2693. warn(`the message that is resolve with key '${context.key}' is not supported for jit compilation`);
  2694. return (() => message);
  2695. }
  2696. // AST case (passed from bundler)
  2697. const cacheKey = message.cacheKey;
  2698. if (cacheKey) {
  2699. const cached = compileCache[cacheKey];
  2700. if (cached) {
  2701. return cached;
  2702. }
  2703. // compose message function from message (AST)
  2704. return (compileCache[cacheKey] =
  2705. format(message));
  2706. }
  2707. else {
  2708. return format(message);
  2709. }
  2710. }
  2711. }
  2712. const NOOP_MESSAGE_FUNCTION = () => '';
  2713. const isMessageFunction = (val) => isFunction(val);
  2714. // implementation of `translate` function
  2715. function translate(context, ...args) {
  2716. const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  2717. const [key, options] = parseTranslateArgs(...args);
  2718. const missingWarn = isBoolean(options.missingWarn)
  2719. ? options.missingWarn
  2720. : context.missingWarn;
  2721. const fallbackWarn = isBoolean(options.fallbackWarn)
  2722. ? options.fallbackWarn
  2723. : context.fallbackWarn;
  2724. const escapeParameter = isBoolean(options.escapeParameter)
  2725. ? options.escapeParameter
  2726. : context.escapeParameter;
  2727. const resolvedMessage = !!options.resolvedMessage;
  2728. // prettier-ignore
  2729. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  2730. ? !isBoolean(options.default)
  2731. ? options.default
  2732. : (!messageCompiler ? () => key : key)
  2733. : fallbackFormat // default by `fallbackFormat` option
  2734. ? (!messageCompiler ? () => key : key)
  2735. : '';
  2736. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  2737. const locale = getLocale(context, options);
  2738. // escape params
  2739. escapeParameter && escapeParams(options);
  2740. // resolve message format
  2741. // eslint-disable-next-line prefer-const
  2742. let [formatScope, targetLocale, message] = !resolvedMessage
  2743. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  2744. : [
  2745. key,
  2746. locale,
  2747. messages[locale] || {}
  2748. ];
  2749. // NOTE:
  2750. // Fix to work around `ssrTransfrom` bug in Vite.
  2751. // https://github.com/vitejs/vite/issues/4306
  2752. // To get around this, use temporary variables.
  2753. // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
  2754. let format = formatScope;
  2755. // if you use default message, set it as message format!
  2756. let cacheBaseKey = key;
  2757. if (!resolvedMessage &&
  2758. !(isString(format) ||
  2759. isMessageAST(format) ||
  2760. isMessageFunction(format))) {
  2761. if (enableDefaultMsg) {
  2762. format = defaultMsgOrKey;
  2763. cacheBaseKey = format;
  2764. }
  2765. }
  2766. // checking message format and target locale
  2767. if (!resolvedMessage &&
  2768. (!(isString(format) ||
  2769. isMessageAST(format) ||
  2770. isMessageFunction(format)) ||
  2771. !isString(targetLocale))) {
  2772. return unresolving ? NOT_REOSLVED : key;
  2773. }
  2774. // TODO: refactor
  2775. if (isString(format) && context.messageCompiler == null) {
  2776. warn(`The message format compilation is not supported in this build. ` +
  2777. `Because message compiler isn't included. ` +
  2778. `You need to pre-compilation all message format. ` +
  2779. `So translate function return '${key}'.`);
  2780. return key;
  2781. }
  2782. // setup compile error detecting
  2783. let occurred = false;
  2784. const onError = () => {
  2785. occurred = true;
  2786. };
  2787. // compile message format
  2788. const msg = !isMessageFunction(format)
  2789. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
  2790. : format;
  2791. // if occurred compile error, return the message format
  2792. if (occurred) {
  2793. return format;
  2794. }
  2795. // evaluate message with context
  2796. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  2797. const msgContext = createMessageContext(ctxOptions);
  2798. const messaged = evaluateMessage(context, msg, msgContext);
  2799. // if use post translation option, proceed it with handler
  2800. const ret = postTranslation
  2801. ? postTranslation(messaged, key)
  2802. : messaged;
  2803. // NOTE: experimental !!
  2804. {
  2805. // prettier-ignore
  2806. const payloads = {
  2807. timestamp: Date.now(),
  2808. key: isString(key)
  2809. ? key
  2810. : isMessageFunction(format)
  2811. ? format.key
  2812. : '',
  2813. locale: targetLocale || (isMessageFunction(format)
  2814. ? format.locale
  2815. : ''),
  2816. format: isString(format)
  2817. ? format
  2818. : isMessageFunction(format)
  2819. ? format.source
  2820. : '',
  2821. message: ret
  2822. };
  2823. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  2824. translateDevTools(payloads);
  2825. }
  2826. return ret;
  2827. }
  2828. function escapeParams(options) {
  2829. if (isArray(options.list)) {
  2830. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  2831. }
  2832. else if (isObject(options.named)) {
  2833. Object.keys(options.named).forEach(key => {
  2834. if (isString(options.named[key])) {
  2835. options.named[key] = escapeHtml(options.named[key]);
  2836. }
  2837. });
  2838. }
  2839. }
  2840. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  2841. const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
  2842. const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
  2843. let message = {};
  2844. let targetLocale;
  2845. let format = null;
  2846. let from = locale;
  2847. let to = null;
  2848. const type = 'translate';
  2849. for (let i = 0; i < locales.length; i++) {
  2850. targetLocale = to = locales[i];
  2851. if (locale !== targetLocale &&
  2852. isTranslateFallbackWarn(fallbackWarn, key)) {
  2853. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
  2854. key,
  2855. target: targetLocale
  2856. }));
  2857. }
  2858. // for vue-devtools timeline event
  2859. if (locale !== targetLocale) {
  2860. const emitter = context.__v_emitter;
  2861. if (emitter) {
  2862. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  2863. type,
  2864. key,
  2865. from,
  2866. to,
  2867. groupId: `${type}:${key}`
  2868. });
  2869. }
  2870. }
  2871. message =
  2872. messages[targetLocale] || {};
  2873. // for vue-devtools timeline event
  2874. let start = null;
  2875. let startTag;
  2876. let endTag;
  2877. if (inBrowser) {
  2878. start = window.performance.now();
  2879. startTag = 'intlify-message-resolve-start';
  2880. endTag = 'intlify-message-resolve-end';
  2881. mark && mark(startTag);
  2882. }
  2883. if ((format = resolveValue(message, key)) === null) {
  2884. // if null, resolve with object key path
  2885. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  2886. }
  2887. // for vue-devtools timeline event
  2888. if (inBrowser) {
  2889. const end = window.performance.now();
  2890. const emitter = context.__v_emitter;
  2891. if (emitter && start && format) {
  2892. emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
  2893. type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
  2894. key,
  2895. message: format,
  2896. time: end - start,
  2897. groupId: `${type}:${key}`
  2898. });
  2899. }
  2900. if (startTag && endTag && mark && measure) {
  2901. mark(endTag);
  2902. measure('intlify message resolve', startTag, endTag);
  2903. }
  2904. }
  2905. if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
  2906. break;
  2907. }
  2908. const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  2909. key, targetLocale, missingWarn, type);
  2910. if (missingRet !== key) {
  2911. format = missingRet;
  2912. }
  2913. from = to;
  2914. }
  2915. return [format, targetLocale, message];
  2916. }
  2917. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
  2918. const { messageCompiler, warnHtmlMessage } = context;
  2919. if (isMessageFunction(format)) {
  2920. const msg = format;
  2921. msg.locale = msg.locale || targetLocale;
  2922. msg.key = msg.key || key;
  2923. return msg;
  2924. }
  2925. if (messageCompiler == null) {
  2926. const msg = (() => format);
  2927. msg.locale = targetLocale;
  2928. msg.key = key;
  2929. return msg;
  2930. }
  2931. // for vue-devtools timeline event
  2932. let start = null;
  2933. let startTag;
  2934. let endTag;
  2935. if (inBrowser) {
  2936. start = window.performance.now();
  2937. startTag = 'intlify-message-compilation-start';
  2938. endTag = 'intlify-message-compilation-end';
  2939. mark && mark(startTag);
  2940. }
  2941. const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
  2942. // for vue-devtools timeline event
  2943. if (inBrowser) {
  2944. const end = window.performance.now();
  2945. const emitter = context.__v_emitter;
  2946. if (emitter && start) {
  2947. emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
  2948. type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
  2949. message: format,
  2950. time: end - start,
  2951. groupId: `${'translate'}:${key}`
  2952. });
  2953. }
  2954. if (startTag && endTag && mark && measure) {
  2955. mark(endTag);
  2956. measure('intlify message compilation', startTag, endTag);
  2957. }
  2958. }
  2959. msg.locale = targetLocale;
  2960. msg.key = key;
  2961. msg.source = format;
  2962. return msg;
  2963. }
  2964. function evaluateMessage(context, msg, msgCtx) {
  2965. // for vue-devtools timeline event
  2966. let start = null;
  2967. let startTag;
  2968. let endTag;
  2969. if (inBrowser) {
  2970. start = window.performance.now();
  2971. startTag = 'intlify-message-evaluation-start';
  2972. endTag = 'intlify-message-evaluation-end';
  2973. mark && mark(startTag);
  2974. }
  2975. const messaged = msg(msgCtx);
  2976. // for vue-devtools timeline event
  2977. if (inBrowser) {
  2978. const end = window.performance.now();
  2979. const emitter = context.__v_emitter;
  2980. if (emitter && start) {
  2981. emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
  2982. type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
  2983. value: messaged,
  2984. time: end - start,
  2985. groupId: `${'translate'}:${msg.key}`
  2986. });
  2987. }
  2988. if (startTag && endTag && mark && measure) {
  2989. mark(endTag);
  2990. measure('intlify message evaluation', startTag, endTag);
  2991. }
  2992. }
  2993. return messaged;
  2994. }
  2995. /** @internal */
  2996. function parseTranslateArgs(...args) {
  2997. const [arg1, arg2, arg3] = args;
  2998. const options = {};
  2999. if (!isString(arg1) &&
  3000. !isNumber(arg1) &&
  3001. !isMessageFunction(arg1) &&
  3002. !isMessageAST(arg1)) {
  3003. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3004. }
  3005. // prettier-ignore
  3006. const key = isNumber(arg1)
  3007. ? String(arg1)
  3008. : isMessageFunction(arg1)
  3009. ? arg1
  3010. : arg1;
  3011. if (isNumber(arg2)) {
  3012. options.plural = arg2;
  3013. }
  3014. else if (isString(arg2)) {
  3015. options.default = arg2;
  3016. }
  3017. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  3018. options.named = arg2;
  3019. }
  3020. else if (isArray(arg2)) {
  3021. options.list = arg2;
  3022. }
  3023. if (isNumber(arg3)) {
  3024. options.plural = arg3;
  3025. }
  3026. else if (isString(arg3)) {
  3027. options.default = arg3;
  3028. }
  3029. else if (isPlainObject(arg3)) {
  3030. assign(options, arg3);
  3031. }
  3032. return [key, options];
  3033. }
  3034. function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  3035. return {
  3036. locale,
  3037. key,
  3038. warnHtmlMessage,
  3039. onError: (err) => {
  3040. onError && onError(err);
  3041. {
  3042. const _source = getSourceForCodeFrame(source);
  3043. const message = `Message compilation error: ${err.message}`;
  3044. const codeFrame = err.location &&
  3045. _source &&
  3046. generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
  3047. const emitter = context.__v_emitter;
  3048. if (emitter && _source) {
  3049. emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
  3050. message: _source,
  3051. error: err.message,
  3052. start: err.location && err.location.start.offset,
  3053. end: err.location && err.location.end.offset,
  3054. groupId: `${'translate'}:${key}`
  3055. });
  3056. }
  3057. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  3058. }
  3059. },
  3060. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  3061. };
  3062. }
  3063. function getSourceForCodeFrame(source) {
  3064. if (isString(source)) {
  3065. return source;
  3066. }
  3067. else {
  3068. if (source.loc && source.loc.source) {
  3069. return source.loc.source;
  3070. }
  3071. }
  3072. }
  3073. function getMessageContextOptions(context, locale, message, options) {
  3074. const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  3075. const resolveMessage = (key) => {
  3076. let val = resolveValue(message, key);
  3077. // fallback to root context
  3078. if (val == null && fallbackContext) {
  3079. const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
  3080. val = resolveValue(message, key);
  3081. }
  3082. if (isString(val) || isMessageAST(val)) {
  3083. let occurred = false;
  3084. const onError = () => {
  3085. occurred = true;
  3086. };
  3087. const msg = compileMessageFormat(context, key, locale, val, key, onError);
  3088. return !occurred
  3089. ? msg
  3090. : NOOP_MESSAGE_FUNCTION;
  3091. }
  3092. else if (isMessageFunction(val)) {
  3093. return val;
  3094. }
  3095. else {
  3096. // TODO: should be implemented warning message
  3097. return NOOP_MESSAGE_FUNCTION;
  3098. }
  3099. };
  3100. const ctxOptions = {
  3101. locale,
  3102. modifiers,
  3103. pluralRules,
  3104. messages: resolveMessage
  3105. };
  3106. if (context.processor) {
  3107. ctxOptions.processor = context.processor;
  3108. }
  3109. if (options.list) {
  3110. ctxOptions.list = options.list;
  3111. }
  3112. if (options.named) {
  3113. ctxOptions.named = options.named;
  3114. }
  3115. if (isNumber(options.plural)) {
  3116. ctxOptions.pluralIndex = options.plural;
  3117. }
  3118. return ctxOptions;
  3119. }
  3120. const intlDefined = typeof Intl !== 'undefined';
  3121. const Availabilities = {
  3122. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  3123. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  3124. };
  3125. // implementation of `datetime` function
  3126. function datetime(context, ...args) {
  3127. const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  3128. const { __datetimeFormatters } = context;
  3129. if (!Availabilities.dateTimeFormat) {
  3130. onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_DATE));
  3131. return MISSING_RESOLVE_VALUE;
  3132. }
  3133. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  3134. const missingWarn = isBoolean(options.missingWarn)
  3135. ? options.missingWarn
  3136. : context.missingWarn;
  3137. const fallbackWarn = isBoolean(options.fallbackWarn)
  3138. ? options.fallbackWarn
  3139. : context.fallbackWarn;
  3140. const part = !!options.part;
  3141. const locale = getLocale(context, options);
  3142. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  3143. fallbackLocale, locale);
  3144. if (!isString(key) || key === '') {
  3145. return new Intl.DateTimeFormat(locale, overrides).format(value);
  3146. }
  3147. // resolve format
  3148. let datetimeFormat = {};
  3149. let targetLocale;
  3150. let format = null;
  3151. let from = locale;
  3152. let to = null;
  3153. const type = 'datetime format';
  3154. for (let i = 0; i < locales.length; i++) {
  3155. targetLocale = to = locales[i];
  3156. if (locale !== targetLocale &&
  3157. isTranslateFallbackWarn(fallbackWarn, key)) {
  3158. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
  3159. key,
  3160. target: targetLocale
  3161. }));
  3162. }
  3163. // for vue-devtools timeline event
  3164. if (locale !== targetLocale) {
  3165. const emitter = context.__v_emitter;
  3166. if (emitter) {
  3167. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  3168. type,
  3169. key,
  3170. from,
  3171. to,
  3172. groupId: `${type}:${key}`
  3173. });
  3174. }
  3175. }
  3176. datetimeFormat =
  3177. datetimeFormats[targetLocale] || {};
  3178. format = datetimeFormat[key];
  3179. if (isPlainObject(format))
  3180. break;
  3181. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  3182. from = to;
  3183. }
  3184. // checking format and target locale
  3185. if (!isPlainObject(format) || !isString(targetLocale)) {
  3186. return unresolving ? NOT_REOSLVED : key;
  3187. }
  3188. let id = `${targetLocale}__${key}`;
  3189. if (!isEmptyObject(overrides)) {
  3190. id = `${id}__${JSON.stringify(overrides)}`;
  3191. }
  3192. let formatter = __datetimeFormatters.get(id);
  3193. if (!formatter) {
  3194. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  3195. __datetimeFormatters.set(id, formatter);
  3196. }
  3197. return !part ? formatter.format(value) : formatter.formatToParts(value);
  3198. }
  3199. /** @internal */
  3200. const DATETIME_FORMAT_OPTIONS_KEYS = [
  3201. 'localeMatcher',
  3202. 'weekday',
  3203. 'era',
  3204. 'year',
  3205. 'month',
  3206. 'day',
  3207. 'hour',
  3208. 'minute',
  3209. 'second',
  3210. 'timeZoneName',
  3211. 'formatMatcher',
  3212. 'hour12',
  3213. 'timeZone',
  3214. 'dateStyle',
  3215. 'timeStyle',
  3216. 'calendar',
  3217. 'dayPeriod',
  3218. 'numberingSystem',
  3219. 'hourCycle',
  3220. 'fractionalSecondDigits'
  3221. ];
  3222. /** @internal */
  3223. function parseDateTimeArgs(...args) {
  3224. const [arg1, arg2, arg3, arg4] = args;
  3225. const options = {};
  3226. let overrides = {};
  3227. let value;
  3228. if (isString(arg1)) {
  3229. // Only allow ISO strings - other date formats are often supported,
  3230. // but may cause different results in different browsers.
  3231. const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
  3232. if (!matches) {
  3233. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  3234. }
  3235. // Some browsers can not parse the iso datetime separated by space,
  3236. // this is a compromise solution by replace the 'T'/' ' with 'T'
  3237. const dateTime = matches[3]
  3238. ? matches[3].trim().startsWith('T')
  3239. ? `${matches[1].trim()}${matches[3].trim()}`
  3240. : `${matches[1].trim()}T${matches[3].trim()}`
  3241. : matches[1].trim();
  3242. value = new Date(dateTime);
  3243. try {
  3244. // This will fail if the date is not valid
  3245. value.toISOString();
  3246. }
  3247. catch (e) {
  3248. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  3249. }
  3250. }
  3251. else if (isDate(arg1)) {
  3252. if (isNaN(arg1.getTime())) {
  3253. throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
  3254. }
  3255. value = arg1;
  3256. }
  3257. else if (isNumber(arg1)) {
  3258. value = arg1;
  3259. }
  3260. else {
  3261. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3262. }
  3263. if (isString(arg2)) {
  3264. options.key = arg2;
  3265. }
  3266. else if (isPlainObject(arg2)) {
  3267. Object.keys(arg2).forEach(key => {
  3268. if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
  3269. overrides[key] = arg2[key];
  3270. }
  3271. else {
  3272. options[key] = arg2[key];
  3273. }
  3274. });
  3275. }
  3276. if (isString(arg3)) {
  3277. options.locale = arg3;
  3278. }
  3279. else if (isPlainObject(arg3)) {
  3280. overrides = arg3;
  3281. }
  3282. if (isPlainObject(arg4)) {
  3283. overrides = arg4;
  3284. }
  3285. return [options.key || '', value, options, overrides];
  3286. }
  3287. /** @internal */
  3288. function clearDateTimeFormat(ctx, locale, format) {
  3289. const context = ctx;
  3290. for (const key in format) {
  3291. const id = `${locale}__${key}`;
  3292. if (!context.__datetimeFormatters.has(id)) {
  3293. continue;
  3294. }
  3295. context.__datetimeFormatters.delete(id);
  3296. }
  3297. }
  3298. // implementation of `number` function
  3299. function number(context, ...args) {
  3300. const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  3301. const { __numberFormatters } = context;
  3302. if (!Availabilities.numberFormat) {
  3303. onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
  3304. return MISSING_RESOLVE_VALUE;
  3305. }
  3306. const [key, value, options, overrides] = parseNumberArgs(...args);
  3307. const missingWarn = isBoolean(options.missingWarn)
  3308. ? options.missingWarn
  3309. : context.missingWarn;
  3310. const fallbackWarn = isBoolean(options.fallbackWarn)
  3311. ? options.fallbackWarn
  3312. : context.fallbackWarn;
  3313. const part = !!options.part;
  3314. const locale = getLocale(context, options);
  3315. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  3316. fallbackLocale, locale);
  3317. if (!isString(key) || key === '') {
  3318. return new Intl.NumberFormat(locale, overrides).format(value);
  3319. }
  3320. // resolve format
  3321. let numberFormat = {};
  3322. let targetLocale;
  3323. let format = null;
  3324. let from = locale;
  3325. let to = null;
  3326. const type = 'number format';
  3327. for (let i = 0; i < locales.length; i++) {
  3328. targetLocale = to = locales[i];
  3329. if (locale !== targetLocale &&
  3330. isTranslateFallbackWarn(fallbackWarn, key)) {
  3331. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
  3332. key,
  3333. target: targetLocale
  3334. }));
  3335. }
  3336. // for vue-devtools timeline event
  3337. if (locale !== targetLocale) {
  3338. const emitter = context.__v_emitter;
  3339. if (emitter) {
  3340. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  3341. type,
  3342. key,
  3343. from,
  3344. to,
  3345. groupId: `${type}:${key}`
  3346. });
  3347. }
  3348. }
  3349. numberFormat =
  3350. numberFormats[targetLocale] || {};
  3351. format = numberFormat[key];
  3352. if (isPlainObject(format))
  3353. break;
  3354. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  3355. from = to;
  3356. }
  3357. // checking format and target locale
  3358. if (!isPlainObject(format) || !isString(targetLocale)) {
  3359. return unresolving ? NOT_REOSLVED : key;
  3360. }
  3361. let id = `${targetLocale}__${key}`;
  3362. if (!isEmptyObject(overrides)) {
  3363. id = `${id}__${JSON.stringify(overrides)}`;
  3364. }
  3365. let formatter = __numberFormatters.get(id);
  3366. if (!formatter) {
  3367. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  3368. __numberFormatters.set(id, formatter);
  3369. }
  3370. return !part ? formatter.format(value) : formatter.formatToParts(value);
  3371. }
  3372. /** @internal */
  3373. const NUMBER_FORMAT_OPTIONS_KEYS = [
  3374. 'localeMatcher',
  3375. 'style',
  3376. 'currency',
  3377. 'currencyDisplay',
  3378. 'currencySign',
  3379. 'useGrouping',
  3380. 'minimumIntegerDigits',
  3381. 'minimumFractionDigits',
  3382. 'maximumFractionDigits',
  3383. 'minimumSignificantDigits',
  3384. 'maximumSignificantDigits',
  3385. 'compactDisplay',
  3386. 'notation',
  3387. 'signDisplay',
  3388. 'unit',
  3389. 'unitDisplay',
  3390. 'roundingMode',
  3391. 'roundingPriority',
  3392. 'roundingIncrement',
  3393. 'trailingZeroDisplay'
  3394. ];
  3395. /** @internal */
  3396. function parseNumberArgs(...args) {
  3397. const [arg1, arg2, arg3, arg4] = args;
  3398. const options = {};
  3399. let overrides = {};
  3400. if (!isNumber(arg1)) {
  3401. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  3402. }
  3403. const value = arg1;
  3404. if (isString(arg2)) {
  3405. options.key = arg2;
  3406. }
  3407. else if (isPlainObject(arg2)) {
  3408. Object.keys(arg2).forEach(key => {
  3409. if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
  3410. overrides[key] = arg2[key];
  3411. }
  3412. else {
  3413. options[key] = arg2[key];
  3414. }
  3415. });
  3416. }
  3417. if (isString(arg3)) {
  3418. options.locale = arg3;
  3419. }
  3420. else if (isPlainObject(arg3)) {
  3421. overrides = arg3;
  3422. }
  3423. if (isPlainObject(arg4)) {
  3424. overrides = arg4;
  3425. }
  3426. return [options.key || '', value, options, overrides];
  3427. }
  3428. /** @internal */
  3429. function clearNumberFormat(ctx, locale, format) {
  3430. const context = ctx;
  3431. for (const key in format) {
  3432. const id = `${locale}__${key}`;
  3433. if (!context.__numberFormatters.has(id)) {
  3434. continue;
  3435. }
  3436. context.__numberFormatters.delete(id);
  3437. }
  3438. }
  3439. /**
  3440. * Vue I18n Version
  3441. *
  3442. * @remarks
  3443. * Semver format. Same format as the package.json `version` field.
  3444. *
  3445. * @VueI18nGeneral
  3446. */
  3447. const VERSION = '9.8.0';
  3448. /**
  3449. * This is only called development env
  3450. * istanbul-ignore-next
  3451. */
  3452. function initDev() {
  3453. {
  3454. {
  3455. console.info(`You are running a development build of vue-i18n.\n` +
  3456. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  3457. }
  3458. }
  3459. }
  3460. const code$1 = CoreWarnCodes.__EXTEND_POINT__;
  3461. const inc$1 = incrementer(code$1);
  3462. const I18nWarnCodes = {
  3463. FALLBACK_TO_ROOT: code$1,
  3464. NOT_SUPPORTED_PRESERVE: inc$1(),
  3465. NOT_SUPPORTED_FORMATTER: inc$1(),
  3466. NOT_SUPPORTED_PRESERVE_DIRECTIVE: inc$1(),
  3467. NOT_SUPPORTED_GET_CHOICE_INDEX: inc$1(),
  3468. COMPONENT_NAME_LEGACY_COMPATIBLE: inc$1(),
  3469. NOT_FOUND_PARENT_SCOPE: inc$1(),
  3470. IGNORE_OBJ_FLATTEN: inc$1(),
  3471. NOTICE_DROP_ALLOW_COMPOSITION: inc$1() // 17
  3472. };
  3473. const warnMessages = {
  3474. [I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,
  3475. [I18nWarnCodes.NOT_SUPPORTED_PRESERVE]: `Not supported 'preserve'.`,
  3476. [I18nWarnCodes.NOT_SUPPORTED_FORMATTER]: `Not supported 'formatter'.`,
  3477. [I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE]: `Not supported 'preserveDirectiveContent'.`,
  3478. [I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX]: `Not supported 'getChoiceIndex'.`,
  3479. [I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE]: `Component name legacy compatible: '{name}' -> 'i18n'`,
  3480. [I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,
  3481. [I18nWarnCodes.IGNORE_OBJ_FLATTEN]: `Ignore object flatten: '{key}' key has an string value`,
  3482. [I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION]: `'allowComposition' option will be dropped in the next major version. For more information, please see 👉 https://tinyurl.com/2p97mcze`
  3483. };
  3484. function getWarnMessage(code, ...args) {
  3485. return format$1(warnMessages[code], ...args);
  3486. }
  3487. const code = CoreErrorCodes.__EXTEND_POINT__;
  3488. const inc = incrementer(code);
  3489. const I18nErrorCodes = {
  3490. // composer module errors
  3491. UNEXPECTED_RETURN_TYPE: code,
  3492. // legacy module errors
  3493. INVALID_ARGUMENT: inc(),
  3494. // i18n module errors
  3495. MUST_BE_CALL_SETUP_TOP: inc(),
  3496. NOT_INSTALLED: inc(),
  3497. NOT_AVAILABLE_IN_LEGACY_MODE: inc(),
  3498. // directive module errors
  3499. REQUIRED_VALUE: inc(),
  3500. INVALID_VALUE: inc(),
  3501. // vue-devtools errors
  3502. CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: inc(),
  3503. NOT_INSTALLED_WITH_PROVIDE: inc(),
  3504. // unexpected error
  3505. UNEXPECTED_ERROR: inc(),
  3506. // not compatible legacy vue-i18n constructor
  3507. NOT_COMPATIBLE_LEGACY_VUE_I18N: inc(),
  3508. // bridge support vue 2.x only
  3509. BRIDGE_SUPPORT_VUE_2_ONLY: inc(),
  3510. // need to define `i18n` option in `allowComposition: true` and `useScope: 'local' at `useI18n``
  3511. MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION: inc(),
  3512. // Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly
  3513. NOT_AVAILABLE_COMPOSITION_IN_LEGACY: inc(),
  3514. // for enhancement
  3515. __EXTEND_POINT__: inc() // 40
  3516. };
  3517. function createI18nError(code, ...args) {
  3518. return createCompileError(code, null, { messages: errorMessages, args } );
  3519. }
  3520. const errorMessages = {
  3521. [I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',
  3522. [I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',
  3523. [I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',
  3524. [I18nErrorCodes.NOT_INSTALLED]: 'Need to install with `app.use` function',
  3525. [I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',
  3526. [I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE]: 'Not available in legacy mode',
  3527. [I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,
  3528. [I18nErrorCodes.INVALID_VALUE]: `Invalid value`,
  3529. [I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,
  3530. [I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE]: 'Need to install with `provide` function',
  3531. [I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',
  3532. [I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY]: 'vue-i18n-bridge support Vue 2.x only',
  3533. [I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION]: 'Must define ‘i18n’ option or custom block in Composition API with using local scope in Legacy API mode',
  3534. [I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY]: 'Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly'
  3535. };
  3536. const TranslateVNodeSymbol =
  3537. /* #__PURE__*/ makeSymbol('__translateVNode');
  3538. const DatetimePartsSymbol = /* #__PURE__*/ makeSymbol('__datetimeParts');
  3539. const NumberPartsSymbol = /* #__PURE__*/ makeSymbol('__numberParts');
  3540. const EnableEmitter = /* #__PURE__*/ makeSymbol('__enableEmitter');
  3541. const DisableEmitter = /* #__PURE__*/ makeSymbol('__disableEmitter');
  3542. const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
  3543. const InejctWithOptionSymbol =
  3544. /* #__PURE__*/ makeSymbol('__injectWithOption');
  3545. const DisposeSymbol = /* #__PURE__*/ makeSymbol('__dispose');
  3546. const __VUE_I18N_BRIDGE__ = '__VUE_I18N_BRIDGE__';
  3547. /* eslint-disable @typescript-eslint/no-explicit-any */
  3548. /**
  3549. * Transform flat json in obj to normal json in obj
  3550. */
  3551. function handleFlatJson(obj) {
  3552. // check obj
  3553. if (!isObject(obj)) {
  3554. return obj;
  3555. }
  3556. for (const key in obj) {
  3557. // check key
  3558. if (!hasOwn(obj, key)) {
  3559. continue;
  3560. }
  3561. // handle for normal json
  3562. if (!key.includes('.')) {
  3563. // recursive process value if value is also a object
  3564. if (isObject(obj[key])) {
  3565. handleFlatJson(obj[key]);
  3566. }
  3567. }
  3568. // handle for flat json, transform to normal json
  3569. else {
  3570. // go to the last object
  3571. const subKeys = key.split('.');
  3572. const lastIndex = subKeys.length - 1;
  3573. let currentObj = obj;
  3574. let hasStringValue = false;
  3575. for (let i = 0; i < lastIndex; i++) {
  3576. if (!(subKeys[i] in currentObj)) {
  3577. currentObj[subKeys[i]] = {};
  3578. }
  3579. if (!isObject(currentObj[subKeys[i]])) {
  3580. warn(getWarnMessage(I18nWarnCodes.IGNORE_OBJ_FLATTEN, {
  3581. key: subKeys[i]
  3582. }));
  3583. hasStringValue = true;
  3584. break;
  3585. }
  3586. currentObj = currentObj[subKeys[i]];
  3587. }
  3588. // update last object value, delete old property
  3589. if (!hasStringValue) {
  3590. currentObj[subKeys[lastIndex]] = obj[key];
  3591. delete obj[key];
  3592. }
  3593. // recursive process value if value is also a object
  3594. if (isObject(currentObj[subKeys[lastIndex]])) {
  3595. handleFlatJson(currentObj[subKeys[lastIndex]]);
  3596. }
  3597. }
  3598. }
  3599. return obj;
  3600. }
  3601. function getLocaleMessages(locale, options) {
  3602. const { messages, __i18n, messageResolver, flatJson } = options;
  3603. // prettier-ignore
  3604. const ret = (isPlainObject(messages)
  3605. ? messages
  3606. : isArray(__i18n)
  3607. ? {}
  3608. : { [locale]: {} });
  3609. // merge locale messages of i18n custom block
  3610. if (isArray(__i18n)) {
  3611. __i18n.forEach(custom => {
  3612. if ('locale' in custom && 'resource' in custom) {
  3613. const { locale, resource } = custom;
  3614. if (locale) {
  3615. ret[locale] = ret[locale] || {};
  3616. deepCopy(resource, ret[locale]);
  3617. }
  3618. else {
  3619. deepCopy(resource, ret);
  3620. }
  3621. }
  3622. else {
  3623. isString(custom) && deepCopy(JSON.parse(custom), ret);
  3624. }
  3625. });
  3626. }
  3627. // handle messages for flat json
  3628. if (messageResolver == null && flatJson) {
  3629. for (const key in ret) {
  3630. if (hasOwn(ret, key)) {
  3631. handleFlatJson(ret[key]);
  3632. }
  3633. }
  3634. }
  3635. return ret;
  3636. }
  3637. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3638. function getComponentOptions(instance) {
  3639. return instance.type ;
  3640. }
  3641. function adjustI18nResources(gl, options, componentOptions // eslint-disable-line @typescript-eslint/no-explicit-any
  3642. ) {
  3643. let messages = isObject(options.messages) ? options.messages : {};
  3644. if ('__i18nGlobal' in componentOptions) {
  3645. messages = getLocaleMessages(gl.locale.value, {
  3646. messages,
  3647. __i18n: componentOptions.__i18nGlobal
  3648. });
  3649. }
  3650. // merge locale messages
  3651. const locales = Object.keys(messages);
  3652. if (locales.length) {
  3653. locales.forEach(locale => {
  3654. gl.mergeLocaleMessage(locale, messages[locale]);
  3655. });
  3656. }
  3657. {
  3658. // merge datetime formats
  3659. if (isObject(options.datetimeFormats)) {
  3660. const locales = Object.keys(options.datetimeFormats);
  3661. if (locales.length) {
  3662. locales.forEach(locale => {
  3663. gl.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
  3664. });
  3665. }
  3666. }
  3667. // merge number formats
  3668. if (isObject(options.numberFormats)) {
  3669. const locales = Object.keys(options.numberFormats);
  3670. if (locales.length) {
  3671. locales.forEach(locale => {
  3672. gl.mergeNumberFormat(locale, options.numberFormats[locale]);
  3673. });
  3674. }
  3675. }
  3676. }
  3677. }
  3678. function createTextNode(key) {
  3679. return createVNode(Text, null, key, 0)
  3680. ;
  3681. }
  3682. /* eslint-enable @typescript-eslint/no-explicit-any */
  3683. /* eslint-disable @typescript-eslint/no-explicit-any */
  3684. // extend VNode interface
  3685. const DEVTOOLS_META = '__INTLIFY_META__';
  3686. const NOOP_RETURN_ARRAY = () => [];
  3687. const NOOP_RETURN_FALSE = () => false;
  3688. let composerID = 0;
  3689. function defineCoreMissingHandler(missing) {
  3690. return ((ctx, locale, key, type) => {
  3691. return missing(locale, key, getCurrentInstance() || undefined, type);
  3692. });
  3693. }
  3694. // for Intlify DevTools
  3695. /* #__NO_SIDE_EFFECTS__ */
  3696. const getMetaInfo = () => {
  3697. const instance = getCurrentInstance();
  3698. let meta = null; // eslint-disable-line @typescript-eslint/no-explicit-any
  3699. return instance && (meta = getComponentOptions(instance)[DEVTOOLS_META])
  3700. ? { [DEVTOOLS_META]: meta } // eslint-disable-line @typescript-eslint/no-explicit-any
  3701. : null;
  3702. };
  3703. /**
  3704. * Create composer interface factory
  3705. *
  3706. * @internal
  3707. */
  3708. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  3709. function createComposer(options = {}, VueI18nLegacy) {
  3710. const { __root, __injectWithOption } = options;
  3711. const _isGlobal = __root === undefined;
  3712. const flatJson = options.flatJson;
  3713. let _inheritLocale = isBoolean(options.inheritLocale)
  3714. ? options.inheritLocale
  3715. : true;
  3716. const _locale = ref(
  3717. // prettier-ignore
  3718. __root && _inheritLocale
  3719. ? __root.locale.value
  3720. : isString(options.locale)
  3721. ? options.locale
  3722. : DEFAULT_LOCALE);
  3723. const _fallbackLocale = ref(
  3724. // prettier-ignore
  3725. __root && _inheritLocale
  3726. ? __root.fallbackLocale.value
  3727. : isString(options.fallbackLocale) ||
  3728. isArray(options.fallbackLocale) ||
  3729. isPlainObject(options.fallbackLocale) ||
  3730. options.fallbackLocale === false
  3731. ? options.fallbackLocale
  3732. : _locale.value);
  3733. const _messages = ref(getLocaleMessages(_locale.value, options));
  3734. // prettier-ignore
  3735. const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
  3736. ? options.datetimeFormats
  3737. : { [_locale.value]: {} })
  3738. ;
  3739. // prettier-ignore
  3740. const _numberFormats = ref(isPlainObject(options.numberFormats)
  3741. ? options.numberFormats
  3742. : { [_locale.value]: {} })
  3743. ;
  3744. // warning suppress options
  3745. // prettier-ignore
  3746. let _missingWarn = __root
  3747. ? __root.missingWarn
  3748. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  3749. ? options.missingWarn
  3750. : true;
  3751. // prettier-ignore
  3752. let _fallbackWarn = __root
  3753. ? __root.fallbackWarn
  3754. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  3755. ? options.fallbackWarn
  3756. : true;
  3757. // prettier-ignore
  3758. let _fallbackRoot = __root
  3759. ? __root.fallbackRoot
  3760. : isBoolean(options.fallbackRoot)
  3761. ? options.fallbackRoot
  3762. : true;
  3763. // configure fall back to root
  3764. let _fallbackFormat = !!options.fallbackFormat;
  3765. // runtime missing
  3766. let _missing = isFunction(options.missing) ? options.missing : null;
  3767. let _runtimeMissing = isFunction(options.missing)
  3768. ? defineCoreMissingHandler(options.missing)
  3769. : null;
  3770. // postTranslation handler
  3771. let _postTranslation = isFunction(options.postTranslation)
  3772. ? options.postTranslation
  3773. : null;
  3774. // prettier-ignore
  3775. let _warnHtmlMessage = __root
  3776. ? __root.warnHtmlMessage
  3777. : isBoolean(options.warnHtmlMessage)
  3778. ? options.warnHtmlMessage
  3779. : true;
  3780. let _escapeParameter = !!options.escapeParameter;
  3781. // custom linked modifiers
  3782. // prettier-ignore
  3783. const _modifiers = __root
  3784. ? __root.modifiers
  3785. : isPlainObject(options.modifiers)
  3786. ? options.modifiers
  3787. : {};
  3788. // pluralRules
  3789. let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
  3790. // runtime context
  3791. // eslint-disable-next-line prefer-const
  3792. let _context;
  3793. const getCoreContext = () => {
  3794. _isGlobal && setFallbackContext(null);
  3795. const ctxOptions = {
  3796. version: VERSION,
  3797. locale: _locale.value,
  3798. fallbackLocale: _fallbackLocale.value,
  3799. messages: _messages.value,
  3800. modifiers: _modifiers,
  3801. pluralRules: _pluralRules,
  3802. missing: _runtimeMissing === null ? undefined : _runtimeMissing,
  3803. missingWarn: _missingWarn,
  3804. fallbackWarn: _fallbackWarn,
  3805. fallbackFormat: _fallbackFormat,
  3806. unresolving: true,
  3807. postTranslation: _postTranslation === null ? undefined : _postTranslation,
  3808. warnHtmlMessage: _warnHtmlMessage,
  3809. escapeParameter: _escapeParameter,
  3810. messageResolver: options.messageResolver,
  3811. messageCompiler: options.messageCompiler,
  3812. __meta: { framework: 'vue' }
  3813. };
  3814. {
  3815. ctxOptions.datetimeFormats = _datetimeFormats.value;
  3816. ctxOptions.numberFormats = _numberFormats.value;
  3817. ctxOptions.__datetimeFormatters = isPlainObject(_context)
  3818. ? _context.__datetimeFormatters
  3819. : undefined;
  3820. ctxOptions.__numberFormatters = isPlainObject(_context)
  3821. ? _context.__numberFormatters
  3822. : undefined;
  3823. }
  3824. {
  3825. ctxOptions.__v_emitter = isPlainObject(_context)
  3826. ? _context.__v_emitter
  3827. : undefined;
  3828. }
  3829. const ctx = createCoreContext(ctxOptions);
  3830. _isGlobal && setFallbackContext(ctx);
  3831. return ctx;
  3832. };
  3833. _context = getCoreContext();
  3834. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  3835. // track reactivity
  3836. function trackReactivityValues() {
  3837. return [
  3838. _locale.value,
  3839. _fallbackLocale.value,
  3840. _messages.value,
  3841. _datetimeFormats.value,
  3842. _numberFormats.value
  3843. ]
  3844. ;
  3845. }
  3846. // locale
  3847. const locale = computed({
  3848. get: () => _locale.value,
  3849. set: val => {
  3850. _locale.value = val;
  3851. _context.locale = _locale.value;
  3852. }
  3853. });
  3854. // fallbackLocale
  3855. const fallbackLocale = computed({
  3856. get: () => _fallbackLocale.value,
  3857. set: val => {
  3858. _fallbackLocale.value = val;
  3859. _context.fallbackLocale = _fallbackLocale.value;
  3860. updateFallbackLocale(_context, _locale.value, val);
  3861. }
  3862. });
  3863. // messages
  3864. const messages = computed(() => _messages.value);
  3865. // datetimeFormats
  3866. const datetimeFormats = /* #__PURE__*/ computed(() => _datetimeFormats.value);
  3867. // numberFormats
  3868. const numberFormats = /* #__PURE__*/ computed(() => _numberFormats.value);
  3869. // getPostTranslationHandler
  3870. function getPostTranslationHandler() {
  3871. return isFunction(_postTranslation) ? _postTranslation : null;
  3872. }
  3873. // setPostTranslationHandler
  3874. function setPostTranslationHandler(handler) {
  3875. _postTranslation = handler;
  3876. _context.postTranslation = handler;
  3877. }
  3878. // getMissingHandler
  3879. function getMissingHandler() {
  3880. return _missing;
  3881. }
  3882. // setMissingHandler
  3883. function setMissingHandler(handler) {
  3884. if (handler !== null) {
  3885. _runtimeMissing = defineCoreMissingHandler(handler);
  3886. }
  3887. _missing = handler;
  3888. _context.missing = _runtimeMissing;
  3889. }
  3890. function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
  3891. ) {
  3892. return type !== 'translate' || !arg.resolvedMessage;
  3893. }
  3894. const wrapWithDeps = (fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) => {
  3895. trackReactivityValues(); // track reactive dependency
  3896. // NOTE: experimental !!
  3897. let ret;
  3898. try {
  3899. if (true || false) {
  3900. setAdditionalMeta(getMetaInfo());
  3901. }
  3902. if (!_isGlobal) {
  3903. _context.fallbackContext = __root
  3904. ? getFallbackContext()
  3905. : undefined;
  3906. }
  3907. ret = fn(_context);
  3908. }
  3909. finally {
  3910. if (!_isGlobal) {
  3911. _context.fallbackContext = undefined;
  3912. }
  3913. }
  3914. if ((warnType !== 'translate exists' && // for not `te` (e.g `t`)
  3915. isNumber(ret) &&
  3916. ret === NOT_REOSLVED) ||
  3917. (warnType === 'translate exists' && !ret) // for `te`
  3918. ) {
  3919. const [key, arg2] = argumentParser();
  3920. if (__root &&
  3921. isString(key) &&
  3922. isResolvedTranslateMessage(warnType, arg2)) {
  3923. if (_fallbackRoot &&
  3924. (isTranslateFallbackWarn(_fallbackWarn, key) ||
  3925. isTranslateMissingWarn(_missingWarn, key))) {
  3926. warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {
  3927. key,
  3928. type: warnType
  3929. }));
  3930. }
  3931. // for vue-devtools timeline event
  3932. {
  3933. const { __v_emitter: emitter } = _context;
  3934. if (emitter && _fallbackRoot) {
  3935. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  3936. type: warnType,
  3937. key,
  3938. to: 'global',
  3939. groupId: `${warnType}:${key}`
  3940. });
  3941. }
  3942. }
  3943. }
  3944. return __root && _fallbackRoot
  3945. ? fallbackSuccess(__root)
  3946. : fallbackFail(key);
  3947. }
  3948. else if (successCondition(ret)) {
  3949. return ret;
  3950. }
  3951. else {
  3952. /* istanbul ignore next */
  3953. throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);
  3954. }
  3955. };
  3956. // t
  3957. function t(...args) {
  3958. return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));
  3959. }
  3960. // rt
  3961. function rt(...args) {
  3962. const [arg1, arg2, arg3] = args;
  3963. if (arg3 && !isObject(arg3)) {
  3964. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  3965. }
  3966. return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
  3967. }
  3968. // d
  3969. function d(...args) {
  3970. return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', root => Reflect.apply(root.d, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
  3971. }
  3972. // n
  3973. function n(...args) {
  3974. return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', root => Reflect.apply(root.n, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
  3975. }
  3976. // for custom processor
  3977. function normalize(values) {
  3978. return values.map(val => isString(val) || isNumber(val) || isBoolean(val)
  3979. ? createTextNode(String(val))
  3980. : val);
  3981. }
  3982. const interpolate = (val) => val;
  3983. const processor = {
  3984. normalize,
  3985. interpolate,
  3986. type: 'vnode'
  3987. };
  3988. // translateVNode, using for `i18n-t` component
  3989. function translateVNode(...args) {
  3990. return wrapWithDeps(context => {
  3991. let ret;
  3992. const _context = context;
  3993. try {
  3994. _context.processor = processor;
  3995. ret = Reflect.apply(translate, null, [_context, ...args]);
  3996. }
  3997. finally {
  3998. _context.processor = null;
  3999. }
  4000. return ret;
  4001. }, () => parseTranslateArgs(...args), 'translate',
  4002. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4003. root => root[TranslateVNodeSymbol](...args), key => [createTextNode(key)], val => isArray(val));
  4004. }
  4005. // numberParts, using for `i18n-n` component
  4006. function numberParts(...args) {
  4007. return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format',
  4008. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4009. root => root[NumberPartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  4010. }
  4011. // datetimeParts, using for `i18n-d` component
  4012. function datetimeParts(...args) {
  4013. return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format',
  4014. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4015. root => root[DatetimePartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  4016. }
  4017. function setPluralRules(rules) {
  4018. _pluralRules = rules;
  4019. _context.pluralRules = _pluralRules;
  4020. }
  4021. // te
  4022. function te(key, locale) {
  4023. return wrapWithDeps(() => {
  4024. if (!key) {
  4025. return false;
  4026. }
  4027. const targetLocale = isString(locale) ? locale : _locale.value;
  4028. const message = getLocaleMessage(targetLocale);
  4029. const resolved = _context.messageResolver(message, key);
  4030. return (isMessageAST(resolved) ||
  4031. isMessageFunction(resolved) ||
  4032. isString(resolved));
  4033. }, () => [key], 'translate exists', root => {
  4034. return Reflect.apply(root.te, root, [key, locale]);
  4035. }, NOOP_RETURN_FALSE, val => isBoolean(val));
  4036. }
  4037. function resolveMessages(key) {
  4038. let messages = null;
  4039. const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);
  4040. for (let i = 0; i < locales.length; i++) {
  4041. const targetLocaleMessages = _messages.value[locales[i]] || {};
  4042. const messageValue = _context.messageResolver(targetLocaleMessages, key);
  4043. if (messageValue != null) {
  4044. messages = messageValue;
  4045. break;
  4046. }
  4047. }
  4048. return messages;
  4049. }
  4050. // tm
  4051. function tm(key) {
  4052. const messages = resolveMessages(key);
  4053. // prettier-ignore
  4054. return messages != null
  4055. ? messages
  4056. : __root
  4057. ? __root.tm(key) || {}
  4058. : {};
  4059. }
  4060. // getLocaleMessage
  4061. function getLocaleMessage(locale) {
  4062. return (_messages.value[locale] || {});
  4063. }
  4064. // setLocaleMessage
  4065. function setLocaleMessage(locale, message) {
  4066. if (flatJson) {
  4067. const _message = { [locale]: message };
  4068. for (const key in _message) {
  4069. if (hasOwn(_message, key)) {
  4070. handleFlatJson(_message[key]);
  4071. }
  4072. }
  4073. message = _message[locale];
  4074. }
  4075. _messages.value[locale] = message;
  4076. _context.messages = _messages.value;
  4077. }
  4078. // mergeLocaleMessage
  4079. function mergeLocaleMessage(locale, message) {
  4080. _messages.value[locale] = _messages.value[locale] || {};
  4081. const _message = { [locale]: message };
  4082. for (const key in _message) {
  4083. if (hasOwn(_message, key)) {
  4084. handleFlatJson(_message[key]);
  4085. }
  4086. }
  4087. message = _message[locale];
  4088. deepCopy(message, _messages.value[locale]);
  4089. _context.messages = _messages.value;
  4090. }
  4091. // getDateTimeFormat
  4092. function getDateTimeFormat(locale) {
  4093. return _datetimeFormats.value[locale] || {};
  4094. }
  4095. // setDateTimeFormat
  4096. function setDateTimeFormat(locale, format) {
  4097. _datetimeFormats.value[locale] = format;
  4098. _context.datetimeFormats = _datetimeFormats.value;
  4099. clearDateTimeFormat(_context, locale, format);
  4100. }
  4101. // mergeDateTimeFormat
  4102. function mergeDateTimeFormat(locale, format) {
  4103. _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
  4104. _context.datetimeFormats = _datetimeFormats.value;
  4105. clearDateTimeFormat(_context, locale, format);
  4106. }
  4107. // getNumberFormat
  4108. function getNumberFormat(locale) {
  4109. return _numberFormats.value[locale] || {};
  4110. }
  4111. // setNumberFormat
  4112. function setNumberFormat(locale, format) {
  4113. _numberFormats.value[locale] = format;
  4114. _context.numberFormats = _numberFormats.value;
  4115. clearNumberFormat(_context, locale, format);
  4116. }
  4117. // mergeNumberFormat
  4118. function mergeNumberFormat(locale, format) {
  4119. _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
  4120. _context.numberFormats = _numberFormats.value;
  4121. clearNumberFormat(_context, locale, format);
  4122. }
  4123. // for debug
  4124. composerID++;
  4125. // watch root locale & fallbackLocale
  4126. if (__root && inBrowser) {
  4127. watch(__root.locale, (val) => {
  4128. if (_inheritLocale) {
  4129. _locale.value = val;
  4130. _context.locale = val;
  4131. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  4132. }
  4133. });
  4134. watch(__root.fallbackLocale, (val) => {
  4135. if (_inheritLocale) {
  4136. _fallbackLocale.value = val;
  4137. _context.fallbackLocale = val;
  4138. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  4139. }
  4140. });
  4141. }
  4142. // define basic composition API!
  4143. const composer = {
  4144. id: composerID,
  4145. locale,
  4146. fallbackLocale,
  4147. get inheritLocale() {
  4148. return _inheritLocale;
  4149. },
  4150. set inheritLocale(val) {
  4151. _inheritLocale = val;
  4152. if (val && __root) {
  4153. _locale.value = __root.locale.value;
  4154. _fallbackLocale.value = __root.fallbackLocale.value;
  4155. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  4156. }
  4157. },
  4158. get availableLocales() {
  4159. return Object.keys(_messages.value).sort();
  4160. },
  4161. messages,
  4162. get modifiers() {
  4163. return _modifiers;
  4164. },
  4165. get pluralRules() {
  4166. return _pluralRules || {};
  4167. },
  4168. get isGlobal() {
  4169. return _isGlobal;
  4170. },
  4171. get missingWarn() {
  4172. return _missingWarn;
  4173. },
  4174. set missingWarn(val) {
  4175. _missingWarn = val;
  4176. _context.missingWarn = _missingWarn;
  4177. },
  4178. get fallbackWarn() {
  4179. return _fallbackWarn;
  4180. },
  4181. set fallbackWarn(val) {
  4182. _fallbackWarn = val;
  4183. _context.fallbackWarn = _fallbackWarn;
  4184. },
  4185. get fallbackRoot() {
  4186. return _fallbackRoot;
  4187. },
  4188. set fallbackRoot(val) {
  4189. _fallbackRoot = val;
  4190. },
  4191. get fallbackFormat() {
  4192. return _fallbackFormat;
  4193. },
  4194. set fallbackFormat(val) {
  4195. _fallbackFormat = val;
  4196. _context.fallbackFormat = _fallbackFormat;
  4197. },
  4198. get warnHtmlMessage() {
  4199. return _warnHtmlMessage;
  4200. },
  4201. set warnHtmlMessage(val) {
  4202. _warnHtmlMessage = val;
  4203. _context.warnHtmlMessage = val;
  4204. },
  4205. get escapeParameter() {
  4206. return _escapeParameter;
  4207. },
  4208. set escapeParameter(val) {
  4209. _escapeParameter = val;
  4210. _context.escapeParameter = val;
  4211. },
  4212. t,
  4213. getLocaleMessage,
  4214. setLocaleMessage,
  4215. mergeLocaleMessage,
  4216. getPostTranslationHandler,
  4217. setPostTranslationHandler,
  4218. getMissingHandler,
  4219. setMissingHandler,
  4220. [SetPluralRulesSymbol]: setPluralRules
  4221. };
  4222. {
  4223. composer.datetimeFormats = datetimeFormats;
  4224. composer.numberFormats = numberFormats;
  4225. composer.rt = rt;
  4226. composer.te = te;
  4227. composer.tm = tm;
  4228. composer.d = d;
  4229. composer.n = n;
  4230. composer.getDateTimeFormat = getDateTimeFormat;
  4231. composer.setDateTimeFormat = setDateTimeFormat;
  4232. composer.mergeDateTimeFormat = mergeDateTimeFormat;
  4233. composer.getNumberFormat = getNumberFormat;
  4234. composer.setNumberFormat = setNumberFormat;
  4235. composer.mergeNumberFormat = mergeNumberFormat;
  4236. composer[InejctWithOptionSymbol] = __injectWithOption;
  4237. composer[TranslateVNodeSymbol] = translateVNode;
  4238. composer[DatetimePartsSymbol] = datetimeParts;
  4239. composer[NumberPartsSymbol] = numberParts;
  4240. }
  4241. // for vue-devtools timeline event
  4242. {
  4243. composer[EnableEmitter] = (emitter) => {
  4244. _context.__v_emitter = emitter;
  4245. };
  4246. composer[DisableEmitter] = () => {
  4247. _context.__v_emitter = undefined;
  4248. };
  4249. }
  4250. return composer;
  4251. }
  4252. /* eslint-enable @typescript-eslint/no-explicit-any */
  4253. /* eslint-disable @typescript-eslint/no-explicit-any */
  4254. /**
  4255. * Convert to I18n Composer Options from VueI18n Options
  4256. *
  4257. * @internal
  4258. */
  4259. function convertComposerOptions(options) {
  4260. const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
  4261. const fallbackLocale = isString(options.fallbackLocale) ||
  4262. isArray(options.fallbackLocale) ||
  4263. isPlainObject(options.fallbackLocale) ||
  4264. options.fallbackLocale === false
  4265. ? options.fallbackLocale
  4266. : locale;
  4267. const missing = isFunction(options.missing) ? options.missing : undefined;
  4268. const missingWarn = isBoolean(options.silentTranslationWarn) ||
  4269. isRegExp(options.silentTranslationWarn)
  4270. ? !options.silentTranslationWarn
  4271. : true;
  4272. const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
  4273. isRegExp(options.silentFallbackWarn)
  4274. ? !options.silentFallbackWarn
  4275. : true;
  4276. const fallbackRoot = isBoolean(options.fallbackRoot)
  4277. ? options.fallbackRoot
  4278. : true;
  4279. const fallbackFormat = !!options.formatFallbackMessages;
  4280. const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
  4281. const pluralizationRules = options.pluralizationRules;
  4282. const postTranslation = isFunction(options.postTranslation)
  4283. ? options.postTranslation
  4284. : undefined;
  4285. const warnHtmlMessage = isString(options.warnHtmlInMessage)
  4286. ? options.warnHtmlInMessage !== 'off'
  4287. : true;
  4288. const escapeParameter = !!options.escapeParameterHtml;
  4289. const inheritLocale = isBoolean(options.sync) ? options.sync : true;
  4290. if (options.formatter) {
  4291. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  4292. }
  4293. if (options.preserveDirectiveContent) {
  4294. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  4295. }
  4296. let messages = options.messages;
  4297. if (isPlainObject(options.sharedMessages)) {
  4298. const sharedMessages = options.sharedMessages;
  4299. const locales = Object.keys(sharedMessages);
  4300. messages = locales.reduce((messages, locale) => {
  4301. const message = messages[locale] || (messages[locale] = {});
  4302. assign(message, sharedMessages[locale]);
  4303. return messages;
  4304. }, (messages || {}));
  4305. }
  4306. const { __i18n, __root, __injectWithOption } = options;
  4307. const datetimeFormats = options.datetimeFormats;
  4308. const numberFormats = options.numberFormats;
  4309. const flatJson = options.flatJson;
  4310. return {
  4311. locale,
  4312. fallbackLocale,
  4313. messages,
  4314. flatJson,
  4315. datetimeFormats,
  4316. numberFormats,
  4317. missing,
  4318. missingWarn,
  4319. fallbackWarn,
  4320. fallbackRoot,
  4321. fallbackFormat,
  4322. modifiers,
  4323. pluralRules: pluralizationRules,
  4324. postTranslation,
  4325. warnHtmlMessage,
  4326. escapeParameter,
  4327. messageResolver: options.messageResolver,
  4328. inheritLocale,
  4329. __i18n,
  4330. __root,
  4331. __injectWithOption
  4332. };
  4333. }
  4334. /**
  4335. * create VueI18n interface factory
  4336. *
  4337. * @internal
  4338. */
  4339. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  4340. function createVueI18n(options = {}, VueI18nLegacy) {
  4341. {
  4342. const composer = createComposer(convertComposerOptions(options));
  4343. const { __extender } = options;
  4344. // defines VueI18n
  4345. const vueI18n = {
  4346. // id
  4347. id: composer.id,
  4348. // locale
  4349. get locale() {
  4350. return composer.locale.value;
  4351. },
  4352. set locale(val) {
  4353. composer.locale.value = val;
  4354. },
  4355. // fallbackLocale
  4356. get fallbackLocale() {
  4357. return composer.fallbackLocale.value;
  4358. },
  4359. set fallbackLocale(val) {
  4360. composer.fallbackLocale.value = val;
  4361. },
  4362. // messages
  4363. get messages() {
  4364. return composer.messages.value;
  4365. },
  4366. // datetimeFormats
  4367. get datetimeFormats() {
  4368. return composer.datetimeFormats.value;
  4369. },
  4370. // numberFormats
  4371. get numberFormats() {
  4372. return composer.numberFormats.value;
  4373. },
  4374. // availableLocales
  4375. get availableLocales() {
  4376. return composer.availableLocales;
  4377. },
  4378. // formatter
  4379. get formatter() {
  4380. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  4381. // dummy
  4382. return {
  4383. interpolate() {
  4384. return [];
  4385. }
  4386. };
  4387. },
  4388. set formatter(val) {
  4389. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  4390. },
  4391. // missing
  4392. get missing() {
  4393. return composer.getMissingHandler();
  4394. },
  4395. set missing(handler) {
  4396. composer.setMissingHandler(handler);
  4397. },
  4398. // silentTranslationWarn
  4399. get silentTranslationWarn() {
  4400. return isBoolean(composer.missingWarn)
  4401. ? !composer.missingWarn
  4402. : composer.missingWarn;
  4403. },
  4404. set silentTranslationWarn(val) {
  4405. composer.missingWarn = isBoolean(val) ? !val : val;
  4406. },
  4407. // silentFallbackWarn
  4408. get silentFallbackWarn() {
  4409. return isBoolean(composer.fallbackWarn)
  4410. ? !composer.fallbackWarn
  4411. : composer.fallbackWarn;
  4412. },
  4413. set silentFallbackWarn(val) {
  4414. composer.fallbackWarn = isBoolean(val) ? !val : val;
  4415. },
  4416. // modifiers
  4417. get modifiers() {
  4418. return composer.modifiers;
  4419. },
  4420. // formatFallbackMessages
  4421. get formatFallbackMessages() {
  4422. return composer.fallbackFormat;
  4423. },
  4424. set formatFallbackMessages(val) {
  4425. composer.fallbackFormat = val;
  4426. },
  4427. // postTranslation
  4428. get postTranslation() {
  4429. return composer.getPostTranslationHandler();
  4430. },
  4431. set postTranslation(handler) {
  4432. composer.setPostTranslationHandler(handler);
  4433. },
  4434. // sync
  4435. get sync() {
  4436. return composer.inheritLocale;
  4437. },
  4438. set sync(val) {
  4439. composer.inheritLocale = val;
  4440. },
  4441. // warnInHtmlMessage
  4442. get warnHtmlInMessage() {
  4443. return composer.warnHtmlMessage ? 'warn' : 'off';
  4444. },
  4445. set warnHtmlInMessage(val) {
  4446. composer.warnHtmlMessage = val !== 'off';
  4447. },
  4448. // escapeParameterHtml
  4449. get escapeParameterHtml() {
  4450. return composer.escapeParameter;
  4451. },
  4452. set escapeParameterHtml(val) {
  4453. composer.escapeParameter = val;
  4454. },
  4455. // preserveDirectiveContent
  4456. get preserveDirectiveContent() {
  4457. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  4458. return true;
  4459. },
  4460. set preserveDirectiveContent(val) {
  4461. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  4462. },
  4463. // pluralizationRules
  4464. get pluralizationRules() {
  4465. return composer.pluralRules || {};
  4466. },
  4467. // for internal
  4468. __composer: composer,
  4469. // t
  4470. t(...args) {
  4471. const [arg1, arg2, arg3] = args;
  4472. const options = {};
  4473. let list = null;
  4474. let named = null;
  4475. if (!isString(arg1)) {
  4476. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  4477. }
  4478. const key = arg1;
  4479. if (isString(arg2)) {
  4480. options.locale = arg2;
  4481. }
  4482. else if (isArray(arg2)) {
  4483. list = arg2;
  4484. }
  4485. else if (isPlainObject(arg2)) {
  4486. named = arg2;
  4487. }
  4488. if (isArray(arg3)) {
  4489. list = arg3;
  4490. }
  4491. else if (isPlainObject(arg3)) {
  4492. named = arg3;
  4493. }
  4494. // return composer.t(key, (list || named || {}) as any, options)
  4495. return Reflect.apply(composer.t, composer, [
  4496. key,
  4497. (list || named || {}),
  4498. options
  4499. ]);
  4500. },
  4501. rt(...args) {
  4502. return Reflect.apply(composer.rt, composer, [...args]);
  4503. },
  4504. // tc
  4505. tc(...args) {
  4506. const [arg1, arg2, arg3] = args;
  4507. const options = { plural: 1 };
  4508. let list = null;
  4509. let named = null;
  4510. if (!isString(arg1)) {
  4511. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  4512. }
  4513. const key = arg1;
  4514. if (isString(arg2)) {
  4515. options.locale = arg2;
  4516. }
  4517. else if (isNumber(arg2)) {
  4518. options.plural = arg2;
  4519. }
  4520. else if (isArray(arg2)) {
  4521. list = arg2;
  4522. }
  4523. else if (isPlainObject(arg2)) {
  4524. named = arg2;
  4525. }
  4526. if (isString(arg3)) {
  4527. options.locale = arg3;
  4528. }
  4529. else if (isArray(arg3)) {
  4530. list = arg3;
  4531. }
  4532. else if (isPlainObject(arg3)) {
  4533. named = arg3;
  4534. }
  4535. // return composer.t(key, (list || named || {}) as any, options)
  4536. return Reflect.apply(composer.t, composer, [
  4537. key,
  4538. (list || named || {}),
  4539. options
  4540. ]);
  4541. },
  4542. // te
  4543. te(key, locale) {
  4544. return composer.te(key, locale);
  4545. },
  4546. // tm
  4547. tm(key) {
  4548. return composer.tm(key);
  4549. },
  4550. // getLocaleMessage
  4551. getLocaleMessage(locale) {
  4552. return composer.getLocaleMessage(locale);
  4553. },
  4554. // setLocaleMessage
  4555. setLocaleMessage(locale, message) {
  4556. composer.setLocaleMessage(locale, message);
  4557. },
  4558. // mergeLocaleMessage
  4559. mergeLocaleMessage(locale, message) {
  4560. composer.mergeLocaleMessage(locale, message);
  4561. },
  4562. // d
  4563. d(...args) {
  4564. return Reflect.apply(composer.d, composer, [...args]);
  4565. },
  4566. // getDateTimeFormat
  4567. getDateTimeFormat(locale) {
  4568. return composer.getDateTimeFormat(locale);
  4569. },
  4570. // setDateTimeFormat
  4571. setDateTimeFormat(locale, format) {
  4572. composer.setDateTimeFormat(locale, format);
  4573. },
  4574. // mergeDateTimeFormat
  4575. mergeDateTimeFormat(locale, format) {
  4576. composer.mergeDateTimeFormat(locale, format);
  4577. },
  4578. // n
  4579. n(...args) {
  4580. return Reflect.apply(composer.n, composer, [...args]);
  4581. },
  4582. // getNumberFormat
  4583. getNumberFormat(locale) {
  4584. return composer.getNumberFormat(locale);
  4585. },
  4586. // setNumberFormat
  4587. setNumberFormat(locale, format) {
  4588. composer.setNumberFormat(locale, format);
  4589. },
  4590. // mergeNumberFormat
  4591. mergeNumberFormat(locale, format) {
  4592. composer.mergeNumberFormat(locale, format);
  4593. },
  4594. // getChoiceIndex
  4595. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  4596. getChoiceIndex(choice, choicesLength) {
  4597. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX));
  4598. return -1;
  4599. }
  4600. };
  4601. vueI18n.__extender = __extender;
  4602. // for vue-devtools timeline event
  4603. {
  4604. vueI18n.__enableEmitter = (emitter) => {
  4605. const __composer = composer;
  4606. __composer[EnableEmitter] && __composer[EnableEmitter](emitter);
  4607. };
  4608. vueI18n.__disableEmitter = () => {
  4609. const __composer = composer;
  4610. __composer[DisableEmitter] && __composer[DisableEmitter]();
  4611. };
  4612. }
  4613. return vueI18n;
  4614. }
  4615. }
  4616. /* eslint-enable @typescript-eslint/no-explicit-any */
  4617. const baseFormatProps = {
  4618. tag: {
  4619. type: [String, Object]
  4620. },
  4621. locale: {
  4622. type: String
  4623. },
  4624. scope: {
  4625. type: String,
  4626. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  4627. validator: (val /* ComponentI18nScope */) => val === 'parent' || val === 'global',
  4628. default: 'parent' /* ComponentI18nScope */
  4629. },
  4630. i18n: {
  4631. type: Object
  4632. }
  4633. };
  4634. function getInterpolateArg(
  4635. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4636. { slots }, // SetupContext,
  4637. keys) {
  4638. if (keys.length === 1 && keys[0] === 'default') {
  4639. // default slot with list
  4640. const ret = slots.default ? slots.default() : [];
  4641. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4642. return ret.reduce((slot, current) => {
  4643. return [
  4644. ...slot,
  4645. // prettier-ignore
  4646. ...(current.type === Fragment ? current.children : [current]
  4647. )
  4648. ];
  4649. }, []);
  4650. }
  4651. else {
  4652. // named slots
  4653. return keys.reduce((arg, key) => {
  4654. const slot = slots[key];
  4655. if (slot) {
  4656. arg[key] = slot();
  4657. }
  4658. return arg;
  4659. }, {});
  4660. }
  4661. }
  4662. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4663. function getFragmentableTag(tag) {
  4664. return Fragment ;
  4665. }
  4666. const TranslationImpl = /*#__PURE__*/ defineComponent({
  4667. /* eslint-disable */
  4668. name: 'i18n-t',
  4669. props: assign({
  4670. keypath: {
  4671. type: String,
  4672. required: true
  4673. },
  4674. plural: {
  4675. type: [Number, String],
  4676. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4677. validator: (val) => isNumber(val) || !isNaN(val)
  4678. }
  4679. }, baseFormatProps),
  4680. /* eslint-enable */
  4681. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4682. setup(props, context) {
  4683. const { slots, attrs } = context;
  4684. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  4685. const i18n = props.i18n ||
  4686. useI18n({
  4687. useScope: props.scope,
  4688. __useComponent: true
  4689. });
  4690. return () => {
  4691. const keys = Object.keys(slots).filter(key => key !== '_');
  4692. const options = {};
  4693. if (props.locale) {
  4694. options.locale = props.locale;
  4695. }
  4696. if (props.plural !== undefined) {
  4697. options.plural = isString(props.plural) ? +props.plural : props.plural;
  4698. }
  4699. const arg = getInterpolateArg(context, keys);
  4700. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4701. const children = i18n[TranslateVNodeSymbol](props.keypath, arg, options);
  4702. const assignedAttrs = assign({}, attrs);
  4703. const tag = isString(props.tag) || isObject(props.tag)
  4704. ? props.tag
  4705. : getFragmentableTag();
  4706. return h(tag, assignedAttrs, children);
  4707. };
  4708. }
  4709. });
  4710. /**
  4711. * export the public type for h/tsx inference
  4712. * also to avoid inline import() in generated d.ts files
  4713. */
  4714. /**
  4715. * Translation Component
  4716. *
  4717. * @remarks
  4718. * See the following items for property about details
  4719. *
  4720. * @VueI18nSee [TranslationProps](component#translationprops)
  4721. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  4722. * @VueI18nSee [Component Interpolation](../guide/advanced/component)
  4723. *
  4724. * @example
  4725. * ```html
  4726. * <div id="app">
  4727. * <!-- ... -->
  4728. * <i18n keypath="term" tag="label" for="tos">
  4729. * <a :href="url" target="_blank">{{ $t('tos') }}</a>
  4730. * </i18n>
  4731. * <!-- ... -->
  4732. * </div>
  4733. * ```
  4734. * ```js
  4735. * import { createApp } from 'vue'
  4736. * import { createI18n } from 'vue-i18n'
  4737. *
  4738. * const messages = {
  4739. * en: {
  4740. * tos: 'Term of Service',
  4741. * term: 'I accept xxx {0}.'
  4742. * },
  4743. * ja: {
  4744. * tos: '利用規約',
  4745. * term: '私は xxx の{0}に同意します。'
  4746. * }
  4747. * }
  4748. *
  4749. * const i18n = createI18n({
  4750. * locale: 'en',
  4751. * messages
  4752. * })
  4753. *
  4754. * const app = createApp({
  4755. * data: {
  4756. * url: '/term'
  4757. * }
  4758. * }).use(i18n).mount('#app')
  4759. * ```
  4760. *
  4761. * @VueI18nComponent
  4762. */
  4763. const Translation = TranslationImpl;
  4764. const I18nT = Translation;
  4765. function isVNode(target) {
  4766. return isArray(target) && !isString(target[0]);
  4767. }
  4768. function renderFormatter(props, context, slotKeys, partFormatter) {
  4769. const { slots, attrs } = context;
  4770. return () => {
  4771. const options = { part: true };
  4772. let overrides = {};
  4773. if (props.locale) {
  4774. options.locale = props.locale;
  4775. }
  4776. if (isString(props.format)) {
  4777. options.key = props.format;
  4778. }
  4779. else if (isObject(props.format)) {
  4780. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4781. if (isString(props.format.key)) {
  4782. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4783. options.key = props.format.key;
  4784. }
  4785. // Filter out number format options only
  4786. overrides = Object.keys(props.format).reduce((options, prop) => {
  4787. return slotKeys.includes(prop)
  4788. ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
  4789. : options;
  4790. }, {});
  4791. }
  4792. const parts = partFormatter(...[props.value, options, overrides]);
  4793. let children = [options.key];
  4794. if (isArray(parts)) {
  4795. children = parts.map((part, index) => {
  4796. const slot = slots[part.type];
  4797. const node = slot
  4798. ? slot({ [part.type]: part.value, index, parts })
  4799. : [part.value];
  4800. if (isVNode(node)) {
  4801. node[0].key = `${part.type}-${index}`;
  4802. }
  4803. return node;
  4804. });
  4805. }
  4806. else if (isString(parts)) {
  4807. children = [parts];
  4808. }
  4809. const assignedAttrs = assign({}, attrs);
  4810. const tag = isString(props.tag) || isObject(props.tag)
  4811. ? props.tag
  4812. : getFragmentableTag();
  4813. return h(tag, assignedAttrs, children);
  4814. };
  4815. }
  4816. const NumberFormatImpl = /*#__PURE__*/ defineComponent({
  4817. /* eslint-disable */
  4818. name: 'i18n-n',
  4819. props: assign({
  4820. value: {
  4821. type: Number,
  4822. required: true
  4823. },
  4824. format: {
  4825. type: [String, Object]
  4826. }
  4827. }, baseFormatProps),
  4828. /* eslint-enable */
  4829. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4830. setup(props, context) {
  4831. const i18n = props.i18n ||
  4832. useI18n({
  4833. useScope: 'parent',
  4834. __useComponent: true
  4835. });
  4836. return renderFormatter(props, context, NUMBER_FORMAT_OPTIONS_KEYS, (...args) =>
  4837. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4838. i18n[NumberPartsSymbol](...args));
  4839. }
  4840. });
  4841. /**
  4842. * export the public type for h/tsx inference
  4843. * also to avoid inline import() in generated d.ts files
  4844. */
  4845. /**
  4846. * Number Format Component
  4847. *
  4848. * @remarks
  4849. * See the following items for property about details
  4850. *
  4851. * @VueI18nSee [FormattableProps](component#formattableprops)
  4852. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  4853. * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
  4854. *
  4855. * @VueI18nDanger
  4856. * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)
  4857. *
  4858. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
  4859. *
  4860. * @VueI18nComponent
  4861. */
  4862. const NumberFormat = NumberFormatImpl;
  4863. const I18nN = NumberFormat;
  4864. const DatetimeFormatImpl = /* #__PURE__*/ defineComponent({
  4865. /* eslint-disable */
  4866. name: 'i18n-d',
  4867. props: assign({
  4868. value: {
  4869. type: [Number, Date],
  4870. required: true
  4871. },
  4872. format: {
  4873. type: [String, Object]
  4874. }
  4875. }, baseFormatProps),
  4876. /* eslint-enable */
  4877. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4878. setup(props, context) {
  4879. const i18n = props.i18n ||
  4880. useI18n({
  4881. useScope: 'parent',
  4882. __useComponent: true
  4883. });
  4884. return renderFormatter(props, context, DATETIME_FORMAT_OPTIONS_KEYS, (...args) =>
  4885. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4886. i18n[DatetimePartsSymbol](...args));
  4887. }
  4888. });
  4889. /**
  4890. * Datetime Format Component
  4891. *
  4892. * @remarks
  4893. * See the following items for property about details
  4894. *
  4895. * @VueI18nSee [FormattableProps](component#formattableprops)
  4896. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  4897. * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
  4898. *
  4899. * @VueI18nDanger
  4900. * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
  4901. *
  4902. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
  4903. *
  4904. * @VueI18nComponent
  4905. */
  4906. const DatetimeFormat = DatetimeFormatImpl;
  4907. const I18nD = DatetimeFormat;
  4908. function getComposer$2(i18n, instance) {
  4909. const i18nInternal = i18n;
  4910. if (i18n.mode === 'composition') {
  4911. return (i18nInternal.__getInstance(instance) || i18n.global);
  4912. }
  4913. else {
  4914. const vueI18n = i18nInternal.__getInstance(instance);
  4915. return vueI18n != null
  4916. ? vueI18n.__composer
  4917. : i18n.global.__composer;
  4918. }
  4919. }
  4920. function vTDirective(i18n) {
  4921. const _process = (binding) => {
  4922. const { instance, modifiers, value } = binding;
  4923. /* istanbul ignore if */
  4924. if (!instance || !instance.$) {
  4925. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4926. }
  4927. const composer = getComposer$2(i18n, instance.$);
  4928. if (modifiers.preserve) {
  4929. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE));
  4930. }
  4931. const parsedValue = parseValue(value);
  4932. return [
  4933. Reflect.apply(composer.t, composer, [...makeParams(parsedValue)]),
  4934. composer
  4935. ];
  4936. };
  4937. const register = (el, binding) => {
  4938. const [textContent, composer] = _process(binding);
  4939. if (inBrowser && i18n.global === composer) {
  4940. // global scope only
  4941. el.__i18nWatcher = watch(composer.locale, () => {
  4942. binding.instance && binding.instance.$forceUpdate();
  4943. });
  4944. }
  4945. el.__composer = composer;
  4946. el.textContent = textContent;
  4947. };
  4948. const unregister = (el) => {
  4949. if (inBrowser && el.__i18nWatcher) {
  4950. el.__i18nWatcher();
  4951. el.__i18nWatcher = undefined;
  4952. delete el.__i18nWatcher;
  4953. }
  4954. if (el.__composer) {
  4955. el.__composer = undefined;
  4956. delete el.__composer;
  4957. }
  4958. };
  4959. const update = (el, { value }) => {
  4960. if (el.__composer) {
  4961. const composer = el.__composer;
  4962. const parsedValue = parseValue(value);
  4963. el.textContent = Reflect.apply(composer.t, composer, [
  4964. ...makeParams(parsedValue)
  4965. ]);
  4966. }
  4967. };
  4968. const getSSRProps = (binding) => {
  4969. const [textContent] = _process(binding);
  4970. return { textContent };
  4971. };
  4972. return {
  4973. created: register,
  4974. unmounted: unregister,
  4975. beforeUpdate: update,
  4976. getSSRProps
  4977. };
  4978. }
  4979. function parseValue(value) {
  4980. if (isString(value)) {
  4981. return { path: value };
  4982. }
  4983. else if (isPlainObject(value)) {
  4984. if (!('path' in value)) {
  4985. throw createI18nError(I18nErrorCodes.REQUIRED_VALUE, 'path');
  4986. }
  4987. return value;
  4988. }
  4989. else {
  4990. throw createI18nError(I18nErrorCodes.INVALID_VALUE);
  4991. }
  4992. }
  4993. function makeParams(value) {
  4994. const { path, locale, args, choice, plural } = value;
  4995. const options = {};
  4996. const named = args || {};
  4997. if (isString(locale)) {
  4998. options.locale = locale;
  4999. }
  5000. if (isNumber(choice)) {
  5001. options.plural = choice;
  5002. }
  5003. if (isNumber(plural)) {
  5004. options.plural = plural;
  5005. }
  5006. return [path, named, options];
  5007. }
  5008. function apply(app, i18n, ...options) {
  5009. const pluginOptions = isPlainObject(options[0])
  5010. ? options[0]
  5011. : {};
  5012. const useI18nComponentName = !!pluginOptions.useI18nComponentName;
  5013. const globalInstall = isBoolean(pluginOptions.globalInstall)
  5014. ? pluginOptions.globalInstall
  5015. : true;
  5016. if (globalInstall && useI18nComponentName) {
  5017. warn(getWarnMessage(I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE, {
  5018. name: Translation.name
  5019. }));
  5020. }
  5021. if (globalInstall) {
  5022. [!useI18nComponentName ? Translation.name : 'i18n', 'I18nT'].forEach(name => app.component(name, Translation));
  5023. [NumberFormat.name, 'I18nN'].forEach(name => app.component(name, NumberFormat));
  5024. [DatetimeFormat.name, 'I18nD'].forEach(name => app.component(name, DatetimeFormat));
  5025. }
  5026. // install directive
  5027. {
  5028. app.directive('t', vTDirective(i18n));
  5029. }
  5030. }
  5031. var global$1 = (typeof global !== "undefined" ? global :
  5032. typeof self !== "undefined" ? self :
  5033. typeof window !== "undefined" ? window : {});
  5034. function getDevtoolsGlobalHook() {
  5035. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  5036. }
  5037. function getTarget() {
  5038. // @ts-ignore
  5039. return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
  5040. ? window
  5041. : typeof global$1 !== 'undefined'
  5042. ? global$1
  5043. : {};
  5044. }
  5045. const isProxyAvailable = typeof Proxy === 'function';
  5046. const HOOK_SETUP = 'devtools-plugin:setup';
  5047. const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
  5048. let supported;
  5049. let perf;
  5050. function isPerformanceSupported() {
  5051. var _a;
  5052. if (supported !== undefined) {
  5053. return supported;
  5054. }
  5055. if (typeof window !== 'undefined' && window.performance) {
  5056. supported = true;
  5057. perf = window.performance;
  5058. }
  5059. else if (typeof global$1 !== 'undefined' && ((_a = global$1.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {
  5060. supported = true;
  5061. perf = global$1.perf_hooks.performance;
  5062. }
  5063. else {
  5064. supported = false;
  5065. }
  5066. return supported;
  5067. }
  5068. function now() {
  5069. return isPerformanceSupported() ? perf.now() : Date.now();
  5070. }
  5071. class ApiProxy {
  5072. constructor(plugin, hook) {
  5073. this.target = null;
  5074. this.targetQueue = [];
  5075. this.onQueue = [];
  5076. this.plugin = plugin;
  5077. this.hook = hook;
  5078. const defaultSettings = {};
  5079. if (plugin.settings) {
  5080. for (const id in plugin.settings) {
  5081. const item = plugin.settings[id];
  5082. defaultSettings[id] = item.defaultValue;
  5083. }
  5084. }
  5085. const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
  5086. let currentSettings = Object.assign({}, defaultSettings);
  5087. try {
  5088. const raw = localStorage.getItem(localSettingsSaveId);
  5089. const data = JSON.parse(raw);
  5090. Object.assign(currentSettings, data);
  5091. }
  5092. catch (e) {
  5093. // noop
  5094. }
  5095. this.fallbacks = {
  5096. getSettings() {
  5097. return currentSettings;
  5098. },
  5099. setSettings(value) {
  5100. try {
  5101. localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
  5102. }
  5103. catch (e) {
  5104. // noop
  5105. }
  5106. currentSettings = value;
  5107. },
  5108. now() {
  5109. return now();
  5110. },
  5111. };
  5112. if (hook) {
  5113. hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
  5114. if (pluginId === this.plugin.id) {
  5115. this.fallbacks.setSettings(value);
  5116. }
  5117. });
  5118. }
  5119. this.proxiedOn = new Proxy({}, {
  5120. get: (_target, prop) => {
  5121. if (this.target) {
  5122. return this.target.on[prop];
  5123. }
  5124. else {
  5125. return (...args) => {
  5126. this.onQueue.push({
  5127. method: prop,
  5128. args,
  5129. });
  5130. };
  5131. }
  5132. },
  5133. });
  5134. this.proxiedTarget = new Proxy({}, {
  5135. get: (_target, prop) => {
  5136. if (this.target) {
  5137. return this.target[prop];
  5138. }
  5139. else if (prop === 'on') {
  5140. return this.proxiedOn;
  5141. }
  5142. else if (Object.keys(this.fallbacks).includes(prop)) {
  5143. return (...args) => {
  5144. this.targetQueue.push({
  5145. method: prop,
  5146. args,
  5147. resolve: () => { },
  5148. });
  5149. return this.fallbacks[prop](...args);
  5150. };
  5151. }
  5152. else {
  5153. return (...args) => {
  5154. return new Promise(resolve => {
  5155. this.targetQueue.push({
  5156. method: prop,
  5157. args,
  5158. resolve,
  5159. });
  5160. });
  5161. };
  5162. }
  5163. },
  5164. });
  5165. }
  5166. async setRealTarget(target) {
  5167. this.target = target;
  5168. for (const item of this.onQueue) {
  5169. this.target.on[item.method](...item.args);
  5170. }
  5171. for (const item of this.targetQueue) {
  5172. item.resolve(await this.target[item.method](...item.args));
  5173. }
  5174. }
  5175. }
  5176. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  5177. const descriptor = pluginDescriptor;
  5178. const target = getTarget();
  5179. const hook = getDevtoolsGlobalHook();
  5180. const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
  5181. if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
  5182. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  5183. }
  5184. else {
  5185. const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
  5186. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  5187. list.push({
  5188. pluginDescriptor: descriptor,
  5189. setupFn,
  5190. proxy,
  5191. });
  5192. if (proxy)
  5193. setupFn(proxy.proxiedTarget);
  5194. }
  5195. }
  5196. const VueDevToolsLabels = {
  5197. ["vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */]: 'Vue I18n devtools',
  5198. ["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'I18n Resources',
  5199. ["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]: 'Vue I18n'
  5200. };
  5201. const VueDevToolsPlaceholders = {
  5202. ["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'Search for scopes ...'
  5203. };
  5204. const VueDevToolsTimelineColors = {
  5205. ["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]: 0xffcd19
  5206. };
  5207. const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
  5208. let devtoolsApi;
  5209. async function enableDevTools(app, i18n) {
  5210. return new Promise((resolve, reject) => {
  5211. try {
  5212. setupDevtoolsPlugin({
  5213. id: "vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */,
  5214. label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */],
  5215. packageName: 'vue-i18n',
  5216. homepage: 'https://vue-i18n.intlify.dev',
  5217. logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
  5218. componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
  5219. app: app // eslint-disable-line @typescript-eslint/no-explicit-any
  5220. }, api => {
  5221. devtoolsApi = api;
  5222. api.on.visitComponentTree(({ componentInstance, treeNode }) => {
  5223. updateComponentTreeTags(componentInstance, treeNode, i18n);
  5224. });
  5225. api.on.inspectComponent(({ componentInstance, instanceData }) => {
  5226. if (componentInstance.vnode.el &&
  5227. componentInstance.vnode.el.__VUE_I18N__ &&
  5228. instanceData) {
  5229. if (i18n.mode === 'legacy') {
  5230. // ignore global scope on legacy mode
  5231. if (componentInstance.vnode.el.__VUE_I18N__ !==
  5232. i18n.global.__composer) {
  5233. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  5234. }
  5235. }
  5236. else {
  5237. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  5238. }
  5239. }
  5240. });
  5241. api.addInspector({
  5242. id: "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */,
  5243. label: VueDevToolsLabels["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */],
  5244. icon: 'language',
  5245. treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]
  5246. });
  5247. api.on.getInspectorTree(payload => {
  5248. if (payload.app === app &&
  5249. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  5250. registerScope(payload, i18n);
  5251. }
  5252. });
  5253. const roots = new Map();
  5254. api.on.getInspectorState(async (payload) => {
  5255. if (payload.app === app &&
  5256. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  5257. api.unhighlightElement();
  5258. inspectScope(payload, i18n);
  5259. if (payload.nodeId === 'global') {
  5260. if (!roots.has(payload.app)) {
  5261. const [root] = await api.getComponentInstances(payload.app);
  5262. roots.set(payload.app, root);
  5263. }
  5264. api.highlightElement(roots.get(payload.app));
  5265. }
  5266. else {
  5267. const instance = getComponentInstance(payload.nodeId, i18n);
  5268. instance && api.highlightElement(instance);
  5269. }
  5270. }
  5271. });
  5272. api.on.editInspectorState(payload => {
  5273. if (payload.app === app &&
  5274. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  5275. editScope(payload, i18n);
  5276. }
  5277. });
  5278. api.addTimelineLayer({
  5279. id: "vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */,
  5280. label: VueDevToolsLabels["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */],
  5281. color: VueDevToolsTimelineColors["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]
  5282. });
  5283. resolve(true);
  5284. });
  5285. }
  5286. catch (e) {
  5287. console.error(e);
  5288. reject(false);
  5289. }
  5290. });
  5291. }
  5292. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5293. function getI18nScopeLable(instance) {
  5294. return (instance.type.name ||
  5295. instance.type.displayName ||
  5296. instance.type.__file ||
  5297. 'Anonymous');
  5298. }
  5299. function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
  5300. treeNode, i18n) {
  5301. // prettier-ignore
  5302. const global = i18n.mode === 'composition'
  5303. ? i18n.global
  5304. : i18n.global.__composer;
  5305. if (instance && instance.vnode.el && instance.vnode.el.__VUE_I18N__) {
  5306. // add custom tags local scope only
  5307. if (instance.vnode.el.__VUE_I18N__ !== global) {
  5308. const tag = {
  5309. label: `i18n (${getI18nScopeLable(instance)} Scope)`,
  5310. textColor: 0x000000,
  5311. backgroundColor: 0xffcd19
  5312. };
  5313. treeNode.tags.push(tag);
  5314. }
  5315. }
  5316. }
  5317. function inspectComposer(instanceData, composer) {
  5318. const type = VUE_I18N_COMPONENT_TYPES;
  5319. instanceData.state.push({
  5320. type,
  5321. key: 'locale',
  5322. editable: true,
  5323. value: composer.locale.value
  5324. });
  5325. instanceData.state.push({
  5326. type,
  5327. key: 'availableLocales',
  5328. editable: false,
  5329. value: composer.availableLocales
  5330. });
  5331. instanceData.state.push({
  5332. type,
  5333. key: 'fallbackLocale',
  5334. editable: true,
  5335. value: composer.fallbackLocale.value
  5336. });
  5337. instanceData.state.push({
  5338. type,
  5339. key: 'inheritLocale',
  5340. editable: true,
  5341. value: composer.inheritLocale
  5342. });
  5343. instanceData.state.push({
  5344. type,
  5345. key: 'messages',
  5346. editable: false,
  5347. value: getLocaleMessageValue(composer.messages.value)
  5348. });
  5349. {
  5350. instanceData.state.push({
  5351. type,
  5352. key: 'datetimeFormats',
  5353. editable: false,
  5354. value: composer.datetimeFormats.value
  5355. });
  5356. instanceData.state.push({
  5357. type,
  5358. key: 'numberFormats',
  5359. editable: false,
  5360. value: composer.numberFormats.value
  5361. });
  5362. }
  5363. }
  5364. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5365. function getLocaleMessageValue(messages) {
  5366. const value = {};
  5367. Object.keys(messages).forEach((key) => {
  5368. const v = messages[key];
  5369. if (isFunction(v) && 'source' in v) {
  5370. value[key] = getMessageFunctionDetails(v);
  5371. }
  5372. else if (isMessageAST(v) && v.loc && v.loc.source) {
  5373. value[key] = v.loc.source;
  5374. }
  5375. else if (isObject(v)) {
  5376. value[key] = getLocaleMessageValue(v);
  5377. }
  5378. else {
  5379. value[key] = v;
  5380. }
  5381. });
  5382. return value;
  5383. }
  5384. const ESC = {
  5385. '<': '&lt;',
  5386. '>': '&gt;',
  5387. '"': '&quot;',
  5388. '&': '&amp;'
  5389. };
  5390. function escape(s) {
  5391. return s.replace(/[<>"&]/g, escapeChar);
  5392. }
  5393. function escapeChar(a) {
  5394. return ESC[a] || a;
  5395. }
  5396. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5397. function getMessageFunctionDetails(func) {
  5398. const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
  5399. return {
  5400. _custom: {
  5401. type: 'function',
  5402. display: `<span>ƒ</span> ${argString}`
  5403. }
  5404. };
  5405. }
  5406. function registerScope(payload, i18n) {
  5407. payload.rootNodes.push({
  5408. id: 'global',
  5409. label: 'Global Scope'
  5410. });
  5411. // prettier-ignore
  5412. const global = i18n.mode === 'composition'
  5413. ? i18n.global
  5414. : i18n.global.__composer;
  5415. for (const [keyInstance, instance] of i18n.__instances) {
  5416. // prettier-ignore
  5417. const composer = i18n.mode === 'composition'
  5418. ? instance
  5419. : instance.__composer;
  5420. if (global === composer) {
  5421. continue;
  5422. }
  5423. payload.rootNodes.push({
  5424. id: composer.id.toString(),
  5425. label: `${getI18nScopeLable(keyInstance)} Scope`
  5426. });
  5427. }
  5428. }
  5429. function getComponentInstance(nodeId, i18n) {
  5430. let instance = null;
  5431. if (nodeId !== 'global') {
  5432. for (const [component, composer] of i18n.__instances.entries()) {
  5433. if (composer.id.toString() === nodeId) {
  5434. instance = component;
  5435. break;
  5436. }
  5437. }
  5438. }
  5439. return instance;
  5440. }
  5441. function getComposer$1(nodeId, i18n) {
  5442. if (nodeId === 'global') {
  5443. return i18n.mode === 'composition'
  5444. ? i18n.global
  5445. : i18n.global.__composer;
  5446. }
  5447. else {
  5448. const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
  5449. if (instance) {
  5450. return i18n.mode === 'composition'
  5451. ? instance
  5452. : instance.__composer;
  5453. }
  5454. else {
  5455. return null;
  5456. }
  5457. }
  5458. }
  5459. function inspectScope(payload, i18n
  5460. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5461. ) {
  5462. const composer = getComposer$1(payload.nodeId, i18n);
  5463. if (composer) {
  5464. // TODO:
  5465. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5466. payload.state = makeScopeInspectState(composer);
  5467. }
  5468. return null;
  5469. }
  5470. function makeScopeInspectState(composer) {
  5471. const state = {};
  5472. const localeType = 'Locale related info';
  5473. const localeStates = [
  5474. {
  5475. type: localeType,
  5476. key: 'locale',
  5477. editable: true,
  5478. value: composer.locale.value
  5479. },
  5480. {
  5481. type: localeType,
  5482. key: 'fallbackLocale',
  5483. editable: true,
  5484. value: composer.fallbackLocale.value
  5485. },
  5486. {
  5487. type: localeType,
  5488. key: 'availableLocales',
  5489. editable: false,
  5490. value: composer.availableLocales
  5491. },
  5492. {
  5493. type: localeType,
  5494. key: 'inheritLocale',
  5495. editable: true,
  5496. value: composer.inheritLocale
  5497. }
  5498. ];
  5499. state[localeType] = localeStates;
  5500. const localeMessagesType = 'Locale messages info';
  5501. const localeMessagesStates = [
  5502. {
  5503. type: localeMessagesType,
  5504. key: 'messages',
  5505. editable: false,
  5506. value: getLocaleMessageValue(composer.messages.value)
  5507. }
  5508. ];
  5509. state[localeMessagesType] = localeMessagesStates;
  5510. {
  5511. const datetimeFormatsType = 'Datetime formats info';
  5512. const datetimeFormatsStates = [
  5513. {
  5514. type: datetimeFormatsType,
  5515. key: 'datetimeFormats',
  5516. editable: false,
  5517. value: composer.datetimeFormats.value
  5518. }
  5519. ];
  5520. state[datetimeFormatsType] = datetimeFormatsStates;
  5521. const numberFormatsType = 'Datetime formats info';
  5522. const numberFormatsStates = [
  5523. {
  5524. type: numberFormatsType,
  5525. key: 'numberFormats',
  5526. editable: false,
  5527. value: composer.numberFormats.value
  5528. }
  5529. ];
  5530. state[numberFormatsType] = numberFormatsStates;
  5531. }
  5532. return state;
  5533. }
  5534. function addTimelineEvent(event, payload) {
  5535. if (devtoolsApi) {
  5536. let groupId;
  5537. if (payload && 'groupId' in payload) {
  5538. groupId = payload.groupId;
  5539. delete payload.groupId;
  5540. }
  5541. devtoolsApi.addTimelineEvent({
  5542. layerId: "vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */,
  5543. event: {
  5544. title: event,
  5545. groupId,
  5546. time: Date.now(),
  5547. meta: {},
  5548. data: payload || {},
  5549. logType: event === "compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */
  5550. ? 'error'
  5551. : event === "fallback" /* VueDevToolsTimelineEvents.FALBACK */ ||
  5552. event === "missing" /* VueDevToolsTimelineEvents.MISSING */
  5553. ? 'warning'
  5554. : 'default'
  5555. }
  5556. });
  5557. }
  5558. }
  5559. function editScope(payload, i18n) {
  5560. const composer = getComposer$1(payload.nodeId, i18n);
  5561. if (composer) {
  5562. const [field] = payload.path;
  5563. if (field === 'locale' && isString(payload.state.value)) {
  5564. composer.locale.value = payload.state.value;
  5565. }
  5566. else if (field === 'fallbackLocale' &&
  5567. (isString(payload.state.value) ||
  5568. isArray(payload.state.value) ||
  5569. isObject(payload.state.value))) {
  5570. composer.fallbackLocale.value = payload.state.value;
  5571. }
  5572. else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
  5573. composer.inheritLocale = payload.state.value;
  5574. }
  5575. }
  5576. }
  5577. /**
  5578. * Supports compatibility for legacy vue-i18n APIs
  5579. * This mixin is used when we use vue-i18n@v9.x or later
  5580. */
  5581. function defineMixin(vuei18n, composer, i18n) {
  5582. return {
  5583. beforeCreate() {
  5584. const instance = getCurrentInstance();
  5585. /* istanbul ignore if */
  5586. if (!instance) {
  5587. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5588. }
  5589. const options = this.$options;
  5590. if (options.i18n) {
  5591. const optionsI18n = options.i18n;
  5592. if (options.__i18n) {
  5593. optionsI18n.__i18n = options.__i18n;
  5594. }
  5595. optionsI18n.__root = composer;
  5596. if (this === this.$root) {
  5597. // merge option and gttach global
  5598. this.$i18n = mergeToGlobal(vuei18n, optionsI18n);
  5599. }
  5600. else {
  5601. optionsI18n.__injectWithOption = true;
  5602. optionsI18n.__extender = i18n.__vueI18nExtend;
  5603. // atttach local VueI18n instance
  5604. this.$i18n = createVueI18n(optionsI18n);
  5605. // extend VueI18n instance
  5606. const _vueI18n = this.$i18n;
  5607. if (_vueI18n.__extender) {
  5608. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  5609. }
  5610. }
  5611. }
  5612. else if (options.__i18n) {
  5613. if (this === this.$root) {
  5614. // merge option and gttach global
  5615. this.$i18n = mergeToGlobal(vuei18n, options);
  5616. }
  5617. else {
  5618. // atttach local VueI18n instance
  5619. this.$i18n = createVueI18n({
  5620. __i18n: options.__i18n,
  5621. __injectWithOption: true,
  5622. __extender: i18n.__vueI18nExtend,
  5623. __root: composer
  5624. });
  5625. // extend VueI18n instance
  5626. const _vueI18n = this.$i18n;
  5627. if (_vueI18n.__extender) {
  5628. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  5629. }
  5630. }
  5631. }
  5632. else {
  5633. // attach global VueI18n instance
  5634. this.$i18n = vuei18n;
  5635. }
  5636. if (options.__i18nGlobal) {
  5637. adjustI18nResources(composer, options, options);
  5638. }
  5639. // defines vue-i18n legacy APIs
  5640. this.$t = (...args) => this.$i18n.t(...args);
  5641. this.$rt = (...args) => this.$i18n.rt(...args);
  5642. this.$tc = (...args) => this.$i18n.tc(...args);
  5643. this.$te = (key, locale) => this.$i18n.te(key, locale);
  5644. this.$d = (...args) => this.$i18n.d(...args);
  5645. this.$n = (...args) => this.$i18n.n(...args);
  5646. this.$tm = (key) => this.$i18n.tm(key);
  5647. i18n.__setInstance(instance, this.$i18n);
  5648. },
  5649. mounted() {
  5650. /* istanbul ignore if */
  5651. if (this.$el &&
  5652. this.$i18n) {
  5653. const _vueI18n = this.$i18n;
  5654. this.$el.__VUE_I18N__ = _vueI18n.__composer;
  5655. const emitter = (this.__v_emitter =
  5656. createEmitter());
  5657. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  5658. emitter.on('*', addTimelineEvent);
  5659. }
  5660. },
  5661. unmounted() {
  5662. const instance = getCurrentInstance();
  5663. /* istanbul ignore if */
  5664. if (!instance) {
  5665. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5666. }
  5667. const _vueI18n = this.$i18n;
  5668. /* istanbul ignore if */
  5669. if (this.$el &&
  5670. this.$el.__VUE_I18N__) {
  5671. if (this.__v_emitter) {
  5672. this.__v_emitter.off('*', addTimelineEvent);
  5673. delete this.__v_emitter;
  5674. }
  5675. if (this.$i18n) {
  5676. _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
  5677. delete this.$el.__VUE_I18N__;
  5678. }
  5679. }
  5680. delete this.$t;
  5681. delete this.$rt;
  5682. delete this.$tc;
  5683. delete this.$te;
  5684. delete this.$d;
  5685. delete this.$n;
  5686. delete this.$tm;
  5687. if (_vueI18n.__disposer) {
  5688. _vueI18n.__disposer();
  5689. delete _vueI18n.__disposer;
  5690. delete _vueI18n.__extender;
  5691. }
  5692. i18n.__deleteInstance(instance);
  5693. delete this.$i18n;
  5694. }
  5695. };
  5696. }
  5697. function mergeToGlobal(g, options) {
  5698. g.locale = options.locale || g.locale;
  5699. g.fallbackLocale = options.fallbackLocale || g.fallbackLocale;
  5700. g.missing = options.missing || g.missing;
  5701. g.silentTranslationWarn =
  5702. options.silentTranslationWarn || g.silentFallbackWarn;
  5703. g.silentFallbackWarn = options.silentFallbackWarn || g.silentFallbackWarn;
  5704. g.formatFallbackMessages =
  5705. options.formatFallbackMessages || g.formatFallbackMessages;
  5706. g.postTranslation = options.postTranslation || g.postTranslation;
  5707. g.warnHtmlInMessage = options.warnHtmlInMessage || g.warnHtmlInMessage;
  5708. g.escapeParameterHtml = options.escapeParameterHtml || g.escapeParameterHtml;
  5709. g.sync = options.sync || g.sync;
  5710. g.__composer[SetPluralRulesSymbol](options.pluralizationRules || g.pluralizationRules);
  5711. const messages = getLocaleMessages(g.locale, {
  5712. messages: options.messages,
  5713. __i18n: options.__i18n
  5714. });
  5715. Object.keys(messages).forEach(locale => g.mergeLocaleMessage(locale, messages[locale]));
  5716. if (options.datetimeFormats) {
  5717. Object.keys(options.datetimeFormats).forEach(locale => g.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
  5718. }
  5719. if (options.numberFormats) {
  5720. Object.keys(options.numberFormats).forEach(locale => g.mergeNumberFormat(locale, options.numberFormats[locale]));
  5721. }
  5722. return g;
  5723. }
  5724. /**
  5725. * Injection key for {@link useI18n}
  5726. *
  5727. * @remarks
  5728. * The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.
  5729. * Specify the i18n instance created by {@link createI18n} together with `provide` function.
  5730. *
  5731. * @VueI18nGeneral
  5732. */
  5733. const I18nInjectionKey =
  5734. /* #__PURE__*/ makeSymbol('global-vue-i18n');
  5735. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  5736. function createI18n(options = {}, VueI18nLegacy) {
  5737. // prettier-ignore
  5738. const __legacyMode = isBoolean(options.legacy)
  5739. ? options.legacy
  5740. : true;
  5741. // prettier-ignore
  5742. const __globalInjection = isBoolean(options.globalInjection)
  5743. ? options.globalInjection
  5744. : true;
  5745. // prettier-ignore
  5746. const __allowComposition = __legacyMode
  5747. ? !!options.allowComposition
  5748. : true;
  5749. const __instances = new Map();
  5750. const [globalScope, __global] = createGlobal(options, __legacyMode);
  5751. const symbol = /* #__PURE__*/ makeSymbol('vue-i18n' );
  5752. {
  5753. if (__legacyMode && __allowComposition && !false) {
  5754. warn(getWarnMessage(I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION));
  5755. }
  5756. }
  5757. function __getInstance(component) {
  5758. return __instances.get(component) || null;
  5759. }
  5760. function __setInstance(component, instance) {
  5761. __instances.set(component, instance);
  5762. }
  5763. function __deleteInstance(component) {
  5764. __instances.delete(component);
  5765. }
  5766. {
  5767. const i18n = {
  5768. // mode
  5769. get mode() {
  5770. return __legacyMode
  5771. ? 'legacy'
  5772. : 'composition';
  5773. },
  5774. // allowComposition
  5775. get allowComposition() {
  5776. return __allowComposition;
  5777. },
  5778. // install plugin
  5779. async install(app, ...options) {
  5780. {
  5781. app.__VUE_I18N__ = i18n;
  5782. }
  5783. // setup global provider
  5784. app.__VUE_I18N_SYMBOL__ = symbol;
  5785. app.provide(app.__VUE_I18N_SYMBOL__, i18n);
  5786. // set composer & vuei18n extend hook options from plugin options
  5787. if (isPlainObject(options[0])) {
  5788. const opts = options[0];
  5789. i18n.__composerExtend =
  5790. opts.__composerExtend;
  5791. i18n.__vueI18nExtend =
  5792. opts.__vueI18nExtend;
  5793. }
  5794. // global method and properties injection for Composition API
  5795. let globalReleaseHandler = null;
  5796. if (!__legacyMode && __globalInjection) {
  5797. globalReleaseHandler = injectGlobalFields(app, i18n.global);
  5798. }
  5799. // install built-in components and directive
  5800. {
  5801. apply(app, i18n, ...options);
  5802. }
  5803. // setup mixin for Legacy API
  5804. if (__legacyMode) {
  5805. app.mixin(defineMixin(__global, __global.__composer, i18n));
  5806. }
  5807. // release global scope
  5808. const unmountApp = app.unmount;
  5809. app.unmount = () => {
  5810. globalReleaseHandler && globalReleaseHandler();
  5811. i18n.dispose();
  5812. unmountApp();
  5813. };
  5814. // setup vue-devtools plugin
  5815. {
  5816. const ret = await enableDevTools(app, i18n);
  5817. if (!ret) {
  5818. throw createI18nError(I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);
  5819. }
  5820. const emitter = createEmitter();
  5821. if (__legacyMode) {
  5822. const _vueI18n = __global;
  5823. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  5824. }
  5825. else {
  5826. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5827. const _composer = __global;
  5828. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  5829. }
  5830. emitter.on('*', addTimelineEvent);
  5831. }
  5832. },
  5833. // global accessor
  5834. get global() {
  5835. return __global;
  5836. },
  5837. dispose() {
  5838. globalScope.stop();
  5839. },
  5840. // @internal
  5841. __instances,
  5842. // @internal
  5843. __getInstance,
  5844. // @internal
  5845. __setInstance,
  5846. // @internal
  5847. __deleteInstance
  5848. };
  5849. return i18n;
  5850. }
  5851. }
  5852. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  5853. function useI18n(options = {}) {
  5854. const instance = getCurrentInstance();
  5855. if (instance == null) {
  5856. throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);
  5857. }
  5858. if (!instance.isCE &&
  5859. instance.appContext.app != null &&
  5860. !instance.appContext.app.__VUE_I18N_SYMBOL__) {
  5861. throw createI18nError(I18nErrorCodes.NOT_INSTALLED);
  5862. }
  5863. const i18n = getI18nInstance(instance);
  5864. const gl = getGlobalComposer(i18n);
  5865. const componentOptions = getComponentOptions(instance);
  5866. const scope = getScope(options, componentOptions);
  5867. {
  5868. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5869. if (i18n.mode === 'legacy' && !options.__useComponent) {
  5870. if (!i18n.allowComposition) {
  5871. throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE);
  5872. }
  5873. return useI18nForLegacy(instance, scope, gl, options);
  5874. }
  5875. }
  5876. if (scope === 'global') {
  5877. adjustI18nResources(gl, options, componentOptions);
  5878. return gl;
  5879. }
  5880. if (scope === 'parent') {
  5881. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5882. let composer = getComposer(i18n, instance, options.__useComponent);
  5883. if (composer == null) {
  5884. {
  5885. warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));
  5886. }
  5887. composer = gl;
  5888. }
  5889. return composer;
  5890. }
  5891. const i18nInternal = i18n;
  5892. let composer = i18nInternal.__getInstance(instance);
  5893. if (composer == null) {
  5894. const composerOptions = assign({}, options);
  5895. if ('__i18n' in componentOptions) {
  5896. composerOptions.__i18n = componentOptions.__i18n;
  5897. }
  5898. if (gl) {
  5899. composerOptions.__root = gl;
  5900. }
  5901. composer = createComposer(composerOptions);
  5902. if (i18nInternal.__composerExtend) {
  5903. composer[DisposeSymbol] =
  5904. i18nInternal.__composerExtend(composer);
  5905. }
  5906. setupLifeCycle(i18nInternal, instance, composer);
  5907. i18nInternal.__setInstance(instance, composer);
  5908. }
  5909. return composer;
  5910. }
  5911. /**
  5912. * Cast to VueI18n legacy compatible type
  5913. *
  5914. * @remarks
  5915. * This API is provided only with [vue-i18n-bridge](https://vue-i18n.intlify.dev/guide/migration/ways.html#what-is-vue-i18n-bridge).
  5916. *
  5917. * The purpose of this function is to convert an {@link I18n} instance created with {@link createI18n | createI18n(legacy: true)} into a `vue-i18n@v8.x` compatible instance of `new VueI18n` in a TypeScript environment.
  5918. *
  5919. * @param i18n - An instance of {@link I18n}
  5920. * @returns A i18n instance which is casted to {@link VueI18n} type
  5921. *
  5922. * @VueI18nTip
  5923. * :new: provided by **vue-i18n-bridge only**
  5924. *
  5925. * @VueI18nGeneral
  5926. */
  5927. /* #__NO_SIDE_EFFECTS__ */
  5928. const castToVueI18n = (i18n
  5929. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5930. ) => {
  5931. if (!(__VUE_I18N_BRIDGE__ in i18n)) {
  5932. throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);
  5933. }
  5934. return i18n;
  5935. };
  5936. function createGlobal(options, legacyMode, VueI18nLegacy // eslint-disable-line @typescript-eslint/no-explicit-any
  5937. ) {
  5938. const scope = effectScope();
  5939. {
  5940. const obj = legacyMode
  5941. ? scope.run(() => createVueI18n(options))
  5942. : scope.run(() => createComposer(options));
  5943. if (obj == null) {
  5944. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  5945. }
  5946. return [scope, obj];
  5947. }
  5948. }
  5949. function getI18nInstance(instance) {
  5950. {
  5951. const i18n = inject(!instance.isCE
  5952. ? instance.appContext.app.__VUE_I18N_SYMBOL__
  5953. : I18nInjectionKey);
  5954. /* istanbul ignore if */
  5955. if (!i18n) {
  5956. throw createI18nError(!instance.isCE
  5957. ? I18nErrorCodes.UNEXPECTED_ERROR
  5958. : I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE);
  5959. }
  5960. return i18n;
  5961. }
  5962. }
  5963. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5964. function getScope(options, componentOptions) {
  5965. // prettier-ignore
  5966. return isEmptyObject(options)
  5967. ? ('__i18n' in componentOptions)
  5968. ? 'local'
  5969. : 'global'
  5970. : !options.useScope
  5971. ? 'local'
  5972. : options.useScope;
  5973. }
  5974. function getGlobalComposer(i18n) {
  5975. // prettier-ignore
  5976. return i18n.mode === 'composition'
  5977. ? i18n.global
  5978. : i18n.global.__composer
  5979. ;
  5980. }
  5981. function getComposer(i18n, target, useComponent = false) {
  5982. let composer = null;
  5983. const root = target.root;
  5984. let current = getParentComponentInstance(target, useComponent);
  5985. while (current != null) {
  5986. const i18nInternal = i18n;
  5987. if (i18n.mode === 'composition') {
  5988. composer = i18nInternal.__getInstance(current);
  5989. }
  5990. else {
  5991. {
  5992. const vueI18n = i18nInternal.__getInstance(current);
  5993. if (vueI18n != null) {
  5994. composer = vueI18n
  5995. .__composer;
  5996. if (useComponent &&
  5997. composer &&
  5998. !composer[InejctWithOptionSymbol] // eslint-disable-line @typescript-eslint/no-explicit-any
  5999. ) {
  6000. composer = null;
  6001. }
  6002. }
  6003. }
  6004. }
  6005. if (composer != null) {
  6006. break;
  6007. }
  6008. if (root === current) {
  6009. break;
  6010. }
  6011. current = current.parent;
  6012. }
  6013. return composer;
  6014. }
  6015. function getParentComponentInstance(target, useComponent = false) {
  6016. if (target == null) {
  6017. return null;
  6018. }
  6019. {
  6020. // if `useComponent: true` will be specified, we get lexical scope owner instance for use-case slots
  6021. return !useComponent
  6022. ? target.parent
  6023. : target.vnode.ctx || target.parent; // eslint-disable-line @typescript-eslint/no-explicit-any
  6024. }
  6025. }
  6026. function setupLifeCycle(i18n, target, composer) {
  6027. let emitter = null;
  6028. {
  6029. onMounted(() => {
  6030. // inject composer instance to DOM for intlify-devtools
  6031. if (target.vnode.el) {
  6032. target.vnode.el.__VUE_I18N__ = composer;
  6033. emitter = createEmitter();
  6034. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6035. const _composer = composer;
  6036. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  6037. emitter.on('*', addTimelineEvent);
  6038. }
  6039. }, target);
  6040. onUnmounted(() => {
  6041. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6042. const _composer = composer;
  6043. // remove composer instance from DOM for intlify-devtools
  6044. if (target.vnode.el &&
  6045. target.vnode.el.__VUE_I18N__) {
  6046. emitter && emitter.off('*', addTimelineEvent);
  6047. _composer[DisableEmitter] && _composer[DisableEmitter]();
  6048. delete target.vnode.el.__VUE_I18N__;
  6049. }
  6050. i18n.__deleteInstance(target);
  6051. // dispose extended resources
  6052. const dispose = _composer[DisposeSymbol];
  6053. if (dispose) {
  6054. dispose();
  6055. delete _composer[DisposeSymbol];
  6056. }
  6057. }, target);
  6058. }
  6059. }
  6060. function useI18nForLegacy(instance, scope, root, options = {} // eslint-disable-line @typescript-eslint/no-explicit-any
  6061. ) {
  6062. const isLocalScope = scope === 'local';
  6063. const _composer = shallowRef(null);
  6064. if (isLocalScope &&
  6065. instance.proxy &&
  6066. !(instance.proxy.$options.i18n || instance.proxy.$options.__i18n)) {
  6067. throw createI18nError(I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION);
  6068. }
  6069. const _inheritLocale = isBoolean(options.inheritLocale)
  6070. ? options.inheritLocale
  6071. : !isString(options.locale);
  6072. const _locale = ref(
  6073. // prettier-ignore
  6074. !isLocalScope || _inheritLocale
  6075. ? root.locale.value
  6076. : isString(options.locale)
  6077. ? options.locale
  6078. : DEFAULT_LOCALE);
  6079. const _fallbackLocale = ref(
  6080. // prettier-ignore
  6081. !isLocalScope || _inheritLocale
  6082. ? root.fallbackLocale.value
  6083. : isString(options.fallbackLocale) ||
  6084. isArray(options.fallbackLocale) ||
  6085. isPlainObject(options.fallbackLocale) ||
  6086. options.fallbackLocale === false
  6087. ? options.fallbackLocale
  6088. : _locale.value);
  6089. const _messages = ref(getLocaleMessages(_locale.value, options));
  6090. // prettier-ignore
  6091. const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
  6092. ? options.datetimeFormats
  6093. : { [_locale.value]: {} });
  6094. // prettier-ignore
  6095. const _numberFormats = ref(isPlainObject(options.numberFormats)
  6096. ? options.numberFormats
  6097. : { [_locale.value]: {} });
  6098. // prettier-ignore
  6099. const _missingWarn = isLocalScope
  6100. ? root.missingWarn
  6101. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  6102. ? options.missingWarn
  6103. : true;
  6104. // prettier-ignore
  6105. const _fallbackWarn = isLocalScope
  6106. ? root.fallbackWarn
  6107. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  6108. ? options.fallbackWarn
  6109. : true;
  6110. // prettier-ignore
  6111. const _fallbackRoot = isLocalScope
  6112. ? root.fallbackRoot
  6113. : isBoolean(options.fallbackRoot)
  6114. ? options.fallbackRoot
  6115. : true;
  6116. // configure fall back to root
  6117. const _fallbackFormat = !!options.fallbackFormat;
  6118. // runtime missing
  6119. const _missing = isFunction(options.missing) ? options.missing : null;
  6120. // postTranslation handler
  6121. const _postTranslation = isFunction(options.postTranslation)
  6122. ? options.postTranslation
  6123. : null;
  6124. // prettier-ignore
  6125. const _warnHtmlMessage = isLocalScope
  6126. ? root.warnHtmlMessage
  6127. : isBoolean(options.warnHtmlMessage)
  6128. ? options.warnHtmlMessage
  6129. : true;
  6130. const _escapeParameter = !!options.escapeParameter;
  6131. // prettier-ignore
  6132. const _modifiers = isLocalScope
  6133. ? root.modifiers
  6134. : isPlainObject(options.modifiers)
  6135. ? options.modifiers
  6136. : {};
  6137. // pluralRules
  6138. const _pluralRules = options.pluralRules || (isLocalScope && root.pluralRules);
  6139. // track reactivity
  6140. function trackReactivityValues() {
  6141. return [
  6142. _locale.value,
  6143. _fallbackLocale.value,
  6144. _messages.value,
  6145. _datetimeFormats.value,
  6146. _numberFormats.value
  6147. ];
  6148. }
  6149. // locale
  6150. const locale = computed({
  6151. get: () => {
  6152. return _composer.value ? _composer.value.locale.value : _locale.value;
  6153. },
  6154. set: val => {
  6155. if (_composer.value) {
  6156. _composer.value.locale.value = val;
  6157. }
  6158. _locale.value = val;
  6159. }
  6160. });
  6161. // fallbackLocale
  6162. const fallbackLocale = computed({
  6163. get: () => {
  6164. return _composer.value
  6165. ? _composer.value.fallbackLocale.value
  6166. : _fallbackLocale.value;
  6167. },
  6168. set: val => {
  6169. if (_composer.value) {
  6170. _composer.value.fallbackLocale.value = val;
  6171. }
  6172. _fallbackLocale.value = val;
  6173. }
  6174. });
  6175. // messages
  6176. const messages = computed(() => {
  6177. if (_composer.value) {
  6178. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6179. return _composer.value.messages.value;
  6180. }
  6181. else {
  6182. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6183. return _messages.value;
  6184. }
  6185. });
  6186. const datetimeFormats = computed(() => _datetimeFormats.value);
  6187. const numberFormats = computed(() => _numberFormats.value);
  6188. function getPostTranslationHandler() {
  6189. return _composer.value
  6190. ? _composer.value.getPostTranslationHandler()
  6191. : _postTranslation;
  6192. }
  6193. function setPostTranslationHandler(handler) {
  6194. if (_composer.value) {
  6195. _composer.value.setPostTranslationHandler(handler);
  6196. }
  6197. }
  6198. function getMissingHandler() {
  6199. return _composer.value ? _composer.value.getMissingHandler() : _missing;
  6200. }
  6201. function setMissingHandler(handler) {
  6202. if (_composer.value) {
  6203. _composer.value.setMissingHandler(handler);
  6204. }
  6205. }
  6206. function warpWithDeps(fn) {
  6207. trackReactivityValues();
  6208. return fn();
  6209. }
  6210. function t(...args) {
  6211. return _composer.value
  6212. ? warpWithDeps(() => Reflect.apply(_composer.value.t, null, [...args]))
  6213. : warpWithDeps(() => '');
  6214. }
  6215. function rt(...args) {
  6216. return _composer.value
  6217. ? Reflect.apply(_composer.value.rt, null, [...args])
  6218. : '';
  6219. }
  6220. function d(...args) {
  6221. return _composer.value
  6222. ? warpWithDeps(() => Reflect.apply(_composer.value.d, null, [...args]))
  6223. : warpWithDeps(() => '');
  6224. }
  6225. function n(...args) {
  6226. return _composer.value
  6227. ? warpWithDeps(() => Reflect.apply(_composer.value.n, null, [...args]))
  6228. : warpWithDeps(() => '');
  6229. }
  6230. function tm(key) {
  6231. return _composer.value ? _composer.value.tm(key) : {};
  6232. }
  6233. function te(key, locale) {
  6234. return _composer.value ? _composer.value.te(key, locale) : false;
  6235. }
  6236. function getLocaleMessage(locale) {
  6237. return _composer.value ? _composer.value.getLocaleMessage(locale) : {};
  6238. }
  6239. function setLocaleMessage(locale, message) {
  6240. if (_composer.value) {
  6241. _composer.value.setLocaleMessage(locale, message);
  6242. _messages.value[locale] = message;
  6243. }
  6244. }
  6245. function mergeLocaleMessage(locale, message) {
  6246. if (_composer.value) {
  6247. _composer.value.mergeLocaleMessage(locale, message);
  6248. }
  6249. }
  6250. function getDateTimeFormat(locale) {
  6251. return _composer.value ? _composer.value.getDateTimeFormat(locale) : {};
  6252. }
  6253. function setDateTimeFormat(locale, format) {
  6254. if (_composer.value) {
  6255. _composer.value.setDateTimeFormat(locale, format);
  6256. _datetimeFormats.value[locale] = format;
  6257. }
  6258. }
  6259. function mergeDateTimeFormat(locale, format) {
  6260. if (_composer.value) {
  6261. _composer.value.mergeDateTimeFormat(locale, format);
  6262. }
  6263. }
  6264. function getNumberFormat(locale) {
  6265. return _composer.value ? _composer.value.getNumberFormat(locale) : {};
  6266. }
  6267. function setNumberFormat(locale, format) {
  6268. if (_composer.value) {
  6269. _composer.value.setNumberFormat(locale, format);
  6270. _numberFormats.value[locale] = format;
  6271. }
  6272. }
  6273. function mergeNumberFormat(locale, format) {
  6274. if (_composer.value) {
  6275. _composer.value.mergeNumberFormat(locale, format);
  6276. }
  6277. }
  6278. const wrapper = {
  6279. get id() {
  6280. return _composer.value ? _composer.value.id : -1;
  6281. },
  6282. locale,
  6283. fallbackLocale,
  6284. messages,
  6285. datetimeFormats,
  6286. numberFormats,
  6287. get inheritLocale() {
  6288. return _composer.value ? _composer.value.inheritLocale : _inheritLocale;
  6289. },
  6290. set inheritLocale(val) {
  6291. if (_composer.value) {
  6292. _composer.value.inheritLocale = val;
  6293. }
  6294. },
  6295. get availableLocales() {
  6296. return _composer.value
  6297. ? _composer.value.availableLocales
  6298. : Object.keys(_messages.value);
  6299. },
  6300. get modifiers() {
  6301. return (_composer.value ? _composer.value.modifiers : _modifiers);
  6302. },
  6303. get pluralRules() {
  6304. return (_composer.value ? _composer.value.pluralRules : _pluralRules);
  6305. },
  6306. get isGlobal() {
  6307. return _composer.value ? _composer.value.isGlobal : false;
  6308. },
  6309. get missingWarn() {
  6310. return _composer.value ? _composer.value.missingWarn : _missingWarn;
  6311. },
  6312. set missingWarn(val) {
  6313. if (_composer.value) {
  6314. _composer.value.missingWarn = val;
  6315. }
  6316. },
  6317. get fallbackWarn() {
  6318. return _composer.value ? _composer.value.fallbackWarn : _fallbackWarn;
  6319. },
  6320. set fallbackWarn(val) {
  6321. if (_composer.value) {
  6322. _composer.value.missingWarn = val;
  6323. }
  6324. },
  6325. get fallbackRoot() {
  6326. return _composer.value ? _composer.value.fallbackRoot : _fallbackRoot;
  6327. },
  6328. set fallbackRoot(val) {
  6329. if (_composer.value) {
  6330. _composer.value.fallbackRoot = val;
  6331. }
  6332. },
  6333. get fallbackFormat() {
  6334. return _composer.value ? _composer.value.fallbackFormat : _fallbackFormat;
  6335. },
  6336. set fallbackFormat(val) {
  6337. if (_composer.value) {
  6338. _composer.value.fallbackFormat = val;
  6339. }
  6340. },
  6341. get warnHtmlMessage() {
  6342. return _composer.value
  6343. ? _composer.value.warnHtmlMessage
  6344. : _warnHtmlMessage;
  6345. },
  6346. set warnHtmlMessage(val) {
  6347. if (_composer.value) {
  6348. _composer.value.warnHtmlMessage = val;
  6349. }
  6350. },
  6351. get escapeParameter() {
  6352. return _composer.value
  6353. ? _composer.value.escapeParameter
  6354. : _escapeParameter;
  6355. },
  6356. set escapeParameter(val) {
  6357. if (_composer.value) {
  6358. _composer.value.escapeParameter = val;
  6359. }
  6360. },
  6361. t,
  6362. getPostTranslationHandler,
  6363. setPostTranslationHandler,
  6364. getMissingHandler,
  6365. setMissingHandler,
  6366. rt,
  6367. d,
  6368. n,
  6369. tm,
  6370. te,
  6371. getLocaleMessage,
  6372. setLocaleMessage,
  6373. mergeLocaleMessage,
  6374. getDateTimeFormat,
  6375. setDateTimeFormat,
  6376. mergeDateTimeFormat,
  6377. getNumberFormat,
  6378. setNumberFormat,
  6379. mergeNumberFormat
  6380. };
  6381. function sync(composer) {
  6382. composer.locale.value = _locale.value;
  6383. composer.fallbackLocale.value = _fallbackLocale.value;
  6384. Object.keys(_messages.value).forEach(locale => {
  6385. composer.mergeLocaleMessage(locale, _messages.value[locale]);
  6386. });
  6387. Object.keys(_datetimeFormats.value).forEach(locale => {
  6388. composer.mergeDateTimeFormat(locale, _datetimeFormats.value[locale]);
  6389. });
  6390. Object.keys(_numberFormats.value).forEach(locale => {
  6391. composer.mergeNumberFormat(locale, _numberFormats.value[locale]);
  6392. });
  6393. composer.escapeParameter = _escapeParameter;
  6394. composer.fallbackFormat = _fallbackFormat;
  6395. composer.fallbackRoot = _fallbackRoot;
  6396. composer.fallbackWarn = _fallbackWarn;
  6397. composer.missingWarn = _missingWarn;
  6398. composer.warnHtmlMessage = _warnHtmlMessage;
  6399. }
  6400. onBeforeMount(() => {
  6401. if (instance.proxy == null || instance.proxy.$i18n == null) {
  6402. throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY);
  6403. }
  6404. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6405. const composer = (_composer.value = instance.proxy.$i18n
  6406. .__composer);
  6407. if (scope === 'global') {
  6408. _locale.value = composer.locale.value;
  6409. _fallbackLocale.value = composer.fallbackLocale.value;
  6410. _messages.value = composer.messages.value;
  6411. _datetimeFormats.value = composer.datetimeFormats.value;
  6412. _numberFormats.value = composer.numberFormats.value;
  6413. }
  6414. else if (isLocalScope) {
  6415. sync(composer);
  6416. }
  6417. });
  6418. return wrapper;
  6419. }
  6420. const globalExportProps = [
  6421. 'locale',
  6422. 'fallbackLocale',
  6423. 'availableLocales'
  6424. ];
  6425. const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm', 'te']
  6426. ;
  6427. function injectGlobalFields(app, composer) {
  6428. const i18n = Object.create(null);
  6429. globalExportProps.forEach(prop => {
  6430. const desc = Object.getOwnPropertyDescriptor(composer, prop);
  6431. if (!desc) {
  6432. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  6433. }
  6434. const wrap = isRef(desc.value) // check computed props
  6435. ? {
  6436. get() {
  6437. return desc.value.value;
  6438. },
  6439. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6440. set(val) {
  6441. desc.value.value = val;
  6442. }
  6443. }
  6444. : {
  6445. get() {
  6446. return desc.get && desc.get();
  6447. }
  6448. };
  6449. Object.defineProperty(i18n, prop, wrap);
  6450. });
  6451. app.config.globalProperties.$i18n = i18n;
  6452. globalExportMethods.forEach(method => {
  6453. const desc = Object.getOwnPropertyDescriptor(composer, method);
  6454. if (!desc || !desc.value) {
  6455. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  6456. }
  6457. Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
  6458. });
  6459. const dispose = () => {
  6460. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6461. delete app.config.globalProperties.$i18n;
  6462. globalExportMethods.forEach(method => {
  6463. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6464. delete app.config.globalProperties[`$${method}`];
  6465. });
  6466. };
  6467. return dispose;
  6468. }
  6469. // register message compiler at vue-i18n
  6470. {
  6471. registerMessageCompiler(compile);
  6472. }
  6473. // register message resolver at vue-i18n
  6474. registerMessageResolver(resolveValue);
  6475. // register fallback locale at vue-i18n
  6476. registerLocaleFallbacker(fallbackWithLocaleChain);
  6477. // NOTE: experimental !!
  6478. {
  6479. const target = getGlobalThis();
  6480. target.__INTLIFY__ = true;
  6481. setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
  6482. }
  6483. {
  6484. initDev();
  6485. }
  6486. export { DatetimeFormat, I18nD, I18nInjectionKey, I18nN, I18nT, NumberFormat, Translation, VERSION, castToVueI18n, createI18n, useI18n, vTDirective };