i18next.js 92 KB

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