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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737
  1. /*!
  2. * vue-i18n v9.1.9
  3. * (c) 2021 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue';
  7. /**
  8. * Original Utilities
  9. * written by kazuya kawaguchi
  10. */
  11. const inBrowser = typeof window !== 'undefined';
  12. let mark;
  13. let measure;
  14. {
  15. const perf = inBrowser && window.performance;
  16. if (perf &&
  17. perf.mark &&
  18. perf.measure &&
  19. perf.clearMarks &&
  20. perf.clearMeasures) {
  21. mark = (tag) => perf.mark(tag);
  22. measure = (name, startTag, endTag) => {
  23. perf.measure(name, startTag, endTag);
  24. perf.clearMarks(startTag);
  25. perf.clearMarks(endTag);
  26. };
  27. }
  28. }
  29. const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
  30. /* eslint-disable */
  31. function format(message, ...args) {
  32. if (args.length === 1 && isObject(args[0])) {
  33. args = args[0];
  34. }
  35. if (!args || !args.hasOwnProperty) {
  36. args = {};
  37. }
  38. return message.replace(RE_ARGS, (match, identifier) => {
  39. return args.hasOwnProperty(identifier) ? args[identifier] : '';
  40. });
  41. }
  42. const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  43. const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
  44. const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
  45. const friendlyJSONstringify = (json) => JSON.stringify(json)
  46. .replace(/\u2028/g, '\\u2028')
  47. .replace(/\u2029/g, '\\u2029')
  48. .replace(/\u0027/g, '\\u0027');
  49. const isNumber = (val) => typeof val === 'number' && isFinite(val);
  50. const isDate = (val) => toTypeString(val) === '[object Date]';
  51. const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
  52. const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
  53. function warn(msg, err) {
  54. if (typeof console !== 'undefined') {
  55. console.warn(`[intlify] ` + msg);
  56. /* istanbul ignore if */
  57. if (err) {
  58. console.warn(err.stack);
  59. }
  60. }
  61. }
  62. const assign = Object.assign;
  63. let _globalThis;
  64. const getGlobalThis = () => {
  65. // prettier-ignore
  66. return (_globalThis ||
  67. (_globalThis =
  68. typeof globalThis !== 'undefined'
  69. ? globalThis
  70. : typeof self !== 'undefined'
  71. ? self
  72. : typeof window !== 'undefined'
  73. ? window
  74. : typeof global !== 'undefined'
  75. ? global
  76. : {}));
  77. };
  78. function escapeHtml(rawText) {
  79. return rawText
  80. .replace(/</g, '&lt;')
  81. .replace(/>/g, '&gt;')
  82. .replace(/"/g, '&quot;')
  83. .replace(/'/g, '&apos;');
  84. }
  85. const hasOwnProperty = Object.prototype.hasOwnProperty;
  86. function hasOwn(obj, key) {
  87. return hasOwnProperty.call(obj, key);
  88. }
  89. /* eslint-enable */
  90. /**
  91. * Useful Utilities By Evan you
  92. * Modified by kazuya kawaguchi
  93. * MIT License
  94. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
  95. * https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
  96. */
  97. const isArray = Array.isArray;
  98. const isFunction = (val) => typeof val === 'function';
  99. const isString = (val) => typeof val === 'string';
  100. const isBoolean = (val) => typeof val === 'boolean';
  101. const isObject = (val) => // eslint-disable-line
  102. val !== null && typeof val === 'object';
  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. const RANGE = 2;
  115. function generateCodeFrame(source, start = 0, end = source.length) {
  116. const lines = source.split(/\r?\n/);
  117. let count = 0;
  118. const res = [];
  119. for (let i = 0; i < lines.length; i++) {
  120. count += lines[i].length + 1;
  121. if (count >= start) {
  122. for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
  123. if (j < 0 || j >= lines.length)
  124. continue;
  125. const line = j + 1;
  126. res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
  127. const lineLength = lines[j].length;
  128. if (j === i) {
  129. // push underline
  130. const pad = start - (count - lineLength) + 1;
  131. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  132. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  133. }
  134. else if (j > i) {
  135. if (end > count) {
  136. const length = Math.max(Math.min(end - count, lineLength), 1);
  137. res.push(` | ` + '^'.repeat(length));
  138. }
  139. count += lineLength + 1;
  140. }
  141. }
  142. break;
  143. }
  144. }
  145. return res.join('\n');
  146. }
  147. /**
  148. * Event emitter, forked from the below:
  149. * - original repository url: https://github.com/developit/mitt
  150. * - code url: https://github.com/developit/mitt/blob/master/src/index.ts
  151. * - author: Jason Miller (https://github.com/developit)
  152. * - license: MIT
  153. */
  154. /**
  155. * Create a event emitter
  156. *
  157. * @returns An event emitter
  158. */
  159. function createEmitter() {
  160. const events = new Map();
  161. const emitter = {
  162. events,
  163. on(event, handler) {
  164. const handlers = events.get(event);
  165. const added = handlers && handlers.push(handler);
  166. if (!added) {
  167. events.set(event, [handler]);
  168. }
  169. },
  170. off(event, handler) {
  171. const handlers = events.get(event);
  172. if (handlers) {
  173. handlers.splice(handlers.indexOf(handler) >>> 0, 1);
  174. }
  175. },
  176. emit(event, payload) {
  177. (events.get(event) || [])
  178. .slice()
  179. .map(handler => handler(payload));
  180. (events.get('*') || [])
  181. .slice()
  182. .map(handler => handler(event, payload));
  183. }
  184. };
  185. return emitter;
  186. }
  187. const pathStateMachine = [];
  188. pathStateMachine[0 /* BEFORE_PATH */] = {
  189. ["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
  190. ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  191. ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
  192. ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
  193. };
  194. pathStateMachine[1 /* IN_PATH */] = {
  195. ["w" /* WORKSPACE */]: [1 /* IN_PATH */],
  196. ["." /* DOT */]: [2 /* BEFORE_IDENT */],
  197. ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
  198. ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
  199. };
  200. pathStateMachine[2 /* BEFORE_IDENT */] = {
  201. ["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
  202. ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  203. ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
  204. };
  205. pathStateMachine[3 /* IN_IDENT */] = {
  206. ["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  207. ["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
  208. ["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
  209. ["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
  210. ["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
  211. ["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
  212. };
  213. pathStateMachine[4 /* IN_SUB_PATH */] = {
  214. ["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
  215. ["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
  216. ["[" /* LEFT_BRACKET */]: [
  217. 4 /* IN_SUB_PATH */,
  218. 2 /* INC_SUB_PATH_DEPTH */
  219. ],
  220. ["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
  221. ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
  222. ["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
  223. };
  224. pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
  225. ["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
  226. ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
  227. ["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
  228. };
  229. pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
  230. ["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
  231. ["o" /* END_OF_FAIL */]: 8 /* ERROR */,
  232. ["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
  233. };
  234. /**
  235. * Check if an expression is a literal value.
  236. */
  237. const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
  238. function isLiteral(exp) {
  239. return literalValueRE.test(exp);
  240. }
  241. /**
  242. * Strip quotes from a string
  243. */
  244. function stripQuotes(str) {
  245. const a = str.charCodeAt(0);
  246. const b = str.charCodeAt(str.length - 1);
  247. return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
  248. }
  249. /**
  250. * Determine the type of a character in a keypath.
  251. */
  252. function getPathCharType(ch) {
  253. if (ch === undefined || ch === null) {
  254. return "o" /* END_OF_FAIL */;
  255. }
  256. const code = ch.charCodeAt(0);
  257. switch (code) {
  258. case 0x5b: // [
  259. case 0x5d: // ]
  260. case 0x2e: // .
  261. case 0x22: // "
  262. case 0x27: // '
  263. return ch;
  264. case 0x5f: // _
  265. case 0x24: // $
  266. case 0x2d: // -
  267. return "i" /* IDENT */;
  268. case 0x09: // Tab (HT)
  269. case 0x0a: // Newline (LF)
  270. case 0x0d: // Return (CR)
  271. case 0xa0: // No-break space (NBSP)
  272. case 0xfeff: // Byte Order Mark (BOM)
  273. case 0x2028: // Line Separator (LS)
  274. case 0x2029: // Paragraph Separator (PS)
  275. return "w" /* WORKSPACE */;
  276. }
  277. return "i" /* IDENT */;
  278. }
  279. /**
  280. * Format a subPath, return its plain form if it is
  281. * a literal string or number. Otherwise prepend the
  282. * dynamic indicator (*).
  283. */
  284. function formatSubPath(path) {
  285. const trimmed = path.trim();
  286. // invalid leading 0
  287. if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
  288. return false;
  289. }
  290. return isLiteral(trimmed)
  291. ? stripQuotes(trimmed)
  292. : "*" /* ASTARISK */ + trimmed;
  293. }
  294. /**
  295. * Parse a string path into an array of segments
  296. */
  297. function parse(path) {
  298. const keys = [];
  299. let index = -1;
  300. let mode = 0 /* BEFORE_PATH */;
  301. let subPathDepth = 0;
  302. let c;
  303. let key; // eslint-disable-line
  304. let newChar;
  305. let type;
  306. let transition;
  307. let action;
  308. let typeMap;
  309. const actions = [];
  310. actions[0 /* APPEND */] = () => {
  311. if (key === undefined) {
  312. key = newChar;
  313. }
  314. else {
  315. key += newChar;
  316. }
  317. };
  318. actions[1 /* PUSH */] = () => {
  319. if (key !== undefined) {
  320. keys.push(key);
  321. key = undefined;
  322. }
  323. };
  324. actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
  325. actions[0 /* APPEND */]();
  326. subPathDepth++;
  327. };
  328. actions[3 /* PUSH_SUB_PATH */] = () => {
  329. if (subPathDepth > 0) {
  330. subPathDepth--;
  331. mode = 4 /* IN_SUB_PATH */;
  332. actions[0 /* APPEND */]();
  333. }
  334. else {
  335. subPathDepth = 0;
  336. if (key === undefined) {
  337. return false;
  338. }
  339. key = formatSubPath(key);
  340. if (key === false) {
  341. return false;
  342. }
  343. else {
  344. actions[1 /* PUSH */]();
  345. }
  346. }
  347. };
  348. function maybeUnescapeQuote() {
  349. const nextChar = path[index + 1];
  350. if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
  351. nextChar === "'" /* SINGLE_QUOTE */) ||
  352. (mode === 6 /* IN_DOUBLE_QUOTE */ &&
  353. nextChar === "\"" /* DOUBLE_QUOTE */)) {
  354. index++;
  355. newChar = '\\' + nextChar;
  356. actions[0 /* APPEND */]();
  357. return true;
  358. }
  359. }
  360. while (mode !== null) {
  361. index++;
  362. c = path[index];
  363. if (c === '\\' && maybeUnescapeQuote()) {
  364. continue;
  365. }
  366. type = getPathCharType(c);
  367. typeMap = pathStateMachine[mode];
  368. transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
  369. // check parse error
  370. if (transition === 8 /* ERROR */) {
  371. return;
  372. }
  373. mode = transition[0];
  374. if (transition[1] !== undefined) {
  375. action = actions[transition[1]];
  376. if (action) {
  377. newChar = c;
  378. if (action() === false) {
  379. return;
  380. }
  381. }
  382. }
  383. // check parse finish
  384. if (mode === 7 /* AFTER_PATH */) {
  385. return keys;
  386. }
  387. }
  388. }
  389. // path token cache
  390. const cache = new Map();
  391. function resolveValue(obj, path) {
  392. // check object
  393. if (!isObject(obj)) {
  394. return null;
  395. }
  396. // parse path
  397. let hit = cache.get(path);
  398. if (!hit) {
  399. hit = parse(path);
  400. if (hit) {
  401. cache.set(path, hit);
  402. }
  403. }
  404. // check hit
  405. if (!hit) {
  406. return null;
  407. }
  408. // resolve path value
  409. const len = hit.length;
  410. let last = obj;
  411. let i = 0;
  412. while (i < len) {
  413. const val = last[hit[i]];
  414. if (val === undefined) {
  415. return null;
  416. }
  417. last = val;
  418. i++;
  419. }
  420. return last;
  421. }
  422. /**
  423. * Transform flat json in obj to normal json in obj
  424. */
  425. function handleFlatJson(obj) {
  426. // check obj
  427. if (!isObject(obj)) {
  428. return obj;
  429. }
  430. for (const key in obj) {
  431. // check key
  432. if (!hasOwn(obj, key)) {
  433. continue;
  434. }
  435. // handle for normal json
  436. if (!key.includes("." /* DOT */)) {
  437. // recursive process value if value is also a object
  438. if (isObject(obj[key])) {
  439. handleFlatJson(obj[key]);
  440. }
  441. }
  442. // handle for flat json, transform to normal json
  443. else {
  444. // go to the last object
  445. const subKeys = key.split("." /* DOT */);
  446. const lastIndex = subKeys.length - 1;
  447. let currentObj = obj;
  448. for (let i = 0; i < lastIndex; i++) {
  449. if (!(subKeys[i] in currentObj)) {
  450. currentObj[subKeys[i]] = {};
  451. }
  452. currentObj = currentObj[subKeys[i]];
  453. }
  454. // update last object value, delete old property
  455. currentObj[subKeys[lastIndex]] = obj[key];
  456. delete obj[key];
  457. // recursive process value if value is also a object
  458. if (isObject(currentObj[subKeys[lastIndex]])) {
  459. handleFlatJson(currentObj[subKeys[lastIndex]]);
  460. }
  461. }
  462. }
  463. return obj;
  464. }
  465. const DEFAULT_MODIFIER = (str) => str;
  466. const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
  467. const DEFAULT_MESSAGE_DATA_TYPE = 'text';
  468. const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
  469. const DEFAULT_INTERPOLATE = toDisplayString;
  470. function pluralDefault(choice, choicesLength) {
  471. choice = Math.abs(choice);
  472. if (choicesLength === 2) {
  473. // prettier-ignore
  474. return choice
  475. ? choice > 1
  476. ? 1
  477. : 0
  478. : 1;
  479. }
  480. return choice ? Math.min(choice, 2) : 0;
  481. }
  482. function getPluralIndex(options) {
  483. // prettier-ignore
  484. const index = isNumber(options.pluralIndex)
  485. ? options.pluralIndex
  486. : -1;
  487. // prettier-ignore
  488. return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
  489. ? isNumber(options.named.count)
  490. ? options.named.count
  491. : isNumber(options.named.n)
  492. ? options.named.n
  493. : index
  494. : index;
  495. }
  496. function normalizeNamed(pluralIndex, props) {
  497. if (!props.count) {
  498. props.count = pluralIndex;
  499. }
  500. if (!props.n) {
  501. props.n = pluralIndex;
  502. }
  503. }
  504. function createMessageContext(options = {}) {
  505. const locale = options.locale;
  506. const pluralIndex = getPluralIndex(options);
  507. const pluralRule = isObject(options.pluralRules) &&
  508. isString(locale) &&
  509. isFunction(options.pluralRules[locale])
  510. ? options.pluralRules[locale]
  511. : pluralDefault;
  512. const orgPluralRule = isObject(options.pluralRules) &&
  513. isString(locale) &&
  514. isFunction(options.pluralRules[locale])
  515. ? pluralDefault
  516. : undefined;
  517. const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
  518. const _list = options.list || [];
  519. const list = (index) => _list[index];
  520. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  521. const _named = options.named || {};
  522. isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
  523. const named = (key) => _named[key];
  524. // TODO: need to design resolve message function?
  525. function message(key) {
  526. // prettier-ignore
  527. const msg = isFunction(options.messages)
  528. ? options.messages(key)
  529. : isObject(options.messages)
  530. ? options.messages[key]
  531. : false;
  532. return !msg
  533. ? options.parent
  534. ? options.parent.message(key) // resolve from parent messages
  535. : DEFAULT_MESSAGE
  536. : msg;
  537. }
  538. const _modifier = (name) => options.modifiers
  539. ? options.modifiers[name]
  540. : DEFAULT_MODIFIER;
  541. const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
  542. ? options.processor.normalize
  543. : DEFAULT_NORMALIZE;
  544. const interpolate = isPlainObject(options.processor) &&
  545. isFunction(options.processor.interpolate)
  546. ? options.processor.interpolate
  547. : DEFAULT_INTERPOLATE;
  548. const type = isPlainObject(options.processor) && isString(options.processor.type)
  549. ? options.processor.type
  550. : DEFAULT_MESSAGE_DATA_TYPE;
  551. const ctx = {
  552. ["list" /* LIST */]: list,
  553. ["named" /* NAMED */]: named,
  554. ["plural" /* PLURAL */]: plural,
  555. ["linked" /* LINKED */]: (key, modifier) => {
  556. // TODO: should check `key`
  557. const msg = message(key)(ctx);
  558. return isString(modifier) ? _modifier(modifier)(msg) : msg;
  559. },
  560. ["message" /* MESSAGE */]: message,
  561. ["type" /* TYPE */]: type,
  562. ["interpolate" /* INTERPOLATE */]: interpolate,
  563. ["normalize" /* NORMALIZE */]: normalize
  564. };
  565. return ctx;
  566. }
  567. /** @internal */
  568. const errorMessages$2 = {
  569. // tokenizer error messages
  570. [0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`,
  571. [1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`,
  572. [2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`,
  573. [3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`,
  574. [4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`,
  575. [5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`,
  576. [6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`,
  577. [7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`,
  578. [8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`,
  579. [9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`,
  580. // parser error messages
  581. [10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`,
  582. [11 /* UNEXPECTED_EMPTY_LINKED_MODIFIER */]: `Unexpected empty linked modifier`,
  583. [12 /* UNEXPECTED_EMPTY_LINKED_KEY */]: `Unexpected empty linked key`,
  584. [13 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'`
  585. };
  586. function createCompileError(code, loc, options = {}) {
  587. const { domain, messages, args } = options;
  588. const msg = format((messages || errorMessages$2)[code] || '', ...(args || []))
  589. ;
  590. const error = new SyntaxError(String(msg));
  591. error.code = code;
  592. if (loc) {
  593. error.location = loc;
  594. }
  595. error.domain = domain;
  596. return error;
  597. }
  598. const IntlifyDevToolsHooks = {
  599. I18nInit: 'i18n:init',
  600. FunctionTranslate: 'function:translate'
  601. };
  602. let devtools = null;
  603. function setDevToolsHook(hook) {
  604. devtools = hook;
  605. }
  606. function initI18nDevTools(i18n, version, meta) {
  607. // TODO: queue if devtools is undefined
  608. devtools &&
  609. devtools.emit(IntlifyDevToolsHooks.I18nInit, {
  610. timestamp: Date.now(),
  611. i18n,
  612. version,
  613. meta
  614. });
  615. }
  616. const translateDevTools = /* #__PURE__*/ createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
  617. function createDevToolsHook(hook) {
  618. return (payloads) => devtools && devtools.emit(hook, payloads);
  619. }
  620. /** @internal */
  621. const warnMessages$1 = {
  622. [0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`,
  623. [1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`,
  624. [2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
  625. [3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`,
  626. [4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
  627. [5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.`
  628. };
  629. function getWarnMessage$1(code, ...args) {
  630. return format(warnMessages$1[code], ...args);
  631. }
  632. /**
  633. * Intlify core-base version
  634. * @internal
  635. */
  636. const VERSION$1 = '9.1.9';
  637. const NOT_REOSLVED = -1;
  638. const MISSING_RESOLVE_VALUE = '';
  639. function getDefaultLinkedModifiers() {
  640. return {
  641. upper: (val) => (isString(val) ? val.toUpperCase() : val),
  642. lower: (val) => (isString(val) ? val.toLowerCase() : val),
  643. // prettier-ignore
  644. capitalize: (val) => (isString(val)
  645. ? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
  646. : val)
  647. };
  648. }
  649. let _compiler;
  650. // Additional Meta for Intlify DevTools
  651. let _additionalMeta = null;
  652. const setAdditionalMeta = /* #__PURE__*/ (meta) => {
  653. _additionalMeta = meta;
  654. };
  655. const getAdditionalMeta = /* #__PURE__*/ () => _additionalMeta;
  656. // ID for CoreContext
  657. let _cid = 0;
  658. function createCoreContext(options = {}) {
  659. // setup options
  660. const version = isString(options.version) ? options.version : VERSION$1;
  661. const locale = isString(options.locale) ? options.locale : 'en-US';
  662. const fallbackLocale = isArray(options.fallbackLocale) ||
  663. isPlainObject(options.fallbackLocale) ||
  664. isString(options.fallbackLocale) ||
  665. options.fallbackLocale === false
  666. ? options.fallbackLocale
  667. : locale;
  668. const messages = isPlainObject(options.messages)
  669. ? options.messages
  670. : { [locale]: {} };
  671. const datetimeFormats = isPlainObject(options.datetimeFormats)
  672. ? options.datetimeFormats
  673. : { [locale]: {} };
  674. const numberFormats = isPlainObject(options.numberFormats)
  675. ? options.numberFormats
  676. : { [locale]: {} };
  677. const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
  678. const pluralRules = options.pluralRules || {};
  679. const missing = isFunction(options.missing) ? options.missing : null;
  680. const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  681. ? options.missingWarn
  682. : true;
  683. const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  684. ? options.fallbackWarn
  685. : true;
  686. const fallbackFormat = !!options.fallbackFormat;
  687. const unresolving = !!options.unresolving;
  688. const postTranslation = isFunction(options.postTranslation)
  689. ? options.postTranslation
  690. : null;
  691. const processor = isPlainObject(options.processor) ? options.processor : null;
  692. const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  693. ? options.warnHtmlMessage
  694. : true;
  695. const escapeParameter = !!options.escapeParameter;
  696. const messageCompiler = isFunction(options.messageCompiler)
  697. ? options.messageCompiler
  698. : _compiler;
  699. const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
  700. // setup internal options
  701. const internalOptions = options;
  702. const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
  703. ? internalOptions.__datetimeFormatters
  704. : new Map();
  705. const __numberFormatters = isObject(internalOptions.__numberFormatters)
  706. ? internalOptions.__numberFormatters
  707. : new Map();
  708. const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
  709. _cid++;
  710. const context = {
  711. version,
  712. cid: _cid,
  713. locale,
  714. fallbackLocale,
  715. messages,
  716. datetimeFormats,
  717. numberFormats,
  718. modifiers,
  719. pluralRules,
  720. missing,
  721. missingWarn,
  722. fallbackWarn,
  723. fallbackFormat,
  724. unresolving,
  725. postTranslation,
  726. processor,
  727. warnHtmlMessage,
  728. escapeParameter,
  729. messageCompiler,
  730. onWarn,
  731. __datetimeFormatters,
  732. __numberFormatters,
  733. __meta
  734. };
  735. // for vue-devtools timeline event
  736. {
  737. context.__v_emitter =
  738. internalOptions.__v_emitter != null
  739. ? internalOptions.__v_emitter
  740. : undefined;
  741. }
  742. // NOTE: experimental !!
  743. {
  744. initI18nDevTools(context, version, __meta);
  745. }
  746. return context;
  747. }
  748. /** @internal */
  749. function isTranslateFallbackWarn(fallback, key) {
  750. return fallback instanceof RegExp ? fallback.test(key) : fallback;
  751. }
  752. /** @internal */
  753. function isTranslateMissingWarn(missing, key) {
  754. return missing instanceof RegExp ? missing.test(key) : missing;
  755. }
  756. /** @internal */
  757. function handleMissing(context, key, locale, missingWarn, type) {
  758. const { missing, onWarn } = context;
  759. // for vue-devtools timeline event
  760. {
  761. const emitter = context.__v_emitter;
  762. if (emitter) {
  763. emitter.emit("missing" /* MISSING */, {
  764. locale,
  765. key,
  766. type,
  767. groupId: `${type}:${key}`
  768. });
  769. }
  770. }
  771. if (missing !== null) {
  772. const ret = missing(context, locale, key, type);
  773. return isString(ret) ? ret : key;
  774. }
  775. else {
  776. if (isTranslateMissingWarn(missingWarn, key)) {
  777. onWarn(getWarnMessage$1(0 /* NOT_FOUND_KEY */, { key, locale }));
  778. }
  779. return key;
  780. }
  781. }
  782. /** @internal */
  783. function getLocaleChain(ctx, fallback, start) {
  784. const context = ctx;
  785. if (!context.__localeChainCache) {
  786. context.__localeChainCache = new Map();
  787. }
  788. let chain = context.__localeChainCache.get(start);
  789. if (!chain) {
  790. chain = [];
  791. // first block defined by start
  792. let block = [start];
  793. // while any intervening block found
  794. while (isArray(block)) {
  795. block = appendBlockToChain(chain, block, fallback);
  796. }
  797. // prettier-ignore
  798. // last block defined by default
  799. const defaults = isArray(fallback)
  800. ? fallback
  801. : isPlainObject(fallback)
  802. ? fallback['default']
  803. ? fallback['default']
  804. : null
  805. : fallback;
  806. // convert defaults to array
  807. block = isString(defaults) ? [defaults] : defaults;
  808. if (isArray(block)) {
  809. appendBlockToChain(chain, block, false);
  810. }
  811. context.__localeChainCache.set(start, chain);
  812. }
  813. return chain;
  814. }
  815. function appendBlockToChain(chain, block, blocks) {
  816. let follow = true;
  817. for (let i = 0; i < block.length && isBoolean(follow); i++) {
  818. const locale = block[i];
  819. if (isString(locale)) {
  820. follow = appendLocaleToChain(chain, block[i], blocks);
  821. }
  822. }
  823. return follow;
  824. }
  825. function appendLocaleToChain(chain, locale, blocks) {
  826. let follow;
  827. const tokens = locale.split('-');
  828. do {
  829. const target = tokens.join('-');
  830. follow = appendItemToChain(chain, target, blocks);
  831. tokens.splice(-1, 1);
  832. } while (tokens.length && follow === true);
  833. return follow;
  834. }
  835. function appendItemToChain(chain, target, blocks) {
  836. let follow = false;
  837. if (!chain.includes(target)) {
  838. follow = true;
  839. if (target) {
  840. follow = target[target.length - 1] !== '!';
  841. const locale = target.replace(/!/g, '');
  842. chain.push(locale);
  843. if ((isArray(blocks) || isPlainObject(blocks)) &&
  844. blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
  845. ) {
  846. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  847. follow = blocks[locale];
  848. }
  849. }
  850. }
  851. return follow;
  852. }
  853. /** @internal */
  854. function updateFallbackLocale(ctx, locale, fallback) {
  855. const context = ctx;
  856. context.__localeChainCache = new Map();
  857. getLocaleChain(ctx, fallback, locale);
  858. }
  859. function createCoreError(code) {
  860. return createCompileError(code, null, { messages: errorMessages$1 } );
  861. }
  862. /** @internal */
  863. const errorMessages$1 = {
  864. [14 /* INVALID_ARGUMENT */]: 'Invalid arguments',
  865. [15 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' +
  866. 'Make sure your Date represents a valid date.',
  867. [16 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string'
  868. };
  869. const NOOP_MESSAGE_FUNCTION = () => '';
  870. const isMessageFunction = (val) => isFunction(val);
  871. // implementation of `translate` function
  872. function translate(context, ...args) {
  873. const { fallbackFormat, postTranslation, unresolving, fallbackLocale, messages } = context;
  874. const [key, options] = parseTranslateArgs(...args);
  875. const missingWarn = isBoolean(options.missingWarn)
  876. ? options.missingWarn
  877. : context.missingWarn;
  878. const fallbackWarn = isBoolean(options.fallbackWarn)
  879. ? options.fallbackWarn
  880. : context.fallbackWarn;
  881. const escapeParameter = isBoolean(options.escapeParameter)
  882. ? options.escapeParameter
  883. : context.escapeParameter;
  884. const resolvedMessage = !!options.resolvedMessage;
  885. // prettier-ignore
  886. const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
  887. ? !isBoolean(options.default)
  888. ? options.default
  889. : key
  890. : fallbackFormat // default by `fallbackFormat` option
  891. ? key
  892. : '';
  893. const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
  894. const locale = isString(options.locale) ? options.locale : context.locale;
  895. // escape params
  896. escapeParameter && escapeParams(options);
  897. // resolve message format
  898. // eslint-disable-next-line prefer-const
  899. let [format, targetLocale, message] = !resolvedMessage
  900. ? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
  901. : [
  902. key,
  903. locale,
  904. messages[locale] || {}
  905. ];
  906. // if you use default message, set it as message format!
  907. let cacheBaseKey = key;
  908. if (!resolvedMessage &&
  909. !(isString(format) || isMessageFunction(format))) {
  910. if (enableDefaultMsg) {
  911. format = defaultMsgOrKey;
  912. cacheBaseKey = format;
  913. }
  914. }
  915. // checking message format and target locale
  916. if (!resolvedMessage &&
  917. (!(isString(format) || isMessageFunction(format)) ||
  918. !isString(targetLocale))) {
  919. return unresolving ? NOT_REOSLVED : key;
  920. }
  921. if (isString(format) && context.messageCompiler == null) {
  922. warn(`The message format compilation is not supported in this build. ` +
  923. `Because message compiler isn't included. ` +
  924. `You need to pre-compilation all message format. ` +
  925. `So translate function return '${key}'.`);
  926. return key;
  927. }
  928. // setup compile error detecting
  929. let occurred = false;
  930. const errorDetector = () => {
  931. occurred = true;
  932. };
  933. // compile message format
  934. const msg = !isMessageFunction(format)
  935. ? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
  936. : format;
  937. // if occurred compile error, return the message format
  938. if (occurred) {
  939. return format;
  940. }
  941. // evaluate message with context
  942. const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
  943. const msgContext = createMessageContext(ctxOptions);
  944. const messaged = evaluateMessage(context, msg, msgContext);
  945. // if use post translation option, proceed it with handler
  946. const ret = postTranslation ? postTranslation(messaged) : messaged;
  947. // NOTE: experimental !!
  948. {
  949. // prettier-ignore
  950. const payloads = {
  951. timestamp: Date.now(),
  952. key: isString(key)
  953. ? key
  954. : isMessageFunction(format)
  955. ? format.key
  956. : '',
  957. locale: targetLocale || (isMessageFunction(format)
  958. ? format.locale
  959. : ''),
  960. format: isString(format)
  961. ? format
  962. : isMessageFunction(format)
  963. ? format.source
  964. : '',
  965. message: ret
  966. };
  967. payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
  968. translateDevTools(payloads);
  969. }
  970. return ret;
  971. }
  972. function escapeParams(options) {
  973. if (isArray(options.list)) {
  974. options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
  975. }
  976. else if (isObject(options.named)) {
  977. Object.keys(options.named).forEach(key => {
  978. if (isString(options.named[key])) {
  979. options.named[key] = escapeHtml(options.named[key]);
  980. }
  981. });
  982. }
  983. }
  984. function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
  985. const { messages, onWarn } = context;
  986. const locales = getLocaleChain(context, fallbackLocale, locale);
  987. let message = {};
  988. let targetLocale;
  989. let format = null;
  990. let from = locale;
  991. let to = null;
  992. const type = 'translate';
  993. for (let i = 0; i < locales.length; i++) {
  994. targetLocale = to = locales[i];
  995. if (locale !== targetLocale &&
  996. isTranslateFallbackWarn(fallbackWarn, key)) {
  997. onWarn(getWarnMessage$1(1 /* FALLBACK_TO_TRANSLATE */, {
  998. key,
  999. target: targetLocale
  1000. }));
  1001. }
  1002. // for vue-devtools timeline event
  1003. if (locale !== targetLocale) {
  1004. const emitter = context.__v_emitter;
  1005. if (emitter) {
  1006. emitter.emit("fallback" /* FALBACK */, {
  1007. type,
  1008. key,
  1009. from,
  1010. to,
  1011. groupId: `${type}:${key}`
  1012. });
  1013. }
  1014. }
  1015. message =
  1016. messages[targetLocale] || {};
  1017. // for vue-devtools timeline event
  1018. let start = null;
  1019. let startTag;
  1020. let endTag;
  1021. if (inBrowser) {
  1022. start = window.performance.now();
  1023. startTag = 'intlify-message-resolve-start';
  1024. endTag = 'intlify-message-resolve-end';
  1025. mark && mark(startTag);
  1026. }
  1027. if ((format = resolveValue(message, key)) === null) {
  1028. // if null, resolve with object key path
  1029. format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
  1030. }
  1031. // for vue-devtools timeline event
  1032. if (inBrowser) {
  1033. const end = window.performance.now();
  1034. const emitter = context.__v_emitter;
  1035. if (emitter && start && format) {
  1036. emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
  1037. type: "message-resolve" /* MESSAGE_RESOLVE */,
  1038. key,
  1039. message: format,
  1040. time: end - start,
  1041. groupId: `${type}:${key}`
  1042. });
  1043. }
  1044. if (startTag && endTag && mark && measure) {
  1045. mark(endTag);
  1046. measure('intlify message resolve', startTag, endTag);
  1047. }
  1048. }
  1049. if (isString(format) || isFunction(format))
  1050. break;
  1051. const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
  1052. if (missingRet !== key) {
  1053. format = missingRet;
  1054. }
  1055. from = to;
  1056. }
  1057. return [format, targetLocale, message];
  1058. }
  1059. function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
  1060. const { messageCompiler, warnHtmlMessage } = context;
  1061. if (isMessageFunction(format)) {
  1062. const msg = format;
  1063. msg.locale = msg.locale || targetLocale;
  1064. msg.key = msg.key || key;
  1065. return msg;
  1066. }
  1067. // for vue-devtools timeline event
  1068. let start = null;
  1069. let startTag;
  1070. let endTag;
  1071. if (inBrowser) {
  1072. start = window.performance.now();
  1073. startTag = 'intlify-message-compilation-start';
  1074. endTag = 'intlify-message-compilation-end';
  1075. mark && mark(startTag);
  1076. }
  1077. const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
  1078. // for vue-devtools timeline event
  1079. if (inBrowser) {
  1080. const end = window.performance.now();
  1081. const emitter = context.__v_emitter;
  1082. if (emitter && start) {
  1083. emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
  1084. type: "message-compilation" /* MESSAGE_COMPILATION */,
  1085. message: format,
  1086. time: end - start,
  1087. groupId: `${'translate'}:${key}`
  1088. });
  1089. }
  1090. if (startTag && endTag && mark && measure) {
  1091. mark(endTag);
  1092. measure('intlify message compilation', startTag, endTag);
  1093. }
  1094. }
  1095. msg.locale = targetLocale;
  1096. msg.key = key;
  1097. msg.source = format;
  1098. return msg;
  1099. }
  1100. function evaluateMessage(context, msg, msgCtx) {
  1101. // for vue-devtools timeline event
  1102. let start = null;
  1103. let startTag;
  1104. let endTag;
  1105. if (inBrowser) {
  1106. start = window.performance.now();
  1107. startTag = 'intlify-message-evaluation-start';
  1108. endTag = 'intlify-message-evaluation-end';
  1109. mark && mark(startTag);
  1110. }
  1111. const messaged = msg(msgCtx);
  1112. // for vue-devtools timeline event
  1113. if (inBrowser) {
  1114. const end = window.performance.now();
  1115. const emitter = context.__v_emitter;
  1116. if (emitter && start) {
  1117. emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
  1118. type: "message-evaluation" /* MESSAGE_EVALUATION */,
  1119. value: messaged,
  1120. time: end - start,
  1121. groupId: `${'translate'}:${msg.key}`
  1122. });
  1123. }
  1124. if (startTag && endTag && mark && measure) {
  1125. mark(endTag);
  1126. measure('intlify message evaluation', startTag, endTag);
  1127. }
  1128. }
  1129. return messaged;
  1130. }
  1131. /** @internal */
  1132. function parseTranslateArgs(...args) {
  1133. const [arg1, arg2, arg3] = args;
  1134. const options = {};
  1135. if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
  1136. throw createCoreError(14 /* INVALID_ARGUMENT */);
  1137. }
  1138. // prettier-ignore
  1139. const key = isNumber(arg1)
  1140. ? String(arg1)
  1141. : isMessageFunction(arg1)
  1142. ? arg1
  1143. : arg1;
  1144. if (isNumber(arg2)) {
  1145. options.plural = arg2;
  1146. }
  1147. else if (isString(arg2)) {
  1148. options.default = arg2;
  1149. }
  1150. else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
  1151. options.named = arg2;
  1152. }
  1153. else if (isArray(arg2)) {
  1154. options.list = arg2;
  1155. }
  1156. if (isNumber(arg3)) {
  1157. options.plural = arg3;
  1158. }
  1159. else if (isString(arg3)) {
  1160. options.default = arg3;
  1161. }
  1162. else if (isPlainObject(arg3)) {
  1163. assign(options, arg3);
  1164. }
  1165. return [key, options];
  1166. }
  1167. function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
  1168. return {
  1169. warnHtmlMessage,
  1170. onError: (err) => {
  1171. errorDetector && errorDetector(err);
  1172. {
  1173. const message = `Message compilation error: ${err.message}`;
  1174. const codeFrame = err.location &&
  1175. generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
  1176. const emitter = context
  1177. .__v_emitter;
  1178. if (emitter) {
  1179. emitter.emit("compile-error" /* COMPILE_ERROR */, {
  1180. message: source,
  1181. error: err.message,
  1182. start: err.location && err.location.start.offset,
  1183. end: err.location && err.location.end.offset,
  1184. groupId: `${'translate'}:${key}`
  1185. });
  1186. }
  1187. console.error(codeFrame ? `${message}\n${codeFrame}` : message);
  1188. }
  1189. },
  1190. onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
  1191. };
  1192. }
  1193. function getMessageContextOptions(context, locale, message, options) {
  1194. const { modifiers, pluralRules } = context;
  1195. const resolveMessage = (key) => {
  1196. const val = resolveValue(message, key);
  1197. if (isString(val)) {
  1198. let occurred = false;
  1199. const errorDetector = () => {
  1200. occurred = true;
  1201. };
  1202. const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
  1203. return !occurred
  1204. ? msg
  1205. : NOOP_MESSAGE_FUNCTION;
  1206. }
  1207. else if (isMessageFunction(val)) {
  1208. return val;
  1209. }
  1210. else {
  1211. // TODO: should be implemented warning message
  1212. return NOOP_MESSAGE_FUNCTION;
  1213. }
  1214. };
  1215. const ctxOptions = {
  1216. locale,
  1217. modifiers,
  1218. pluralRules,
  1219. messages: resolveMessage
  1220. };
  1221. if (context.processor) {
  1222. ctxOptions.processor = context.processor;
  1223. }
  1224. if (options.list) {
  1225. ctxOptions.list = options.list;
  1226. }
  1227. if (options.named) {
  1228. ctxOptions.named = options.named;
  1229. }
  1230. if (isNumber(options.plural)) {
  1231. ctxOptions.pluralIndex = options.plural;
  1232. }
  1233. return ctxOptions;
  1234. }
  1235. const intlDefined = typeof Intl !== 'undefined';
  1236. const Availabilities = {
  1237. dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
  1238. numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
  1239. };
  1240. // implementation of `datetime` function
  1241. function datetime(context, ...args) {
  1242. const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context;
  1243. const { __datetimeFormatters } = context;
  1244. if (!Availabilities.dateTimeFormat) {
  1245. onWarn(getWarnMessage$1(4 /* CANNOT_FORMAT_DATE */));
  1246. return MISSING_RESOLVE_VALUE;
  1247. }
  1248. const [key, value, options, overrides] = parseDateTimeArgs(...args);
  1249. const missingWarn = isBoolean(options.missingWarn)
  1250. ? options.missingWarn
  1251. : context.missingWarn;
  1252. const fallbackWarn = isBoolean(options.fallbackWarn)
  1253. ? options.fallbackWarn
  1254. : context.fallbackWarn;
  1255. const part = !!options.part;
  1256. const locale = isString(options.locale) ? options.locale : context.locale;
  1257. const locales = getLocaleChain(context, fallbackLocale, locale);
  1258. if (!isString(key) || key === '') {
  1259. return new Intl.DateTimeFormat(locale).format(value);
  1260. }
  1261. // resolve format
  1262. let datetimeFormat = {};
  1263. let targetLocale;
  1264. let format = null;
  1265. let from = locale;
  1266. let to = null;
  1267. const type = 'datetime format';
  1268. for (let i = 0; i < locales.length; i++) {
  1269. targetLocale = to = locales[i];
  1270. if (locale !== targetLocale &&
  1271. isTranslateFallbackWarn(fallbackWarn, key)) {
  1272. onWarn(getWarnMessage$1(5 /* FALLBACK_TO_DATE_FORMAT */, {
  1273. key,
  1274. target: targetLocale
  1275. }));
  1276. }
  1277. // for vue-devtools timeline event
  1278. if (locale !== targetLocale) {
  1279. const emitter = context.__v_emitter;
  1280. if (emitter) {
  1281. emitter.emit("fallback" /* FALBACK */, {
  1282. type,
  1283. key,
  1284. from,
  1285. to,
  1286. groupId: `${type}:${key}`
  1287. });
  1288. }
  1289. }
  1290. datetimeFormat =
  1291. datetimeFormats[targetLocale] || {};
  1292. format = datetimeFormat[key];
  1293. if (isPlainObject(format))
  1294. break;
  1295. handleMissing(context, key, targetLocale, missingWarn, type);
  1296. from = to;
  1297. }
  1298. // checking format and target locale
  1299. if (!isPlainObject(format) || !isString(targetLocale)) {
  1300. return unresolving ? NOT_REOSLVED : key;
  1301. }
  1302. let id = `${targetLocale}__${key}`;
  1303. if (!isEmptyObject(overrides)) {
  1304. id = `${id}__${JSON.stringify(overrides)}`;
  1305. }
  1306. let formatter = __datetimeFormatters.get(id);
  1307. if (!formatter) {
  1308. formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
  1309. __datetimeFormatters.set(id, formatter);
  1310. }
  1311. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1312. }
  1313. /** @internal */
  1314. function parseDateTimeArgs(...args) {
  1315. const [arg1, arg2, arg3, arg4] = args;
  1316. let options = {};
  1317. let overrides = {};
  1318. let value;
  1319. if (isString(arg1)) {
  1320. // Only allow ISO strings - other date formats are often supported,
  1321. // but may cause different results in different browsers.
  1322. if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
  1323. throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
  1324. }
  1325. value = new Date(arg1);
  1326. try {
  1327. // This will fail if the date is not valid
  1328. value.toISOString();
  1329. }
  1330. catch (e) {
  1331. throw createCoreError(16 /* INVALID_ISO_DATE_ARGUMENT */);
  1332. }
  1333. }
  1334. else if (isDate(arg1)) {
  1335. if (isNaN(arg1.getTime())) {
  1336. throw createCoreError(15 /* INVALID_DATE_ARGUMENT */);
  1337. }
  1338. value = arg1;
  1339. }
  1340. else if (isNumber(arg1)) {
  1341. value = arg1;
  1342. }
  1343. else {
  1344. throw createCoreError(14 /* INVALID_ARGUMENT */);
  1345. }
  1346. if (isString(arg2)) {
  1347. options.key = arg2;
  1348. }
  1349. else if (isPlainObject(arg2)) {
  1350. options = arg2;
  1351. }
  1352. if (isString(arg3)) {
  1353. options.locale = arg3;
  1354. }
  1355. else if (isPlainObject(arg3)) {
  1356. overrides = arg3;
  1357. }
  1358. if (isPlainObject(arg4)) {
  1359. overrides = arg4;
  1360. }
  1361. return [options.key || '', value, options, overrides];
  1362. }
  1363. /** @internal */
  1364. function clearDateTimeFormat(ctx, locale, format) {
  1365. const context = ctx;
  1366. for (const key in format) {
  1367. const id = `${locale}__${key}`;
  1368. if (!context.__datetimeFormatters.has(id)) {
  1369. continue;
  1370. }
  1371. context.__datetimeFormatters.delete(id);
  1372. }
  1373. }
  1374. // implementation of `number` function
  1375. function number(context, ...args) {
  1376. const { numberFormats, unresolving, fallbackLocale, onWarn } = context;
  1377. const { __numberFormatters } = context;
  1378. if (!Availabilities.numberFormat) {
  1379. onWarn(getWarnMessage$1(2 /* CANNOT_FORMAT_NUMBER */));
  1380. return MISSING_RESOLVE_VALUE;
  1381. }
  1382. const [key, value, options, overrides] = parseNumberArgs(...args);
  1383. const missingWarn = isBoolean(options.missingWarn)
  1384. ? options.missingWarn
  1385. : context.missingWarn;
  1386. const fallbackWarn = isBoolean(options.fallbackWarn)
  1387. ? options.fallbackWarn
  1388. : context.fallbackWarn;
  1389. const part = !!options.part;
  1390. const locale = isString(options.locale) ? options.locale : context.locale;
  1391. const locales = getLocaleChain(context, fallbackLocale, locale);
  1392. if (!isString(key) || key === '') {
  1393. return new Intl.NumberFormat(locale).format(value);
  1394. }
  1395. // resolve format
  1396. let numberFormat = {};
  1397. let targetLocale;
  1398. let format = null;
  1399. let from = locale;
  1400. let to = null;
  1401. const type = 'number format';
  1402. for (let i = 0; i < locales.length; i++) {
  1403. targetLocale = to = locales[i];
  1404. if (locale !== targetLocale &&
  1405. isTranslateFallbackWarn(fallbackWarn, key)) {
  1406. onWarn(getWarnMessage$1(3 /* FALLBACK_TO_NUMBER_FORMAT */, {
  1407. key,
  1408. target: targetLocale
  1409. }));
  1410. }
  1411. // for vue-devtools timeline event
  1412. if (locale !== targetLocale) {
  1413. const emitter = context.__v_emitter;
  1414. if (emitter) {
  1415. emitter.emit("fallback" /* FALBACK */, {
  1416. type,
  1417. key,
  1418. from,
  1419. to,
  1420. groupId: `${type}:${key}`
  1421. });
  1422. }
  1423. }
  1424. numberFormat =
  1425. numberFormats[targetLocale] || {};
  1426. format = numberFormat[key];
  1427. if (isPlainObject(format))
  1428. break;
  1429. handleMissing(context, key, targetLocale, missingWarn, type);
  1430. from = to;
  1431. }
  1432. // checking format and target locale
  1433. if (!isPlainObject(format) || !isString(targetLocale)) {
  1434. return unresolving ? NOT_REOSLVED : key;
  1435. }
  1436. let id = `${targetLocale}__${key}`;
  1437. if (!isEmptyObject(overrides)) {
  1438. id = `${id}__${JSON.stringify(overrides)}`;
  1439. }
  1440. let formatter = __numberFormatters.get(id);
  1441. if (!formatter) {
  1442. formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
  1443. __numberFormatters.set(id, formatter);
  1444. }
  1445. return !part ? formatter.format(value) : formatter.formatToParts(value);
  1446. }
  1447. /** @internal */
  1448. function parseNumberArgs(...args) {
  1449. const [arg1, arg2, arg3, arg4] = args;
  1450. let options = {};
  1451. let overrides = {};
  1452. if (!isNumber(arg1)) {
  1453. throw createCoreError(14 /* INVALID_ARGUMENT */);
  1454. }
  1455. const value = arg1;
  1456. if (isString(arg2)) {
  1457. options.key = arg2;
  1458. }
  1459. else if (isPlainObject(arg2)) {
  1460. options = arg2;
  1461. }
  1462. if (isString(arg3)) {
  1463. options.locale = arg3;
  1464. }
  1465. else if (isPlainObject(arg3)) {
  1466. overrides = arg3;
  1467. }
  1468. if (isPlainObject(arg4)) {
  1469. overrides = arg4;
  1470. }
  1471. return [options.key || '', value, options, overrides];
  1472. }
  1473. /** @internal */
  1474. function clearNumberFormat(ctx, locale, format) {
  1475. const context = ctx;
  1476. for (const key in format) {
  1477. const id = `${locale}__${key}`;
  1478. if (!context.__numberFormatters.has(id)) {
  1479. continue;
  1480. }
  1481. context.__numberFormatters.delete(id);
  1482. }
  1483. }
  1484. /**
  1485. * Vue I18n Version
  1486. *
  1487. * @remarks
  1488. * Semver format. Same format as the package.json `version` field.
  1489. *
  1490. * @VueI18nGeneral
  1491. */
  1492. const VERSION = '9.1.9';
  1493. /**
  1494. * This is only called development env
  1495. * istanbul-ignore-next
  1496. */
  1497. function initDev() {
  1498. {
  1499. {
  1500. console.info(`You are running a development build of vue-i18n.\n` +
  1501. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  1502. }
  1503. }
  1504. }
  1505. const warnMessages = {
  1506. [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`,
  1507. [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`,
  1508. [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`,
  1509. [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`,
  1510. [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`,
  1511. [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`,
  1512. [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.`
  1513. };
  1514. function getWarnMessage(code, ...args) {
  1515. return format(warnMessages[code], ...args);
  1516. }
  1517. function createI18nError(code, ...args) {
  1518. return createCompileError(code, null, { messages: errorMessages, args } );
  1519. }
  1520. const errorMessages = {
  1521. [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer',
  1522. [15 /* INVALID_ARGUMENT */]: 'Invalid argument',
  1523. [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function',
  1524. [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function',
  1525. [22 /* UNEXPECTED_ERROR */]: 'Unexpected error',
  1526. [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode',
  1527. [19 /* REQUIRED_VALUE */]: `Required in value: {0}`,
  1528. [20 /* INVALID_VALUE */]: `Invalid value`,
  1529. [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin`
  1530. };
  1531. const DEVTOOLS_META = '__INTLIFY_META__';
  1532. const TransrateVNodeSymbol = makeSymbol('__transrateVNode');
  1533. const DatetimePartsSymbol = makeSymbol('__datetimeParts');
  1534. const NumberPartsSymbol = makeSymbol('__numberParts');
  1535. const EnableEmitter = makeSymbol('__enableEmitter');
  1536. const DisableEmitter = makeSymbol('__disableEmitter');
  1537. const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
  1538. const InejctWithOption = makeSymbol('__injectWithOption');
  1539. let composerID = 0;
  1540. function defineCoreMissingHandler(missing) {
  1541. return ((ctx, locale, key, type) => {
  1542. return missing(locale, key, getCurrentInstance() || undefined, type);
  1543. });
  1544. }
  1545. function getLocaleMessages(locale, options) {
  1546. const { messages, __i18n } = options;
  1547. // prettier-ignore
  1548. const ret = isPlainObject(messages)
  1549. ? messages
  1550. : isArray(__i18n)
  1551. ? {}
  1552. : { [locale]: {} };
  1553. // merge locale messages of i18n custom block
  1554. if (isArray(__i18n)) {
  1555. __i18n.forEach(({ locale, resource }) => {
  1556. if (locale) {
  1557. ret[locale] = ret[locale] || {};
  1558. deepCopy(resource, ret[locale]);
  1559. }
  1560. else {
  1561. deepCopy(resource, ret);
  1562. }
  1563. });
  1564. }
  1565. // handle messages for flat json
  1566. if (options.flatJson) {
  1567. for (const key in ret) {
  1568. if (hasOwn(ret, key)) {
  1569. handleFlatJson(ret[key]);
  1570. }
  1571. }
  1572. }
  1573. return ret;
  1574. }
  1575. const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
  1576. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1577. function deepCopy(src, des) {
  1578. // src and des should both be objects, and non of then can be a array
  1579. if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
  1580. throw createI18nError(20 /* INVALID_VALUE */);
  1581. }
  1582. for (const key in src) {
  1583. if (hasOwn(src, key)) {
  1584. if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
  1585. // replace with src[key] when:
  1586. // src[key] or des[key] is not a object, or
  1587. // src[key] or des[key] is a array
  1588. des[key] = src[key];
  1589. }
  1590. else {
  1591. // src[key] and des[key] are both object, merge them
  1592. deepCopy(src[key], des[key]);
  1593. }
  1594. }
  1595. }
  1596. }
  1597. // for Intlify DevTools
  1598. const getMetaInfo = /* #__PURE__*/ () => {
  1599. const instance = getCurrentInstance();
  1600. return instance && instance.type[DEVTOOLS_META] // eslint-disable-line @typescript-eslint/no-explicit-any
  1601. ? { [DEVTOOLS_META]: instance.type[DEVTOOLS_META] } // eslint-disable-line @typescript-eslint/no-explicit-any
  1602. : null;
  1603. };
  1604. /**
  1605. * Create composer interface factory
  1606. *
  1607. * @internal
  1608. */
  1609. function createComposer(options = {}) {
  1610. const { __root } = options;
  1611. const _isGlobal = __root === undefined;
  1612. let _inheritLocale = isBoolean(options.inheritLocale)
  1613. ? options.inheritLocale
  1614. : true;
  1615. const _locale = ref(
  1616. // prettier-ignore
  1617. __root && _inheritLocale
  1618. ? __root.locale.value
  1619. : isString(options.locale)
  1620. ? options.locale
  1621. : 'en-US');
  1622. const _fallbackLocale = ref(
  1623. // prettier-ignore
  1624. __root && _inheritLocale
  1625. ? __root.fallbackLocale.value
  1626. : isString(options.fallbackLocale) ||
  1627. isArray(options.fallbackLocale) ||
  1628. isPlainObject(options.fallbackLocale) ||
  1629. options.fallbackLocale === false
  1630. ? options.fallbackLocale
  1631. : _locale.value);
  1632. const _messages = ref(getLocaleMessages(_locale.value, options));
  1633. const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
  1634. ? options.datetimeFormats
  1635. : { [_locale.value]: {} });
  1636. const _numberFormats = ref(isPlainObject(options.numberFormats)
  1637. ? options.numberFormats
  1638. : { [_locale.value]: {} });
  1639. // warning suppress options
  1640. // prettier-ignore
  1641. let _missingWarn = __root
  1642. ? __root.missingWarn
  1643. : isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
  1644. ? options.missingWarn
  1645. : true;
  1646. // prettier-ignore
  1647. let _fallbackWarn = __root
  1648. ? __root.fallbackWarn
  1649. : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
  1650. ? options.fallbackWarn
  1651. : true;
  1652. // prettier-ignore
  1653. let _fallbackRoot = __root
  1654. ? __root.fallbackRoot
  1655. : isBoolean(options.fallbackRoot)
  1656. ? options.fallbackRoot
  1657. : true;
  1658. // configure fall back to root
  1659. let _fallbackFormat = !!options.fallbackFormat;
  1660. // runtime missing
  1661. let _missing = isFunction(options.missing) ? options.missing : null;
  1662. let _runtimeMissing = isFunction(options.missing)
  1663. ? defineCoreMissingHandler(options.missing)
  1664. : null;
  1665. // postTranslation handler
  1666. let _postTranslation = isFunction(options.postTranslation)
  1667. ? options.postTranslation
  1668. : null;
  1669. let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
  1670. ? options.warnHtmlMessage
  1671. : true;
  1672. let _escapeParameter = !!options.escapeParameter;
  1673. // custom linked modifiers
  1674. // prettier-ignore
  1675. const _modifiers = __root
  1676. ? __root.modifiers
  1677. : isPlainObject(options.modifiers)
  1678. ? options.modifiers
  1679. : {};
  1680. // pluralRules
  1681. let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
  1682. // runtime context
  1683. // eslint-disable-next-line prefer-const
  1684. let _context;
  1685. function getCoreContext() {
  1686. return createCoreContext({
  1687. version: VERSION,
  1688. locale: _locale.value,
  1689. fallbackLocale: _fallbackLocale.value,
  1690. messages: _messages.value,
  1691. datetimeFormats: _datetimeFormats.value,
  1692. numberFormats: _numberFormats.value,
  1693. modifiers: _modifiers,
  1694. pluralRules: _pluralRules,
  1695. missing: _runtimeMissing === null ? undefined : _runtimeMissing,
  1696. missingWarn: _missingWarn,
  1697. fallbackWarn: _fallbackWarn,
  1698. fallbackFormat: _fallbackFormat,
  1699. unresolving: true,
  1700. postTranslation: _postTranslation === null ? undefined : _postTranslation,
  1701. warnHtmlMessage: _warnHtmlMessage,
  1702. escapeParameter: _escapeParameter,
  1703. __datetimeFormatters: isPlainObject(_context)
  1704. ? _context.__datetimeFormatters
  1705. : undefined,
  1706. __numberFormatters: isPlainObject(_context)
  1707. ? _context.__numberFormatters
  1708. : undefined,
  1709. __v_emitter: isPlainObject(_context)
  1710. ? _context.__v_emitter
  1711. : undefined,
  1712. __meta: { framework: 'vue' }
  1713. });
  1714. }
  1715. _context = getCoreContext();
  1716. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  1717. // track reactivity
  1718. function trackReactivityValues() {
  1719. return [
  1720. _locale.value,
  1721. _fallbackLocale.value,
  1722. _messages.value,
  1723. _datetimeFormats.value,
  1724. _numberFormats.value
  1725. ];
  1726. }
  1727. // locale
  1728. const locale = computed({
  1729. get: () => _locale.value,
  1730. set: val => {
  1731. _locale.value = val;
  1732. _context.locale = _locale.value;
  1733. }
  1734. });
  1735. // fallbackLocale
  1736. const fallbackLocale = computed({
  1737. get: () => _fallbackLocale.value,
  1738. set: val => {
  1739. _fallbackLocale.value = val;
  1740. _context.fallbackLocale = _fallbackLocale.value;
  1741. updateFallbackLocale(_context, _locale.value, val);
  1742. }
  1743. });
  1744. // messages
  1745. const messages = computed(() => _messages.value);
  1746. // datetimeFormats
  1747. const datetimeFormats = computed(() => _datetimeFormats.value);
  1748. // numberFormats
  1749. const numberFormats = computed(() => _numberFormats.value);
  1750. // getPostTranslationHandler
  1751. function getPostTranslationHandler() {
  1752. return isFunction(_postTranslation) ? _postTranslation : null;
  1753. }
  1754. // setPostTranslationHandler
  1755. function setPostTranslationHandler(handler) {
  1756. _postTranslation = handler;
  1757. _context.postTranslation = handler;
  1758. }
  1759. // getMissingHandler
  1760. function getMissingHandler() {
  1761. return _missing;
  1762. }
  1763. // setMissingHandler
  1764. function setMissingHandler(handler) {
  1765. if (handler !== null) {
  1766. _runtimeMissing = defineCoreMissingHandler(handler);
  1767. }
  1768. _missing = handler;
  1769. _context.missing = _runtimeMissing;
  1770. }
  1771. function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
  1772. ) {
  1773. return type !== 'translate' || !!arg.resolvedMessage === false;
  1774. }
  1775. function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
  1776. trackReactivityValues(); // track reactive dependency
  1777. // NOTE: experimental !!
  1778. let ret;
  1779. {
  1780. try {
  1781. setAdditionalMeta(getMetaInfo());
  1782. ret = fn(_context);
  1783. }
  1784. finally {
  1785. setAdditionalMeta(null);
  1786. }
  1787. }
  1788. if (isNumber(ret) && ret === NOT_REOSLVED) {
  1789. const [key, arg2] = argumentParser();
  1790. if (__root &&
  1791. isString(key) &&
  1792. isResolvedTranslateMessage(warnType, arg2)) {
  1793. if (_fallbackRoot &&
  1794. (isTranslateFallbackWarn(_fallbackWarn, key) ||
  1795. isTranslateMissingWarn(_missingWarn, key))) {
  1796. warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, {
  1797. key,
  1798. type: warnType
  1799. }));
  1800. }
  1801. // for vue-devtools timeline event
  1802. {
  1803. const { __v_emitter: emitter } = _context;
  1804. if (emitter && _fallbackRoot) {
  1805. emitter.emit("fallback" /* FALBACK */, {
  1806. type: warnType,
  1807. key,
  1808. to: 'global',
  1809. groupId: `${warnType}:${key}`
  1810. });
  1811. }
  1812. }
  1813. }
  1814. return __root && _fallbackRoot
  1815. ? fallbackSuccess(__root)
  1816. : fallbackFail(key);
  1817. }
  1818. else if (successCondition(ret)) {
  1819. return ret;
  1820. }
  1821. else {
  1822. /* istanbul ignore next */
  1823. throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */);
  1824. }
  1825. }
  1826. // t
  1827. function t(...args) {
  1828. return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args), 'translate', root => root.t(...args), key => key, val => isString(val));
  1829. }
  1830. // rt
  1831. function rt(...args) {
  1832. const [arg1, arg2, arg3] = args;
  1833. if (arg3 && !isObject(arg3)) {
  1834. throw createI18nError(15 /* INVALID_ARGUMENT */);
  1835. }
  1836. return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
  1837. }
  1838. // d
  1839. function d(...args) {
  1840. return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
  1841. }
  1842. // n
  1843. function n(...args) {
  1844. return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
  1845. }
  1846. // for custom processor
  1847. function normalize(values) {
  1848. return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val);
  1849. }
  1850. const interpolate = (val) => val;
  1851. const processor = {
  1852. normalize,
  1853. interpolate,
  1854. type: 'vnode'
  1855. };
  1856. // transrateVNode, using for `i18n-t` component
  1857. function transrateVNode(...args) {
  1858. return wrapWithDeps(context => {
  1859. let ret;
  1860. const _context = context;
  1861. try {
  1862. _context.processor = processor;
  1863. ret = translate(_context, ...args);
  1864. }
  1865. finally {
  1866. _context.processor = null;
  1867. }
  1868. return ret;
  1869. }, () => parseTranslateArgs(...args), 'translate',
  1870. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1871. root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val));
  1872. }
  1873. // numberParts, using for `i18n-n` component
  1874. function numberParts(...args) {
  1875. return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args), 'number format',
  1876. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1877. root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val));
  1878. }
  1879. // datetimeParts, using for `i18n-d` component
  1880. function datetimeParts(...args) {
  1881. return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args), 'datetime format',
  1882. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1883. root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val));
  1884. }
  1885. function setPluralRules(rules) {
  1886. _pluralRules = rules;
  1887. _context.pluralRules = _pluralRules;
  1888. }
  1889. // te
  1890. function te(key, locale) {
  1891. const targetLocale = isString(locale) ? locale : _locale.value;
  1892. const message = getLocaleMessage(targetLocale);
  1893. return resolveValue(message, key) !== null;
  1894. }
  1895. function resolveMessages(key) {
  1896. let messages = null;
  1897. const locales = getLocaleChain(_context, _fallbackLocale.value, _locale.value);
  1898. for (let i = 0; i < locales.length; i++) {
  1899. const targetLocaleMessages = _messages.value[locales[i]] || {};
  1900. const messageValue = resolveValue(targetLocaleMessages, key);
  1901. if (messageValue != null) {
  1902. messages = messageValue;
  1903. break;
  1904. }
  1905. }
  1906. return messages;
  1907. }
  1908. // tm
  1909. function tm(key) {
  1910. const messages = resolveMessages(key);
  1911. // prettier-ignore
  1912. return messages != null
  1913. ? messages
  1914. : __root
  1915. ? __root.tm(key) || {}
  1916. : {};
  1917. }
  1918. // getLocaleMessage
  1919. function getLocaleMessage(locale) {
  1920. return (_messages.value[locale] || {});
  1921. }
  1922. // setLocaleMessage
  1923. function setLocaleMessage(locale, message) {
  1924. _messages.value[locale] = message;
  1925. _context.messages = _messages.value;
  1926. }
  1927. // mergeLocaleMessage
  1928. function mergeLocaleMessage(locale, message) {
  1929. _messages.value[locale] = _messages.value[locale] || {};
  1930. deepCopy(message, _messages.value[locale]);
  1931. _context.messages = _messages.value;
  1932. }
  1933. // getDateTimeFormat
  1934. function getDateTimeFormat(locale) {
  1935. return _datetimeFormats.value[locale] || {};
  1936. }
  1937. // setDateTimeFormat
  1938. function setDateTimeFormat(locale, format) {
  1939. _datetimeFormats.value[locale] = format;
  1940. _context.datetimeFormats = _datetimeFormats.value;
  1941. clearDateTimeFormat(_context, locale, format);
  1942. }
  1943. // mergeDateTimeFormat
  1944. function mergeDateTimeFormat(locale, format) {
  1945. _datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
  1946. _context.datetimeFormats = _datetimeFormats.value;
  1947. clearDateTimeFormat(_context, locale, format);
  1948. }
  1949. // getNumberFormat
  1950. function getNumberFormat(locale) {
  1951. return _numberFormats.value[locale] || {};
  1952. }
  1953. // setNumberFormat
  1954. function setNumberFormat(locale, format) {
  1955. _numberFormats.value[locale] = format;
  1956. _context.numberFormats = _numberFormats.value;
  1957. clearNumberFormat(_context, locale, format);
  1958. }
  1959. // mergeNumberFormat
  1960. function mergeNumberFormat(locale, format) {
  1961. _numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
  1962. _context.numberFormats = _numberFormats.value;
  1963. clearNumberFormat(_context, locale, format);
  1964. }
  1965. // for debug
  1966. composerID++;
  1967. // watch root locale & fallbackLocale
  1968. if (__root) {
  1969. watch(__root.locale, (val) => {
  1970. if (_inheritLocale) {
  1971. _locale.value = val;
  1972. _context.locale = val;
  1973. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  1974. }
  1975. });
  1976. watch(__root.fallbackLocale, (val) => {
  1977. if (_inheritLocale) {
  1978. _fallbackLocale.value = val;
  1979. _context.fallbackLocale = val;
  1980. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  1981. }
  1982. });
  1983. }
  1984. // define composition API!
  1985. const composer = {
  1986. id: composerID,
  1987. locale,
  1988. fallbackLocale,
  1989. get inheritLocale() {
  1990. return _inheritLocale;
  1991. },
  1992. set inheritLocale(val) {
  1993. _inheritLocale = val;
  1994. if (val && __root) {
  1995. _locale.value = __root.locale.value;
  1996. _fallbackLocale.value = __root.fallbackLocale.value;
  1997. updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
  1998. }
  1999. },
  2000. get availableLocales() {
  2001. return Object.keys(_messages.value).sort();
  2002. },
  2003. messages,
  2004. datetimeFormats,
  2005. numberFormats,
  2006. get modifiers() {
  2007. return _modifiers;
  2008. },
  2009. get pluralRules() {
  2010. return _pluralRules || {};
  2011. },
  2012. get isGlobal() {
  2013. return _isGlobal;
  2014. },
  2015. get missingWarn() {
  2016. return _missingWarn;
  2017. },
  2018. set missingWarn(val) {
  2019. _missingWarn = val;
  2020. _context.missingWarn = _missingWarn;
  2021. },
  2022. get fallbackWarn() {
  2023. return _fallbackWarn;
  2024. },
  2025. set fallbackWarn(val) {
  2026. _fallbackWarn = val;
  2027. _context.fallbackWarn = _fallbackWarn;
  2028. },
  2029. get fallbackRoot() {
  2030. return _fallbackRoot;
  2031. },
  2032. set fallbackRoot(val) {
  2033. _fallbackRoot = val;
  2034. },
  2035. get fallbackFormat() {
  2036. return _fallbackFormat;
  2037. },
  2038. set fallbackFormat(val) {
  2039. _fallbackFormat = val;
  2040. _context.fallbackFormat = _fallbackFormat;
  2041. },
  2042. get warnHtmlMessage() {
  2043. return _warnHtmlMessage;
  2044. },
  2045. set warnHtmlMessage(val) {
  2046. _warnHtmlMessage = val;
  2047. _context.warnHtmlMessage = val;
  2048. },
  2049. get escapeParameter() {
  2050. return _escapeParameter;
  2051. },
  2052. set escapeParameter(val) {
  2053. _escapeParameter = val;
  2054. _context.escapeParameter = val;
  2055. },
  2056. t,
  2057. rt,
  2058. d,
  2059. n,
  2060. te,
  2061. tm,
  2062. getLocaleMessage,
  2063. setLocaleMessage,
  2064. mergeLocaleMessage,
  2065. getDateTimeFormat,
  2066. setDateTimeFormat,
  2067. mergeDateTimeFormat,
  2068. getNumberFormat,
  2069. setNumberFormat,
  2070. mergeNumberFormat,
  2071. getPostTranslationHandler,
  2072. setPostTranslationHandler,
  2073. getMissingHandler,
  2074. setMissingHandler,
  2075. [TransrateVNodeSymbol]: transrateVNode,
  2076. [NumberPartsSymbol]: numberParts,
  2077. [DatetimePartsSymbol]: datetimeParts,
  2078. [SetPluralRulesSymbol]: setPluralRules,
  2079. [InejctWithOption]: options.__injectWithOption // eslint-disable-line @typescript-eslint/no-explicit-any
  2080. };
  2081. // for vue-devtools timeline event
  2082. {
  2083. composer[EnableEmitter] = (emitter) => {
  2084. _context.__v_emitter = emitter;
  2085. };
  2086. composer[DisableEmitter] = () => {
  2087. _context.__v_emitter = undefined;
  2088. };
  2089. }
  2090. return composer;
  2091. }
  2092. /**
  2093. * Convert to I18n Composer Options from VueI18n Options
  2094. *
  2095. * @internal
  2096. */
  2097. function convertComposerOptions(options) {
  2098. const locale = isString(options.locale) ? options.locale : 'en-US';
  2099. const fallbackLocale = isString(options.fallbackLocale) ||
  2100. isArray(options.fallbackLocale) ||
  2101. isPlainObject(options.fallbackLocale) ||
  2102. options.fallbackLocale === false
  2103. ? options.fallbackLocale
  2104. : locale;
  2105. const missing = isFunction(options.missing) ? options.missing : undefined;
  2106. const missingWarn = isBoolean(options.silentTranslationWarn) ||
  2107. isRegExp(options.silentTranslationWarn)
  2108. ? !options.silentTranslationWarn
  2109. : true;
  2110. const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
  2111. isRegExp(options.silentFallbackWarn)
  2112. ? !options.silentFallbackWarn
  2113. : true;
  2114. const fallbackRoot = isBoolean(options.fallbackRoot)
  2115. ? options.fallbackRoot
  2116. : true;
  2117. const fallbackFormat = !!options.formatFallbackMessages;
  2118. const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
  2119. const pluralizationRules = options.pluralizationRules;
  2120. const postTranslation = isFunction(options.postTranslation)
  2121. ? options.postTranslation
  2122. : undefined;
  2123. const warnHtmlMessage = isString(options.warnHtmlInMessage)
  2124. ? options.warnHtmlInMessage !== 'off'
  2125. : true;
  2126. const escapeParameter = !!options.escapeParameterHtml;
  2127. const inheritLocale = isBoolean(options.sync) ? options.sync : true;
  2128. if (options.formatter) {
  2129. warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  2130. }
  2131. if (options.preserveDirectiveContent) {
  2132. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  2133. }
  2134. let messages = options.messages;
  2135. if (isPlainObject(options.sharedMessages)) {
  2136. const sharedMessages = options.sharedMessages;
  2137. const locales = Object.keys(sharedMessages);
  2138. messages = locales.reduce((messages, locale) => {
  2139. const message = messages[locale] || (messages[locale] = {});
  2140. assign(message, sharedMessages[locale]);
  2141. return messages;
  2142. }, (messages || {}));
  2143. }
  2144. const { __i18n, __root, __injectWithOption } = options;
  2145. const datetimeFormats = options.datetimeFormats;
  2146. const numberFormats = options.numberFormats;
  2147. const flatJson = options.flatJson;
  2148. return {
  2149. locale,
  2150. fallbackLocale,
  2151. messages,
  2152. flatJson,
  2153. datetimeFormats,
  2154. numberFormats,
  2155. missing,
  2156. missingWarn,
  2157. fallbackWarn,
  2158. fallbackRoot,
  2159. fallbackFormat,
  2160. modifiers,
  2161. pluralRules: pluralizationRules,
  2162. postTranslation,
  2163. warnHtmlMessage,
  2164. escapeParameter,
  2165. inheritLocale,
  2166. __i18n,
  2167. __root,
  2168. __injectWithOption
  2169. };
  2170. }
  2171. /**
  2172. * create VueI18n interface factory
  2173. *
  2174. * @internal
  2175. */
  2176. function createVueI18n(options = {}) {
  2177. const composer = createComposer(convertComposerOptions(options));
  2178. // defines VueI18n
  2179. const vueI18n = {
  2180. // id
  2181. id: composer.id,
  2182. // locale
  2183. get locale() {
  2184. return composer.locale.value;
  2185. },
  2186. set locale(val) {
  2187. composer.locale.value = val;
  2188. },
  2189. // fallbackLocale
  2190. get fallbackLocale() {
  2191. return composer.fallbackLocale.value;
  2192. },
  2193. set fallbackLocale(val) {
  2194. composer.fallbackLocale.value = val;
  2195. },
  2196. // messages
  2197. get messages() {
  2198. return composer.messages.value;
  2199. },
  2200. // datetimeFormats
  2201. get datetimeFormats() {
  2202. return composer.datetimeFormats.value;
  2203. },
  2204. // numberFormats
  2205. get numberFormats() {
  2206. return composer.numberFormats.value;
  2207. },
  2208. // availableLocales
  2209. get availableLocales() {
  2210. return composer.availableLocales;
  2211. },
  2212. // formatter
  2213. get formatter() {
  2214. warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  2215. // dummy
  2216. return {
  2217. interpolate() {
  2218. return [];
  2219. }
  2220. };
  2221. },
  2222. set formatter(val) {
  2223. warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */));
  2224. },
  2225. // missing
  2226. get missing() {
  2227. return composer.getMissingHandler();
  2228. },
  2229. set missing(handler) {
  2230. composer.setMissingHandler(handler);
  2231. },
  2232. // silentTranslationWarn
  2233. get silentTranslationWarn() {
  2234. return isBoolean(composer.missingWarn)
  2235. ? !composer.missingWarn
  2236. : composer.missingWarn;
  2237. },
  2238. set silentTranslationWarn(val) {
  2239. composer.missingWarn = isBoolean(val) ? !val : val;
  2240. },
  2241. // silentFallbackWarn
  2242. get silentFallbackWarn() {
  2243. return isBoolean(composer.fallbackWarn)
  2244. ? !composer.fallbackWarn
  2245. : composer.fallbackWarn;
  2246. },
  2247. set silentFallbackWarn(val) {
  2248. composer.fallbackWarn = isBoolean(val) ? !val : val;
  2249. },
  2250. // modifiers
  2251. get modifiers() {
  2252. return composer.modifiers;
  2253. },
  2254. // formatFallbackMessages
  2255. get formatFallbackMessages() {
  2256. return composer.fallbackFormat;
  2257. },
  2258. set formatFallbackMessages(val) {
  2259. composer.fallbackFormat = val;
  2260. },
  2261. // postTranslation
  2262. get postTranslation() {
  2263. return composer.getPostTranslationHandler();
  2264. },
  2265. set postTranslation(handler) {
  2266. composer.setPostTranslationHandler(handler);
  2267. },
  2268. // sync
  2269. get sync() {
  2270. return composer.inheritLocale;
  2271. },
  2272. set sync(val) {
  2273. composer.inheritLocale = val;
  2274. },
  2275. // warnInHtmlMessage
  2276. get warnHtmlInMessage() {
  2277. return composer.warnHtmlMessage ? 'warn' : 'off';
  2278. },
  2279. set warnHtmlInMessage(val) {
  2280. composer.warnHtmlMessage = val !== 'off';
  2281. },
  2282. // escapeParameterHtml
  2283. get escapeParameterHtml() {
  2284. return composer.escapeParameter;
  2285. },
  2286. set escapeParameterHtml(val) {
  2287. composer.escapeParameter = val;
  2288. },
  2289. // preserveDirectiveContent
  2290. get preserveDirectiveContent() {
  2291. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  2292. return true;
  2293. },
  2294. set preserveDirectiveContent(val) {
  2295. warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
  2296. },
  2297. // pluralizationRules
  2298. get pluralizationRules() {
  2299. return composer.pluralRules || {};
  2300. },
  2301. // for internal
  2302. __composer: composer,
  2303. // t
  2304. t(...args) {
  2305. const [arg1, arg2, arg3] = args;
  2306. const options = {};
  2307. let list = null;
  2308. let named = null;
  2309. if (!isString(arg1)) {
  2310. throw createI18nError(15 /* INVALID_ARGUMENT */);
  2311. }
  2312. const key = arg1;
  2313. if (isString(arg2)) {
  2314. options.locale = arg2;
  2315. }
  2316. else if (isArray(arg2)) {
  2317. list = arg2;
  2318. }
  2319. else if (isPlainObject(arg2)) {
  2320. named = arg2;
  2321. }
  2322. if (isArray(arg3)) {
  2323. list = arg3;
  2324. }
  2325. else if (isPlainObject(arg3)) {
  2326. named = arg3;
  2327. }
  2328. return composer.t(key, list || named || {}, options);
  2329. },
  2330. rt(...args) {
  2331. return composer.rt(...args);
  2332. },
  2333. // tc
  2334. tc(...args) {
  2335. const [arg1, arg2, arg3] = args;
  2336. const options = { plural: 1 };
  2337. let list = null;
  2338. let named = null;
  2339. if (!isString(arg1)) {
  2340. throw createI18nError(15 /* INVALID_ARGUMENT */);
  2341. }
  2342. const key = arg1;
  2343. if (isString(arg2)) {
  2344. options.locale = arg2;
  2345. }
  2346. else if (isNumber(arg2)) {
  2347. options.plural = arg2;
  2348. }
  2349. else if (isArray(arg2)) {
  2350. list = arg2;
  2351. }
  2352. else if (isPlainObject(arg2)) {
  2353. named = arg2;
  2354. }
  2355. if (isString(arg3)) {
  2356. options.locale = arg3;
  2357. }
  2358. else if (isArray(arg3)) {
  2359. list = arg3;
  2360. }
  2361. else if (isPlainObject(arg3)) {
  2362. named = arg3;
  2363. }
  2364. return composer.t(key, list || named || {}, options);
  2365. },
  2366. // te
  2367. te(key, locale) {
  2368. return composer.te(key, locale);
  2369. },
  2370. // tm
  2371. tm(key) {
  2372. return composer.tm(key);
  2373. },
  2374. // getLocaleMessage
  2375. getLocaleMessage(locale) {
  2376. return composer.getLocaleMessage(locale);
  2377. },
  2378. // setLocaleMessage
  2379. setLocaleMessage(locale, message) {
  2380. composer.setLocaleMessage(locale, message);
  2381. },
  2382. // mergeLocaleMessage
  2383. mergeLocaleMessage(locale, message) {
  2384. composer.mergeLocaleMessage(locale, message);
  2385. },
  2386. // d
  2387. d(...args) {
  2388. return composer.d(...args);
  2389. },
  2390. // getDateTimeFormat
  2391. getDateTimeFormat(locale) {
  2392. return composer.getDateTimeFormat(locale);
  2393. },
  2394. // setDateTimeFormat
  2395. setDateTimeFormat(locale, format) {
  2396. composer.setDateTimeFormat(locale, format);
  2397. },
  2398. // mergeDateTimeFormat
  2399. mergeDateTimeFormat(locale, format) {
  2400. composer.mergeDateTimeFormat(locale, format);
  2401. },
  2402. // n
  2403. n(...args) {
  2404. return composer.n(...args);
  2405. },
  2406. // getNumberFormat
  2407. getNumberFormat(locale) {
  2408. return composer.getNumberFormat(locale);
  2409. },
  2410. // setNumberFormat
  2411. setNumberFormat(locale, format) {
  2412. composer.setNumberFormat(locale, format);
  2413. },
  2414. // mergeNumberFormat
  2415. mergeNumberFormat(locale, format) {
  2416. composer.mergeNumberFormat(locale, format);
  2417. },
  2418. // getChoiceIndex
  2419. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  2420. getChoiceIndex(choice, choicesLength) {
  2421. warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */));
  2422. return -1;
  2423. },
  2424. // for internal
  2425. __onComponentInstanceCreated(target) {
  2426. const { componentInstanceCreatedListener } = options;
  2427. if (componentInstanceCreatedListener) {
  2428. componentInstanceCreatedListener(target, vueI18n);
  2429. }
  2430. }
  2431. };
  2432. // for vue-devtools timeline event
  2433. {
  2434. vueI18n.__enableEmitter = (emitter) => {
  2435. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2436. const __composer = composer;
  2437. __composer[EnableEmitter] && __composer[EnableEmitter](emitter);
  2438. };
  2439. vueI18n.__disableEmitter = () => {
  2440. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2441. const __composer = composer;
  2442. __composer[DisableEmitter] && __composer[DisableEmitter]();
  2443. };
  2444. }
  2445. return vueI18n;
  2446. }
  2447. const baseFormatProps = {
  2448. tag: {
  2449. type: [String, Object]
  2450. },
  2451. locale: {
  2452. type: String
  2453. },
  2454. scope: {
  2455. type: String,
  2456. validator: (val) => val === 'parent' || val === 'global',
  2457. default: 'parent'
  2458. },
  2459. i18n: {
  2460. type: Object
  2461. }
  2462. };
  2463. /**
  2464. * Translation Component
  2465. *
  2466. * @remarks
  2467. * See the following items for property about details
  2468. *
  2469. * @VueI18nSee [TranslationProps](component#translationprops)
  2470. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  2471. * @VueI18nSee [Component Interpolation](../guide/advanced/component)
  2472. *
  2473. * @example
  2474. * ```html
  2475. * <div id="app">
  2476. * <!-- ... -->
  2477. * <i18n path="term" tag="label" for="tos">
  2478. * <a :href="url" target="_blank">{{ $t('tos') }}</a>
  2479. * </i18n>
  2480. * <!-- ... -->
  2481. * </div>
  2482. * ```
  2483. * ```js
  2484. * import { createApp } from 'vue'
  2485. * import { createI18n } from 'vue-i18n'
  2486. *
  2487. * const messages = {
  2488. * en: {
  2489. * tos: 'Term of Service',
  2490. * term: 'I accept xxx {0}.'
  2491. * },
  2492. * ja: {
  2493. * tos: '利用規約',
  2494. * term: '私は xxx の{0}に同意します。'
  2495. * }
  2496. * }
  2497. *
  2498. * const i18n = createI18n({
  2499. * locale: 'en',
  2500. * messages
  2501. * })
  2502. *
  2503. * const app = createApp({
  2504. * data: {
  2505. * url: '/term'
  2506. * }
  2507. * }).use(i18n).mount('#app')
  2508. * ```
  2509. *
  2510. * @VueI18nComponent
  2511. */
  2512. const Translation = {
  2513. /* eslint-disable */
  2514. name: 'i18n-t',
  2515. props: assign({
  2516. keypath: {
  2517. type: String,
  2518. required: true
  2519. },
  2520. plural: {
  2521. type: [Number, String],
  2522. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2523. validator: (val) => isNumber(val) || !isNaN(val)
  2524. }
  2525. }, baseFormatProps),
  2526. /* eslint-enable */
  2527. setup(props, context) {
  2528. const { slots, attrs } = context;
  2529. const i18n = props.i18n ||
  2530. useI18n({
  2531. useScope: props.scope,
  2532. __useComponent: true
  2533. });
  2534. const keys = Object.keys(slots).filter(key => key !== '_');
  2535. return () => {
  2536. const options = {};
  2537. if (props.locale) {
  2538. options.locale = props.locale;
  2539. }
  2540. if (props.plural !== undefined) {
  2541. options.plural = isString(props.plural) ? +props.plural : props.plural;
  2542. }
  2543. const arg = getInterpolateArg(context, keys);
  2544. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2545. const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options);
  2546. const assignedAttrs = assign({}, attrs);
  2547. // prettier-ignore
  2548. return isString(props.tag)
  2549. ? h(props.tag, assignedAttrs, children)
  2550. : isObject(props.tag)
  2551. ? h(props.tag, assignedAttrs, children)
  2552. : h(Fragment, assignedAttrs, children);
  2553. };
  2554. }
  2555. };
  2556. function getInterpolateArg({ slots }, keys) {
  2557. if (keys.length === 1 && keys[0] === 'default') {
  2558. // default slot only
  2559. return slots.default ? slots.default() : [];
  2560. }
  2561. else {
  2562. // named slots
  2563. return keys.reduce((arg, key) => {
  2564. const slot = slots[key];
  2565. if (slot) {
  2566. arg[key] = slot();
  2567. }
  2568. return arg;
  2569. }, {});
  2570. }
  2571. }
  2572. function renderFormatter(props, context, slotKeys, partFormatter) {
  2573. const { slots, attrs } = context;
  2574. return () => {
  2575. const options = { part: true };
  2576. let overrides = {};
  2577. if (props.locale) {
  2578. options.locale = props.locale;
  2579. }
  2580. if (isString(props.format)) {
  2581. options.key = props.format;
  2582. }
  2583. else if (isObject(props.format)) {
  2584. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2585. if (isString(props.format.key)) {
  2586. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2587. options.key = props.format.key;
  2588. }
  2589. // Filter out number format options only
  2590. overrides = Object.keys(props.format).reduce((options, prop) => {
  2591. return slotKeys.includes(prop)
  2592. ? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
  2593. : options;
  2594. }, {});
  2595. }
  2596. const parts = partFormatter(...[props.value, options, overrides]);
  2597. let children = [options.key];
  2598. if (isArray(parts)) {
  2599. children = parts.map((part, index) => {
  2600. const slot = slots[part.type];
  2601. return slot
  2602. ? slot({ [part.type]: part.value, index, parts })
  2603. : [part.value];
  2604. });
  2605. }
  2606. else if (isString(parts)) {
  2607. children = [parts];
  2608. }
  2609. const assignedAttrs = assign({}, attrs);
  2610. // prettier-ignore
  2611. return isString(props.tag)
  2612. ? h(props.tag, assignedAttrs, children)
  2613. : isObject(props.tag)
  2614. ? h(props.tag, assignedAttrs, children)
  2615. : h(Fragment, assignedAttrs, children);
  2616. };
  2617. }
  2618. const NUMBER_FORMAT_KEYS = [
  2619. 'localeMatcher',
  2620. 'style',
  2621. 'unit',
  2622. 'unitDisplay',
  2623. 'currency',
  2624. 'currencyDisplay',
  2625. 'useGrouping',
  2626. 'numberingSystem',
  2627. 'minimumIntegerDigits',
  2628. 'minimumFractionDigits',
  2629. 'maximumFractionDigits',
  2630. 'minimumSignificantDigits',
  2631. 'maximumSignificantDigits',
  2632. 'notation',
  2633. 'formatMatcher'
  2634. ];
  2635. /**
  2636. * Number Format Component
  2637. *
  2638. * @remarks
  2639. * See the following items for property about details
  2640. *
  2641. * @VueI18nSee [FormattableProps](component#formattableprops)
  2642. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  2643. * @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
  2644. *
  2645. * @VueI18nDanger
  2646. * 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)
  2647. *
  2648. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
  2649. *
  2650. * @VueI18nComponent
  2651. */
  2652. const NumberFormat = {
  2653. /* eslint-disable */
  2654. name: 'i18n-n',
  2655. props: assign({
  2656. value: {
  2657. type: Number,
  2658. required: true
  2659. },
  2660. format: {
  2661. type: [String, Object]
  2662. }
  2663. }, baseFormatProps),
  2664. /* eslint-enable */
  2665. setup(props, context) {
  2666. const i18n = props.i18n ||
  2667. useI18n({ useScope: 'parent', __useComponent: true });
  2668. return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) =>
  2669. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2670. i18n[NumberPartsSymbol](...args));
  2671. }
  2672. };
  2673. const DATETIME_FORMAT_KEYS = [
  2674. 'dateStyle',
  2675. 'timeStyle',
  2676. 'fractionalSecondDigits',
  2677. 'calendar',
  2678. 'dayPeriod',
  2679. 'numberingSystem',
  2680. 'localeMatcher',
  2681. 'timeZone',
  2682. 'hour12',
  2683. 'hourCycle',
  2684. 'formatMatcher',
  2685. 'weekday',
  2686. 'era',
  2687. 'year',
  2688. 'month',
  2689. 'day',
  2690. 'hour',
  2691. 'minute',
  2692. 'second',
  2693. 'timeZoneName'
  2694. ];
  2695. /**
  2696. * Datetime Format Component
  2697. *
  2698. * @remarks
  2699. * See the following items for property about details
  2700. *
  2701. * @VueI18nSee [FormattableProps](component#formattableprops)
  2702. * @VueI18nSee [BaseFormatProps](component#baseformatprops)
  2703. * @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
  2704. *
  2705. * @VueI18nDanger
  2706. * 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)
  2707. *
  2708. * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
  2709. *
  2710. * @VueI18nComponent
  2711. */
  2712. const DatetimeFormat = {
  2713. /* eslint-disable */
  2714. name: 'i18n-d',
  2715. props: assign({
  2716. value: {
  2717. type: [Number, Date],
  2718. required: true
  2719. },
  2720. format: {
  2721. type: [String, Object]
  2722. }
  2723. }, baseFormatProps),
  2724. /* eslint-enable */
  2725. setup(props, context) {
  2726. const i18n = props.i18n ||
  2727. useI18n({ useScope: 'parent', __useComponent: true });
  2728. return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) =>
  2729. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2730. i18n[DatetimePartsSymbol](...args));
  2731. }
  2732. };
  2733. function getComposer$2(i18n, instance) {
  2734. const i18nInternal = i18n;
  2735. if (i18n.mode === 'composition') {
  2736. return (i18nInternal.__getInstance(instance) || i18n.global);
  2737. }
  2738. else {
  2739. const vueI18n = i18nInternal.__getInstance(instance);
  2740. return vueI18n != null
  2741. ? vueI18n.__composer
  2742. : i18n.global.__composer;
  2743. }
  2744. }
  2745. function vTDirective(i18n) {
  2746. const bind = (el, { instance, value, modifiers }) => {
  2747. /* istanbul ignore if */
  2748. if (!instance || !instance.$) {
  2749. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  2750. }
  2751. const composer = getComposer$2(i18n, instance.$);
  2752. if (modifiers.preserve) {
  2753. warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */));
  2754. }
  2755. const parsedValue = parseValue(value);
  2756. el.textContent = composer.t(...makeParams(parsedValue));
  2757. };
  2758. return {
  2759. beforeMount: bind,
  2760. beforeUpdate: bind
  2761. };
  2762. }
  2763. function parseValue(value) {
  2764. if (isString(value)) {
  2765. return { path: value };
  2766. }
  2767. else if (isPlainObject(value)) {
  2768. if (!('path' in value)) {
  2769. throw createI18nError(19 /* REQUIRED_VALUE */, 'path');
  2770. }
  2771. return value;
  2772. }
  2773. else {
  2774. throw createI18nError(20 /* INVALID_VALUE */);
  2775. }
  2776. }
  2777. function makeParams(value) {
  2778. const { path, locale, args, choice, plural } = value;
  2779. const options = {};
  2780. const named = args || {};
  2781. if (isString(locale)) {
  2782. options.locale = locale;
  2783. }
  2784. if (isNumber(choice)) {
  2785. options.plural = choice;
  2786. }
  2787. if (isNumber(plural)) {
  2788. options.plural = plural;
  2789. }
  2790. return [path, named, options];
  2791. }
  2792. function apply(app, i18n, ...options) {
  2793. const pluginOptions = isPlainObject(options[0])
  2794. ? options[0]
  2795. : {};
  2796. const useI18nComponentName = !!pluginOptions.useI18nComponentName;
  2797. const globalInstall = isBoolean(pluginOptions.globalInstall)
  2798. ? pluginOptions.globalInstall
  2799. : true;
  2800. if (globalInstall && useI18nComponentName) {
  2801. warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, {
  2802. name: Translation.name
  2803. }));
  2804. }
  2805. if (globalInstall) {
  2806. // install components
  2807. app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation);
  2808. app.component(NumberFormat.name, NumberFormat);
  2809. app.component(DatetimeFormat.name, DatetimeFormat);
  2810. }
  2811. // install directive
  2812. app.directive('t', vTDirective(i18n));
  2813. }
  2814. var global$1 = (typeof global !== "undefined" ? global :
  2815. typeof self !== "undefined" ? self :
  2816. typeof window !== "undefined" ? window : {});
  2817. function getDevtoolsGlobalHook() {
  2818. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  2819. }
  2820. function getTarget() {
  2821. // @ts-ignore
  2822. return typeof navigator !== 'undefined'
  2823. ? window
  2824. : typeof global$1 !== 'undefined'
  2825. ? global$1
  2826. : {};
  2827. }
  2828. const HOOK_SETUP = 'devtools-plugin:setup';
  2829. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  2830. const hook = getDevtoolsGlobalHook();
  2831. if (hook) {
  2832. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  2833. }
  2834. else {
  2835. const target = getTarget();
  2836. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  2837. list.push({
  2838. pluginDescriptor,
  2839. setupFn
  2840. });
  2841. }
  2842. }
  2843. const VueDevToolsLabels = {
  2844. ["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools',
  2845. ["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources',
  2846. ["vue-i18n-timeline" /* TIMELINE */]: 'Vue I18n'
  2847. };
  2848. const VueDevToolsPlaceholders = {
  2849. ["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...'
  2850. };
  2851. const VueDevToolsTimelineColors = {
  2852. ["vue-i18n-timeline" /* TIMELINE */]: 0xffcd19
  2853. };
  2854. const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
  2855. let devtoolsApi;
  2856. async function enableDevTools(app, i18n) {
  2857. return new Promise((resolve, reject) => {
  2858. try {
  2859. setupDevtoolsPlugin({
  2860. id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */,
  2861. label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */],
  2862. packageName: 'vue-i18n',
  2863. homepage: 'https://vue-i18n.intlify.dev',
  2864. logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
  2865. componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
  2866. app
  2867. }, api => {
  2868. devtoolsApi = api;
  2869. api.on.visitComponentTree(({ componentInstance, treeNode }) => {
  2870. updateComponentTreeTags(componentInstance, treeNode, i18n);
  2871. });
  2872. api.on.inspectComponent(({ componentInstance, instanceData }) => {
  2873. if (componentInstance.vnode.el.__VUE_I18N__ && instanceData) {
  2874. if (i18n.mode === 'legacy') {
  2875. // ignore global scope on legacy mode
  2876. if (componentInstance.vnode.el.__VUE_I18N__ !==
  2877. i18n.global.__composer) {
  2878. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  2879. }
  2880. }
  2881. else {
  2882. inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
  2883. }
  2884. }
  2885. });
  2886. api.addInspector({
  2887. id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */,
  2888. label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */],
  2889. icon: 'language',
  2890. treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]
  2891. });
  2892. api.on.getInspectorTree(payload => {
  2893. if (payload.app === app &&
  2894. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  2895. registerScope(payload, i18n);
  2896. }
  2897. });
  2898. api.on.getInspectorState(payload => {
  2899. if (payload.app === app &&
  2900. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  2901. inspectScope(payload, i18n);
  2902. }
  2903. });
  2904. api.on.editInspectorState(payload => {
  2905. if (payload.app === app &&
  2906. payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
  2907. editScope(payload, i18n);
  2908. }
  2909. });
  2910. api.addTimelineLayer({
  2911. id: "vue-i18n-timeline" /* TIMELINE */,
  2912. label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */],
  2913. color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */]
  2914. });
  2915. resolve(true);
  2916. });
  2917. }
  2918. catch (e) {
  2919. console.error(e);
  2920. reject(false);
  2921. }
  2922. });
  2923. }
  2924. function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
  2925. treeNode, i18n) {
  2926. // prettier-ignore
  2927. const global = i18n.mode === 'composition'
  2928. ? i18n.global
  2929. : i18n.global.__composer;
  2930. if (instance && instance.vnode.el.__VUE_I18N__) {
  2931. // add custom tags local scope only
  2932. if (instance.vnode.el.__VUE_I18N__ !== global) {
  2933. const label = instance.type.name || instance.type.displayName || instance.type.__file;
  2934. const tag = {
  2935. label: `i18n (${label} Scope)`,
  2936. textColor: 0x000000,
  2937. backgroundColor: 0xffcd19
  2938. };
  2939. treeNode.tags.push(tag);
  2940. }
  2941. }
  2942. }
  2943. function inspectComposer(instanceData, composer) {
  2944. const type = VUE_I18N_COMPONENT_TYPES;
  2945. instanceData.state.push({
  2946. type,
  2947. key: 'locale',
  2948. editable: true,
  2949. value: composer.locale.value
  2950. });
  2951. instanceData.state.push({
  2952. type,
  2953. key: 'availableLocales',
  2954. editable: false,
  2955. value: composer.availableLocales
  2956. });
  2957. instanceData.state.push({
  2958. type,
  2959. key: 'fallbackLocale',
  2960. editable: true,
  2961. value: composer.fallbackLocale.value
  2962. });
  2963. instanceData.state.push({
  2964. type,
  2965. key: 'inheritLocale',
  2966. editable: true,
  2967. value: composer.inheritLocale
  2968. });
  2969. instanceData.state.push({
  2970. type,
  2971. key: 'messages',
  2972. editable: false,
  2973. value: getLocaleMessageValue(composer.messages.value)
  2974. });
  2975. instanceData.state.push({
  2976. type,
  2977. key: 'datetimeFormats',
  2978. editable: false,
  2979. value: composer.datetimeFormats.value
  2980. });
  2981. instanceData.state.push({
  2982. type,
  2983. key: 'numberFormats',
  2984. editable: false,
  2985. value: composer.numberFormats.value
  2986. });
  2987. }
  2988. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2989. function getLocaleMessageValue(messages) {
  2990. const value = {};
  2991. Object.keys(messages).forEach((key) => {
  2992. const v = messages[key];
  2993. if (isFunction(v) && 'source' in v) {
  2994. value[key] = getMessageFunctionDetails(v);
  2995. }
  2996. else if (isObject(v)) {
  2997. value[key] = getLocaleMessageValue(v);
  2998. }
  2999. else {
  3000. value[key] = v;
  3001. }
  3002. });
  3003. return value;
  3004. }
  3005. const ESC = {
  3006. '<': '&lt;',
  3007. '>': '&gt;',
  3008. '"': '&quot;',
  3009. '&': '&amp;'
  3010. };
  3011. function escape(s) {
  3012. return s.replace(/[<>"&]/g, escapeChar);
  3013. }
  3014. function escapeChar(a) {
  3015. return ESC[a] || a;
  3016. }
  3017. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3018. function getMessageFunctionDetails(func) {
  3019. const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
  3020. return {
  3021. _custom: {
  3022. type: 'function',
  3023. display: `<span>ƒ</span> ${argString}`
  3024. }
  3025. };
  3026. }
  3027. function registerScope(payload, i18n) {
  3028. payload.rootNodes.push({
  3029. id: 'global',
  3030. label: 'Global Scope'
  3031. });
  3032. // prettier-ignore
  3033. const global = i18n.mode === 'composition'
  3034. ? i18n.global
  3035. : i18n.global.__composer;
  3036. for (const [keyInstance, instance] of i18n.__instances) {
  3037. // prettier-ignore
  3038. const composer = i18n.mode === 'composition'
  3039. ? instance
  3040. : instance.__composer;
  3041. if (global === composer) {
  3042. continue;
  3043. }
  3044. const label = keyInstance.type.name ||
  3045. keyInstance.type.displayName ||
  3046. keyInstance.type.__file;
  3047. payload.rootNodes.push({
  3048. id: composer.id.toString(),
  3049. label: `${label} Scope`
  3050. });
  3051. }
  3052. }
  3053. function getComposer$1(nodeId, i18n) {
  3054. if (nodeId === 'global') {
  3055. return i18n.mode === 'composition'
  3056. ? i18n.global
  3057. : i18n.global.__composer;
  3058. }
  3059. else {
  3060. const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
  3061. if (instance) {
  3062. return i18n.mode === 'composition'
  3063. ? instance
  3064. : instance.__composer;
  3065. }
  3066. else {
  3067. return null;
  3068. }
  3069. }
  3070. }
  3071. function inspectScope(payload, i18n) {
  3072. const composer = getComposer$1(payload.nodeId, i18n);
  3073. if (composer) {
  3074. payload.state = makeScopeInspectState(composer);
  3075. }
  3076. }
  3077. function makeScopeInspectState(composer) {
  3078. const state = {};
  3079. const localeType = 'Locale related info';
  3080. const localeStates = [
  3081. {
  3082. type: localeType,
  3083. key: 'locale',
  3084. editable: true,
  3085. value: composer.locale.value
  3086. },
  3087. {
  3088. type: localeType,
  3089. key: 'fallbackLocale',
  3090. editable: true,
  3091. value: composer.fallbackLocale.value
  3092. },
  3093. {
  3094. type: localeType,
  3095. key: 'availableLocales',
  3096. editable: false,
  3097. value: composer.availableLocales
  3098. },
  3099. {
  3100. type: localeType,
  3101. key: 'inheritLocale',
  3102. editable: true,
  3103. value: composer.inheritLocale
  3104. }
  3105. ];
  3106. state[localeType] = localeStates;
  3107. const localeMessagesType = 'Locale messages info';
  3108. const localeMessagesStates = [
  3109. {
  3110. type: localeMessagesType,
  3111. key: 'messages',
  3112. editable: false,
  3113. value: getLocaleMessageValue(composer.messages.value)
  3114. }
  3115. ];
  3116. state[localeMessagesType] = localeMessagesStates;
  3117. const datetimeFormatsType = 'Datetime formats info';
  3118. const datetimeFormatsStates = [
  3119. {
  3120. type: datetimeFormatsType,
  3121. key: 'datetimeFormats',
  3122. editable: false,
  3123. value: composer.datetimeFormats.value
  3124. }
  3125. ];
  3126. state[datetimeFormatsType] = datetimeFormatsStates;
  3127. const numberFormatsType = 'Datetime formats info';
  3128. const numberFormatsStates = [
  3129. {
  3130. type: numberFormatsType,
  3131. key: 'numberFormats',
  3132. editable: false,
  3133. value: composer.numberFormats.value
  3134. }
  3135. ];
  3136. state[numberFormatsType] = numberFormatsStates;
  3137. return state;
  3138. }
  3139. function addTimelineEvent(event, payload) {
  3140. if (devtoolsApi) {
  3141. let groupId;
  3142. if (payload && 'groupId' in payload) {
  3143. groupId = payload.groupId;
  3144. delete payload.groupId;
  3145. }
  3146. devtoolsApi.addTimelineEvent({
  3147. layerId: "vue-i18n-timeline" /* TIMELINE */,
  3148. event: {
  3149. title: event,
  3150. groupId,
  3151. time: Date.now(),
  3152. meta: {},
  3153. data: payload || {},
  3154. logType: event === "compile-error" /* COMPILE_ERROR */
  3155. ? 'error'
  3156. : event === "fallback" /* FALBACK */ ||
  3157. event === "missing" /* MISSING */
  3158. ? 'warning'
  3159. : 'default'
  3160. }
  3161. });
  3162. }
  3163. }
  3164. function editScope(payload, i18n) {
  3165. const composer = getComposer$1(payload.nodeId, i18n);
  3166. if (composer) {
  3167. const [field] = payload.path;
  3168. if (field === 'locale' && isString(payload.state.value)) {
  3169. composer.locale.value = payload.state.value;
  3170. }
  3171. else if (field === 'fallbackLocale' &&
  3172. (isString(payload.state.value) ||
  3173. isArray(payload.state.value) ||
  3174. isObject(payload.state.value))) {
  3175. composer.fallbackLocale.value = payload.state.value;
  3176. }
  3177. else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
  3178. composer.inheritLocale = payload.state.value;
  3179. }
  3180. }
  3181. }
  3182. // supports compatibility for legacy vue-i18n APIs
  3183. function defineMixin(vuei18n, composer, i18n) {
  3184. return {
  3185. beforeCreate() {
  3186. const instance = getCurrentInstance();
  3187. /* istanbul ignore if */
  3188. if (!instance) {
  3189. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  3190. }
  3191. const options = this.$options;
  3192. if (options.i18n) {
  3193. const optionsI18n = options.i18n;
  3194. if (options.__i18n) {
  3195. optionsI18n.__i18n = options.__i18n;
  3196. }
  3197. optionsI18n.__root = composer;
  3198. if (this === this.$root) {
  3199. this.$i18n = mergeToRoot(vuei18n, optionsI18n);
  3200. }
  3201. else {
  3202. optionsI18n.__injectWithOption = true;
  3203. this.$i18n = createVueI18n(optionsI18n);
  3204. }
  3205. }
  3206. else if (options.__i18n) {
  3207. if (this === this.$root) {
  3208. this.$i18n = mergeToRoot(vuei18n, options);
  3209. }
  3210. else {
  3211. this.$i18n = createVueI18n({
  3212. __i18n: options.__i18n,
  3213. __injectWithOption: true,
  3214. __root: composer
  3215. });
  3216. }
  3217. }
  3218. else {
  3219. // set global
  3220. this.$i18n = vuei18n;
  3221. }
  3222. vuei18n.__onComponentInstanceCreated(this.$i18n);
  3223. i18n.__setInstance(instance, this.$i18n);
  3224. // defines vue-i18n legacy APIs
  3225. this.$t = (...args) => this.$i18n.t(...args);
  3226. this.$rt = (...args) => this.$i18n.rt(...args);
  3227. this.$tc = (...args) => this.$i18n.tc(...args);
  3228. this.$te = (key, locale) => this.$i18n.te(key, locale);
  3229. this.$d = (...args) => this.$i18n.d(...args);
  3230. this.$n = (...args) => this.$i18n.n(...args);
  3231. this.$tm = (key) => this.$i18n.tm(key);
  3232. },
  3233. mounted() {
  3234. /* istanbul ignore if */
  3235. {
  3236. this.$el.__VUE_I18N__ = this.$i18n.__composer;
  3237. const emitter = (this.__v_emitter = createEmitter());
  3238. const _vueI18n = this.$i18n;
  3239. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  3240. emitter.on('*', addTimelineEvent);
  3241. }
  3242. },
  3243. beforeUnmount() {
  3244. const instance = getCurrentInstance();
  3245. /* istanbul ignore if */
  3246. if (!instance) {
  3247. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  3248. }
  3249. /* istanbul ignore if */
  3250. {
  3251. if (this.__v_emitter) {
  3252. this.__v_emitter.off('*', addTimelineEvent);
  3253. delete this.__v_emitter;
  3254. }
  3255. const _vueI18n = this.$i18n;
  3256. _vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
  3257. delete this.$el.__VUE_I18N__;
  3258. }
  3259. delete this.$t;
  3260. delete this.$rt;
  3261. delete this.$tc;
  3262. delete this.$te;
  3263. delete this.$d;
  3264. delete this.$n;
  3265. delete this.$tm;
  3266. i18n.__deleteInstance(instance);
  3267. delete this.$i18n;
  3268. }
  3269. };
  3270. }
  3271. function mergeToRoot(root, options) {
  3272. root.locale = options.locale || root.locale;
  3273. root.fallbackLocale = options.fallbackLocale || root.fallbackLocale;
  3274. root.missing = options.missing || root.missing;
  3275. root.silentTranslationWarn =
  3276. options.silentTranslationWarn || root.silentFallbackWarn;
  3277. root.silentFallbackWarn =
  3278. options.silentFallbackWarn || root.silentFallbackWarn;
  3279. root.formatFallbackMessages =
  3280. options.formatFallbackMessages || root.formatFallbackMessages;
  3281. root.postTranslation = options.postTranslation || root.postTranslation;
  3282. root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage;
  3283. root.escapeParameterHtml =
  3284. options.escapeParameterHtml || root.escapeParameterHtml;
  3285. root.sync = options.sync || root.sync;
  3286. root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules);
  3287. const messages = getLocaleMessages(root.locale, {
  3288. messages: options.messages,
  3289. __i18n: options.__i18n
  3290. });
  3291. Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale]));
  3292. if (options.datetimeFormats) {
  3293. Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
  3294. }
  3295. if (options.numberFormats) {
  3296. Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale]));
  3297. }
  3298. return root;
  3299. }
  3300. /**
  3301. * Vue I18n factory
  3302. *
  3303. * @param options - An options, see the {@link I18nOptions}
  3304. *
  3305. * @returns {@link I18n} instance
  3306. *
  3307. * @remarks
  3308. * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option.
  3309. *
  3310. * If you use composition API mode, you need to specify {@link ComposerOptions}.
  3311. *
  3312. * @VueI18nSee [Getting Started](../guide/)
  3313. * @VueI18nSee [Composition API](../guide/advanced/composition)
  3314. *
  3315. * @example
  3316. * case: for Legacy API
  3317. * ```js
  3318. * import { createApp } from 'vue'
  3319. * import { createI18n } from 'vue-i18n'
  3320. *
  3321. * // call with I18n option
  3322. * const i18n = createI18n({
  3323. * locale: 'ja',
  3324. * messages: {
  3325. * en: { ... },
  3326. * ja: { ... }
  3327. * }
  3328. * })
  3329. *
  3330. * const App = {
  3331. * // ...
  3332. * }
  3333. *
  3334. * const app = createApp(App)
  3335. *
  3336. * // install!
  3337. * app.use(i18n)
  3338. * app.mount('#app')
  3339. * ```
  3340. *
  3341. * @example
  3342. * case: for composition API
  3343. * ```js
  3344. * import { createApp } from 'vue'
  3345. * import { createI18n, useI18n } from 'vue-i18n'
  3346. *
  3347. * // call with I18n option
  3348. * const i18n = createI18n({
  3349. * legacy: false, // you must specify 'legacy: false' option
  3350. * locale: 'ja',
  3351. * messages: {
  3352. * en: { ... },
  3353. * ja: { ... }
  3354. * }
  3355. * })
  3356. *
  3357. * const App = {
  3358. * setup() {
  3359. * // ...
  3360. * const { t } = useI18n({ ... })
  3361. * return { ... , t }
  3362. * }
  3363. * }
  3364. *
  3365. * const app = createApp(App)
  3366. *
  3367. * // install!
  3368. * app.use(i18n)
  3369. * app.mount('#app')
  3370. * ```
  3371. *
  3372. * @VueI18nGeneral
  3373. */
  3374. function createI18n(options = {}) {
  3375. // prettier-ignore
  3376. const __legacyMode = isBoolean(options.legacy)
  3377. ? options.legacy
  3378. : true;
  3379. const __globalInjection = !!options.globalInjection;
  3380. const __instances = new Map();
  3381. // prettier-ignore
  3382. const __global = __legacyMode
  3383. ? createVueI18n(options)
  3384. : createComposer(options);
  3385. const symbol = makeSymbol('vue-i18n' );
  3386. const i18n = {
  3387. // mode
  3388. get mode() {
  3389. // prettier-ignore
  3390. return __legacyMode
  3391. ? 'legacy'
  3392. : 'composition'
  3393. ;
  3394. },
  3395. // install plugin
  3396. async install(app, ...options) {
  3397. {
  3398. app.__VUE_I18N__ = i18n;
  3399. }
  3400. // setup global provider
  3401. app.__VUE_I18N_SYMBOL__ = symbol;
  3402. app.provide(app.__VUE_I18N_SYMBOL__, i18n);
  3403. // global method and properties injection for Composition API
  3404. if (!__legacyMode && __globalInjection) {
  3405. injectGlobalFields(app, i18n.global);
  3406. }
  3407. // install built-in components and directive
  3408. {
  3409. apply(app, i18n, ...options);
  3410. }
  3411. // setup mixin for Legacy API
  3412. if (__legacyMode) {
  3413. app.mixin(defineMixin(__global, __global.__composer, i18n));
  3414. }
  3415. // setup vue-devtools plugin
  3416. {
  3417. const ret = await enableDevTools(app, i18n);
  3418. if (!ret) {
  3419. throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */);
  3420. }
  3421. const emitter = createEmitter();
  3422. if (__legacyMode) {
  3423. const _vueI18n = __global;
  3424. _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
  3425. }
  3426. else {
  3427. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3428. const _composer = __global;
  3429. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  3430. }
  3431. emitter.on('*', addTimelineEvent);
  3432. }
  3433. },
  3434. // global accessor
  3435. get global() {
  3436. return __global;
  3437. },
  3438. // @internal
  3439. __instances,
  3440. // @internal
  3441. __getInstance(component) {
  3442. return __instances.get(component) || null;
  3443. },
  3444. // @internal
  3445. __setInstance(component, instance) {
  3446. __instances.set(component, instance);
  3447. },
  3448. // @internal
  3449. __deleteInstance(component) {
  3450. __instances.delete(component);
  3451. }
  3452. };
  3453. return i18n;
  3454. }
  3455. /**
  3456. * Use Composition API for Vue I18n
  3457. *
  3458. * @param options - An options, see {@link UseI18nOptions}
  3459. *
  3460. * @returns {@link Composer} instance
  3461. *
  3462. * @remarks
  3463. * This function is mainly used by `setup`.
  3464. *
  3465. * If options are specified, Composer instance is created for each component and you can be localized on the component.
  3466. *
  3467. * If options are not specified, you can be localized using the global Composer.
  3468. *
  3469. * @example
  3470. * case: Component resource base localization
  3471. * ```html
  3472. * <template>
  3473. * <form>
  3474. * <label>{{ t('language') }}</label>
  3475. * <select v-model="locale">
  3476. * <option value="en">en</option>
  3477. * <option value="ja">ja</option>
  3478. * </select>
  3479. * </form>
  3480. * <p>message: {{ t('hello') }}</p>
  3481. * </template>
  3482. *
  3483. * <script>
  3484. * import { useI18n } from 'vue-i18n'
  3485. *
  3486. * export default {
  3487. * setup() {
  3488. * const { t, locale } = useI18n({
  3489. * locale: 'ja',
  3490. * messages: {
  3491. * en: { ... },
  3492. * ja: { ... }
  3493. * }
  3494. * })
  3495. * // Something to do ...
  3496. *
  3497. * return { ..., t, locale }
  3498. * }
  3499. * }
  3500. * </script>
  3501. * ```
  3502. *
  3503. * @VueI18nComposition
  3504. */
  3505. function useI18n(options = {}) {
  3506. const instance = getCurrentInstance();
  3507. if (instance == null) {
  3508. throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */);
  3509. }
  3510. if (!instance.appContext.app.__VUE_I18N_SYMBOL__) {
  3511. throw createI18nError(17 /* NOT_INSLALLED */);
  3512. }
  3513. const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__);
  3514. /* istanbul ignore if */
  3515. if (!i18n) {
  3516. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  3517. }
  3518. // prettier-ignore
  3519. const global = i18n.mode === 'composition'
  3520. ? i18n.global
  3521. : i18n.global.__composer;
  3522. // prettier-ignore
  3523. const scope = isEmptyObject(options)
  3524. ? ('__i18n' in instance.type)
  3525. ? 'local'
  3526. : 'global'
  3527. : !options.useScope
  3528. ? 'local'
  3529. : options.useScope;
  3530. if (scope === 'global') {
  3531. let messages = isObject(options.messages) ? options.messages : {};
  3532. if ('__i18nGlobal' in instance.type) {
  3533. messages = getLocaleMessages(global.locale.value, {
  3534. messages,
  3535. __i18n: instance.type.__i18nGlobal
  3536. });
  3537. }
  3538. // merge locale messages
  3539. const locales = Object.keys(messages);
  3540. if (locales.length) {
  3541. locales.forEach(locale => {
  3542. global.mergeLocaleMessage(locale, messages[locale]);
  3543. });
  3544. }
  3545. // merge datetime formats
  3546. if (isObject(options.datetimeFormats)) {
  3547. const locales = Object.keys(options.datetimeFormats);
  3548. if (locales.length) {
  3549. locales.forEach(locale => {
  3550. global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
  3551. });
  3552. }
  3553. }
  3554. // merge number formats
  3555. if (isObject(options.numberFormats)) {
  3556. const locales = Object.keys(options.numberFormats);
  3557. if (locales.length) {
  3558. locales.forEach(locale => {
  3559. global.mergeNumberFormat(locale, options.numberFormats[locale]);
  3560. });
  3561. }
  3562. }
  3563. return global;
  3564. }
  3565. if (scope === 'parent') {
  3566. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3567. let composer = getComposer(i18n, instance, options.__useComponent);
  3568. if (composer == null) {
  3569. {
  3570. warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */));
  3571. }
  3572. composer = global;
  3573. }
  3574. return composer;
  3575. }
  3576. // scope 'local' case
  3577. if (i18n.mode === 'legacy') {
  3578. throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */);
  3579. }
  3580. const i18nInternal = i18n;
  3581. let composer = i18nInternal.__getInstance(instance);
  3582. if (composer == null) {
  3583. const type = instance.type;
  3584. const composerOptions = assign({}, options);
  3585. if (type.__i18n) {
  3586. composerOptions.__i18n = type.__i18n;
  3587. }
  3588. if (global) {
  3589. composerOptions.__root = global;
  3590. }
  3591. composer = createComposer(composerOptions);
  3592. setupLifeCycle(i18nInternal, instance, composer);
  3593. i18nInternal.__setInstance(instance, composer);
  3594. }
  3595. return composer;
  3596. }
  3597. function getComposer(i18n, target, useComponent = false) {
  3598. let composer = null;
  3599. const root = target.root;
  3600. let current = target.parent;
  3601. while (current != null) {
  3602. const i18nInternal = i18n;
  3603. if (i18n.mode === 'composition') {
  3604. composer = i18nInternal.__getInstance(current);
  3605. }
  3606. else {
  3607. const vueI18n = i18nInternal.__getInstance(current);
  3608. if (vueI18n != null) {
  3609. composer = vueI18n
  3610. .__composer;
  3611. }
  3612. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3613. if (useComponent && composer && !composer[InejctWithOption]) {
  3614. composer = null;
  3615. }
  3616. }
  3617. if (composer != null) {
  3618. break;
  3619. }
  3620. if (root === current) {
  3621. break;
  3622. }
  3623. current = current.parent;
  3624. }
  3625. return composer;
  3626. }
  3627. function setupLifeCycle(i18n, target, composer) {
  3628. let emitter = null;
  3629. onMounted(() => {
  3630. // inject composer instance to DOM for intlify-devtools
  3631. if (target.vnode.el) {
  3632. target.vnode.el.__VUE_I18N__ = composer;
  3633. emitter = createEmitter();
  3634. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3635. const _composer = composer;
  3636. _composer[EnableEmitter] && _composer[EnableEmitter](emitter);
  3637. emitter.on('*', addTimelineEvent);
  3638. }
  3639. }, target);
  3640. onUnmounted(() => {
  3641. // remove composer instance from DOM for intlify-devtools
  3642. if (target.vnode.el &&
  3643. target.vnode.el.__VUE_I18N__) {
  3644. emitter && emitter.off('*', addTimelineEvent);
  3645. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3646. const _composer = composer;
  3647. _composer[DisableEmitter] && _composer[DisableEmitter]();
  3648. delete target.vnode.el.__VUE_I18N__;
  3649. }
  3650. i18n.__deleteInstance(target);
  3651. }, target);
  3652. }
  3653. const globalExportProps = [
  3654. 'locale',
  3655. 'fallbackLocale',
  3656. 'availableLocales'
  3657. ];
  3658. const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm'];
  3659. function injectGlobalFields(app, composer) {
  3660. const i18n = Object.create(null);
  3661. globalExportProps.forEach(prop => {
  3662. const desc = Object.getOwnPropertyDescriptor(composer, prop);
  3663. if (!desc) {
  3664. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  3665. }
  3666. const wrap = isRef(desc.value) // check computed props
  3667. ? {
  3668. get() {
  3669. return desc.value.value;
  3670. },
  3671. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3672. set(val) {
  3673. desc.value.value = val;
  3674. }
  3675. }
  3676. : {
  3677. get() {
  3678. return desc.get && desc.get();
  3679. }
  3680. };
  3681. Object.defineProperty(i18n, prop, wrap);
  3682. });
  3683. app.config.globalProperties.$i18n = i18n;
  3684. globalExportMethods.forEach(method => {
  3685. const desc = Object.getOwnPropertyDescriptor(composer, method);
  3686. if (!desc || !desc.value) {
  3687. throw createI18nError(22 /* UNEXPECTED_ERROR */);
  3688. }
  3689. Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
  3690. });
  3691. }
  3692. // NOTE: experimental !!
  3693. {
  3694. const target = getGlobalThis();
  3695. target.__INTLIFY__ = true;
  3696. setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
  3697. }
  3698. {
  3699. initDev();
  3700. }
  3701. export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective };