@bigbinary/neeto-media-recorder 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/core.js ADDED
@@ -0,0 +1,4061 @@
1
+ import axios from 'axios';
2
+ import { isPresent, isNot, existsBy, isNotEmpty } from '@bigbinary/neeto-cist';
3
+ import { min, identity, isNil, pick } from 'ramda';
4
+ import '@bigbinary/neetoui';
5
+ import { RETRIABLE_ERRORS, UPLOAD_EVENT, UPLOAD_STATUS, SCREEN_RECORDER_STATUS, SCREEN_RECORDER_ERROR, SCREEN_RECORDER_EVENT, ONE_SECOND, ONE_SECOND_IN_MILLISECONDS } from '@bigbinary/neeto-media-recorder/constants';
6
+ import { withImmutableActions } from '@bigbinary/neeto-commons-frontend/react-utils';
7
+ import { create as create$3 } from 'zustand';
8
+
9
+ function _arrayLikeToArray$1(arr, len) {
10
+ if (len == null || len > arr.length) len = arr.length;
11
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
12
+ return arr2;
13
+ }
14
+
15
+ function _arrayWithoutHoles(arr) {
16
+ if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
17
+ }
18
+
19
+ function _iterableToArray$1(iter) {
20
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
21
+ }
22
+
23
+ function _unsupportedIterableToArray$1(o, minLen) {
24
+ if (!o) return;
25
+ if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
26
+ var n = Object.prototype.toString.call(o).slice(8, -1);
27
+ if (n === "Object" && o.constructor) n = o.constructor.name;
28
+ if (n === "Map" || n === "Set") return Array.from(o);
29
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
30
+ }
31
+
32
+ function _nonIterableSpread() {
33
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
34
+ }
35
+
36
+ function _toConsumableArray(arr) {
37
+ return _arrayWithoutHoles(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread();
38
+ }
39
+
40
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
41
+ try {
42
+ var info = gen[key](arg);
43
+ var value = info.value;
44
+ } catch (error) {
45
+ reject(error);
46
+ return;
47
+ }
48
+ if (info.done) {
49
+ resolve(value);
50
+ } else {
51
+ Promise.resolve(value).then(_next, _throw);
52
+ }
53
+ }
54
+ function _asyncToGenerator(fn) {
55
+ return function () {
56
+ var self = this,
57
+ args = arguments;
58
+ return new Promise(function (resolve, reject) {
59
+ var gen = fn.apply(self, args);
60
+ function _next(value) {
61
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
62
+ }
63
+ function _throw(err) {
64
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
65
+ }
66
+ _next(undefined);
67
+ });
68
+ };
69
+ }
70
+
71
+ function _classCallCheck$1(instance, Constructor) {
72
+ if (!(instance instanceof Constructor)) {
73
+ throw new TypeError("Cannot call a class as a function");
74
+ }
75
+ }
76
+
77
+ function _typeof$2(obj) {
78
+ "@babel/helpers - typeof";
79
+
80
+ return _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
81
+ return typeof obj;
82
+ } : function (obj) {
83
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
84
+ }, _typeof$2(obj);
85
+ }
86
+
87
+ function _toPrimitive$1(input, hint) {
88
+ if (_typeof$2(input) !== "object" || input === null) return input;
89
+ var prim = input[Symbol.toPrimitive];
90
+ if (prim !== undefined) {
91
+ var res = prim.call(input, hint || "default");
92
+ if (_typeof$2(res) !== "object") return res;
93
+ throw new TypeError("@@toPrimitive must return a primitive value.");
94
+ }
95
+ return (hint === "string" ? String : Number)(input);
96
+ }
97
+
98
+ function _toPropertyKey$1(arg) {
99
+ var key = _toPrimitive$1(arg, "string");
100
+ return _typeof$2(key) === "symbol" ? key : String(key);
101
+ }
102
+
103
+ function _defineProperties$1(target, props) {
104
+ for (var i = 0; i < props.length; i++) {
105
+ var descriptor = props[i];
106
+ descriptor.enumerable = descriptor.enumerable || false;
107
+ descriptor.configurable = true;
108
+ if ("value" in descriptor) descriptor.writable = true;
109
+ Object.defineProperty(target, _toPropertyKey$1(descriptor.key), descriptor);
110
+ }
111
+ }
112
+ function _createClass$1(Constructor, protoProps, staticProps) {
113
+ if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
114
+ if (staticProps) _defineProperties$1(Constructor, staticProps);
115
+ Object.defineProperty(Constructor, "prototype", {
116
+ writable: false
117
+ });
118
+ return Constructor;
119
+ }
120
+
121
+ function _defineProperty$1(obj, key, value) {
122
+ key = _toPropertyKey$1(key);
123
+ if (key in obj) {
124
+ Object.defineProperty(obj, key, {
125
+ value: value,
126
+ enumerable: true,
127
+ configurable: true,
128
+ writable: true
129
+ });
130
+ } else {
131
+ obj[key] = value;
132
+ }
133
+ return obj;
134
+ }
135
+
136
+ function _classApplyDescriptorGet(receiver, descriptor) {
137
+ if (descriptor.get) {
138
+ return descriptor.get.call(receiver);
139
+ }
140
+ return descriptor.value;
141
+ }
142
+
143
+ function _classExtractFieldDescriptor(receiver, privateMap, action) {
144
+ if (!privateMap.has(receiver)) {
145
+ throw new TypeError("attempted to " + action + " private field on non-instance");
146
+ }
147
+ return privateMap.get(receiver);
148
+ }
149
+
150
+ function _classPrivateFieldGet(receiver, privateMap) {
151
+ var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get");
152
+ return _classApplyDescriptorGet(receiver, descriptor);
153
+ }
154
+
155
+ function _classApplyDescriptorSet(receiver, descriptor, value) {
156
+ if (descriptor.set) {
157
+ descriptor.set.call(receiver, value);
158
+ } else {
159
+ if (!descriptor.writable) {
160
+ throw new TypeError("attempted to set read only private field");
161
+ }
162
+ descriptor.value = value;
163
+ }
164
+ }
165
+
166
+ function _classPrivateFieldSet(receiver, privateMap, value) {
167
+ var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set");
168
+ _classApplyDescriptorSet(receiver, descriptor, value);
169
+ return value;
170
+ }
171
+
172
+ function getDefaultExportFromCjs (x) {
173
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
174
+ }
175
+
176
+ var regeneratorRuntime$1 = {exports: {}};
177
+
178
+ var _typeof$1 = {exports: {}};
179
+
180
+ _typeof$1.exports;
181
+
182
+ (function (module) {
183
+ function _typeof(obj) {
184
+ "@babel/helpers - typeof";
185
+
186
+ return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
187
+ return typeof obj;
188
+ } : function (obj) {
189
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
190
+ }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
191
+ }
192
+ module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
193
+ } (_typeof$1));
194
+
195
+ var _typeofExports = _typeof$1.exports;
196
+
197
+ regeneratorRuntime$1.exports;
198
+
199
+ (function (module) {
200
+ var _typeof = _typeofExports["default"];
201
+ function _regeneratorRuntime() {
202
+ module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
203
+ return exports;
204
+ }, module.exports.__esModule = true, module.exports["default"] = module.exports;
205
+ var exports = {},
206
+ Op = Object.prototype,
207
+ hasOwn = Op.hasOwnProperty,
208
+ defineProperty = Object.defineProperty || function (obj, key, desc) {
209
+ obj[key] = desc.value;
210
+ },
211
+ $Symbol = "function" == typeof Symbol ? Symbol : {},
212
+ iteratorSymbol = $Symbol.iterator || "@@iterator",
213
+ asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
214
+ toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
215
+ function define(obj, key, value) {
216
+ return Object.defineProperty(obj, key, {
217
+ value: value,
218
+ enumerable: !0,
219
+ configurable: !0,
220
+ writable: !0
221
+ }), obj[key];
222
+ }
223
+ try {
224
+ define({}, "");
225
+ } catch (err) {
226
+ define = function define(obj, key, value) {
227
+ return obj[key] = value;
228
+ };
229
+ }
230
+ function wrap(innerFn, outerFn, self, tryLocsList) {
231
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
232
+ generator = Object.create(protoGenerator.prototype),
233
+ context = new Context(tryLocsList || []);
234
+ return defineProperty(generator, "_invoke", {
235
+ value: makeInvokeMethod(innerFn, self, context)
236
+ }), generator;
237
+ }
238
+ function tryCatch(fn, obj, arg) {
239
+ try {
240
+ return {
241
+ type: "normal",
242
+ arg: fn.call(obj, arg)
243
+ };
244
+ } catch (err) {
245
+ return {
246
+ type: "throw",
247
+ arg: err
248
+ };
249
+ }
250
+ }
251
+ exports.wrap = wrap;
252
+ var ContinueSentinel = {};
253
+ function Generator() {}
254
+ function GeneratorFunction() {}
255
+ function GeneratorFunctionPrototype() {}
256
+ var IteratorPrototype = {};
257
+ define(IteratorPrototype, iteratorSymbol, function () {
258
+ return this;
259
+ });
260
+ var getProto = Object.getPrototypeOf,
261
+ NativeIteratorPrototype = getProto && getProto(getProto(values([])));
262
+ NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
263
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
264
+ function defineIteratorMethods(prototype) {
265
+ ["next", "throw", "return"].forEach(function (method) {
266
+ define(prototype, method, function (arg) {
267
+ return this._invoke(method, arg);
268
+ });
269
+ });
270
+ }
271
+ function AsyncIterator(generator, PromiseImpl) {
272
+ function invoke(method, arg, resolve, reject) {
273
+ var record = tryCatch(generator[method], generator, arg);
274
+ if ("throw" !== record.type) {
275
+ var result = record.arg,
276
+ value = result.value;
277
+ return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
278
+ invoke("next", value, resolve, reject);
279
+ }, function (err) {
280
+ invoke("throw", err, resolve, reject);
281
+ }) : PromiseImpl.resolve(value).then(function (unwrapped) {
282
+ result.value = unwrapped, resolve(result);
283
+ }, function (error) {
284
+ return invoke("throw", error, resolve, reject);
285
+ });
286
+ }
287
+ reject(record.arg);
288
+ }
289
+ var previousPromise;
290
+ defineProperty(this, "_invoke", {
291
+ value: function value(method, arg) {
292
+ function callInvokeWithMethodAndArg() {
293
+ return new PromiseImpl(function (resolve, reject) {
294
+ invoke(method, arg, resolve, reject);
295
+ });
296
+ }
297
+ return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
298
+ }
299
+ });
300
+ }
301
+ function makeInvokeMethod(innerFn, self, context) {
302
+ var state = "suspendedStart";
303
+ return function (method, arg) {
304
+ if ("executing" === state) throw new Error("Generator is already running");
305
+ if ("completed" === state) {
306
+ if ("throw" === method) throw arg;
307
+ return doneResult();
308
+ }
309
+ for (context.method = method, context.arg = arg;;) {
310
+ var delegate = context.delegate;
311
+ if (delegate) {
312
+ var delegateResult = maybeInvokeDelegate(delegate, context);
313
+ if (delegateResult) {
314
+ if (delegateResult === ContinueSentinel) continue;
315
+ return delegateResult;
316
+ }
317
+ }
318
+ if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
319
+ if ("suspendedStart" === state) throw state = "completed", context.arg;
320
+ context.dispatchException(context.arg);
321
+ } else "return" === context.method && context.abrupt("return", context.arg);
322
+ state = "executing";
323
+ var record = tryCatch(innerFn, self, context);
324
+ if ("normal" === record.type) {
325
+ if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
326
+ return {
327
+ value: record.arg,
328
+ done: context.done
329
+ };
330
+ }
331
+ "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
332
+ }
333
+ };
334
+ }
335
+ function maybeInvokeDelegate(delegate, context) {
336
+ var methodName = context.method,
337
+ method = delegate.iterator[methodName];
338
+ if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
339
+ var record = tryCatch(method, delegate.iterator, context.arg);
340
+ if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
341
+ var info = record.arg;
342
+ return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
343
+ }
344
+ function pushTryEntry(locs) {
345
+ var entry = {
346
+ tryLoc: locs[0]
347
+ };
348
+ 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
349
+ }
350
+ function resetTryEntry(entry) {
351
+ var record = entry.completion || {};
352
+ record.type = "normal", delete record.arg, entry.completion = record;
353
+ }
354
+ function Context(tryLocsList) {
355
+ this.tryEntries = [{
356
+ tryLoc: "root"
357
+ }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
358
+ }
359
+ function values(iterable) {
360
+ if (iterable) {
361
+ var iteratorMethod = iterable[iteratorSymbol];
362
+ if (iteratorMethod) return iteratorMethod.call(iterable);
363
+ if ("function" == typeof iterable.next) return iterable;
364
+ if (!isNaN(iterable.length)) {
365
+ var i = -1,
366
+ next = function next() {
367
+ for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
368
+ return next.value = undefined, next.done = !0, next;
369
+ };
370
+ return next.next = next;
371
+ }
372
+ }
373
+ return {
374
+ next: doneResult
375
+ };
376
+ }
377
+ function doneResult() {
378
+ return {
379
+ value: undefined,
380
+ done: !0
381
+ };
382
+ }
383
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
384
+ value: GeneratorFunctionPrototype,
385
+ configurable: !0
386
+ }), defineProperty(GeneratorFunctionPrototype, "constructor", {
387
+ value: GeneratorFunction,
388
+ configurable: !0
389
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
390
+ var ctor = "function" == typeof genFun && genFun.constructor;
391
+ return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
392
+ }, exports.mark = function (genFun) {
393
+ return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
394
+ }, exports.awrap = function (arg) {
395
+ return {
396
+ __await: arg
397
+ };
398
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
399
+ return this;
400
+ }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
401
+ void 0 === PromiseImpl && (PromiseImpl = Promise);
402
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
403
+ return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
404
+ return result.done ? result.value : iter.next();
405
+ });
406
+ }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
407
+ return this;
408
+ }), define(Gp, "toString", function () {
409
+ return "[object Generator]";
410
+ }), exports.keys = function (val) {
411
+ var object = Object(val),
412
+ keys = [];
413
+ for (var key in object) keys.push(key);
414
+ return keys.reverse(), function next() {
415
+ for (; keys.length;) {
416
+ var key = keys.pop();
417
+ if (key in object) return next.value = key, next.done = !1, next;
418
+ }
419
+ return next.done = !0, next;
420
+ };
421
+ }, exports.values = values, Context.prototype = {
422
+ constructor: Context,
423
+ reset: function reset(skipTempReset) {
424
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
425
+ },
426
+ stop: function stop() {
427
+ this.done = !0;
428
+ var rootRecord = this.tryEntries[0].completion;
429
+ if ("throw" === rootRecord.type) throw rootRecord.arg;
430
+ return this.rval;
431
+ },
432
+ dispatchException: function dispatchException(exception) {
433
+ if (this.done) throw exception;
434
+ var context = this;
435
+ function handle(loc, caught) {
436
+ return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
437
+ }
438
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
439
+ var entry = this.tryEntries[i],
440
+ record = entry.completion;
441
+ if ("root" === entry.tryLoc) return handle("end");
442
+ if (entry.tryLoc <= this.prev) {
443
+ var hasCatch = hasOwn.call(entry, "catchLoc"),
444
+ hasFinally = hasOwn.call(entry, "finallyLoc");
445
+ if (hasCatch && hasFinally) {
446
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
447
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
448
+ } else if (hasCatch) {
449
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
450
+ } else {
451
+ if (!hasFinally) throw new Error("try statement without catch or finally");
452
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
453
+ }
454
+ }
455
+ }
456
+ },
457
+ abrupt: function abrupt(type, arg) {
458
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
459
+ var entry = this.tryEntries[i];
460
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
461
+ var finallyEntry = entry;
462
+ break;
463
+ }
464
+ }
465
+ finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
466
+ var record = finallyEntry ? finallyEntry.completion : {};
467
+ return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
468
+ },
469
+ complete: function complete(record, afterLoc) {
470
+ if ("throw" === record.type) throw record.arg;
471
+ return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
472
+ },
473
+ finish: function finish(finallyLoc) {
474
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
475
+ var entry = this.tryEntries[i];
476
+ if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
477
+ }
478
+ },
479
+ "catch": function _catch(tryLoc) {
480
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
481
+ var entry = this.tryEntries[i];
482
+ if (entry.tryLoc === tryLoc) {
483
+ var record = entry.completion;
484
+ if ("throw" === record.type) {
485
+ var thrown = record.arg;
486
+ resetTryEntry(entry);
487
+ }
488
+ return thrown;
489
+ }
490
+ }
491
+ throw new Error("illegal catch attempt");
492
+ },
493
+ delegateYield: function delegateYield(iterable, resultName, nextLoc) {
494
+ return this.delegate = {
495
+ iterator: values(iterable),
496
+ resultName: resultName,
497
+ nextLoc: nextLoc
498
+ }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
499
+ }
500
+ }, exports;
501
+ }
502
+ module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
503
+ } (regeneratorRuntime$1));
504
+
505
+ var regeneratorRuntimeExports = regeneratorRuntime$1.exports;
506
+
507
+ // TODO(Babel 8): Remove this file.
508
+
509
+ var runtime = regeneratorRuntimeExports();
510
+ var regenerator = runtime;
511
+
512
+ // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
513
+ try {
514
+ regeneratorRuntime = runtime;
515
+ } catch (accidentalStrictMode) {
516
+ if (typeof globalThis === "object") {
517
+ globalThis.regeneratorRuntime = runtime;
518
+ } else {
519
+ Function("r", "regeneratorRuntime = r")(runtime);
520
+ }
521
+ }
522
+
523
+ var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator);
524
+
525
+ // https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html#ErrorCodeList
526
+ var TOTAL_RETRIES = 30;
527
+ var INITIAL_RETRY_DELAY = 4000;
528
+ var MAX_RETRY_DELAY = 16000;
529
+ var DEFAULT_RETRY_CONFIG = {
530
+ retries: TOTAL_RETRIES,
531
+ retryDelay: INITIAL_RETRY_DELAY,
532
+ retryableStatuses: []
533
+ };
534
+
535
+ // No need to localize this since it will only be used in the code
536
+ // eslint-disable-next-line @bigbinary/neeto/hard-coded-strings-should-be-localized
537
+ var NETWORK_ERROR = "Network Error";
538
+
539
+ var sleep = function sleep(delay) {
540
+ return new Promise(function (resolve) {
541
+ return setTimeout(resolve, delay);
542
+ });
543
+ };
544
+
545
+ var buildRetryableApi = function buildRetryableApi(apiConnector) {
546
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_RETRY_CONFIG,
547
+ _ref$retries = _ref.retries,
548
+ retries = _ref$retries === void 0 ? TOTAL_RETRIES : _ref$retries,
549
+ _ref$retryDelay = _ref.retryDelay,
550
+ retryDelay = _ref$retryDelay === void 0 ? INITIAL_RETRY_DELAY : _ref$retryDelay,
551
+ retryableStatuses = _ref.retryableStatuses;
552
+ return /*#__PURE__*/function () {
553
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(apiConnectorArgs) {
554
+ var remainingAttempts, _error$response, isRetryableStatus, isRetryableError;
555
+ return _regeneratorRuntime.wrap(function _callee$(_context) {
556
+ while (1) switch (_context.prev = _context.next) {
557
+ case 0:
558
+ remainingAttempts = retries + 1;
559
+ case 1:
560
+ if (!remainingAttempts--) {
561
+ _context.next = 21;
562
+ break;
563
+ }
564
+ _context.prev = 2;
565
+ _context.next = 5;
566
+ return apiConnector(apiConnectorArgs);
567
+ case 5:
568
+ return _context.abrupt("return", _context.sent);
569
+ case 8:
570
+ _context.prev = 8;
571
+ _context.t0 = _context["catch"](2);
572
+ isRetryableStatus = isPresent(retryableStatuses) && retryableStatuses.includes((_error$response = _context.t0.response) === null || _error$response === void 0 ? void 0 : _error$response.status);
573
+ isRetryableError = isRetryableStatus || _context.t0.message === NETWORK_ERROR;
574
+ if (!(isRetryableError && remainingAttempts > 0)) {
575
+ _context.next = 18;
576
+ break;
577
+ }
578
+ _context.next = 15;
579
+ return sleep(retryDelay);
580
+ case 15:
581
+ retryDelay = min(retryDelay * 2, MAX_RETRY_DELAY);
582
+ _context.next = 19;
583
+ break;
584
+ case 18:
585
+ throw _context.t0;
586
+ case 19:
587
+ _context.next = 1;
588
+ break;
589
+ case 21:
590
+ return _context.abrupt("return", null);
591
+ case 22:
592
+ case "end":
593
+ return _context.stop();
594
+ }
595
+ }, _callee, null, [[2, 8]]);
596
+ }));
597
+ return function (_x) {
598
+ return _ref2.apply(this, arguments);
599
+ };
600
+ }();
601
+ };
602
+
603
+ var create$2 = function create(_ref) {
604
+ var recordingId = _ref.recordingId,
605
+ payload = _ref.payload;
606
+ return axios.post("/api/v1/recordings/".concat(recordingId, "/abort_upload"), {
607
+ abortUpload: payload
608
+ });
609
+ };
610
+ var retryableCreate$2 = buildRetryableApi(create$2);
611
+ var abortUploadApi = {
612
+ create: retryableCreate$2
613
+ };
614
+
615
+ var create$1 = function create(_ref) {
616
+ var recordingId = _ref.recordingId,
617
+ payload = _ref.payload;
618
+ return axios.post("/api/v1/recordings/".concat(recordingId, "/complete_upload"), {
619
+ completeUpload: payload
620
+ });
621
+ };
622
+ var retryableCreate$1 = buildRetryableApi(create$1);
623
+ var completeUploadApi = {
624
+ create: retryableCreate$1
625
+ };
626
+
627
+ var create = function create(_ref) {
628
+ var recordingId = _ref.recordingId,
629
+ payload = _ref.payload;
630
+ return axios.post("/api/v1/recordings/".concat(recordingId, "/part_presigned_url"), {
631
+ partPresignedUrl: payload
632
+ });
633
+ };
634
+ var retryableCreate = buildRetryableApi(create);
635
+ var partPresignedUrlApi = {
636
+ create: retryableCreate
637
+ };
638
+
639
+ function _typeof(obj) {
640
+ "@babel/helpers - typeof";
641
+
642
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
643
+ return typeof obj;
644
+ } : function (obj) {
645
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
646
+ }, _typeof(obj);
647
+ }
648
+
649
+ function _classCallCheck(instance, Constructor) {
650
+ if (!(instance instanceof Constructor)) {
651
+ throw new TypeError("Cannot call a class as a function");
652
+ }
653
+ }
654
+
655
+ function _toPrimitive(input, hint) {
656
+ if (_typeof(input) !== "object" || input === null) return input;
657
+ var prim = input[Symbol.toPrimitive];
658
+ if (prim !== undefined) {
659
+ var res = prim.call(input, hint || "default");
660
+ if (_typeof(res) !== "object") return res;
661
+ throw new TypeError("@@toPrimitive must return a primitive value.");
662
+ }
663
+ return (hint === "string" ? String : Number)(input);
664
+ }
665
+
666
+ function _toPropertyKey(arg) {
667
+ var key = _toPrimitive(arg, "string");
668
+ return _typeof(key) === "symbol" ? key : String(key);
669
+ }
670
+
671
+ function _defineProperties(target, props) {
672
+ for (var i = 0; i < props.length; i++) {
673
+ var descriptor = props[i];
674
+ descriptor.enumerable = descriptor.enumerable || false;
675
+ descriptor.configurable = true;
676
+ if ("value" in descriptor) descriptor.writable = true;
677
+ Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
678
+ }
679
+ }
680
+ function _createClass(Constructor, protoProps, staticProps) {
681
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
682
+ if (staticProps) _defineProperties(Constructor, staticProps);
683
+ Object.defineProperty(Constructor, "prototype", {
684
+ writable: false
685
+ });
686
+ return Constructor;
687
+ }
688
+
689
+ function _assertThisInitialized(self) {
690
+ if (self === void 0) {
691
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
692
+ }
693
+ return self;
694
+ }
695
+
696
+ function _setPrototypeOf(o, p) {
697
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
698
+ o.__proto__ = p;
699
+ return o;
700
+ };
701
+ return _setPrototypeOf(o, p);
702
+ }
703
+
704
+ function _inherits(subClass, superClass) {
705
+ if (typeof superClass !== "function" && superClass !== null) {
706
+ throw new TypeError("Super expression must either be null or a function");
707
+ }
708
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
709
+ constructor: {
710
+ value: subClass,
711
+ writable: true,
712
+ configurable: true
713
+ }
714
+ });
715
+ Object.defineProperty(subClass, "prototype", {
716
+ writable: false
717
+ });
718
+ if (superClass) _setPrototypeOf(subClass, superClass);
719
+ }
720
+
721
+ function _possibleConstructorReturn(self, call) {
722
+ if (call && (_typeof(call) === "object" || typeof call === "function")) {
723
+ return call;
724
+ } else if (call !== void 0) {
725
+ throw new TypeError("Derived constructors may only return object or undefined");
726
+ }
727
+ return _assertThisInitialized(self);
728
+ }
729
+
730
+ function _getPrototypeOf(o) {
731
+ _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
732
+ return o.__proto__ || Object.getPrototypeOf(o);
733
+ };
734
+ return _getPrototypeOf(o);
735
+ }
736
+
737
+ function _defineProperty(obj, key, value) {
738
+ key = _toPropertyKey(key);
739
+ if (key in obj) {
740
+ Object.defineProperty(obj, key, {
741
+ value: value,
742
+ enumerable: true,
743
+ configurable: true,
744
+ writable: true
745
+ });
746
+ } else {
747
+ obj[key] = value;
748
+ }
749
+ return obj;
750
+ }
751
+
752
+ function _arrayWithHoles(arr) {
753
+ if (Array.isArray(arr)) return arr;
754
+ }
755
+
756
+ function _iterableToArray(iter) {
757
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
758
+ }
759
+
760
+ function _arrayLikeToArray(arr, len) {
761
+ if (len == null || len > arr.length) len = arr.length;
762
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
763
+ return arr2;
764
+ }
765
+
766
+ function _unsupportedIterableToArray(o, minLen) {
767
+ if (!o) return;
768
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
769
+ var n = Object.prototype.toString.call(o).slice(8, -1);
770
+ if (n === "Object" && o.constructor) n = o.constructor.name;
771
+ if (n === "Map" || n === "Set") return Array.from(o);
772
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
773
+ }
774
+
775
+ function _nonIterableRest() {
776
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
777
+ }
778
+
779
+ function _toArray(arr) {
780
+ return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest();
781
+ }
782
+
783
+ function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
784
+ function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$6(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
785
+ var consoleLogger = {
786
+ type: 'logger',
787
+ log: function log(args) {
788
+ this.output('log', args);
789
+ },
790
+ warn: function warn(args) {
791
+ this.output('warn', args);
792
+ },
793
+ error: function error(args) {
794
+ this.output('error', args);
795
+ },
796
+ output: function output(type, args) {
797
+ if (console && console[type]) console[type].apply(console, args);
798
+ }
799
+ };
800
+ var Logger = function () {
801
+ function Logger(concreteLogger) {
802
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
803
+ _classCallCheck(this, Logger);
804
+ this.init(concreteLogger, options);
805
+ }
806
+ _createClass(Logger, [{
807
+ key: "init",
808
+ value: function init(concreteLogger) {
809
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
810
+ this.prefix = options.prefix || 'i18next:';
811
+ this.logger = concreteLogger || consoleLogger;
812
+ this.options = options;
813
+ this.debug = options.debug;
814
+ }
815
+ }, {
816
+ key: "setDebug",
817
+ value: function setDebug(bool) {
818
+ this.debug = bool;
819
+ }
820
+ }, {
821
+ key: "log",
822
+ value: function log() {
823
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
824
+ args[_key] = arguments[_key];
825
+ }
826
+ return this.forward(args, 'log', '', true);
827
+ }
828
+ }, {
829
+ key: "warn",
830
+ value: function warn() {
831
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
832
+ args[_key2] = arguments[_key2];
833
+ }
834
+ return this.forward(args, 'warn', '', true);
835
+ }
836
+ }, {
837
+ key: "error",
838
+ value: function error() {
839
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
840
+ args[_key3] = arguments[_key3];
841
+ }
842
+ return this.forward(args, 'error', '');
843
+ }
844
+ }, {
845
+ key: "deprecate",
846
+ value: function deprecate() {
847
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
848
+ args[_key4] = arguments[_key4];
849
+ }
850
+ return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
851
+ }
852
+ }, {
853
+ key: "forward",
854
+ value: function forward(args, lvl, prefix, debugOnly) {
855
+ if (debugOnly && !this.debug) return null;
856
+ if (typeof args[0] === 'string') args[0] = "".concat(prefix).concat(this.prefix, " ").concat(args[0]);
857
+ return this.logger[lvl](args);
858
+ }
859
+ }, {
860
+ key: "create",
861
+ value: function create(moduleName) {
862
+ return new Logger(this.logger, _objectSpread$6(_objectSpread$6({}, {
863
+ prefix: "".concat(this.prefix, ":").concat(moduleName, ":")
864
+ }), this.options));
865
+ }
866
+ }, {
867
+ key: "clone",
868
+ value: function clone(options) {
869
+ options = options || this.options;
870
+ options.prefix = options.prefix || this.prefix;
871
+ return new Logger(this.logger, options);
872
+ }
873
+ }]);
874
+ return Logger;
875
+ }();
876
+ var baseLogger = new Logger();
877
+
878
+ var EventEmitter = function () {
879
+ function EventEmitter() {
880
+ _classCallCheck(this, EventEmitter);
881
+ this.observers = {};
882
+ }
883
+ _createClass(EventEmitter, [{
884
+ key: "on",
885
+ value: function on(events, listener) {
886
+ var _this = this;
887
+ events.split(' ').forEach(function (event) {
888
+ _this.observers[event] = _this.observers[event] || [];
889
+ _this.observers[event].push(listener);
890
+ });
891
+ return this;
892
+ }
893
+ }, {
894
+ key: "off",
895
+ value: function off(event, listener) {
896
+ if (!this.observers[event]) return;
897
+ if (!listener) {
898
+ delete this.observers[event];
899
+ return;
900
+ }
901
+ this.observers[event] = this.observers[event].filter(function (l) {
902
+ return l !== listener;
903
+ });
904
+ }
905
+ }, {
906
+ key: "emit",
907
+ value: function emit(event) {
908
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
909
+ args[_key - 1] = arguments[_key];
910
+ }
911
+ if (this.observers[event]) {
912
+ var cloned = [].concat(this.observers[event]);
913
+ cloned.forEach(function (observer) {
914
+ observer.apply(void 0, args);
915
+ });
916
+ }
917
+ if (this.observers['*']) {
918
+ var _cloned = [].concat(this.observers['*']);
919
+ _cloned.forEach(function (observer) {
920
+ observer.apply(observer, [event].concat(args));
921
+ });
922
+ }
923
+ }
924
+ }]);
925
+ return EventEmitter;
926
+ }();
927
+
928
+ function defer() {
929
+ var res;
930
+ var rej;
931
+ var promise = new Promise(function (resolve, reject) {
932
+ res = resolve;
933
+ rej = reject;
934
+ });
935
+ promise.resolve = res;
936
+ promise.reject = rej;
937
+ return promise;
938
+ }
939
+ function makeString(object) {
940
+ if (object == null) return '';
941
+ return '' + object;
942
+ }
943
+ function copy(a, s, t) {
944
+ a.forEach(function (m) {
945
+ if (s[m]) t[m] = s[m];
946
+ });
947
+ }
948
+ function getLastOfPath(object, path, Empty) {
949
+ function cleanKey(key) {
950
+ return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
951
+ }
952
+ function canNotTraverseDeeper() {
953
+ return !object || typeof object === 'string';
954
+ }
955
+ var stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
956
+ while (stack.length > 1) {
957
+ if (canNotTraverseDeeper()) return {};
958
+ var key = cleanKey(stack.shift());
959
+ if (!object[key] && Empty) object[key] = new Empty();
960
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
961
+ object = object[key];
962
+ } else {
963
+ object = {};
964
+ }
965
+ }
966
+ if (canNotTraverseDeeper()) return {};
967
+ return {
968
+ obj: object,
969
+ k: cleanKey(stack.shift())
970
+ };
971
+ }
972
+ function setPath(object, path, newValue) {
973
+ var _getLastOfPath = getLastOfPath(object, path, Object),
974
+ obj = _getLastOfPath.obj,
975
+ k = _getLastOfPath.k;
976
+ obj[k] = newValue;
977
+ }
978
+ function pushPath(object, path, newValue, concat) {
979
+ var _getLastOfPath2 = getLastOfPath(object, path, Object),
980
+ obj = _getLastOfPath2.obj,
981
+ k = _getLastOfPath2.k;
982
+ obj[k] = obj[k] || [];
983
+ if (concat) obj[k] = obj[k].concat(newValue);
984
+ if (!concat) obj[k].push(newValue);
985
+ }
986
+ function getPath(object, path) {
987
+ var _getLastOfPath3 = getLastOfPath(object, path),
988
+ obj = _getLastOfPath3.obj,
989
+ k = _getLastOfPath3.k;
990
+ if (!obj) return undefined;
991
+ return obj[k];
992
+ }
993
+ function getPathWithDefaults(data, defaultData, key) {
994
+ var value = getPath(data, key);
995
+ if (value !== undefined) {
996
+ return value;
997
+ }
998
+ return getPath(defaultData, key);
999
+ }
1000
+ function deepExtend(target, source, overwrite) {
1001
+ for (var prop in source) {
1002
+ if (prop !== '__proto__' && prop !== 'constructor') {
1003
+ if (prop in target) {
1004
+ if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
1005
+ if (overwrite) target[prop] = source[prop];
1006
+ } else {
1007
+ deepExtend(target[prop], source[prop], overwrite);
1008
+ }
1009
+ } else {
1010
+ target[prop] = source[prop];
1011
+ }
1012
+ }
1013
+ }
1014
+ return target;
1015
+ }
1016
+ function regexEscape(str) {
1017
+ return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
1018
+ }
1019
+ var _entityMap = {
1020
+ '&': '&amp;',
1021
+ '<': '&lt;',
1022
+ '>': '&gt;',
1023
+ '"': '&quot;',
1024
+ "'": '&#39;',
1025
+ '/': '&#x2F;'
1026
+ };
1027
+ function escape(data) {
1028
+ if (typeof data === 'string') {
1029
+ return data.replace(/[&<>"'\/]/g, function (s) {
1030
+ return _entityMap[s];
1031
+ });
1032
+ }
1033
+ return data;
1034
+ }
1035
+ var isIE10 = typeof window !== 'undefined' && window.navigator && typeof window.navigator.userAgentData === 'undefined' && window.navigator.userAgent && window.navigator.userAgent.indexOf('MSIE') > -1;
1036
+ var chars = [' ', ',', '?', '!', ';'];
1037
+ function looksLikeObjectPath(key, nsSeparator, keySeparator) {
1038
+ nsSeparator = nsSeparator || '';
1039
+ keySeparator = keySeparator || '';
1040
+ var possibleChars = chars.filter(function (c) {
1041
+ return nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0;
1042
+ });
1043
+ if (possibleChars.length === 0) return true;
1044
+ var r = new RegExp("(".concat(possibleChars.map(function (c) {
1045
+ return c === '?' ? '\\?' : c;
1046
+ }).join('|'), ")"));
1047
+ var matched = !r.test(key);
1048
+ if (!matched) {
1049
+ var ki = key.indexOf(keySeparator);
1050
+ if (ki > 0 && !r.test(key.substring(0, ki))) {
1051
+ matched = true;
1052
+ }
1053
+ }
1054
+ return matched;
1055
+ }
1056
+ function deepFind(obj, path) {
1057
+ var keySeparator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '.';
1058
+ if (!obj) return undefined;
1059
+ if (obj[path]) return obj[path];
1060
+ var paths = path.split(keySeparator);
1061
+ var current = obj;
1062
+ for (var i = 0; i < paths.length; ++i) {
1063
+ if (!current) return undefined;
1064
+ if (typeof current[paths[i]] === 'string' && i + 1 < paths.length) {
1065
+ return undefined;
1066
+ }
1067
+ if (current[paths[i]] === undefined) {
1068
+ var j = 2;
1069
+ var p = paths.slice(i, i + j).join(keySeparator);
1070
+ var mix = current[p];
1071
+ while (mix === undefined && paths.length > i + j) {
1072
+ j++;
1073
+ p = paths.slice(i, i + j).join(keySeparator);
1074
+ mix = current[p];
1075
+ }
1076
+ if (mix === undefined) return undefined;
1077
+ if (mix === null) return null;
1078
+ if (path.endsWith(p)) {
1079
+ if (typeof mix === 'string') return mix;
1080
+ if (p && typeof mix[p] === 'string') return mix[p];
1081
+ }
1082
+ var joinedPath = paths.slice(i + j).join(keySeparator);
1083
+ if (joinedPath) return deepFind(mix, joinedPath, keySeparator);
1084
+ return undefined;
1085
+ }
1086
+ current = current[paths[i]];
1087
+ }
1088
+ return current;
1089
+ }
1090
+
1091
+ function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
1092
+ function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$5(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1093
+ function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
1094
+ function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
1095
+ var ResourceStore = function (_EventEmitter) {
1096
+ _inherits(ResourceStore, _EventEmitter);
1097
+ var _super = _createSuper$3(ResourceStore);
1098
+ function ResourceStore(data) {
1099
+ var _this;
1100
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
1101
+ ns: ['translation'],
1102
+ defaultNS: 'translation'
1103
+ };
1104
+ _classCallCheck(this, ResourceStore);
1105
+ _this = _super.call(this);
1106
+ if (isIE10) {
1107
+ EventEmitter.call(_assertThisInitialized(_this));
1108
+ }
1109
+ _this.data = data || {};
1110
+ _this.options = options;
1111
+ if (_this.options.keySeparator === undefined) {
1112
+ _this.options.keySeparator = '.';
1113
+ }
1114
+ if (_this.options.ignoreJSONStructure === undefined) {
1115
+ _this.options.ignoreJSONStructure = true;
1116
+ }
1117
+ return _this;
1118
+ }
1119
+ _createClass(ResourceStore, [{
1120
+ key: "addNamespaces",
1121
+ value: function addNamespaces(ns) {
1122
+ if (this.options.ns.indexOf(ns) < 0) {
1123
+ this.options.ns.push(ns);
1124
+ }
1125
+ }
1126
+ }, {
1127
+ key: "removeNamespaces",
1128
+ value: function removeNamespaces(ns) {
1129
+ var index = this.options.ns.indexOf(ns);
1130
+ if (index > -1) {
1131
+ this.options.ns.splice(index, 1);
1132
+ }
1133
+ }
1134
+ }, {
1135
+ key: "getResource",
1136
+ value: function getResource(lng, ns, key) {
1137
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1138
+ var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
1139
+ var ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
1140
+ var path = [lng, ns];
1141
+ if (key && typeof key !== 'string') path = path.concat(key);
1142
+ if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
1143
+ if (lng.indexOf('.') > -1) {
1144
+ path = lng.split('.');
1145
+ }
1146
+ var result = getPath(this.data, path);
1147
+ if (result || !ignoreJSONStructure || typeof key !== 'string') return result;
1148
+ return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
1149
+ }
1150
+ }, {
1151
+ key: "addResource",
1152
+ value: function addResource(lng, ns, key, value) {
1153
+ var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
1154
+ silent: false
1155
+ };
1156
+ var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
1157
+ var path = [lng, ns];
1158
+ if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
1159
+ if (lng.indexOf('.') > -1) {
1160
+ path = lng.split('.');
1161
+ value = ns;
1162
+ ns = path[1];
1163
+ }
1164
+ this.addNamespaces(ns);
1165
+ setPath(this.data, path, value);
1166
+ if (!options.silent) this.emit('added', lng, ns, key, value);
1167
+ }
1168
+ }, {
1169
+ key: "addResources",
1170
+ value: function addResources(lng, ns, resources) {
1171
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
1172
+ silent: false
1173
+ };
1174
+ for (var m in resources) {
1175
+ if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {
1176
+ silent: true
1177
+ });
1178
+ }
1179
+ if (!options.silent) this.emit('added', lng, ns, resources);
1180
+ }
1181
+ }, {
1182
+ key: "addResourceBundle",
1183
+ value: function addResourceBundle(lng, ns, resources, deep, overwrite) {
1184
+ var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
1185
+ silent: false
1186
+ };
1187
+ var path = [lng, ns];
1188
+ if (lng.indexOf('.') > -1) {
1189
+ path = lng.split('.');
1190
+ deep = resources;
1191
+ resources = ns;
1192
+ ns = path[1];
1193
+ }
1194
+ this.addNamespaces(ns);
1195
+ var pack = getPath(this.data, path) || {};
1196
+ if (deep) {
1197
+ deepExtend(pack, resources, overwrite);
1198
+ } else {
1199
+ pack = _objectSpread$5(_objectSpread$5({}, pack), resources);
1200
+ }
1201
+ setPath(this.data, path, pack);
1202
+ if (!options.silent) this.emit('added', lng, ns, resources);
1203
+ }
1204
+ }, {
1205
+ key: "removeResourceBundle",
1206
+ value: function removeResourceBundle(lng, ns) {
1207
+ if (this.hasResourceBundle(lng, ns)) {
1208
+ delete this.data[lng][ns];
1209
+ }
1210
+ this.removeNamespaces(ns);
1211
+ this.emit('removed', lng, ns);
1212
+ }
1213
+ }, {
1214
+ key: "hasResourceBundle",
1215
+ value: function hasResourceBundle(lng, ns) {
1216
+ return this.getResource(lng, ns) !== undefined;
1217
+ }
1218
+ }, {
1219
+ key: "getResourceBundle",
1220
+ value: function getResourceBundle(lng, ns) {
1221
+ if (!ns) ns = this.options.defaultNS;
1222
+ if (this.options.compatibilityAPI === 'v1') return _objectSpread$5(_objectSpread$5({}, {}), this.getResource(lng, ns));
1223
+ return this.getResource(lng, ns);
1224
+ }
1225
+ }, {
1226
+ key: "getDataByLanguage",
1227
+ value: function getDataByLanguage(lng) {
1228
+ return this.data[lng];
1229
+ }
1230
+ }, {
1231
+ key: "hasLanguageSomeTranslations",
1232
+ value: function hasLanguageSomeTranslations(lng) {
1233
+ var data = this.getDataByLanguage(lng);
1234
+ var n = data && Object.keys(data) || [];
1235
+ return !!n.find(function (v) {
1236
+ return data[v] && Object.keys(data[v]).length > 0;
1237
+ });
1238
+ }
1239
+ }, {
1240
+ key: "toJSON",
1241
+ value: function toJSON() {
1242
+ return this.data;
1243
+ }
1244
+ }]);
1245
+ return ResourceStore;
1246
+ }(EventEmitter);
1247
+
1248
+ var postProcessor = {
1249
+ processors: {},
1250
+ addPostProcessor: function addPostProcessor(module) {
1251
+ this.processors[module.name] = module;
1252
+ },
1253
+ handle: function handle(processors, value, key, options, translator) {
1254
+ var _this = this;
1255
+ processors.forEach(function (processor) {
1256
+ if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator);
1257
+ });
1258
+ return value;
1259
+ }
1260
+ };
1261
+
1262
+ function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
1263
+ function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$4(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
1264
+ function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
1265
+ function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
1266
+ var checkedLoadedFor = {};
1267
+ var Translator = function (_EventEmitter) {
1268
+ _inherits(Translator, _EventEmitter);
1269
+ var _super = _createSuper$2(Translator);
1270
+ function Translator(services) {
1271
+ var _this;
1272
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1273
+ _classCallCheck(this, Translator);
1274
+ _this = _super.call(this);
1275
+ if (isIE10) {
1276
+ EventEmitter.call(_assertThisInitialized(_this));
1277
+ }
1278
+ copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, _assertThisInitialized(_this));
1279
+ _this.options = options;
1280
+ if (_this.options.keySeparator === undefined) {
1281
+ _this.options.keySeparator = '.';
1282
+ }
1283
+ _this.logger = baseLogger.create('translator');
1284
+ return _this;
1285
+ }
1286
+ _createClass(Translator, [{
1287
+ key: "changeLanguage",
1288
+ value: function changeLanguage(lng) {
1289
+ if (lng) this.language = lng;
1290
+ }
1291
+ }, {
1292
+ key: "exists",
1293
+ value: function exists(key) {
1294
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
1295
+ interpolation: {}
1296
+ };
1297
+ if (key === undefined || key === null) {
1298
+ return false;
1299
+ }
1300
+ var resolved = this.resolve(key, options);
1301
+ return resolved && resolved.res !== undefined;
1302
+ }
1303
+ }, {
1304
+ key: "extractFromKey",
1305
+ value: function extractFromKey(key, options) {
1306
+ var nsSeparator = options.nsSeparator !== undefined ? options.nsSeparator : this.options.nsSeparator;
1307
+ if (nsSeparator === undefined) nsSeparator = ':';
1308
+ var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
1309
+ var namespaces = options.ns || this.options.defaultNS || [];
1310
+ var wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
1311
+ var seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
1312
+ if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
1313
+ var m = key.match(this.interpolator.nestingRegexp);
1314
+ if (m && m.length > 0) {
1315
+ return {
1316
+ key: key,
1317
+ namespaces: namespaces
1318
+ };
1319
+ }
1320
+ var parts = key.split(nsSeparator);
1321
+ if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
1322
+ key = parts.join(keySeparator);
1323
+ }
1324
+ if (typeof namespaces === 'string') namespaces = [namespaces];
1325
+ return {
1326
+ key: key,
1327
+ namespaces: namespaces
1328
+ };
1329
+ }
1330
+ }, {
1331
+ key: "translate",
1332
+ value: function translate(keys, options, lastKey) {
1333
+ var _this2 = this;
1334
+ if (_typeof(options) !== 'object' && this.options.overloadTranslationOptionHandler) {
1335
+ options = this.options.overloadTranslationOptionHandler(arguments);
1336
+ }
1337
+ if (_typeof(options) === 'object') options = _objectSpread$4({}, options);
1338
+ if (!options) options = {};
1339
+ if (keys === undefined || keys === null) return '';
1340
+ if (!Array.isArray(keys)) keys = [String(keys)];
1341
+ var returnDetails = options.returnDetails !== undefined ? options.returnDetails : this.options.returnDetails;
1342
+ var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
1343
+ var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options),
1344
+ key = _this$extractFromKey.key,
1345
+ namespaces = _this$extractFromKey.namespaces;
1346
+ var namespace = namespaces[namespaces.length - 1];
1347
+ var lng = options.lng || this.language;
1348
+ var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
1349
+ if (lng && lng.toLowerCase() === 'cimode') {
1350
+ if (appendNamespaceToCIMode) {
1351
+ var nsSeparator = options.nsSeparator || this.options.nsSeparator;
1352
+ if (returnDetails) {
1353
+ return {
1354
+ res: "".concat(namespace).concat(nsSeparator).concat(key),
1355
+ usedKey: key,
1356
+ exactUsedKey: key,
1357
+ usedLng: lng,
1358
+ usedNS: namespace
1359
+ };
1360
+ }
1361
+ return "".concat(namespace).concat(nsSeparator).concat(key);
1362
+ }
1363
+ if (returnDetails) {
1364
+ return {
1365
+ res: key,
1366
+ usedKey: key,
1367
+ exactUsedKey: key,
1368
+ usedLng: lng,
1369
+ usedNS: namespace
1370
+ };
1371
+ }
1372
+ return key;
1373
+ }
1374
+ var resolved = this.resolve(keys, options);
1375
+ var res = resolved && resolved.res;
1376
+ var resUsedKey = resolved && resolved.usedKey || key;
1377
+ var resExactUsedKey = resolved && resolved.exactUsedKey || key;
1378
+ var resType = Object.prototype.toString.apply(res);
1379
+ var noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
1380
+ var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays;
1381
+ var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
1382
+ var handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';
1383
+ if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {
1384
+ if (!options.returnObjects && !this.options.returnObjects) {
1385
+ if (!this.options.returnedObjectHandler) {
1386
+ this.logger.warn('accessing an object - but returnObjects options is not enabled!');
1387
+ }
1388
+ var r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, _objectSpread$4(_objectSpread$4({}, options), {}, {
1389
+ ns: namespaces
1390
+ })) : "key '".concat(key, " (").concat(this.language, ")' returned an object instead of string.");
1391
+ if (returnDetails) {
1392
+ resolved.res = r;
1393
+ return resolved;
1394
+ }
1395
+ return r;
1396
+ }
1397
+ if (keySeparator) {
1398
+ var resTypeIsArray = resType === '[object Array]';
1399
+ var copy = resTypeIsArray ? [] : {};
1400
+ var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
1401
+ for (var m in res) {
1402
+ if (Object.prototype.hasOwnProperty.call(res, m)) {
1403
+ var deepKey = "".concat(newKeyToUse).concat(keySeparator).concat(m);
1404
+ copy[m] = this.translate(deepKey, _objectSpread$4(_objectSpread$4({}, options), {
1405
+ joinArrays: false,
1406
+ ns: namespaces
1407
+ }));
1408
+ if (copy[m] === deepKey) copy[m] = res[m];
1409
+ }
1410
+ }
1411
+ res = copy;
1412
+ }
1413
+ } else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {
1414
+ res = res.join(joinArrays);
1415
+ if (res) res = this.extendTranslation(res, keys, options, lastKey);
1416
+ } else {
1417
+ var usedDefault = false;
1418
+ var usedKey = false;
1419
+ var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
1420
+ var hasDefaultValue = Translator.hasDefaultValue(options);
1421
+ var defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : '';
1422
+ var defaultValue = options["defaultValue".concat(defaultValueSuffix)] || options.defaultValue;
1423
+ if (!this.isValidLookup(res) && hasDefaultValue) {
1424
+ usedDefault = true;
1425
+ res = defaultValue;
1426
+ }
1427
+ if (!this.isValidLookup(res)) {
1428
+ usedKey = true;
1429
+ res = key;
1430
+ }
1431
+ var missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
1432
+ var resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
1433
+ var updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
1434
+ if (usedKey || usedDefault || updateMissing) {
1435
+ this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
1436
+ if (keySeparator) {
1437
+ var fk = this.resolve(key, _objectSpread$4(_objectSpread$4({}, options), {}, {
1438
+ keySeparator: false
1439
+ }));
1440
+ if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');
1441
+ }
1442
+ var lngs = [];
1443
+ var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
1444
+ if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
1445
+ for (var i = 0; i < fallbackLngs.length; i++) {
1446
+ lngs.push(fallbackLngs[i]);
1447
+ }
1448
+ } else if (this.options.saveMissingTo === 'all') {
1449
+ lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
1450
+ } else {
1451
+ lngs.push(options.lng || this.language);
1452
+ }
1453
+ var send = function send(l, k, specificDefaultValue) {
1454
+ var defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
1455
+ if (_this2.options.missingKeyHandler) {
1456
+ _this2.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
1457
+ } else if (_this2.backendConnector && _this2.backendConnector.saveMissing) {
1458
+ _this2.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
1459
+ }
1460
+ _this2.emit('missingKey', l, namespace, k, res);
1461
+ };
1462
+ if (this.options.saveMissing) {
1463
+ if (this.options.saveMissingPlurals && needsPluralHandling) {
1464
+ lngs.forEach(function (language) {
1465
+ _this2.pluralResolver.getSuffixes(language, options).forEach(function (suffix) {
1466
+ send([language], key + suffix, options["defaultValue".concat(suffix)] || defaultValue);
1467
+ });
1468
+ });
1469
+ } else {
1470
+ send(lngs, key, defaultValue);
1471
+ }
1472
+ }
1473
+ }
1474
+ res = this.extendTranslation(res, keys, options, resolved, lastKey);
1475
+ if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = "".concat(namespace, ":").concat(key);
1476
+ if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
1477
+ if (this.options.compatibilityAPI !== 'v1') {
1478
+ res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? "".concat(namespace, ":").concat(key) : key, usedDefault ? res : undefined);
1479
+ } else {
1480
+ res = this.options.parseMissingKeyHandler(res);
1481
+ }
1482
+ }
1483
+ }
1484
+ if (returnDetails) {
1485
+ resolved.res = res;
1486
+ return resolved;
1487
+ }
1488
+ return res;
1489
+ }
1490
+ }, {
1491
+ key: "extendTranslation",
1492
+ value: function extendTranslation(res, key, options, resolved, lastKey) {
1493
+ var _this3 = this;
1494
+ if (this.i18nFormat && this.i18nFormat.parse) {
1495
+ res = this.i18nFormat.parse(res, _objectSpread$4(_objectSpread$4({}, this.options.interpolation.defaultVariables), options), resolved.usedLng, resolved.usedNS, resolved.usedKey, {
1496
+ resolved: resolved
1497
+ });
1498
+ } else if (!options.skipInterpolation) {
1499
+ if (options.interpolation) this.interpolator.init(_objectSpread$4(_objectSpread$4({}, options), {
1500
+ interpolation: _objectSpread$4(_objectSpread$4({}, this.options.interpolation), options.interpolation)
1501
+ }));
1502
+ var skipOnVariables = typeof res === 'string' && (options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
1503
+ var nestBef;
1504
+ if (skipOnVariables) {
1505
+ var nb = res.match(this.interpolator.nestingRegexp);
1506
+ nestBef = nb && nb.length;
1507
+ }
1508
+ var data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
1509
+ if (this.options.interpolation.defaultVariables) data = _objectSpread$4(_objectSpread$4({}, this.options.interpolation.defaultVariables), data);
1510
+ res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
1511
+ if (skipOnVariables) {
1512
+ var na = res.match(this.interpolator.nestingRegexp);
1513
+ var nestAft = na && na.length;
1514
+ if (nestBef < nestAft) options.nest = false;
1515
+ }
1516
+ if (!options.lng && this.options.compatibilityAPI !== 'v1' && resolved && resolved.res) options.lng = resolved.usedLng;
1517
+ if (options.nest !== false) res = this.interpolator.nest(res, function () {
1518
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1519
+ args[_key] = arguments[_key];
1520
+ }
1521
+ if (lastKey && lastKey[0] === args[0] && !options.context) {
1522
+ _this3.logger.warn("It seems you are nesting recursively key: ".concat(args[0], " in key: ").concat(key[0]));
1523
+ return null;
1524
+ }
1525
+ return _this3.translate.apply(_this3, args.concat([key]));
1526
+ }, options);
1527
+ if (options.interpolation) this.interpolator.reset();
1528
+ }
1529
+ var postProcess = options.postProcess || this.options.postProcess;
1530
+ var postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
1531
+ if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
1532
+ res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread$4({
1533
+ i18nResolved: resolved
1534
+ }, options) : options, this);
1535
+ }
1536
+ return res;
1537
+ }
1538
+ }, {
1539
+ key: "resolve",
1540
+ value: function resolve(keys) {
1541
+ var _this4 = this;
1542
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1543
+ var found;
1544
+ var usedKey;
1545
+ var exactUsedKey;
1546
+ var usedLng;
1547
+ var usedNS;
1548
+ if (typeof keys === 'string') keys = [keys];
1549
+ keys.forEach(function (k) {
1550
+ if (_this4.isValidLookup(found)) return;
1551
+ var extracted = _this4.extractFromKey(k, options);
1552
+ var key = extracted.key;
1553
+ usedKey = key;
1554
+ var namespaces = extracted.namespaces;
1555
+ if (_this4.options.fallbackNS) namespaces = namespaces.concat(_this4.options.fallbackNS);
1556
+ var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
1557
+ var needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && _this4.pluralResolver.shouldUseIntlApi();
1558
+ var needsContextHandling = options.context !== undefined && (typeof options.context === 'string' || typeof options.context === 'number') && options.context !== '';
1559
+ var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng);
1560
+ namespaces.forEach(function (ns) {
1561
+ if (_this4.isValidLookup(found)) return;
1562
+ usedNS = ns;
1563
+ if (!checkedLoadedFor["".concat(codes[0], "-").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) {
1564
+ checkedLoadedFor["".concat(codes[0], "-").concat(ns)] = true;
1565
+ _this4.logger.warn("key \"".concat(usedKey, "\" for languages \"").concat(codes.join(', '), "\" won't get resolved as namespace \"").concat(usedNS, "\" was not yet loaded"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
1566
+ }
1567
+ codes.forEach(function (code) {
1568
+ if (_this4.isValidLookup(found)) return;
1569
+ usedLng = code;
1570
+ var finalKeys = [key];
1571
+ if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) {
1572
+ _this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
1573
+ } else {
1574
+ var pluralSuffix;
1575
+ if (needsPluralHandling) pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count, options);
1576
+ var zeroSuffix = "".concat(_this4.options.pluralSeparator, "zero");
1577
+ if (needsPluralHandling) {
1578
+ finalKeys.push(key + pluralSuffix);
1579
+ if (needsZeroSuffixLookup) {
1580
+ finalKeys.push(key + zeroSuffix);
1581
+ }
1582
+ }
1583
+ if (needsContextHandling) {
1584
+ var contextKey = "".concat(key).concat(_this4.options.contextSeparator).concat(options.context);
1585
+ finalKeys.push(contextKey);
1586
+ if (needsPluralHandling) {
1587
+ finalKeys.push(contextKey + pluralSuffix);
1588
+ if (needsZeroSuffixLookup) {
1589
+ finalKeys.push(contextKey + zeroSuffix);
1590
+ }
1591
+ }
1592
+ }
1593
+ }
1594
+ var possibleKey;
1595
+ while (possibleKey = finalKeys.pop()) {
1596
+ if (!_this4.isValidLookup(found)) {
1597
+ exactUsedKey = possibleKey;
1598
+ found = _this4.getResource(code, ns, possibleKey, options);
1599
+ }
1600
+ }
1601
+ });
1602
+ });
1603
+ });
1604
+ return {
1605
+ res: found,
1606
+ usedKey: usedKey,
1607
+ exactUsedKey: exactUsedKey,
1608
+ usedLng: usedLng,
1609
+ usedNS: usedNS
1610
+ };
1611
+ }
1612
+ }, {
1613
+ key: "isValidLookup",
1614
+ value: function isValidLookup(res) {
1615
+ return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
1616
+ }
1617
+ }, {
1618
+ key: "getResource",
1619
+ value: function getResource(code, ns, key) {
1620
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
1621
+ if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
1622
+ return this.resourceStore.getResource(code, ns, key, options);
1623
+ }
1624
+ }], [{
1625
+ key: "hasDefaultValue",
1626
+ value: function hasDefaultValue(options) {
1627
+ var prefix = 'defaultValue';
1628
+ for (var option in options) {
1629
+ if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
1630
+ return true;
1631
+ }
1632
+ }
1633
+ return false;
1634
+ }
1635
+ }]);
1636
+ return Translator;
1637
+ }(EventEmitter);
1638
+
1639
+ function capitalize(string) {
1640
+ return string.charAt(0).toUpperCase() + string.slice(1);
1641
+ }
1642
+ var LanguageUtil = function () {
1643
+ function LanguageUtil(options) {
1644
+ _classCallCheck(this, LanguageUtil);
1645
+ this.options = options;
1646
+ this.supportedLngs = this.options.supportedLngs || false;
1647
+ this.logger = baseLogger.create('languageUtils');
1648
+ }
1649
+ _createClass(LanguageUtil, [{
1650
+ key: "getScriptPartFromCode",
1651
+ value: function getScriptPartFromCode(code) {
1652
+ if (!code || code.indexOf('-') < 0) return null;
1653
+ var p = code.split('-');
1654
+ if (p.length === 2) return null;
1655
+ p.pop();
1656
+ if (p[p.length - 1].toLowerCase() === 'x') return null;
1657
+ return this.formatLanguageCode(p.join('-'));
1658
+ }
1659
+ }, {
1660
+ key: "getLanguagePartFromCode",
1661
+ value: function getLanguagePartFromCode(code) {
1662
+ if (!code || code.indexOf('-') < 0) return code;
1663
+ var p = code.split('-');
1664
+ return this.formatLanguageCode(p[0]);
1665
+ }
1666
+ }, {
1667
+ key: "formatLanguageCode",
1668
+ value: function formatLanguageCode(code) {
1669
+ if (typeof code === 'string' && code.indexOf('-') > -1) {
1670
+ var specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
1671
+ var p = code.split('-');
1672
+ if (this.options.lowerCaseLng) {
1673
+ p = p.map(function (part) {
1674
+ return part.toLowerCase();
1675
+ });
1676
+ } else if (p.length === 2) {
1677
+ p[0] = p[0].toLowerCase();
1678
+ p[1] = p[1].toUpperCase();
1679
+ if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
1680
+ } else if (p.length === 3) {
1681
+ p[0] = p[0].toLowerCase();
1682
+ if (p[1].length === 2) p[1] = p[1].toUpperCase();
1683
+ if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
1684
+ if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
1685
+ if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
1686
+ }
1687
+ return p.join('-');
1688
+ }
1689
+ return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
1690
+ }
1691
+ }, {
1692
+ key: "isSupportedCode",
1693
+ value: function isSupportedCode(code) {
1694
+ if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
1695
+ code = this.getLanguagePartFromCode(code);
1696
+ }
1697
+ return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1698
+ }
1699
+ }, {
1700
+ key: "getBestMatchFromCodes",
1701
+ value: function getBestMatchFromCodes(codes) {
1702
+ var _this = this;
1703
+ if (!codes) return null;
1704
+ var found;
1705
+ codes.forEach(function (code) {
1706
+ if (found) return;
1707
+ var cleanedLng = _this.formatLanguageCode(code);
1708
+ if (!_this.options.supportedLngs || _this.isSupportedCode(cleanedLng)) found = cleanedLng;
1709
+ });
1710
+ if (!found && this.options.supportedLngs) {
1711
+ codes.forEach(function (code) {
1712
+ if (found) return;
1713
+ var lngOnly = _this.getLanguagePartFromCode(code);
1714
+ if (_this.isSupportedCode(lngOnly)) return found = lngOnly;
1715
+ found = _this.options.supportedLngs.find(function (supportedLng) {
1716
+ if (supportedLng === lngOnly) return supportedLng;
1717
+ if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
1718
+ if (supportedLng.indexOf(lngOnly) === 0) return supportedLng;
1719
+ });
1720
+ });
1721
+ }
1722
+ if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1723
+ return found;
1724
+ }
1725
+ }, {
1726
+ key: "getFallbackCodes",
1727
+ value: function getFallbackCodes(fallbacks, code) {
1728
+ if (!fallbacks) return [];
1729
+ if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
1730
+ if (typeof fallbacks === 'string') fallbacks = [fallbacks];
1731
+ if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
1732
+ if (!code) return fallbacks["default"] || [];
1733
+ var found = fallbacks[code];
1734
+ if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1735
+ if (!found) found = fallbacks[this.formatLanguageCode(code)];
1736
+ if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1737
+ if (!found) found = fallbacks["default"];
1738
+ return found || [];
1739
+ }
1740
+ }, {
1741
+ key: "toResolveHierarchy",
1742
+ value: function toResolveHierarchy(code, fallbackCode) {
1743
+ var _this2 = this;
1744
+ var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
1745
+ var codes = [];
1746
+ var addCode = function addCode(c) {
1747
+ if (!c) return;
1748
+ if (_this2.isSupportedCode(c)) {
1749
+ codes.push(c);
1750
+ } else {
1751
+ _this2.logger.warn("rejecting language code not found in supportedLngs: ".concat(c));
1752
+ }
1753
+ };
1754
+ if (typeof code === 'string' && code.indexOf('-') > -1) {
1755
+ if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
1756
+ if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
1757
+ if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
1758
+ } else if (typeof code === 'string') {
1759
+ addCode(this.formatLanguageCode(code));
1760
+ }
1761
+ fallbackCodes.forEach(function (fc) {
1762
+ if (codes.indexOf(fc) < 0) addCode(_this2.formatLanguageCode(fc));
1763
+ });
1764
+ return codes;
1765
+ }
1766
+ }]);
1767
+ return LanguageUtil;
1768
+ }();
1769
+
1770
+ var sets = [{
1771
+ lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'tl', 'ti', 'tr', 'uz', 'wa'],
1772
+ nr: [1, 2],
1773
+ fc: 1
1774
+ }, {
1775
+ lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kk', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],
1776
+ nr: [1, 2],
1777
+ fc: 2
1778
+ }, {
1779
+ lngs: ['ay', 'bo', 'cgg', 'fa', 'ht', 'id', 'ja', 'jbo', 'ka', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
1780
+ nr: [1],
1781
+ fc: 3
1782
+ }, {
1783
+ lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
1784
+ nr: [1, 2, 5],
1785
+ fc: 4
1786
+ }, {
1787
+ lngs: ['ar'],
1788
+ nr: [0, 1, 2, 3, 11, 100],
1789
+ fc: 5
1790
+ }, {
1791
+ lngs: ['cs', 'sk'],
1792
+ nr: [1, 2, 5],
1793
+ fc: 6
1794
+ }, {
1795
+ lngs: ['csb', 'pl'],
1796
+ nr: [1, 2, 5],
1797
+ fc: 7
1798
+ }, {
1799
+ lngs: ['cy'],
1800
+ nr: [1, 2, 3, 8],
1801
+ fc: 8
1802
+ }, {
1803
+ lngs: ['fr'],
1804
+ nr: [1, 2],
1805
+ fc: 9
1806
+ }, {
1807
+ lngs: ['ga'],
1808
+ nr: [1, 2, 3, 7, 11],
1809
+ fc: 10
1810
+ }, {
1811
+ lngs: ['gd'],
1812
+ nr: [1, 2, 3, 20],
1813
+ fc: 11
1814
+ }, {
1815
+ lngs: ['is'],
1816
+ nr: [1, 2],
1817
+ fc: 12
1818
+ }, {
1819
+ lngs: ['jv'],
1820
+ nr: [0, 1],
1821
+ fc: 13
1822
+ }, {
1823
+ lngs: ['kw'],
1824
+ nr: [1, 2, 3, 4],
1825
+ fc: 14
1826
+ }, {
1827
+ lngs: ['lt'],
1828
+ nr: [1, 2, 10],
1829
+ fc: 15
1830
+ }, {
1831
+ lngs: ['lv'],
1832
+ nr: [1, 2, 0],
1833
+ fc: 16
1834
+ }, {
1835
+ lngs: ['mk'],
1836
+ nr: [1, 2],
1837
+ fc: 17
1838
+ }, {
1839
+ lngs: ['mnk'],
1840
+ nr: [0, 1, 2],
1841
+ fc: 18
1842
+ }, {
1843
+ lngs: ['mt'],
1844
+ nr: [1, 2, 11, 20],
1845
+ fc: 19
1846
+ }, {
1847
+ lngs: ['or'],
1848
+ nr: [2, 1],
1849
+ fc: 2
1850
+ }, {
1851
+ lngs: ['ro'],
1852
+ nr: [1, 2, 20],
1853
+ fc: 20
1854
+ }, {
1855
+ lngs: ['sl'],
1856
+ nr: [5, 1, 2, 3],
1857
+ fc: 21
1858
+ }, {
1859
+ lngs: ['he', 'iw'],
1860
+ nr: [1, 2, 20, 21],
1861
+ fc: 22
1862
+ }];
1863
+ var _rulesPluralsTypes = {
1864
+ 1: function _(n) {
1865
+ return Number(n > 1);
1866
+ },
1867
+ 2: function _(n) {
1868
+ return Number(n != 1);
1869
+ },
1870
+ 3: function _(n) {
1871
+ return 0;
1872
+ },
1873
+ 4: function _(n) {
1874
+ return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1875
+ },
1876
+ 5: function _(n) {
1877
+ return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
1878
+ },
1879
+ 6: function _(n) {
1880
+ return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
1881
+ },
1882
+ 7: function _(n) {
1883
+ return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1884
+ },
1885
+ 8: function _(n) {
1886
+ return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
1887
+ },
1888
+ 9: function _(n) {
1889
+ return Number(n >= 2);
1890
+ },
1891
+ 10: function _(n) {
1892
+ return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
1893
+ },
1894
+ 11: function _(n) {
1895
+ return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
1896
+ },
1897
+ 12: function _(n) {
1898
+ return Number(n % 10 != 1 || n % 100 == 11);
1899
+ },
1900
+ 13: function _(n) {
1901
+ return Number(n !== 0);
1902
+ },
1903
+ 14: function _(n) {
1904
+ return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
1905
+ },
1906
+ 15: function _(n) {
1907
+ return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
1908
+ },
1909
+ 16: function _(n) {
1910
+ return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
1911
+ },
1912
+ 17: function _(n) {
1913
+ return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);
1914
+ },
1915
+ 18: function _(n) {
1916
+ return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
1917
+ },
1918
+ 19: function _(n) {
1919
+ return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
1920
+ },
1921
+ 20: function _(n) {
1922
+ return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
1923
+ },
1924
+ 21: function _(n) {
1925
+ return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
1926
+ },
1927
+ 22: function _(n) {
1928
+ return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
1929
+ }
1930
+ };
1931
+ var deprecatedJsonVersions = ['v1', 'v2', 'v3'];
1932
+ var suffixesOrder = {
1933
+ zero: 0,
1934
+ one: 1,
1935
+ two: 2,
1936
+ few: 3,
1937
+ many: 4,
1938
+ other: 5
1939
+ };
1940
+ function createRules() {
1941
+ var rules = {};
1942
+ sets.forEach(function (set) {
1943
+ set.lngs.forEach(function (l) {
1944
+ rules[l] = {
1945
+ numbers: set.nr,
1946
+ plurals: _rulesPluralsTypes[set.fc]
1947
+ };
1948
+ });
1949
+ });
1950
+ return rules;
1951
+ }
1952
+ var PluralResolver = function () {
1953
+ function PluralResolver(languageUtils) {
1954
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1955
+ _classCallCheck(this, PluralResolver);
1956
+ this.languageUtils = languageUtils;
1957
+ this.options = options;
1958
+ this.logger = baseLogger.create('pluralResolver');
1959
+ if ((!this.options.compatibilityJSON || this.options.compatibilityJSON === 'v4') && (typeof Intl === 'undefined' || !Intl.PluralRules)) {
1960
+ this.options.compatibilityJSON = 'v3';
1961
+ this.logger.error('Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.');
1962
+ }
1963
+ this.rules = createRules();
1964
+ }
1965
+ _createClass(PluralResolver, [{
1966
+ key: "addRule",
1967
+ value: function addRule(lng, obj) {
1968
+ this.rules[lng] = obj;
1969
+ }
1970
+ }, {
1971
+ key: "getRule",
1972
+ value: function getRule(code) {
1973
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1974
+ if (this.shouldUseIntlApi()) {
1975
+ try {
1976
+ return new Intl.PluralRules(code, {
1977
+ type: options.ordinal ? 'ordinal' : 'cardinal'
1978
+ });
1979
+ } catch (_unused) {
1980
+ return;
1981
+ }
1982
+ }
1983
+ return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
1984
+ }
1985
+ }, {
1986
+ key: "needsPlural",
1987
+ value: function needsPlural(code) {
1988
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1989
+ var rule = this.getRule(code, options);
1990
+ if (this.shouldUseIntlApi()) {
1991
+ return rule && rule.resolvedOptions().pluralCategories.length > 1;
1992
+ }
1993
+ return rule && rule.numbers.length > 1;
1994
+ }
1995
+ }, {
1996
+ key: "getPluralFormsOfKey",
1997
+ value: function getPluralFormsOfKey(code, key) {
1998
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
1999
+ return this.getSuffixes(code, options).map(function (suffix) {
2000
+ return "".concat(key).concat(suffix);
2001
+ });
2002
+ }
2003
+ }, {
2004
+ key: "getSuffixes",
2005
+ value: function getSuffixes(code) {
2006
+ var _this = this;
2007
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2008
+ var rule = this.getRule(code, options);
2009
+ if (!rule) {
2010
+ return [];
2011
+ }
2012
+ if (this.shouldUseIntlApi()) {
2013
+ return rule.resolvedOptions().pluralCategories.sort(function (pluralCategory1, pluralCategory2) {
2014
+ return suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2];
2015
+ }).map(function (pluralCategory) {
2016
+ return "".concat(_this.options.prepend).concat(pluralCategory);
2017
+ });
2018
+ }
2019
+ return rule.numbers.map(function (number) {
2020
+ return _this.getSuffix(code, number, options);
2021
+ });
2022
+ }
2023
+ }, {
2024
+ key: "getSuffix",
2025
+ value: function getSuffix(code, count) {
2026
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2027
+ var rule = this.getRule(code, options);
2028
+ if (rule) {
2029
+ if (this.shouldUseIntlApi()) {
2030
+ return "".concat(this.options.prepend).concat(rule.select(count));
2031
+ }
2032
+ return this.getSuffixRetroCompatible(rule, count);
2033
+ }
2034
+ this.logger.warn("no plural rule found for: ".concat(code));
2035
+ return '';
2036
+ }
2037
+ }, {
2038
+ key: "getSuffixRetroCompatible",
2039
+ value: function getSuffixRetroCompatible(rule, count) {
2040
+ var _this2 = this;
2041
+ var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
2042
+ var suffix = rule.numbers[idx];
2043
+ if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
2044
+ if (suffix === 2) {
2045
+ suffix = 'plural';
2046
+ } else if (suffix === 1) {
2047
+ suffix = '';
2048
+ }
2049
+ }
2050
+ var returnSuffix = function returnSuffix() {
2051
+ return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString();
2052
+ };
2053
+ if (this.options.compatibilityJSON === 'v1') {
2054
+ if (suffix === 1) return '';
2055
+ if (typeof suffix === 'number') return "_plural_".concat(suffix.toString());
2056
+ return returnSuffix();
2057
+ } else if (this.options.compatibilityJSON === 'v2') {
2058
+ return returnSuffix();
2059
+ } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
2060
+ return returnSuffix();
2061
+ }
2062
+ return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
2063
+ }
2064
+ }, {
2065
+ key: "shouldUseIntlApi",
2066
+ value: function shouldUseIntlApi() {
2067
+ return !deprecatedJsonVersions.includes(this.options.compatibilityJSON);
2068
+ }
2069
+ }]);
2070
+ return PluralResolver;
2071
+ }();
2072
+
2073
+ function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2074
+ function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$3(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2075
+ function deepFindWithDefaults(data, defaultData, key) {
2076
+ var keySeparator = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '.';
2077
+ var ignoreJSONStructure = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
2078
+ var path = getPathWithDefaults(data, defaultData, key);
2079
+ if (!path && ignoreJSONStructure && typeof key === 'string') {
2080
+ path = deepFind(data, key, keySeparator);
2081
+ if (path === undefined) path = deepFind(defaultData, key, keySeparator);
2082
+ }
2083
+ return path;
2084
+ }
2085
+ var Interpolator = function () {
2086
+ function Interpolator() {
2087
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2088
+ _classCallCheck(this, Interpolator);
2089
+ this.logger = baseLogger.create('interpolator');
2090
+ this.options = options;
2091
+ this.format = options.interpolation && options.interpolation.format || function (value) {
2092
+ return value;
2093
+ };
2094
+ this.init(options);
2095
+ }
2096
+ _createClass(Interpolator, [{
2097
+ key: "init",
2098
+ value: function init() {
2099
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2100
+ if (!options.interpolation) options.interpolation = {
2101
+ escapeValue: true
2102
+ };
2103
+ var iOpts = options.interpolation;
2104
+ this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
2105
+ this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
2106
+ this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;
2107
+ this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
2108
+ this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
2109
+ this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
2110
+ this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
2111
+ this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
2112
+ this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
2113
+ this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
2114
+ this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';
2115
+ this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
2116
+ this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false;
2117
+ this.resetRegExp();
2118
+ }
2119
+ }, {
2120
+ key: "reset",
2121
+ value: function reset() {
2122
+ if (this.options) this.init(this.options);
2123
+ }
2124
+ }, {
2125
+ key: "resetRegExp",
2126
+ value: function resetRegExp() {
2127
+ var regexpStr = "".concat(this.prefix, "(.+?)").concat(this.suffix);
2128
+ this.regexp = new RegExp(regexpStr, 'g');
2129
+ var regexpUnescapeStr = "".concat(this.prefix).concat(this.unescapePrefix, "(.+?)").concat(this.unescapeSuffix).concat(this.suffix);
2130
+ this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
2131
+ var nestingRegexpStr = "".concat(this.nestingPrefix, "(.+?)").concat(this.nestingSuffix);
2132
+ this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
2133
+ }
2134
+ }, {
2135
+ key: "interpolate",
2136
+ value: function interpolate(str, data, lng, options) {
2137
+ var _this = this;
2138
+ var match;
2139
+ var value;
2140
+ var replaces;
2141
+ var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
2142
+ function regexSafe(val) {
2143
+ return val.replace(/\$/g, '$$$$');
2144
+ }
2145
+ var handleFormat = function handleFormat(key) {
2146
+ if (key.indexOf(_this.formatSeparator) < 0) {
2147
+ var path = deepFindWithDefaults(data, defaultData, key, _this.options.keySeparator, _this.options.ignoreJSONStructure);
2148
+ return _this.alwaysFormat ? _this.format(path, undefined, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, {
2149
+ interpolationkey: key
2150
+ })) : path;
2151
+ }
2152
+ var p = key.split(_this.formatSeparator);
2153
+ var k = p.shift().trim();
2154
+ var f = p.join(_this.formatSeparator).trim();
2155
+ return _this.format(deepFindWithDefaults(data, defaultData, k, _this.options.keySeparator, _this.options.ignoreJSONStructure), f, lng, _objectSpread$3(_objectSpread$3(_objectSpread$3({}, options), data), {}, {
2156
+ interpolationkey: k
2157
+ }));
2158
+ };
2159
+ this.resetRegExp();
2160
+ var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
2161
+ var skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
2162
+ var todos = [{
2163
+ regex: this.regexpUnescape,
2164
+ safeValue: function safeValue(val) {
2165
+ return regexSafe(val);
2166
+ }
2167
+ }, {
2168
+ regex: this.regexp,
2169
+ safeValue: function safeValue(val) {
2170
+ return _this.escapeValue ? regexSafe(_this.escape(val)) : regexSafe(val);
2171
+ }
2172
+ }];
2173
+ todos.forEach(function (todo) {
2174
+ replaces = 0;
2175
+ while (match = todo.regex.exec(str)) {
2176
+ var matchedVar = match[1].trim();
2177
+ value = handleFormat(matchedVar);
2178
+ if (value === undefined) {
2179
+ if (typeof missingInterpolationHandler === 'function') {
2180
+ var temp = missingInterpolationHandler(str, match, options);
2181
+ value = typeof temp === 'string' ? temp : '';
2182
+ } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
2183
+ value = '';
2184
+ } else if (skipOnVariables) {
2185
+ value = match[0];
2186
+ continue;
2187
+ } else {
2188
+ _this.logger.warn("missed to pass in variable ".concat(matchedVar, " for interpolating ").concat(str));
2189
+ value = '';
2190
+ }
2191
+ } else if (typeof value !== 'string' && !_this.useRawValueToEscape) {
2192
+ value = makeString(value);
2193
+ }
2194
+ var safeValue = todo.safeValue(value);
2195
+ str = str.replace(match[0], safeValue);
2196
+ if (skipOnVariables) {
2197
+ todo.regex.lastIndex += value.length;
2198
+ todo.regex.lastIndex -= match[0].length;
2199
+ } else {
2200
+ todo.regex.lastIndex = 0;
2201
+ }
2202
+ replaces++;
2203
+ if (replaces >= _this.maxReplaces) {
2204
+ break;
2205
+ }
2206
+ }
2207
+ });
2208
+ return str;
2209
+ }
2210
+ }, {
2211
+ key: "nest",
2212
+ value: function nest(str, fc) {
2213
+ var _this2 = this;
2214
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2215
+ var match;
2216
+ var value;
2217
+ var clonedOptions;
2218
+ function handleHasOptions(key, inheritedOptions) {
2219
+ var sep = this.nestingOptionsSeparator;
2220
+ if (key.indexOf(sep) < 0) return key;
2221
+ var c = key.split(new RegExp("".concat(sep, "[ ]*{")));
2222
+ var optionsString = "{".concat(c[1]);
2223
+ key = c[0];
2224
+ optionsString = this.interpolate(optionsString, clonedOptions);
2225
+ var matchedSingleQuotes = optionsString.match(/'/g);
2226
+ var matchedDoubleQuotes = optionsString.match(/"/g);
2227
+ if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
2228
+ optionsString = optionsString.replace(/'/g, '"');
2229
+ }
2230
+ try {
2231
+ clonedOptions = JSON.parse(optionsString);
2232
+ if (inheritedOptions) clonedOptions = _objectSpread$3(_objectSpread$3({}, inheritedOptions), clonedOptions);
2233
+ } catch (e) {
2234
+ this.logger.warn("failed parsing options string in nesting for key ".concat(key), e);
2235
+ return "".concat(key).concat(sep).concat(optionsString);
2236
+ }
2237
+ delete clonedOptions.defaultValue;
2238
+ return key;
2239
+ }
2240
+ while (match = this.nestingRegexp.exec(str)) {
2241
+ var formatters = [];
2242
+ clonedOptions = _objectSpread$3({}, options);
2243
+ clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== 'string' ? clonedOptions.replace : clonedOptions;
2244
+ clonedOptions.applyPostProcessor = false;
2245
+ delete clonedOptions.defaultValue;
2246
+ var doReduce = false;
2247
+ if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
2248
+ var r = match[1].split(this.formatSeparator).map(function (elem) {
2249
+ return elem.trim();
2250
+ });
2251
+ match[1] = r.shift();
2252
+ formatters = r;
2253
+ doReduce = true;
2254
+ }
2255
+ value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
2256
+ if (value && match[0] === str && typeof value !== 'string') return value;
2257
+ if (typeof value !== 'string') value = makeString(value);
2258
+ if (!value) {
2259
+ this.logger.warn("missed to resolve ".concat(match[1], " for nesting ").concat(str));
2260
+ value = '';
2261
+ }
2262
+ if (doReduce) {
2263
+ value = formatters.reduce(function (v, f) {
2264
+ return _this2.format(v, f, options.lng, _objectSpread$3(_objectSpread$3({}, options), {}, {
2265
+ interpolationkey: match[1].trim()
2266
+ }));
2267
+ }, value.trim());
2268
+ }
2269
+ str = str.replace(match[0], value);
2270
+ this.regexp.lastIndex = 0;
2271
+ }
2272
+ return str;
2273
+ }
2274
+ }]);
2275
+ return Interpolator;
2276
+ }();
2277
+
2278
+ function ownKeys$2$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2279
+ function _objectSpread$2$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2280
+ function parseFormatStr(formatStr) {
2281
+ var formatName = formatStr.toLowerCase().trim();
2282
+ var formatOptions = {};
2283
+ if (formatStr.indexOf('(') > -1) {
2284
+ var p = formatStr.split('(');
2285
+ formatName = p[0].toLowerCase().trim();
2286
+ var optStr = p[1].substring(0, p[1].length - 1);
2287
+ if (formatName === 'currency' && optStr.indexOf(':') < 0) {
2288
+ if (!formatOptions.currency) formatOptions.currency = optStr.trim();
2289
+ } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
2290
+ if (!formatOptions.range) formatOptions.range = optStr.trim();
2291
+ } else {
2292
+ var opts = optStr.split(';');
2293
+ opts.forEach(function (opt) {
2294
+ if (!opt) return;
2295
+ var _opt$split = opt.split(':'),
2296
+ _opt$split2 = _toArray(_opt$split),
2297
+ key = _opt$split2[0],
2298
+ rest = _opt$split2.slice(1);
2299
+ var val = rest.join(':').trim().replace(/^'+|'+$/g, '');
2300
+ if (!formatOptions[key.trim()]) formatOptions[key.trim()] = val;
2301
+ if (val === 'false') formatOptions[key.trim()] = false;
2302
+ if (val === 'true') formatOptions[key.trim()] = true;
2303
+ if (!isNaN(val)) formatOptions[key.trim()] = parseInt(val, 10);
2304
+ });
2305
+ }
2306
+ }
2307
+ return {
2308
+ formatName: formatName,
2309
+ formatOptions: formatOptions
2310
+ };
2311
+ }
2312
+ function createCachedFormatter(fn) {
2313
+ var cache = {};
2314
+ return function invokeFormatter(val, lng, options) {
2315
+ var key = lng + JSON.stringify(options);
2316
+ var formatter = cache[key];
2317
+ if (!formatter) {
2318
+ formatter = fn(lng, options);
2319
+ cache[key] = formatter;
2320
+ }
2321
+ return formatter(val);
2322
+ };
2323
+ }
2324
+ var Formatter = function () {
2325
+ function Formatter() {
2326
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2327
+ _classCallCheck(this, Formatter);
2328
+ this.logger = baseLogger.create('formatter');
2329
+ this.options = options;
2330
+ this.formats = {
2331
+ number: createCachedFormatter(function (lng, opt) {
2332
+ var formatter = new Intl.NumberFormat(lng, _objectSpread$2$1({}, opt));
2333
+ return function (val) {
2334
+ return formatter.format(val);
2335
+ };
2336
+ }),
2337
+ currency: createCachedFormatter(function (lng, opt) {
2338
+ var formatter = new Intl.NumberFormat(lng, _objectSpread$2$1(_objectSpread$2$1({}, opt), {}, {
2339
+ style: 'currency'
2340
+ }));
2341
+ return function (val) {
2342
+ return formatter.format(val);
2343
+ };
2344
+ }),
2345
+ datetime: createCachedFormatter(function (lng, opt) {
2346
+ var formatter = new Intl.DateTimeFormat(lng, _objectSpread$2$1({}, opt));
2347
+ return function (val) {
2348
+ return formatter.format(val);
2349
+ };
2350
+ }),
2351
+ relativetime: createCachedFormatter(function (lng, opt) {
2352
+ var formatter = new Intl.RelativeTimeFormat(lng, _objectSpread$2$1({}, opt));
2353
+ return function (val) {
2354
+ return formatter.format(val, opt.range || 'day');
2355
+ };
2356
+ }),
2357
+ list: createCachedFormatter(function (lng, opt) {
2358
+ var formatter = new Intl.ListFormat(lng, _objectSpread$2$1({}, opt));
2359
+ return function (val) {
2360
+ return formatter.format(val);
2361
+ };
2362
+ })
2363
+ };
2364
+ this.init(options);
2365
+ }
2366
+ _createClass(Formatter, [{
2367
+ key: "init",
2368
+ value: function init(services) {
2369
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
2370
+ interpolation: {}
2371
+ };
2372
+ var iOpts = options.interpolation;
2373
+ this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
2374
+ }
2375
+ }, {
2376
+ key: "add",
2377
+ value: function add(name, fc) {
2378
+ this.formats[name.toLowerCase().trim()] = fc;
2379
+ }
2380
+ }, {
2381
+ key: "addCached",
2382
+ value: function addCached(name, fc) {
2383
+ this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
2384
+ }
2385
+ }, {
2386
+ key: "format",
2387
+ value: function format(value, _format, lng) {
2388
+ var _this = this;
2389
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2390
+ var formats = _format.split(this.formatSeparator);
2391
+ var result = formats.reduce(function (mem, f) {
2392
+ var _parseFormatStr = parseFormatStr(f),
2393
+ formatName = _parseFormatStr.formatName,
2394
+ formatOptions = _parseFormatStr.formatOptions;
2395
+ if (_this.formats[formatName]) {
2396
+ var formatted = mem;
2397
+ try {
2398
+ var valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
2399
+ var l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
2400
+ formatted = _this.formats[formatName](mem, l, _objectSpread$2$1(_objectSpread$2$1(_objectSpread$2$1({}, formatOptions), options), valOptions));
2401
+ } catch (error) {
2402
+ _this.logger.warn(error);
2403
+ }
2404
+ return formatted;
2405
+ } else {
2406
+ _this.logger.warn("there was no format function for ".concat(formatName));
2407
+ }
2408
+ return mem;
2409
+ }, value);
2410
+ return result;
2411
+ }
2412
+ }]);
2413
+ return Formatter;
2414
+ }();
2415
+
2416
+ function ownKeys$1$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2417
+ function _objectSpread$1$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2418
+ function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
2419
+ function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
2420
+ function removePending(q, name) {
2421
+ if (q.pending[name] !== undefined) {
2422
+ delete q.pending[name];
2423
+ q.pendingCount--;
2424
+ }
2425
+ }
2426
+ var Connector = function (_EventEmitter) {
2427
+ _inherits(Connector, _EventEmitter);
2428
+ var _super = _createSuper$1(Connector);
2429
+ function Connector(backend, store, services) {
2430
+ var _this;
2431
+ var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2432
+ _classCallCheck(this, Connector);
2433
+ _this = _super.call(this);
2434
+ if (isIE10) {
2435
+ EventEmitter.call(_assertThisInitialized(_this));
2436
+ }
2437
+ _this.backend = backend;
2438
+ _this.store = store;
2439
+ _this.services = services;
2440
+ _this.languageUtils = services.languageUtils;
2441
+ _this.options = options;
2442
+ _this.logger = baseLogger.create('backendConnector');
2443
+ _this.waitingReads = [];
2444
+ _this.maxParallelReads = options.maxParallelReads || 10;
2445
+ _this.readingCalls = 0;
2446
+ _this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
2447
+ _this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
2448
+ _this.state = {};
2449
+ _this.queue = [];
2450
+ if (_this.backend && _this.backend.init) {
2451
+ _this.backend.init(services, options.backend, options);
2452
+ }
2453
+ return _this;
2454
+ }
2455
+ _createClass(Connector, [{
2456
+ key: "queueLoad",
2457
+ value: function queueLoad(languages, namespaces, options, callback) {
2458
+ var _this2 = this;
2459
+ var toLoad = {};
2460
+ var pending = {};
2461
+ var toLoadLanguages = {};
2462
+ var toLoadNamespaces = {};
2463
+ languages.forEach(function (lng) {
2464
+ var hasAllNamespaces = true;
2465
+ namespaces.forEach(function (ns) {
2466
+ var name = "".concat(lng, "|").concat(ns);
2467
+ if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) {
2468
+ _this2.state[name] = 2;
2469
+ } else if (_this2.state[name] < 0) ; else if (_this2.state[name] === 1) {
2470
+ if (pending[name] === undefined) pending[name] = true;
2471
+ } else {
2472
+ _this2.state[name] = 1;
2473
+ hasAllNamespaces = false;
2474
+ if (pending[name] === undefined) pending[name] = true;
2475
+ if (toLoad[name] === undefined) toLoad[name] = true;
2476
+ if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
2477
+ }
2478
+ });
2479
+ if (!hasAllNamespaces) toLoadLanguages[lng] = true;
2480
+ });
2481
+ if (Object.keys(toLoad).length || Object.keys(pending).length) {
2482
+ this.queue.push({
2483
+ pending: pending,
2484
+ pendingCount: Object.keys(pending).length,
2485
+ loaded: {},
2486
+ errors: [],
2487
+ callback: callback
2488
+ });
2489
+ }
2490
+ return {
2491
+ toLoad: Object.keys(toLoad),
2492
+ pending: Object.keys(pending),
2493
+ toLoadLanguages: Object.keys(toLoadLanguages),
2494
+ toLoadNamespaces: Object.keys(toLoadNamespaces)
2495
+ };
2496
+ }
2497
+ }, {
2498
+ key: "loaded",
2499
+ value: function loaded(name, err, data) {
2500
+ var s = name.split('|');
2501
+ var lng = s[0];
2502
+ var ns = s[1];
2503
+ if (err) this.emit('failedLoading', lng, ns, err);
2504
+ if (data) {
2505
+ this.store.addResourceBundle(lng, ns, data);
2506
+ }
2507
+ this.state[name] = err ? -1 : 2;
2508
+ var loaded = {};
2509
+ this.queue.forEach(function (q) {
2510
+ pushPath(q.loaded, [lng], ns);
2511
+ removePending(q, name);
2512
+ if (err) q.errors.push(err);
2513
+ if (q.pendingCount === 0 && !q.done) {
2514
+ Object.keys(q.loaded).forEach(function (l) {
2515
+ if (!loaded[l]) loaded[l] = {};
2516
+ var loadedKeys = q.loaded[l];
2517
+ if (loadedKeys.length) {
2518
+ loadedKeys.forEach(function (n) {
2519
+ if (loaded[l][n] === undefined) loaded[l][n] = true;
2520
+ });
2521
+ }
2522
+ });
2523
+ q.done = true;
2524
+ if (q.errors.length) {
2525
+ q.callback(q.errors);
2526
+ } else {
2527
+ q.callback();
2528
+ }
2529
+ }
2530
+ });
2531
+ this.emit('loaded', loaded);
2532
+ this.queue = this.queue.filter(function (q) {
2533
+ return !q.done;
2534
+ });
2535
+ }
2536
+ }, {
2537
+ key: "read",
2538
+ value: function read(lng, ns, fcName) {
2539
+ var _this3 = this;
2540
+ var tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
2541
+ var wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : this.retryTimeout;
2542
+ var callback = arguments.length > 5 ? arguments[5] : undefined;
2543
+ if (!lng.length) return callback(null, {});
2544
+ if (this.readingCalls >= this.maxParallelReads) {
2545
+ this.waitingReads.push({
2546
+ lng: lng,
2547
+ ns: ns,
2548
+ fcName: fcName,
2549
+ tried: tried,
2550
+ wait: wait,
2551
+ callback: callback
2552
+ });
2553
+ return;
2554
+ }
2555
+ this.readingCalls++;
2556
+ var resolver = function resolver(err, data) {
2557
+ _this3.readingCalls--;
2558
+ if (_this3.waitingReads.length > 0) {
2559
+ var next = _this3.waitingReads.shift();
2560
+ _this3.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
2561
+ }
2562
+ if (err && data && tried < _this3.maxRetries) {
2563
+ setTimeout(function () {
2564
+ _this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback);
2565
+ }, wait);
2566
+ return;
2567
+ }
2568
+ callback(err, data);
2569
+ };
2570
+ var fc = this.backend[fcName].bind(this.backend);
2571
+ if (fc.length === 2) {
2572
+ try {
2573
+ var r = fc(lng, ns);
2574
+ if (r && typeof r.then === 'function') {
2575
+ r.then(function (data) {
2576
+ return resolver(null, data);
2577
+ })["catch"](resolver);
2578
+ } else {
2579
+ resolver(null, r);
2580
+ }
2581
+ } catch (err) {
2582
+ resolver(err);
2583
+ }
2584
+ return;
2585
+ }
2586
+ return fc(lng, ns, resolver);
2587
+ }
2588
+ }, {
2589
+ key: "prepareLoading",
2590
+ value: function prepareLoading(languages, namespaces) {
2591
+ var _this4 = this;
2592
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2593
+ var callback = arguments.length > 3 ? arguments[3] : undefined;
2594
+ if (!this.backend) {
2595
+ this.logger.warn('No backend was added via i18next.use. Will not load resources.');
2596
+ return callback && callback();
2597
+ }
2598
+ if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);
2599
+ if (typeof namespaces === 'string') namespaces = [namespaces];
2600
+ var toLoad = this.queueLoad(languages, namespaces, options, callback);
2601
+ if (!toLoad.toLoad.length) {
2602
+ if (!toLoad.pending.length) callback();
2603
+ return null;
2604
+ }
2605
+ toLoad.toLoad.forEach(function (name) {
2606
+ _this4.loadOne(name);
2607
+ });
2608
+ }
2609
+ }, {
2610
+ key: "load",
2611
+ value: function load(languages, namespaces, callback) {
2612
+ this.prepareLoading(languages, namespaces, {}, callback);
2613
+ }
2614
+ }, {
2615
+ key: "reload",
2616
+ value: function reload(languages, namespaces, callback) {
2617
+ this.prepareLoading(languages, namespaces, {
2618
+ reload: true
2619
+ }, callback);
2620
+ }
2621
+ }, {
2622
+ key: "loadOne",
2623
+ value: function loadOne(name) {
2624
+ var _this5 = this;
2625
+ var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
2626
+ var s = name.split('|');
2627
+ var lng = s[0];
2628
+ var ns = s[1];
2629
+ this.read(lng, ns, 'read', undefined, undefined, function (err, data) {
2630
+ if (err) _this5.logger.warn("".concat(prefix, "loading namespace ").concat(ns, " for language ").concat(lng, " failed"), err);
2631
+ if (!err && data) _this5.logger.log("".concat(prefix, "loaded namespace ").concat(ns, " for language ").concat(lng), data);
2632
+ _this5.loaded(name, err, data);
2633
+ });
2634
+ }
2635
+ }, {
2636
+ key: "saveMissing",
2637
+ value: function saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
2638
+ var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
2639
+ var clb = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : function () {};
2640
+ if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
2641
+ this.logger.warn("did not save key \"".concat(key, "\" as the namespace \"").concat(namespace, "\" was not yet loaded"), 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
2642
+ return;
2643
+ }
2644
+ if (key === undefined || key === null || key === '') return;
2645
+ if (this.backend && this.backend.create) {
2646
+ var opts = _objectSpread$1$1(_objectSpread$1$1({}, options), {}, {
2647
+ isUpdate: isUpdate
2648
+ });
2649
+ var fc = this.backend.create.bind(this.backend);
2650
+ if (fc.length < 6) {
2651
+ try {
2652
+ var r;
2653
+ if (fc.length === 5) {
2654
+ r = fc(languages, namespace, key, fallbackValue, opts);
2655
+ } else {
2656
+ r = fc(languages, namespace, key, fallbackValue);
2657
+ }
2658
+ if (r && typeof r.then === 'function') {
2659
+ r.then(function (data) {
2660
+ return clb(null, data);
2661
+ })["catch"](clb);
2662
+ } else {
2663
+ clb(null, r);
2664
+ }
2665
+ } catch (err) {
2666
+ clb(err);
2667
+ }
2668
+ } else {
2669
+ fc(languages, namespace, key, fallbackValue, clb, opts);
2670
+ }
2671
+ }
2672
+ if (!languages || !languages[0]) return;
2673
+ this.store.addResource(languages[0], namespace, key, fallbackValue);
2674
+ }
2675
+ }]);
2676
+ return Connector;
2677
+ }(EventEmitter);
2678
+
2679
+ function get() {
2680
+ return {
2681
+ debug: false,
2682
+ initImmediate: true,
2683
+ ns: ['translation'],
2684
+ defaultNS: ['translation'],
2685
+ fallbackLng: ['dev'],
2686
+ fallbackNS: false,
2687
+ supportedLngs: false,
2688
+ nonExplicitSupportedLngs: false,
2689
+ load: 'all',
2690
+ preload: false,
2691
+ simplifyPluralSuffix: true,
2692
+ keySeparator: '.',
2693
+ nsSeparator: ':',
2694
+ pluralSeparator: '_',
2695
+ contextSeparator: '_',
2696
+ partialBundledLanguages: false,
2697
+ saveMissing: false,
2698
+ updateMissing: false,
2699
+ saveMissingTo: 'fallback',
2700
+ saveMissingPlurals: true,
2701
+ missingKeyHandler: false,
2702
+ missingInterpolationHandler: false,
2703
+ postProcess: false,
2704
+ postProcessPassResolved: false,
2705
+ returnNull: true,
2706
+ returnEmptyString: true,
2707
+ returnObjects: false,
2708
+ joinArrays: false,
2709
+ returnedObjectHandler: false,
2710
+ parseMissingKeyHandler: false,
2711
+ appendNamespaceToMissingKey: false,
2712
+ appendNamespaceToCIMode: false,
2713
+ overloadTranslationOptionHandler: function handle(args) {
2714
+ var ret = {};
2715
+ if (_typeof(args[1]) === 'object') ret = args[1];
2716
+ if (typeof args[1] === 'string') ret.defaultValue = args[1];
2717
+ if (typeof args[2] === 'string') ret.tDescription = args[2];
2718
+ if (_typeof(args[2]) === 'object' || _typeof(args[3]) === 'object') {
2719
+ var options = args[3] || args[2];
2720
+ Object.keys(options).forEach(function (key) {
2721
+ ret[key] = options[key];
2722
+ });
2723
+ }
2724
+ return ret;
2725
+ },
2726
+ interpolation: {
2727
+ escapeValue: true,
2728
+ format: function format(value, _format, lng, options) {
2729
+ return value;
2730
+ },
2731
+ prefix: '{{',
2732
+ suffix: '}}',
2733
+ formatSeparator: ',',
2734
+ unescapePrefix: '-',
2735
+ nestingPrefix: '$t(',
2736
+ nestingSuffix: ')',
2737
+ nestingOptionsSeparator: ',',
2738
+ maxReplaces: 1000,
2739
+ skipOnVariables: true
2740
+ }
2741
+ };
2742
+ }
2743
+ function transformOptions(options) {
2744
+ if (typeof options.ns === 'string') options.ns = [options.ns];
2745
+ if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
2746
+ if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS];
2747
+ if (options.supportedLngs && options.supportedLngs.indexOf('cimode') < 0) {
2748
+ options.supportedLngs = options.supportedLngs.concat(['cimode']);
2749
+ }
2750
+ return options;
2751
+ }
2752
+
2753
+ function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2754
+ function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$7(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
2755
+ function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
2756
+ function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
2757
+ function noop() {}
2758
+ function bindMemberFunctions(inst) {
2759
+ var mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
2760
+ mems.forEach(function (mem) {
2761
+ if (typeof inst[mem] === 'function') {
2762
+ inst[mem] = inst[mem].bind(inst);
2763
+ }
2764
+ });
2765
+ }
2766
+ var I18n = function (_EventEmitter) {
2767
+ _inherits(I18n, _EventEmitter);
2768
+ var _super = _createSuper(I18n);
2769
+ function I18n() {
2770
+ var _this;
2771
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2772
+ var callback = arguments.length > 1 ? arguments[1] : undefined;
2773
+ _classCallCheck(this, I18n);
2774
+ _this = _super.call(this);
2775
+ if (isIE10) {
2776
+ EventEmitter.call(_assertThisInitialized(_this));
2777
+ }
2778
+ _this.options = transformOptions(options);
2779
+ _this.services = {};
2780
+ _this.logger = baseLogger;
2781
+ _this.modules = {
2782
+ external: []
2783
+ };
2784
+ bindMemberFunctions(_assertThisInitialized(_this));
2785
+ if (callback && !_this.isInitialized && !options.isClone) {
2786
+ if (!_this.options.initImmediate) {
2787
+ _this.init(options, callback);
2788
+ return _possibleConstructorReturn(_this, _assertThisInitialized(_this));
2789
+ }
2790
+ setTimeout(function () {
2791
+ _this.init(options, callback);
2792
+ }, 0);
2793
+ }
2794
+ return _this;
2795
+ }
2796
+ _createClass(I18n, [{
2797
+ key: "init",
2798
+ value: function init() {
2799
+ var _this2 = this;
2800
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2801
+ var callback = arguments.length > 1 ? arguments[1] : undefined;
2802
+ if (typeof options === 'function') {
2803
+ callback = options;
2804
+ options = {};
2805
+ }
2806
+ if (!options.defaultNS && options.defaultNS !== false && options.ns) {
2807
+ if (typeof options.ns === 'string') {
2808
+ options.defaultNS = options.ns;
2809
+ } else if (options.ns.indexOf('translation') < 0) {
2810
+ options.defaultNS = options.ns[0];
2811
+ }
2812
+ }
2813
+ var defOpts = get();
2814
+ this.options = _objectSpread$7(_objectSpread$7(_objectSpread$7({}, defOpts), this.options), transformOptions(options));
2815
+ if (this.options.compatibilityAPI !== 'v1') {
2816
+ this.options.interpolation = _objectSpread$7(_objectSpread$7({}, defOpts.interpolation), this.options.interpolation);
2817
+ }
2818
+ if (options.keySeparator !== undefined) {
2819
+ this.options.userDefinedKeySeparator = options.keySeparator;
2820
+ }
2821
+ if (options.nsSeparator !== undefined) {
2822
+ this.options.userDefinedNsSeparator = options.nsSeparator;
2823
+ }
2824
+ function createClassOnDemand(ClassOrObject) {
2825
+ if (!ClassOrObject) return null;
2826
+ if (typeof ClassOrObject === 'function') return new ClassOrObject();
2827
+ return ClassOrObject;
2828
+ }
2829
+ if (!this.options.isClone) {
2830
+ if (this.modules.logger) {
2831
+ baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
2832
+ } else {
2833
+ baseLogger.init(null, this.options);
2834
+ }
2835
+ var formatter;
2836
+ if (this.modules.formatter) {
2837
+ formatter = this.modules.formatter;
2838
+ } else if (typeof Intl !== 'undefined') {
2839
+ formatter = Formatter;
2840
+ }
2841
+ var lu = new LanguageUtil(this.options);
2842
+ this.store = new ResourceStore(this.options.resources, this.options);
2843
+ var s = this.services;
2844
+ s.logger = baseLogger;
2845
+ s.resourceStore = this.store;
2846
+ s.languageUtils = lu;
2847
+ s.pluralResolver = new PluralResolver(lu, {
2848
+ prepend: this.options.pluralSeparator,
2849
+ compatibilityJSON: this.options.compatibilityJSON,
2850
+ simplifyPluralSuffix: this.options.simplifyPluralSuffix
2851
+ });
2852
+ if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
2853
+ s.formatter = createClassOnDemand(formatter);
2854
+ s.formatter.init(s, this.options);
2855
+ this.options.interpolation.format = s.formatter.format.bind(s.formatter);
2856
+ }
2857
+ s.interpolator = new Interpolator(this.options);
2858
+ s.utils = {
2859
+ hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
2860
+ };
2861
+ s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
2862
+ s.backendConnector.on('*', function (event) {
2863
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2864
+ args[_key - 1] = arguments[_key];
2865
+ }
2866
+ _this2.emit.apply(_this2, [event].concat(args));
2867
+ });
2868
+ if (this.modules.languageDetector) {
2869
+ s.languageDetector = createClassOnDemand(this.modules.languageDetector);
2870
+ if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
2871
+ }
2872
+ if (this.modules.i18nFormat) {
2873
+ s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
2874
+ if (s.i18nFormat.init) s.i18nFormat.init(this);
2875
+ }
2876
+ this.translator = new Translator(this.services, this.options);
2877
+ this.translator.on('*', function (event) {
2878
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
2879
+ args[_key2 - 1] = arguments[_key2];
2880
+ }
2881
+ _this2.emit.apply(_this2, [event].concat(args));
2882
+ });
2883
+ this.modules.external.forEach(function (m) {
2884
+ if (m.init) m.init(_this2);
2885
+ });
2886
+ }
2887
+ this.format = this.options.interpolation.format;
2888
+ if (!callback) callback = noop;
2889
+ if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
2890
+ var codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2891
+ if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
2892
+ }
2893
+ if (!this.services.languageDetector && !this.options.lng) {
2894
+ this.logger.warn('init: no languageDetector is used and no lng is defined');
2895
+ }
2896
+ var storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
2897
+ storeApi.forEach(function (fcName) {
2898
+ _this2[fcName] = function () {
2899
+ var _this2$store;
2900
+ return (_this2$store = _this2.store)[fcName].apply(_this2$store, arguments);
2901
+ };
2902
+ });
2903
+ var storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
2904
+ storeApiChained.forEach(function (fcName) {
2905
+ _this2[fcName] = function () {
2906
+ var _this2$store2;
2907
+ (_this2$store2 = _this2.store)[fcName].apply(_this2$store2, arguments);
2908
+ return _this2;
2909
+ };
2910
+ });
2911
+ var deferred = defer();
2912
+ var load = function load() {
2913
+ var finish = function finish(err, t) {
2914
+ if (_this2.isInitialized && !_this2.initializedStoreOnce) _this2.logger.warn('init: i18next is already initialized. You should call init just once!');
2915
+ _this2.isInitialized = true;
2916
+ if (!_this2.options.isClone) _this2.logger.log('initialized', _this2.options);
2917
+ _this2.emit('initialized', _this2.options);
2918
+ deferred.resolve(t);
2919
+ callback(err, t);
2920
+ };
2921
+ if (_this2.languages && _this2.options.compatibilityAPI !== 'v1' && !_this2.isInitialized) return finish(null, _this2.t.bind(_this2));
2922
+ _this2.changeLanguage(_this2.options.lng, finish);
2923
+ };
2924
+ if (this.options.resources || !this.options.initImmediate) {
2925
+ load();
2926
+ } else {
2927
+ setTimeout(load, 0);
2928
+ }
2929
+ return deferred;
2930
+ }
2931
+ }, {
2932
+ key: "loadResources",
2933
+ value: function loadResources(language) {
2934
+ var _this3 = this;
2935
+ var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
2936
+ var usedCallback = callback;
2937
+ var usedLng = typeof language === 'string' ? language : this.language;
2938
+ if (typeof language === 'function') usedCallback = language;
2939
+ if (!this.options.resources || this.options.partialBundledLanguages) {
2940
+ if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback();
2941
+ var toLoad = [];
2942
+ var append = function append(lng) {
2943
+ if (!lng) return;
2944
+ var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);
2945
+ lngs.forEach(function (l) {
2946
+ if (toLoad.indexOf(l) < 0) toLoad.push(l);
2947
+ });
2948
+ };
2949
+ if (!usedLng) {
2950
+ var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
2951
+ fallbacks.forEach(function (l) {
2952
+ return append(l);
2953
+ });
2954
+ } else {
2955
+ append(usedLng);
2956
+ }
2957
+ if (this.options.preload) {
2958
+ this.options.preload.forEach(function (l) {
2959
+ return append(l);
2960
+ });
2961
+ }
2962
+ this.services.backendConnector.load(toLoad, this.options.ns, function (e) {
2963
+ if (!e && !_this3.resolvedLanguage && _this3.language) _this3.setResolvedLanguage(_this3.language);
2964
+ usedCallback(e);
2965
+ });
2966
+ } else {
2967
+ usedCallback(null);
2968
+ }
2969
+ }
2970
+ }, {
2971
+ key: "reloadResources",
2972
+ value: function reloadResources(lngs, ns, callback) {
2973
+ var deferred = defer();
2974
+ if (!lngs) lngs = this.languages;
2975
+ if (!ns) ns = this.options.ns;
2976
+ if (!callback) callback = noop;
2977
+ this.services.backendConnector.reload(lngs, ns, function (err) {
2978
+ deferred.resolve();
2979
+ callback(err);
2980
+ });
2981
+ return deferred;
2982
+ }
2983
+ }, {
2984
+ key: "use",
2985
+ value: function use(module) {
2986
+ if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
2987
+ if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
2988
+ if (module.type === 'backend') {
2989
+ this.modules.backend = module;
2990
+ }
2991
+ if (module.type === 'logger' || module.log && module.warn && module.error) {
2992
+ this.modules.logger = module;
2993
+ }
2994
+ if (module.type === 'languageDetector') {
2995
+ this.modules.languageDetector = module;
2996
+ }
2997
+ if (module.type === 'i18nFormat') {
2998
+ this.modules.i18nFormat = module;
2999
+ }
3000
+ if (module.type === 'postProcessor') {
3001
+ postProcessor.addPostProcessor(module);
3002
+ }
3003
+ if (module.type === 'formatter') {
3004
+ this.modules.formatter = module;
3005
+ }
3006
+ if (module.type === '3rdParty') {
3007
+ this.modules.external.push(module);
3008
+ }
3009
+ return this;
3010
+ }
3011
+ }, {
3012
+ key: "setResolvedLanguage",
3013
+ value: function setResolvedLanguage(l) {
3014
+ if (!l || !this.languages) return;
3015
+ if (['cimode', 'dev'].indexOf(l) > -1) return;
3016
+ for (var li = 0; li < this.languages.length; li++) {
3017
+ var lngInLngs = this.languages[li];
3018
+ if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
3019
+ if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
3020
+ this.resolvedLanguage = lngInLngs;
3021
+ break;
3022
+ }
3023
+ }
3024
+ }
3025
+ }, {
3026
+ key: "changeLanguage",
3027
+ value: function changeLanguage(lng, callback) {
3028
+ var _this4 = this;
3029
+ this.isLanguageChangingTo = lng;
3030
+ var deferred = defer();
3031
+ this.emit('languageChanging', lng);
3032
+ var setLngProps = function setLngProps(l) {
3033
+ _this4.language = l;
3034
+ _this4.languages = _this4.services.languageUtils.toResolveHierarchy(l);
3035
+ _this4.resolvedLanguage = undefined;
3036
+ _this4.setResolvedLanguage(l);
3037
+ };
3038
+ var done = function done(err, l) {
3039
+ if (l) {
3040
+ setLngProps(l);
3041
+ _this4.translator.changeLanguage(l);
3042
+ _this4.isLanguageChangingTo = undefined;
3043
+ _this4.emit('languageChanged', l);
3044
+ _this4.logger.log('languageChanged', l);
3045
+ } else {
3046
+ _this4.isLanguageChangingTo = undefined;
3047
+ }
3048
+ deferred.resolve(function () {
3049
+ return _this4.t.apply(_this4, arguments);
3050
+ });
3051
+ if (callback) callback(err, function () {
3052
+ return _this4.t.apply(_this4, arguments);
3053
+ });
3054
+ };
3055
+ var setLng = function setLng(lngs) {
3056
+ if (!lng && !lngs && _this4.services.languageDetector) lngs = [];
3057
+ var l = typeof lngs === 'string' ? lngs : _this4.services.languageUtils.getBestMatchFromCodes(lngs);
3058
+ if (l) {
3059
+ if (!_this4.language) {
3060
+ setLngProps(l);
3061
+ }
3062
+ if (!_this4.translator.language) _this4.translator.changeLanguage(l);
3063
+ if (_this4.services.languageDetector && _this4.services.languageDetector.cacheUserLanguage) _this4.services.languageDetector.cacheUserLanguage(l);
3064
+ }
3065
+ _this4.loadResources(l, function (err) {
3066
+ done(err, l);
3067
+ });
3068
+ };
3069
+ if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
3070
+ setLng(this.services.languageDetector.detect());
3071
+ } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
3072
+ if (this.services.languageDetector.detect.length === 0) {
3073
+ this.services.languageDetector.detect().then(setLng);
3074
+ } else {
3075
+ this.services.languageDetector.detect(setLng);
3076
+ }
3077
+ } else {
3078
+ setLng(lng);
3079
+ }
3080
+ return deferred;
3081
+ }
3082
+ }, {
3083
+ key: "getFixedT",
3084
+ value: function getFixedT(lng, ns, keyPrefix) {
3085
+ var _this5 = this;
3086
+ var fixedT = function fixedT(key, opts) {
3087
+ var options;
3088
+ if (_typeof(opts) !== 'object') {
3089
+ for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
3090
+ rest[_key3 - 2] = arguments[_key3];
3091
+ }
3092
+ options = _this5.options.overloadTranslationOptionHandler([key, opts].concat(rest));
3093
+ } else {
3094
+ options = _objectSpread$7({}, opts);
3095
+ }
3096
+ options.lng = options.lng || fixedT.lng;
3097
+ options.lngs = options.lngs || fixedT.lngs;
3098
+ options.ns = options.ns || fixedT.ns;
3099
+ options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
3100
+ var keySeparator = _this5.options.keySeparator || '.';
3101
+ var resultKey;
3102
+ if (options.keyPrefix && Array.isArray(key)) {
3103
+ resultKey = key.map(function (k) {
3104
+ return "".concat(options.keyPrefix).concat(keySeparator).concat(k);
3105
+ });
3106
+ } else {
3107
+ resultKey = options.keyPrefix ? "".concat(options.keyPrefix).concat(keySeparator).concat(key) : key;
3108
+ }
3109
+ return _this5.t(resultKey, options);
3110
+ };
3111
+ if (typeof lng === 'string') {
3112
+ fixedT.lng = lng;
3113
+ } else {
3114
+ fixedT.lngs = lng;
3115
+ }
3116
+ fixedT.ns = ns;
3117
+ fixedT.keyPrefix = keyPrefix;
3118
+ return fixedT;
3119
+ }
3120
+ }, {
3121
+ key: "t",
3122
+ value: function t() {
3123
+ var _this$translator;
3124
+ return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments);
3125
+ }
3126
+ }, {
3127
+ key: "exists",
3128
+ value: function exists() {
3129
+ var _this$translator2;
3130
+ return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments);
3131
+ }
3132
+ }, {
3133
+ key: "setDefaultNamespace",
3134
+ value: function setDefaultNamespace(ns) {
3135
+ this.options.defaultNS = ns;
3136
+ }
3137
+ }, {
3138
+ key: "hasLoadedNamespace",
3139
+ value: function hasLoadedNamespace(ns) {
3140
+ var _this6 = this;
3141
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3142
+ if (!this.isInitialized) {
3143
+ this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
3144
+ return false;
3145
+ }
3146
+ if (!this.languages || !this.languages.length) {
3147
+ this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
3148
+ return false;
3149
+ }
3150
+ var lng = options.lng || this.resolvedLanguage || this.languages[0];
3151
+ var fallbackLng = this.options ? this.options.fallbackLng : false;
3152
+ var lastLng = this.languages[this.languages.length - 1];
3153
+ if (lng.toLowerCase() === 'cimode') return true;
3154
+ var loadNotPending = function loadNotPending(l, n) {
3155
+ var loadState = _this6.services.backendConnector.state["".concat(l, "|").concat(n)];
3156
+ return loadState === -1 || loadState === 2;
3157
+ };
3158
+ if (options.precheck) {
3159
+ var preResult = options.precheck(this, loadNotPending);
3160
+ if (preResult !== undefined) return preResult;
3161
+ }
3162
+ if (this.hasResourceBundle(lng, ns)) return true;
3163
+ if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
3164
+ if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
3165
+ return false;
3166
+ }
3167
+ }, {
3168
+ key: "loadNamespaces",
3169
+ value: function loadNamespaces(ns, callback) {
3170
+ var _this7 = this;
3171
+ var deferred = defer();
3172
+ if (!this.options.ns) {
3173
+ if (callback) callback();
3174
+ return Promise.resolve();
3175
+ }
3176
+ if (typeof ns === 'string') ns = [ns];
3177
+ ns.forEach(function (n) {
3178
+ if (_this7.options.ns.indexOf(n) < 0) _this7.options.ns.push(n);
3179
+ });
3180
+ this.loadResources(function (err) {
3181
+ deferred.resolve();
3182
+ if (callback) callback(err);
3183
+ });
3184
+ return deferred;
3185
+ }
3186
+ }, {
3187
+ key: "loadLanguages",
3188
+ value: function loadLanguages(lngs, callback) {
3189
+ var deferred = defer();
3190
+ if (typeof lngs === 'string') lngs = [lngs];
3191
+ var preloaded = this.options.preload || [];
3192
+ var newLngs = lngs.filter(function (lng) {
3193
+ return preloaded.indexOf(lng) < 0;
3194
+ });
3195
+ if (!newLngs.length) {
3196
+ if (callback) callback();
3197
+ return Promise.resolve();
3198
+ }
3199
+ this.options.preload = preloaded.concat(newLngs);
3200
+ this.loadResources(function (err) {
3201
+ deferred.resolve();
3202
+ if (callback) callback(err);
3203
+ });
3204
+ return deferred;
3205
+ }
3206
+ }, {
3207
+ key: "dir",
3208
+ value: function dir(lng) {
3209
+ if (!lng) lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
3210
+ if (!lng) return 'rtl';
3211
+ var rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
3212
+ var languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());
3213
+ return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
3214
+ }
3215
+ }, {
3216
+ key: "cloneInstance",
3217
+ value: function cloneInstance() {
3218
+ var _this8 = this;
3219
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3220
+ var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
3221
+ var mergedOptions = _objectSpread$7(_objectSpread$7(_objectSpread$7({}, this.options), options), {
3222
+ isClone: true
3223
+ });
3224
+ var clone = new I18n(mergedOptions);
3225
+ if (options.debug !== undefined || options.prefix !== undefined) {
3226
+ clone.logger = clone.logger.clone(options);
3227
+ }
3228
+ var membersToCopy = ['store', 'services', 'language'];
3229
+ membersToCopy.forEach(function (m) {
3230
+ clone[m] = _this8[m];
3231
+ });
3232
+ clone.services = _objectSpread$7({}, this.services);
3233
+ clone.services.utils = {
3234
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
3235
+ };
3236
+ clone.translator = new Translator(clone.services, clone.options);
3237
+ clone.translator.on('*', function (event) {
3238
+ for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
3239
+ args[_key4 - 1] = arguments[_key4];
3240
+ }
3241
+ clone.emit.apply(clone, [event].concat(args));
3242
+ });
3243
+ clone.init(mergedOptions, callback);
3244
+ clone.translator.options = clone.options;
3245
+ clone.translator.backendConnector.services.utils = {
3246
+ hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
3247
+ };
3248
+ return clone;
3249
+ }
3250
+ }, {
3251
+ key: "toJSON",
3252
+ value: function toJSON() {
3253
+ return {
3254
+ options: this.options,
3255
+ store: this.store,
3256
+ language: this.language,
3257
+ languages: this.languages,
3258
+ resolvedLanguage: this.resolvedLanguage
3259
+ };
3260
+ }
3261
+ }]);
3262
+ return I18n;
3263
+ }(EventEmitter);
3264
+ _defineProperty(I18n, "createInstance", function () {
3265
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3266
+ var callback = arguments.length > 1 ? arguments[1] : undefined;
3267
+ return new I18n(options, callback);
3268
+ });
3269
+ var instance = I18n.createInstance();
3270
+ instance.createInstance = I18n.createInstance;
3271
+
3272
+ instance.createInstance;
3273
+ instance.dir;
3274
+ instance.init;
3275
+ instance.loadResources;
3276
+ instance.reloadResources;
3277
+ instance.use;
3278
+ instance.changeLanguage;
3279
+ instance.getFixedT;
3280
+ instance.t;
3281
+ instance.exists;
3282
+ instance.setDefaultNamespace;
3283
+ instance.hasLoadedNamespace;
3284
+ instance.loadNamespaces;
3285
+ instance.loadLanguages;
3286
+
3287
+ var s3AxiosInstance = axios.create({
3288
+ headers: {
3289
+ "Content-Type": 'video/webm;codecs="vp9"'
3290
+ }
3291
+ });
3292
+ s3AxiosInstance.interceptors.response.use(identity, function (error) {
3293
+ return !axios.isCancel(error) && Promise.reject(error);
3294
+ });
3295
+ var presignedUpload = function presignedUpload(_ref) {
3296
+ var presignedUrl = _ref.presignedUrl,
3297
+ blob = _ref.blob,
3298
+ config = _ref.config;
3299
+ return s3AxiosInstance.put(presignedUrl, blob, config);
3300
+ };
3301
+ var retryablePresignedUpload = buildRetryableApi(presignedUpload, {
3302
+ retryableStatuses: RETRIABLE_ERRORS
3303
+ });
3304
+ var s3Api = {
3305
+ presignedUpload: retryablePresignedUpload
3306
+ };
3307
+
3308
+ var prepareStore$1 = function prepareStore() {
3309
+ return create$3(withImmutableActions(function () {
3310
+ return {
3311
+ status: ""
3312
+ };
3313
+ }));
3314
+ };
3315
+
3316
+ function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
3317
+ function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3318
+ function _classPrivateFieldInitSpec$1(obj, privateMap, value) { _checkPrivateRedeclaration$1(obj, privateMap); privateMap.set(obj, value); }
3319
+ function _checkPrivateRedeclaration$1(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
3320
+ var _recordingId = /*#__PURE__*/new WeakMap();
3321
+ var _uploadId = /*#__PURE__*/new WeakMap();
3322
+ var _unUploadedChunks = /*#__PURE__*/new WeakMap();
3323
+ var _partNumber = /*#__PURE__*/new WeakMap();
3324
+ var _s3PartUploadPromises = /*#__PURE__*/new WeakMap();
3325
+ var _callbacks$1 = /*#__PURE__*/new WeakMap();
3326
+ var _store$1 = /*#__PURE__*/new WeakMap();
3327
+ var _abortController = /*#__PURE__*/new WeakMap();
3328
+ var _pendingS3ChunkUploads = /*#__PURE__*/new WeakMap();
3329
+ var _fireCallbacks$1 = /*#__PURE__*/new WeakMap();
3330
+ var _uploadChunkToS = /*#__PURE__*/new WeakMap();
3331
+ var _getCurrentUnUploadedBlob = /*#__PURE__*/new WeakMap();
3332
+ var MultipartS3Uploader = /*#__PURE__*/function () {
3333
+ function MultipartS3Uploader() {
3334
+ var _this = this;
3335
+ _classCallCheck$1(this, MultipartS3Uploader);
3336
+ _defineProperty$1(this, "MIN_UPLOAD_CHUNK_SIZE", 5 * 1024 * 1024);
3337
+ _classPrivateFieldInitSpec$1(this, _recordingId, {
3338
+ writable: true,
3339
+ value: ""
3340
+ });
3341
+ _classPrivateFieldInitSpec$1(this, _uploadId, {
3342
+ writable: true,
3343
+ value: ""
3344
+ });
3345
+ _classPrivateFieldInitSpec$1(this, _unUploadedChunks, {
3346
+ writable: true,
3347
+ value: []
3348
+ });
3349
+ _classPrivateFieldInitSpec$1(this, _partNumber, {
3350
+ writable: true,
3351
+ value: 1
3352
+ });
3353
+ _classPrivateFieldInitSpec$1(this, _s3PartUploadPromises, {
3354
+ writable: true,
3355
+ value: []
3356
+ });
3357
+ _classPrivateFieldInitSpec$1(this, _callbacks$1, {
3358
+ writable: true,
3359
+ value: {}
3360
+ });
3361
+ _classPrivateFieldInitSpec$1(this, _store$1, {
3362
+ writable: true,
3363
+ value: void 0
3364
+ });
3365
+ _classPrivateFieldInitSpec$1(this, _abortController, {
3366
+ writable: true,
3367
+ value: void 0
3368
+ });
3369
+ _classPrivateFieldInitSpec$1(this, _pendingS3ChunkUploads, {
3370
+ writable: true,
3371
+ value: []
3372
+ });
3373
+ _defineProperty$1(this, "initialize", function (recordingId, uploadId) {
3374
+ _classPrivateFieldSet(_this, _recordingId, recordingId);
3375
+ _classPrivateFieldSet(_this, _uploadId, uploadId);
3376
+ _classPrivateFieldSet(_this, _abortController, new AbortController());
3377
+ });
3378
+ _defineProperty$1(this, "push", function (data) {
3379
+ if (data.size > 0) {
3380
+ _classPrivateFieldGet(_this, _unUploadedChunks).push(data);
3381
+ }
3382
+ logger.info("Current unuploaded data size is ", _classPrivateFieldGet(_this, _getCurrentUnUploadedBlob).call(_this).size / 1024 / 1024, "MB");
3383
+ if (_classPrivateFieldGet(_this, _getCurrentUnUploadedBlob).call(_this).size > _this.MIN_UPLOAD_CHUNK_SIZE) {
3384
+ var uploadChunkToS3Promise = _classPrivateFieldGet(_this, _uploadChunkToS).call(_this, _classPrivateFieldGet(_this, _unUploadedChunks));
3385
+ _classPrivateFieldGet(_this, _pendingS3ChunkUploads).push(uploadChunkToS3Promise);
3386
+ _classPrivateFieldSet(_this, _unUploadedChunks, []);
3387
+ }
3388
+ });
3389
+ _defineProperty$1(this, "completeUpload", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
3390
+ var uploadChunkToS3Promise, resolvedS3PartUploadPromises, parts;
3391
+ return _regeneratorRuntime.wrap(function _callee$(_context) {
3392
+ while (1) switch (_context.prev = _context.next) {
3393
+ case 0:
3394
+ _context.prev = 0;
3395
+ _classPrivateFieldGet(_this, _store$1).setState({
3396
+ status: UPLOAD_STATUS.uploading
3397
+ });
3398
+
3399
+ // Upload last chunk; only if last chunk has data
3400
+ if (_classPrivateFieldGet(_this, _getCurrentUnUploadedBlob).call(_this).size > 0) {
3401
+ uploadChunkToS3Promise = _classPrivateFieldGet(_this, _uploadChunkToS).call(_this, _classPrivateFieldGet(_this, _unUploadedChunks));
3402
+ _classPrivateFieldGet(_this, _pendingS3ChunkUploads).push(uploadChunkToS3Promise);
3403
+ }
3404
+
3405
+ /**
3406
+ * Wait for all the pending uploadToS3Promises.
3407
+ * Else we encounter a race condition where a new request is made for presignedUrl
3408
+ * but at the same time we reach the resolvedS3PartUploadPromises line and await
3409
+ * the s3PartUploadPromises. And the s3PartUploadPromises is resolved before
3410
+ * adding the new presignedUrl part upload to s3PartUploadPromises.
3411
+ * This results in incorrect partNumbers.
3412
+ */
3413
+ _context.next = 5;
3414
+ return Promise.all(_classPrivateFieldGet(_this, _pendingS3ChunkUploads));
3415
+ case 5:
3416
+ _context.next = 7;
3417
+ return Promise.all(_classPrivateFieldGet(_this, _s3PartUploadPromises));
3418
+ case 7:
3419
+ resolvedS3PartUploadPromises = _context.sent;
3420
+ parts = resolvedS3PartUploadPromises.map(function (resolvedResponse) {
3421
+ return {
3422
+ etag: resolvedResponse.headers.etag,
3423
+ partNumber: new URL(resolvedResponse.request.responseURL).searchParams.get("partNumber")
3424
+ };
3425
+ }).toSorted(function (a, b) {
3426
+ return Number(a.partNumber) - Number(b.partNumber);
3427
+ });
3428
+ _context.next = 11;
3429
+ return completeUploadApi.create({
3430
+ recordingId: _classPrivateFieldGet(_this, _recordingId),
3431
+ payload: {
3432
+ parts: parts,
3433
+ uploadId: _classPrivateFieldGet(_this, _uploadId)
3434
+ }
3435
+ });
3436
+ case 11:
3437
+ _context.next = 13;
3438
+ return _classPrivateFieldGet(_this, _store$1).setState({
3439
+ status: UPLOAD_STATUS.completed
3440
+ });
3441
+ case 13:
3442
+ _classPrivateFieldGet(_this, _fireCallbacks$1).call(_this, UPLOAD_EVENT.onComplete);
3443
+ _context.next = 19;
3444
+ break;
3445
+ case 16:
3446
+ _context.prev = 16;
3447
+ _context.t0 = _context["catch"](0);
3448
+ logger.error(_context.t0);
3449
+ case 19:
3450
+ case "end":
3451
+ return _context.stop();
3452
+ }
3453
+ }, _callee, null, [[0, 16]]);
3454
+ })));
3455
+ _defineProperty$1(this, "abortUpload", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
3456
+ return _regeneratorRuntime.wrap(function _callee2$(_context2) {
3457
+ while (1) switch (_context2.prev = _context2.next) {
3458
+ case 0:
3459
+ _context2.prev = 0;
3460
+ _classPrivateFieldGet(_this, _store$1).setState({
3461
+ status: UPLOAD_STATUS.aborting
3462
+ });
3463
+ _classPrivateFieldGet(_this, _abortController).abort();
3464
+ _context2.next = 5;
3465
+ return abortUploadApi.create({
3466
+ recordingId: _classPrivateFieldGet(_this, _recordingId),
3467
+ payload: {
3468
+ uploadId: _classPrivateFieldGet(_this, _uploadId)
3469
+ }
3470
+ });
3471
+ case 5:
3472
+ _classPrivateFieldSet(_this, _unUploadedChunks, []);
3473
+ _classPrivateFieldSet(_this, _partNumber, 1);
3474
+ _classPrivateFieldSet(_this, _s3PartUploadPromises, []);
3475
+ _classPrivateFieldGet(_this, _store$1).setState({
3476
+ status: ""
3477
+ });
3478
+ _classPrivateFieldSet(_this, _abortController, null);
3479
+ _context2.next = 15;
3480
+ break;
3481
+ case 12:
3482
+ _context2.prev = 12;
3483
+ _context2.t0 = _context2["catch"](0);
3484
+ logger.error(_context2.t0);
3485
+ case 15:
3486
+ case "end":
3487
+ return _context2.stop();
3488
+ }
3489
+ }, _callee2, null, [[0, 12]]);
3490
+ })));
3491
+ _defineProperty$1(this, "resetState", function () {
3492
+ _classPrivateFieldSet(_this, _recordingId, "");
3493
+ _classPrivateFieldSet(_this, _uploadId, "");
3494
+ _classPrivateFieldSet(_this, _unUploadedChunks, []);
3495
+ _classPrivateFieldSet(_this, _partNumber, 1);
3496
+ _classPrivateFieldSet(_this, _s3PartUploadPromises, []);
3497
+ _classPrivateFieldSet(_this, _callbacks$1, {});
3498
+ _classPrivateFieldGet(_this, _store$1).setState({
3499
+ status: ""
3500
+ });
3501
+ });
3502
+ _defineProperty$1(this, "addCallback", function (event, callback) {
3503
+ var _classPrivateFieldGet2;
3504
+ var existingCallbacks = (_classPrivateFieldGet2 = _classPrivateFieldGet(_this, _callbacks$1)[event]) !== null && _classPrivateFieldGet2 !== void 0 ? _classPrivateFieldGet2 : [];
3505
+ _classPrivateFieldSet(_this, _callbacks$1, _objectSpread$2(_objectSpread$2({}, _classPrivateFieldGet(_this, _callbacks$1)), {}, _defineProperty$1({}, event, [].concat(_toConsumableArray(existingCallbacks), [callback]))));
3506
+ });
3507
+ _defineProperty$1(this, "removeCallback", function (event, callback) {
3508
+ var _classPrivateFieldGet3;
3509
+ var registeredCallbacks = (_classPrivateFieldGet3 = _classPrivateFieldGet(_this, _callbacks$1)[event]) !== null && _classPrivateFieldGet3 !== void 0 ? _classPrivateFieldGet3 : [];
3510
+ var updatedCallbacks = registeredCallbacks.filter(isNot(callback));
3511
+ _classPrivateFieldSet(_this, _callbacks$1, _objectSpread$2(_objectSpread$2({}, _classPrivateFieldGet(_this, _callbacks$1)), {}, _defineProperty$1({}, event, updatedCallbacks)));
3512
+ });
3513
+ _classPrivateFieldInitSpec$1(this, _fireCallbacks$1, {
3514
+ writable: true,
3515
+ value: function value(event) {
3516
+ var _classPrivateFieldGet4;
3517
+ var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
3518
+ (_classPrivateFieldGet4 = _classPrivateFieldGet(_this, _callbacks$1)[event]) === null || _classPrivateFieldGet4 === void 0 ? void 0 : _classPrivateFieldGet4.forEach(function (callback) {
3519
+ callback.apply(void 0, _toConsumableArray(args));
3520
+ });
3521
+ }
3522
+ });
3523
+ _classPrivateFieldInitSpec$1(this, _uploadChunkToS, {
3524
+ writable: true,
3525
+ value: function () {
3526
+ var _value = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(chunks) {
3527
+ var _this$partNumber, _this$partNumber2, _yield$partPresignedU, presignedUrl, s3PartUploadPromise;
3528
+ return _regeneratorRuntime.wrap(function _callee3$(_context3) {
3529
+ while (1) switch (_context3.prev = _context3.next) {
3530
+ case 0:
3531
+ logger.info("Part ready to be uploaded: ", _classPrivateFieldGet(_this, _partNumber));
3532
+ _context3.prev = 1;
3533
+ _context3.next = 4;
3534
+ return partPresignedUrlApi.create({
3535
+ recordingId: _classPrivateFieldGet(_this, _recordingId),
3536
+ payload: {
3537
+ partNumber: (_classPrivateFieldSet(_this, _partNumber, (_this$partNumber = _classPrivateFieldGet(_this, _partNumber), _this$partNumber2 = _this$partNumber++, _this$partNumber)), _this$partNumber2),
3538
+ uploadId: _classPrivateFieldGet(_this, _uploadId)
3539
+ }
3540
+ });
3541
+ case 4:
3542
+ _yield$partPresignedU = _context3.sent;
3543
+ presignedUrl = _yield$partPresignedU.presignedUrl;
3544
+ s3PartUploadPromise = s3Api.presignedUpload({
3545
+ presignedUrl: presignedUrl,
3546
+ blob: new Blob(chunks, {
3547
+ type: 'video/webm;codecs="vp9"'
3548
+ }),
3549
+ config: {
3550
+ includeMetadataInResponse: true,
3551
+ signal: _classPrivateFieldGet(_this, _abortController).signal
3552
+ }
3553
+ });
3554
+ _classPrivateFieldGet(_this, _s3PartUploadPromises).push(s3PartUploadPromise);
3555
+ _context3.next = 13;
3556
+ break;
3557
+ case 10:
3558
+ _context3.prev = 10;
3559
+ _context3.t0 = _context3["catch"](1);
3560
+ if (!axios.isCancel(_context3.t0)) logger.error(_context3.t0);
3561
+ case 13:
3562
+ return _context3.abrupt("return");
3563
+ case 14:
3564
+ case "end":
3565
+ return _context3.stop();
3566
+ }
3567
+ }, _callee3, null, [[1, 10]]);
3568
+ }));
3569
+ function value(_x) {
3570
+ return _value.apply(this, arguments);
3571
+ }
3572
+ return value;
3573
+ }()
3574
+ });
3575
+ _classPrivateFieldInitSpec$1(this, _getCurrentUnUploadedBlob, {
3576
+ writable: true,
3577
+ value: function value() {
3578
+ return new Blob(_classPrivateFieldGet(_this, _unUploadedChunks), {
3579
+ type: 'video/webm;codecs="vp9"'
3580
+ });
3581
+ }
3582
+ });
3583
+ _classPrivateFieldSet(this, _store$1, prepareStore$1());
3584
+ }
3585
+
3586
+ /** @type {import("neetocommons/react-utils").ZustandStoreHook} */
3587
+ _createClass$1(MultipartS3Uploader, [{
3588
+ key: "useMultipartS3UploadStore",
3589
+ get: function get() {
3590
+ return _classPrivateFieldGet(this, _store$1);
3591
+ }
3592
+ }]);
3593
+ return MultipartS3Uploader;
3594
+ }();
3595
+ var multipartS3Uploader = new MultipartS3Uploader();
3596
+
3597
+ // https://www.w3.org/TR/screen-capture/#displaycapturesurfacetype
3598
+ var DISPLAY_SURFACE = {
3599
+ monitor: "monitor",
3600
+ window: "window",
3601
+ browser: "browser"
3602
+ };
3603
+
3604
+ function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
3605
+ function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3606
+ var initialState = {
3607
+ status: SCREEN_RECORDER_STATUS.idle,
3608
+ error: "",
3609
+ elapsedTime: 0,
3610
+ countdownTimeLeft: 3
3611
+ };
3612
+ var prepareStore = function prepareStore() {
3613
+ return create$3(withImmutableActions(function (set) {
3614
+ return _objectSpread$1(_objectSpread$1({}, initialState), {}, {
3615
+ resetState: function resetState() {
3616
+ return set(initialState);
3617
+ }
3618
+ });
3619
+ }));
3620
+ };
3621
+
3622
+ var getUnSupportedConstraints = function getUnSupportedConstraints(mediaType) {
3623
+ var supportedMediaConstraints = navigator.mediaDevices.getSupportedConstraints();
3624
+ return Object.keys(mediaType).filter(function (constraint) {
3625
+ return !supportedMediaConstraints[constraint];
3626
+ });
3627
+ };
3628
+ var checkConstraints = function checkConstraints() {
3629
+ if (isNil(navigator.mediaDevices)) {
3630
+ return;
3631
+ }
3632
+ for (var _len = arguments.length, mediaTypes = new Array(_len), _key = 0; _key < _len; _key++) {
3633
+ mediaTypes[_key] = arguments[_key];
3634
+ }
3635
+ var unSupportedConstraints = mediaTypes.filter(function (mediaType) {
3636
+ return _typeof$2(mediaType) === "object";
3637
+ }).map(getUnSupportedConstraints).flat();
3638
+ if (isNotEmpty(unSupportedConstraints)) {
3639
+ // eslint-disable-next-line no-console
3640
+ console.error("The constraints ".concat(unSupportedConstraints.join(","), " doesn't support on this browser."));
3641
+ }
3642
+ };
3643
+ var isStreamEnded = function isStreamEnded(mediaStream) {
3644
+ return existsBy({
3645
+ readyState: "ended"
3646
+ }, mediaStream.getTracks());
3647
+ };
3648
+
3649
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
3650
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
3651
+ function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
3652
+ function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
3653
+ var _audio = /*#__PURE__*/new WeakMap();
3654
+ var _video = /*#__PURE__*/new WeakMap();
3655
+ var _mediaRecorder = /*#__PURE__*/new WeakMap();
3656
+ var _mediaStream = /*#__PURE__*/new WeakMap();
3657
+ var _store = /*#__PURE__*/new WeakMap();
3658
+ var _mediaChunks = /*#__PURE__*/new WeakMap();
3659
+ var _callbacks = /*#__PURE__*/new WeakMap();
3660
+ var _lastTimerUpdatedAt = /*#__PURE__*/new WeakMap();
3661
+ var _timerId = /*#__PURE__*/new WeakMap();
3662
+ var _countdownTimerId = /*#__PURE__*/new WeakMap();
3663
+ var _checkCompatibility = /*#__PURE__*/new WeakMap();
3664
+ var _acquireMediaStream = /*#__PURE__*/new WeakMap();
3665
+ var _fireCallbacks = /*#__PURE__*/new WeakMap();
3666
+ var _onRecordingStart = /*#__PURE__*/new WeakMap();
3667
+ var _onRecordingActive = /*#__PURE__*/new WeakMap();
3668
+ var _onRecordingStop = /*#__PURE__*/new WeakMap();
3669
+ var _countdownAndStartRecording = /*#__PURE__*/new WeakMap();
3670
+ var _startTimer = /*#__PURE__*/new WeakMap();
3671
+ var _stopTimer = /*#__PURE__*/new WeakMap();
3672
+ var ScreenRecorder = /*#__PURE__*/function () {
3673
+ function ScreenRecorder(audio, video) {
3674
+ var _this = this;
3675
+ _classCallCheck$1(this, ScreenRecorder);
3676
+ _classPrivateFieldInitSpec(this, _audio, {
3677
+ writable: true,
3678
+ value: void 0
3679
+ });
3680
+ _classPrivateFieldInitSpec(this, _video, {
3681
+ writable: true,
3682
+ value: void 0
3683
+ });
3684
+ _classPrivateFieldInitSpec(this, _mediaRecorder, {
3685
+ writable: true,
3686
+ value: void 0
3687
+ });
3688
+ _classPrivateFieldInitSpec(this, _mediaStream, {
3689
+ writable: true,
3690
+ value: void 0
3691
+ });
3692
+ _classPrivateFieldInitSpec(this, _store, {
3693
+ writable: true,
3694
+ value: void 0
3695
+ });
3696
+ _classPrivateFieldInitSpec(this, _mediaChunks, {
3697
+ writable: true,
3698
+ value: []
3699
+ });
3700
+ _classPrivateFieldInitSpec(this, _callbacks, {
3701
+ writable: true,
3702
+ value: {}
3703
+ });
3704
+ _classPrivateFieldInitSpec(this, _lastTimerUpdatedAt, {
3705
+ writable: true,
3706
+ value: 0
3707
+ });
3708
+ _classPrivateFieldInitSpec(this, _timerId, {
3709
+ writable: true,
3710
+ value: void 0
3711
+ });
3712
+ _classPrivateFieldInitSpec(this, _countdownTimerId, {
3713
+ writable: true,
3714
+ value: void 0
3715
+ });
3716
+ _defineProperty$1(this, "getPreviewStream", function () {
3717
+ return new MediaStream(_classPrivateFieldGet(_this, _mediaStream).getVideoTracks());
3718
+ });
3719
+ _defineProperty$1(this, "getMediaBlobUrl", function () {
3720
+ var blob = new Blob(_classPrivateFieldGet(_this, _mediaChunks), {
3721
+ type: 'video/webm;codecs="vp9"'
3722
+ });
3723
+
3724
+ // TODO: Revoke the object url
3725
+ return URL.createObjectURL(blob);
3726
+ });
3727
+ _defineProperty$1(this, "getWebmMediaBlob", function () {
3728
+ return new Blob(_classPrivateFieldGet(_this, _mediaChunks), {
3729
+ type: 'video/webm;codecs="vp9"'
3730
+ });
3731
+ });
3732
+ _defineProperty$1(this, "addCallback", function (event, callback) {
3733
+ var _classPrivateFieldGet2;
3734
+ var existingCallbacks = (_classPrivateFieldGet2 = _classPrivateFieldGet(_this, _callbacks)[event]) !== null && _classPrivateFieldGet2 !== void 0 ? _classPrivateFieldGet2 : [];
3735
+ _classPrivateFieldSet(_this, _callbacks, _objectSpread(_objectSpread({}, _classPrivateFieldGet(_this, _callbacks)), {}, _defineProperty$1({}, event, [].concat(_toConsumableArray(existingCallbacks), [callback]))));
3736
+ });
3737
+ _defineProperty$1(this, "removeCallback", function (event, callback) {
3738
+ var _classPrivateFieldGet3;
3739
+ var registeredCallbacks = (_classPrivateFieldGet3 = _classPrivateFieldGet(_this, _callbacks)[event]) !== null && _classPrivateFieldGet3 !== void 0 ? _classPrivateFieldGet3 : [];
3740
+ var updatedCallbacks = registeredCallbacks.filter(isNot(callback));
3741
+ _classPrivateFieldSet(_this, _callbacks, _objectSpread(_objectSpread({}, _classPrivateFieldGet(_this, _callbacks)), {}, _defineProperty$1({}, event, updatedCallbacks)));
3742
+ });
3743
+ _defineProperty$1(this, "removeAllCallbacksByEvent", function (event) {
3744
+ delete _classPrivateFieldGet(_this, _callbacks)[event];
3745
+ });
3746
+ _defineProperty$1(this, "startRecording", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
3747
+ return _regeneratorRuntime.wrap(function _callee$(_context) {
3748
+ while (1) switch (_context.prev = _context.next) {
3749
+ case 0:
3750
+ _classPrivateFieldGet(_this, _store).setState(pick(["error"], initialState));
3751
+ if (_classPrivateFieldGet(_this, _mediaStream)) {
3752
+ _context.next = 4;
3753
+ break;
3754
+ }
3755
+ _context.next = 4;
3756
+ return _classPrivateFieldGet(_this, _acquireMediaStream).call(_this);
3757
+ case 4:
3758
+ if (!(_classPrivateFieldGet(_this, _mediaStream) && isStreamEnded(_classPrivateFieldGet(_this, _mediaStream)))) {
3759
+ _context.next = 7;
3760
+ break;
3761
+ }
3762
+ _context.next = 7;
3763
+ return _classPrivateFieldGet(_this, _acquireMediaStream).call(_this);
3764
+ case 7:
3765
+ if (!(!_classPrivateFieldGet(_this, _mediaStream) || isStreamEnded(_classPrivateFieldGet(_this, _mediaStream)))) {
3766
+ _context.next = 9;
3767
+ break;
3768
+ }
3769
+ return _context.abrupt("return");
3770
+ case 9:
3771
+ _classPrivateFieldSet(_this, _mediaChunks, []);
3772
+ _classPrivateFieldSet(_this, _mediaRecorder, new MediaRecorder(_classPrivateFieldGet(_this, _mediaStream)));
3773
+ _classPrivateFieldGet(_this, _mediaRecorder).ondataavailable = _classPrivateFieldGet(_this, _onRecordingActive);
3774
+ _classPrivateFieldGet(_this, _mediaRecorder).onstart = _classPrivateFieldGet(_this, _onRecordingStart);
3775
+ _classPrivateFieldGet(_this, _mediaRecorder).onstop = _classPrivateFieldGet(_this, _onRecordingStop);
3776
+ _classPrivateFieldGet(_this, _mediaRecorder).onerror = function () {
3777
+ _classPrivateFieldGet(_this, _store).setState({
3778
+ status: SCREEN_RECORDER_STATUS.idle,
3779
+ error: SCREEN_RECORDER_ERROR.NoRecorder
3780
+ });
3781
+ };
3782
+ _classPrivateFieldGet(_this, _countdownAndStartRecording).call(_this);
3783
+ case 16:
3784
+ case "end":
3785
+ return _context.stop();
3786
+ }
3787
+ }, _callee);
3788
+ })));
3789
+ _defineProperty$1(this, "stopRecording", function () {
3790
+ var _classPrivateFieldGet4;
3791
+ if (((_classPrivateFieldGet4 = _classPrivateFieldGet(_this, _mediaRecorder)) === null || _classPrivateFieldGet4 === void 0 ? void 0 : _classPrivateFieldGet4.state) === "inactive") {
3792
+ // When recording is stopped from the 'Stop Sharing' overlay
3793
+ // before it even starts, i.e during the countdown.
3794
+ clearInterval(_classPrivateFieldGet(_this, _countdownTimerId));
3795
+ _classPrivateFieldGet(_this, _mediaStream).getTracks().forEach(function (track) {
3796
+ return track.stop();
3797
+ });
3798
+ _classPrivateFieldGet(_this, _fireCallbacks).call(_this, SCREEN_RECORDER_EVENT.onDiscardDuringCountdown);
3799
+ return;
3800
+ }
3801
+ _classPrivateFieldGet(_this, _store).setState({
3802
+ status: SCREEN_RECORDER_STATUS.stopping
3803
+ });
3804
+ _classPrivateFieldGet(_this, _mediaRecorder).stop();
3805
+ _classPrivateFieldGet(_this, _mediaStream) && _classPrivateFieldGet(_this, _mediaStream).getTracks().forEach(function (track) {
3806
+ return track.stop();
3807
+ });
3808
+ _classPrivateFieldGet(_this, _stopTimer).call(_this);
3809
+ });
3810
+ _defineProperty$1(this, "pauseRecording", function () {
3811
+ var _classPrivateFieldGet5;
3812
+ if (((_classPrivateFieldGet5 = _classPrivateFieldGet(_this, _mediaRecorder)) === null || _classPrivateFieldGet5 === void 0 ? void 0 : _classPrivateFieldGet5.state) === "recording") {
3813
+ _classPrivateFieldGet(_this, _store).setState({
3814
+ status: SCREEN_RECORDER_STATUS.paused
3815
+ });
3816
+ _classPrivateFieldGet(_this, _mediaRecorder).pause();
3817
+ }
3818
+ _classPrivateFieldGet(_this, _stopTimer).call(_this);
3819
+ });
3820
+ _defineProperty$1(this, "resumeRecording", function () {
3821
+ var _classPrivateFieldGet6;
3822
+ if (((_classPrivateFieldGet6 = _classPrivateFieldGet(_this, _mediaRecorder)) === null || _classPrivateFieldGet6 === void 0 ? void 0 : _classPrivateFieldGet6.state) === "paused") {
3823
+ _classPrivateFieldGet(_this, _store).setState({
3824
+ status: SCREEN_RECORDER_STATUS.recording
3825
+ });
3826
+ _classPrivateFieldGet(_this, _mediaRecorder).resume();
3827
+ }
3828
+ _classPrivateFieldGet(_this, _startTimer).call(_this);
3829
+ });
3830
+ _defineProperty$1(this, "discardRecording", function () {
3831
+ var _classPrivateFieldGet7;
3832
+ if (((_classPrivateFieldGet7 = _classPrivateFieldGet(_this, _mediaRecorder)) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.state) === "inactive") return;
3833
+ _classPrivateFieldGet(_this, _store).setState({
3834
+ status: SCREEN_RECORDER_STATUS.stopping
3835
+ });
3836
+ _this.removeAllCallbacksByEvent(SCREEN_RECORDER_EVENT.onStop);
3837
+ _classPrivateFieldGet(_this, _mediaRecorder).stop();
3838
+ _classPrivateFieldGet(_this, _mediaStream) && _classPrivateFieldGet(_this, _mediaStream).getTracks().forEach(function (track) {
3839
+ return track.stop();
3840
+ });
3841
+ clearInterval(_classPrivateFieldGet(_this, _timerId));
3842
+ _classPrivateFieldGet(_this, _store).setState(pick(["elapsedTime"], initialState));
3843
+ _classPrivateFieldSet(_this, _mediaChunks, []);
3844
+ _classPrivateFieldGet(_this, _fireCallbacks).call(_this, SCREEN_RECORDER_EVENT.onDiscard);
3845
+ });
3846
+ _defineProperty$1(this, "restartRecording", function () {
3847
+ _classPrivateFieldGet(_this, _store).setState({
3848
+ status: SCREEN_RECORDER_STATUS.stopping
3849
+ });
3850
+ _this.removeAllCallbacksByEvent(SCREEN_RECORDER_EVENT.onStop);
3851
+ _classPrivateFieldGet(_this, _mediaRecorder).stop();
3852
+ clearInterval(_classPrivateFieldGet(_this, _timerId));
3853
+ _classPrivateFieldGet(_this, _store).setState(pick(["elapsedTime", "countdownTimeLeft"], initialState));
3854
+ _classPrivateFieldSet(_this, _mediaChunks, []);
3855
+ _classPrivateFieldGet(_this, _fireCallbacks).call(_this, SCREEN_RECORDER_EVENT.onRestart);
3856
+ _classPrivateFieldGet(_this, _countdownAndStartRecording).call(_this);
3857
+ });
3858
+ _defineProperty$1(this, "resetState", function () {
3859
+ _classPrivateFieldSet(_this, _mediaChunks, []);
3860
+ _classPrivateFieldSet(_this, _callbacks, {});
3861
+ clearInterval(_classPrivateFieldGet(_this, _timerId));
3862
+ clearInterval(_classPrivateFieldGet(_this, _countdownTimerId));
3863
+ _classPrivateFieldGet(_this, _store).getState().resetState();
3864
+ });
3865
+ _defineProperty$1(this, "revokePermissions", function () {
3866
+ if (!_classPrivateFieldGet(_this, _mediaRecorder)) return;
3867
+ _classPrivateFieldGet(_this, _mediaRecorder).onstop = null;
3868
+ _classPrivateFieldGet(_this, _mediaStream).getTracks().forEach(function (track) {
3869
+ return track.stop();
3870
+ });
3871
+ });
3872
+ _classPrivateFieldInitSpec(this, _checkCompatibility, {
3873
+ writable: true,
3874
+ value: function value() {
3875
+ var _navigator$mediaDevic;
3876
+ if (!((_navigator$mediaDevic = navigator.mediaDevices) !== null && _navigator$mediaDevic !== void 0 && _navigator$mediaDevic.getDisplayMedia)) {
3877
+ _classPrivateFieldGet(_this, _store).setState({
3878
+ error: SCREEN_RECORDER_ERROR.UnSupportedBrowser
3879
+ });
3880
+ }
3881
+ checkConstraints(_classPrivateFieldGet(_this, _audio), _classPrivateFieldGet(_this, _video));
3882
+ }
3883
+ });
3884
+ _classPrivateFieldInitSpec(this, _acquireMediaStream, {
3885
+ writable: true,
3886
+ value: function () {
3887
+ var _value = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
3888
+ var stream, audioStream;
3889
+ return _regeneratorRuntime.wrap(function _callee2$(_context2) {
3890
+ while (1) switch (_context2.prev = _context2.next) {
3891
+ case 0:
3892
+ _classPrivateFieldGet(_this, _store).setState({
3893
+ status: SCREEN_RECORDER_STATUS.acquiring_media
3894
+ });
3895
+ _context2.prev = 1;
3896
+ _context2.next = 4;
3897
+ return window.navigator.mediaDevices.getDisplayMedia({
3898
+ video: _classPrivateFieldGet(_this, _video) || true
3899
+ });
3900
+ case 4:
3901
+ stream = _context2.sent;
3902
+ // Event triggered when the user clicks on the stop sharing overlay button
3903
+ stream.getVideoTracks()[0].addEventListener("ended", function () {
3904
+ _this.stopRecording();
3905
+ });
3906
+ if (!_classPrivateFieldGet(_this, _audio)) {
3907
+ _context2.next = 11;
3908
+ break;
3909
+ }
3910
+ _context2.next = 9;
3911
+ return window.navigator.mediaDevices.getUserMedia({
3912
+ audio: _classPrivateFieldGet(_this, _audio)
3913
+ });
3914
+ case 9:
3915
+ audioStream = _context2.sent;
3916
+ audioStream.getAudioTracks().forEach(function (audioTrack) {
3917
+ return stream.addTrack(audioTrack);
3918
+ });
3919
+ case 11:
3920
+ _classPrivateFieldSet(_this, _mediaStream, stream);
3921
+ _classPrivateFieldGet(_this, _store).setState({
3922
+ status: SCREEN_RECORDER_STATUS.media_acquired
3923
+ });
3924
+ _context2.next = 18;
3925
+ break;
3926
+ case 15:
3927
+ _context2.prev = 15;
3928
+ _context2.t0 = _context2["catch"](1);
3929
+ _classPrivateFieldGet(_this, _store).setState({
3930
+ error: SCREEN_RECORDER_ERROR[_context2.t0.name],
3931
+ status: SCREEN_RECORDER_STATUS.idle
3932
+ });
3933
+ case 18:
3934
+ case "end":
3935
+ return _context2.stop();
3936
+ }
3937
+ }, _callee2, null, [[1, 15]]);
3938
+ }));
3939
+ function value() {
3940
+ return _value.apply(this, arguments);
3941
+ }
3942
+ return value;
3943
+ }()
3944
+ });
3945
+ _classPrivateFieldInitSpec(this, _fireCallbacks, {
3946
+ writable: true,
3947
+ value: function value(event) {
3948
+ var _classPrivateFieldGet8;
3949
+ var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
3950
+ (_classPrivateFieldGet8 = _classPrivateFieldGet(_this, _callbacks)[event]) === null || _classPrivateFieldGet8 === void 0 ? void 0 : _classPrivateFieldGet8.forEach(function (callback) {
3951
+ callback.apply(void 0, _toConsumableArray(args));
3952
+ });
3953
+ }
3954
+ });
3955
+ _classPrivateFieldInitSpec(this, _onRecordingStart, {
3956
+ writable: true,
3957
+ value: function value() {
3958
+ _classPrivateFieldGet(_this, _fireCallbacks).call(_this, SCREEN_RECORDER_EVENT.onStart);
3959
+ }
3960
+ });
3961
+ _classPrivateFieldInitSpec(this, _onRecordingActive, {
3962
+ writable: true,
3963
+ value: function value(_ref2) {
3964
+ var data = _ref2.data;
3965
+ if (data.size <= 0) return;
3966
+ _classPrivateFieldGet(_this, _mediaChunks).push(data);
3967
+ _classPrivateFieldGet(_this, _fireCallbacks).call(_this, SCREEN_RECORDER_EVENT.onDataAvailable, [data]);
3968
+ }
3969
+ });
3970
+ _classPrivateFieldInitSpec(this, _onRecordingStop, {
3971
+ writable: true,
3972
+ value: function value() {
3973
+ _classPrivateFieldGet(_this, _store).setState({
3974
+ status: SCREEN_RECORDER_STATUS.stopped
3975
+ });
3976
+ _classPrivateFieldGet(_this, _fireCallbacks).call(_this, SCREEN_RECORDER_EVENT.onStop);
3977
+
3978
+ // If mediaStream is active after stopping mediaRecorder, then that means that
3979
+ // we are restarting and not stopping.
3980
+ if (_classPrivateFieldGet(_this, _mediaStream).active) {
3981
+ _classPrivateFieldGet(_this, _store).setState({
3982
+ status: SCREEN_RECORDER_STATUS.restarting
3983
+ });
3984
+ }
3985
+ }
3986
+ });
3987
+ _classPrivateFieldInitSpec(this, _countdownAndStartRecording, {
3988
+ writable: true,
3989
+ value: function value() {
3990
+ _classPrivateFieldSet(_this, _countdownTimerId, setInterval(function () {
3991
+ _classPrivateFieldGet(_this, _store).setState(function (_ref3) {
3992
+ var countdownTimeLeft = _ref3.countdownTimeLeft;
3993
+ if (countdownTimeLeft - ONE_SECOND > 0) {
3994
+ return {
3995
+ countdownTimeLeft: countdownTimeLeft - ONE_SECOND
3996
+ };
3997
+ }
3998
+ _classPrivateFieldGet(_this, _store).setState({
3999
+ status: SCREEN_RECORDER_STATUS.recording
4000
+ });
4001
+ _classPrivateFieldGet(_this, _mediaRecorder).start(5000);
4002
+ _classPrivateFieldGet(_this, _startTimer).call(_this);
4003
+ clearInterval(_classPrivateFieldGet(_this, _countdownTimerId));
4004
+ return {
4005
+ countdownTimeLeft: 0
4006
+ };
4007
+ });
4008
+ }, ONE_SECOND_IN_MILLISECONDS));
4009
+ }
4010
+ });
4011
+ _classPrivateFieldInitSpec(this, _startTimer, {
4012
+ writable: true,
4013
+ value: function value() {
4014
+ _classPrivateFieldSet(_this, _lastTimerUpdatedAt, Date.now());
4015
+ _classPrivateFieldSet(_this, _timerId, setInterval(function () {
4016
+ _classPrivateFieldGet(_this, _store).setState(function (_ref4) {
4017
+ var elapsedTime = _ref4.elapsedTime;
4018
+ var now = Date.now();
4019
+ var newElapsedTime = elapsedTime + (now - _classPrivateFieldGet(_this, _lastTimerUpdatedAt));
4020
+ _classPrivateFieldSet(_this, _lastTimerUpdatedAt, now);
4021
+ return {
4022
+ elapsedTime: newElapsedTime
4023
+ };
4024
+ });
4025
+ }, ONE_SECOND_IN_MILLISECONDS));
4026
+ }
4027
+ });
4028
+ _classPrivateFieldInitSpec(this, _stopTimer, {
4029
+ writable: true,
4030
+ value: function value() {
4031
+ clearInterval(_classPrivateFieldGet(_this, _timerId));
4032
+ var newElapsedTime = _classPrivateFieldGet(_this, _store).getState().elapsedTime + (Date.now() - _classPrivateFieldGet(_this, _lastTimerUpdatedAt));
4033
+ _classPrivateFieldGet(_this, _store).setState({
4034
+ elapsedTime: newElapsedTime
4035
+ });
4036
+ }
4037
+ });
4038
+ _classPrivateFieldSet(this, _audio, audio);
4039
+ _classPrivateFieldSet(this, _video, video);
4040
+ _classPrivateFieldSet(this, _store, prepareStore());
4041
+ _classPrivateFieldGet(this, _store).setState({
4042
+ status: SCREEN_RECORDER_STATUS.idle
4043
+ });
4044
+ _classPrivateFieldGet(this, _checkCompatibility).call(this);
4045
+ }
4046
+
4047
+ /** @type {import("neetocommons/react-utils").ZustandStoreHook} */
4048
+ _createClass$1(ScreenRecorder, [{
4049
+ key: "useRecorderStore",
4050
+ get: function get() {
4051
+ return _classPrivateFieldGet(this, _store);
4052
+ }
4053
+ }]);
4054
+ return ScreenRecorder;
4055
+ }();
4056
+ var screenRecorder = new ScreenRecorder(true, {
4057
+ displaySurface: DISPLAY_SURFACE.monitor
4058
+ });
4059
+
4060
+ export { multipartS3Uploader, screenRecorder };
4061
+ //# sourceMappingURL=core.js.map