vue-i18n.runtime.global.js 165 KB

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