i18next.js 78 KB

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