i18next.js 69 KB

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