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

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