i18next.js 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global.i18next = factory());
  5. }(this, (function () { 'use strict';
  6. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  7. return typeof obj;
  8. } : function (obj) {
  9. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  10. };
  11. var classCallCheck = function (instance, Constructor) {
  12. if (!(instance instanceof Constructor)) {
  13. throw new TypeError("Cannot call a class as a function");
  14. }
  15. };
  16. var _extends = Object.assign || function (target) {
  17. for (var i = 1; i < arguments.length; i++) {
  18. var source = arguments[i];
  19. for (var key in source) {
  20. if (Object.prototype.hasOwnProperty.call(source, key)) {
  21. target[key] = source[key];
  22. }
  23. }
  24. }
  25. return target;
  26. };
  27. var inherits = function (subClass, superClass) {
  28. if (typeof superClass !== "function" && superClass !== null) {
  29. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  30. }
  31. subClass.prototype = Object.create(superClass && superClass.prototype, {
  32. constructor: {
  33. value: subClass,
  34. enumerable: false,
  35. writable: true,
  36. configurable: true
  37. }
  38. });
  39. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  40. };
  41. var possibleConstructorReturn = function (self, call) {
  42. if (!self) {
  43. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  44. }
  45. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  46. };
  47. var slicedToArray = function () {
  48. function sliceIterator(arr, i) {
  49. var _arr = [];
  50. var _n = true;
  51. var _d = false;
  52. var _e = undefined;
  53. try {
  54. for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
  55. _arr.push(_s.value);
  56. if (i && _arr.length === i) break;
  57. }
  58. } catch (err) {
  59. _d = true;
  60. _e = err;
  61. } finally {
  62. try {
  63. if (!_n && _i["return"]) _i["return"]();
  64. } finally {
  65. if (_d) throw _e;
  66. }
  67. }
  68. return _arr;
  69. }
  70. return function (arr, i) {
  71. if (Array.isArray(arr)) {
  72. return arr;
  73. } else if (Symbol.iterator in Object(arr)) {
  74. return sliceIterator(arr, i);
  75. } else {
  76. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  77. }
  78. };
  79. }();
  80. var consoleLogger = {
  81. type: 'logger',
  82. log: function log(args) {
  83. this._output('log', args);
  84. },
  85. warn: function warn(args) {
  86. this._output('warn', args);
  87. },
  88. error: function error(args) {
  89. this._output('error', args);
  90. },
  91. _output: function _output(type, args) {
  92. if (console && console[type]) console[type].apply(console, Array.prototype.slice.call(args));
  93. }
  94. };
  95. var Logger = function () {
  96. function Logger(concreteLogger) {
  97. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  98. classCallCheck(this, Logger);
  99. this.init(concreteLogger, options);
  100. }
  101. Logger.prototype.init = function init(concreteLogger) {
  102. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  103. this.prefix = options.prefix || 'i18next:';
  104. this.logger = concreteLogger || consoleLogger;
  105. this.options = options;
  106. this.debug = options.debug === false ? false : true;
  107. };
  108. Logger.prototype.setDebug = function setDebug(bool) {
  109. this.debug = bool;
  110. };
  111. Logger.prototype.log = function log() {
  112. this.forward(arguments, 'log', '', true);
  113. };
  114. Logger.prototype.warn = function warn() {
  115. this.forward(arguments, 'warn', '', true);
  116. };
  117. Logger.prototype.error = function error() {
  118. this.forward(arguments, 'error', '');
  119. };
  120. Logger.prototype.deprecate = function deprecate() {
  121. this.forward(arguments, 'warn', 'WARNING DEPRECATED: ', true);
  122. };
  123. Logger.prototype.forward = function forward(args, lvl, prefix, debugOnly) {
  124. if (debugOnly && !this.debug) return;
  125. if (typeof args[0] === 'string') args[0] = prefix + this.prefix + ' ' + args[0];
  126. this.logger[lvl](args);
  127. };
  128. Logger.prototype.create = function create(moduleName) {
  129. var sub = new Logger(this.logger, _extends({ prefix: this.prefix + ':' + moduleName + ':' }, this.options));
  130. return sub;
  131. };
  132. // createInstance(options = {}) {
  133. // return new Logger(options, callback);
  134. // }
  135. return Logger;
  136. }();
  137. var baseLogger = new Logger();
  138. var EventEmitter = function () {
  139. function EventEmitter() {
  140. classCallCheck(this, EventEmitter);
  141. this.observers = {};
  142. }
  143. EventEmitter.prototype.on = function on(events, listener) {
  144. var _this = this;
  145. events.split(' ').forEach(function (event) {
  146. _this.observers[event] = _this.observers[event] || [];
  147. _this.observers[event].push(listener);
  148. });
  149. };
  150. EventEmitter.prototype.off = function off(event, listener) {
  151. var _this2 = this;
  152. if (!this.observers[event]) {
  153. return;
  154. }
  155. this.observers[event].forEach(function () {
  156. if (!listener) {
  157. delete _this2.observers[event];
  158. } else {
  159. var index = _this2.observers[event].indexOf(listener);
  160. if (index > -1) {
  161. _this2.observers[event].splice(index, 1);
  162. }
  163. }
  164. });
  165. };
  166. EventEmitter.prototype.emit = function emit(event) {
  167. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  168. args[_key - 1] = arguments[_key];
  169. }
  170. if (this.observers[event]) {
  171. var cloned = [].concat(this.observers[event]);
  172. cloned.forEach(function (observer) {
  173. observer.apply(undefined, args);
  174. });
  175. }
  176. if (this.observers['*']) {
  177. var _cloned = [].concat(this.observers['*']);
  178. _cloned.forEach(function (observer) {
  179. var _ref;
  180. observer.apply(observer, (_ref = [event]).concat.apply(_ref, args));
  181. });
  182. }
  183. };
  184. return EventEmitter;
  185. }();
  186. function makeString(object) {
  187. if (object == null) return '';
  188. return '' + object;
  189. }
  190. function copy(a, s, t) {
  191. a.forEach(function (m) {
  192. if (s[m]) t[m] = s[m];
  193. });
  194. }
  195. function getLastOfPath(object, path, Empty) {
  196. function cleanKey(key) {
  197. return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
  198. }
  199. var stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
  200. while (stack.length > 1) {
  201. if (!object) return {};
  202. var key = cleanKey(stack.shift());
  203. if (!object[key] && Empty) object[key] = new Empty();
  204. object = object[key];
  205. }
  206. if (!object) return {};
  207. return {
  208. obj: object,
  209. k: cleanKey(stack.shift())
  210. };
  211. }
  212. function setPath(object, path, newValue) {
  213. var _getLastOfPath = getLastOfPath(object, path, Object),
  214. obj = _getLastOfPath.obj,
  215. k = _getLastOfPath.k;
  216. obj[k] = newValue;
  217. }
  218. function pushPath(object, path, newValue, concat) {
  219. var _getLastOfPath2 = getLastOfPath(object, path, Object),
  220. obj = _getLastOfPath2.obj,
  221. k = _getLastOfPath2.k;
  222. obj[k] = obj[k] || [];
  223. if (concat) obj[k] = obj[k].concat(newValue);
  224. if (!concat) obj[k].push(newValue);
  225. }
  226. function getPath(object, path) {
  227. var _getLastOfPath3 = getLastOfPath(object, path),
  228. obj = _getLastOfPath3.obj,
  229. k = _getLastOfPath3.k;
  230. if (!obj) return undefined;
  231. return obj[k];
  232. }
  233. function deepExtend(target, source, overwrite) {
  234. for (var prop in source) {
  235. if (prop in target) {
  236. // If we reached a leaf string in target or source then replace with source or skip depending on the 'overwrite' switch
  237. if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
  238. if (overwrite) target[prop] = source[prop];
  239. } else {
  240. deepExtend(target[prop], source[prop], overwrite);
  241. }
  242. } else {
  243. target[prop] = source[prop];
  244. }
  245. }return target;
  246. }
  247. function regexEscape(str) {
  248. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  249. }
  250. /* eslint-disable */
  251. var _entityMap = {
  252. "&": "&amp;",
  253. "<": "&lt;",
  254. ">": "&gt;",
  255. '"': '&quot;',
  256. "'": '&#39;',
  257. "/": '&#x2F;'
  258. };
  259. /* eslint-enable */
  260. function escape(data) {
  261. if (typeof data === 'string') {
  262. return data.replace(/[&<>"'\/]/g, function (s) {
  263. return _entityMap[s];
  264. });
  265. } else {
  266. return data;
  267. }
  268. }
  269. var ResourceStore = function (_EventEmitter) {
  270. inherits(ResourceStore, _EventEmitter);
  271. function ResourceStore() {
  272. var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  273. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { ns: ['translation'], defaultNS: 'translation' };
  274. classCallCheck(this, ResourceStore);
  275. var _this = possibleConstructorReturn(this, _EventEmitter.call(this));
  276. _this.data = data;
  277. _this.options = options;
  278. return _this;
  279. }
  280. ResourceStore.prototype.addNamespaces = function addNamespaces(ns) {
  281. if (this.options.ns.indexOf(ns) < 0) {
  282. this.options.ns.push(ns);
  283. }
  284. };
  285. ResourceStore.prototype.removeNamespaces = function removeNamespaces(ns) {
  286. var index = this.options.ns.indexOf(ns);
  287. if (index > -1) {
  288. this.options.ns.splice(index, 1);
  289. }
  290. };
  291. ResourceStore.prototype.getResource = function getResource(lng, ns, key) {
  292. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  293. var keySeparator = options.keySeparator || this.options.keySeparator;
  294. if (keySeparator === undefined) keySeparator = '.';
  295. var path = [lng, ns];
  296. if (key && typeof key !== 'string') path = path.concat(key);
  297. if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
  298. if (lng.indexOf('.') > -1) {
  299. path = lng.split('.');
  300. }
  301. return getPath(this.data, path);
  302. };
  303. ResourceStore.prototype.addResource = function addResource(lng, ns, key, value) {
  304. var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : { silent: false };
  305. var keySeparator = this.options.keySeparator;
  306. if (keySeparator === undefined) keySeparator = '.';
  307. var path = [lng, ns];
  308. if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
  309. if (lng.indexOf('.') > -1) {
  310. path = lng.split('.');
  311. value = ns;
  312. ns = path[1];
  313. }
  314. this.addNamespaces(ns);
  315. setPath(this.data, path, value);
  316. if (!options.silent) this.emit('added', lng, ns, key, value);
  317. };
  318. ResourceStore.prototype.addResources = function addResources(lng, ns, resources) {
  319. for (var m in resources) {
  320. if (typeof resources[m] === 'string') this.addResource(lng, ns, m, resources[m], { silent: true });
  321. }
  322. this.emit('added', lng, ns, resources);
  323. };
  324. ResourceStore.prototype.addResourceBundle = function addResourceBundle(lng, ns, resources, deep, overwrite) {
  325. var path = [lng, ns];
  326. if (lng.indexOf('.') > -1) {
  327. path = lng.split('.');
  328. deep = resources;
  329. resources = ns;
  330. ns = path[1];
  331. }
  332. this.addNamespaces(ns);
  333. var pack = getPath(this.data, path) || {};
  334. if (deep) {
  335. deepExtend(pack, resources, overwrite);
  336. } else {
  337. pack = _extends({}, pack, resources);
  338. }
  339. setPath(this.data, path, pack);
  340. this.emit('added', lng, ns, resources);
  341. };
  342. ResourceStore.prototype.removeResourceBundle = function removeResourceBundle(lng, ns) {
  343. if (this.hasResourceBundle(lng, ns)) {
  344. delete this.data[lng][ns];
  345. }
  346. this.removeNamespaces(ns);
  347. this.emit('removed', lng, ns);
  348. };
  349. ResourceStore.prototype.hasResourceBundle = function hasResourceBundle(lng, ns) {
  350. return this.getResource(lng, ns) !== undefined;
  351. };
  352. ResourceStore.prototype.getResourceBundle = function getResourceBundle(lng, ns) {
  353. if (!ns) ns = this.options.defaultNS;
  354. // TODO: COMPATIBILITY remove extend in v2.1.0
  355. if (this.options.compatibilityAPI === 'v1') return _extends({}, this.getResource(lng, ns));
  356. return this.getResource(lng, ns);
  357. };
  358. ResourceStore.prototype.toJSON = function toJSON() {
  359. return this.data;
  360. };
  361. return ResourceStore;
  362. }(EventEmitter);
  363. var postProcessor = {
  364. processors: {},
  365. addPostProcessor: function addPostProcessor(module) {
  366. this.processors[module.name] = module;
  367. },
  368. handle: function handle(processors, value, key, options, translator) {
  369. var _this = this;
  370. processors.forEach(function (processor) {
  371. if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator);
  372. });
  373. return value;
  374. }
  375. };
  376. function convertInterpolation(options) {
  377. options.interpolation = {
  378. unescapeSuffix: 'HTML'
  379. };
  380. options.interpolation.prefix = options.interpolationPrefix || '__';
  381. options.interpolation.suffix = options.interpolationSuffix || '__';
  382. options.interpolation.escapeValue = options.escapeInterpolation || false;
  383. options.interpolation.nestingPrefix = options.reusePrefix || '$t(';
  384. options.interpolation.nestingSuffix = options.reuseSuffix || ')';
  385. return options;
  386. }
  387. function convertAPIOptions(options) {
  388. if (options.resStore) options.resources = options.resStore;
  389. if (options.ns && options.ns.defaultNs) {
  390. options.defaultNS = options.ns.defaultNs;
  391. options.ns = options.ns.namespaces;
  392. } else {
  393. options.defaultNS = options.ns || 'translation';
  394. }
  395. if (options.fallbackToDefaultNS && options.defaultNS) options.fallbackNS = options.defaultNS;
  396. options.saveMissing = options.sendMissing;
  397. options.saveMissingTo = options.sendMissingTo || 'current';
  398. options.returnNull = options.fallbackOnNull ? false : true;
  399. options.returnEmptyString = options.fallbackOnEmpty ? false : true;
  400. options.returnObjects = options.returnObjectTrees;
  401. options.joinArrays = '\n';
  402. options.returnedObjectHandler = options.objectTreeKeyHandler;
  403. options.parseMissingKeyHandler = options.parseMissingKey;
  404. options.appendNamespaceToMissingKey = true;
  405. options.nsSeparator = options.nsseparator || ':';
  406. options.keySeparator = options.keyseparator || '.';
  407. if (options.shortcutFunction === 'sprintf') {
  408. options.overloadTranslationOptionHandler = function (args) {
  409. var values = [];
  410. for (var i = 1; i < args.length; i++) {
  411. values.push(args[i]);
  412. }
  413. return {
  414. postProcess: 'sprintf',
  415. sprintf: values
  416. };
  417. };
  418. }
  419. options.whitelist = options.lngWhitelist;
  420. options.preload = options.preload;
  421. if (options.load === 'current') options.load = 'currentOnly';
  422. if (options.load === 'unspecific') options.load = 'languageOnly';
  423. // backend
  424. options.backend = options.backend || {};
  425. options.backend.loadPath = options.resGetPath || 'locales/__lng__/__ns__.json';
  426. options.backend.addPath = options.resPostPath || 'locales/add/__lng__/__ns__';
  427. options.backend.allowMultiLoading = options.dynamicLoad;
  428. // cache
  429. options.cache = options.cache || {};
  430. options.cache.prefix = 'res_';
  431. options.cache.expirationTime = 7 * 24 * 60 * 60 * 1000;
  432. options.cache.enabled = options.useLocalStorage ? true : false;
  433. options = convertInterpolation(options);
  434. if (options.defaultVariables) options.interpolation.defaultVariables = options.defaultVariables;
  435. // TODO: deprecation
  436. // if (options.getAsync === false) throw deprecation error
  437. return options;
  438. }
  439. function convertJSONOptions(options) {
  440. options = convertInterpolation(options);
  441. options.joinArrays = '\n';
  442. return options;
  443. }
  444. function convertTOptions(options) {
  445. if (options.interpolationPrefix || options.interpolationSuffix || options.escapeInterpolation) {
  446. options = convertInterpolation(options);
  447. }
  448. options.nsSeparator = options.nsseparator;
  449. options.keySeparator = options.keyseparator;
  450. options.returnObjects = options.returnObjectTrees;
  451. return options;
  452. }
  453. function appendBackwardsAPI(i18n) {
  454. i18n.lng = function () {
  455. baseLogger.deprecate('i18next.lng() can be replaced by i18next.language for detected language or i18next.languages for languages ordered by translation lookup.');
  456. return i18n.services.languageUtils.toResolveHierarchy(i18n.language)[0];
  457. };
  458. i18n.preload = function (lngs, cb) {
  459. baseLogger.deprecate('i18next.preload() can be replaced with i18next.loadLanguages()');
  460. i18n.loadLanguages(lngs, cb);
  461. };
  462. i18n.setLng = function (lng, options, callback) {
  463. baseLogger.deprecate('i18next.setLng() can be replaced with i18next.changeLanguage() or i18next.getFixedT() to get a translation function with fixed language or namespace.');
  464. if (typeof options === 'function') {
  465. callback = options;
  466. options = {};
  467. }
  468. if (!options) options = {};
  469. if (options.fixLng === true) {
  470. if (callback) return callback(null, i18n.getFixedT(lng));
  471. }
  472. i18n.changeLanguage(lng, callback);
  473. };
  474. i18n.addPostProcessor = function (name, fc) {
  475. baseLogger.deprecate('i18next.addPostProcessor() can be replaced by i18next.use({ type: \'postProcessor\', name: \'name\', process: fc })');
  476. i18n.use({
  477. type: 'postProcessor',
  478. name: name,
  479. process: fc
  480. });
  481. };
  482. }
  483. var Translator = function (_EventEmitter) {
  484. inherits(Translator, _EventEmitter);
  485. function Translator(services) {
  486. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  487. classCallCheck(this, Translator);
  488. var _this = possibleConstructorReturn(this, _EventEmitter.call(this));
  489. copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector'], services, _this);
  490. _this.options = options;
  491. _this.logger = baseLogger.create('translator');
  492. return _this;
  493. }
  494. Translator.prototype.changeLanguage = function changeLanguage(lng) {
  495. if (lng) this.language = lng;
  496. };
  497. Translator.prototype.exists = function exists(key) {
  498. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { interpolation: {} };
  499. if (this.options.compatibilityAPI === 'v1') {
  500. options = convertTOptions(options);
  501. }
  502. return this.resolve(key, options) !== undefined;
  503. };
  504. Translator.prototype.extractFromKey = function extractFromKey(key, options) {
  505. var nsSeparator = options.nsSeparator || this.options.nsSeparator;
  506. if (nsSeparator === undefined) nsSeparator = ':';
  507. var keySeparator = options.keySeparator || this.options.keySeparator || '.';
  508. var namespaces = options.ns || this.options.defaultNS;
  509. if (nsSeparator && key.indexOf(nsSeparator) > -1) {
  510. var parts = key.split(nsSeparator);
  511. if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
  512. key = parts.join(keySeparator);
  513. }
  514. if (typeof namespaces === 'string') namespaces = [namespaces];
  515. return {
  516. key: key,
  517. namespaces: namespaces
  518. };
  519. };
  520. Translator.prototype.translate = function translate(keys) {
  521. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  522. if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') {
  523. options = this.options.overloadTranslationOptionHandler(arguments);
  524. } else if (this.options.compatibilityAPI === 'v1') {
  525. options = convertTOptions(options);
  526. }
  527. // non valid keys handling
  528. if (keys === undefined || keys === null || keys === '') return '';
  529. if (typeof keys === 'number') keys = String(keys);
  530. if (typeof keys === 'string') keys = [keys];
  531. // separators
  532. var keySeparator = options.keySeparator || this.options.keySeparator || '.';
  533. // get namespace(s)
  534. var _extractFromKey = this.extractFromKey(keys[keys.length - 1], options),
  535. key = _extractFromKey.key,
  536. namespaces = _extractFromKey.namespaces;
  537. var namespace = namespaces[namespaces.length - 1];
  538. // return key on CIMode
  539. var lng = options.lng || this.language;
  540. var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
  541. if (lng && lng.toLowerCase() === 'cimode') {
  542. if (appendNamespaceToCIMode) {
  543. var nsSeparator = options.nsSeparator || this.options.nsSeparator;
  544. return namespace + nsSeparator + key;
  545. }
  546. return key;
  547. }
  548. // resolve from store
  549. var res = this.resolve(keys, options);
  550. var resType = Object.prototype.toString.apply(res);
  551. var noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
  552. var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
  553. // object
  554. if (res && typeof res !== 'string' && noObject.indexOf(resType) < 0 && !(joinArrays && resType === '[object Array]')) {
  555. if (!options.returnObjects && !this.options.returnObjects) {
  556. this.logger.warn('accessing an object - but returnObjects options is not enabled!');
  557. return this.options.returnedObjectHandler ? this.options.returnedObjectHandler(key, res, options) : 'key \'' + key + ' (' + this.language + ')\' returned an object instead of string.';
  558. }
  559. // if we got a separator we loop over children - else we just return object as is
  560. // as having it set to false means no hierarchy so no lookup for nested values
  561. if (options.keySeparator || this.options.keySeparator) {
  562. var copy$$1 = resType === '[object Array]' ? [] : {}; // apply child translation on a copy
  563. for (var m in res) {
  564. copy$$1[m] = this.translate('' + key + keySeparator + m, _extends({}, options, { joinArrays: false, ns: namespaces }));
  565. }
  566. res = copy$$1;
  567. }
  568. }
  569. // array special treatment
  570. else if (joinArrays && resType === '[object Array]') {
  571. res = res.join(joinArrays);
  572. if (res) res = this.extendTranslation(res, key, options);
  573. }
  574. // string, empty or null
  575. else {
  576. var usedDefault = false,
  577. usedKey = false;
  578. // fallback value
  579. if (!this.isValidLookup(res) && options.defaultValue !== undefined) {
  580. usedDefault = true;
  581. res = options.defaultValue;
  582. }
  583. if (!this.isValidLookup(res)) {
  584. usedKey = true;
  585. res = key;
  586. }
  587. // save missing
  588. if (usedKey || usedDefault) {
  589. this.logger.log('missingKey', lng, namespace, key, res);
  590. var lngs = [];
  591. var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
  592. if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
  593. for (var i = 0; i < fallbackLngs.length; i++) {
  594. lngs.push(fallbackLngs[i]);
  595. }
  596. } else if (this.options.saveMissingTo === 'all') {
  597. lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
  598. } else {
  599. //(this.options.saveMissingTo === 'current' || (this.options.saveMissingTo === 'fallback' && this.options.fallbackLng[0] === false) ) {
  600. lngs.push(options.lng || this.language);
  601. }
  602. if (this.options.saveMissing) {
  603. if (this.options.missingKeyHandler) {
  604. this.options.missingKeyHandler(lngs, namespace, key, res);
  605. } else if (this.backendConnector && this.backendConnector.saveMissing) {
  606. this.backendConnector.saveMissing(lngs, namespace, key, res);
  607. }
  608. }
  609. this.emit('missingKey', lngs, namespace, key, res);
  610. }
  611. // extend
  612. res = this.extendTranslation(res, key, options);
  613. // append namespace if still key
  614. if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = namespace + ':' + key;
  615. // parseMissingKeyHandler
  616. if (usedKey && this.options.parseMissingKeyHandler) res = this.options.parseMissingKeyHandler(res);
  617. }
  618. // return
  619. return res;
  620. };
  621. Translator.prototype.extendTranslation = function extendTranslation(res, key, options) {
  622. var _this2 = this;
  623. if (options.interpolation) this.interpolator.init(_extends({}, options, { interpolation: _extends({}, this.options.interpolation, options.interpolation) }));
  624. // interpolate
  625. var data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
  626. if (this.options.interpolation.defaultVariables) data = _extends({}, this.options.interpolation.defaultVariables, data);
  627. res = this.interpolator.interpolate(res, data, this.language);
  628. // nesting
  629. res = this.interpolator.nest(res, function () {
  630. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  631. args[_key] = arguments[_key];
  632. }
  633. return _this2.translate.apply(_this2, args);
  634. }, options);
  635. if (options.interpolation) this.interpolator.reset();
  636. // post process
  637. var postProcess = options.postProcess || this.options.postProcess;
  638. var postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
  639. if (res !== undefined && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
  640. res = postProcessor.handle(postProcessorNames, res, key, options, this);
  641. }
  642. return res;
  643. };
  644. Translator.prototype.resolve = function resolve(keys) {
  645. var _this3 = this;
  646. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  647. var found = void 0;
  648. if (typeof keys === 'string') keys = [keys];
  649. // forEach possible key
  650. keys.forEach(function (k) {
  651. if (_this3.isValidLookup(found)) return;
  652. var _extractFromKey2 = _this3.extractFromKey(k, options),
  653. key = _extractFromKey2.key,
  654. namespaces = _extractFromKey2.namespaces;
  655. if (_this3.options.fallbackNS) namespaces = namespaces.concat(_this3.options.fallbackNS);
  656. var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
  657. var needsContextHandling = options.context !== undefined && typeof options.context === 'string' && options.context !== '';
  658. var codes = options.lngs ? options.lngs : _this3.languageUtils.toResolveHierarchy(options.lng || _this3.language);
  659. namespaces.forEach(function (ns) {
  660. if (_this3.isValidLookup(found)) return;
  661. codes.forEach(function (code) {
  662. if (_this3.isValidLookup(found)) return;
  663. var finalKey = key;
  664. var finalKeys = [finalKey];
  665. var pluralSuffix = void 0;
  666. if (needsPluralHandling) pluralSuffix = _this3.pluralResolver.getSuffix(code, options.count);
  667. // fallback for plural if context not found
  668. if (needsPluralHandling && needsContextHandling) finalKeys.push(finalKey + pluralSuffix);
  669. // get key for context if needed
  670. if (needsContextHandling) finalKeys.push(finalKey += '' + _this3.options.contextSeparator + options.context);
  671. // get key for plural if needed
  672. if (needsPluralHandling) finalKeys.push(finalKey += pluralSuffix);
  673. // iterate over finalKeys starting with most specific pluralkey (-> contextkey only) -> singularkey only
  674. var possibleKey = void 0;
  675. while (possibleKey = finalKeys.pop()) {
  676. if (_this3.isValidLookup(found)) continue;
  677. found = _this3.getResource(code, ns, possibleKey, options);
  678. }
  679. });
  680. });
  681. });
  682. return found;
  683. };
  684. Translator.prototype.isValidLookup = function isValidLookup(res) {
  685. return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
  686. };
  687. Translator.prototype.getResource = function getResource(code, ns, key) {
  688. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  689. return this.resourceStore.getResource(code, ns, key, options);
  690. };
  691. return Translator;
  692. }(EventEmitter);
  693. function capitalize(string) {
  694. return string.charAt(0).toUpperCase() + string.slice(1);
  695. }
  696. var LanguageUtil = function () {
  697. function LanguageUtil(options) {
  698. classCallCheck(this, LanguageUtil);
  699. this.options = options;
  700. this.whitelist = this.options.whitelist || false;
  701. this.logger = baseLogger.create('languageUtils');
  702. }
  703. LanguageUtil.prototype.getScriptPartFromCode = function getScriptPartFromCode(code) {
  704. if (!code || code.indexOf('-') < 0) return null;
  705. var p = code.split('-');
  706. if (p.length === 2) return null;
  707. p.pop();
  708. return this.formatLanguageCode(p.join('-'));
  709. };
  710. LanguageUtil.prototype.getLanguagePartFromCode = function getLanguagePartFromCode(code) {
  711. if (!code || code.indexOf('-') < 0) return code;
  712. var p = code.split('-');
  713. return this.formatLanguageCode(p[0]);
  714. };
  715. LanguageUtil.prototype.formatLanguageCode = function formatLanguageCode(code) {
  716. // http://www.iana.org/assignments/language-tags/language-tags.xhtml
  717. if (typeof code === 'string' && code.indexOf('-') > -1) {
  718. var specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
  719. var p = code.split('-');
  720. if (this.options.lowerCaseLng) {
  721. p = p.map(function (part) {
  722. return part.toLowerCase();
  723. });
  724. } else if (p.length === 2) {
  725. p[0] = p[0].toLowerCase();
  726. p[1] = p[1].toUpperCase();
  727. if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
  728. } else if (p.length === 3) {
  729. p[0] = p[0].toLowerCase();
  730. // if lenght 2 guess it's a country
  731. if (p[1].length === 2) p[1] = p[1].toUpperCase();
  732. if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
  733. if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
  734. if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
  735. }
  736. return p.join('-');
  737. } else {
  738. return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
  739. }
  740. };
  741. LanguageUtil.prototype.isWhitelisted = function isWhitelisted(code, exactMatch) {
  742. if (this.options.load === 'languageOnly' || this.options.nonExplicitWhitelist && !exactMatch) {
  743. code = this.getLanguagePartFromCode(code);
  744. }
  745. return !this.whitelist || !this.whitelist.length || this.whitelist.indexOf(code) > -1 ? true : false;
  746. };
  747. LanguageUtil.prototype.getFallbackCodes = function getFallbackCodes(fallbacks, code) {
  748. if (!fallbacks) return [];
  749. if (typeof fallbacks === 'string') fallbacks = [fallbacks];
  750. if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
  751. if (!code) return fallbacks.default || [];
  752. // asume we have an object defining fallbacks
  753. var found = fallbacks[code];
  754. if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
  755. if (!found) found = fallbacks[this.formatLanguageCode(code)];
  756. if (!found) found = fallbacks.default;
  757. return found || [];
  758. };
  759. LanguageUtil.prototype.toResolveHierarchy = function toResolveHierarchy(code, fallbackCode) {
  760. var _this = this;
  761. var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
  762. var codes = [];
  763. var addCode = function addCode(code) {
  764. var exactMatch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  765. if (!code) return;
  766. if (_this.isWhitelisted(code, exactMatch)) {
  767. codes.push(code);
  768. } else {
  769. _this.logger.warn('rejecting non-whitelisted language code: ' + code);
  770. }
  771. };
  772. if (typeof code === 'string' && code.indexOf('-') > -1) {
  773. if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code), true);
  774. if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code), true);
  775. if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
  776. } else if (typeof code === 'string') {
  777. addCode(this.formatLanguageCode(code));
  778. }
  779. fallbackCodes.forEach(function (fc) {
  780. if (codes.indexOf(fc) < 0) addCode(_this.formatLanguageCode(fc));
  781. });
  782. return codes;
  783. };
  784. return LanguageUtil;
  785. }();
  786. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  787. /* eslint-disable */
  788. var sets = [{ lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'tg', 'ti', 'tr', 'uz', 'wa'], nr: [1, 2], fc: 1 }, { lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'es_ar', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'he', 'hi', 'hu', 'hy', 'ia', 'it', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt', 'pt_br', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'], nr: [1, 2], fc: 2 }, { lngs: ['ay', 'bo', 'cgg', 'fa', 'id', 'ja', 'jbo', 'ka', 'kk', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'], nr: [1], fc: 3 }, { lngs: ['be', 'bs', 'dz', 'hr', 'ru', 'sr', 'uk'], nr: [1, 2, 5], fc: 4 }, { lngs: ['ar'], nr: [0, 1, 2, 3, 11, 100], fc: 5 }, { lngs: ['cs', 'sk'], nr: [1, 2, 5], fc: 6 }, { lngs: ['csb', 'pl'], nr: [1, 2, 5], fc: 7 }, { lngs: ['cy'], nr: [1, 2, 3, 8], fc: 8 }, { lngs: ['fr'], nr: [1, 2], fc: 9 }, { lngs: ['ga'], nr: [1, 2, 3, 7, 11], fc: 10 }, { lngs: ['gd'], nr: [1, 2, 3, 20], fc: 11 }, { lngs: ['is'], nr: [1, 2], fc: 12 }, { lngs: ['jv'], nr: [0, 1], fc: 13 }, { lngs: ['kw'], nr: [1, 2, 3, 4], fc: 14 }, { lngs: ['lt'], nr: [1, 2, 10], fc: 15 }, { lngs: ['lv'], nr: [1, 2, 0], fc: 16 }, { lngs: ['mk'], nr: [1, 2], fc: 17 }, { lngs: ['mnk'], nr: [0, 1, 2], fc: 18 }, { lngs: ['mt'], nr: [1, 2, 11, 20], fc: 19 }, { lngs: ['or'], nr: [2, 1], fc: 2 }, { lngs: ['ro'], nr: [1, 2, 20], fc: 20 }, { lngs: ['sl'], nr: [5, 1, 2, 3], fc: 21 }];
  789. var _rulesPluralsTypes = {
  790. 1: function _(n) {
  791. return Number(n > 1);
  792. },
  793. 2: function _(n) {
  794. return Number(n != 1);
  795. },
  796. 3: function _(n) {
  797. return 0;
  798. },
  799. 4: function _(n) {
  800. return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  801. },
  802. 5: function _(n) {
  803. return Number(n === 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
  804. },
  805. 6: function _(n) {
  806. return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
  807. },
  808. 7: function _(n) {
  809. return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  810. },
  811. 8: function _(n) {
  812. return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
  813. },
  814. 9: function _(n) {
  815. return Number(n >= 2);
  816. },
  817. 10: function _(n) {
  818. return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
  819. },
  820. 11: function _(n) {
  821. return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
  822. },
  823. 12: function _(n) {
  824. return Number(n % 10 != 1 || n % 100 == 11);
  825. },
  826. 13: function _(n) {
  827. return Number(n !== 0);
  828. },
  829. 14: function _(n) {
  830. return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
  831. },
  832. 15: function _(n) {
  833. return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  834. },
  835. 16: function _(n) {
  836. return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
  837. },
  838. 17: function _(n) {
  839. return Number(n == 1 || n % 10 == 1 ? 0 : 1);
  840. },
  841. 18: function _(n) {
  842. return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
  843. },
  844. 19: function _(n) {
  845. return Number(n == 1 ? 0 : n === 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
  846. },
  847. 20: function _(n) {
  848. return Number(n == 1 ? 0 : n === 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
  849. },
  850. 21: function _(n) {
  851. return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
  852. }
  853. };
  854. /* eslint-enable */
  855. function createRules() {
  856. var l,
  857. rules = {};
  858. sets.forEach(function (set$$1) {
  859. set$$1.lngs.forEach(function (l) {
  860. return rules[l] = {
  861. numbers: set$$1.nr,
  862. plurals: _rulesPluralsTypes[set$$1.fc]
  863. };
  864. });
  865. });
  866. return rules;
  867. }
  868. var PluralResolver = function () {
  869. function PluralResolver(languageUtils) {
  870. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  871. classCallCheck(this, PluralResolver);
  872. this.languageUtils = languageUtils;
  873. this.options = options;
  874. this.logger = baseLogger.create('pluralResolver');
  875. this.rules = createRules();
  876. }
  877. PluralResolver.prototype.addRule = function addRule(lng, obj) {
  878. this.rules[lng] = obj;
  879. };
  880. PluralResolver.prototype.getRule = function getRule(code) {
  881. return this.rules[this.languageUtils.getLanguagePartFromCode(code)];
  882. };
  883. PluralResolver.prototype.needsPlural = function needsPlural(code) {
  884. var rule = this.getRule(code);
  885. return rule && rule.numbers.length <= 1 ? false : true;
  886. };
  887. PluralResolver.prototype.getSuffix = function getSuffix(code, count) {
  888. var _this = this;
  889. var rule = this.getRule(code);
  890. if (rule) {
  891. if (rule.numbers.length === 1) return ''; // only singular
  892. var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
  893. var suffix = rule.numbers[idx];
  894. // special treatment for lngs only having singular and plural
  895. if (rule.numbers.length === 2 && rule.numbers[0] === 1) {
  896. if (suffix === 2) {
  897. suffix = 'plural';
  898. } else if (suffix === 1) {
  899. suffix = '';
  900. }
  901. }
  902. var returnSuffix = function returnSuffix() {
  903. return _this.options.prepend && suffix.toString() ? _this.options.prepend + suffix.toString() : suffix.toString();
  904. };
  905. // COMPATIBILITY JSON
  906. // v1
  907. if (this.options.compatibilityJSON === 'v1') {
  908. if (suffix === 1) return '';
  909. if (typeof suffix === 'number') return '_plural_' + suffix.toString();
  910. return returnSuffix();
  911. }
  912. // v2
  913. else if (this.options.compatibilityJSON === 'v2' || rule.numbers.length === 2 && rule.numbers[0] === 1) {
  914. return returnSuffix();
  915. }
  916. // v3 - gettext index
  917. else if (rule.numbers.length === 2 && rule.numbers[0] === 1) {
  918. return returnSuffix();
  919. }
  920. return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
  921. } else {
  922. this.logger.warn('no plural rule found for: ' + code);
  923. return '';
  924. }
  925. };
  926. return PluralResolver;
  927. }();
  928. var Interpolator = function () {
  929. function Interpolator() {
  930. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  931. classCallCheck(this, Interpolator);
  932. this.logger = baseLogger.create('interpolator');
  933. this.init(options, true);
  934. }
  935. Interpolator.prototype.init = function init() {
  936. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  937. var reset = arguments[1];
  938. if (reset) {
  939. this.options = options;
  940. this.format = options.interpolation && options.interpolation.format || function (value) {
  941. return value;
  942. };
  943. this.escape = options.interpolation && options.interpolation.escape || escape;
  944. }
  945. if (!options.interpolation) options.interpolation = { escapeValue: true };
  946. var iOpts = options.interpolation;
  947. this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
  948. this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
  949. this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
  950. this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
  951. this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
  952. this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
  953. this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
  954. this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
  955. // the regexp
  956. this.resetRegExp();
  957. };
  958. Interpolator.prototype.reset = function reset() {
  959. if (this.options) this.init(this.options);
  960. };
  961. Interpolator.prototype.resetRegExp = function resetRegExp() {
  962. // the regexp
  963. var regexpStr = this.prefix + '(.+?)' + this.suffix;
  964. this.regexp = new RegExp(regexpStr, 'g');
  965. var regexpUnescapeStr = this.prefix + this.unescapePrefix + '(.+?)' + this.unescapeSuffix + this.suffix;
  966. this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
  967. var nestingRegexpStr = this.nestingPrefix + '(.+?)' + this.nestingSuffix;
  968. this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
  969. };
  970. Interpolator.prototype.interpolate = function interpolate(str, data, lng) {
  971. var _this = this;
  972. var match = void 0,
  973. value = void 0;
  974. function regexSafe(val) {
  975. return val.replace(/\$/g, '$$$$');
  976. }
  977. var handleFormat = function handleFormat(key) {
  978. if (key.indexOf(_this.formatSeparator) < 0) return getPath(data, key);
  979. var p = key.split(_this.formatSeparator);
  980. var k = p.shift().trim();
  981. var f = p.join(_this.formatSeparator).trim();
  982. return _this.format(getPath(data, k), f, lng);
  983. };
  984. this.resetRegExp();
  985. // unescape if has unescapePrefix/Suffix
  986. while (match = this.regexpUnescape.exec(str)) {
  987. var _value = handleFormat(match[1].trim());
  988. str = str.replace(match[0], _value);
  989. this.regexpUnescape.lastIndex = 0;
  990. }
  991. // regular escape on demand
  992. while (match = this.regexp.exec(str)) {
  993. value = handleFormat(match[1].trim());
  994. if (typeof value !== 'string') value = makeString(value);
  995. if (!value) {
  996. this.logger.warn('missed to pass in variable ' + match[1] + ' for interpolating ' + str);
  997. value = '';
  998. }
  999. value = this.escapeValue ? regexSafe(this.escape(value)) : regexSafe(value);
  1000. str = str.replace(match[0], value);
  1001. this.regexp.lastIndex = 0;
  1002. }
  1003. return str;
  1004. };
  1005. Interpolator.prototype.nest = function nest(str, fc) {
  1006. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  1007. var match = void 0,
  1008. value = void 0;
  1009. var clonedOptions = _extends({}, options);
  1010. clonedOptions.applyPostProcessor = false; // avoid post processing on nested lookup
  1011. function handleHasOptions(key) {
  1012. if (key.indexOf(',') < 0) return key;
  1013. var p = key.split(',');
  1014. key = p.shift();
  1015. var optionsString = p.join(',');
  1016. optionsString = this.interpolate(optionsString, clonedOptions);
  1017. optionsString = optionsString.replace(/'/g, '"');
  1018. try {
  1019. clonedOptions = JSON.parse(optionsString);
  1020. } catch (e) {
  1021. this.logger.error('failed parsing options string in nesting for key ' + key, e);
  1022. }
  1023. return key;
  1024. }
  1025. // regular escape on demand
  1026. while (match = this.nestingRegexp.exec(str)) {
  1027. value = fc(handleHasOptions.call(this, match[1].trim()), clonedOptions);
  1028. if (typeof value !== 'string') value = makeString(value);
  1029. if (!value) {
  1030. this.logger.warn('missed to pass in variable ' + match[1] + ' for interpolating ' + str);
  1031. value = '';
  1032. }
  1033. // Nested keys should not be escaped by default #854
  1034. // value = this.escapeValue ? regexSafe(utils.escape(value)) : regexSafe(value);
  1035. str = str.replace(match[0], value);
  1036. this.regexp.lastIndex = 0;
  1037. }
  1038. return str;
  1039. };
  1040. return Interpolator;
  1041. }();
  1042. function remove(arr, what) {
  1043. var found = arr.indexOf(what);
  1044. while (found !== -1) {
  1045. arr.splice(found, 1);
  1046. found = arr.indexOf(what);
  1047. }
  1048. }
  1049. var Connector = function (_EventEmitter) {
  1050. inherits(Connector, _EventEmitter);
  1051. function Connector(backend, store, services) {
  1052. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  1053. classCallCheck(this, Connector);
  1054. var _this = possibleConstructorReturn(this, _EventEmitter.call(this));
  1055. _this.backend = backend;
  1056. _this.store = store;
  1057. _this.services = services;
  1058. _this.options = options;
  1059. _this.logger = baseLogger.create('backendConnector');
  1060. _this.state = {};
  1061. _this.queue = [];
  1062. _this.backend && _this.backend.init && _this.backend.init(services, options.backend, options);
  1063. return _this;
  1064. }
  1065. Connector.prototype.queueLoad = function queueLoad(languages, namespaces, callback) {
  1066. var _this2 = this;
  1067. // find what needs to be loaded
  1068. var toLoad = [],
  1069. pending = [],
  1070. toLoadLanguages = [],
  1071. toLoadNamespaces = [];
  1072. languages.forEach(function (lng) {
  1073. var hasAllNamespaces = true;
  1074. namespaces.forEach(function (ns) {
  1075. var name = lng + '|' + ns;
  1076. if (_this2.store.hasResourceBundle(lng, ns)) {
  1077. _this2.state[name] = 2; // loaded
  1078. } else if (_this2.state[name] < 0) {
  1079. // nothing to do for err
  1080. } else if (_this2.state[name] === 1) {
  1081. if (pending.indexOf(name) < 0) pending.push(name);
  1082. } else {
  1083. _this2.state[name] = 1; // pending
  1084. hasAllNamespaces = false;
  1085. if (pending.indexOf(name) < 0) pending.push(name);
  1086. if (toLoad.indexOf(name) < 0) toLoad.push(name);
  1087. if (toLoadNamespaces.indexOf(ns) < 0) toLoadNamespaces.push(ns);
  1088. }
  1089. });
  1090. if (!hasAllNamespaces) toLoadLanguages.push(lng);
  1091. });
  1092. if (toLoad.length || pending.length) {
  1093. this.queue.push({
  1094. pending: pending,
  1095. loaded: {},
  1096. errors: [],
  1097. callback: callback
  1098. });
  1099. }
  1100. return {
  1101. toLoad: toLoad,
  1102. pending: pending,
  1103. toLoadLanguages: toLoadLanguages,
  1104. toLoadNamespaces: toLoadNamespaces
  1105. };
  1106. };
  1107. Connector.prototype.loaded = function loaded(name, err, data) {
  1108. var _this3 = this;
  1109. var _name$split = name.split('|'),
  1110. _name$split2 = slicedToArray(_name$split, 2),
  1111. lng = _name$split2[0],
  1112. ns = _name$split2[1];
  1113. if (err) this.emit('failedLoading', lng, ns, err);
  1114. if (data) {
  1115. this.store.addResourceBundle(lng, ns, data);
  1116. }
  1117. // set loaded
  1118. this.state[name] = err ? -1 : 2;
  1119. // callback if ready
  1120. this.queue.forEach(function (q) {
  1121. pushPath(q.loaded, [lng], ns);
  1122. remove(q.pending, name);
  1123. if (err) q.errors.push(err);
  1124. if (q.pending.length === 0 && !q.done) {
  1125. _this3.emit('loaded', q.loaded);
  1126. q.errors.length ? q.callback(q.errors) : q.callback();
  1127. q.done = true;
  1128. }
  1129. });
  1130. // remove done load requests
  1131. this.queue = this.queue.filter(function (q) {
  1132. return !q.done;
  1133. });
  1134. };
  1135. Connector.prototype.read = function read(lng, ns, fcName, tried, wait, callback) {
  1136. var _this4 = this;
  1137. if (!tried) tried = 0;
  1138. if (!wait) wait = 250;
  1139. if (!lng.length) return callback(null, {}); // noting to load
  1140. this.backend[fcName](lng, ns, function (err, data) {
  1141. if (err && data /* = retryFlag */ && tried < 5) {
  1142. setTimeout(function () {
  1143. _this4.read.call(_this4, lng, ns, fcName, ++tried, wait * 2, callback);
  1144. }, wait);
  1145. return;
  1146. }
  1147. callback(err, data);
  1148. });
  1149. };
  1150. Connector.prototype.load = function load(languages, namespaces, callback) {
  1151. var _this5 = this;
  1152. if (!this.backend) {
  1153. this.logger.warn('No backend was added via i18next.use. Will not load resources.');
  1154. return callback && callback();
  1155. }
  1156. var options = _extends({}, this.backend.options, this.options.backend);
  1157. if (typeof languages === 'string') languages = this.services.languageUtils.toResolveHierarchy(languages);
  1158. if (typeof namespaces === 'string') namespaces = [namespaces];
  1159. var toLoad = this.queueLoad(languages, namespaces, callback);
  1160. if (!toLoad.toLoad.length) {
  1161. if (!toLoad.pending.length) callback(); // nothing to load and no pendings...callback now
  1162. return; // pendings will trigger callback
  1163. }
  1164. // load with multi-load
  1165. if (options.allowMultiLoading && this.backend.readMulti) {
  1166. this.read(toLoad.toLoadLanguages, toLoad.toLoadNamespaces, 'readMulti', null, null, function (err, data) {
  1167. if (err) _this5.logger.warn('loading namespaces ' + toLoad.toLoadNamespaces.join(', ') + ' for languages ' + toLoad.toLoadLanguages.join(', ') + ' via multiloading failed', err);
  1168. if (!err && data) _this5.logger.log('loaded namespaces ' + toLoad.toLoadNamespaces.join(', ') + ' for languages ' + toLoad.toLoadLanguages.join(', ') + ' via multiloading', data);
  1169. toLoad.toLoad.forEach(function (name) {
  1170. var _name$split3 = name.split('|'),
  1171. _name$split4 = slicedToArray(_name$split3, 2),
  1172. l = _name$split4[0],
  1173. n = _name$split4[1];
  1174. var bundle = getPath(data, [l, n]);
  1175. if (bundle) {
  1176. _this5.loaded(name, err, bundle);
  1177. } else {
  1178. var _err = 'loading namespace ' + n + ' for language ' + l + ' via multiloading failed';
  1179. _this5.loaded(name, _err);
  1180. _this5.logger.error(_err);
  1181. }
  1182. });
  1183. });
  1184. }
  1185. // load one by one
  1186. else {
  1187. var readOne = function readOne(name) {
  1188. var _this6 = this;
  1189. var _name$split5 = name.split('|'),
  1190. _name$split6 = slicedToArray(_name$split5, 2),
  1191. lng = _name$split6[0],
  1192. ns = _name$split6[1];
  1193. this.read(lng, ns, 'read', null, null, function (err, data) {
  1194. if (err) _this6.logger.warn('loading namespace ' + ns + ' for language ' + lng + ' failed', err);
  1195. if (!err && data) _this6.logger.log('loaded namespace ' + ns + ' for language ' + lng, data);
  1196. _this6.loaded(name, err, data);
  1197. });
  1198. };
  1199. toLoad.toLoad.forEach(function (name) {
  1200. readOne.call(_this5, name);
  1201. });
  1202. }
  1203. };
  1204. Connector.prototype.reload = function reload(languages, namespaces) {
  1205. var _this7 = this;
  1206. if (!this.backend) {
  1207. this.logger.warn('No backend was added via i18next.use. Will not load resources.');
  1208. }
  1209. var options = _extends({}, this.backend.options, this.options.backend);
  1210. if (typeof languages === 'string') languages = this.services.languageUtils.toResolveHierarchy(languages);
  1211. if (typeof namespaces === 'string') namespaces = [namespaces];
  1212. // load with multi-load
  1213. if (options.allowMultiLoading && this.backend.readMulti) {
  1214. this.read(languages, namespaces, 'readMulti', null, null, function (err, data) {
  1215. if (err) _this7.logger.warn('reloading namespaces ' + namespaces.join(', ') + ' for languages ' + languages.join(', ') + ' via multiloading failed', err);
  1216. if (!err && data) _this7.logger.log('reloaded namespaces ' + namespaces.join(', ') + ' for languages ' + languages.join(', ') + ' via multiloading', data);
  1217. languages.forEach(function (l) {
  1218. namespaces.forEach(function (n) {
  1219. var bundle = getPath(data, [l, n]);
  1220. if (bundle) {
  1221. _this7.loaded(l + '|' + n, err, bundle);
  1222. } else {
  1223. var _err2 = 'reloading namespace ' + n + ' for language ' + l + ' via multiloading failed';
  1224. _this7.loaded(l + '|' + n, _err2);
  1225. _this7.logger.error(_err2);
  1226. }
  1227. });
  1228. });
  1229. });
  1230. }
  1231. // load one by one
  1232. else {
  1233. var readOne = function readOne(name) {
  1234. var _this8 = this;
  1235. var _name$split7 = name.split('|'),
  1236. _name$split8 = slicedToArray(_name$split7, 2),
  1237. lng = _name$split8[0],
  1238. ns = _name$split8[1];
  1239. this.read(lng, ns, 'read', null, null, function (err, data) {
  1240. if (err) _this8.logger.warn('reloading namespace ' + ns + ' for language ' + lng + ' failed', err);
  1241. if (!err && data) _this8.logger.log('reloaded namespace ' + ns + ' for language ' + lng, data);
  1242. _this8.loaded(name, err, data);
  1243. });
  1244. };
  1245. languages.forEach(function (l) {
  1246. namespaces.forEach(function (n) {
  1247. readOne.call(_this7, l + '|' + n);
  1248. });
  1249. });
  1250. }
  1251. };
  1252. Connector.prototype.saveMissing = function saveMissing(languages, namespace, key, fallbackValue) {
  1253. if (this.backend && this.backend.create) this.backend.create(languages, namespace, key, fallbackValue);
  1254. // write to store to avoid resending
  1255. if (!languages || !languages[0]) return;
  1256. this.store.addResource(languages[0], namespace, key, fallbackValue);
  1257. };
  1258. return Connector;
  1259. }(EventEmitter);
  1260. var Connector$1 = function (_EventEmitter) {
  1261. inherits(Connector, _EventEmitter);
  1262. function Connector(cache, store, services) {
  1263. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  1264. classCallCheck(this, Connector);
  1265. var _this = possibleConstructorReturn(this, _EventEmitter.call(this));
  1266. _this.cache = cache;
  1267. _this.store = store;
  1268. _this.services = services;
  1269. _this.options = options;
  1270. _this.logger = baseLogger.create('cacheConnector');
  1271. _this.cache && _this.cache.init && _this.cache.init(services, options.cache, options);
  1272. return _this;
  1273. }
  1274. Connector.prototype.load = function load(languages, namespaces, callback) {
  1275. var _this2 = this;
  1276. if (!this.cache) return callback && callback();
  1277. var options = _extends({}, this.cache.options, this.options.cache);
  1278. if (typeof languages === 'string') languages = this.services.languageUtils.toResolveHierarchy(languages);
  1279. if (typeof namespaces === 'string') namespaces = [namespaces];
  1280. if (options.enabled) {
  1281. this.cache.load(languages, function (err, data) {
  1282. if (err) _this2.logger.error('loading languages ' + languages.join(', ') + ' from cache failed', err);
  1283. if (data) {
  1284. for (var l in data) {
  1285. for (var n in data[l]) {
  1286. if (n === 'i18nStamp') continue;
  1287. var bundle = data[l][n];
  1288. if (bundle) _this2.store.addResourceBundle(l, n, bundle);
  1289. }
  1290. }
  1291. }
  1292. if (callback) callback();
  1293. });
  1294. } else {
  1295. if (callback) callback();
  1296. }
  1297. };
  1298. Connector.prototype.save = function save() {
  1299. if (this.cache && this.options.cache && this.options.cache.enabled) this.cache.save(this.store.data);
  1300. };
  1301. return Connector;
  1302. }(EventEmitter);
  1303. function get$1() {
  1304. return {
  1305. debug: false,
  1306. initImmediate: true,
  1307. ns: ['translation'],
  1308. defaultNS: ['translation'],
  1309. fallbackLng: ['dev'],
  1310. fallbackNS: false, // string or array of namespaces
  1311. whitelist: false, // array with whitelisted languages
  1312. nonExplicitWhitelist: false,
  1313. load: 'all', // | currentOnly | languageOnly
  1314. preload: false, // array with preload languages
  1315. keySeparator: '.',
  1316. nsSeparator: ':',
  1317. pluralSeparator: '_',
  1318. contextSeparator: '_',
  1319. saveMissing: false, // enable to send missing values
  1320. saveMissingTo: 'fallback', // 'current' || 'all'
  1321. missingKeyHandler: false, // function(lng, ns, key, fallbackValue) -> override if prefer on handling
  1322. postProcess: false, // string or array of postProcessor names
  1323. returnNull: true, // allows null value as valid translation
  1324. returnEmptyString: true, // allows empty string value as valid translation
  1325. returnObjects: false,
  1326. joinArrays: false, // or string to join array
  1327. returnedObjectHandler: function returnedObjectHandler() {}, // function(key, value, options) triggered if key returns object but returnObjects is set to false
  1328. parseMissingKeyHandler: false, // function(key) parsed a key that was not found in t() before returning
  1329. appendNamespaceToMissingKey: false,
  1330. appendNamespaceToCIMode: false,
  1331. overloadTranslationOptionHandler: function overloadTranslationOptionHandler(args) {
  1332. return { defaultValue: args[1] };
  1333. },
  1334. interpolation: {
  1335. escapeValue: true,
  1336. format: function format(value, _format, lng) {
  1337. return value;
  1338. },
  1339. prefix: '{{',
  1340. suffix: '}}',
  1341. formatSeparator: ',',
  1342. // prefixEscaped: '{{',
  1343. // suffixEscaped: '}}',
  1344. // unescapeSuffix: '',
  1345. unescapePrefix: '-',
  1346. nestingPrefix: '$t(',
  1347. nestingSuffix: ')',
  1348. // nestingPrefixEscaped: '$t(',
  1349. // nestingSuffixEscaped: ')',
  1350. defaultVariables: undefined // object that can have values to interpolate on - extends passed in interpolation data
  1351. }
  1352. };
  1353. }
  1354. function transformOptions(options) {
  1355. // create namespace object if namespace is passed in as string
  1356. if (typeof options.ns === 'string') options.ns = [options.ns];
  1357. if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
  1358. if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];
  1359. // extend whitelist with cimode
  1360. if (options.whitelist && options.whitelist.indexOf('cimode') < 0) options.whitelist.push('cimode');
  1361. return options;
  1362. }
  1363. function noop() {}
  1364. var I18n = function (_EventEmitter) {
  1365. inherits(I18n, _EventEmitter);
  1366. function I18n() {
  1367. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1368. var callback = arguments[1];
  1369. classCallCheck(this, I18n);
  1370. var _this = possibleConstructorReturn(this, _EventEmitter.call(this));
  1371. _this.options = transformOptions(options);
  1372. _this.services = {};
  1373. _this.logger = baseLogger;
  1374. _this.modules = { external: [] };
  1375. if (callback && !_this.isInitialized && !options.isClone) _this.init(options, callback);
  1376. return _this;
  1377. }
  1378. I18n.prototype.init = function init(options, callback) {
  1379. var _this2 = this;
  1380. if (typeof options === 'function') {
  1381. callback = options;
  1382. options = {};
  1383. }
  1384. if (!options) options = {};
  1385. if (options.compatibilityAPI === 'v1') {
  1386. this.options = _extends({}, get$1(), transformOptions(convertAPIOptions(options)), {});
  1387. } else if (options.compatibilityJSON === 'v1') {
  1388. this.options = _extends({}, get$1(), transformOptions(convertJSONOptions(options)), {});
  1389. } else {
  1390. this.options = _extends({}, get$1(), this.options, transformOptions(options));
  1391. }
  1392. if (!callback) callback = noop;
  1393. function createClassOnDemand(ClassOrObject) {
  1394. if (!ClassOrObject) return;
  1395. if (typeof ClassOrObject === 'function') return new ClassOrObject();
  1396. return ClassOrObject;
  1397. }
  1398. // init services
  1399. if (!this.options.isClone) {
  1400. if (this.modules.logger) {
  1401. baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
  1402. } else {
  1403. baseLogger.init(null, this.options);
  1404. }
  1405. var lu = new LanguageUtil(this.options);
  1406. this.store = new ResourceStore(this.options.resources, this.options);
  1407. var s = this.services;
  1408. s.logger = baseLogger;
  1409. s.resourceStore = this.store;
  1410. s.resourceStore.on('added removed', function (lng, ns) {
  1411. s.cacheConnector.save();
  1412. });
  1413. s.languageUtils = lu;
  1414. s.pluralResolver = new PluralResolver(lu, { prepend: this.options.pluralSeparator, compatibilityJSON: this.options.compatibilityJSON });
  1415. s.interpolator = new Interpolator(this.options);
  1416. s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
  1417. // pipe events from backendConnector
  1418. s.backendConnector.on('*', function (event) {
  1419. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  1420. args[_key - 1] = arguments[_key];
  1421. }
  1422. _this2.emit.apply(_this2, [event].concat(args));
  1423. });
  1424. s.backendConnector.on('loaded', function (loaded) {
  1425. s.cacheConnector.save();
  1426. });
  1427. s.cacheConnector = new Connector$1(createClassOnDemand(this.modules.cache), s.resourceStore, s, this.options);
  1428. // pipe events from backendConnector
  1429. s.cacheConnector.on('*', function (event) {
  1430. for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  1431. args[_key2 - 1] = arguments[_key2];
  1432. }
  1433. _this2.emit.apply(_this2, [event].concat(args));
  1434. });
  1435. if (this.modules.languageDetector) {
  1436. s.languageDetector = createClassOnDemand(this.modules.languageDetector);
  1437. s.languageDetector.init(s, this.options.detection, this.options);
  1438. }
  1439. this.translator = new Translator(this.services, this.options);
  1440. // pipe events from translator
  1441. this.translator.on('*', function (event) {
  1442. for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
  1443. args[_key3 - 1] = arguments[_key3];
  1444. }
  1445. _this2.emit.apply(_this2, [event].concat(args));
  1446. });
  1447. this.modules.external.forEach(function (m) {
  1448. if (m.init) m.init(_this2);
  1449. });
  1450. }
  1451. // append api
  1452. var storeApi = ['getResource', 'addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle', 'hasResourceBundle', 'getResourceBundle'];
  1453. storeApi.forEach(function (fcName) {
  1454. _this2[fcName] = function () {
  1455. return this.store[fcName].apply(this.store, arguments);
  1456. };
  1457. });
  1458. // TODO: COMPATIBILITY remove this
  1459. if (this.options.compatibilityAPI === 'v1') appendBackwardsAPI(this);
  1460. var load = function load() {
  1461. _this2.changeLanguage(_this2.options.lng, function (err, t) {
  1462. _this2.isInitialized = true;
  1463. _this2.logger.log('initialized', _this2.options);
  1464. _this2.emit('initialized', _this2.options);
  1465. callback(err, t);
  1466. });
  1467. };
  1468. if (this.options.resources || !this.options.initImmediate) {
  1469. load();
  1470. } else {
  1471. setTimeout(load, 0);
  1472. }
  1473. return this;
  1474. };
  1475. I18n.prototype.loadResources = function loadResources() {
  1476. var _this3 = this;
  1477. var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : noop;
  1478. if (!this.options.resources) {
  1479. if (this.language && this.language.toLowerCase() === 'cimode') return callback(); // avoid loading resources for cimode
  1480. var toLoad = [];
  1481. var append = function append(lng) {
  1482. if (!lng) return;
  1483. var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);
  1484. lngs.forEach(function (l) {
  1485. if (toLoad.indexOf(l) < 0) toLoad.push(l);
  1486. });
  1487. };
  1488. append(this.language);
  1489. if (this.options.preload) {
  1490. this.options.preload.forEach(function (l) {
  1491. append(l);
  1492. });
  1493. }
  1494. this.services.cacheConnector.load(toLoad, this.options.ns, function () {
  1495. _this3.services.backendConnector.load(toLoad, _this3.options.ns, callback);
  1496. });
  1497. } else {
  1498. callback(null);
  1499. }
  1500. };
  1501. I18n.prototype.reloadResources = function reloadResources(lngs, ns) {
  1502. if (!lngs) lngs = this.languages;
  1503. if (!ns) ns = this.options.ns;
  1504. this.services.backendConnector.reload(lngs, ns);
  1505. };
  1506. I18n.prototype.use = function use(module) {
  1507. if (module.type === 'backend') {
  1508. this.modules.backend = module;
  1509. }
  1510. if (module.type === 'cache') {
  1511. this.modules.cache = module;
  1512. }
  1513. if (module.type === 'logger' || module.log && module.warn && module.error) {
  1514. this.modules.logger = module;
  1515. }
  1516. if (module.type === 'languageDetector') {
  1517. this.modules.languageDetector = module;
  1518. }
  1519. if (module.type === 'postProcessor') {
  1520. postProcessor.addPostProcessor(module);
  1521. }
  1522. if (module.type === '3rdParty') {
  1523. this.modules.external.push(module);
  1524. }
  1525. return this;
  1526. };
  1527. I18n.prototype.changeLanguage = function changeLanguage(lng, callback) {
  1528. var _this4 = this;
  1529. var done = function done(err) {
  1530. if (lng) {
  1531. _this4.emit('languageChanged', lng);
  1532. _this4.logger.log('languageChanged', lng);
  1533. }
  1534. if (callback) callback(err, function () {
  1535. for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  1536. args[_key4] = arguments[_key4];
  1537. }
  1538. return _this4.t.apply(_this4, args);
  1539. });
  1540. };
  1541. if (!lng && this.services.languageDetector) lng = this.services.languageDetector.detect();
  1542. if (lng) {
  1543. this.language = lng;
  1544. this.languages = this.services.languageUtils.toResolveHierarchy(lng);
  1545. this.translator.changeLanguage(lng);
  1546. if (this.services.languageDetector) this.services.languageDetector.cacheUserLanguage(lng);
  1547. }
  1548. this.loadResources(function (err) {
  1549. done(err);
  1550. });
  1551. };
  1552. I18n.prototype.getFixedT = function getFixedT(lng, ns) {
  1553. var _this5 = this;
  1554. var fixedT = function fixedT(key) {
  1555. var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1556. var options = _extends({}, opts);
  1557. options.lng = options.lng || fixedT.lng;
  1558. options.ns = options.ns || fixedT.ns;
  1559. return _this5.t(key, options);
  1560. };
  1561. fixedT.lng = lng;
  1562. fixedT.ns = ns;
  1563. return fixedT;
  1564. };
  1565. I18n.prototype.t = function t() {
  1566. return this.translator && this.translator.translate.apply(this.translator, arguments);
  1567. };
  1568. I18n.prototype.exists = function exists() {
  1569. return this.translator && this.translator.exists.apply(this.translator, arguments);
  1570. };
  1571. I18n.prototype.setDefaultNamespace = function setDefaultNamespace(ns) {
  1572. this.options.defaultNS = ns;
  1573. };
  1574. I18n.prototype.loadNamespaces = function loadNamespaces(ns, callback) {
  1575. var _this6 = this;
  1576. if (!this.options.ns) return callback && callback();
  1577. if (typeof ns === 'string') ns = [ns];
  1578. ns.forEach(function (n) {
  1579. if (_this6.options.ns.indexOf(n) < 0) _this6.options.ns.push(n);
  1580. });
  1581. this.loadResources(callback);
  1582. };
  1583. I18n.prototype.loadLanguages = function loadLanguages(lngs, callback) {
  1584. if (typeof lngs === 'string') lngs = [lngs];
  1585. var preloaded = this.options.preload || [];
  1586. var newLngs = lngs.filter(function (lng) {
  1587. return preloaded.indexOf(lng) < 0;
  1588. });
  1589. // Exit early if all given languages are already preloaded
  1590. if (!newLngs.length) return callback();
  1591. this.options.preload = preloaded.concat(newLngs);
  1592. this.loadResources(callback);
  1593. };
  1594. I18n.prototype.dir = function dir(lng) {
  1595. if (!lng) lng = this.language;
  1596. if (!lng) return 'rtl';
  1597. 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', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam'];
  1598. return rtlLngs.indexOf(this.services.languageUtils.getLanguagePartFromCode(lng)) >= 0 ? 'rtl' : 'ltr';
  1599. };
  1600. I18n.prototype.createInstance = function createInstance() {
  1601. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1602. var callback = arguments[1];
  1603. return new I18n(options, callback);
  1604. };
  1605. I18n.prototype.cloneInstance = function cloneInstance() {
  1606. var _this7 = this;
  1607. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1608. var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
  1609. var mergedOptions = _extends({}, options, this.options, { isClone: true });
  1610. var clone = new I18n(mergedOptions, callback);
  1611. var membersToCopy = ['store', 'services', 'language'];
  1612. membersToCopy.forEach(function (m) {
  1613. clone[m] = _this7[m];
  1614. });
  1615. clone.translator = new Translator(clone.services, clone.options);
  1616. clone.translator.on('*', function (event) {
  1617. for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
  1618. args[_key5 - 1] = arguments[_key5];
  1619. }
  1620. clone.emit.apply(clone, [event].concat(args));
  1621. });
  1622. clone.init(mergedOptions, callback);
  1623. return clone;
  1624. };
  1625. return I18n;
  1626. }(EventEmitter);
  1627. var i18next = new I18n();
  1628. return i18next;
  1629. })));