i18nextHttpBackend.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.i18nextHttpBackend = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. (function (global){(function (){
  3. var fetchApi
  4. if (typeof fetch === 'function') {
  5. if (typeof global !== 'undefined' && global.fetch) {
  6. fetchApi = global.fetch
  7. } else if (typeof window !== 'undefined' && window.fetch) {
  8. fetchApi = window.fetch
  9. } else {
  10. fetchApi = fetch
  11. }
  12. }
  13. if (typeof require !== 'undefined' && (typeof window === 'undefined' || typeof window.document === 'undefined')) {
  14. var f = fetchApi || require('cross-fetch')
  15. if (f.default) f = f.default
  16. exports.default = f
  17. module.exports = exports.default
  18. }
  19. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  20. },{"cross-fetch":5}],2:[function(require,module,exports){
  21. "use strict";
  22. Object.defineProperty(exports, "__esModule", {
  23. value: true
  24. });
  25. exports.default = void 0;
  26. var _utils = require("./utils.js");
  27. var _request = _interopRequireDefault(require("./request.js"));
  28. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  30. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
  32. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  33. function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  34. function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
  35. function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
  36. var getDefaults = function getDefaults() {
  37. return {
  38. loadPath: '/locales/{{lng}}/{{ns}}.json',
  39. addPath: '/locales/add/{{lng}}/{{ns}}',
  40. parse: function parse(data) {
  41. return JSON.parse(data);
  42. },
  43. stringify: JSON.stringify,
  44. parsePayload: function parsePayload(namespace, key, fallbackValue) {
  45. return _defineProperty({}, key, fallbackValue || '');
  46. },
  47. parseLoadPayload: function parseLoadPayload(languages, namespaces) {
  48. return undefined;
  49. },
  50. request: _request.default,
  51. reloadInterval: typeof window !== 'undefined' ? false : 60 * 60 * 1000,
  52. customHeaders: {},
  53. queryStringParams: {},
  54. crossDomain: false,
  55. withCredentials: false,
  56. overrideMimeType: false,
  57. requestOptions: {
  58. mode: 'cors',
  59. credentials: 'same-origin',
  60. cache: 'default'
  61. }
  62. };
  63. };
  64. var Backend = function () {
  65. function Backend(services) {
  66. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  67. var allOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  68. _classCallCheck(this, Backend);
  69. this.services = services;
  70. this.options = options;
  71. this.allOptions = allOptions;
  72. this.type = 'backend';
  73. this.init(services, options, allOptions);
  74. }
  75. _createClass(Backend, [{
  76. key: "init",
  77. value: function init(services) {
  78. var _this = this;
  79. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  80. var allOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  81. this.services = services;
  82. this.options = (0, _utils.defaults)(options, this.options || {}, getDefaults());
  83. this.allOptions = allOptions;
  84. if (this.services && this.options.reloadInterval) {
  85. setInterval(function () {
  86. return _this.reload();
  87. }, this.options.reloadInterval);
  88. }
  89. }
  90. }, {
  91. key: "readMulti",
  92. value: function readMulti(languages, namespaces, callback) {
  93. this._readAny(languages, languages, namespaces, namespaces, callback);
  94. }
  95. }, {
  96. key: "read",
  97. value: function read(language, namespace, callback) {
  98. this._readAny([language], language, [namespace], namespace, callback);
  99. }
  100. }, {
  101. key: "_readAny",
  102. value: function _readAny(languages, loadUrlLanguages, namespaces, loadUrlNamespaces, callback) {
  103. var _this2 = this;
  104. var loadPath = this.options.loadPath;
  105. if (typeof this.options.loadPath === 'function') {
  106. loadPath = this.options.loadPath(languages, namespaces);
  107. }
  108. loadPath = (0, _utils.makePromise)(loadPath);
  109. loadPath.then(function (resolvedLoadPath) {
  110. if (!resolvedLoadPath) return callback(null, {});
  111. var url = _this2.services.interpolator.interpolate(resolvedLoadPath, {
  112. lng: languages.join('+'),
  113. ns: namespaces.join('+')
  114. });
  115. _this2.loadUrl(url, callback, loadUrlLanguages, loadUrlNamespaces);
  116. });
  117. }
  118. }, {
  119. key: "loadUrl",
  120. value: function loadUrl(url, callback, languages, namespaces) {
  121. var _this3 = this;
  122. var lng = typeof languages === 'string' ? [languages] : languages;
  123. var ns = typeof namespaces === 'string' ? [namespaces] : namespaces;
  124. var payload = this.options.parseLoadPayload(lng, ns);
  125. this.options.request(this.options, url, payload, function (err, res) {
  126. if (res && (res.status >= 500 && res.status < 600 || !res.status)) return callback('failed loading ' + url + '; status code: ' + res.status, true);
  127. if (res && res.status >= 400 && res.status < 500) return callback('failed loading ' + url + '; status code: ' + res.status, false);
  128. if (!res && err && err.message && err.message.indexOf('Failed to fetch') > -1) return callback('failed loading ' + url + ': ' + err.message, true);
  129. if (err) return callback(err, false);
  130. var ret, parseErr;
  131. try {
  132. if (typeof res.data === 'string') {
  133. ret = _this3.options.parse(res.data, languages, namespaces);
  134. } else {
  135. ret = res.data;
  136. }
  137. } catch (e) {
  138. parseErr = 'failed parsing ' + url + ' to json';
  139. }
  140. if (parseErr) return callback(parseErr, false);
  141. callback(null, ret);
  142. });
  143. }
  144. }, {
  145. key: "create",
  146. value: function create(languages, namespace, key, fallbackValue, callback) {
  147. var _this4 = this;
  148. if (!this.options.addPath) return;
  149. if (typeof languages === 'string') languages = [languages];
  150. var payload = this.options.parsePayload(namespace, key, fallbackValue);
  151. var finished = 0;
  152. var dataArray = [];
  153. var resArray = [];
  154. languages.forEach(function (lng) {
  155. var addPath = _this4.options.addPath;
  156. if (typeof _this4.options.addPath === 'function') {
  157. addPath = _this4.options.addPath(lng, namespace);
  158. }
  159. var url = _this4.services.interpolator.interpolate(addPath, {
  160. lng: lng,
  161. ns: namespace
  162. });
  163. _this4.options.request(_this4.options, url, payload, function (data, res) {
  164. finished += 1;
  165. dataArray.push(data);
  166. resArray.push(res);
  167. if (finished === languages.length) {
  168. if (typeof callback === 'function') callback(dataArray, resArray);
  169. }
  170. });
  171. });
  172. }
  173. }, {
  174. key: "reload",
  175. value: function reload() {
  176. var _this5 = this;
  177. var _this$services = this.services,
  178. backendConnector = _this$services.backendConnector,
  179. languageUtils = _this$services.languageUtils,
  180. logger = _this$services.logger;
  181. var currentLanguage = backendConnector.language;
  182. if (currentLanguage && currentLanguage.toLowerCase() === 'cimode') return;
  183. var toLoad = [];
  184. var append = function append(lng) {
  185. var lngs = languageUtils.toResolveHierarchy(lng);
  186. lngs.forEach(function (l) {
  187. if (toLoad.indexOf(l) < 0) toLoad.push(l);
  188. });
  189. };
  190. append(currentLanguage);
  191. if (this.allOptions.preload) this.allOptions.preload.forEach(function (l) {
  192. return append(l);
  193. });
  194. toLoad.forEach(function (lng) {
  195. _this5.allOptions.ns.forEach(function (ns) {
  196. backendConnector.read(lng, ns, 'read', null, null, function (err, data) {
  197. if (err) logger.warn("loading namespace ".concat(ns, " for language ").concat(lng, " failed"), err);
  198. if (!err && data) logger.log("loaded namespace ".concat(ns, " for language ").concat(lng), data);
  199. backendConnector.loaded("".concat(lng, "|").concat(ns), err, data);
  200. });
  201. });
  202. });
  203. }
  204. }]);
  205. return Backend;
  206. }();
  207. Backend.type = 'backend';
  208. var _default = exports.default = Backend;
  209. module.exports = exports.default;
  210. },{"./request.js":3,"./utils.js":4}],3:[function(require,module,exports){
  211. (function (global){(function (){
  212. "use strict";
  213. Object.defineProperty(exports, "__esModule", {
  214. value: true
  215. });
  216. exports.default = void 0;
  217. var _utils = require("./utils.js");
  218. var fetchNode = _interopRequireWildcard(require("./getFetch.js"));
  219. function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
  220. function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
  221. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  222. var fetchApi;
  223. if (typeof fetch === 'function') {
  224. if (typeof global !== 'undefined' && global.fetch) {
  225. fetchApi = global.fetch;
  226. } else if (typeof window !== 'undefined' && window.fetch) {
  227. fetchApi = window.fetch;
  228. } else {
  229. fetchApi = fetch;
  230. }
  231. }
  232. var XmlHttpRequestApi;
  233. if ((0, _utils.hasXMLHttpRequest)()) {
  234. if (typeof global !== 'undefined' && global.XMLHttpRequest) {
  235. XmlHttpRequestApi = global.XMLHttpRequest;
  236. } else if (typeof window !== 'undefined' && window.XMLHttpRequest) {
  237. XmlHttpRequestApi = window.XMLHttpRequest;
  238. }
  239. }
  240. var ActiveXObjectApi;
  241. if (typeof ActiveXObject === 'function') {
  242. if (typeof global !== 'undefined' && global.ActiveXObject) {
  243. ActiveXObjectApi = global.ActiveXObject;
  244. } else if (typeof window !== 'undefined' && window.ActiveXObject) {
  245. ActiveXObjectApi = window.ActiveXObject;
  246. }
  247. }
  248. if (!fetchApi && fetchNode && !XmlHttpRequestApi && !ActiveXObjectApi) fetchApi = fetchNode.default || fetchNode;
  249. if (typeof fetchApi !== 'function') fetchApi = undefined;
  250. var addQueryString = function addQueryString(url, params) {
  251. if (params && _typeof(params) === 'object') {
  252. var queryString = '';
  253. for (var paramName in params) {
  254. queryString += '&' + encodeURIComponent(paramName) + '=' + encodeURIComponent(params[paramName]);
  255. }
  256. if (!queryString) return url;
  257. url = url + (url.indexOf('?') !== -1 ? '&' : '?') + queryString.slice(1);
  258. }
  259. return url;
  260. };
  261. var fetchIt = function fetchIt(url, fetchOptions, callback) {
  262. var resolver = function resolver(response) {
  263. if (!response.ok) return callback(response.statusText || 'Error', {
  264. status: response.status
  265. });
  266. response.text().then(function (data) {
  267. callback(null, {
  268. status: response.status,
  269. data: data
  270. });
  271. }).catch(callback);
  272. };
  273. if (typeof fetch === 'function') {
  274. fetch(url, fetchOptions).then(resolver).catch(callback);
  275. } else {
  276. fetchApi(url, fetchOptions).then(resolver).catch(callback);
  277. }
  278. };
  279. var omitFetchOptions = false;
  280. var requestWithFetch = function requestWithFetch(options, url, payload, callback) {
  281. if (options.queryStringParams) {
  282. url = addQueryString(url, options.queryStringParams);
  283. }
  284. var headers = (0, _utils.defaults)({}, typeof options.customHeaders === 'function' ? options.customHeaders() : options.customHeaders);
  285. if (typeof window === 'undefined' && typeof global !== 'undefined' && typeof global.process !== 'undefined' && global.process.versions && global.process.versions.node) {
  286. headers['User-Agent'] = "i18next-http-backend (node/".concat(global.process.version, "; ").concat(global.process.platform, " ").concat(global.process.arch, ")");
  287. }
  288. if (payload) headers['Content-Type'] = 'application/json';
  289. var reqOptions = typeof options.requestOptions === 'function' ? options.requestOptions(payload) : options.requestOptions;
  290. var fetchOptions = (0, _utils.defaults)({
  291. method: payload ? 'POST' : 'GET',
  292. body: payload ? options.stringify(payload) : undefined,
  293. headers: headers
  294. }, omitFetchOptions ? {} : reqOptions);
  295. try {
  296. fetchIt(url, fetchOptions, callback);
  297. } catch (e) {
  298. if (!reqOptions || Object.keys(reqOptions).length === 0 || !e.message || e.message.indexOf('not implemented') < 0) {
  299. return callback(e);
  300. }
  301. try {
  302. Object.keys(reqOptions).forEach(function (opt) {
  303. delete fetchOptions[opt];
  304. });
  305. fetchIt(url, fetchOptions, callback);
  306. omitFetchOptions = true;
  307. } catch (err) {
  308. callback(err);
  309. }
  310. }
  311. };
  312. var requestWithXmlHttpRequest = function requestWithXmlHttpRequest(options, url, payload, callback) {
  313. if (payload && _typeof(payload) === 'object') {
  314. payload = addQueryString('', payload).slice(1);
  315. }
  316. if (options.queryStringParams) {
  317. url = addQueryString(url, options.queryStringParams);
  318. }
  319. try {
  320. var x;
  321. if (XmlHttpRequestApi) {
  322. x = new XmlHttpRequestApi();
  323. } else {
  324. x = new ActiveXObjectApi('MSXML2.XMLHTTP.3.0');
  325. }
  326. x.open(payload ? 'POST' : 'GET', url, 1);
  327. if (!options.crossDomain) {
  328. x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  329. }
  330. x.withCredentials = !!options.withCredentials;
  331. if (payload) {
  332. x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  333. }
  334. if (x.overrideMimeType) {
  335. x.overrideMimeType('application/json');
  336. }
  337. var h = options.customHeaders;
  338. h = typeof h === 'function' ? h() : h;
  339. if (h) {
  340. for (var i in h) {
  341. x.setRequestHeader(i, h[i]);
  342. }
  343. }
  344. x.onreadystatechange = function () {
  345. x.readyState > 3 && callback(x.status >= 400 ? x.statusText : null, {
  346. status: x.status,
  347. data: x.responseText
  348. });
  349. };
  350. x.send(payload);
  351. } catch (e) {
  352. console && console.log(e);
  353. }
  354. };
  355. var request = function request(options, url, payload, callback) {
  356. if (typeof payload === 'function') {
  357. callback = payload;
  358. payload = undefined;
  359. }
  360. callback = callback || function () {};
  361. if (fetchApi && url.indexOf('file:') !== 0) {
  362. return requestWithFetch(options, url, payload, callback);
  363. }
  364. if ((0, _utils.hasXMLHttpRequest)() || typeof ActiveXObject === 'function') {
  365. return requestWithXmlHttpRequest(options, url, payload, callback);
  366. }
  367. callback(new Error('No fetch and no xhr implementation found!'));
  368. };
  369. var _default = exports.default = request;
  370. module.exports = exports.default;
  371. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  372. },{"./getFetch.js":1,"./utils.js":4}],4:[function(require,module,exports){
  373. "use strict";
  374. Object.defineProperty(exports, "__esModule", {
  375. value: true
  376. });
  377. exports.defaults = defaults;
  378. exports.hasXMLHttpRequest = hasXMLHttpRequest;
  379. exports.makePromise = makePromise;
  380. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  381. var arr = [];
  382. var each = arr.forEach;
  383. var slice = arr.slice;
  384. function defaults(obj) {
  385. each.call(slice.call(arguments, 1), function (source) {
  386. if (source) {
  387. for (var prop in source) {
  388. if (obj[prop] === undefined) obj[prop] = source[prop];
  389. }
  390. }
  391. });
  392. return obj;
  393. }
  394. function hasXMLHttpRequest() {
  395. return typeof XMLHttpRequest === 'function' || (typeof XMLHttpRequest === "undefined" ? "undefined" : _typeof(XMLHttpRequest)) === 'object';
  396. }
  397. function isPromise(maybePromise) {
  398. return !!maybePromise && typeof maybePromise.then === 'function';
  399. }
  400. function makePromise(maybePromise) {
  401. if (isPromise(maybePromise)) {
  402. return maybePromise;
  403. }
  404. return Promise.resolve(maybePromise);
  405. }
  406. },{}],5:[function(require,module,exports){
  407. },{}]},{},[2])(2)
  408. });