i18next.js 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.i18next = factory());
  5. })(this, (function () { 'use strict';
  6. const isString = obj => typeof obj === 'string';
  7. const defer = () => {
  8. let res;
  9. let rej;
  10. const promise = new Promise((resolve, reject) => {
  11. res = resolve;
  12. rej = reject;
  13. });
  14. promise.resolve = res;
  15. promise.reject = rej;
  16. return promise;
  17. };
  18. const makeString = object => {
  19. if (object == null) return '';
  20. return '' + object;
  21. };
  22. const copy = (a, s, t) => {
  23. a.forEach(m => {
  24. if (s[m]) t[m] = s[m];
  25. });
  26. };
  27. const lastOfPathSeparatorRegExp = /###/g;
  28. const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;
  29. const canNotTraverseDeeper = object => !object || isString(object);
  30. const getLastOfPath = (object, path, Empty) => {
  31. const stack = !isString(path) ? path : path.split('.');
  32. let stackIndex = 0;
  33. while (stackIndex < stack.length - 1) {
  34. if (canNotTraverseDeeper(object)) return {};
  35. const key = cleanKey(stack[stackIndex]);
  36. if (!object[key] && Empty) object[key] = new Empty();
  37. if (Object.prototype.hasOwnProperty.call(object, key)) {
  38. object = object[key];
  39. } else {
  40. object = {};
  41. }
  42. ++stackIndex;
  43. }
  44. if (canNotTraverseDeeper(object)) return {};
  45. return {
  46. obj: object,
  47. k: cleanKey(stack[stackIndex])
  48. };
  49. };
  50. const setPath = (object, path, newValue) => {
  51. const {
  52. obj,
  53. k
  54. } = getLastOfPath(object, path, Object);
  55. if (obj !== undefined || path.length === 1) {
  56. obj[k] = newValue;
  57. return;
  58. }
  59. let e = path[path.length - 1];
  60. let p = path.slice(0, path.length - 1);
  61. let last = getLastOfPath(object, p, Object);
  62. while (last.obj === undefined && p.length) {
  63. e = `${p[p.length - 1]}.${e}`;
  64. p = p.slice(0, p.length - 1);
  65. last = getLastOfPath(object, p, Object);
  66. if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
  67. last.obj = undefined;
  68. }
  69. }
  70. last.obj[`${last.k}.${e}`] = newValue;
  71. };
  72. const pushPath = (object, path, newValue, concat) => {
  73. const {
  74. obj,
  75. k
  76. } = getLastOfPath(object, path, Object);
  77. obj[k] = obj[k] || [];
  78. obj[k].push(newValue);
  79. };
  80. const getPath = (object, path) => {
  81. const {
  82. obj,
  83. k
  84. } = getLastOfPath(object, path);
  85. if (!obj) return undefined;
  86. if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;
  87. return obj[k];
  88. };
  89. const getPathWithDefaults = (data, defaultData, key) => {
  90. const value = getPath(data, key);
  91. if (value !== undefined) {
  92. return value;
  93. }
  94. return getPath(defaultData, key);
  95. };
  96. const deepExtend = (target, source, overwrite) => {
  97. for (const prop in source) {
  98. if (prop !== '__proto__' && prop !== 'constructor') {
  99. if (prop in target) {
  100. if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
  101. if (overwrite) target[prop] = source[prop];
  102. } else {
  103. deepExtend(target[prop], source[prop], overwrite);
  104. }
  105. } else {
  106. target[prop] = source[prop];
  107. }
  108. }
  109. }
  110. return target;
  111. };
  112. const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  113. var _entityMap = {
  114. '&': '&amp;',
  115. '<': '&lt;',
  116. '>': '&gt;',
  117. '"': '&quot;',
  118. "'": '&#39;',
  119. '/': '&#x2F;'
  120. };
  121. const escape = data => {
  122. if (isString(data)) {
  123. return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
  124. }
  125. return data;
  126. };
  127. class RegExpCache {
  128. constructor(capacity) {
  129. this.capacity = capacity;
  130. this.regExpMap = new Map();
  131. this.regExpQueue = [];
  132. }
  133. getRegExp(pattern) {
  134. const regExpFromCache = this.regExpMap.get(pattern);
  135. if (regExpFromCache !== undefined) {
  136. return regExpFromCache;
  137. }
  138. const regExpNew = new RegExp(pattern);
  139. if (this.regExpQueue.length === this.capacity) {
  140. this.regExpMap.delete(this.regExpQueue.shift());
  141. }
  142. this.regExpMap.set(pattern, regExpNew);
  143. this.regExpQueue.push(pattern);
  144. return regExpNew;
  145. }
  146. }
  147. const chars = [' ', ',', '?', '!', ';'];
  148. const looksLikeObjectPathRegExpCache = new RegExpCache(20);
  149. const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
  150. nsSeparator = nsSeparator || '';
  151. keySeparator = keySeparator || '';
  152. const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
  153. if (possibleChars.length === 0) return true;
  154. const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
  155. let matched = !r.test(key);
  156. if (!matched) {
  157. const ki = key.indexOf(keySeparator);
  158. if (ki > 0 && !r.test(key.substring(0, ki))) {
  159. matched = true;
  160. }
  161. }
  162. return matched;
  163. };
  164. const deepFind = (obj, path, keySeparator = '.') => {
  165. if (!obj) return undefined;
  166. if (obj[path]) {
  167. if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;
  168. return obj[path];
  169. }
  170. const tokens = path.split(keySeparator);
  171. let current = obj;
  172. for (let i = 0; i < tokens.length;) {
  173. if (!current || typeof current !== 'object') {
  174. return undefined;
  175. }
  176. let next;
  177. let nextPath = '';
  178. for (let j = i; j < tokens.length; ++j) {
  179. if (j !== i) {
  180. nextPath += keySeparator;
  181. }
  182. nextPath += tokens[j];
  183. next = current[nextPath];
  184. if (next !== undefined) {
  185. if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {
  186. continue;
  187. }
  188. i += j - i + 1;
  189. break;
  190. }
  191. }
  192. current = next;
  193. }
  194. return current;
  195. };
  196. const getCleanedCode = code => code?.replace('_', '-');
  197. const consoleLogger = {
  198. type: 'logger',
  199. log(args) {
  200. this.output('log', args);
  201. },
  202. warn(args) {
  203. this.output('warn', args);
  204. },
  205. error(args) {
  206. this.output('error', args);
  207. },
  208. output(type, args) {
  209. console?.[type]?.apply?.(console, args);
  210. }
  211. };
  212. class Logger {
  213. constructor(concreteLogger, options = {}) {
  214. this.init(concreteLogger, options);
  215. }
  216. init(concreteLogger, options = {}) {
  217. this.prefix = options.prefix || 'i18next:';
  218. this.logger = concreteLogger || consoleLogger;
  219. this.options = options;
  220. this.debug = options.debug;
  221. }
  222. log(...args) {
  223. return this.forward(args, 'log', '', true);
  224. }
  225. warn(...args) {
  226. return this.forward(args, 'warn', '', true);
  227. }
  228. error(...args) {
  229. return this.forward(args, 'error', '');
  230. }
  231. deprecate(...args) {
  232. return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
  233. }
  234. forward(args, lvl, prefix, debugOnly) {
  235. if (debugOnly && !this.debug) return null;
  236. if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
  237. return this.logger[lvl](args);
  238. }
  239. create(moduleName) {
  240. return new Logger(this.logger, {
  241. ...{
  242. prefix: `${this.prefix}:${moduleName}:`
  243. },
  244. ...this.options
  245. });
  246. }
  247. clone(options) {
  248. options = options || this.options;
  249. options.prefix = options.prefix || this.prefix;
  250. return new Logger(this.logger, options);
  251. }
  252. }
  253. var baseLogger = new Logger();
  254. class EventEmitter {
  255. constructor() {
  256. this.observers = {};
  257. }
  258. on(events, listener) {
  259. events.split(' ').forEach(event => {
  260. if (!this.observers[event]) this.observers[event] = new Map();
  261. const numListeners = this.observers[event].get(listener) || 0;
  262. this.observers[event].set(listener, numListeners + 1);
  263. });
  264. return this;
  265. }
  266. off(event, listener) {
  267. if (!this.observers[event]) return;
  268. if (!listener) {
  269. delete this.observers[event];
  270. return;
  271. }
  272. this.observers[event].delete(listener);
  273. }
  274. emit(event, ...args) {
  275. if (this.observers[event]) {
  276. const cloned = Array.from(this.observers[event].entries());
  277. cloned.forEach(([observer, numTimesAdded]) => {
  278. for (let i = 0; i < numTimesAdded; i++) {
  279. observer(...args);
  280. }
  281. });
  282. }
  283. if (this.observers['*']) {
  284. const cloned = Array.from(this.observers['*'].entries());
  285. cloned.forEach(([observer, numTimesAdded]) => {
  286. for (let i = 0; i < numTimesAdded; i++) {
  287. observer.apply(observer, [event, ...args]);
  288. }
  289. });
  290. }
  291. }
  292. }
  293. class ResourceStore extends EventEmitter {
  294. constructor(data, options = {
  295. ns: ['translation'],
  296. defaultNS: 'translation'
  297. }) {
  298. super();
  299. this.data = data || {};
  300. this.options = options;
  301. if (this.options.keySeparator === undefined) {
  302. this.options.keySeparator = '.';
  303. }
  304. if (this.options.ignoreJSONStructure === undefined) {
  305. this.options.ignoreJSONStructure = true;
  306. }
  307. }
  308. addNamespaces(ns) {
  309. if (this.options.ns.indexOf(ns) < 0) {
  310. this.options.ns.push(ns);
  311. }
  312. }
  313. removeNamespaces(ns) {
  314. const index = this.options.ns.indexOf(ns);
  315. if (index > -1) {
  316. this.options.ns.splice(index, 1);
  317. }
  318. }
  319. getResource(lng, ns, key, options = {}) {
  320. const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
  321. const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
  322. let path;
  323. if (lng.indexOf('.') > -1) {
  324. path = lng.split('.');
  325. } else {
  326. path = [lng, ns];
  327. if (key) {
  328. if (Array.isArray(key)) {
  329. path.push(...key);
  330. } else if (isString(key) && keySeparator) {
  331. path.push(...key.split(keySeparator));
  332. } else {
  333. path.push(key);
  334. }
  335. }
  336. }
  337. const result = getPath(this.data, path);
  338. if (!result && !ns && !key && lng.indexOf('.') > -1) {
  339. lng = path[0];
  340. ns = path[1];
  341. key = path.slice(2).join('.');
  342. }
  343. if (result || !ignoreJSONStructure || !isString(key)) return result;
  344. return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
  345. }
  346. addResource(lng, ns, key, value, options = {
  347. silent: false
  348. }) {
  349. const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
  350. let path = [lng, ns];
  351. if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
  352. if (lng.indexOf('.') > -1) {
  353. path = lng.split('.');
  354. value = ns;
  355. ns = path[1];
  356. }
  357. this.addNamespaces(ns);
  358. setPath(this.data, path, value);
  359. if (!options.silent) this.emit('added', lng, ns, key, value);
  360. }
  361. addResources(lng, ns, resources, options = {
  362. silent: false
  363. }) {
  364. for (const m in resources) {
  365. if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
  366. silent: true
  367. });
  368. }
  369. if (!options.silent) this.emit('added', lng, ns, resources);
  370. }
  371. addResourceBundle(lng, ns, resources, deep, overwrite, options = {
  372. silent: false,
  373. skipCopy: false
  374. }) {
  375. let path = [lng, ns];
  376. if (lng.indexOf('.') > -1) {
  377. path = lng.split('.');
  378. deep = resources;
  379. resources = ns;
  380. ns = path[1];
  381. }
  382. this.addNamespaces(ns);
  383. let pack = getPath(this.data, path) || {};
  384. if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
  385. if (deep) {
  386. deepExtend(pack, resources, overwrite);
  387. } else {
  388. pack = {
  389. ...pack,
  390. ...resources
  391. };
  392. }
  393. setPath(this.data, path, pack);
  394. if (!options.silent) this.emit('added', lng, ns, resources);
  395. }
  396. removeResourceBundle(lng, ns) {
  397. if (this.hasResourceBundle(lng, ns)) {
  398. delete this.data[lng][ns];
  399. }
  400. this.removeNamespaces(ns);
  401. this.emit('removed', lng, ns);
  402. }
  403. hasResourceBundle(lng, ns) {
  404. return this.getResource(lng, ns) !== undefined;
  405. }
  406. getResourceBundle(lng, ns) {
  407. if (!ns) ns = this.options.defaultNS;
  408. return this.getResource(lng, ns);
  409. }
  410. getDataByLanguage(lng) {
  411. return this.data[lng];
  412. }
  413. hasLanguageSomeTranslations(lng) {
  414. const data = this.getDataByLanguage(lng);
  415. const n = data && Object.keys(data) || [];
  416. return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
  417. }
  418. toJSON() {
  419. return this.data;
  420. }
  421. }
  422. var postProcessor = {
  423. processors: {},
  424. addPostProcessor(module) {
  425. this.processors[module.name] = module;
  426. },
  427. handle(processors, value, key, options, translator) {
  428. processors.forEach(processor => {
  429. value = this.processors[processor]?.process(value, key, options, translator) ?? value;
  430. });
  431. return value;
  432. }
  433. };
  434. const PATH_KEY = Symbol('i18next/PATH_KEY');
  435. function createProxy() {
  436. const state = [];
  437. const handler = Object.create(null);
  438. let proxy;
  439. handler.get = (target, key) => {
  440. proxy?.revoke?.();
  441. if (key === PATH_KEY) return state;
  442. state.push(key);
  443. proxy = Proxy.revocable(target, handler);
  444. return proxy.proxy;
  445. };
  446. return Proxy.revocable(Object.create(null), handler).proxy;
  447. }
  448. function keysFromSelector(selector, opts) {
  449. const {
  450. [PATH_KEY]: path
  451. } = selector(createProxy());
  452. return path.join(opts?.keySeparator ?? '.');
  453. }
  454. const checkedLoadedFor = {};
  455. const shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';
  456. class Translator extends EventEmitter {
  457. constructor(services, options = {}) {
  458. super();
  459. copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
  460. this.options = options;
  461. if (this.options.keySeparator === undefined) {
  462. this.options.keySeparator = '.';
  463. }
  464. this.logger = baseLogger.create('translator');
  465. }
  466. changeLanguage(lng) {
  467. if (lng) this.language = lng;
  468. }
  469. exists(key, o = {
  470. interpolation: {}
  471. }) {
  472. const opt = {
  473. ...o
  474. };
  475. if (key == null) return false;
  476. const resolved = this.resolve(key, opt);
  477. if (resolved?.res === undefined) return false;
  478. const isObject = shouldHandleAsObject(resolved.res);
  479. if (opt.returnObjects === false && isObject) {
  480. return false;
  481. }
  482. return true;
  483. }
  484. extractFromKey(key, opt) {
  485. let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
  486. if (nsSeparator === undefined) nsSeparator = ':';
  487. const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
  488. let namespaces = opt.ns || this.options.defaultNS || [];
  489. const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
  490. const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
  491. if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
  492. const m = key.match(this.interpolator.nestingRegexp);
  493. if (m && m.length > 0) {
  494. return {
  495. key,
  496. namespaces: isString(namespaces) ? [namespaces] : namespaces
  497. };
  498. }
  499. const parts = key.split(nsSeparator);
  500. if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
  501. key = parts.join(keySeparator);
  502. }
  503. return {
  504. key,
  505. namespaces: isString(namespaces) ? [namespaces] : namespaces
  506. };
  507. }
  508. translate(keys, o, lastKey) {
  509. let opt = typeof o === 'object' ? {
  510. ...o
  511. } : o;
  512. if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {
  513. opt = this.options.overloadTranslationOptionHandler(arguments);
  514. }
  515. if (typeof opt === 'object') opt = {
  516. ...opt
  517. };
  518. if (!opt) opt = {};
  519. if (keys == null) return '';
  520. if (typeof keys === 'function') keys = keysFromSelector(keys, {
  521. ...this.options,
  522. ...opt
  523. });
  524. if (!Array.isArray(keys)) keys = [String(keys)];
  525. const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
  526. const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
  527. const {
  528. key,
  529. namespaces
  530. } = this.extractFromKey(keys[keys.length - 1], opt);
  531. const namespace = namespaces[namespaces.length - 1];
  532. let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
  533. if (nsSeparator === undefined) nsSeparator = ':';
  534. const lng = opt.lng || this.language;
  535. const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
  536. if (lng?.toLowerCase() === 'cimode') {
  537. if (appendNamespaceToCIMode) {
  538. if (returnDetails) {
  539. return {
  540. res: `${namespace}${nsSeparator}${key}`,
  541. usedKey: key,
  542. exactUsedKey: key,
  543. usedLng: lng,
  544. usedNS: namespace,
  545. usedParams: this.getUsedParamsDetails(opt)
  546. };
  547. }
  548. return `${namespace}${nsSeparator}${key}`;
  549. }
  550. if (returnDetails) {
  551. return {
  552. res: key,
  553. usedKey: key,
  554. exactUsedKey: key,
  555. usedLng: lng,
  556. usedNS: namespace,
  557. usedParams: this.getUsedParamsDetails(opt)
  558. };
  559. }
  560. return key;
  561. }
  562. const resolved = this.resolve(keys, opt);
  563. let res = resolved?.res;
  564. const resUsedKey = resolved?.usedKey || key;
  565. const resExactUsedKey = resolved?.exactUsedKey || key;
  566. const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
  567. const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
  568. const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
  569. const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
  570. const hasDefaultValue = Translator.hasDefaultValue(opt);
  571. const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';
  572. const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
  573. ordinal: false
  574. }) : '';
  575. const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
  576. const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
  577. let resForObjHndl = res;
  578. if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
  579. resForObjHndl = defaultValue;
  580. }
  581. const handleAsObject = shouldHandleAsObject(resForObjHndl);
  582. const resType = Object.prototype.toString.apply(resForObjHndl);
  583. if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
  584. if (!opt.returnObjects && !this.options.returnObjects) {
  585. if (!this.options.returnedObjectHandler) {
  586. this.logger.warn('accessing an object - but returnObjects options is not enabled!');
  587. }
  588. const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
  589. ...opt,
  590. ns: namespaces
  591. }) : `key '${key} (${this.language})' returned an object instead of string.`;
  592. if (returnDetails) {
  593. resolved.res = r;
  594. resolved.usedParams = this.getUsedParamsDetails(opt);
  595. return resolved;
  596. }
  597. return r;
  598. }
  599. if (keySeparator) {
  600. const resTypeIsArray = Array.isArray(resForObjHndl);
  601. const copy = resTypeIsArray ? [] : {};
  602. const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
  603. for (const m in resForObjHndl) {
  604. if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
  605. const deepKey = `${newKeyToUse}${keySeparator}${m}`;
  606. if (hasDefaultValue && !res) {
  607. copy[m] = this.translate(deepKey, {
  608. ...opt,
  609. defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
  610. ...{
  611. joinArrays: false,
  612. ns: namespaces
  613. }
  614. });
  615. } else {
  616. copy[m] = this.translate(deepKey, {
  617. ...opt,
  618. ...{
  619. joinArrays: false,
  620. ns: namespaces
  621. }
  622. });
  623. }
  624. if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
  625. }
  626. }
  627. res = copy;
  628. }
  629. } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
  630. res = res.join(joinArrays);
  631. if (res) res = this.extendTranslation(res, keys, opt, lastKey);
  632. } else {
  633. let usedDefault = false;
  634. let usedKey = false;
  635. if (!this.isValidLookup(res) && hasDefaultValue) {
  636. usedDefault = true;
  637. res = defaultValue;
  638. }
  639. if (!this.isValidLookup(res)) {
  640. usedKey = true;
  641. res = key;
  642. }
  643. const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
  644. const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
  645. const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
  646. if (usedKey || usedDefault || updateMissing) {
  647. this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
  648. if (keySeparator) {
  649. const fk = this.resolve(key, {
  650. ...opt,
  651. keySeparator: false
  652. });
  653. if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');
  654. }
  655. let lngs = [];
  656. const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
  657. if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
  658. for (let i = 0; i < fallbackLngs.length; i++) {
  659. lngs.push(fallbackLngs[i]);
  660. }
  661. } else if (this.options.saveMissingTo === 'all') {
  662. lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
  663. } else {
  664. lngs.push(opt.lng || this.language);
  665. }
  666. const send = (l, k, specificDefaultValue) => {
  667. const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
  668. if (this.options.missingKeyHandler) {
  669. this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
  670. } else if (this.backendConnector?.saveMissing) {
  671. this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
  672. }
  673. this.emit('missingKey', l, namespace, k, res);
  674. };
  675. if (this.options.saveMissing) {
  676. if (this.options.saveMissingPlurals && needsPluralHandling) {
  677. lngs.forEach(language => {
  678. const suffixes = this.pluralResolver.getSuffixes(language, opt);
  679. if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
  680. suffixes.push(`${this.options.pluralSeparator}zero`);
  681. }
  682. suffixes.forEach(suffix => {
  683. send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
  684. });
  685. });
  686. } else {
  687. send(lngs, key, defaultValue);
  688. }
  689. }
  690. }
  691. res = this.extendTranslation(res, keys, opt, resolved, lastKey);
  692. if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
  693. res = `${namespace}${nsSeparator}${key}`;
  694. }
  695. if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
  696. res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
  697. }
  698. }
  699. if (returnDetails) {
  700. resolved.res = res;
  701. resolved.usedParams = this.getUsedParamsDetails(opt);
  702. return resolved;
  703. }
  704. return res;
  705. }
  706. extendTranslation(res, key, opt, resolved, lastKey) {
  707. if (this.i18nFormat?.parse) {
  708. res = this.i18nFormat.parse(res, {
  709. ...this.options.interpolation.defaultVariables,
  710. ...opt
  711. }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
  712. resolved
  713. });
  714. } else if (!opt.skipInterpolation) {
  715. if (opt.interpolation) this.interpolator.init({
  716. ...opt,
  717. ...{
  718. interpolation: {
  719. ...this.options.interpolation,
  720. ...opt.interpolation
  721. }
  722. }
  723. });
  724. const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
  725. let nestBef;
  726. if (skipOnVariables) {
  727. const nb = res.match(this.interpolator.nestingRegexp);
  728. nestBef = nb && nb.length;
  729. }
  730. let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
  731. if (this.options.interpolation.defaultVariables) data = {
  732. ...this.options.interpolation.defaultVariables,
  733. ...data
  734. };
  735. res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
  736. if (skipOnVariables) {
  737. const na = res.match(this.interpolator.nestingRegexp);
  738. const nestAft = na && na.length;
  739. if (nestBef < nestAft) opt.nest = false;
  740. }
  741. if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
  742. if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
  743. if (lastKey?.[0] === args[0] && !opt.context) {
  744. this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
  745. return null;
  746. }
  747. return this.translate(...args, key);
  748. }, opt);
  749. if (opt.interpolation) this.interpolator.reset();
  750. }
  751. const postProcess = opt.postProcess || this.options.postProcess;
  752. const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
  753. if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
  754. res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
  755. i18nResolved: {
  756. ...resolved,
  757. usedParams: this.getUsedParamsDetails(opt)
  758. },
  759. ...opt
  760. } : opt, this);
  761. }
  762. return res;
  763. }
  764. resolve(keys, opt = {}) {
  765. let found;
  766. let usedKey;
  767. let exactUsedKey;
  768. let usedLng;
  769. let usedNS;
  770. if (isString(keys)) keys = [keys];
  771. keys.forEach(k => {
  772. if (this.isValidLookup(found)) return;
  773. const extracted = this.extractFromKey(k, opt);
  774. const key = extracted.key;
  775. usedKey = key;
  776. let namespaces = extracted.namespaces;
  777. if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
  778. const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
  779. const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
  780. const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== '';
  781. const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
  782. namespaces.forEach(ns => {
  783. if (this.isValidLookup(found)) return;
  784. usedNS = ns;
  785. if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
  786. checkedLoadedFor[`${codes[0]}-${ns}`] = true;
  787. this.logger.warn(`key "${usedKey}" for languages "${codes.join(', ')}" won't get resolved as namespace "${usedNS}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
  788. }
  789. codes.forEach(code => {
  790. if (this.isValidLookup(found)) return;
  791. usedLng = code;
  792. const finalKeys = [key];
  793. if (this.i18nFormat?.addLookupKeys) {
  794. this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
  795. } else {
  796. let pluralSuffix;
  797. if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
  798. const zeroSuffix = `${this.options.pluralSeparator}zero`;
  799. const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
  800. if (needsPluralHandling) {
  801. if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
  802. finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
  803. }
  804. finalKeys.push(key + pluralSuffix);
  805. if (needsZeroSuffixLookup) {
  806. finalKeys.push(key + zeroSuffix);
  807. }
  808. }
  809. if (needsContextHandling) {
  810. const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;
  811. finalKeys.push(contextKey);
  812. if (needsPluralHandling) {
  813. if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
  814. finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
  815. }
  816. finalKeys.push(contextKey + pluralSuffix);
  817. if (needsZeroSuffixLookup) {
  818. finalKeys.push(contextKey + zeroSuffix);
  819. }
  820. }
  821. }
  822. }
  823. let possibleKey;
  824. while (possibleKey = finalKeys.pop()) {
  825. if (!this.isValidLookup(found)) {
  826. exactUsedKey = possibleKey;
  827. found = this.getResource(code, ns, possibleKey, opt);
  828. }
  829. }
  830. });
  831. });
  832. });
  833. return {
  834. res: found,
  835. usedKey,
  836. exactUsedKey,
  837. usedLng,
  838. usedNS
  839. };
  840. }
  841. isValidLookup(res) {
  842. return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
  843. }
  844. getResource(code, ns, key, options = {}) {
  845. if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
  846. return this.resourceStore.getResource(code, ns, key, options);
  847. }
  848. getUsedParamsDetails(options = {}) {
  849. const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];
  850. const useOptionsReplaceForData = options.replace && !isString(options.replace);
  851. let data = useOptionsReplaceForData ? options.replace : options;
  852. if (useOptionsReplaceForData && typeof options.count !== 'undefined') {
  853. data.count = options.count;
  854. }
  855. if (this.options.interpolation.defaultVariables) {
  856. data = {
  857. ...this.options.interpolation.defaultVariables,
  858. ...data
  859. };
  860. }
  861. if (!useOptionsReplaceForData) {
  862. data = {
  863. ...data
  864. };
  865. for (const key of optionsKeys) {
  866. delete data[key];
  867. }
  868. }
  869. return data;
  870. }
  871. static hasDefaultValue(options) {
  872. const prefix = 'defaultValue';
  873. for (const option in options) {
  874. if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
  875. return true;
  876. }
  877. }
  878. return false;
  879. }
  880. }
  881. class LanguageUtil {
  882. constructor(options) {
  883. this.options = options;
  884. this.supportedLngs = this.options.supportedLngs || false;
  885. this.logger = baseLogger.create('languageUtils');
  886. }
  887. getScriptPartFromCode(code) {
  888. code = getCleanedCode(code);
  889. if (!code || code.indexOf('-') < 0) return null;
  890. const p = code.split('-');
  891. if (p.length === 2) return null;
  892. p.pop();
  893. if (p[p.length - 1].toLowerCase() === 'x') return null;
  894. return this.formatLanguageCode(p.join('-'));
  895. }
  896. getLanguagePartFromCode(code) {
  897. code = getCleanedCode(code);
  898. if (!code || code.indexOf('-') < 0) return code;
  899. const p = code.split('-');
  900. return this.formatLanguageCode(p[0]);
  901. }
  902. formatLanguageCode(code) {
  903. if (isString(code) && code.indexOf('-') > -1) {
  904. let formattedCode;
  905. try {
  906. formattedCode = Intl.getCanonicalLocales(code)[0];
  907. } catch (e) {}
  908. if (formattedCode && this.options.lowerCaseLng) {
  909. formattedCode = formattedCode.toLowerCase();
  910. }
  911. if (formattedCode) return formattedCode;
  912. if (this.options.lowerCaseLng) {
  913. return code.toLowerCase();
  914. }
  915. return code;
  916. }
  917. return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
  918. }
  919. isSupportedCode(code) {
  920. if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
  921. code = this.getLanguagePartFromCode(code);
  922. }
  923. return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
  924. }
  925. getBestMatchFromCodes(codes) {
  926. if (!codes) return null;
  927. let found;
  928. codes.forEach(code => {
  929. if (found) return;
  930. const cleanedLng = this.formatLanguageCode(code);
  931. if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
  932. });
  933. if (!found && this.options.supportedLngs) {
  934. codes.forEach(code => {
  935. if (found) return;
  936. const lngScOnly = this.getScriptPartFromCode(code);
  937. if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
  938. const lngOnly = this.getLanguagePartFromCode(code);
  939. if (this.isSupportedCode(lngOnly)) return found = lngOnly;
  940. found = this.options.supportedLngs.find(supportedLng => {
  941. if (supportedLng === lngOnly) return supportedLng;
  942. if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
  943. if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;
  944. if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
  945. });
  946. });
  947. }
  948. if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
  949. return found;
  950. }
  951. getFallbackCodes(fallbacks, code) {
  952. if (!fallbacks) return [];
  953. if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
  954. if (isString(fallbacks)) fallbacks = [fallbacks];
  955. if (Array.isArray(fallbacks)) return fallbacks;
  956. if (!code) return fallbacks.default || [];
  957. let found = fallbacks[code];
  958. if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
  959. if (!found) found = fallbacks[this.formatLanguageCode(code)];
  960. if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
  961. if (!found) found = fallbacks.default;
  962. return found || [];
  963. }
  964. toResolveHierarchy(code, fallbackCode) {
  965. const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
  966. const codes = [];
  967. const addCode = c => {
  968. if (!c) return;
  969. if (this.isSupportedCode(c)) {
  970. codes.push(c);
  971. } else {
  972. this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
  973. }
  974. };
  975. if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
  976. if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
  977. if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
  978. if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
  979. } else if (isString(code)) {
  980. addCode(this.formatLanguageCode(code));
  981. }
  982. fallbackCodes.forEach(fc => {
  983. if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
  984. });
  985. return codes;
  986. }
  987. }
  988. const suffixesOrder = {
  989. zero: 0,
  990. one: 1,
  991. two: 2,
  992. few: 3,
  993. many: 4,
  994. other: 5
  995. };
  996. const dummyRule = {
  997. select: count => count === 1 ? 'one' : 'other',
  998. resolvedOptions: () => ({
  999. pluralCategories: ['one', 'other']
  1000. })
  1001. };
  1002. class PluralResolver {
  1003. constructor(languageUtils, options = {}) {
  1004. this.languageUtils = languageUtils;
  1005. this.options = options;
  1006. this.logger = baseLogger.create('pluralResolver');
  1007. this.pluralRulesCache = {};
  1008. }
  1009. addRule(lng, obj) {
  1010. this.rules[lng] = obj;
  1011. }
  1012. clearCache() {
  1013. this.pluralRulesCache = {};
  1014. }
  1015. getRule(code, options = {}) {
  1016. const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);
  1017. const type = options.ordinal ? 'ordinal' : 'cardinal';
  1018. const cacheKey = JSON.stringify({
  1019. cleanedCode,
  1020. type
  1021. });
  1022. if (cacheKey in this.pluralRulesCache) {
  1023. return this.pluralRulesCache[cacheKey];
  1024. }
  1025. let rule;
  1026. try {
  1027. rule = new Intl.PluralRules(cleanedCode, {
  1028. type
  1029. });
  1030. } catch (err) {
  1031. if (!Intl) {
  1032. this.logger.error('No Intl support, please use an Intl polyfill!');
  1033. return dummyRule;
  1034. }
  1035. if (!code.match(/-|_/)) return dummyRule;
  1036. const lngPart = this.languageUtils.getLanguagePartFromCode(code);
  1037. rule = this.getRule(lngPart, options);
  1038. }
  1039. this.pluralRulesCache[cacheKey] = rule;
  1040. return rule;
  1041. }
  1042. needsPlural(code, options = {}) {
  1043. let rule = this.getRule(code, options);
  1044. if (!rule) rule = this.getRule('dev', options);
  1045. return rule?.resolvedOptions().pluralCategories.length > 1;
  1046. }
  1047. getPluralFormsOfKey(code, key, options = {}) {
  1048. return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
  1049. }
  1050. getSuffixes(code, options = {}) {
  1051. let rule = this.getRule(code, options);
  1052. if (!rule) rule = this.getRule('dev', options);
  1053. if (!rule) return [];
  1054. return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
  1055. }
  1056. getSuffix(code, count, options = {}) {
  1057. const rule = this.getRule(code, options);
  1058. if (rule) {
  1059. return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
  1060. }
  1061. this.logger.warn(`no plural rule found for: ${code}`);
  1062. return this.getSuffix('dev', count, options);
  1063. }
  1064. }
  1065. const deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {
  1066. let path = getPathWithDefaults(data, defaultData, key);
  1067. if (!path && ignoreJSONStructure && isString(key)) {
  1068. path = deepFind(data, key, keySeparator);
  1069. if (path === undefined) path = deepFind(defaultData, key, keySeparator);
  1070. }
  1071. return path;
  1072. };
  1073. const regexSafe = val => val.replace(/\$/g, '$$$$');
  1074. class Interpolator {
  1075. constructor(options = {}) {
  1076. this.logger = baseLogger.create('interpolator');
  1077. this.options = options;
  1078. this.format = options?.interpolation?.format || (value => value);
  1079. this.init(options);
  1080. }
  1081. init(options = {}) {
  1082. if (!options.interpolation) options.interpolation = {
  1083. escapeValue: true
  1084. };
  1085. const {
  1086. escape: escape$1,
  1087. escapeValue,
  1088. useRawValueToEscape,
  1089. prefix,
  1090. prefixEscaped,
  1091. suffix,
  1092. suffixEscaped,
  1093. formatSeparator,
  1094. unescapeSuffix,
  1095. unescapePrefix,
  1096. nestingPrefix,
  1097. nestingPrefixEscaped,
  1098. nestingSuffix,
  1099. nestingSuffixEscaped,
  1100. nestingOptionsSeparator,
  1101. maxReplaces,
  1102. alwaysFormat
  1103. } = options.interpolation;
  1104. this.escape = escape$1 !== undefined ? escape$1 : escape;
  1105. this.escapeValue = escapeValue !== undefined ? escapeValue : true;
  1106. this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
  1107. this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';
  1108. this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';
  1109. this.formatSeparator = formatSeparator || ',';
  1110. this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';
  1111. this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';
  1112. this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');
  1113. this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');
  1114. this.nestingOptionsSeparator = nestingOptionsSeparator || ',';
  1115. this.maxReplaces = maxReplaces || 1000;
  1116. this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
  1117. this.resetRegExp();
  1118. }
  1119. reset() {
  1120. if (this.options) this.init(this.options);
  1121. }
  1122. resetRegExp() {
  1123. const getOrResetRegExp = (existingRegExp, pattern) => {
  1124. if (existingRegExp?.source === pattern) {
  1125. existingRegExp.lastIndex = 0;
  1126. return existingRegExp;
  1127. }
  1128. return new RegExp(pattern, 'g');
  1129. };
  1130. this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
  1131. this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
  1132. this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
  1133. }
  1134. interpolate(str, data, lng, options) {
  1135. let match;
  1136. let value;
  1137. let replaces;
  1138. const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
  1139. const handleFormat = key => {
  1140. if (key.indexOf(this.formatSeparator) < 0) {
  1141. const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
  1142. return this.alwaysFormat ? this.format(path, undefined, lng, {
  1143. ...options,
  1144. ...data,
  1145. interpolationkey: key
  1146. }) : path;
  1147. }
  1148. const p = key.split(this.formatSeparator);
  1149. const k = p.shift().trim();
  1150. const f = p.join(this.formatSeparator).trim();
  1151. return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
  1152. ...options,
  1153. ...data,
  1154. interpolationkey: k
  1155. });
  1156. };
  1157. this.resetRegExp();
  1158. const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
  1159. const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
  1160. const todos = [{
  1161. regex: this.regexpUnescape,
  1162. safeValue: val => regexSafe(val)
  1163. }, {
  1164. regex: this.regexp,
  1165. safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
  1166. }];
  1167. todos.forEach(todo => {
  1168. replaces = 0;
  1169. while (match = todo.regex.exec(str)) {
  1170. const matchedVar = match[1].trim();
  1171. value = handleFormat(matchedVar);
  1172. if (value === undefined) {
  1173. if (typeof missingInterpolationHandler === 'function') {
  1174. const temp = missingInterpolationHandler(str, match, options);
  1175. value = isString(temp) ? temp : '';
  1176. } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
  1177. value = '';
  1178. } else if (skipOnVariables) {
  1179. value = match[0];
  1180. continue;
  1181. } else {
  1182. this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
  1183. value = '';
  1184. }
  1185. } else if (!isString(value) && !this.useRawValueToEscape) {
  1186. value = makeString(value);
  1187. }
  1188. const safeValue = todo.safeValue(value);
  1189. str = str.replace(match[0], safeValue);
  1190. if (skipOnVariables) {
  1191. todo.regex.lastIndex += value.length;
  1192. todo.regex.lastIndex -= match[0].length;
  1193. } else {
  1194. todo.regex.lastIndex = 0;
  1195. }
  1196. replaces++;
  1197. if (replaces >= this.maxReplaces) {
  1198. break;
  1199. }
  1200. }
  1201. });
  1202. return str;
  1203. }
  1204. nest(str, fc, options = {}) {
  1205. let match;
  1206. let value;
  1207. let clonedOptions;
  1208. const handleHasOptions = (key, inheritedOptions) => {
  1209. const sep = this.nestingOptionsSeparator;
  1210. if (key.indexOf(sep) < 0) return key;
  1211. const c = key.split(new RegExp(`${sep}[ ]*{`));
  1212. let optionsString = `{${c[1]}`;
  1213. key = c[0];
  1214. optionsString = this.interpolate(optionsString, clonedOptions);
  1215. const matchedSingleQuotes = optionsString.match(/'/g);
  1216. const matchedDoubleQuotes = optionsString.match(/"/g);
  1217. if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
  1218. optionsString = optionsString.replace(/'/g, '"');
  1219. }
  1220. try {
  1221. clonedOptions = JSON.parse(optionsString);
  1222. if (inheritedOptions) clonedOptions = {
  1223. ...inheritedOptions,
  1224. ...clonedOptions
  1225. };
  1226. } catch (e) {
  1227. this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
  1228. return `${key}${sep}${optionsString}`;
  1229. }
  1230. if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
  1231. return key;
  1232. };
  1233. while (match = this.nestingRegexp.exec(str)) {
  1234. let formatters = [];
  1235. clonedOptions = {
  1236. ...options
  1237. };
  1238. clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
  1239. clonedOptions.applyPostProcessor = false;
  1240. delete clonedOptions.defaultValue;
  1241. const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);
  1242. if (keyEndIndex !== -1) {
  1243. formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);
  1244. match[1] = match[1].slice(0, keyEndIndex);
  1245. }
  1246. value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
  1247. if (value && match[0] === str && !isString(value)) return value;
  1248. if (!isString(value)) value = makeString(value);
  1249. if (!value) {
  1250. this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
  1251. value = '';
  1252. }
  1253. if (formatters.length) {
  1254. value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
  1255. ...options,
  1256. interpolationkey: match[1].trim()
  1257. }), value.trim());
  1258. }
  1259. str = str.replace(match[0], value);
  1260. this.regexp.lastIndex = 0;
  1261. }
  1262. return str;
  1263. }
  1264. }
  1265. const parseFormatStr = formatStr => {
  1266. let formatName = formatStr.toLowerCase().trim();
  1267. const formatOptions = {};
  1268. if (formatStr.indexOf('(') > -1) {
  1269. const p = formatStr.split('(');
  1270. formatName = p[0].toLowerCase().trim();
  1271. const optStr = p[1].substring(0, p[1].length - 1);
  1272. if (formatName === 'currency' && optStr.indexOf(':') < 0) {
  1273. if (!formatOptions.currency) formatOptions.currency = optStr.trim();
  1274. } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
  1275. if (!formatOptions.range) formatOptions.range = optStr.trim();
  1276. } else {
  1277. const opts = optStr.split(';');
  1278. opts.forEach(opt => {
  1279. if (opt) {
  1280. const [key, ...rest] = opt.split(':');
  1281. const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
  1282. const trimmedKey = key.trim();
  1283. if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
  1284. if (val === 'false') formatOptions[trimmedKey] = false;
  1285. if (val === 'true') formatOptions[trimmedKey] = true;
  1286. if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
  1287. }
  1288. });
  1289. }
  1290. }
  1291. return {
  1292. formatName,
  1293. formatOptions
  1294. };
  1295. };
  1296. const createCachedFormatter = fn => {
  1297. const cache = {};
  1298. return (v, l, o) => {
  1299. let optForCache = o;
  1300. if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
  1301. optForCache = {
  1302. ...optForCache,
  1303. [o.interpolationkey]: undefined
  1304. };
  1305. }
  1306. const key = l + JSON.stringify(optForCache);
  1307. let frm = cache[key];
  1308. if (!frm) {
  1309. frm = fn(getCleanedCode(l), o);
  1310. cache[key] = frm;
  1311. }
  1312. return frm(v);
  1313. };
  1314. };
  1315. const createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);
  1316. class Formatter {
  1317. constructor(options = {}) {
  1318. this.logger = baseLogger.create('formatter');
  1319. this.options = options;
  1320. this.init(options);
  1321. }
  1322. init(services, options = {
  1323. interpolation: {}
  1324. }) {
  1325. this.formatSeparator = options.interpolation.formatSeparator || ',';
  1326. const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
  1327. this.formats = {
  1328. number: cf((lng, opt) => {
  1329. const formatter = new Intl.NumberFormat(lng, {
  1330. ...opt
  1331. });
  1332. return val => formatter.format(val);
  1333. }),
  1334. currency: cf((lng, opt) => {
  1335. const formatter = new Intl.NumberFormat(lng, {
  1336. ...opt,
  1337. style: 'currency'
  1338. });
  1339. return val => formatter.format(val);
  1340. }),
  1341. datetime: cf((lng, opt) => {
  1342. const formatter = new Intl.DateTimeFormat(lng, {
  1343. ...opt
  1344. });
  1345. return val => formatter.format(val);
  1346. }),
  1347. relativetime: cf((lng, opt) => {
  1348. const formatter = new Intl.RelativeTimeFormat(lng, {
  1349. ...opt
  1350. });
  1351. return val => formatter.format(val, opt.range || 'day');
  1352. }),
  1353. list: cf((lng, opt) => {
  1354. const formatter = new Intl.ListFormat(lng, {
  1355. ...opt
  1356. });
  1357. return val => formatter.format(val);
  1358. })
  1359. };
  1360. }
  1361. add(name, fc) {
  1362. this.formats[name.toLowerCase().trim()] = fc;
  1363. }
  1364. addCached(name, fc) {
  1365. this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
  1366. }
  1367. format(value, format, lng, options = {}) {
  1368. const formats = format.split(this.formatSeparator);
  1369. if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {
  1370. const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);
  1371. formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
  1372. }
  1373. const result = formats.reduce((mem, f) => {
  1374. const {
  1375. formatName,
  1376. formatOptions
  1377. } = parseFormatStr(f);
  1378. if (this.formats[formatName]) {
  1379. let formatted = mem;
  1380. try {
  1381. const valOptions = options?.formatParams?.[options.interpolationkey] || {};
  1382. const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
  1383. formatted = this.formats[formatName](mem, l, {
  1384. ...formatOptions,
  1385. ...options,
  1386. ...valOptions
  1387. });
  1388. } catch (error) {
  1389. this.logger.warn(error);
  1390. }
  1391. return formatted;
  1392. } else {
  1393. this.logger.warn(`there was no format function for ${formatName}`);
  1394. }
  1395. return mem;
  1396. }, value);
  1397. return result;
  1398. }
  1399. }
  1400. const removePending = (q, name) => {
  1401. if (q.pending[name] !== undefined) {
  1402. delete q.pending[name];
  1403. q.pendingCount--;
  1404. }
  1405. };
  1406. class Connector extends EventEmitter {
  1407. constructor(backend, store, services, options = {}) {
  1408. super();
  1409. this.backend = backend;
  1410. this.store = store;
  1411. this.services = services;
  1412. this.languageUtils = services.languageUtils;
  1413. this.options = options;
  1414. this.logger = baseLogger.create('backendConnector');
  1415. this.waitingReads = [];
  1416. this.maxParallelReads = options.maxParallelReads || 10;
  1417. this.readingCalls = 0;
  1418. this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
  1419. this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
  1420. this.state = {};
  1421. this.queue = [];
  1422. this.backend?.init?.(services, options.backend, options);
  1423. }
  1424. queueLoad(languages, namespaces, options, callback) {
  1425. const toLoad = {};
  1426. const pending = {};
  1427. const toLoadLanguages = {};
  1428. const toLoadNamespaces = {};
  1429. languages.forEach(lng => {
  1430. let hasAllNamespaces = true;
  1431. namespaces.forEach(ns => {
  1432. const name = `${lng}|${ns}`;
  1433. if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
  1434. this.state[name] = 2;
  1435. } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
  1436. if (pending[name] === undefined) pending[name] = true;
  1437. } else {
  1438. this.state[name] = 1;
  1439. hasAllNamespaces = false;
  1440. if (pending[name] === undefined) pending[name] = true;
  1441. if (toLoad[name] === undefined) toLoad[name] = true;
  1442. if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
  1443. }
  1444. });
  1445. if (!hasAllNamespaces) toLoadLanguages[lng] = true;
  1446. });
  1447. if (Object.keys(toLoad).length || Object.keys(pending).length) {
  1448. this.queue.push({
  1449. pending,
  1450. pendingCount: Object.keys(pending).length,
  1451. loaded: {},
  1452. errors: [],
  1453. callback
  1454. });
  1455. }
  1456. return {
  1457. toLoad: Object.keys(toLoad),
  1458. pending: Object.keys(pending),
  1459. toLoadLanguages: Object.keys(toLoadLanguages),
  1460. toLoadNamespaces: Object.keys(toLoadNamespaces)
  1461. };
  1462. }
  1463. loaded(name, err, data) {
  1464. const s = name.split('|');
  1465. const lng = s[0];
  1466. const ns = s[1];
  1467. if (err) this.emit('failedLoading', lng, ns, err);
  1468. if (!err && data) {
  1469. this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
  1470. skipCopy: true
  1471. });
  1472. }
  1473. this.state[name] = err ? -1 : 2;
  1474. if (err && data) this.state[name] = 0;
  1475. const loaded = {};
  1476. this.queue.forEach(q => {
  1477. pushPath(q.loaded, [lng], ns);
  1478. removePending(q, name);
  1479. if (err) q.errors.push(err);
  1480. if (q.pendingCount === 0 && !q.done) {
  1481. Object.keys(q.loaded).forEach(l => {
  1482. if (!loaded[l]) loaded[l] = {};
  1483. const loadedKeys = q.loaded[l];
  1484. if (loadedKeys.length) {
  1485. loadedKeys.forEach(n => {
  1486. if (loaded[l][n] === undefined) loaded[l][n] = true;
  1487. });
  1488. }
  1489. });
  1490. q.done = true;
  1491. if (q.errors.length) {
  1492. q.callback(q.errors);
  1493. } else {
  1494. q.callback();
  1495. }
  1496. }
  1497. });
  1498. this.emit('loaded', loaded);
  1499. this.queue = this.queue.filter(q => !q.done);
  1500. }
  1501. read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
  1502. if (!lng.length) return callback(null, {});
  1503. if (this.readingCalls >= this.maxParallelReads) {
  1504. this.waitingReads.push({
  1505. lng,
  1506. ns,
  1507. fcName,
  1508. tried,
  1509. wait,
  1510. callback
  1511. });
  1512. return;
  1513. }
  1514. this.readingCalls++;
  1515. const resolver = (err, data) => {
  1516. this.readingCalls--;
  1517. if (this.waitingReads.length > 0) {
  1518. const next = this.waitingReads.shift();
  1519. this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
  1520. }
  1521. if (err && data && tried < this.maxRetries) {
  1522. setTimeout(() => {
  1523. this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
  1524. }, wait);
  1525. return;
  1526. }
  1527. callback(err, data);
  1528. };
  1529. const fc = this.backend[fcName].bind(this.backend);
  1530. if (fc.length === 2) {
  1531. try {
  1532. const r = fc(lng, ns);
  1533. if (r && typeof r.then === 'function') {
  1534. r.then(data => resolver(null, data)).catch(resolver);
  1535. } else {
  1536. resolver(null, r);
  1537. }
  1538. } catch (err) {
  1539. resolver(err);
  1540. }
  1541. return;
  1542. }
  1543. return fc(lng, ns, resolver);
  1544. }
  1545. prepareLoading(languages, namespaces, options = {}, callback) {
  1546. if (!this.backend) {
  1547. this.logger.warn('No backend was added via i18next.use. Will not load resources.');
  1548. return callback && callback();
  1549. }
  1550. if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
  1551. if (isString(namespaces)) namespaces = [namespaces];
  1552. const toLoad = this.queueLoad(languages, namespaces, options, callback);
  1553. if (!toLoad.toLoad.length) {
  1554. if (!toLoad.pending.length) callback();
  1555. return null;
  1556. }
  1557. toLoad.toLoad.forEach(name => {
  1558. this.loadOne(name);
  1559. });
  1560. }
  1561. load(languages, namespaces, callback) {
  1562. this.prepareLoading(languages, namespaces, {}, callback);
  1563. }
  1564. reload(languages, namespaces, callback) {
  1565. this.prepareLoading(languages, namespaces, {
  1566. reload: true
  1567. }, callback);
  1568. }
  1569. loadOne(name, prefix = '') {
  1570. const s = name.split('|');
  1571. const lng = s[0];
  1572. const ns = s[1];
  1573. this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
  1574. if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
  1575. if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
  1576. this.loaded(name, err, data);
  1577. });
  1578. }
  1579. saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
  1580. if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
  1581. this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
  1582. return;
  1583. }
  1584. if (key === undefined || key === null || key === '') return;
  1585. if (this.backend?.create) {
  1586. const opts = {
  1587. ...options,
  1588. isUpdate
  1589. };
  1590. const fc = this.backend.create.bind(this.backend);
  1591. if (fc.length < 6) {
  1592. try {
  1593. let r;
  1594. if (fc.length === 5) {
  1595. r = fc(languages, namespace, key, fallbackValue, opts);
  1596. } else {
  1597. r = fc(languages, namespace, key, fallbackValue);
  1598. }
  1599. if (r && typeof r.then === 'function') {
  1600. r.then(data => clb(null, data)).catch(clb);
  1601. } else {
  1602. clb(null, r);
  1603. }
  1604. } catch (err) {
  1605. clb(err);
  1606. }
  1607. } else {
  1608. fc(languages, namespace, key, fallbackValue, clb, opts);
  1609. }
  1610. }
  1611. if (!languages || !languages[0]) return;
  1612. this.store.addResource(languages[0], namespace, key, fallbackValue);
  1613. }
  1614. }
  1615. const get = () => ({
  1616. debug: false,
  1617. initAsync: true,
  1618. ns: ['translation'],
  1619. defaultNS: ['translation'],
  1620. fallbackLng: ['dev'],
  1621. fallbackNS: false,
  1622. supportedLngs: false,
  1623. nonExplicitSupportedLngs: false,
  1624. load: 'all',
  1625. preload: false,
  1626. simplifyPluralSuffix: true,
  1627. keySeparator: '.',
  1628. nsSeparator: ':',
  1629. pluralSeparator: '_',
  1630. contextSeparator: '_',
  1631. partialBundledLanguages: false,
  1632. saveMissing: false,
  1633. updateMissing: false,
  1634. saveMissingTo: 'fallback',
  1635. saveMissingPlurals: true,
  1636. missingKeyHandler: false,
  1637. missingInterpolationHandler: false,
  1638. postProcess: false,
  1639. postProcessPassResolved: false,
  1640. returnNull: false,
  1641. returnEmptyString: true,
  1642. returnObjects: false,
  1643. joinArrays: false,
  1644. returnedObjectHandler: false,
  1645. parseMissingKeyHandler: false,
  1646. appendNamespaceToMissingKey: false,
  1647. appendNamespaceToCIMode: false,
  1648. overloadTranslationOptionHandler: args => {
  1649. let ret = {};
  1650. if (typeof args[1] === 'object') ret = args[1];
  1651. if (isString(args[1])) ret.defaultValue = args[1];
  1652. if (isString(args[2])) ret.tDescription = args[2];
  1653. if (typeof args[2] === 'object' || typeof args[3] === 'object') {
  1654. const options = args[3] || args[2];
  1655. Object.keys(options).forEach(key => {
  1656. ret[key] = options[key];
  1657. });
  1658. }
  1659. return ret;
  1660. },
  1661. interpolation: {
  1662. escapeValue: true,
  1663. format: value => value,
  1664. prefix: '{{',
  1665. suffix: '}}',
  1666. formatSeparator: ',',
  1667. unescapePrefix: '-',
  1668. nestingPrefix: '$t(',
  1669. nestingSuffix: ')',
  1670. nestingOptionsSeparator: ',',
  1671. maxReplaces: 1000,
  1672. skipOnVariables: true
  1673. },
  1674. cacheInBuiltFormats: true
  1675. });
  1676. const transformOptions = options => {
  1677. if (isString(options.ns)) options.ns = [options.ns];
  1678. if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
  1679. if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
  1680. if (options.supportedLngs?.indexOf?.('cimode') < 0) {
  1681. options.supportedLngs = options.supportedLngs.concat(['cimode']);
  1682. }
  1683. if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;
  1684. return options;
  1685. };
  1686. const noop = () => {};
  1687. const bindMemberFunctions = inst => {
  1688. const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
  1689. mems.forEach(mem => {
  1690. if (typeof inst[mem] === 'function') {
  1691. inst[mem] = inst[mem].bind(inst);
  1692. }
  1693. });
  1694. };
  1695. class I18n extends EventEmitter {
  1696. constructor(options = {}, callback) {
  1697. super();
  1698. this.options = transformOptions(options);
  1699. this.services = {};
  1700. this.logger = baseLogger;
  1701. this.modules = {
  1702. external: []
  1703. };
  1704. bindMemberFunctions(this);
  1705. if (callback && !this.isInitialized && !options.isClone) {
  1706. if (!this.options.initAsync) {
  1707. this.init(options, callback);
  1708. return this;
  1709. }
  1710. setTimeout(() => {
  1711. this.init(options, callback);
  1712. }, 0);
  1713. }
  1714. }
  1715. init(options = {}, callback) {
  1716. this.isInitializing = true;
  1717. if (typeof options === 'function') {
  1718. callback = options;
  1719. options = {};
  1720. }
  1721. if (options.defaultNS == null && options.ns) {
  1722. if (isString(options.ns)) {
  1723. options.defaultNS = options.ns;
  1724. } else if (options.ns.indexOf('translation') < 0) {
  1725. options.defaultNS = options.ns[0];
  1726. }
  1727. }
  1728. const defOpts = get();
  1729. this.options = {
  1730. ...defOpts,
  1731. ...this.options,
  1732. ...transformOptions(options)
  1733. };
  1734. this.options.interpolation = {
  1735. ...defOpts.interpolation,
  1736. ...this.options.interpolation
  1737. };
  1738. if (options.keySeparator !== undefined) {
  1739. this.options.userDefinedKeySeparator = options.keySeparator;
  1740. }
  1741. if (options.nsSeparator !== undefined) {
  1742. this.options.userDefinedNsSeparator = options.nsSeparator;
  1743. }
  1744. const createClassOnDemand = ClassOrObject => {
  1745. if (!ClassOrObject) return null;
  1746. if (typeof ClassOrObject === 'function') return new ClassOrObject();
  1747. return ClassOrObject;
  1748. };
  1749. if (!this.options.isClone) {
  1750. if (this.modules.logger) {
  1751. baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
  1752. } else {
  1753. baseLogger.init(null, this.options);
  1754. }
  1755. let formatter;
  1756. if (this.modules.formatter) {
  1757. formatter = this.modules.formatter;
  1758. } else {
  1759. formatter = Formatter;
  1760. }
  1761. const lu = new LanguageUtil(this.options);
  1762. this.store = new ResourceStore(this.options.resources, this.options);
  1763. const s = this.services;
  1764. s.logger = baseLogger;
  1765. s.resourceStore = this.store;
  1766. s.languageUtils = lu;
  1767. s.pluralResolver = new PluralResolver(lu, {
  1768. prepend: this.options.pluralSeparator,
  1769. simplifyPluralSuffix: this.options.simplifyPluralSuffix
  1770. });
  1771. const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
  1772. if (usingLegacyFormatFunction) {
  1773. this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
  1774. }
  1775. if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
  1776. s.formatter = createClassOnDemand(formatter);
  1777. if (s.formatter.init) s.formatter.init(s, this.options);
  1778. this.options.interpolation.format = s.formatter.format.bind(s.formatter);
  1779. }
  1780. s.interpolator = new Interpolator(this.options);
  1781. s.utils = {
  1782. hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
  1783. };
  1784. s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
  1785. s.backendConnector.on('*', (event, ...args) => {
  1786. this.emit(event, ...args);
  1787. });
  1788. if (this.modules.languageDetector) {
  1789. s.languageDetector = createClassOnDemand(this.modules.languageDetector);
  1790. if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
  1791. }
  1792. if (this.modules.i18nFormat) {
  1793. s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
  1794. if (s.i18nFormat.init) s.i18nFormat.init(this);
  1795. }
  1796. this.translator = new Translator(this.services, this.options);
  1797. this.translator.on('*', (event, ...args) => {
  1798. this.emit(event, ...args);
  1799. });
  1800. this.modules.external.forEach(m => {
  1801. if (m.init) m.init(this);
  1802. });
  1803. }
  1804. this.format = this.options.interpolation.format;
  1805. if (!callback) callback = noop;
  1806. if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
  1807. const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
  1808. if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
  1809. }
  1810. if (!this.services.languageDetector && !this.options.lng) {
  1811. this.logger.warn('init: no languageDetector is used and no lng is defined');
  1812. }
  1813. const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
  1814. storeApi.forEach(fcName => {
  1815. this[fcName] = (...args) => this.store[fcName](...args);
  1816. });
  1817. const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
  1818. storeApiChained.forEach(fcName => {
  1819. this[fcName] = (...args) => {
  1820. this.store[fcName](...args);
  1821. return this;
  1822. };
  1823. });
  1824. const deferred = defer();
  1825. const load = () => {
  1826. const finish = (err, t) => {
  1827. this.isInitializing = false;
  1828. if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
  1829. this.isInitialized = true;
  1830. if (!this.options.isClone) this.logger.log('initialized', this.options);
  1831. this.emit('initialized', this.options);
  1832. deferred.resolve(t);
  1833. callback(err, t);
  1834. };
  1835. if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
  1836. this.changeLanguage(this.options.lng, finish);
  1837. };
  1838. if (this.options.resources || !this.options.initAsync) {
  1839. load();
  1840. } else {
  1841. setTimeout(load, 0);
  1842. }
  1843. return deferred;
  1844. }
  1845. loadResources(language, callback = noop) {
  1846. let usedCallback = callback;
  1847. const usedLng = isString(language) ? language : this.language;
  1848. if (typeof language === 'function') usedCallback = language;
  1849. if (!this.options.resources || this.options.partialBundledLanguages) {
  1850. if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
  1851. const toLoad = [];
  1852. const append = lng => {
  1853. if (!lng) return;
  1854. if (lng === 'cimode') return;
  1855. const lngs = this.services.languageUtils.toResolveHierarchy(lng);
  1856. lngs.forEach(l => {
  1857. if (l === 'cimode') return;
  1858. if (toLoad.indexOf(l) < 0) toLoad.push(l);
  1859. });
  1860. };
  1861. if (!usedLng) {
  1862. const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
  1863. fallbacks.forEach(l => append(l));
  1864. } else {
  1865. append(usedLng);
  1866. }
  1867. this.options.preload?.forEach?.(l => append(l));
  1868. this.services.backendConnector.load(toLoad, this.options.ns, e => {
  1869. if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
  1870. usedCallback(e);
  1871. });
  1872. } else {
  1873. usedCallback(null);
  1874. }
  1875. }
  1876. reloadResources(lngs, ns, callback) {
  1877. const deferred = defer();
  1878. if (typeof lngs === 'function') {
  1879. callback = lngs;
  1880. lngs = undefined;
  1881. }
  1882. if (typeof ns === 'function') {
  1883. callback = ns;
  1884. ns = undefined;
  1885. }
  1886. if (!lngs) lngs = this.languages;
  1887. if (!ns) ns = this.options.ns;
  1888. if (!callback) callback = noop;
  1889. this.services.backendConnector.reload(lngs, ns, err => {
  1890. deferred.resolve();
  1891. callback(err);
  1892. });
  1893. return deferred;
  1894. }
  1895. use(module) {
  1896. if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
  1897. if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
  1898. if (module.type === 'backend') {
  1899. this.modules.backend = module;
  1900. }
  1901. if (module.type === 'logger' || module.log && module.warn && module.error) {
  1902. this.modules.logger = module;
  1903. }
  1904. if (module.type === 'languageDetector') {
  1905. this.modules.languageDetector = module;
  1906. }
  1907. if (module.type === 'i18nFormat') {
  1908. this.modules.i18nFormat = module;
  1909. }
  1910. if (module.type === 'postProcessor') {
  1911. postProcessor.addPostProcessor(module);
  1912. }
  1913. if (module.type === 'formatter') {
  1914. this.modules.formatter = module;
  1915. }
  1916. if (module.type === '3rdParty') {
  1917. this.modules.external.push(module);
  1918. }
  1919. return this;
  1920. }
  1921. setResolvedLanguage(l) {
  1922. if (!l || !this.languages) return;
  1923. if (['cimode', 'dev'].indexOf(l) > -1) return;
  1924. for (let li = 0; li < this.languages.length; li++) {
  1925. const lngInLngs = this.languages[li];
  1926. if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
  1927. if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
  1928. this.resolvedLanguage = lngInLngs;
  1929. break;
  1930. }
  1931. }
  1932. if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
  1933. this.resolvedLanguage = l;
  1934. this.languages.unshift(l);
  1935. }
  1936. }
  1937. changeLanguage(lng, callback) {
  1938. this.isLanguageChangingTo = lng;
  1939. const deferred = defer();
  1940. this.emit('languageChanging', lng);
  1941. const setLngProps = l => {
  1942. this.language = l;
  1943. this.languages = this.services.languageUtils.toResolveHierarchy(l);
  1944. this.resolvedLanguage = undefined;
  1945. this.setResolvedLanguage(l);
  1946. };
  1947. const done = (err, l) => {
  1948. if (l) {
  1949. if (this.isLanguageChangingTo === lng) {
  1950. setLngProps(l);
  1951. this.translator.changeLanguage(l);
  1952. this.isLanguageChangingTo = undefined;
  1953. this.emit('languageChanged', l);
  1954. this.logger.log('languageChanged', l);
  1955. }
  1956. } else {
  1957. this.isLanguageChangingTo = undefined;
  1958. }
  1959. deferred.resolve((...args) => this.t(...args));
  1960. if (callback) callback(err, (...args) => this.t(...args));
  1961. };
  1962. const setLng = lngs => {
  1963. if (!lng && !lngs && this.services.languageDetector) lngs = [];
  1964. const fl = isString(lngs) ? lngs : lngs && lngs[0];
  1965. const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
  1966. if (l) {
  1967. if (!this.language) {
  1968. setLngProps(l);
  1969. }
  1970. if (!this.translator.language) this.translator.changeLanguage(l);
  1971. this.services.languageDetector?.cacheUserLanguage?.(l);
  1972. }
  1973. this.loadResources(l, err => {
  1974. done(err, l);
  1975. });
  1976. };
  1977. if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
  1978. setLng(this.services.languageDetector.detect());
  1979. } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
  1980. if (this.services.languageDetector.detect.length === 0) {
  1981. this.services.languageDetector.detect().then(setLng);
  1982. } else {
  1983. this.services.languageDetector.detect(setLng);
  1984. }
  1985. } else {
  1986. setLng(lng);
  1987. }
  1988. return deferred;
  1989. }
  1990. getFixedT(lng, ns, keyPrefix) {
  1991. const fixedT = (key, opts, ...rest) => {
  1992. let o;
  1993. if (typeof opts !== 'object') {
  1994. o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
  1995. } else {
  1996. o = {
  1997. ...opts
  1998. };
  1999. }
  2000. o.lng = o.lng || fixedT.lng;
  2001. o.lngs = o.lngs || fixedT.lngs;
  2002. o.ns = o.ns || fixedT.ns;
  2003. if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
  2004. const keySeparator = this.options.keySeparator || '.';
  2005. let resultKey;
  2006. if (o.keyPrefix && Array.isArray(key)) {
  2007. resultKey = key.map(k => {
  2008. if (typeof k === 'function') k = keysFromSelector(k, {
  2009. ...this.options,
  2010. ...opts
  2011. });
  2012. return `${o.keyPrefix}${keySeparator}${k}`;
  2013. });
  2014. } else {
  2015. if (typeof key === 'function') key = keysFromSelector(key, {
  2016. ...this.options,
  2017. ...opts
  2018. });
  2019. resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
  2020. }
  2021. return this.t(resultKey, o);
  2022. };
  2023. if (isString(lng)) {
  2024. fixedT.lng = lng;
  2025. } else {
  2026. fixedT.lngs = lng;
  2027. }
  2028. fixedT.ns = ns;
  2029. fixedT.keyPrefix = keyPrefix;
  2030. return fixedT;
  2031. }
  2032. t(...args) {
  2033. return this.translator?.translate(...args);
  2034. }
  2035. exists(...args) {
  2036. return this.translator?.exists(...args);
  2037. }
  2038. setDefaultNamespace(ns) {
  2039. this.options.defaultNS = ns;
  2040. }
  2041. hasLoadedNamespace(ns, options = {}) {
  2042. if (!this.isInitialized) {
  2043. this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
  2044. return false;
  2045. }
  2046. if (!this.languages || !this.languages.length) {
  2047. this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
  2048. return false;
  2049. }
  2050. const lng = options.lng || this.resolvedLanguage || this.languages[0];
  2051. const fallbackLng = this.options ? this.options.fallbackLng : false;
  2052. const lastLng = this.languages[this.languages.length - 1];
  2053. if (lng.toLowerCase() === 'cimode') return true;
  2054. const loadNotPending = (l, n) => {
  2055. const loadState = this.services.backendConnector.state[`${l}|${n}`];
  2056. return loadState === -1 || loadState === 0 || loadState === 2;
  2057. };
  2058. if (options.precheck) {
  2059. const preResult = options.precheck(this, loadNotPending);
  2060. if (preResult !== undefined) return preResult;
  2061. }
  2062. if (this.hasResourceBundle(lng, ns)) return true;
  2063. if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
  2064. if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
  2065. return false;
  2066. }
  2067. loadNamespaces(ns, callback) {
  2068. const deferred = defer();
  2069. if (!this.options.ns) {
  2070. if (callback) callback();
  2071. return Promise.resolve();
  2072. }
  2073. if (isString(ns)) ns = [ns];
  2074. ns.forEach(n => {
  2075. if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
  2076. });
  2077. this.loadResources(err => {
  2078. deferred.resolve();
  2079. if (callback) callback(err);
  2080. });
  2081. return deferred;
  2082. }
  2083. loadLanguages(lngs, callback) {
  2084. const deferred = defer();
  2085. if (isString(lngs)) lngs = [lngs];
  2086. const preloaded = this.options.preload || [];
  2087. const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
  2088. if (!newLngs.length) {
  2089. if (callback) callback();
  2090. return Promise.resolve();
  2091. }
  2092. this.options.preload = preloaded.concat(newLngs);
  2093. this.loadResources(err => {
  2094. deferred.resolve();
  2095. if (callback) callback(err);
  2096. });
  2097. return deferred;
  2098. }
  2099. dir(lng) {
  2100. if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
  2101. if (!lng) return 'rtl';
  2102. try {
  2103. const l = new Intl.Locale(lng);
  2104. if (l && l.getTextInfo) {
  2105. const ti = l.getTextInfo();
  2106. if (ti && ti.direction) return ti.direction;
  2107. }
  2108. } catch (e) {}
  2109. const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
  2110. const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
  2111. if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';
  2112. return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
  2113. }
  2114. static createInstance(options = {}, callback) {
  2115. const instance = new I18n(options, callback);
  2116. instance.createInstance = I18n.createInstance;
  2117. return instance;
  2118. }
  2119. cloneInstance(options = {}, callback = noop) {
  2120. const forkResourceStore = options.forkResourceStore;
  2121. if (forkResourceStore) delete options.forkResourceStore;
  2122. const mergedOptions = {
  2123. ...this.options,
  2124. ...options,
  2125. ...{
  2126. isClone: true
  2127. }
  2128. };
  2129. const clone = new I18n(mergedOptions);
  2130. if (options.debug !== undefined || options.prefix !== undefined) {
  2131. clone.logger = clone.logger.clone(options);
  2132. }
  2133. const membersToCopy = ['store', 'services', 'language'];
  2134. membersToCopy.forEach(m => {
  2135. clone[m] = this[m];
  2136. });
  2137. clone.services = {
  2138. ...this.services
  2139. };
  2140. clone.services.utils = {
  2141. hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
  2142. };
  2143. if (forkResourceStore) {
  2144. const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
  2145. prev[l] = {
  2146. ...this.store.data[l]
  2147. };
  2148. prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
  2149. acc[n] = {
  2150. ...prev[l][n]
  2151. };
  2152. return acc;
  2153. }, prev[l]);
  2154. return prev;
  2155. }, {});
  2156. clone.store = new ResourceStore(clonedData, mergedOptions);
  2157. clone.services.resourceStore = clone.store;
  2158. }
  2159. if (options.interpolation) clone.services.interpolator = new Interpolator(mergedOptions);
  2160. clone.translator = new Translator(clone.services, mergedOptions);
  2161. clone.translator.on('*', (event, ...args) => {
  2162. clone.emit(event, ...args);
  2163. });
  2164. clone.init(mergedOptions, callback);
  2165. clone.translator.options = mergedOptions;
  2166. clone.translator.backendConnector.services.utils = {
  2167. hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
  2168. };
  2169. return clone;
  2170. }
  2171. toJSON() {
  2172. return {
  2173. options: this.options,
  2174. store: this.store,
  2175. language: this.language,
  2176. languages: this.languages,
  2177. resolvedLanguage: this.resolvedLanguage
  2178. };
  2179. }
  2180. }
  2181. const instance = I18n.createInstance();
  2182. instance.keyFromSelector = keysFromSelector;
  2183. return instance;
  2184. }));