vue-i18n.runtime.esm-browser.js 172 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001
  1. /*!
  2. * vue-i18n v9.13.1
  3. * (c) 2024 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. import { createVNode, Text, computed, watch, getCurrentInstance, ref, shallowRef, Fragment, defineComponent, h, effectScope, inject, onMounted, onUnmounted, 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(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. const stack = [{ src, des }];
  220. while (stack.length) {
  221. const { src, des } = stack.pop();
  222. Object.keys(src).forEach(key => {
  223. if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
  224. // replace with src[key] when:
  225. // src[key] or des[key] is not an object, or
  226. // src[key] or des[key] is an array
  227. des[key] = src[key];
  228. }
  229. else {
  230. // src[key] and des[key] are both objects, merge them
  231. stack.push({ src: src[key], des: des[key] });
  232. }
  233. });
  234. }
  235. }
  236. const CompileWarnCodes = {
  237. USE_MODULO_SYNTAX: 1,
  238. __EXTEND_POINT__: 2
  239. };
  240. const CompileErrorCodes = {
  241. // tokenizer error codes
  242. EXPECTED_TOKEN: 1,
  243. INVALID_TOKEN_IN_PLACEHOLDER: 2,
  244. UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
  245. UNKNOWN_ESCAPE_SEQUENCE: 4,
  246. INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
  247. UNBALANCED_CLOSING_BRACE: 6,
  248. UNTERMINATED_CLOSING_BRACE: 7,
  249. EMPTY_PLACEHOLDER: 8,
  250. NOT_ALLOW_NEST_PLACEHOLDER: 9,
  251. INVALID_LINKED_FORMAT: 10,
  252. // parser error codes
  253. MUST_HAVE_MESSAGES_IN_PLURAL: 11,
  254. UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
  255. UNEXPECTED_EMPTY_LINKED_KEY: 13,
  256. UNEXPECTED_LEXICAL_ANALYSIS: 14,
  257. // generator error codes
  258. UNHANDLED_CODEGEN_NODE_TYPE: 15,
  259. // minifier error codes
  260. UNHANDLED_MINIFIER_NODE_TYPE: 16,
  261. // Special value for higher-order compilers to pick up the last code
  262. // to avoid collision of error codes. This should always be kept as the last
  263. // item.
  264. __EXTEND_POINT__: 17
  265. };
  266. /** @internal */
  267. const errorMessages$2 = {
  268. // tokenizer error messages
  269. [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
  270. [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
  271. [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
  272. [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
  273. [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
  274. [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
  275. [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
  276. [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
  277. [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
  278. [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
  279. // parser error messages
  280. [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
  281. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
  282. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
  283. [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
  284. // generator error messages
  285. [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
  286. // minimizer error messages
  287. [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
  288. };
  289. function createCompileError(code, loc, options = {}) {
  290. const { domain, messages, args } = options;
  291. const msg = format((messages || errorMessages$2)[code] || '', ...(args || []))
  292. ;
  293. const error = new SyntaxError(String(msg));
  294. error.code = code;
  295. if (loc) {
  296. error.location = loc;
  297. }
  298. error.domain = domain;
  299. return error;
  300. }
  301. const pathStateMachine = [];
  302. pathStateMachine[0 /* States.BEFORE_PATH */] = {
  303. ["w" /* PathCharTypes.WORKSPACE */]: [0 /* States.BEFORE_PATH */],
  304. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  305. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  306. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  307. };
  308. pathStateMachine[1 /* States.IN_PATH */] = {
  309. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */],
  310. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */],
  311. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */],
  312. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */]
  313. };
  314. pathStateMachine[2 /* States.BEFORE_IDENT */] = {
  315. ["w" /* PathCharTypes.WORKSPACE */]: [2 /* States.BEFORE_IDENT */],
  316. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  317. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */]
  318. };
  319. pathStateMachine[3 /* States.IN_IDENT */] = {
  320. ["i" /* PathCharTypes.IDENT */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  321. ["0" /* PathCharTypes.ZERO */]: [3 /* States.IN_IDENT */, 0 /* Actions.APPEND */],
  322. ["w" /* PathCharTypes.WORKSPACE */]: [1 /* States.IN_PATH */, 1 /* Actions.PUSH */],
  323. ["." /* PathCharTypes.DOT */]: [2 /* States.BEFORE_IDENT */, 1 /* Actions.PUSH */],
  324. ["[" /* PathCharTypes.LEFT_BRACKET */]: [4 /* States.IN_SUB_PATH */, 1 /* Actions.PUSH */],
  325. ["o" /* PathCharTypes.END_OF_FAIL */]: [7 /* States.AFTER_PATH */, 1 /* Actions.PUSH */]
  326. };
  327. pathStateMachine[4 /* States.IN_SUB_PATH */] = {
  328. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */],
  329. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */],
  330. ["[" /* PathCharTypes.LEFT_BRACKET */]: [
  331. 4 /* States.IN_SUB_PATH */,
  332. 2 /* Actions.INC_SUB_PATH_DEPTH */
  333. ],
  334. ["]" /* PathCharTypes.RIGHT_BRACKET */]: [1 /* States.IN_PATH */, 3 /* Actions.PUSH_SUB_PATH */],
  335. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  336. ["l" /* PathCharTypes.ELSE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */]
  337. };
  338. pathStateMachine[5 /* States.IN_SINGLE_QUOTE */] = {
  339. ["'" /* PathCharTypes.SINGLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  340. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  341. ["l" /* PathCharTypes.ELSE */]: [5 /* States.IN_SINGLE_QUOTE */, 0 /* Actions.APPEND */]
  342. };
  343. pathStateMachine[6 /* States.IN_DOUBLE_QUOTE */] = {
  344. ["\"" /* PathCharTypes.DOUBLE_QUOTE */]: [4 /* States.IN_SUB_PATH */, 0 /* Actions.APPEND */],
  345. ["o" /* PathCharTypes.END_OF_FAIL */]: 8 /* States.ERROR */,
  346. ["l" /* PathCharTypes.ELSE */]: [6 /* States.IN_DOUBLE_QUOTE */, 0 /* Actions.APPEND */]
  347. };
  348. /**
  349. * Check if an expression is a literal value.
  350. */
  351. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  352. function isLiteral(exp) {
  353. return literalValueRE.test(exp);
  354. }
  355. /**
  356. * Strip quotes from a string
  357. */
  358. function stripQuotes(str) {
  359. const a = str.charCodeAt(0);
  360. const b = str.charCodeAt(str.length - 1);
  361. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  362. }
  363. /**
  364. * Determine the type of a character in a keypath.
  365. */
  366. function getPathCharType(ch) {
  367. if (ch === undefined || ch === null) {
  368. return "o" /* PathCharTypes.END_OF_FAIL */;
  369. }
  370. const code = ch.charCodeAt(0);
  371. switch (code) {
  372. case 0x5b: // [
  373. case 0x5d: // ]
  374. case 0x2e: // .
  375. case 0x22: // "
  376. case 0x27: // '
  377. return ch;
  378. case 0x5f: // _
  379. case 0x24: // $
  380. case 0x2d: // -
  381. return "i" /* PathCharTypes.IDENT */;
  382. case 0x09: // Tab (HT)
  383. case 0x0a: // Newline (LF)
  384. case 0x0d: // Return (CR)
  385. case 0xa0: // No-break space (NBSP)
  386. case 0xfeff: // Byte Order Mark (BOM)
  387. case 0x2028: // Line Separator (LS)
  388. case 0x2029: // Paragraph Separator (PS)
  389. return "w" /* PathCharTypes.WORKSPACE */;
  390. }
  391. return "i" /* PathCharTypes.IDENT */;
  392. }
  393. /**
  394. * Format a subPath, return its plain form if it is
  395. * a literal string or number. Otherwise prepend the
  396. * dynamic indicator (*).
  397. */
  398. function formatSubPath(path) {
  399. const trimmed = path.trim();
  400. // invalid leading 0
  401. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  402. return false;
  403. }
  404. return isLiteral(trimmed)
  405. ? stripQuotes(trimmed)
  406. : "*" /* PathCharTypes.ASTARISK */ + trimmed;
  407. }
  408. /**
  409. * Parse a string path into an array of segments
  410. */
  411. function parse(path) {
  412. const keys = [];
  413. let index = -1;
  414. let mode = 0 /* States.BEFORE_PATH */;
  415. let subPathDepth = 0;
  416. let c;
  417. let key; // eslint-disable-line
  418. let newChar;
  419. let type;
  420. let transition;
  421. let action;
  422. let typeMap;
  423. const actions = [];
  424. actions[0 /* Actions.APPEND */] = () => {
  425. if (key === undefined) {
  426. key = newChar;
  427. }
  428. else {
  429. key += newChar;
  430. }
  431. };
  432. actions[1 /* Actions.PUSH */] = () => {
  433. if (key !== undefined) {
  434. keys.push(key);
  435. key = undefined;
  436. }
  437. };
  438. actions[2 /* Actions.INC_SUB_PATH_DEPTH */] = () => {
  439. actions[0 /* Actions.APPEND */]();
  440. subPathDepth++;
  441. };
  442. actions[3 /* Actions.PUSH_SUB_PATH */] = () => {
  443. if (subPathDepth > 0) {
  444. subPathDepth--;
  445. mode = 4 /* States.IN_SUB_PATH */;
  446. actions[0 /* Actions.APPEND */]();
  447. }
  448. else {
  449. subPathDepth = 0;
  450. if (key === undefined) {
  451. return false;
  452. }
  453. key = formatSubPath(key);
  454. if (key === false) {
  455. return false;
  456. }
  457. else {
  458. actions[1 /* Actions.PUSH */]();
  459. }
  460. }
  461. };
  462. function maybeUnescapeQuote() {
  463. const nextChar = path[index + 1];
  464. if ((mode === 5 /* States.IN_SINGLE_QUOTE */ &&
  465. nextChar === "'" /* PathCharTypes.SINGLE_QUOTE */) ||
  466. (mode === 6 /* States.IN_DOUBLE_QUOTE */ &&
  467. nextChar === "\"" /* PathCharTypes.DOUBLE_QUOTE */)) {
  468. index++;
  469. newChar = '\\' + nextChar;
  470. actions[0 /* Actions.APPEND */]();
  471. return true;
  472. }
  473. }
  474. while (mode !== null) {
  475. index++;
  476. c = path[index];
  477. if (c === '\\' && maybeUnescapeQuote()) {
  478. continue;
  479. }
  480. type = getPathCharType(c);
  481. typeMap = pathStateMachine[mode];
  482. transition = typeMap[type] || typeMap["l" /* PathCharTypes.ELSE */] || 8 /* States.ERROR */;
  483. // check parse error
  484. if (transition === 8 /* States.ERROR */) {
  485. return;
  486. }
  487. mode = transition[0];
  488. if (transition[1] !== undefined) {
  489. action = actions[transition[1]];
  490. if (action) {
  491. newChar = c;
  492. if (action() === false) {
  493. return;
  494. }
  495. }
  496. }
  497. // check parse finish
  498. if (mode === 7 /* States.AFTER_PATH */) {
  499. return keys;
  500. }
  501. }
  502. }
  503. // path token cache
  504. const cache = new Map();
  505. /**
  506. * key-value message resolver
  507. *
  508. * @remarks
  509. * Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
  510. *
  511. * @param obj - A target object to be resolved with path
  512. * @param path - A {@link Path | path} to resolve the value of message
  513. *
  514. * @returns A resolved {@link PathValue | path value}
  515. *
  516. * @VueI18nGeneral
  517. */
  518. function resolveWithKeyValue(obj, path) {
  519. return isObject(obj) ? obj[path] : null;
  520. }
  521. /**
  522. * message resolver
  523. *
  524. * @remarks
  525. * Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
  526. *
  527. * @param obj - A target object to be resolved with path
  528. * @param path - A {@link Path | path} to resolve the value of message
  529. *
  530. * @returns A resolved {@link PathValue | path value}
  531. *
  532. * @VueI18nGeneral
  533. */
  534. function resolveValue(obj, path) {
  535. // check object
  536. if (!isObject(obj)) {
  537. return null;
  538. }
  539. // parse path
  540. let hit = cache.get(path);
  541. if (!hit) {
  542. hit = parse(path);
  543. if (hit) {
  544. cache.set(path, hit);
  545. }
  546. }
  547. // check hit
  548. if (!hit) {
  549. return null;
  550. }
  551. // resolve path value
  552. const len = hit.length;
  553. let last = obj;
  554. let i = 0;
  555. while (i < len) {
  556. const val = last[hit[i]];
  557. if (val === undefined) {
  558. return null;
  559. }
  560. if (isFunction(last)) {
  561. return null;
  562. }
  563. last = val;
  564. i++;
  565. }
  566. return last;
  567. }
  568. const DEFAULT_MODIFIER = (str) => str;
  569. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  570. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  571. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : join(values);
  572. const DEFAULT_INTERPOLATE = toDisplayString;
  573. function pluralDefault(choice, choicesLength) {
  574. choice = Math.abs(choice);
  575. if (choicesLength === 2) {
  576. // prettier-ignore
  577. return choice
  578. ? choice > 1
  579. ? 1
  580. : 0
  581. : 1;
  582. }
  583. return choice ? Math.min(choice, 2) : 0;
  584. }
  585. function getPluralIndex(options) {
  586. // prettier-ignore
  587. const index = isNumber(options.pluralIndex)
  588. ? options.pluralIndex
  589. : -1;
  590. // prettier-ignore
  591. return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
  592. ? isNumber(options.named.count)
  593. ? options.named.count
  594. : isNumber(options.named.n)
  595. ? options.named.n
  596. : index
  597. : index;
  598. }
  599. function normalizeNamed(pluralIndex, props) {
  600. if (!props.count) {
  601. props.count = pluralIndex;
  602. }
  603. if (!props.n) {
  604. props.n = pluralIndex;
  605. }
  606. }
  607. function createMessageContext(options = {}) {
  608. const locale = options.locale;
  609. const pluralIndex = getPluralIndex(options);
  610. const pluralRule = isObject(options.pluralRules) &&
  611. isString(locale) &&
  612. isFunction(options.pluralRules[locale])
  613. ? options.pluralRules[locale]
  614. : pluralDefault;
  615. const orgPluralRule = isObject(options.pluralRules) &&
  616. isString(locale) &&
  617. isFunction(options.pluralRules[locale])
  618. ? pluralDefault
  619. : undefined;
  620. const plural = (messages) => {
  621. return messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  622. };
  623. const _list = options.list || [];
  624. const list = (index) => _list[index];
  625. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  626. const _named = options.named || {};
  627. isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  628. const named = (key) => _named[key];
  629. function message(key) {
  630. // prettier-ignore
  631. const msg = isFunction(options.messages)
  632. ? options.messages(key)
  633. : isObject(options.messages)
  634. ? options.messages[key]
  635. : false;
  636. return !msg
  637. ? options.parent
  638. ? options.parent.message(key) // resolve from parent messages
  639. : DEFAULT_MESSAGE
  640. : msg;
  641. }
  642. const _modifier = (name) => options.modifiers
  643. ? options.modifiers[name]
  644. : DEFAULT_MODIFIER;
  645. const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
  646. ? options.processor.normalize
  647. : DEFAULT_NORMALIZE;
  648. const interpolate = isPlainObject(options.processor) &&
  649. isFunction(options.processor.interpolate)
  650. ? options.processor.interpolate
  651. : DEFAULT_INTERPOLATE;
  652. const type = isPlainObject(options.processor) && isString(options.processor.type)
  653. ? options.processor.type
  654. : DEFAULT_MESSAGE_DATA_TYPE;
  655. const linked = (key, ...args) => {
  656. const [arg1, arg2] = args;
  657. let type = 'text';
  658. let modifier = '';
  659. if (args.length === 1) {
  660. if (isObject(arg1)) {
  661. modifier = arg1.modifier || modifier;
  662. type = arg1.type || type;
  663. }
  664. else if (isString(arg1)) {
  665. modifier = arg1 || modifier;
  666. }
  667. }
  668. else if (args.length === 2) {
  669. if (isString(arg1)) {
  670. modifier = arg1 || modifier;
  671. }
  672. if (isString(arg2)) {
  673. type = arg2 || type;
  674. }
  675. }
  676. const ret = message(key)(ctx);
  677. const msg =
  678. // The message in vnode resolved with linked are returned as an array by processor.nomalize
  679. type === 'vnode' && isArray(ret) && modifier
  680. ? ret[0]
  681. : ret;
  682. return modifier ? _modifier(modifier)(msg, type) : msg;
  683. };
  684. const ctx = {
  685. ["list" /* HelperNameMap.LIST */]: list,
  686. ["named" /* HelperNameMap.NAMED */]: named,
  687. ["plural" /* HelperNameMap.PLURAL */]: plural,
  688. ["linked" /* HelperNameMap.LINKED */]: linked,
  689. ["message" /* HelperNameMap.MESSAGE */]: message,
  690. ["type" /* HelperNameMap.TYPE */]: type,
  691. ["interpolate" /* HelperNameMap.INTERPOLATE */]: interpolate,
  692. ["normalize" /* HelperNameMap.NORMALIZE */]: normalize,
  693. ["values" /* HelperNameMap.VALUES */]: assign({}, _list, _named)
  694. };
  695. return ctx;
  696. }
  697. let devtools = null;
  698. function setDevToolsHook(hook) {
  699. devtools = hook;
  700. }
  701. function initI18nDevTools(i18n, version, meta) {
  702. // TODO: queue if devtools is undefined
  703. devtools &&
  704. devtools.emit("i18n:init" /* IntlifyDevToolsHooks.I18nInit */, {
  705. timestamp: Date.now(),
  706. i18n,
  707. version,
  708. meta
  709. });
  710. }
  711. const translateDevTools = /* #__PURE__*/ createDevToolsHook("function:translate" /* IntlifyDevToolsHooks.FunctionTranslate */);
  712. function createDevToolsHook(hook) {
  713. return (payloads) => devtools && devtools.emit(hook, payloads);
  714. }
  715. const code$3 = CompileWarnCodes.__EXTEND_POINT__;
  716. const inc$3 = incrementer(code$3);
  717. const CoreWarnCodes = {
  718. NOT_FOUND_KEY: code$3, // 2
  719. FALLBACK_TO_TRANSLATE: inc$3(), // 3
  720. CANNOT_FORMAT_NUMBER: inc$3(), // 4
  721. FALLBACK_TO_NUMBER_FORMAT: inc$3(), // 5
  722. CANNOT_FORMAT_DATE: inc$3(), // 6
  723. FALLBACK_TO_DATE_FORMAT: inc$3(), // 7
  724. EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER: inc$3(), // 8
  725. __EXTEND_POINT__: inc$3() // 9
  726. };
  727. /** @internal */
  728. const warnMessages$1 = {
  729. [CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
  730. [CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
  731. [CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  732. [CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
  733. [CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  734. [CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`,
  735. [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.`
  736. };
  737. function getWarnMessage$1(code, ...args) {
  738. return format(warnMessages$1[code], ...args);
  739. }
  740. const code$2 = CompileErrorCodes.__EXTEND_POINT__;
  741. const inc$2 = incrementer(code$2);
  742. const CoreErrorCodes = {
  743. INVALID_ARGUMENT: code$2, // 17
  744. INVALID_DATE_ARGUMENT: inc$2(), // 18
  745. INVALID_ISO_DATE_ARGUMENT: inc$2(), // 19
  746. NOT_SUPPORT_NON_STRING_MESSAGE: inc$2(), // 20
  747. NOT_SUPPORT_LOCALE_PROMISE_VALUE: inc$2(), // 21
  748. NOT_SUPPORT_LOCALE_ASYNC_FUNCTION: inc$2(), // 22
  749. NOT_SUPPORT_LOCALE_TYPE: inc$2(), // 23
  750. __EXTEND_POINT__: inc$2() // 24
  751. };
  752. function createCoreError(code) {
  753. return createCompileError(code, null, { messages: errorMessages$1 } );
  754. }
  755. /** @internal */
  756. const errorMessages$1 = {
  757. [CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
  758. [CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
  759. 'Make sure your Date represents a valid date.',
  760. [CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string',
  761. [CoreErrorCodes.NOT_SUPPORT_NON_STRING_MESSAGE]: 'Not support non-string message',
  762. [CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE]: 'cannot support promise value',
  763. [CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION]: 'cannot support async function',
  764. [CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE]: 'cannot support locale type'
  765. };
  766. /** @internal */
  767. function getLocale(context, options) {
  768. return options.locale != null
  769. ? resolveLocale(options.locale)
  770. : resolveLocale(context.locale);
  771. }
  772. let _resolveLocale;
  773. /** @internal */
  774. function resolveLocale(locale) {
  775. if (isString(locale)) {
  776. return locale;
  777. }
  778. else {
  779. if (isFunction(locale)) {
  780. if (locale.resolvedOnce && _resolveLocale != null) {
  781. return _resolveLocale;
  782. }
  783. else if (locale.constructor.name === 'Function') {
  784. const resolve = locale();
  785. if (isPromise(resolve)) {
  786. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_PROMISE_VALUE);
  787. }
  788. return (_resolveLocale = resolve);
  789. }
  790. else {
  791. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_ASYNC_FUNCTION);
  792. }
  793. }
  794. else {
  795. throw createCoreError(CoreErrorCodes.NOT_SUPPORT_LOCALE_TYPE);
  796. }
  797. }
  798. }
  799. /**
  800. * Fallback with simple implemenation
  801. *
  802. * @remarks
  803. * A fallback locale function implemented with a simple fallback algorithm.
  804. *
  805. * Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
  806. *
  807. * @param ctx - A {@link CoreContext | context}
  808. * @param fallback - A {@link FallbackLocale | fallback locale}
  809. * @param start - A starting {@link Locale | locale}
  810. *
  811. * @returns Fallback locales
  812. *
  813. * @VueI18nGeneral
  814. */
  815. function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
  816. ) {
  817. // prettier-ignore
  818. return [...new Set([
  819. start,
  820. ...(isArray(fallback)
  821. ? fallback
  822. : isObject(fallback)
  823. ? Object.keys(fallback)
  824. : isString(fallback)
  825. ? [fallback]
  826. : [start])
  827. ])];
  828. }
  829. /**
  830. * Fallback with locale chain
  831. *
  832. * @remarks
  833. * A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
  834. *
  835. * @param ctx - A {@link CoreContext | context}
  836. * @param fallback - A {@link FallbackLocale | fallback locale}
  837. * @param start - A starting {@link Locale | locale}
  838. *
  839. * @returns Fallback locales
  840. *
  841. * @VueI18nSee [Fallbacking](../guide/essentials/fallback)
  842. *
  843. * @VueI18nGeneral
  844. */
  845. function fallbackWithLocaleChain(ctx, fallback, start) {
  846. const startLocale = isString(start) ? start : DEFAULT_LOCALE;
  847. const context = ctx;
  848. if (!context.__localeChainCache) {
  849. context.__localeChainCache = new Map();
  850. }
  851. let chain = context.__localeChainCache.get(startLocale);
  852. if (!chain) {
  853. chain = [];
  854. // first block defined by start
  855. let block = [start];
  856. // while any intervening block found
  857. while (isArray(block)) {
  858. block = appendBlockToChain(chain, block, fallback);
  859. }
  860. // prettier-ignore
  861. // last block defined by default
  862. const defaults = isArray(fallback) || !isPlainObject(fallback)
  863. ? fallback
  864. : fallback['default']
  865. ? fallback['default']
  866. : null;
  867. // convert defaults to array
  868. block = isString(defaults) ? [defaults] : defaults;
  869. if (isArray(block)) {
  870. appendBlockToChain(chain, block, false);
  871. }
  872. context.__localeChainCache.set(startLocale, chain);
  873. }
  874. return chain;
  875. }
  876. function appendBlockToChain(chain, block, blocks) {
  877. let follow = true;
  878. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  879. const locale = block[i];
  880. if (isString(locale)) {
  881. follow = appendLocaleToChain(chain, block[i], blocks);
  882. }
  883. }
  884. return follow;
  885. }
  886. function appendLocaleToChain(chain, locale, blocks) {
  887. let follow;
  888. const tokens = locale.split('-');
  889. do {
  890. const target = tokens.join('-');
  891. follow = appendItemToChain(chain, target, blocks);
  892. tokens.splice(-1, 1);
  893. } while (tokens.length && follow === true);
  894. return follow;
  895. }
  896. function appendItemToChain(chain, target, blocks) {
  897. let follow = false;
  898. if (!chain.includes(target)) {
  899. follow = true;
  900. if (target) {
  901. follow = target[target.length - 1] !== '!';
  902. const locale = target.replace(/!/g, '');
  903. chain.push(locale);
  904. if ((isArray(blocks) || isPlainObject(blocks)) &&
  905. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  906. ) {
  907. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  908. follow = blocks[locale];
  909. }
  910. }
  911. }
  912. return follow;
  913. }
  914. /* eslint-disable @typescript-eslint/no-explicit-any */
  915. /**
  916. * Intlify core-base version
  917. * @internal
  918. */
  919. const VERSION$1 = '9.13.1';
  920. const NOT_REOSLVED = -1;
  921. const DEFAULT_LOCALE = 'en-US';
  922. const MISSING_RESOLVE_VALUE = '';
  923. const capitalize = (str) => `${str.charAt(0).toLocaleUpperCase()}${str.substr(1)}`;
  924. function getDefaultLinkedModifiers() {
  925. return {
  926. upper: (val, type) => {
  927. // prettier-ignore
  928. return type === 'text' && isString(val)
  929. ? val.toUpperCase()
  930. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  931. ? val.children.toUpperCase()
  932. : val;
  933. },
  934. lower: (val, type) => {
  935. // prettier-ignore
  936. return type === 'text' && isString(val)
  937. ? val.toLowerCase()
  938. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  939. ? val.children.toLowerCase()
  940. : val;
  941. },
  942. capitalize: (val, type) => {
  943. // prettier-ignore
  944. return (type === 'text' && isString(val)
  945. ? capitalize(val)
  946. : type === 'vnode' && isObject(val) && '__v_isVNode' in val
  947. ? capitalize(val.children)
  948. : val);
  949. }
  950. };
  951. }
  952. let _compiler;
  953. let _resolver;
  954. /**
  955. * Register the message resolver
  956. *
  957. * @param resolver - A {@link MessageResolver} function
  958. *
  959. * @VueI18nGeneral
  960. */
  961. function registerMessageResolver(resolver) {
  962. _resolver = resolver;
  963. }
  964. let _fallbacker;
  965. /**
  966. * Register the locale fallbacker
  967. *
  968. * @param fallbacker - A {@link LocaleFallbacker} function
  969. *
  970. * @VueI18nGeneral
  971. */
  972. function registerLocaleFallbacker(fallbacker) {
  973. _fallbacker = fallbacker;
  974. }
  975. // Additional Meta for Intlify DevTools
  976. let _additionalMeta = null;
  977. /* #__NO_SIDE_EFFECTS__ */
  978. const setAdditionalMeta = (meta) => {
  979. _additionalMeta = meta;
  980. };
  981. /* #__NO_SIDE_EFFECTS__ */
  982. const getAdditionalMeta = () => _additionalMeta;
  983. let _fallbackContext = null;
  984. const setFallbackContext = (context) => {
  985. _fallbackContext = context;
  986. };
  987. const getFallbackContext = () => _fallbackContext;
  988. // ID for CoreContext
  989. let _cid = 0;
  990. function createCoreContext(options = {}) {
  991. // setup options
  992. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  993. const version = isString(options.version) ? options.version : VERSION$1;
  994. const locale = isString(options.locale) || isFunction(options.locale)
  995. ? options.locale
  996. : DEFAULT_LOCALE;
  997. const _locale = isFunction(locale) ? DEFAULT_LOCALE : locale;
  998. const fallbackLocale = isArray(options.fallbackLocale) ||
  999. isPlainObject(options.fallbackLocale) ||
  1000. isString(options.fallbackLocale) ||
  1001. options.fallbackLocale === false
  1002. ? options.fallbackLocale
  1003. : _locale;
  1004. const messages = isPlainObject(options.messages)
  1005. ? options.messages
  1006. : { [_locale]: {} };
  1007. const datetimeFormats = isPlainObject(options.datetimeFormats)
  1008. ? options.datetimeFormats
  1009. : { [_locale]: {} }
  1010. ;
  1011. const numberFormats = isPlainObject(options.numberFormats)
  1012. ? options.numberFormats
  1013. : { [_locale]: {} }
  1014. ;
  1015. const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
  1016. const pluralRules = options.pluralRules || {};
  1017. const missing = isFunction(options.missing) ? options.missing : null;
  1018. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  1019. ? options.missingWarn
  1020. : true;
  1021. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  1022. ? options.fallbackWarn
  1023. : true;
  1024. const fallbackFormat = !!options.fallbackFormat;
  1025. const unresolving = !!options.unresolving;
  1026. const postTranslation = isFunction(options.postTranslation)
  1027. ? options.postTranslation
  1028. : null;
  1029. const processor = isPlainObject(options.processor) ? options.processor : null;
  1030. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  1031. ? options.warnHtmlMessage
  1032. : true;
  1033. const escapeParameter = !!options.escapeParameter;
  1034. const messageCompiler = isFunction(options.messageCompiler)
  1035. ? options.messageCompiler
  1036. : _compiler;
  1037. if (isFunction(options.messageCompiler)) {
  1038. warnOnce(getWarnMessage$1(CoreWarnCodes.EXPERIMENTAL_CUSTOM_MESSAGE_COMPILER));
  1039. }
  1040. const messageResolver = isFunction(options.messageResolver)
  1041. ? options.messageResolver
  1042. : _resolver || resolveWithKeyValue;
  1043. const localeFallbacker = isFunction(options.localeFallbacker)
  1044. ? options.localeFallbacker
  1045. : _fallbacker || fallbackWithSimple;
  1046. const fallbackContext = isObject(options.fallbackContext)
  1047. ? options.fallbackContext
  1048. : undefined;
  1049. // setup internal options
  1050. const internalOptions = options;
  1051. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  1052. ? internalOptions.__datetimeFormatters
  1053. : new Map()
  1054. ;
  1055. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  1056. ? internalOptions.__numberFormatters
  1057. : new Map()
  1058. ;
  1059. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  1060. _cid++;
  1061. const context = {
  1062. version,
  1063. cid: _cid,
  1064. locale,
  1065. fallbackLocale,
  1066. messages,
  1067. modifiers,
  1068. pluralRules,
  1069. missing,
  1070. missingWarn,
  1071. fallbackWarn,
  1072. fallbackFormat,
  1073. unresolving,
  1074. postTranslation,
  1075. processor,
  1076. warnHtmlMessage,
  1077. escapeParameter,
  1078. messageCompiler,
  1079. messageResolver,
  1080. localeFallbacker,
  1081. fallbackContext,
  1082. onWarn,
  1083. __meta
  1084. };
  1085. {
  1086. context.datetimeFormats = datetimeFormats;
  1087. context.numberFormats = numberFormats;
  1088. context.__datetimeFormatters = __datetimeFormatters;
  1089. context.__numberFormatters = __numberFormatters;
  1090. }
  1091. // for vue-devtools timeline event
  1092. {
  1093. context.__v_emitter =
  1094. internalOptions.__v_emitter != null
  1095. ? internalOptions.__v_emitter
  1096. : undefined;
  1097. }
  1098. // NOTE: experimental !!
  1099. {
  1100. initI18nDevTools(context, version, __meta);
  1101. }
  1102. return context;
  1103. }
  1104. /** @internal */
  1105. function isTranslateFallbackWarn(fallback, key) {
  1106. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  1107. }
  1108. /** @internal */
  1109. function isTranslateMissingWarn(missing, key) {
  1110. return missing instanceof RegExp ? missing.test(key) : missing;
  1111. }
  1112. /** @internal */
  1113. function handleMissing(context, key, locale, missingWarn, type) {
  1114. const { missing, onWarn } = context;
  1115. // for vue-devtools timeline event
  1116. {
  1117. const emitter = context.__v_emitter;
  1118. if (emitter) {
  1119. emitter.emit("missing" /* VueDevToolsTimelineEvents.MISSING */, {
  1120. locale,
  1121. key,
  1122. type,
  1123. groupId: `${type}:${key}`
  1124. });
  1125. }
  1126. }
  1127. if (missing !== null) {
  1128. const ret = missing(context, locale, key, type);
  1129. return isString(ret) ? ret : key;
  1130. }
  1131. else {
  1132. if (isTranslateMissingWarn(missingWarn, key)) {
  1133. onWarn(getWarnMessage$1(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
  1134. }
  1135. return key;
  1136. }
  1137. }
  1138. /** @internal */
  1139. function updateFallbackLocale(ctx, locale, fallback) {
  1140. const context = ctx;
  1141. context.__localeChainCache = new Map();
  1142. ctx.localeFallbacker(ctx, fallback, locale);
  1143. }
  1144. /** @internal */
  1145. function isAlmostSameLocale(locale, compareLocale) {
  1146. if (locale === compareLocale)
  1147. return false;
  1148. return locale.split('-')[0] === compareLocale.split('-')[0];
  1149. }
  1150. /** @internal */
  1151. function isImplicitFallback(targetLocale, locales) {
  1152. const index = locales.indexOf(targetLocale);
  1153. if (index === -1) {
  1154. return false;
  1155. }
  1156. for (let i = index + 1; i < locales.length; i++) {
  1157. if (isAlmostSameLocale(targetLocale, locales[i])) {
  1158. return true;
  1159. }
  1160. }
  1161. return false;
  1162. }
  1163. /* eslint-enable @typescript-eslint/no-explicit-any */
  1164. const isMessageAST = (val) => isObject(val) &&
  1165. (val.t === 0 || val.type === 0) &&
  1166. ('b' in val || 'body' in val);
  1167. const NOOP_MESSAGE_FUNCTION = () => '';
  1168. const isMessageFunction = (val) => isFunction(val);
  1169. // implementation of `translate` function
  1170. function translate(context, ...args) {
  1171. const { fallbackFormat, postTranslation, unresolving, messageCompiler, fallbackLocale, messages } = context;
  1172. const [key, options] = parseTranslateArgs(...args);
  1173. const missingWarn = isBoolean(options.missingWarn)
  1174. ? options.missingWarn
  1175. : context.missingWarn;
  1176. const fallbackWarn = isBoolean(options.fallbackWarn)
  1177. ? options.fallbackWarn
  1178. : context.fallbackWarn;
  1179. const escapeParameter = isBoolean(options.escapeParameter)
  1180. ? options.escapeParameter
  1181. : context.escapeParameter;
  1182. const resolvedMessage = !!options.resolvedMessage;
  1183. // prettier-ignore
  1184. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  1185. ? !isBoolean(options.default)
  1186. ? options.default
  1187. : (!messageCompiler ? () => key : key)
  1188. : fallbackFormat // default by `fallbackFormat` option
  1189. ? (!messageCompiler ? () => key : key)
  1190. : '';
  1191. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  1192. const locale = getLocale(context, options);
  1193. // escape params
  1194. escapeParameter && escapeParams(options);
  1195. // resolve message format
  1196. // eslint-disable-next-line prefer-const
  1197. let [formatScope, targetLocale, message] = !resolvedMessage
  1198. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  1199. : [
  1200. key,
  1201. locale,
  1202. messages[locale] || {}
  1203. ];
  1204. // NOTE:
  1205. // Fix to work around `ssrTransfrom` bug in Vite.
  1206. // https://github.com/vitejs/vite/issues/4306
  1207. // To get around this, use temporary variables.
  1208. // https://github.com/nuxt/framework/issues/1461#issuecomment-954606243
  1209. let format = formatScope;
  1210. // if you use default message, set it as message format!
  1211. let cacheBaseKey = key;
  1212. if (!resolvedMessage &&
  1213. !(isString(format) ||
  1214. isMessageAST(format) ||
  1215. isMessageFunction(format))) {
  1216. if (enableDefaultMsg) {
  1217. format = defaultMsgOrKey;
  1218. cacheBaseKey = format;
  1219. }
  1220. }
  1221. // checking message format and target locale
  1222. if (!resolvedMessage &&
  1223. (!(isString(format) ||
  1224. isMessageAST(format) ||
  1225. isMessageFunction(format)) ||
  1226. !isString(targetLocale))) {
  1227. return unresolving ? NOT_REOSLVED : key;
  1228. }
  1229. // TODO: refactor
  1230. if (isString(format) && context.messageCompiler == null) {
  1231. warn(`The message format compilation is not supported in this build. ` +
  1232. `Because message compiler isn't included. ` +
  1233. `You need to pre-compilation all message format. ` +
  1234. `So translate function return '${key}'.`);
  1235. return key;
  1236. }
  1237. // setup compile error detecting
  1238. let occurred = false;
  1239. const onError = () => {
  1240. occurred = true;
  1241. };
  1242. // compile message format
  1243. const msg = !isMessageFunction(format)
  1244. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError)
  1245. : format;
  1246. // if occurred compile error, return the message format
  1247. if (occurred) {
  1248. return format;
  1249. }
  1250. // evaluate message with context
  1251. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  1252. const msgContext = createMessageContext(ctxOptions);
  1253. const messaged = evaluateMessage(context, msg, msgContext);
  1254. // if use post translation option, proceed it with handler
  1255. const ret = postTranslation
  1256. ? postTranslation(messaged, key)
  1257. : messaged;
  1258. // NOTE: experimental !!
  1259. {
  1260. // prettier-ignore
  1261. const payloads = {
  1262. timestamp: Date.now(),
  1263. key: isString(key)
  1264. ? key
  1265. : isMessageFunction(format)
  1266. ? format.key
  1267. : '',
  1268. locale: targetLocale || (isMessageFunction(format)
  1269. ? format.locale
  1270. : ''),
  1271. format: isString(format)
  1272. ? format
  1273. : isMessageFunction(format)
  1274. ? format.source
  1275. : '',
  1276. message: ret
  1277. };
  1278. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  1279. translateDevTools(payloads);
  1280. }
  1281. return ret;
  1282. }
  1283. function escapeParams(options) {
  1284. if (isArray(options.list)) {
  1285. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  1286. }
  1287. else if (isObject(options.named)) {
  1288. Object.keys(options.named).forEach(key => {
  1289. if (isString(options.named[key])) {
  1290. options.named[key] = escapeHtml(options.named[key]);
  1291. }
  1292. });
  1293. }
  1294. }
  1295. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  1296. const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
  1297. const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
  1298. let message = {};
  1299. let targetLocale;
  1300. let format = null;
  1301. let from = locale;
  1302. let to = null;
  1303. const type = 'translate';
  1304. for (let i = 0; i < locales.length; i++) {
  1305. targetLocale = to = locales[i];
  1306. if (locale !== targetLocale &&
  1307. !isAlmostSameLocale(locale, targetLocale) &&
  1308. isTranslateFallbackWarn(fallbackWarn, key)) {
  1309. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
  1310. key,
  1311. target: targetLocale
  1312. }));
  1313. }
  1314. // for vue-devtools timeline event
  1315. if (locale !== targetLocale) {
  1316. const emitter = context.__v_emitter;
  1317. if (emitter) {
  1318. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1319. type,
  1320. key,
  1321. from,
  1322. to,
  1323. groupId: `${type}:${key}`
  1324. });
  1325. }
  1326. }
  1327. message =
  1328. messages[targetLocale] || {};
  1329. // for vue-devtools timeline event
  1330. let start = null;
  1331. let startTag;
  1332. let endTag;
  1333. if (inBrowser) {
  1334. start = window.performance.now();
  1335. startTag = 'intlify-message-resolve-start';
  1336. endTag = 'intlify-message-resolve-end';
  1337. mark && mark(startTag);
  1338. }
  1339. if ((format = resolveValue(message, key)) === null) {
  1340. // if null, resolve with object key path
  1341. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  1342. }
  1343. // for vue-devtools timeline event
  1344. if (inBrowser) {
  1345. const end = window.performance.now();
  1346. const emitter = context.__v_emitter;
  1347. if (emitter && start && format) {
  1348. emitter.emit("message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */, {
  1349. type: "message-resolve" /* VueDevToolsTimelineEvents.MESSAGE_RESOLVE */,
  1350. key,
  1351. message: format,
  1352. time: end - start,
  1353. groupId: `${type}:${key}`
  1354. });
  1355. }
  1356. if (startTag && endTag && mark && measure) {
  1357. mark(endTag);
  1358. measure('intlify message resolve', startTag, endTag);
  1359. }
  1360. }
  1361. if (isString(format) || isMessageAST(format) || isMessageFunction(format)) {
  1362. break;
  1363. }
  1364. if (!isImplicitFallback(targetLocale, locales)) {
  1365. const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1366. key, targetLocale, missingWarn, type);
  1367. if (missingRet !== key) {
  1368. format = missingRet;
  1369. }
  1370. }
  1371. from = to;
  1372. }
  1373. return [format, targetLocale, message];
  1374. }
  1375. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, onError) {
  1376. const { messageCompiler, warnHtmlMessage } = context;
  1377. if (isMessageFunction(format)) {
  1378. const msg = format;
  1379. msg.locale = msg.locale || targetLocale;
  1380. msg.key = msg.key || key;
  1381. return msg;
  1382. }
  1383. if (messageCompiler == null) {
  1384. const msg = (() => format);
  1385. msg.locale = targetLocale;
  1386. msg.key = key;
  1387. return msg;
  1388. }
  1389. // for vue-devtools timeline event
  1390. let start = null;
  1391. let startTag;
  1392. let endTag;
  1393. if (inBrowser) {
  1394. start = window.performance.now();
  1395. startTag = 'intlify-message-compilation-start';
  1396. endTag = 'intlify-message-compilation-end';
  1397. mark && mark(startTag);
  1398. }
  1399. const msg = messageCompiler(format, getCompileContext(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, onError));
  1400. // for vue-devtools timeline event
  1401. if (inBrowser) {
  1402. const end = window.performance.now();
  1403. const emitter = context.__v_emitter;
  1404. if (emitter && start) {
  1405. emitter.emit("message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */, {
  1406. type: "message-compilation" /* VueDevToolsTimelineEvents.MESSAGE_COMPILATION */,
  1407. message: format,
  1408. time: end - start,
  1409. groupId: `${'translate'}:${key}`
  1410. });
  1411. }
  1412. if (startTag && endTag && mark && measure) {
  1413. mark(endTag);
  1414. measure('intlify message compilation', startTag, endTag);
  1415. }
  1416. }
  1417. msg.locale = targetLocale;
  1418. msg.key = key;
  1419. msg.source = format;
  1420. return msg;
  1421. }
  1422. function evaluateMessage(context, msg, msgCtx) {
  1423. // for vue-devtools timeline event
  1424. let start = null;
  1425. let startTag;
  1426. let endTag;
  1427. if (inBrowser) {
  1428. start = window.performance.now();
  1429. startTag = 'intlify-message-evaluation-start';
  1430. endTag = 'intlify-message-evaluation-end';
  1431. mark && mark(startTag);
  1432. }
  1433. const messaged = msg(msgCtx);
  1434. // for vue-devtools timeline event
  1435. if (inBrowser) {
  1436. const end = window.performance.now();
  1437. const emitter = context.__v_emitter;
  1438. if (emitter && start) {
  1439. emitter.emit("message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */, {
  1440. type: "message-evaluation" /* VueDevToolsTimelineEvents.MESSAGE_EVALUATION */,
  1441. value: messaged,
  1442. time: end - start,
  1443. groupId: `${'translate'}:${msg.key}`
  1444. });
  1445. }
  1446. if (startTag && endTag && mark && measure) {
  1447. mark(endTag);
  1448. measure('intlify message evaluation', startTag, endTag);
  1449. }
  1450. }
  1451. return messaged;
  1452. }
  1453. /** @internal */
  1454. function parseTranslateArgs(...args) {
  1455. const [arg1, arg2, arg3] = args;
  1456. const options = {};
  1457. if (!isString(arg1) &&
  1458. !isNumber(arg1) &&
  1459. !isMessageFunction(arg1) &&
  1460. !isMessageAST(arg1)) {
  1461. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1462. }
  1463. // prettier-ignore
  1464. const key = isNumber(arg1)
  1465. ? String(arg1)
  1466. : isMessageFunction(arg1)
  1467. ? arg1
  1468. : arg1;
  1469. if (isNumber(arg2)) {
  1470. options.plural = arg2;
  1471. }
  1472. else if (isString(arg2)) {
  1473. options.default = arg2;
  1474. }
  1475. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  1476. options.named = arg2;
  1477. }
  1478. else if (isArray(arg2)) {
  1479. options.list = arg2;
  1480. }
  1481. if (isNumber(arg3)) {
  1482. options.plural = arg3;
  1483. }
  1484. else if (isString(arg3)) {
  1485. options.default = arg3;
  1486. }
  1487. else if (isPlainObject(arg3)) {
  1488. assign(options, arg3);
  1489. }
  1490. return [key, options];
  1491. }
  1492. function getCompileContext(context, locale, key, source, warnHtmlMessage, onError) {
  1493. return {
  1494. locale,
  1495. key,
  1496. warnHtmlMessage,
  1497. onError: (err) => {
  1498. onError && onError(err);
  1499. {
  1500. const _source = getSourceForCodeFrame(source);
  1501. const message = `Message compilation error: ${err.message}`;
  1502. const codeFrame = err.location &&
  1503. _source &&
  1504. generateCodeFrame(_source, err.location.start.offset, err.location.end.offset);
  1505. const emitter = context.__v_emitter;
  1506. if (emitter && _source) {
  1507. emitter.emit("compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */, {
  1508. message: _source,
  1509. error: err.message,
  1510. start: err.location && err.location.start.offset,
  1511. end: err.location && err.location.end.offset,
  1512. groupId: `${'translate'}:${key}`
  1513. });
  1514. }
  1515. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  1516. }
  1517. },
  1518. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  1519. };
  1520. }
  1521. function getSourceForCodeFrame(source) {
  1522. if (isString(source)) {
  1523. return source;
  1524. }
  1525. else {
  1526. if (source.loc && source.loc.source) {
  1527. return source.loc.source;
  1528. }
  1529. }
  1530. }
  1531. function getMessageContextOptions(context, locale, message, options) {
  1532. const { modifiers, pluralRules, messageResolver: resolveValue, fallbackLocale, fallbackWarn, missingWarn, fallbackContext } = context;
  1533. const resolveMessage = (key) => {
  1534. let val = resolveValue(message, key);
  1535. // fallback to root context
  1536. if (val == null && fallbackContext) {
  1537. const [, , message] = resolveMessageFormat(fallbackContext, key, locale, fallbackLocale, fallbackWarn, missingWarn);
  1538. val = resolveValue(message, key);
  1539. }
  1540. if (isString(val) || isMessageAST(val)) {
  1541. let occurred = false;
  1542. const onError = () => {
  1543. occurred = true;
  1544. };
  1545. const msg = compileMessageFormat(context, key, locale, val, key, onError);
  1546. return !occurred
  1547. ? msg
  1548. : NOOP_MESSAGE_FUNCTION;
  1549. }
  1550. else if (isMessageFunction(val)) {
  1551. return val;
  1552. }
  1553. else {
  1554. // TODO: should be implemented warning message
  1555. return NOOP_MESSAGE_FUNCTION;
  1556. }
  1557. };
  1558. const ctxOptions = {
  1559. locale,
  1560. modifiers,
  1561. pluralRules,
  1562. messages: resolveMessage
  1563. };
  1564. if (context.processor) {
  1565. ctxOptions.processor = context.processor;
  1566. }
  1567. if (options.list) {
  1568. ctxOptions.list = options.list;
  1569. }
  1570. if (options.named) {
  1571. ctxOptions.named = options.named;
  1572. }
  1573. if (isNumber(options.plural)) {
  1574. ctxOptions.pluralIndex = options.plural;
  1575. }
  1576. return ctxOptions;
  1577. }
  1578. const intlDefined = typeof Intl !== 'undefined';
  1579. const Availabilities = {
  1580. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  1581. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  1582. };
  1583. // implementation of `datetime` function
  1584. function datetime(context, ...args) {
  1585. const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  1586. const { __datetimeFormatters } = context;
  1587. if (!Availabilities.dateTimeFormat) {
  1588. onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_DATE));
  1589. return MISSING_RESOLVE_VALUE;
  1590. }
  1591. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  1592. const missingWarn = isBoolean(options.missingWarn)
  1593. ? options.missingWarn
  1594. : context.missingWarn;
  1595. const fallbackWarn = isBoolean(options.fallbackWarn)
  1596. ? options.fallbackWarn
  1597. : context.fallbackWarn;
  1598. const part = !!options.part;
  1599. const locale = getLocale(context, options);
  1600. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1601. fallbackLocale, locale);
  1602. if (!isString(key) || key === '') {
  1603. return new Intl.DateTimeFormat(locale, overrides).format(value);
  1604. }
  1605. // resolve format
  1606. let datetimeFormat = {};
  1607. let targetLocale;
  1608. let format = null;
  1609. let from = locale;
  1610. let to = null;
  1611. const type = 'datetime format';
  1612. for (let i = 0; i < locales.length; i++) {
  1613. targetLocale = to = locales[i];
  1614. if (locale !== targetLocale &&
  1615. isTranslateFallbackWarn(fallbackWarn, key)) {
  1616. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
  1617. key,
  1618. target: targetLocale
  1619. }));
  1620. }
  1621. // for vue-devtools timeline event
  1622. if (locale !== targetLocale) {
  1623. const emitter = context.__v_emitter;
  1624. if (emitter) {
  1625. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1626. type,
  1627. key,
  1628. from,
  1629. to,
  1630. groupId: `${type}:${key}`
  1631. });
  1632. }
  1633. }
  1634. datetimeFormat =
  1635. datetimeFormats[targetLocale] || {};
  1636. format = datetimeFormat[key];
  1637. if (isPlainObject(format))
  1638. break;
  1639. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  1640. from = to;
  1641. }
  1642. // checking format and target locale
  1643. if (!isPlainObject(format) || !isString(targetLocale)) {
  1644. return unresolving ? NOT_REOSLVED : key;
  1645. }
  1646. let id = `${targetLocale}__${key}`;
  1647. if (!isEmptyObject(overrides)) {
  1648. id = `${id}__${JSON.stringify(overrides)}`;
  1649. }
  1650. let formatter = __datetimeFormatters.get(id);
  1651. if (!formatter) {
  1652. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  1653. __datetimeFormatters.set(id, formatter);
  1654. }
  1655. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1656. }
  1657. /** @internal */
  1658. const DATETIME_FORMAT_OPTIONS_KEYS = [
  1659. 'localeMatcher',
  1660. 'weekday',
  1661. 'era',
  1662. 'year',
  1663. 'month',
  1664. 'day',
  1665. 'hour',
  1666. 'minute',
  1667. 'second',
  1668. 'timeZoneName',
  1669. 'formatMatcher',
  1670. 'hour12',
  1671. 'timeZone',
  1672. 'dateStyle',
  1673. 'timeStyle',
  1674. 'calendar',
  1675. 'dayPeriod',
  1676. 'numberingSystem',
  1677. 'hourCycle',
  1678. 'fractionalSecondDigits'
  1679. ];
  1680. /** @internal */
  1681. function parseDateTimeArgs(...args) {
  1682. const [arg1, arg2, arg3, arg4] = args;
  1683. const options = {};
  1684. let overrides = {};
  1685. let value;
  1686. if (isString(arg1)) {
  1687. // Only allow ISO strings - other date formats are often supported,
  1688. // but may cause different results in different browsers.
  1689. const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
  1690. if (!matches) {
  1691. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  1692. }
  1693. // Some browsers can not parse the iso datetime separated by space,
  1694. // this is a compromise solution by replace the 'T'/' ' with 'T'
  1695. const dateTime = matches[3]
  1696. ? matches[3].trim().startsWith('T')
  1697. ? `${matches[1].trim()}${matches[3].trim()}`
  1698. : `${matches[1].trim()}T${matches[3].trim()}`
  1699. : matches[1].trim();
  1700. value = new Date(dateTime);
  1701. try {
  1702. // This will fail if the date is not valid
  1703. value.toISOString();
  1704. }
  1705. catch (e) {
  1706. throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
  1707. }
  1708. }
  1709. else if (isDate(arg1)) {
  1710. if (isNaN(arg1.getTime())) {
  1711. throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
  1712. }
  1713. value = arg1;
  1714. }
  1715. else if (isNumber(arg1)) {
  1716. value = arg1;
  1717. }
  1718. else {
  1719. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1720. }
  1721. if (isString(arg2)) {
  1722. options.key = arg2;
  1723. }
  1724. else if (isPlainObject(arg2)) {
  1725. Object.keys(arg2).forEach(key => {
  1726. if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
  1727. overrides[key] = arg2[key];
  1728. }
  1729. else {
  1730. options[key] = arg2[key];
  1731. }
  1732. });
  1733. }
  1734. if (isString(arg3)) {
  1735. options.locale = arg3;
  1736. }
  1737. else if (isPlainObject(arg3)) {
  1738. overrides = arg3;
  1739. }
  1740. if (isPlainObject(arg4)) {
  1741. overrides = arg4;
  1742. }
  1743. return [options.key || '', value, options, overrides];
  1744. }
  1745. /** @internal */
  1746. function clearDateTimeFormat(ctx, locale, format) {
  1747. const context = ctx;
  1748. for (const key in format) {
  1749. const id = `${locale}__${key}`;
  1750. if (!context.__datetimeFormatters.has(id)) {
  1751. continue;
  1752. }
  1753. context.__datetimeFormatters.delete(id);
  1754. }
  1755. }
  1756. // implementation of `number` function
  1757. function number(context, ...args) {
  1758. const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
  1759. const { __numberFormatters } = context;
  1760. if (!Availabilities.numberFormat) {
  1761. onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
  1762. return MISSING_RESOLVE_VALUE;
  1763. }
  1764. const [key, value, options, overrides] = parseNumberArgs(...args);
  1765. const missingWarn = isBoolean(options.missingWarn)
  1766. ? options.missingWarn
  1767. : context.missingWarn;
  1768. const fallbackWarn = isBoolean(options.fallbackWarn)
  1769. ? options.fallbackWarn
  1770. : context.fallbackWarn;
  1771. const part = !!options.part;
  1772. const locale = getLocale(context, options);
  1773. const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
  1774. fallbackLocale, locale);
  1775. if (!isString(key) || key === '') {
  1776. return new Intl.NumberFormat(locale, overrides).format(value);
  1777. }
  1778. // resolve format
  1779. let numberFormat = {};
  1780. let targetLocale;
  1781. let format = null;
  1782. let from = locale;
  1783. let to = null;
  1784. const type = 'number format';
  1785. for (let i = 0; i < locales.length; i++) {
  1786. targetLocale = to = locales[i];
  1787. if (locale !== targetLocale &&
  1788. isTranslateFallbackWarn(fallbackWarn, key)) {
  1789. onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
  1790. key,
  1791. target: targetLocale
  1792. }));
  1793. }
  1794. // for vue-devtools timeline event
  1795. if (locale !== targetLocale) {
  1796. const emitter = context.__v_emitter;
  1797. if (emitter) {
  1798. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  1799. type,
  1800. key,
  1801. from,
  1802. to,
  1803. groupId: `${type}:${key}`
  1804. });
  1805. }
  1806. }
  1807. numberFormat =
  1808. numberFormats[targetLocale] || {};
  1809. format = numberFormat[key];
  1810. if (isPlainObject(format))
  1811. break;
  1812. handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
  1813. from = to;
  1814. }
  1815. // checking format and target locale
  1816. if (!isPlainObject(format) || !isString(targetLocale)) {
  1817. return unresolving ? NOT_REOSLVED : key;
  1818. }
  1819. let id = `${targetLocale}__${key}`;
  1820. if (!isEmptyObject(overrides)) {
  1821. id = `${id}__${JSON.stringify(overrides)}`;
  1822. }
  1823. let formatter = __numberFormatters.get(id);
  1824. if (!formatter) {
  1825. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  1826. __numberFormatters.set(id, formatter);
  1827. }
  1828. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1829. }
  1830. /** @internal */
  1831. const NUMBER_FORMAT_OPTIONS_KEYS = [
  1832. 'localeMatcher',
  1833. 'style',
  1834. 'currency',
  1835. 'currencyDisplay',
  1836. 'currencySign',
  1837. 'useGrouping',
  1838. 'minimumIntegerDigits',
  1839. 'minimumFractionDigits',
  1840. 'maximumFractionDigits',
  1841. 'minimumSignificantDigits',
  1842. 'maximumSignificantDigits',
  1843. 'compactDisplay',
  1844. 'notation',
  1845. 'signDisplay',
  1846. 'unit',
  1847. 'unitDisplay',
  1848. 'roundingMode',
  1849. 'roundingPriority',
  1850. 'roundingIncrement',
  1851. 'trailingZeroDisplay'
  1852. ];
  1853. /** @internal */
  1854. function parseNumberArgs(...args) {
  1855. const [arg1, arg2, arg3, arg4] = args;
  1856. const options = {};
  1857. let overrides = {};
  1858. if (!isNumber(arg1)) {
  1859. throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
  1860. }
  1861. const value = arg1;
  1862. if (isString(arg2)) {
  1863. options.key = arg2;
  1864. }
  1865. else if (isPlainObject(arg2)) {
  1866. Object.keys(arg2).forEach(key => {
  1867. if (NUMBER_FORMAT_OPTIONS_KEYS.includes(key)) {
  1868. overrides[key] = arg2[key];
  1869. }
  1870. else {
  1871. options[key] = arg2[key];
  1872. }
  1873. });
  1874. }
  1875. if (isString(arg3)) {
  1876. options.locale = arg3;
  1877. }
  1878. else if (isPlainObject(arg3)) {
  1879. overrides = arg3;
  1880. }
  1881. if (isPlainObject(arg4)) {
  1882. overrides = arg4;
  1883. }
  1884. return [options.key || '', value, options, overrides];
  1885. }
  1886. /** @internal */
  1887. function clearNumberFormat(ctx, locale, format) {
  1888. const context = ctx;
  1889. for (const key in format) {
  1890. const id = `${locale}__${key}`;
  1891. if (!context.__numberFormatters.has(id)) {
  1892. continue;
  1893. }
  1894. context.__numberFormatters.delete(id);
  1895. }
  1896. }
  1897. /**
  1898. * Vue I18n Version
  1899. *
  1900. * @remarks
  1901. * Semver format. Same format as the package.json `version` field.
  1902. *
  1903. * @VueI18nGeneral
  1904. */
  1905. const VERSION = '9.13.1';
  1906. /**
  1907. * This is only called development env
  1908. * istanbul-ignore-next
  1909. */
  1910. function initDev() {
  1911. {
  1912. {
  1913. console.info(`You are running a development build of vue-i18n.\n` +
  1914. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  1915. }
  1916. }
  1917. }
  1918. const code$1 = CoreWarnCodes.__EXTEND_POINT__;
  1919. const inc$1 = incrementer(code$1);
  1920. const I18nWarnCodes = {
  1921. FALLBACK_TO_ROOT: code$1, // 9
  1922. NOT_SUPPORTED_PRESERVE: inc$1(), // 10
  1923. NOT_SUPPORTED_FORMATTER: inc$1(), // 11
  1924. NOT_SUPPORTED_PRESERVE_DIRECTIVE: inc$1(), // 12
  1925. NOT_SUPPORTED_GET_CHOICE_INDEX: inc$1(), // 13
  1926. COMPONENT_NAME_LEGACY_COMPATIBLE: inc$1(), // 14
  1927. NOT_FOUND_PARENT_SCOPE: inc$1(), // 15
  1928. IGNORE_OBJ_FLATTEN: inc$1(), // 16
  1929. NOTICE_DROP_ALLOW_COMPOSITION: inc$1(), // 17
  1930. NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG: inc$1() // 18
  1931. };
  1932. const warnMessages = {
  1933. [I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,
  1934. [I18nWarnCodes.NOT_SUPPORTED_PRESERVE]: `Not supported 'preserve'.`,
  1935. [I18nWarnCodes.NOT_SUPPORTED_FORMATTER]: `Not supported 'formatter'.`,
  1936. [I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE]: `Not supported 'preserveDirectiveContent'.`,
  1937. [I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX]: `Not supported 'getChoiceIndex'.`,
  1938. [I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE]: `Component name legacy compatible: '{name}' -> 'i18n'`,
  1939. [I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,
  1940. [I18nWarnCodes.IGNORE_OBJ_FLATTEN]: `Ignore object flatten: '{key}' key has an string value`,
  1941. [I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION]: `'allowComposition' option will be dropped in the next major version. For more information, please see 👉 https://tinyurl.com/2p97mcze`,
  1942. [I18nWarnCodes.NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG]: `'translateExistCompatible' option will be dropped in the next major version.`
  1943. };
  1944. function getWarnMessage(code, ...args) {
  1945. return format(warnMessages[code], ...args);
  1946. }
  1947. const code = CoreErrorCodes.__EXTEND_POINT__;
  1948. const inc = incrementer(code);
  1949. const I18nErrorCodes = {
  1950. // composer module errors
  1951. UNEXPECTED_RETURN_TYPE: code, // 24
  1952. // legacy module errors
  1953. INVALID_ARGUMENT: inc(), // 25
  1954. // i18n module errors
  1955. MUST_BE_CALL_SETUP_TOP: inc(), // 26
  1956. NOT_INSTALLED: inc(), // 27
  1957. NOT_AVAILABLE_IN_LEGACY_MODE: inc(), // 28
  1958. // directive module errors
  1959. REQUIRED_VALUE: inc(), // 29
  1960. INVALID_VALUE: inc(), // 30
  1961. // vue-devtools errors
  1962. CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: inc(), // 31
  1963. NOT_INSTALLED_WITH_PROVIDE: inc(), // 32
  1964. // unexpected error
  1965. UNEXPECTED_ERROR: inc(), // 33
  1966. // not compatible legacy vue-i18n constructor
  1967. NOT_COMPATIBLE_LEGACY_VUE_I18N: inc(), // 34
  1968. // bridge support vue 2.x only
  1969. BRIDGE_SUPPORT_VUE_2_ONLY: inc(), // 35
  1970. // need to define `i18n` option in `allowComposition: true` and `useScope: 'local' at `useI18n``
  1971. MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION: inc(), // 36
  1972. // Not available Compostion API in Legacy API mode. Please make sure that the legacy API mode is working properly
  1973. NOT_AVAILABLE_COMPOSITION_IN_LEGACY: inc(), // 37
  1974. // for enhancement
  1975. __EXTEND_POINT__: inc() // 38
  1976. };
  1977. function createI18nError(code, ...args) {
  1978. return createCompileError(code, null, { messages: errorMessages, args } );
  1979. }
  1980. const errorMessages = {
  1981. [I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',
  1982. [I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',
  1983. [I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',
  1984. [I18nErrorCodes.NOT_INSTALLED]: 'Need to install with `app.use` function',
  1985. [I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',
  1986. [I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE]: 'Not available in legacy mode',
  1987. [I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,
  1988. [I18nErrorCodes.INVALID_VALUE]: `Invalid value`,
  1989. [I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,
  1990. [I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE]: 'Need to install with `provide` function',
  1991. [I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',
  1992. [I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY]: 'vue-i18n-bridge support Vue 2.x only',
  1993. [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',
  1994. [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'
  1995. };
  1996. const TranslateVNodeSymbol =
  1997. /* #__PURE__*/ makeSymbol('__translateVNode');
  1998. const DatetimePartsSymbol = /* #__PURE__*/ makeSymbol('__datetimeParts');
  1999. const NumberPartsSymbol = /* #__PURE__*/ makeSymbol('__numberParts');
  2000. const EnableEmitter = /* #__PURE__*/ makeSymbol('__enableEmitter');
  2001. const DisableEmitter = /* #__PURE__*/ makeSymbol('__disableEmitter');
  2002. const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
  2003. const InejctWithOptionSymbol =
  2004. /* #__PURE__*/ makeSymbol('__injectWithOption');
  2005. const DisposeSymbol = /* #__PURE__*/ makeSymbol('__dispose');
  2006. const __VUE_I18N_BRIDGE__ = '__VUE_I18N_BRIDGE__';
  2007. /* eslint-disable @typescript-eslint/no-explicit-any */
  2008. /**
  2009. * Transform flat json in obj to normal json in obj
  2010. */
  2011. function handleFlatJson(obj) {
  2012. // check obj
  2013. if (!isObject(obj)) {
  2014. return obj;
  2015. }
  2016. for (const key in obj) {
  2017. // check key
  2018. if (!hasOwn(obj, key)) {
  2019. continue;
  2020. }
  2021. // handle for normal json
  2022. if (!key.includes('.')) {
  2023. // recursive process value if value is also a object
  2024. if (isObject(obj[key])) {
  2025. handleFlatJson(obj[key]);
  2026. }
  2027. }
  2028. // handle for flat json, transform to normal json
  2029. else {
  2030. // go to the last object
  2031. const subKeys = key.split('.');
  2032. const lastIndex = subKeys.length - 1;
  2033. let currentObj = obj;
  2034. let hasStringValue = false;
  2035. for (let i = 0; i < lastIndex; i++) {
  2036. if (!(subKeys[i] in currentObj)) {
  2037. currentObj[subKeys[i]] = {};
  2038. }
  2039. if (!isObject(currentObj[subKeys[i]])) {
  2040. warn(getWarnMessage(I18nWarnCodes.IGNORE_OBJ_FLATTEN, {
  2041. key: subKeys[i]
  2042. }));
  2043. hasStringValue = true;
  2044. break;
  2045. }
  2046. currentObj = currentObj[subKeys[i]];
  2047. }
  2048. // update last object value, delete old property
  2049. if (!hasStringValue) {
  2050. currentObj[subKeys[lastIndex]] = obj[key];
  2051. delete obj[key];
  2052. }
  2053. // recursive process value if value is also a object
  2054. if (isObject(currentObj[subKeys[lastIndex]])) {
  2055. handleFlatJson(currentObj[subKeys[lastIndex]]);
  2056. }
  2057. }
  2058. }
  2059. return obj;
  2060. }
  2061. function getLocaleMessages(locale, options) {
  2062. const { messages, __i18n, messageResolver, flatJson } = options;
  2063. // prettier-ignore
  2064. const ret = (isPlainObject(messages)
  2065. ? messages
  2066. : isArray(__i18n)
  2067. ? {}
  2068. : { [locale]: {} });
  2069. // merge locale messages of i18n custom block
  2070. if (isArray(__i18n)) {
  2071. __i18n.forEach(custom => {
  2072. if ('locale' in custom && 'resource' in custom) {
  2073. const { locale, resource } = custom;
  2074. if (locale) {
  2075. ret[locale] = ret[locale] || {};
  2076. deepCopy(resource, ret[locale]);
  2077. }
  2078. else {
  2079. deepCopy(resource, ret);
  2080. }
  2081. }
  2082. else {
  2083. isString(custom) && deepCopy(JSON.parse(custom), ret);
  2084. }
  2085. });
  2086. }
  2087. // handle messages for flat json
  2088. if (messageResolver == null && flatJson) {
  2089. for (const key in ret) {
  2090. if (hasOwn(ret, key)) {
  2091. handleFlatJson(ret[key]);
  2092. }
  2093. }
  2094. }
  2095. return ret;
  2096. }
  2097. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2098. function getComponentOptions(instance) {
  2099. return instance.type ;
  2100. }
  2101. function adjustI18nResources(gl, options, componentOptions // eslint-disable-line @typescript-eslint/no-explicit-any
  2102. ) {
  2103. let messages = isObject(options.messages) ? options.messages : {};
  2104. if ('__i18nGlobal' in componentOptions) {
  2105. messages = getLocaleMessages(gl.locale.value, {
  2106. messages,
  2107. __i18n: componentOptions.__i18nGlobal
  2108. });
  2109. }
  2110. // merge locale messages
  2111. const locales = Object.keys(messages);
  2112. if (locales.length) {
  2113. locales.forEach(locale => {
  2114. gl.mergeLocaleMessage(locale, messages[locale]);
  2115. });
  2116. }
  2117. {
  2118. // merge datetime formats
  2119. if (isObject(options.datetimeFormats)) {
  2120. const locales = Object.keys(options.datetimeFormats);
  2121. if (locales.length) {
  2122. locales.forEach(locale => {
  2123. gl.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
  2124. });
  2125. }
  2126. }
  2127. // merge number formats
  2128. if (isObject(options.numberFormats)) {
  2129. const locales = Object.keys(options.numberFormats);
  2130. if (locales.length) {
  2131. locales.forEach(locale => {
  2132. gl.mergeNumberFormat(locale, options.numberFormats[locale]);
  2133. });
  2134. }
  2135. }
  2136. }
  2137. }
  2138. function createTextNode(key) {
  2139. return createVNode(Text, null, key, 0)
  2140. ;
  2141. }
  2142. /* eslint-enable @typescript-eslint/no-explicit-any */
  2143. /* eslint-disable @typescript-eslint/no-explicit-any */
  2144. // extend VNode interface
  2145. const DEVTOOLS_META = '__INTLIFY_META__';
  2146. const NOOP_RETURN_ARRAY = () => [];
  2147. const NOOP_RETURN_FALSE = () => false;
  2148. let composerID = 0;
  2149. function defineCoreMissingHandler(missing) {
  2150. return ((ctx, locale, key, type) => {
  2151. return missing(locale, key, getCurrentInstance() || undefined, type);
  2152. });
  2153. }
  2154. // for Intlify DevTools
  2155. /* #__NO_SIDE_EFFECTS__ */
  2156. const getMetaInfo = () => {
  2157. const instance = getCurrentInstance();
  2158. let meta = null; // eslint-disable-line @typescript-eslint/no-explicit-any
  2159. return instance && (meta = getComponentOptions(instance)[DEVTOOLS_META])
  2160. ? { [DEVTOOLS_META]: meta } // eslint-disable-line @typescript-eslint/no-explicit-any
  2161. : null;
  2162. };
  2163. /**
  2164. * Create composer interface factory
  2165. *
  2166. * @internal
  2167. */
  2168. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  2169. function createComposer(options = {}, VueI18nLegacy) {
  2170. const { __root, __injectWithOption } = options;
  2171. const _isGlobal = __root === undefined;
  2172. const flatJson = options.flatJson;
  2173. const _ref = inBrowser ? ref : shallowRef;
  2174. const translateExistCompatible = !!options.translateExistCompatible;
  2175. {
  2176. if (translateExistCompatible && !false) {
  2177. warnOnce(getWarnMessage(I18nWarnCodes.NOTICE_DROP_TRANSLATE_EXIST_COMPATIBLE_FLAG));
  2178. }
  2179. }
  2180. let _inheritLocale = isBoolean(options.inheritLocale)
  2181. ? options.inheritLocale
  2182. : true;
  2183. const _locale = _ref(
  2184. // prettier-ignore
  2185. __root && _inheritLocale
  2186. ? __root.locale.value
  2187. : isString(options.locale)
  2188. ? options.locale
  2189. : DEFAULT_LOCALE);
  2190. const _fallbackLocale = _ref(
  2191. // prettier-ignore
  2192. __root && _inheritLocale
  2193. ? __root.fallbackLocale.value
  2194. : isString(options.fallbackLocale) ||
  2195. isArray(options.fallbackLocale) ||
  2196. isPlainObject(options.fallbackLocale) ||
  2197. options.fallbackLocale === false
  2198. ? options.fallbackLocale
  2199. : _locale.value);
  2200. const _messages = _ref(getLocaleMessages(_locale.value, options));
  2201. // prettier-ignore
  2202. const _datetimeFormats = _ref(isPlainObject(options.datetimeFormats)
  2203. ? options.datetimeFormats
  2204. : { [_locale.value]: {} })
  2205. ;
  2206. // prettier-ignore
  2207. const _numberFormats = _ref(isPlainObject(options.numberFormats)
  2208. ? options.numberFormats
  2209. : { [_locale.value]: {} })
  2210. ;
  2211. // warning suppress options
  2212. // prettier-ignore
  2213. let _missingWarn = __root
  2214. ? __root.missingWarn
  2215. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  2216. ? options.missingWarn
  2217. : true;
  2218. // prettier-ignore
  2219. let _fallbackWarn = __root
  2220. ? __root.fallbackWarn
  2221. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  2222. ? options.fallbackWarn
  2223. : true;
  2224. // prettier-ignore
  2225. let _fallbackRoot = __root
  2226. ? __root.fallbackRoot
  2227. : isBoolean(options.fallbackRoot)
  2228. ? options.fallbackRoot
  2229. : true;
  2230. // configure fall back to root
  2231. let _fallbackFormat = !!options.fallbackFormat;
  2232. // runtime missing
  2233. let _missing = isFunction(options.missing) ? options.missing : null;
  2234. let _runtimeMissing = isFunction(options.missing)
  2235. ? defineCoreMissingHandler(options.missing)
  2236. : null;
  2237. // postTranslation handler
  2238. let _postTranslation = isFunction(options.postTranslation)
  2239. ? options.postTranslation
  2240. : null;
  2241. // prettier-ignore
  2242. let _warnHtmlMessage = __root
  2243. ? __root.warnHtmlMessage
  2244. : isBoolean(options.warnHtmlMessage)
  2245. ? options.warnHtmlMessage
  2246. : true;
  2247. let _escapeParameter = !!options.escapeParameter;
  2248. // custom linked modifiers
  2249. // prettier-ignore
  2250. const _modifiers = __root
  2251. ? __root.modifiers
  2252. : isPlainObject(options.modifiers)
  2253. ? options.modifiers
  2254. : {};
  2255. // pluralRules
  2256. let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
  2257. // runtime context
  2258. // eslint-disable-next-line prefer-const
  2259. let _context;
  2260. const getCoreContext = () => {
  2261. _isGlobal && setFallbackContext(null);
  2262. const ctxOptions = {
  2263. version: VERSION,
  2264. locale: _locale.value,
  2265. fallbackLocale: _fallbackLocale.value,
  2266. messages: _messages.value,
  2267. modifiers: _modifiers,
  2268. pluralRules: _pluralRules,
  2269. missing: _runtimeMissing === null ? undefined : _runtimeMissing,
  2270. missingWarn: _missingWarn,
  2271. fallbackWarn: _fallbackWarn,
  2272. fallbackFormat: _fallbackFormat,
  2273. unresolving: true,
  2274. postTranslation: _postTranslation === null ? undefined : _postTranslation,
  2275. warnHtmlMessage: _warnHtmlMessage,
  2276. escapeParameter: _escapeParameter,
  2277. messageResolver: options.messageResolver,
  2278. messageCompiler: options.messageCompiler,
  2279. __meta: { framework: 'vue' }
  2280. };
  2281. {
  2282. ctxOptions.datetimeFormats = _datetimeFormats.value;
  2283. ctxOptions.numberFormats = _numberFormats.value;
  2284. ctxOptions.__datetimeFormatters = isPlainObject(_context)
  2285. ? _context.__datetimeFormatters
  2286. : undefined;
  2287. ctxOptions.__numberFormatters = isPlainObject(_context)
  2288. ? _context.__numberFormatters
  2289. : undefined;
  2290. }
  2291. {
  2292. ctxOptions.__v_emitter = isPlainObject(_context)
  2293. ? _context.__v_emitter
  2294. : undefined;
  2295. }
  2296. const ctx = createCoreContext(ctxOptions);
  2297. _isGlobal && setFallbackContext(ctx);
  2298. return ctx;
  2299. };
  2300. _context = getCoreContext();
  2301. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  2302. // track reactivity
  2303. function trackReactivityValues() {
  2304. return [
  2305. _locale.value,
  2306. _fallbackLocale.value,
  2307. _messages.value,
  2308. _datetimeFormats.value,
  2309. _numberFormats.value
  2310. ]
  2311. ;
  2312. }
  2313. // locale
  2314. const locale = computed({
  2315. get: () => _locale.value,
  2316. set: val => {
  2317. _locale.value = val;
  2318. _context.locale = _locale.value;
  2319. }
  2320. });
  2321. // fallbackLocale
  2322. const fallbackLocale = computed({
  2323. get: () => _fallbackLocale.value,
  2324. set: val => {
  2325. _fallbackLocale.value = val;
  2326. _context.fallbackLocale = _fallbackLocale.value;
  2327. updateFallbackLocale(_context, _locale.value, val);
  2328. }
  2329. });
  2330. // messages
  2331. const messages = computed(() => _messages.value);
  2332. // datetimeFormats
  2333. const datetimeFormats = /* #__PURE__*/ computed(() => _datetimeFormats.value);
  2334. // numberFormats
  2335. const numberFormats = /* #__PURE__*/ computed(() => _numberFormats.value);
  2336. // getPostTranslationHandler
  2337. function getPostTranslationHandler() {
  2338. return isFunction(_postTranslation) ? _postTranslation : null;
  2339. }
  2340. // setPostTranslationHandler
  2341. function setPostTranslationHandler(handler) {
  2342. _postTranslation = handler;
  2343. _context.postTranslation = handler;
  2344. }
  2345. // getMissingHandler
  2346. function getMissingHandler() {
  2347. return _missing;
  2348. }
  2349. // setMissingHandler
  2350. function setMissingHandler(handler) {
  2351. if (handler !== null) {
  2352. _runtimeMissing = defineCoreMissingHandler(handler);
  2353. }
  2354. _missing = handler;
  2355. _context.missing = _runtimeMissing;
  2356. }
  2357. function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
  2358. ) {
  2359. return type !== 'translate' || !arg.resolvedMessage;
  2360. }
  2361. const wrapWithDeps = (fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) => {
  2362. trackReactivityValues(); // track reactive dependency
  2363. // NOTE: experimental !!
  2364. let ret;
  2365. try {
  2366. if (true || false) {
  2367. setAdditionalMeta(getMetaInfo());
  2368. }
  2369. if (!_isGlobal) {
  2370. _context.fallbackContext = __root
  2371. ? getFallbackContext()
  2372. : undefined;
  2373. }
  2374. ret = fn(_context);
  2375. }
  2376. finally {
  2377. if (!_isGlobal) {
  2378. _context.fallbackContext = undefined;
  2379. }
  2380. }
  2381. if ((warnType !== 'translate exists' && // for not `te` (e.g `t`)
  2382. isNumber(ret) &&
  2383. ret === NOT_REOSLVED) ||
  2384. (warnType === 'translate exists' && !ret) // for `te`
  2385. ) {
  2386. const [key, arg2] = argumentParser();
  2387. if (__root &&
  2388. isString(key) &&
  2389. isResolvedTranslateMessage(warnType, arg2)) {
  2390. if (_fallbackRoot &&
  2391. (isTranslateFallbackWarn(_fallbackWarn, key) ||
  2392. isTranslateMissingWarn(_missingWarn, key))) {
  2393. warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {
  2394. key,
  2395. type: warnType
  2396. }));
  2397. }
  2398. // for vue-devtools timeline event
  2399. {
  2400. const { __v_emitter: emitter } = _context;
  2401. if (emitter && _fallbackRoot) {
  2402. emitter.emit("fallback" /* VueDevToolsTimelineEvents.FALBACK */, {
  2403. type: warnType,
  2404. key,
  2405. to: 'global',
  2406. groupId: `${warnType}:${key}`
  2407. });
  2408. }
  2409. }
  2410. }
  2411. return __root && _fallbackRoot
  2412. ? fallbackSuccess(__root)
  2413. : fallbackFail(key);
  2414. }
  2415. else if (successCondition(ret)) {
  2416. return ret;
  2417. }
  2418. else {
  2419. /* istanbul ignore next */
  2420. throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);
  2421. }
  2422. };
  2423. // t
  2424. function t(...args) {
  2425. return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));
  2426. }
  2427. // rt
  2428. function rt(...args) {
  2429. const [arg1, arg2, arg3] = args;
  2430. if (arg3 && !isObject(arg3)) {
  2431. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  2432. }
  2433. return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
  2434. }
  2435. // d
  2436. function d(...args) {
  2437. 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));
  2438. }
  2439. // n
  2440. function n(...args) {
  2441. 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));
  2442. }
  2443. // for custom processor
  2444. function normalize(values) {
  2445. return values.map(val => isString(val) || isNumber(val) || isBoolean(val)
  2446. ? createTextNode(String(val))
  2447. : val);
  2448. }
  2449. const interpolate = (val) => val;
  2450. const processor = {
  2451. normalize,
  2452. interpolate,
  2453. type: 'vnode'
  2454. };
  2455. // translateVNode, using for `i18n-t` component
  2456. function translateVNode(...args) {
  2457. return wrapWithDeps(context => {
  2458. let ret;
  2459. const _context = context;
  2460. try {
  2461. _context.processor = processor;
  2462. ret = Reflect.apply(translate, null, [_context, ...args]);
  2463. }
  2464. finally {
  2465. _context.processor = null;
  2466. }
  2467. return ret;
  2468. }, () => parseTranslateArgs(...args), 'translate',
  2469. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2470. root => root[TranslateVNodeSymbol](...args), key => [createTextNode(key)], val => isArray(val));
  2471. }
  2472. // numberParts, using for `i18n-n` component
  2473. function numberParts(...args) {
  2474. return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format',
  2475. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2476. root => root[NumberPartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  2477. }
  2478. // datetimeParts, using for `i18n-d` component
  2479. function datetimeParts(...args) {
  2480. return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format',
  2481. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2482. root => root[DatetimePartsSymbol](...args), NOOP_RETURN_ARRAY, val => isString(val) || isArray(val));
  2483. }
  2484. function setPluralRules(rules) {
  2485. _pluralRules = rules;
  2486. _context.pluralRules = _pluralRules;
  2487. }
  2488. // te
  2489. function te(key, locale) {
  2490. return wrapWithDeps(() => {
  2491. if (!key) {
  2492. return false;
  2493. }
  2494. const targetLocale = isString(locale) ? locale : _locale.value;
  2495. const message = getLocaleMessage(targetLocale);
  2496. const resolved = _context.messageResolver(message, key);
  2497. return !translateExistCompatible
  2498. ? isMessageAST(resolved) ||
  2499. isMessageFunction(resolved) ||
  2500. isString(resolved)
  2501. : resolved != null;
  2502. }, () => [key], 'translate exists', root => {
  2503. return Reflect.apply(root.te, root, [key, locale]);
  2504. }, NOOP_RETURN_FALSE, val => isBoolean(val));
  2505. }
  2506. function resolveMessages(key) {
  2507. let messages = null;
  2508. const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);
  2509. for (let i = 0; i < locales.length; i++) {
  2510. const targetLocaleMessages = _messages.value[locales[i]] || {};
  2511. const messageValue = _context.messageResolver(targetLocaleMessages, key);
  2512. if (messageValue != null) {
  2513. messages = messageValue;
  2514. break;
  2515. }
  2516. }
  2517. return messages;
  2518. }
  2519. // tm
  2520. function tm(key) {
  2521. const messages = resolveMessages(key);
  2522. // prettier-ignore
  2523. return messages != null
  2524. ? messages
  2525. : __root
  2526. ? __root.tm(key) || {}
  2527. : {};
  2528. }
  2529. // getLocaleMessage
  2530. function getLocaleMessage(locale) {
  2531. return (_messages.value[locale] || {});
  2532. }
  2533. // setLocaleMessage
  2534. function setLocaleMessage(locale, message) {
  2535. if (flatJson) {
  2536. const _message = { [locale]: message };
  2537. for (const key in _message) {
  2538. if (hasOwn(_message, key)) {
  2539. handleFlatJson(_message[key]);
  2540. }
  2541. }
  2542. message = _message[locale];
  2543. }
  2544. _messages.value[locale] = message;
  2545. _context.messages = _messages.value;
  2546. }
  2547. // mergeLocaleMessage
  2548. function mergeLocaleMessage(locale, message) {
  2549. _messages.value[locale] = _messages.value[locale] || {};
  2550. const _message = { [locale]: message };
  2551. if (flatJson) {
  2552. for (const key in _message) {
  2553. if (hasOwn(_message, key)) {
  2554. handleFlatJson(_message[key]);
  2555. }
  2556. }
  2557. }
  2558. message = _message[locale];
  2559. deepCopy(message, _messages.value[locale]);
  2560. _context.messages = _messages.value;
  2561. }
  2562. // getDateTimeFormat
  2563. function getDateTimeFormat(locale) {
  2564. return _datetimeFormats.value[locale] || {};
  2565. }
  2566. // setDateTimeFormat
  2567. function setDateTimeFormat(locale, format) {
  2568. _datetimeFormats.value[locale] = format;
  2569. _context.datetimeFormats = _datetimeFormats.value;
  2570. clearDateTimeFormat(_context, locale, format);
  2571. }
  2572. // mergeDateTimeFormat
  2573. function mergeDateTimeFormat(locale, format) {
  2574. _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
  2575. _context.datetimeFormats = _datetimeFormats.value;
  2576. clearDateTimeFormat(_context, locale, format);
  2577. }
  2578. // getNumberFormat
  2579. function getNumberFormat(locale) {
  2580. return _numberFormats.value[locale] || {};
  2581. }
  2582. // setNumberFormat
  2583. function setNumberFormat(locale, format) {
  2584. _numberFormats.value[locale] = format;
  2585. _context.numberFormats = _numberFormats.value;
  2586. clearNumberFormat(_context, locale, format);
  2587. }
  2588. // mergeNumberFormat
  2589. function mergeNumberFormat(locale, format) {
  2590. _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
  2591. _context.numberFormats = _numberFormats.value;
  2592. clearNumberFormat(_context, locale, format);
  2593. }
  2594. // for debug
  2595. composerID++;
  2596. // watch root locale & fallbackLocale
  2597. if (__root && inBrowser) {
  2598. watch(__root.locale, (val) => {
  2599. if (_inheritLocale) {
  2600. _locale.value = val;
  2601. _context.locale = val;
  2602. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  2603. }
  2604. });
  2605. watch(__root.fallbackLocale, (val) => {
  2606. if (_inheritLocale) {
  2607. _fallbackLocale.value = val;
  2608. _context.fallbackLocale = val;
  2609. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  2610. }
  2611. });
  2612. }
  2613. // define basic composition API!
  2614. const composer = {
  2615. id: composerID,
  2616. locale,
  2617. fallbackLocale,
  2618. get inheritLocale() {
  2619. return _inheritLocale;
  2620. },
  2621. set inheritLocale(val) {
  2622. _inheritLocale = val;
  2623. if (val && __root) {
  2624. _locale.value = __root.locale.value;
  2625. _fallbackLocale.value = __root.fallbackLocale.value;
  2626. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  2627. }
  2628. },
  2629. get availableLocales() {
  2630. return Object.keys(_messages.value).sort();
  2631. },
  2632. messages,
  2633. get modifiers() {
  2634. return _modifiers;
  2635. },
  2636. get pluralRules() {
  2637. return _pluralRules || {};
  2638. },
  2639. get isGlobal() {
  2640. return _isGlobal;
  2641. },
  2642. get missingWarn() {
  2643. return _missingWarn;
  2644. },
  2645. set missingWarn(val) {
  2646. _missingWarn = val;
  2647. _context.missingWarn = _missingWarn;
  2648. },
  2649. get fallbackWarn() {
  2650. return _fallbackWarn;
  2651. },
  2652. set fallbackWarn(val) {
  2653. _fallbackWarn = val;
  2654. _context.fallbackWarn = _fallbackWarn;
  2655. },
  2656. get fallbackRoot() {
  2657. return _fallbackRoot;
  2658. },
  2659. set fallbackRoot(val) {
  2660. _fallbackRoot = val;
  2661. },
  2662. get fallbackFormat() {
  2663. return _fallbackFormat;
  2664. },
  2665. set fallbackFormat(val) {
  2666. _fallbackFormat = val;
  2667. _context.fallbackFormat = _fallbackFormat;
  2668. },
  2669. get warnHtmlMessage() {
  2670. return _warnHtmlMessage;
  2671. },
  2672. set warnHtmlMessage(val) {
  2673. _warnHtmlMessage = val;
  2674. _context.warnHtmlMessage = val;
  2675. },
  2676. get escapeParameter() {
  2677. return _escapeParameter;
  2678. },
  2679. set escapeParameter(val) {
  2680. _escapeParameter = val;
  2681. _context.escapeParameter = val;
  2682. },
  2683. t,
  2684. getLocaleMessage,
  2685. setLocaleMessage,
  2686. mergeLocaleMessage,
  2687. getPostTranslationHandler,
  2688. setPostTranslationHandler,
  2689. getMissingHandler,
  2690. setMissingHandler,
  2691. [SetPluralRulesSymbol]: setPluralRules
  2692. };
  2693. {
  2694. composer.datetimeFormats = datetimeFormats;
  2695. composer.numberFormats = numberFormats;
  2696. composer.rt = rt;
  2697. composer.te = te;
  2698. composer.tm = tm;
  2699. composer.d = d;
  2700. composer.n = n;
  2701. composer.getDateTimeFormat = getDateTimeFormat;
  2702. composer.setDateTimeFormat = setDateTimeFormat;
  2703. composer.mergeDateTimeFormat = mergeDateTimeFormat;
  2704. composer.getNumberFormat = getNumberFormat;
  2705. composer.setNumberFormat = setNumberFormat;
  2706. composer.mergeNumberFormat = mergeNumberFormat;
  2707. composer[InejctWithOptionSymbol] = __injectWithOption;
  2708. composer[TranslateVNodeSymbol] = translateVNode;
  2709. composer[DatetimePartsSymbol] = datetimeParts;
  2710. composer[NumberPartsSymbol] = numberParts;
  2711. }
  2712. // for vue-devtools timeline event
  2713. {
  2714. composer[EnableEmitter] = (emitter) => {
  2715. _context.__v_emitter = emitter;
  2716. };
  2717. composer[DisableEmitter] = () => {
  2718. _context.__v_emitter = undefined;
  2719. };
  2720. }
  2721. return composer;
  2722. }
  2723. /* eslint-enable @typescript-eslint/no-explicit-any */
  2724. /* eslint-disable @typescript-eslint/no-explicit-any */
  2725. /**
  2726. * Convert to I18n Composer Options from VueI18n Options
  2727. *
  2728. * @internal
  2729. */
  2730. function convertComposerOptions(options) {
  2731. const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
  2732. const fallbackLocale = isString(options.fallbackLocale) ||
  2733. isArray(options.fallbackLocale) ||
  2734. isPlainObject(options.fallbackLocale) ||
  2735. options.fallbackLocale === false
  2736. ? options.fallbackLocale
  2737. : locale;
  2738. const missing = isFunction(options.missing) ? options.missing : undefined;
  2739. const missingWarn = isBoolean(options.silentTranslationWarn) ||
  2740. isRegExp(options.silentTranslationWarn)
  2741. ? !options.silentTranslationWarn
  2742. : true;
  2743. const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
  2744. isRegExp(options.silentFallbackWarn)
  2745. ? !options.silentFallbackWarn
  2746. : true;
  2747. const fallbackRoot = isBoolean(options.fallbackRoot)
  2748. ? options.fallbackRoot
  2749. : true;
  2750. const fallbackFormat = !!options.formatFallbackMessages;
  2751. const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
  2752. const pluralizationRules = options.pluralizationRules;
  2753. const postTranslation = isFunction(options.postTranslation)
  2754. ? options.postTranslation
  2755. : undefined;
  2756. const warnHtmlMessage = isString(options.warnHtmlInMessage)
  2757. ? options.warnHtmlInMessage !== 'off'
  2758. : true;
  2759. const escapeParameter = !!options.escapeParameterHtml;
  2760. const inheritLocale = isBoolean(options.sync) ? options.sync : true;
  2761. if (options.formatter) {
  2762. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  2763. }
  2764. if (options.preserveDirectiveContent) {
  2765. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  2766. }
  2767. let messages = options.messages;
  2768. if (isPlainObject(options.sharedMessages)) {
  2769. const sharedMessages = options.sharedMessages;
  2770. const locales = Object.keys(sharedMessages);
  2771. messages = locales.reduce((messages, locale) => {
  2772. const message = messages[locale] || (messages[locale] = {});
  2773. assign(message, sharedMessages[locale]);
  2774. return messages;
  2775. }, (messages || {}));
  2776. }
  2777. const { __i18n, __root, __injectWithOption } = options;
  2778. const datetimeFormats = options.datetimeFormats;
  2779. const numberFormats = options.numberFormats;
  2780. const flatJson = options.flatJson;
  2781. const translateExistCompatible = options
  2782. .translateExistCompatible;
  2783. return {
  2784. locale,
  2785. fallbackLocale,
  2786. messages,
  2787. flatJson,
  2788. datetimeFormats,
  2789. numberFormats,
  2790. missing,
  2791. missingWarn,
  2792. fallbackWarn,
  2793. fallbackRoot,
  2794. fallbackFormat,
  2795. modifiers,
  2796. pluralRules: pluralizationRules,
  2797. postTranslation,
  2798. warnHtmlMessage,
  2799. escapeParameter,
  2800. messageResolver: options.messageResolver,
  2801. inheritLocale,
  2802. translateExistCompatible,
  2803. __i18n,
  2804. __root,
  2805. __injectWithOption
  2806. };
  2807. }
  2808. /**
  2809. * create VueI18n interface factory
  2810. *
  2811. * @internal
  2812. */
  2813. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  2814. function createVueI18n(options = {}, VueI18nLegacy) {
  2815. {
  2816. const composer = createComposer(convertComposerOptions(options));
  2817. const { __extender } = options;
  2818. // defines VueI18n
  2819. const vueI18n = {
  2820. // id
  2821. id: composer.id,
  2822. // locale
  2823. get locale() {
  2824. return composer.locale.value;
  2825. },
  2826. set locale(val) {
  2827. composer.locale.value = val;
  2828. },
  2829. // fallbackLocale
  2830. get fallbackLocale() {
  2831. return composer.fallbackLocale.value;
  2832. },
  2833. set fallbackLocale(val) {
  2834. composer.fallbackLocale.value = val;
  2835. },
  2836. // messages
  2837. get messages() {
  2838. return composer.messages.value;
  2839. },
  2840. // datetimeFormats
  2841. get datetimeFormats() {
  2842. return composer.datetimeFormats.value;
  2843. },
  2844. // numberFormats
  2845. get numberFormats() {
  2846. return composer.numberFormats.value;
  2847. },
  2848. // availableLocales
  2849. get availableLocales() {
  2850. return composer.availableLocales;
  2851. },
  2852. // formatter
  2853. get formatter() {
  2854. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  2855. // dummy
  2856. return {
  2857. interpolate() {
  2858. return [];
  2859. }
  2860. };
  2861. },
  2862. set formatter(val) {
  2863. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
  2864. },
  2865. // missing
  2866. get missing() {
  2867. return composer.getMissingHandler();
  2868. },
  2869. set missing(handler) {
  2870. composer.setMissingHandler(handler);
  2871. },
  2872. // silentTranslationWarn
  2873. get silentTranslationWarn() {
  2874. return isBoolean(composer.missingWarn)
  2875. ? !composer.missingWarn
  2876. : composer.missingWarn;
  2877. },
  2878. set silentTranslationWarn(val) {
  2879. composer.missingWarn = isBoolean(val) ? !val : val;
  2880. },
  2881. // silentFallbackWarn
  2882. get silentFallbackWarn() {
  2883. return isBoolean(composer.fallbackWarn)
  2884. ? !composer.fallbackWarn
  2885. : composer.fallbackWarn;
  2886. },
  2887. set silentFallbackWarn(val) {
  2888. composer.fallbackWarn = isBoolean(val) ? !val : val;
  2889. },
  2890. // modifiers
  2891. get modifiers() {
  2892. return composer.modifiers;
  2893. },
  2894. // formatFallbackMessages
  2895. get formatFallbackMessages() {
  2896. return composer.fallbackFormat;
  2897. },
  2898. set formatFallbackMessages(val) {
  2899. composer.fallbackFormat = val;
  2900. },
  2901. // postTranslation
  2902. get postTranslation() {
  2903. return composer.getPostTranslationHandler();
  2904. },
  2905. set postTranslation(handler) {
  2906. composer.setPostTranslationHandler(handler);
  2907. },
  2908. // sync
  2909. get sync() {
  2910. return composer.inheritLocale;
  2911. },
  2912. set sync(val) {
  2913. composer.inheritLocale = val;
  2914. },
  2915. // warnInHtmlMessage
  2916. get warnHtmlInMessage() {
  2917. return composer.warnHtmlMessage ? 'warn' : 'off';
  2918. },
  2919. set warnHtmlInMessage(val) {
  2920. composer.warnHtmlMessage = val !== 'off';
  2921. },
  2922. // escapeParameterHtml
  2923. get escapeParameterHtml() {
  2924. return composer.escapeParameter;
  2925. },
  2926. set escapeParameterHtml(val) {
  2927. composer.escapeParameter = val;
  2928. },
  2929. // preserveDirectiveContent
  2930. get preserveDirectiveContent() {
  2931. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  2932. return true;
  2933. },
  2934. set preserveDirectiveContent(val) {
  2935. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
  2936. },
  2937. // pluralizationRules
  2938. get pluralizationRules() {
  2939. return composer.pluralRules || {};
  2940. },
  2941. // for internal
  2942. __composer: composer,
  2943. // t
  2944. t(...args) {
  2945. const [arg1, arg2, arg3] = args;
  2946. const options = {};
  2947. let list = null;
  2948. let named = null;
  2949. if (!isString(arg1)) {
  2950. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  2951. }
  2952. const key = arg1;
  2953. if (isString(arg2)) {
  2954. options.locale = arg2;
  2955. }
  2956. else if (isArray(arg2)) {
  2957. list = arg2;
  2958. }
  2959. else if (isPlainObject(arg2)) {
  2960. named = arg2;
  2961. }
  2962. if (isArray(arg3)) {
  2963. list = arg3;
  2964. }
  2965. else if (isPlainObject(arg3)) {
  2966. named = arg3;
  2967. }
  2968. // return composer.t(key, (list || named || {}) as any, options)
  2969. return Reflect.apply(composer.t, composer, [
  2970. key,
  2971. (list || named || {}),
  2972. options
  2973. ]);
  2974. },
  2975. rt(...args) {
  2976. return Reflect.apply(composer.rt, composer, [...args]);
  2977. },
  2978. // tc
  2979. tc(...args) {
  2980. const [arg1, arg2, arg3] = args;
  2981. const options = { plural: 1 };
  2982. let list = null;
  2983. let named = null;
  2984. if (!isString(arg1)) {
  2985. throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
  2986. }
  2987. const key = arg1;
  2988. if (isString(arg2)) {
  2989. options.locale = arg2;
  2990. }
  2991. else if (isNumber(arg2)) {
  2992. options.plural = arg2;
  2993. }
  2994. else if (isArray(arg2)) {
  2995. list = arg2;
  2996. }
  2997. else if (isPlainObject(arg2)) {
  2998. named = arg2;
  2999. }
  3000. if (isString(arg3)) {
  3001. options.locale = arg3;
  3002. }
  3003. else if (isArray(arg3)) {
  3004. list = arg3;
  3005. }
  3006. else if (isPlainObject(arg3)) {
  3007. named = arg3;
  3008. }
  3009. // return composer.t(key, (list || named || {}) as any, options)
  3010. return Reflect.apply(composer.t, composer, [
  3011. key,
  3012. (list || named || {}),
  3013. options
  3014. ]);
  3015. },
  3016. // te
  3017. te(key, locale) {
  3018. return composer.te(key, locale);
  3019. },
  3020. // tm
  3021. tm(key) {
  3022. return composer.tm(key);
  3023. },
  3024. // getLocaleMessage
  3025. getLocaleMessage(locale) {
  3026. return composer.getLocaleMessage(locale);
  3027. },
  3028. // setLocaleMessage
  3029. setLocaleMessage(locale, message) {
  3030. composer.setLocaleMessage(locale, message);
  3031. },
  3032. // mergeLocaleMessage
  3033. mergeLocaleMessage(locale, message) {
  3034. composer.mergeLocaleMessage(locale, message);
  3035. },
  3036. // d
  3037. d(...args) {
  3038. return Reflect.apply(composer.d, composer, [...args]);
  3039. },
  3040. // getDateTimeFormat
  3041. getDateTimeFormat(locale) {
  3042. return composer.getDateTimeFormat(locale);
  3043. },
  3044. // setDateTimeFormat
  3045. setDateTimeFormat(locale, format) {
  3046. composer.setDateTimeFormat(locale, format);
  3047. },
  3048. // mergeDateTimeFormat
  3049. mergeDateTimeFormat(locale, format) {
  3050. composer.mergeDateTimeFormat(locale, format);
  3051. },
  3052. // n
  3053. n(...args) {
  3054. return Reflect.apply(composer.n, composer, [...args]);
  3055. },
  3056. // getNumberFormat
  3057. getNumberFormat(locale) {
  3058. return composer.getNumberFormat(locale);
  3059. },
  3060. // setNumberFormat
  3061. setNumberFormat(locale, format) {
  3062. composer.setNumberFormat(locale, format);
  3063. },
  3064. // mergeNumberFormat
  3065. mergeNumberFormat(locale, format) {
  3066. composer.mergeNumberFormat(locale, format);
  3067. },
  3068. // getChoiceIndex
  3069. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  3070. getChoiceIndex(choice, choicesLength) {
  3071. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX));
  3072. return -1;
  3073. }
  3074. };
  3075. vueI18n.__extender = __extender;
  3076. // for vue-devtools timeline event
  3077. {
  3078. vueI18n.__enableEmitter = (emitter) => {
  3079. const __composer = composer;
  3080. __composer[EnableEmitter] && __composer[EnableEmitter](emitter);
  3081. };
  3082. vueI18n.__disableEmitter = () => {
  3083. const __composer = composer;
  3084. __composer[DisableEmitter] && __composer[DisableEmitter]();
  3085. };
  3086. }
  3087. return vueI18n;
  3088. }
  3089. }
  3090. /* eslint-enable @typescript-eslint/no-explicit-any */
  3091. const baseFormatProps = {
  3092. tag: {
  3093. type: [String, Object]
  3094. },
  3095. locale: {
  3096. type: String
  3097. },
  3098. scope: {
  3099. type: String,
  3100. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  3101. validator: (val /* ComponentI18nScope */) => val === 'parent' || val === 'global',
  3102. default: 'parent' /* ComponentI18nScope */
  3103. },
  3104. i18n: {
  3105. type: Object
  3106. }
  3107. };
  3108. function getInterpolateArg(
  3109. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3110. { slots }, // SetupContext,
  3111. keys) {
  3112. if (keys.length === 1 && keys[0] === 'default') {
  3113. // default slot with list
  3114. const ret = slots.default ? slots.default() : [];
  3115. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3116. return ret.reduce((slot, current) => {
  3117. return [
  3118. ...slot,
  3119. // prettier-ignore
  3120. ...(current.type === Fragment ? current.children : [current]
  3121. )
  3122. ];
  3123. }, []);
  3124. }
  3125. else {
  3126. // named slots
  3127. return keys.reduce((arg, key) => {
  3128. const slot = slots[key];
  3129. if (slot) {
  3130. arg[key] = slot();
  3131. }
  3132. return arg;
  3133. }, {});
  3134. }
  3135. }
  3136. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3137. function getFragmentableTag(tag) {
  3138. return Fragment ;
  3139. }
  3140. const TranslationImpl = /*#__PURE__*/ defineComponent({
  3141. /* eslint-disable */
  3142. name: 'i18n-t',
  3143. props: assign({
  3144. keypath: {
  3145. type: String,
  3146. required: true
  3147. },
  3148. plural: {
  3149. type: [Number, String],
  3150. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3151. validator: (val) => isNumber(val) || !isNaN(val)
  3152. }
  3153. }, baseFormatProps),
  3154. /* eslint-enable */
  3155. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3156. setup(props, context) {
  3157. const { slots, attrs } = context;
  3158. // NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
  3159. const i18n = props.i18n ||
  3160. useI18n({
  3161. useScope: props.scope,
  3162. __useComponent: true
  3163. });
  3164. return () => {
  3165. const keys = Object.keys(slots).filter(key => key !== '_');
  3166. const options = {};
  3167. if (props.locale) {
  3168. options.locale = props.locale;
  3169. }
  3170. if (props.plural !== undefined) {
  3171. options.plural = isString(props.plural) ? +props.plural : props.plural;
  3172. }
  3173. const arg = getInterpolateArg(context, keys);
  3174. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3175. const children = i18n[TranslateVNodeSymbol](props.keypath, arg, options);
  3176. const assignedAttrs = assign({}, attrs);
  3177. const tag = isString(props.tag) || isObject(props.tag)
  3178. ? props.tag
  3179. : getFragmentableTag();
  3180. return h(tag, assignedAttrs, children);
  3181. };
  3182. }
  3183. });
  3184. /**
  3185. * export the public type for h/tsx inference
  3186. * also to avoid inline import() in generated d.ts files
  3187. */
  3188. /**
  3189. * Translation Component
  3190. *
  3191. * @remarks
  3192. * See the following items for property about details
  3193. *
  3194. * @VueI18nSee [TranslationProps](component#translationprops)
  3195. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  3196. * @VueI18nSee [Component Interpolation](../guide/advanced/component)
  3197. *
  3198. * @example
  3199. * ```html
  3200. * <div id="app">
  3201. * <!-- ... -->
  3202. * <i18n keypath="term" tag="label" for="tos">
  3203. * <a :href="url" target="_blank">{{ $t('tos') }}</a>
  3204. * </i18n>
  3205. * <!-- ... -->
  3206. * </div>
  3207. * ```
  3208. * ```js
  3209. * import { createApp } from 'vue'
  3210. * import { createI18n } from 'vue-i18n'
  3211. *
  3212. * const messages = {
  3213. * en: {
  3214. * tos: 'Term of Service',
  3215. * term: 'I accept xxx {0}.'
  3216. * },
  3217. * ja: {
  3218. * tos: '利用規約',
  3219. * term: '私は xxx の{0}に同意します。'
  3220. * }
  3221. * }
  3222. *
  3223. * const i18n = createI18n({
  3224. * locale: 'en',
  3225. * messages
  3226. * })
  3227. *
  3228. * const app = createApp({
  3229. * data: {
  3230. * url: '/term'
  3231. * }
  3232. * }).use(i18n).mount('#app')
  3233. * ```
  3234. *
  3235. * @VueI18nComponent
  3236. */
  3237. const Translation = TranslationImpl;
  3238. const I18nT = Translation;
  3239. function isVNode(target) {
  3240. return isArray(target) && !isString(target[0]);
  3241. }
  3242. function renderFormatter(props, context, slotKeys, partFormatter) {
  3243. const { slots, attrs } = context;
  3244. return () => {
  3245. const options = { part: true };
  3246. let overrides = {};
  3247. if (props.locale) {
  3248. options.locale = props.locale;
  3249. }
  3250. if (isString(props.format)) {
  3251. options.key = props.format;
  3252. }
  3253. else if (isObject(props.format)) {
  3254. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3255. if (isString(props.format.key)) {
  3256. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3257. options.key = props.format.key;
  3258. }
  3259. // Filter out number format options only
  3260. overrides = Object.keys(props.format).reduce((options, prop) => {
  3261. return slotKeys.includes(prop)
  3262. ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
  3263. : options;
  3264. }, {});
  3265. }
  3266. const parts = partFormatter(...[props.value, options, overrides]);
  3267. let children = [options.key];
  3268. if (isArray(parts)) {
  3269. children = parts.map((part, index) => {
  3270. const slot = slots[part.type];
  3271. const node = slot
  3272. ? slot({ [part.type]: part.value, index, parts })
  3273. : [part.value];
  3274. if (isVNode(node)) {
  3275. node[0].key = `${part.type}-${index}`;
  3276. }
  3277. return node;
  3278. });
  3279. }
  3280. else if (isString(parts)) {
  3281. children = [parts];
  3282. }
  3283. const assignedAttrs = assign({}, attrs);
  3284. const tag = isString(props.tag) || isObject(props.tag)
  3285. ? props.tag
  3286. : getFragmentableTag();
  3287. return h(tag, assignedAttrs, children);
  3288. };
  3289. }
  3290. const NumberFormatImpl = /*#__PURE__*/ defineComponent({
  3291. /* eslint-disable */
  3292. name: 'i18n-n',
  3293. props: assign({
  3294. value: {
  3295. type: Number,
  3296. required: true
  3297. },
  3298. format: {
  3299. type: [String, Object]
  3300. }
  3301. }, baseFormatProps),
  3302. /* eslint-enable */
  3303. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3304. setup(props, context) {
  3305. const i18n = props.i18n ||
  3306. useI18n({
  3307. useScope: props.scope,
  3308. __useComponent: true
  3309. });
  3310. return renderFormatter(props, context, NUMBER_FORMAT_OPTIONS_KEYS, (...args) =>
  3311. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3312. i18n[NumberPartsSymbol](...args));
  3313. }
  3314. });
  3315. /**
  3316. * export the public type for h/tsx inference
  3317. * also to avoid inline import() in generated d.ts files
  3318. */
  3319. /**
  3320. * Number Format Component
  3321. *
  3322. * @remarks
  3323. * See the following items for property about details
  3324. *
  3325. * @VueI18nSee [FormattableProps](component#formattableprops)
  3326. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  3327. * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
  3328. *
  3329. * @VueI18nDanger
  3330. * 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)
  3331. *
  3332. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
  3333. *
  3334. * @VueI18nComponent
  3335. */
  3336. const NumberFormat = NumberFormatImpl;
  3337. const I18nN = NumberFormat;
  3338. const DatetimeFormatImpl = /* #__PURE__*/ defineComponent({
  3339. /* eslint-disable */
  3340. name: 'i18n-d',
  3341. props: assign({
  3342. value: {
  3343. type: [Number, Date],
  3344. required: true
  3345. },
  3346. format: {
  3347. type: [String, Object]
  3348. }
  3349. }, baseFormatProps),
  3350. /* eslint-enable */
  3351. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3352. setup(props, context) {
  3353. const i18n = props.i18n ||
  3354. useI18n({
  3355. useScope: props.scope,
  3356. __useComponent: true
  3357. });
  3358. return renderFormatter(props, context, DATETIME_FORMAT_OPTIONS_KEYS, (...args) =>
  3359. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3360. i18n[DatetimePartsSymbol](...args));
  3361. }
  3362. });
  3363. /**
  3364. * Datetime Format Component
  3365. *
  3366. * @remarks
  3367. * See the following items for property about details
  3368. *
  3369. * @VueI18nSee [FormattableProps](component#formattableprops)
  3370. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  3371. * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
  3372. *
  3373. * @VueI18nDanger
  3374. * 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)
  3375. *
  3376. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
  3377. *
  3378. * @VueI18nComponent
  3379. */
  3380. const DatetimeFormat = DatetimeFormatImpl;
  3381. const I18nD = DatetimeFormat;
  3382. function getComposer$2(i18n, instance) {
  3383. const i18nInternal = i18n;
  3384. if (i18n.mode === 'composition') {
  3385. return (i18nInternal.__getInstance(instance) || i18n.global);
  3386. }
  3387. else {
  3388. const vueI18n = i18nInternal.__getInstance(instance);
  3389. return vueI18n != null
  3390. ? vueI18n.__composer
  3391. : i18n.global.__composer;
  3392. }
  3393. }
  3394. function vTDirective(i18n) {
  3395. const _process = (binding) => {
  3396. const { instance, modifiers, value } = binding;
  3397. /* istanbul ignore if */
  3398. if (!instance || !instance.$) {
  3399. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  3400. }
  3401. const composer = getComposer$2(i18n, instance.$);
  3402. if (modifiers.preserve) {
  3403. warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE));
  3404. }
  3405. const parsedValue = parseValue(value);
  3406. return [
  3407. Reflect.apply(composer.t, composer, [...makeParams(parsedValue)]),
  3408. composer
  3409. ];
  3410. };
  3411. const register = (el, binding) => {
  3412. const [textContent, composer] = _process(binding);
  3413. if (inBrowser && i18n.global === composer) {
  3414. // global scope only
  3415. el.__i18nWatcher = watch(composer.locale, () => {
  3416. binding.instance && binding.instance.$forceUpdate();
  3417. });
  3418. }
  3419. el.__composer = composer;
  3420. el.textContent = textContent;
  3421. };
  3422. const unregister = (el) => {
  3423. if (inBrowser && el.__i18nWatcher) {
  3424. el.__i18nWatcher();
  3425. el.__i18nWatcher = undefined;
  3426. delete el.__i18nWatcher;
  3427. }
  3428. if (el.__composer) {
  3429. el.__composer = undefined;
  3430. delete el.__composer;
  3431. }
  3432. };
  3433. const update = (el, { value }) => {
  3434. if (el.__composer) {
  3435. const composer = el.__composer;
  3436. const parsedValue = parseValue(value);
  3437. el.textContent = Reflect.apply(composer.t, composer, [
  3438. ...makeParams(parsedValue)
  3439. ]);
  3440. }
  3441. };
  3442. const getSSRProps = (binding) => {
  3443. const [textContent] = _process(binding);
  3444. return { textContent };
  3445. };
  3446. return {
  3447. created: register,
  3448. unmounted: unregister,
  3449. beforeUpdate: update,
  3450. getSSRProps
  3451. };
  3452. }
  3453. function parseValue(value) {
  3454. if (isString(value)) {
  3455. return { path: value };
  3456. }
  3457. else if (isPlainObject(value)) {
  3458. if (!('path' in value)) {
  3459. throw createI18nError(I18nErrorCodes.REQUIRED_VALUE, 'path');
  3460. }
  3461. return value;
  3462. }
  3463. else {
  3464. throw createI18nError(I18nErrorCodes.INVALID_VALUE);
  3465. }
  3466. }
  3467. function makeParams(value) {
  3468. const { path, locale, args, choice, plural } = value;
  3469. const options = {};
  3470. const named = args || {};
  3471. if (isString(locale)) {
  3472. options.locale = locale;
  3473. }
  3474. if (isNumber(choice)) {
  3475. options.plural = choice;
  3476. }
  3477. if (isNumber(plural)) {
  3478. options.plural = plural;
  3479. }
  3480. return [path, named, options];
  3481. }
  3482. function apply(app, i18n, ...options) {
  3483. const pluginOptions = isPlainObject(options[0])
  3484. ? options[0]
  3485. : {};
  3486. const useI18nComponentName = !!pluginOptions.useI18nComponentName;
  3487. const globalInstall = isBoolean(pluginOptions.globalInstall)
  3488. ? pluginOptions.globalInstall
  3489. : true;
  3490. if (globalInstall && useI18nComponentName) {
  3491. warn(getWarnMessage(I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE, {
  3492. name: Translation.name
  3493. }));
  3494. }
  3495. if (globalInstall) {
  3496. [!useI18nComponentName ? Translation.name : 'i18n', 'I18nT'].forEach(name => app.component(name, Translation));
  3497. [NumberFormat.name, 'I18nN'].forEach(name => app.component(name, NumberFormat));
  3498. [DatetimeFormat.name, 'I18nD'].forEach(name => app.component(name, DatetimeFormat));
  3499. }
  3500. // install directive
  3501. {
  3502. app.directive('t', vTDirective(i18n));
  3503. }
  3504. }
  3505. var global$1 = (typeof global !== "undefined" ? global :
  3506. typeof self !== "undefined" ? self :
  3507. typeof window !== "undefined" ? window : {});
  3508. function getDevtoolsGlobalHook() {
  3509. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  3510. }
  3511. function getTarget() {
  3512. // @ts-ignore
  3513. return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
  3514. ? window
  3515. : typeof global$1 !== 'undefined'
  3516. ? global$1
  3517. : {};
  3518. }
  3519. const isProxyAvailable = typeof Proxy === 'function';
  3520. const HOOK_SETUP = 'devtools-plugin:setup';
  3521. const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
  3522. let supported;
  3523. let perf;
  3524. function isPerformanceSupported() {
  3525. var _a;
  3526. if (supported !== undefined) {
  3527. return supported;
  3528. }
  3529. if (typeof window !== 'undefined' && window.performance) {
  3530. supported = true;
  3531. perf = window.performance;
  3532. }
  3533. else if (typeof global$1 !== 'undefined' && ((_a = global$1.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {
  3534. supported = true;
  3535. perf = global$1.perf_hooks.performance;
  3536. }
  3537. else {
  3538. supported = false;
  3539. }
  3540. return supported;
  3541. }
  3542. function now() {
  3543. return isPerformanceSupported() ? perf.now() : Date.now();
  3544. }
  3545. class ApiProxy {
  3546. constructor(plugin, hook) {
  3547. this.target = null;
  3548. this.targetQueue = [];
  3549. this.onQueue = [];
  3550. this.plugin = plugin;
  3551. this.hook = hook;
  3552. const defaultSettings = {};
  3553. if (plugin.settings) {
  3554. for (const id in plugin.settings) {
  3555. const item = plugin.settings[id];
  3556. defaultSettings[id] = item.defaultValue;
  3557. }
  3558. }
  3559. const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
  3560. let currentSettings = Object.assign({}, defaultSettings);
  3561. try {
  3562. const raw = localStorage.getItem(localSettingsSaveId);
  3563. const data = JSON.parse(raw);
  3564. Object.assign(currentSettings, data);
  3565. }
  3566. catch (e) {
  3567. // noop
  3568. }
  3569. this.fallbacks = {
  3570. getSettings() {
  3571. return currentSettings;
  3572. },
  3573. setSettings(value) {
  3574. try {
  3575. localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
  3576. }
  3577. catch (e) {
  3578. // noop
  3579. }
  3580. currentSettings = value;
  3581. },
  3582. now() {
  3583. return now();
  3584. },
  3585. };
  3586. if (hook) {
  3587. hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
  3588. if (pluginId === this.plugin.id) {
  3589. this.fallbacks.setSettings(value);
  3590. }
  3591. });
  3592. }
  3593. this.proxiedOn = new Proxy({}, {
  3594. get: (_target, prop) => {
  3595. if (this.target) {
  3596. return this.target.on[prop];
  3597. }
  3598. else {
  3599. return (...args) => {
  3600. this.onQueue.push({
  3601. method: prop,
  3602. args,
  3603. });
  3604. };
  3605. }
  3606. },
  3607. });
  3608. this.proxiedTarget = new Proxy({}, {
  3609. get: (_target, prop) => {
  3610. if (this.target) {
  3611. return this.target[prop];
  3612. }
  3613. else if (prop === 'on') {
  3614. return this.proxiedOn;
  3615. }
  3616. else if (Object.keys(this.fallbacks).includes(prop)) {
  3617. return (...args) => {
  3618. this.targetQueue.push({
  3619. method: prop,
  3620. args,
  3621. resolve: () => { },
  3622. });
  3623. return this.fallbacks[prop](...args);
  3624. };
  3625. }
  3626. else {
  3627. return (...args) => {
  3628. return new Promise(resolve => {
  3629. this.targetQueue.push({
  3630. method: prop,
  3631. args,
  3632. resolve,
  3633. });
  3634. });
  3635. };
  3636. }
  3637. },
  3638. });
  3639. }
  3640. async setRealTarget(target) {
  3641. this.target = target;
  3642. for (const item of this.onQueue) {
  3643. this.target.on[item.method](...item.args);
  3644. }
  3645. for (const item of this.targetQueue) {
  3646. item.resolve(await this.target[item.method](...item.args));
  3647. }
  3648. }
  3649. }
  3650. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  3651. const descriptor = pluginDescriptor;
  3652. const target = getTarget();
  3653. const hook = getDevtoolsGlobalHook();
  3654. const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
  3655. if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
  3656. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  3657. }
  3658. else {
  3659. const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
  3660. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  3661. list.push({
  3662. pluginDescriptor: descriptor,
  3663. setupFn,
  3664. proxy,
  3665. });
  3666. if (proxy)
  3667. setupFn(proxy.proxiedTarget);
  3668. }
  3669. }
  3670. const VueDevToolsLabels = {
  3671. ["vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */]: 'Vue I18n devtools',
  3672. ["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'I18n Resources',
  3673. ["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]: 'Vue I18n'
  3674. };
  3675. const VueDevToolsPlaceholders = {
  3676. ["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]: 'Search for scopes ...'
  3677. };
  3678. const VueDevToolsTimelineColors = {
  3679. ["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]: 0xffcd19
  3680. };
  3681. const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
  3682. let devtoolsApi;
  3683. async function enableDevTools(app, i18n) {
  3684. return new Promise((resolve, reject) => {
  3685. try {
  3686. setupDevtoolsPlugin({
  3687. id: "vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */,
  3688. label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* VueDevToolsIDs.PLUGIN */],
  3689. packageName: 'vue-i18n',
  3690. homepage: 'https://vue-i18n.intlify.dev',
  3691. logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
  3692. componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
  3693. app: app // eslint-disable-line @typescript-eslint/no-explicit-any
  3694. }, api => {
  3695. devtoolsApi = api;
  3696. api.on.visitComponentTree(({ componentInstance, treeNode }) => {
  3697. updateComponentTreeTags(componentInstance, treeNode, i18n);
  3698. });
  3699. api.on.inspectComponent(({ componentInstance, instanceData }) => {
  3700. if (componentInstance.vnode.el &&
  3701. componentInstance.vnode.el.__VUE_I18N__ &&
  3702. instanceData) {
  3703. if (i18n.mode === 'legacy') {
  3704. // ignore global scope on legacy mode
  3705. if (componentInstance.vnode.el.__VUE_I18N__ !==
  3706. i18n.global.__composer) {
  3707. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  3708. }
  3709. }
  3710. else {
  3711. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  3712. }
  3713. }
  3714. });
  3715. api.addInspector({
  3716. id: "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */,
  3717. label: VueDevToolsLabels["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */],
  3718. icon: 'language',
  3719. treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */]
  3720. });
  3721. api.on.getInspectorTree(payload => {
  3722. if (payload.app === app &&
  3723. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  3724. registerScope(payload, i18n);
  3725. }
  3726. });
  3727. const roots = new Map();
  3728. api.on.getInspectorState(async (payload) => {
  3729. if (payload.app === app &&
  3730. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  3731. api.unhighlightElement();
  3732. inspectScope(payload, i18n);
  3733. if (payload.nodeId === 'global') {
  3734. if (!roots.has(payload.app)) {
  3735. const [root] = await api.getComponentInstances(payload.app);
  3736. roots.set(payload.app, root);
  3737. }
  3738. api.highlightElement(roots.get(payload.app));
  3739. }
  3740. else {
  3741. const instance = getComponentInstance(payload.nodeId, i18n);
  3742. instance && api.highlightElement(instance);
  3743. }
  3744. }
  3745. });
  3746. api.on.editInspectorState(payload => {
  3747. if (payload.app === app &&
  3748. payload.inspectorId === "vue-i18n-resource-inspector" /* VueDevToolsIDs.CUSTOM_INSPECTOR */) {
  3749. editScope(payload, i18n);
  3750. }
  3751. });
  3752. api.addTimelineLayer({
  3753. id: "vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */,
  3754. label: VueDevToolsLabels["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */],
  3755. color: VueDevToolsTimelineColors["vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */]
  3756. });
  3757. resolve(true);
  3758. });
  3759. }
  3760. catch (e) {
  3761. console.error(e);
  3762. reject(false);
  3763. }
  3764. });
  3765. }
  3766. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3767. function getI18nScopeLable(instance) {
  3768. return (instance.type.name ||
  3769. instance.type.displayName ||
  3770. instance.type.__file ||
  3771. 'Anonymous');
  3772. }
  3773. function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
  3774. treeNode, i18n) {
  3775. // prettier-ignore
  3776. const global = i18n.mode === 'composition'
  3777. ? i18n.global
  3778. : i18n.global.__composer;
  3779. if (instance && instance.vnode.el && instance.vnode.el.__VUE_I18N__) {
  3780. // add custom tags local scope only
  3781. if (instance.vnode.el.__VUE_I18N__ !== global) {
  3782. const tag = {
  3783. label: `i18n (${getI18nScopeLable(instance)} Scope)`,
  3784. textColor: 0x000000,
  3785. backgroundColor: 0xffcd19
  3786. };
  3787. treeNode.tags.push(tag);
  3788. }
  3789. }
  3790. }
  3791. function inspectComposer(instanceData, composer) {
  3792. const type = VUE_I18N_COMPONENT_TYPES;
  3793. instanceData.state.push({
  3794. type,
  3795. key: 'locale',
  3796. editable: true,
  3797. value: composer.locale.value
  3798. });
  3799. instanceData.state.push({
  3800. type,
  3801. key: 'availableLocales',
  3802. editable: false,
  3803. value: composer.availableLocales
  3804. });
  3805. instanceData.state.push({
  3806. type,
  3807. key: 'fallbackLocale',
  3808. editable: true,
  3809. value: composer.fallbackLocale.value
  3810. });
  3811. instanceData.state.push({
  3812. type,
  3813. key: 'inheritLocale',
  3814. editable: true,
  3815. value: composer.inheritLocale
  3816. });
  3817. instanceData.state.push({
  3818. type,
  3819. key: 'messages',
  3820. editable: false,
  3821. value: getLocaleMessageValue(composer.messages.value)
  3822. });
  3823. {
  3824. instanceData.state.push({
  3825. type,
  3826. key: 'datetimeFormats',
  3827. editable: false,
  3828. value: composer.datetimeFormats.value
  3829. });
  3830. instanceData.state.push({
  3831. type,
  3832. key: 'numberFormats',
  3833. editable: false,
  3834. value: composer.numberFormats.value
  3835. });
  3836. }
  3837. }
  3838. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3839. function getLocaleMessageValue(messages) {
  3840. const value = {};
  3841. Object.keys(messages).forEach((key) => {
  3842. const v = messages[key];
  3843. if (isFunction(v) && 'source' in v) {
  3844. value[key] = getMessageFunctionDetails(v);
  3845. }
  3846. else if (isMessageAST(v) && v.loc && v.loc.source) {
  3847. value[key] = v.loc.source;
  3848. }
  3849. else if (isObject(v)) {
  3850. value[key] = getLocaleMessageValue(v);
  3851. }
  3852. else {
  3853. value[key] = v;
  3854. }
  3855. });
  3856. return value;
  3857. }
  3858. const ESC = {
  3859. '<': '&lt;',
  3860. '>': '&gt;',
  3861. '"': '&quot;',
  3862. '&': '&amp;'
  3863. };
  3864. function escape(s) {
  3865. return s.replace(/[<>"&]/g, escapeChar);
  3866. }
  3867. function escapeChar(a) {
  3868. return ESC[a] || a;
  3869. }
  3870. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3871. function getMessageFunctionDetails(func) {
  3872. const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
  3873. return {
  3874. _custom: {
  3875. type: 'function',
  3876. display: `<span>ƒ</span> ${argString}`
  3877. }
  3878. };
  3879. }
  3880. function registerScope(payload, i18n) {
  3881. payload.rootNodes.push({
  3882. id: 'global',
  3883. label: 'Global Scope'
  3884. });
  3885. // prettier-ignore
  3886. const global = i18n.mode === 'composition'
  3887. ? i18n.global
  3888. : i18n.global.__composer;
  3889. for (const [keyInstance, instance] of i18n.__instances) {
  3890. // prettier-ignore
  3891. const composer = i18n.mode === 'composition'
  3892. ? instance
  3893. : instance.__composer;
  3894. if (global === composer) {
  3895. continue;
  3896. }
  3897. payload.rootNodes.push({
  3898. id: composer.id.toString(),
  3899. label: `${getI18nScopeLable(keyInstance)} Scope`
  3900. });
  3901. }
  3902. }
  3903. function getComponentInstance(nodeId, i18n) {
  3904. let instance = null;
  3905. if (nodeId !== 'global') {
  3906. for (const [component, composer] of i18n.__instances.entries()) {
  3907. if (composer.id.toString() === nodeId) {
  3908. instance = component;
  3909. break;
  3910. }
  3911. }
  3912. }
  3913. return instance;
  3914. }
  3915. function getComposer$1(nodeId, i18n) {
  3916. if (nodeId === 'global') {
  3917. return i18n.mode === 'composition'
  3918. ? i18n.global
  3919. : i18n.global.__composer;
  3920. }
  3921. else {
  3922. const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
  3923. if (instance) {
  3924. return i18n.mode === 'composition'
  3925. ? instance
  3926. : instance.__composer;
  3927. }
  3928. else {
  3929. return null;
  3930. }
  3931. }
  3932. }
  3933. function inspectScope(payload, i18n
  3934. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3935. ) {
  3936. const composer = getComposer$1(payload.nodeId, i18n);
  3937. if (composer) {
  3938. // TODO:
  3939. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3940. payload.state = makeScopeInspectState(composer);
  3941. }
  3942. return null;
  3943. }
  3944. function makeScopeInspectState(composer) {
  3945. const state = {};
  3946. const localeType = 'Locale related info';
  3947. const localeStates = [
  3948. {
  3949. type: localeType,
  3950. key: 'locale',
  3951. editable: true,
  3952. value: composer.locale.value
  3953. },
  3954. {
  3955. type: localeType,
  3956. key: 'fallbackLocale',
  3957. editable: true,
  3958. value: composer.fallbackLocale.value
  3959. },
  3960. {
  3961. type: localeType,
  3962. key: 'availableLocales',
  3963. editable: false,
  3964. value: composer.availableLocales
  3965. },
  3966. {
  3967. type: localeType,
  3968. key: 'inheritLocale',
  3969. editable: true,
  3970. value: composer.inheritLocale
  3971. }
  3972. ];
  3973. state[localeType] = localeStates;
  3974. const localeMessagesType = 'Locale messages info';
  3975. const localeMessagesStates = [
  3976. {
  3977. type: localeMessagesType,
  3978. key: 'messages',
  3979. editable: false,
  3980. value: getLocaleMessageValue(composer.messages.value)
  3981. }
  3982. ];
  3983. state[localeMessagesType] = localeMessagesStates;
  3984. {
  3985. const datetimeFormatsType = 'Datetime formats info';
  3986. const datetimeFormatsStates = [
  3987. {
  3988. type: datetimeFormatsType,
  3989. key: 'datetimeFormats',
  3990. editable: false,
  3991. value: composer.datetimeFormats.value
  3992. }
  3993. ];
  3994. state[datetimeFormatsType] = datetimeFormatsStates;
  3995. const numberFormatsType = 'Datetime formats info';
  3996. const numberFormatsStates = [
  3997. {
  3998. type: numberFormatsType,
  3999. key: 'numberFormats',
  4000. editable: false,
  4001. value: composer.numberFormats.value
  4002. }
  4003. ];
  4004. state[numberFormatsType] = numberFormatsStates;
  4005. }
  4006. return state;
  4007. }
  4008. function addTimelineEvent(event, payload) {
  4009. if (devtoolsApi) {
  4010. let groupId;
  4011. if (payload && 'groupId' in payload) {
  4012. groupId = payload.groupId;
  4013. delete payload.groupId;
  4014. }
  4015. devtoolsApi.addTimelineEvent({
  4016. layerId: "vue-i18n-timeline" /* VueDevToolsIDs.TIMELINE */,
  4017. event: {
  4018. title: event,
  4019. groupId,
  4020. time: Date.now(),
  4021. meta: {},
  4022. data: payload || {},
  4023. logType: event === "compile-error" /* VueDevToolsTimelineEvents.COMPILE_ERROR */
  4024. ? 'error'
  4025. : event === "fallback" /* VueDevToolsTimelineEvents.FALBACK */ ||
  4026. event === "missing" /* VueDevToolsTimelineEvents.MISSING */
  4027. ? 'warning'
  4028. : 'default'
  4029. }
  4030. });
  4031. }
  4032. }
  4033. function editScope(payload, i18n) {
  4034. const composer = getComposer$1(payload.nodeId, i18n);
  4035. if (composer) {
  4036. const [field] = payload.path;
  4037. if (field === 'locale' && isString(payload.state.value)) {
  4038. composer.locale.value = payload.state.value;
  4039. }
  4040. else if (field === 'fallbackLocale' &&
  4041. (isString(payload.state.value) ||
  4042. isArray(payload.state.value) ||
  4043. isObject(payload.state.value))) {
  4044. composer.fallbackLocale.value = payload.state.value;
  4045. }
  4046. else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
  4047. composer.inheritLocale = payload.state.value;
  4048. }
  4049. }
  4050. }
  4051. /**
  4052. * Supports compatibility for legacy vue-i18n APIs
  4053. * This mixin is used when we use vue-i18n@v9.x or later
  4054. */
  4055. function defineMixin(vuei18n, composer, i18n) {
  4056. return {
  4057. beforeCreate() {
  4058. const instance = getCurrentInstance();
  4059. /* istanbul ignore if */
  4060. if (!instance) {
  4061. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4062. }
  4063. const options = this.$options;
  4064. if (options.i18n) {
  4065. const optionsI18n = options.i18n;
  4066. if (options.__i18n) {
  4067. optionsI18n.__i18n = options.__i18n;
  4068. }
  4069. optionsI18n.__root = composer;
  4070. if (this === this.$root) {
  4071. // merge option and gttach global
  4072. this.$i18n = mergeToGlobal(vuei18n, optionsI18n);
  4073. }
  4074. else {
  4075. optionsI18n.__injectWithOption = true;
  4076. optionsI18n.__extender = i18n.__vueI18nExtend;
  4077. // atttach local VueI18n instance
  4078. this.$i18n = createVueI18n(optionsI18n);
  4079. // extend VueI18n instance
  4080. const _vueI18n = this.$i18n;
  4081. if (_vueI18n.__extender) {
  4082. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  4083. }
  4084. }
  4085. }
  4086. else if (options.__i18n) {
  4087. if (this === this.$root) {
  4088. // merge option and gttach global
  4089. this.$i18n = mergeToGlobal(vuei18n, options);
  4090. }
  4091. else {
  4092. // atttach local VueI18n instance
  4093. this.$i18n = createVueI18n({
  4094. __i18n: options.__i18n,
  4095. __injectWithOption: true,
  4096. __extender: i18n.__vueI18nExtend,
  4097. __root: composer
  4098. });
  4099. // extend VueI18n instance
  4100. const _vueI18n = this.$i18n;
  4101. if (_vueI18n.__extender) {
  4102. _vueI18n.__disposer = _vueI18n.__extender(this.$i18n);
  4103. }
  4104. }
  4105. }
  4106. else {
  4107. // attach global VueI18n instance
  4108. this.$i18n = vuei18n;
  4109. }
  4110. if (options.__i18nGlobal) {
  4111. adjustI18nResources(composer, options, options);
  4112. }
  4113. // defines vue-i18n legacy APIs
  4114. this.$t = (...args) => this.$i18n.t(...args);
  4115. this.$rt = (...args) => this.$i18n.rt(...args);
  4116. this.$tc = (...args) => this.$i18n.tc(...args);
  4117. this.$te = (key, locale) => this.$i18n.te(key, locale);
  4118. this.$d = (...args) => this.$i18n.d(...args);
  4119. this.$n = (...args) => this.$i18n.n(...args);
  4120. this.$tm = (key) => this.$i18n.tm(key);
  4121. i18n.__setInstance(instance, this.$i18n);
  4122. },
  4123. mounted() {
  4124. /* istanbul ignore if */
  4125. if (this.$el &&
  4126. this.$i18n) {
  4127. const _vueI18n = this.$i18n;
  4128. this.$el.__VUE_I18N__ = _vueI18n.__composer;
  4129. const emitter = (this.__v_emitter =
  4130. createEmitter());
  4131. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  4132. emitter.on('*', addTimelineEvent);
  4133. }
  4134. },
  4135. unmounted() {
  4136. const instance = getCurrentInstance();
  4137. /* istanbul ignore if */
  4138. if (!instance) {
  4139. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4140. }
  4141. const _vueI18n = this.$i18n;
  4142. /* istanbul ignore if */
  4143. if (this.$el &&
  4144. this.$el.__VUE_I18N__) {
  4145. if (this.__v_emitter) {
  4146. this.__v_emitter.off('*', addTimelineEvent);
  4147. delete this.__v_emitter;
  4148. }
  4149. if (this.$i18n) {
  4150. _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
  4151. delete this.$el.__VUE_I18N__;
  4152. }
  4153. }
  4154. delete this.$t;
  4155. delete this.$rt;
  4156. delete this.$tc;
  4157. delete this.$te;
  4158. delete this.$d;
  4159. delete this.$n;
  4160. delete this.$tm;
  4161. if (_vueI18n.__disposer) {
  4162. _vueI18n.__disposer();
  4163. delete _vueI18n.__disposer;
  4164. delete _vueI18n.__extender;
  4165. }
  4166. i18n.__deleteInstance(instance);
  4167. delete this.$i18n;
  4168. }
  4169. };
  4170. }
  4171. function mergeToGlobal(g, options) {
  4172. g.locale = options.locale || g.locale;
  4173. g.fallbackLocale = options.fallbackLocale || g.fallbackLocale;
  4174. g.missing = options.missing || g.missing;
  4175. g.silentTranslationWarn =
  4176. options.silentTranslationWarn || g.silentFallbackWarn;
  4177. g.silentFallbackWarn = options.silentFallbackWarn || g.silentFallbackWarn;
  4178. g.formatFallbackMessages =
  4179. options.formatFallbackMessages || g.formatFallbackMessages;
  4180. g.postTranslation = options.postTranslation || g.postTranslation;
  4181. g.warnHtmlInMessage = options.warnHtmlInMessage || g.warnHtmlInMessage;
  4182. g.escapeParameterHtml = options.escapeParameterHtml || g.escapeParameterHtml;
  4183. g.sync = options.sync || g.sync;
  4184. g.__composer[SetPluralRulesSymbol](options.pluralizationRules || g.pluralizationRules);
  4185. const messages = getLocaleMessages(g.locale, {
  4186. messages: options.messages,
  4187. __i18n: options.__i18n
  4188. });
  4189. Object.keys(messages).forEach(locale => g.mergeLocaleMessage(locale, messages[locale]));
  4190. if (options.datetimeFormats) {
  4191. Object.keys(options.datetimeFormats).forEach(locale => g.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
  4192. }
  4193. if (options.numberFormats) {
  4194. Object.keys(options.numberFormats).forEach(locale => g.mergeNumberFormat(locale, options.numberFormats[locale]));
  4195. }
  4196. return g;
  4197. }
  4198. /**
  4199. * Injection key for {@link useI18n}
  4200. *
  4201. * @remarks
  4202. * The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.
  4203. * Specify the i18n instance created by {@link createI18n} together with `provide` function.
  4204. *
  4205. * @VueI18nGeneral
  4206. */
  4207. const I18nInjectionKey =
  4208. /* #__PURE__*/ makeSymbol('global-vue-i18n');
  4209. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
  4210. function createI18n(options = {}, VueI18nLegacy) {
  4211. // prettier-ignore
  4212. const __legacyMode = isBoolean(options.legacy)
  4213. ? options.legacy
  4214. : true;
  4215. // prettier-ignore
  4216. const __globalInjection = isBoolean(options.globalInjection)
  4217. ? options.globalInjection
  4218. : true;
  4219. // prettier-ignore
  4220. const __allowComposition = __legacyMode
  4221. ? !!options.allowComposition
  4222. : true;
  4223. const __instances = new Map();
  4224. const [globalScope, __global] = createGlobal(options, __legacyMode);
  4225. const symbol = /* #__PURE__*/ makeSymbol('vue-i18n' );
  4226. {
  4227. if (__legacyMode && __allowComposition && !false) {
  4228. warn(getWarnMessage(I18nWarnCodes.NOTICE_DROP_ALLOW_COMPOSITION));
  4229. }
  4230. }
  4231. function __getInstance(component) {
  4232. return __instances.get(component) || null;
  4233. }
  4234. function __setInstance(component, instance) {
  4235. __instances.set(component, instance);
  4236. }
  4237. function __deleteInstance(component) {
  4238. __instances.delete(component);
  4239. }
  4240. {
  4241. const i18n = {
  4242. // mode
  4243. get mode() {
  4244. return __legacyMode
  4245. ? 'legacy'
  4246. : 'composition';
  4247. },
  4248. // allowComposition
  4249. get allowComposition() {
  4250. return __allowComposition;
  4251. },
  4252. // install plugin
  4253. async install(app, ...options) {
  4254. {
  4255. app.__VUE_I18N__ = i18n;
  4256. }
  4257. // setup global provider
  4258. app.__VUE_I18N_SYMBOL__ = symbol;
  4259. app.provide(app.__VUE_I18N_SYMBOL__, i18n);
  4260. // set composer & vuei18n extend hook options from plugin options
  4261. if (isPlainObject(options[0])) {
  4262. const opts = options[0];
  4263. i18n.__composerExtend =
  4264. opts.__composerExtend;
  4265. i18n.__vueI18nExtend =
  4266. opts.__vueI18nExtend;
  4267. }
  4268. // global method and properties injection for Composition API
  4269. let globalReleaseHandler = null;
  4270. if (!__legacyMode && __globalInjection) {
  4271. globalReleaseHandler = injectGlobalFields(app, i18n.global);
  4272. }
  4273. // install built-in components and directive
  4274. {
  4275. apply(app, i18n, ...options);
  4276. }
  4277. // setup mixin for Legacy API
  4278. if (__legacyMode) {
  4279. app.mixin(defineMixin(__global, __global.__composer, i18n));
  4280. }
  4281. // release global scope
  4282. const unmountApp = app.unmount;
  4283. app.unmount = () => {
  4284. globalReleaseHandler && globalReleaseHandler();
  4285. i18n.dispose();
  4286. unmountApp();
  4287. };
  4288. // setup vue-devtools plugin
  4289. {
  4290. const ret = await enableDevTools(app, i18n);
  4291. if (!ret) {
  4292. throw createI18nError(I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);
  4293. }
  4294. const emitter = createEmitter();
  4295. if (__legacyMode) {
  4296. const _vueI18n = __global;
  4297. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  4298. }
  4299. else {
  4300. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4301. const _composer = __global;
  4302. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  4303. }
  4304. emitter.on('*', addTimelineEvent);
  4305. }
  4306. },
  4307. // global accessor
  4308. get global() {
  4309. return __global;
  4310. },
  4311. dispose() {
  4312. globalScope.stop();
  4313. },
  4314. // @internal
  4315. __instances,
  4316. // @internal
  4317. __getInstance,
  4318. // @internal
  4319. __setInstance,
  4320. // @internal
  4321. __deleteInstance
  4322. };
  4323. return i18n;
  4324. }
  4325. }
  4326. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  4327. function useI18n(options = {}) {
  4328. const instance = getCurrentInstance();
  4329. if (instance == null) {
  4330. throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);
  4331. }
  4332. if (!instance.isCE &&
  4333. instance.appContext.app != null &&
  4334. !instance.appContext.app.__VUE_I18N_SYMBOL__) {
  4335. throw createI18nError(I18nErrorCodes.NOT_INSTALLED);
  4336. }
  4337. const i18n = getI18nInstance(instance);
  4338. const gl = getGlobalComposer(i18n);
  4339. const componentOptions = getComponentOptions(instance);
  4340. const scope = getScope(options, componentOptions);
  4341. {
  4342. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4343. if (i18n.mode === 'legacy' && !options.__useComponent) {
  4344. if (!i18n.allowComposition) {
  4345. throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE);
  4346. }
  4347. return useI18nForLegacy(instance, scope, gl, options);
  4348. }
  4349. }
  4350. if (scope === 'global') {
  4351. adjustI18nResources(gl, options, componentOptions);
  4352. return gl;
  4353. }
  4354. if (scope === 'parent') {
  4355. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4356. let composer = getComposer(i18n, instance, options.__useComponent);
  4357. if (composer == null) {
  4358. {
  4359. warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));
  4360. }
  4361. composer = gl;
  4362. }
  4363. return composer;
  4364. }
  4365. const i18nInternal = i18n;
  4366. let composer = i18nInternal.__getInstance(instance);
  4367. if (composer == null) {
  4368. const composerOptions = assign({}, options);
  4369. if ('__i18n' in componentOptions) {
  4370. composerOptions.__i18n = componentOptions.__i18n;
  4371. }
  4372. if (gl) {
  4373. composerOptions.__root = gl;
  4374. }
  4375. composer = createComposer(composerOptions);
  4376. if (i18nInternal.__composerExtend) {
  4377. composer[DisposeSymbol] =
  4378. i18nInternal.__composerExtend(composer);
  4379. }
  4380. setupLifeCycle(i18nInternal, instance, composer);
  4381. i18nInternal.__setInstance(instance, composer);
  4382. }
  4383. return composer;
  4384. }
  4385. /**
  4386. * Cast to VueI18n legacy compatible type
  4387. *
  4388. * @remarks
  4389. * This API is provided only with [vue-i18n-bridge](https://vue-i18n.intlify.dev/guide/migration/ways.html#what-is-vue-i18n-bridge).
  4390. *
  4391. * 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.
  4392. *
  4393. * @param i18n - An instance of {@link I18n}
  4394. * @returns A i18n instance which is casted to {@link VueI18n} type
  4395. *
  4396. * @VueI18nTip
  4397. * :new: provided by **vue-i18n-bridge only**
  4398. *
  4399. * @VueI18nGeneral
  4400. */
  4401. /* #__NO_SIDE_EFFECTS__ */
  4402. const castToVueI18n = (i18n
  4403. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4404. ) => {
  4405. if (!(__VUE_I18N_BRIDGE__ in i18n)) {
  4406. throw createI18nError(I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N);
  4407. }
  4408. return i18n;
  4409. };
  4410. function createGlobal(options, legacyMode, VueI18nLegacy // eslint-disable-line @typescript-eslint/no-explicit-any
  4411. ) {
  4412. const scope = effectScope();
  4413. {
  4414. const obj = legacyMode
  4415. ? scope.run(() => createVueI18n(options))
  4416. : scope.run(() => createComposer(options));
  4417. if (obj == null) {
  4418. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4419. }
  4420. return [scope, obj];
  4421. }
  4422. }
  4423. function getI18nInstance(instance) {
  4424. {
  4425. const i18n = inject(!instance.isCE
  4426. ? instance.appContext.app.__VUE_I18N_SYMBOL__
  4427. : I18nInjectionKey);
  4428. /* istanbul ignore if */
  4429. if (!i18n) {
  4430. throw createI18nError(!instance.isCE
  4431. ? I18nErrorCodes.UNEXPECTED_ERROR
  4432. : I18nErrorCodes.NOT_INSTALLED_WITH_PROVIDE);
  4433. }
  4434. return i18n;
  4435. }
  4436. }
  4437. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4438. function getScope(options, componentOptions) {
  4439. // prettier-ignore
  4440. return isEmptyObject(options)
  4441. ? ('__i18n' in componentOptions)
  4442. ? 'local'
  4443. : 'global'
  4444. : !options.useScope
  4445. ? 'local'
  4446. : options.useScope;
  4447. }
  4448. function getGlobalComposer(i18n) {
  4449. // prettier-ignore
  4450. return i18n.mode === 'composition'
  4451. ? i18n.global
  4452. : i18n.global.__composer
  4453. ;
  4454. }
  4455. function getComposer(i18n, target, useComponent = false) {
  4456. let composer = null;
  4457. const root = target.root;
  4458. let current = getParentComponentInstance(target, useComponent);
  4459. while (current != null) {
  4460. const i18nInternal = i18n;
  4461. if (i18n.mode === 'composition') {
  4462. composer = i18nInternal.__getInstance(current);
  4463. }
  4464. else {
  4465. {
  4466. const vueI18n = i18nInternal.__getInstance(current);
  4467. if (vueI18n != null) {
  4468. composer = vueI18n
  4469. .__composer;
  4470. if (useComponent &&
  4471. composer &&
  4472. !composer[InejctWithOptionSymbol] // eslint-disable-line @typescript-eslint/no-explicit-any
  4473. ) {
  4474. composer = null;
  4475. }
  4476. }
  4477. }
  4478. }
  4479. if (composer != null) {
  4480. break;
  4481. }
  4482. if (root === current) {
  4483. break;
  4484. }
  4485. current = current.parent;
  4486. }
  4487. return composer;
  4488. }
  4489. function getParentComponentInstance(target, useComponent = false) {
  4490. if (target == null) {
  4491. return null;
  4492. }
  4493. {
  4494. // if `useComponent: true` will be specified, we get lexical scope owner instance for use-case slots
  4495. return !useComponent
  4496. ? target.parent
  4497. : target.vnode.ctx || target.parent; // eslint-disable-line @typescript-eslint/no-explicit-any
  4498. }
  4499. }
  4500. function setupLifeCycle(i18n, target, composer) {
  4501. let emitter = null;
  4502. {
  4503. onMounted(() => {
  4504. // inject composer instance to DOM for intlify-devtools
  4505. if (target.vnode.el) {
  4506. target.vnode.el.__VUE_I18N__ = composer;
  4507. emitter = createEmitter();
  4508. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4509. const _composer = composer;
  4510. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  4511. emitter.on('*', addTimelineEvent);
  4512. }
  4513. }, target);
  4514. onUnmounted(() => {
  4515. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4516. const _composer = composer;
  4517. // remove composer instance from DOM for intlify-devtools
  4518. if (target.vnode.el &&
  4519. target.vnode.el.__VUE_I18N__) {
  4520. emitter && emitter.off('*', addTimelineEvent);
  4521. _composer[DisableEmitter] && _composer[DisableEmitter]();
  4522. delete target.vnode.el.__VUE_I18N__;
  4523. }
  4524. i18n.__deleteInstance(target);
  4525. // dispose extended resources
  4526. const dispose = _composer[DisposeSymbol];
  4527. if (dispose) {
  4528. dispose();
  4529. delete _composer[DisposeSymbol];
  4530. }
  4531. }, target);
  4532. }
  4533. }
  4534. function useI18nForLegacy(instance, scope, root, options = {} // eslint-disable-line @typescript-eslint/no-explicit-any
  4535. ) {
  4536. const isLocalScope = scope === 'local';
  4537. const _composer = shallowRef(null);
  4538. if (isLocalScope &&
  4539. instance.proxy &&
  4540. !(instance.proxy.$options.i18n || instance.proxy.$options.__i18n)) {
  4541. throw createI18nError(I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION);
  4542. }
  4543. const _inheritLocale = isBoolean(options.inheritLocale)
  4544. ? options.inheritLocale
  4545. : !isString(options.locale);
  4546. const _locale = ref(
  4547. // prettier-ignore
  4548. !isLocalScope || _inheritLocale
  4549. ? root.locale.value
  4550. : isString(options.locale)
  4551. ? options.locale
  4552. : DEFAULT_LOCALE);
  4553. const _fallbackLocale = ref(
  4554. // prettier-ignore
  4555. !isLocalScope || _inheritLocale
  4556. ? root.fallbackLocale.value
  4557. : isString(options.fallbackLocale) ||
  4558. isArray(options.fallbackLocale) ||
  4559. isPlainObject(options.fallbackLocale) ||
  4560. options.fallbackLocale === false
  4561. ? options.fallbackLocale
  4562. : _locale.value);
  4563. const _messages = ref(getLocaleMessages(_locale.value, options));
  4564. // prettier-ignore
  4565. const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
  4566. ? options.datetimeFormats
  4567. : { [_locale.value]: {} });
  4568. // prettier-ignore
  4569. const _numberFormats = ref(isPlainObject(options.numberFormats)
  4570. ? options.numberFormats
  4571. : { [_locale.value]: {} });
  4572. // prettier-ignore
  4573. const _missingWarn = isLocalScope
  4574. ? root.missingWarn
  4575. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  4576. ? options.missingWarn
  4577. : true;
  4578. // prettier-ignore
  4579. const _fallbackWarn = isLocalScope
  4580. ? root.fallbackWarn
  4581. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  4582. ? options.fallbackWarn
  4583. : true;
  4584. // prettier-ignore
  4585. const _fallbackRoot = isLocalScope
  4586. ? root.fallbackRoot
  4587. : isBoolean(options.fallbackRoot)
  4588. ? options.fallbackRoot
  4589. : true;
  4590. // configure fall back to root
  4591. const _fallbackFormat = !!options.fallbackFormat;
  4592. // runtime missing
  4593. const _missing = isFunction(options.missing) ? options.missing : null;
  4594. // postTranslation handler
  4595. const _postTranslation = isFunction(options.postTranslation)
  4596. ? options.postTranslation
  4597. : null;
  4598. // prettier-ignore
  4599. const _warnHtmlMessage = isLocalScope
  4600. ? root.warnHtmlMessage
  4601. : isBoolean(options.warnHtmlMessage)
  4602. ? options.warnHtmlMessage
  4603. : true;
  4604. const _escapeParameter = !!options.escapeParameter;
  4605. // prettier-ignore
  4606. const _modifiers = isLocalScope
  4607. ? root.modifiers
  4608. : isPlainObject(options.modifiers)
  4609. ? options.modifiers
  4610. : {};
  4611. // pluralRules
  4612. const _pluralRules = options.pluralRules || (isLocalScope && root.pluralRules);
  4613. // track reactivity
  4614. function trackReactivityValues() {
  4615. return [
  4616. _locale.value,
  4617. _fallbackLocale.value,
  4618. _messages.value,
  4619. _datetimeFormats.value,
  4620. _numberFormats.value
  4621. ];
  4622. }
  4623. // locale
  4624. const locale = computed({
  4625. get: () => {
  4626. return _composer.value ? _composer.value.locale.value : _locale.value;
  4627. },
  4628. set: val => {
  4629. if (_composer.value) {
  4630. _composer.value.locale.value = val;
  4631. }
  4632. _locale.value = val;
  4633. }
  4634. });
  4635. // fallbackLocale
  4636. const fallbackLocale = computed({
  4637. get: () => {
  4638. return _composer.value
  4639. ? _composer.value.fallbackLocale.value
  4640. : _fallbackLocale.value;
  4641. },
  4642. set: val => {
  4643. if (_composer.value) {
  4644. _composer.value.fallbackLocale.value = val;
  4645. }
  4646. _fallbackLocale.value = val;
  4647. }
  4648. });
  4649. // messages
  4650. const messages = computed(() => {
  4651. if (_composer.value) {
  4652. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4653. return _composer.value.messages.value;
  4654. }
  4655. else {
  4656. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4657. return _messages.value;
  4658. }
  4659. });
  4660. const datetimeFormats = computed(() => _datetimeFormats.value);
  4661. const numberFormats = computed(() => _numberFormats.value);
  4662. function getPostTranslationHandler() {
  4663. return _composer.value
  4664. ? _composer.value.getPostTranslationHandler()
  4665. : _postTranslation;
  4666. }
  4667. function setPostTranslationHandler(handler) {
  4668. if (_composer.value) {
  4669. _composer.value.setPostTranslationHandler(handler);
  4670. }
  4671. }
  4672. function getMissingHandler() {
  4673. return _composer.value ? _composer.value.getMissingHandler() : _missing;
  4674. }
  4675. function setMissingHandler(handler) {
  4676. if (_composer.value) {
  4677. _composer.value.setMissingHandler(handler);
  4678. }
  4679. }
  4680. function warpWithDeps(fn) {
  4681. trackReactivityValues();
  4682. return fn();
  4683. }
  4684. function t(...args) {
  4685. return _composer.value
  4686. ? warpWithDeps(() => Reflect.apply(_composer.value.t, null, [...args]))
  4687. : warpWithDeps(() => '');
  4688. }
  4689. function rt(...args) {
  4690. return _composer.value
  4691. ? Reflect.apply(_composer.value.rt, null, [...args])
  4692. : '';
  4693. }
  4694. function d(...args) {
  4695. return _composer.value
  4696. ? warpWithDeps(() => Reflect.apply(_composer.value.d, null, [...args]))
  4697. : warpWithDeps(() => '');
  4698. }
  4699. function n(...args) {
  4700. return _composer.value
  4701. ? warpWithDeps(() => Reflect.apply(_composer.value.n, null, [...args]))
  4702. : warpWithDeps(() => '');
  4703. }
  4704. function tm(key) {
  4705. return _composer.value ? _composer.value.tm(key) : {};
  4706. }
  4707. function te(key, locale) {
  4708. return _composer.value ? _composer.value.te(key, locale) : false;
  4709. }
  4710. function getLocaleMessage(locale) {
  4711. return _composer.value ? _composer.value.getLocaleMessage(locale) : {};
  4712. }
  4713. function setLocaleMessage(locale, message) {
  4714. if (_composer.value) {
  4715. _composer.value.setLocaleMessage(locale, message);
  4716. _messages.value[locale] = message;
  4717. }
  4718. }
  4719. function mergeLocaleMessage(locale, message) {
  4720. if (_composer.value) {
  4721. _composer.value.mergeLocaleMessage(locale, message);
  4722. }
  4723. }
  4724. function getDateTimeFormat(locale) {
  4725. return _composer.value ? _composer.value.getDateTimeFormat(locale) : {};
  4726. }
  4727. function setDateTimeFormat(locale, format) {
  4728. if (_composer.value) {
  4729. _composer.value.setDateTimeFormat(locale, format);
  4730. _datetimeFormats.value[locale] = format;
  4731. }
  4732. }
  4733. function mergeDateTimeFormat(locale, format) {
  4734. if (_composer.value) {
  4735. _composer.value.mergeDateTimeFormat(locale, format);
  4736. }
  4737. }
  4738. function getNumberFormat(locale) {
  4739. return _composer.value ? _composer.value.getNumberFormat(locale) : {};
  4740. }
  4741. function setNumberFormat(locale, format) {
  4742. if (_composer.value) {
  4743. _composer.value.setNumberFormat(locale, format);
  4744. _numberFormats.value[locale] = format;
  4745. }
  4746. }
  4747. function mergeNumberFormat(locale, format) {
  4748. if (_composer.value) {
  4749. _composer.value.mergeNumberFormat(locale, format);
  4750. }
  4751. }
  4752. const wrapper = {
  4753. get id() {
  4754. return _composer.value ? _composer.value.id : -1;
  4755. },
  4756. locale,
  4757. fallbackLocale,
  4758. messages,
  4759. datetimeFormats,
  4760. numberFormats,
  4761. get inheritLocale() {
  4762. return _composer.value ? _composer.value.inheritLocale : _inheritLocale;
  4763. },
  4764. set inheritLocale(val) {
  4765. if (_composer.value) {
  4766. _composer.value.inheritLocale = val;
  4767. }
  4768. },
  4769. get availableLocales() {
  4770. return _composer.value
  4771. ? _composer.value.availableLocales
  4772. : Object.keys(_messages.value);
  4773. },
  4774. get modifiers() {
  4775. return (_composer.value ? _composer.value.modifiers : _modifiers);
  4776. },
  4777. get pluralRules() {
  4778. return (_composer.value ? _composer.value.pluralRules : _pluralRules);
  4779. },
  4780. get isGlobal() {
  4781. return _composer.value ? _composer.value.isGlobal : false;
  4782. },
  4783. get missingWarn() {
  4784. return _composer.value ? _composer.value.missingWarn : _missingWarn;
  4785. },
  4786. set missingWarn(val) {
  4787. if (_composer.value) {
  4788. _composer.value.missingWarn = val;
  4789. }
  4790. },
  4791. get fallbackWarn() {
  4792. return _composer.value ? _composer.value.fallbackWarn : _fallbackWarn;
  4793. },
  4794. set fallbackWarn(val) {
  4795. if (_composer.value) {
  4796. _composer.value.missingWarn = val;
  4797. }
  4798. },
  4799. get fallbackRoot() {
  4800. return _composer.value ? _composer.value.fallbackRoot : _fallbackRoot;
  4801. },
  4802. set fallbackRoot(val) {
  4803. if (_composer.value) {
  4804. _composer.value.fallbackRoot = val;
  4805. }
  4806. },
  4807. get fallbackFormat() {
  4808. return _composer.value ? _composer.value.fallbackFormat : _fallbackFormat;
  4809. },
  4810. set fallbackFormat(val) {
  4811. if (_composer.value) {
  4812. _composer.value.fallbackFormat = val;
  4813. }
  4814. },
  4815. get warnHtmlMessage() {
  4816. return _composer.value
  4817. ? _composer.value.warnHtmlMessage
  4818. : _warnHtmlMessage;
  4819. },
  4820. set warnHtmlMessage(val) {
  4821. if (_composer.value) {
  4822. _composer.value.warnHtmlMessage = val;
  4823. }
  4824. },
  4825. get escapeParameter() {
  4826. return _composer.value
  4827. ? _composer.value.escapeParameter
  4828. : _escapeParameter;
  4829. },
  4830. set escapeParameter(val) {
  4831. if (_composer.value) {
  4832. _composer.value.escapeParameter = val;
  4833. }
  4834. },
  4835. t,
  4836. getPostTranslationHandler,
  4837. setPostTranslationHandler,
  4838. getMissingHandler,
  4839. setMissingHandler,
  4840. rt,
  4841. d,
  4842. n,
  4843. tm,
  4844. te,
  4845. getLocaleMessage,
  4846. setLocaleMessage,
  4847. mergeLocaleMessage,
  4848. getDateTimeFormat,
  4849. setDateTimeFormat,
  4850. mergeDateTimeFormat,
  4851. getNumberFormat,
  4852. setNumberFormat,
  4853. mergeNumberFormat
  4854. };
  4855. function sync(composer) {
  4856. composer.locale.value = _locale.value;
  4857. composer.fallbackLocale.value = _fallbackLocale.value;
  4858. Object.keys(_messages.value).forEach(locale => {
  4859. composer.mergeLocaleMessage(locale, _messages.value[locale]);
  4860. });
  4861. Object.keys(_datetimeFormats.value).forEach(locale => {
  4862. composer.mergeDateTimeFormat(locale, _datetimeFormats.value[locale]);
  4863. });
  4864. Object.keys(_numberFormats.value).forEach(locale => {
  4865. composer.mergeNumberFormat(locale, _numberFormats.value[locale]);
  4866. });
  4867. composer.escapeParameter = _escapeParameter;
  4868. composer.fallbackFormat = _fallbackFormat;
  4869. composer.fallbackRoot = _fallbackRoot;
  4870. composer.fallbackWarn = _fallbackWarn;
  4871. composer.missingWarn = _missingWarn;
  4872. composer.warnHtmlMessage = _warnHtmlMessage;
  4873. }
  4874. onBeforeMount(() => {
  4875. if (instance.proxy == null || instance.proxy.$i18n == null) {
  4876. throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY);
  4877. }
  4878. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4879. const composer = (_composer.value = instance.proxy.$i18n
  4880. .__composer);
  4881. if (scope === 'global') {
  4882. _locale.value = composer.locale.value;
  4883. _fallbackLocale.value = composer.fallbackLocale.value;
  4884. _messages.value = composer.messages.value;
  4885. _datetimeFormats.value = composer.datetimeFormats.value;
  4886. _numberFormats.value = composer.numberFormats.value;
  4887. }
  4888. else if (isLocalScope) {
  4889. sync(composer);
  4890. }
  4891. });
  4892. return wrapper;
  4893. }
  4894. const globalExportProps = [
  4895. 'locale',
  4896. 'fallbackLocale',
  4897. 'availableLocales'
  4898. ];
  4899. const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm', 'te']
  4900. ;
  4901. function injectGlobalFields(app, composer) {
  4902. const i18n = Object.create(null);
  4903. globalExportProps.forEach(prop => {
  4904. const desc = Object.getOwnPropertyDescriptor(composer, prop);
  4905. if (!desc) {
  4906. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4907. }
  4908. const wrap = isRef(desc.value) // check computed props
  4909. ? {
  4910. get() {
  4911. return desc.value.value;
  4912. },
  4913. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4914. set(val) {
  4915. desc.value.value = val;
  4916. }
  4917. }
  4918. : {
  4919. get() {
  4920. return desc.get && desc.get();
  4921. }
  4922. };
  4923. Object.defineProperty(i18n, prop, wrap);
  4924. });
  4925. app.config.globalProperties.$i18n = i18n;
  4926. globalExportMethods.forEach(method => {
  4927. const desc = Object.getOwnPropertyDescriptor(composer, method);
  4928. if (!desc || !desc.value) {
  4929. throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
  4930. }
  4931. Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
  4932. });
  4933. const dispose = () => {
  4934. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4935. delete app.config.globalProperties.$i18n;
  4936. globalExportMethods.forEach(method => {
  4937. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4938. delete app.config.globalProperties[`$${method}`];
  4939. });
  4940. };
  4941. return dispose;
  4942. }
  4943. // register message resolver at vue-i18n
  4944. registerMessageResolver(resolveValue);
  4945. // register fallback locale at vue-i18n
  4946. registerLocaleFallbacker(fallbackWithLocaleChain);
  4947. // NOTE: experimental !!
  4948. {
  4949. const target = getGlobalThis();
  4950. target.__INTLIFY__ = true;
  4951. setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
  4952. }
  4953. {
  4954. initDev();
  4955. }
  4956. export { DatetimeFormat, I18nD, I18nInjectionKey, I18nN, I18nT, NumberFormat, Translation, VERSION, castToVueI18n, createI18n, useI18n, vTDirective };