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