UNPKG

44.7 kBJavaScriptView Raw
1import { __decorate } from 'tslib';
2import { applyMagic } from 'js-magic';
3import axios from 'axios';
4import { CatchAll } from '@magna_shogun/catch-decorator';
5
6function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
7 try {
8 var info = gen[key](arg);
9 var value = info.value;
10 } catch (error) {
11 reject(error);
12 return;
13 }
14
15 if (info.done) {
16 resolve(value);
17 } else {
18 Promise.resolve(value).then(_next, _throw);
19 }
20}
21
22function _asyncToGenerator(fn) {
23 return function () {
24 var self = this,
25 args = arguments;
26 return new Promise(function (resolve, reject) {
27 var gen = fn.apply(self, args);
28
29 function _next(value) {
30 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
31 }
32
33 function _throw(err) {
34 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
35 }
36
37 _next(undefined);
38 });
39 };
40}
41
42function _extends() {
43 _extends = Object.assign || function (target) {
44 for (var i = 1; i < arguments.length; i++) {
45 var source = arguments[i];
46
47 for (var key in source) {
48 if (Object.prototype.hasOwnProperty.call(source, key)) {
49 target[key] = source[key];
50 }
51 }
52 }
53
54 return target;
55 };
56
57 return _extends.apply(this, arguments);
58}
59
60function _objectWithoutPropertiesLoose(source, excluded) {
61 if (source == null) return {};
62 var target = {};
63 var sourceKeys = Object.keys(source);
64 var key, i;
65
66 for (i = 0; i < sourceKeys.length; i++) {
67 key = sourceKeys[i];
68 if (excluded.indexOf(key) >= 0) continue;
69 target[key] = source[key];
70 }
71
72 return target;
73}
74
75function createCommonjsModule(fn, module) {
76 return module = { exports: {} }, fn(module, module.exports), module.exports;
77}
78
79var runtime_1 = createCommonjsModule(function (module) {
80/**
81 * Copyright (c) 2014-present, Facebook, Inc.
82 *
83 * This source code is licensed under the MIT license found in the
84 * LICENSE file in the root directory of this source tree.
85 */
86
87var runtime = (function (exports) {
88
89 var Op = Object.prototype;
90 var hasOwn = Op.hasOwnProperty;
91 var undefined$1; // More compressible than void 0.
92 var $Symbol = typeof Symbol === "function" ? Symbol : {};
93 var iteratorSymbol = $Symbol.iterator || "@@iterator";
94 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
95 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
96
97 function define(obj, key, value) {
98 Object.defineProperty(obj, key, {
99 value: value,
100 enumerable: true,
101 configurable: true,
102 writable: true
103 });
104 return obj[key];
105 }
106 try {
107 // IE 8 has a broken Object.defineProperty that only works on DOM objects.
108 define({}, "");
109 } catch (err) {
110 define = function(obj, key, value) {
111 return obj[key] = value;
112 };
113 }
114
115 function wrap(innerFn, outerFn, self, tryLocsList) {
116 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
117 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
118 var generator = Object.create(protoGenerator.prototype);
119 var context = new Context(tryLocsList || []);
120
121 // The ._invoke method unifies the implementations of the .next,
122 // .throw, and .return methods.
123 generator._invoke = makeInvokeMethod(innerFn, self, context);
124
125 return generator;
126 }
127 exports.wrap = wrap;
128
129 // Try/catch helper to minimize deoptimizations. Returns a completion
130 // record like context.tryEntries[i].completion. This interface could
131 // have been (and was previously) designed to take a closure to be
132 // invoked without arguments, but in all the cases we care about we
133 // already have an existing method we want to call, so there's no need
134 // to create a new function object. We can even get away with assuming
135 // the method takes exactly one argument, since that happens to be true
136 // in every case, so we don't have to touch the arguments object. The
137 // only additional allocation required is the completion record, which
138 // has a stable shape and so hopefully should be cheap to allocate.
139 function tryCatch(fn, obj, arg) {
140 try {
141 return { type: "normal", arg: fn.call(obj, arg) };
142 } catch (err) {
143 return { type: "throw", arg: err };
144 }
145 }
146
147 var GenStateSuspendedStart = "suspendedStart";
148 var GenStateSuspendedYield = "suspendedYield";
149 var GenStateExecuting = "executing";
150 var GenStateCompleted = "completed";
151
152 // Returning this object from the innerFn has the same effect as
153 // breaking out of the dispatch switch statement.
154 var ContinueSentinel = {};
155
156 // Dummy constructor functions that we use as the .constructor and
157 // .constructor.prototype properties for functions that return Generator
158 // objects. For full spec compliance, you may wish to configure your
159 // minifier not to mangle the names of these two functions.
160 function Generator() {}
161 function GeneratorFunction() {}
162 function GeneratorFunctionPrototype() {}
163
164 // This is a polyfill for %IteratorPrototype% for environments that
165 // don't natively support it.
166 var IteratorPrototype = {};
167 IteratorPrototype[iteratorSymbol] = function () {
168 return this;
169 };
170
171 var getProto = Object.getPrototypeOf;
172 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
173 if (NativeIteratorPrototype &&
174 NativeIteratorPrototype !== Op &&
175 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
176 // This environment has a native %IteratorPrototype%; use it instead
177 // of the polyfill.
178 IteratorPrototype = NativeIteratorPrototype;
179 }
180
181 var Gp = GeneratorFunctionPrototype.prototype =
182 Generator.prototype = Object.create(IteratorPrototype);
183 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
184 GeneratorFunctionPrototype.constructor = GeneratorFunction;
185 GeneratorFunction.displayName = define(
186 GeneratorFunctionPrototype,
187 toStringTagSymbol,
188 "GeneratorFunction"
189 );
190
191 // Helper for defining the .next, .throw, and .return methods of the
192 // Iterator interface in terms of a single ._invoke method.
193 function defineIteratorMethods(prototype) {
194 ["next", "throw", "return"].forEach(function(method) {
195 define(prototype, method, function(arg) {
196 return this._invoke(method, arg);
197 });
198 });
199 }
200
201 exports.isGeneratorFunction = function(genFun) {
202 var ctor = typeof genFun === "function" && genFun.constructor;
203 return ctor
204 ? ctor === GeneratorFunction ||
205 // For the native GeneratorFunction constructor, the best we can
206 // do is to check its .name property.
207 (ctor.displayName || ctor.name) === "GeneratorFunction"
208 : false;
209 };
210
211 exports.mark = function(genFun) {
212 if (Object.setPrototypeOf) {
213 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
214 } else {
215 genFun.__proto__ = GeneratorFunctionPrototype;
216 define(genFun, toStringTagSymbol, "GeneratorFunction");
217 }
218 genFun.prototype = Object.create(Gp);
219 return genFun;
220 };
221
222 // Within the body of any async function, `await x` is transformed to
223 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
224 // `hasOwn.call(value, "__await")` to determine if the yielded value is
225 // meant to be awaited.
226 exports.awrap = function(arg) {
227 return { __await: arg };
228 };
229
230 function AsyncIterator(generator, PromiseImpl) {
231 function invoke(method, arg, resolve, reject) {
232 var record = tryCatch(generator[method], generator, arg);
233 if (record.type === "throw") {
234 reject(record.arg);
235 } else {
236 var result = record.arg;
237 var value = result.value;
238 if (value &&
239 typeof value === "object" &&
240 hasOwn.call(value, "__await")) {
241 return PromiseImpl.resolve(value.__await).then(function(value) {
242 invoke("next", value, resolve, reject);
243 }, function(err) {
244 invoke("throw", err, resolve, reject);
245 });
246 }
247
248 return PromiseImpl.resolve(value).then(function(unwrapped) {
249 // When a yielded Promise is resolved, its final value becomes
250 // the .value of the Promise<{value,done}> result for the
251 // current iteration.
252 result.value = unwrapped;
253 resolve(result);
254 }, function(error) {
255 // If a rejected Promise was yielded, throw the rejection back
256 // into the async generator function so it can be handled there.
257 return invoke("throw", error, resolve, reject);
258 });
259 }
260 }
261
262 var previousPromise;
263
264 function enqueue(method, arg) {
265 function callInvokeWithMethodAndArg() {
266 return new PromiseImpl(function(resolve, reject) {
267 invoke(method, arg, resolve, reject);
268 });
269 }
270
271 return previousPromise =
272 // If enqueue has been called before, then we want to wait until
273 // all previous Promises have been resolved before calling invoke,
274 // so that results are always delivered in the correct order. If
275 // enqueue has not been called before, then it is important to
276 // call invoke immediately, without waiting on a callback to fire,
277 // so that the async generator function has the opportunity to do
278 // any necessary setup in a predictable way. This predictability
279 // is why the Promise constructor synchronously invokes its
280 // executor callback, and why async functions synchronously
281 // execute code before the first await. Since we implement simple
282 // async functions in terms of async generators, it is especially
283 // important to get this right, even though it requires care.
284 previousPromise ? previousPromise.then(
285 callInvokeWithMethodAndArg,
286 // Avoid propagating failures to Promises returned by later
287 // invocations of the iterator.
288 callInvokeWithMethodAndArg
289 ) : callInvokeWithMethodAndArg();
290 }
291
292 // Define the unified helper method that is used to implement .next,
293 // .throw, and .return (see defineIteratorMethods).
294 this._invoke = enqueue;
295 }
296
297 defineIteratorMethods(AsyncIterator.prototype);
298 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
299 return this;
300 };
301 exports.AsyncIterator = AsyncIterator;
302
303 // Note that simple async functions are implemented on top of
304 // AsyncIterator objects; they just return a Promise for the value of
305 // the final result produced by the iterator.
306 exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
307 if (PromiseImpl === void 0) PromiseImpl = Promise;
308
309 var iter = new AsyncIterator(
310 wrap(innerFn, outerFn, self, tryLocsList),
311 PromiseImpl
312 );
313
314 return exports.isGeneratorFunction(outerFn)
315 ? iter // If outerFn is a generator, return the full iterator.
316 : iter.next().then(function(result) {
317 return result.done ? result.value : iter.next();
318 });
319 };
320
321 function makeInvokeMethod(innerFn, self, context) {
322 var state = GenStateSuspendedStart;
323
324 return function invoke(method, arg) {
325 if (state === GenStateExecuting) {
326 throw new Error("Generator is already running");
327 }
328
329 if (state === GenStateCompleted) {
330 if (method === "throw") {
331 throw arg;
332 }
333
334 // Be forgiving, per 25.3.3.3.3 of the spec:
335 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
336 return doneResult();
337 }
338
339 context.method = method;
340 context.arg = arg;
341
342 while (true) {
343 var delegate = context.delegate;
344 if (delegate) {
345 var delegateResult = maybeInvokeDelegate(delegate, context);
346 if (delegateResult) {
347 if (delegateResult === ContinueSentinel) continue;
348 return delegateResult;
349 }
350 }
351
352 if (context.method === "next") {
353 // Setting context._sent for legacy support of Babel's
354 // function.sent implementation.
355 context.sent = context._sent = context.arg;
356
357 } else if (context.method === "throw") {
358 if (state === GenStateSuspendedStart) {
359 state = GenStateCompleted;
360 throw context.arg;
361 }
362
363 context.dispatchException(context.arg);
364
365 } else if (context.method === "return") {
366 context.abrupt("return", context.arg);
367 }
368
369 state = GenStateExecuting;
370
371 var record = tryCatch(innerFn, self, context);
372 if (record.type === "normal") {
373 // If an exception is thrown from innerFn, we leave state ===
374 // GenStateExecuting and loop back for another invocation.
375 state = context.done
376 ? GenStateCompleted
377 : GenStateSuspendedYield;
378
379 if (record.arg === ContinueSentinel) {
380 continue;
381 }
382
383 return {
384 value: record.arg,
385 done: context.done
386 };
387
388 } else if (record.type === "throw") {
389 state = GenStateCompleted;
390 // Dispatch the exception by looping back around to the
391 // context.dispatchException(context.arg) call above.
392 context.method = "throw";
393 context.arg = record.arg;
394 }
395 }
396 };
397 }
398
399 // Call delegate.iterator[context.method](context.arg) and handle the
400 // result, either by returning a { value, done } result from the
401 // delegate iterator, or by modifying context.method and context.arg,
402 // setting context.delegate to null, and returning the ContinueSentinel.
403 function maybeInvokeDelegate(delegate, context) {
404 var method = delegate.iterator[context.method];
405 if (method === undefined$1) {
406 // A .throw or .return when the delegate iterator has no .throw
407 // method always terminates the yield* loop.
408 context.delegate = null;
409
410 if (context.method === "throw") {
411 // Note: ["return"] must be used for ES3 parsing compatibility.
412 if (delegate.iterator["return"]) {
413 // If the delegate iterator has a return method, give it a
414 // chance to clean up.
415 context.method = "return";
416 context.arg = undefined$1;
417 maybeInvokeDelegate(delegate, context);
418
419 if (context.method === "throw") {
420 // If maybeInvokeDelegate(context) changed context.method from
421 // "return" to "throw", let that override the TypeError below.
422 return ContinueSentinel;
423 }
424 }
425
426 context.method = "throw";
427 context.arg = new TypeError(
428 "The iterator does not provide a 'throw' method");
429 }
430
431 return ContinueSentinel;
432 }
433
434 var record = tryCatch(method, delegate.iterator, context.arg);
435
436 if (record.type === "throw") {
437 context.method = "throw";
438 context.arg = record.arg;
439 context.delegate = null;
440 return ContinueSentinel;
441 }
442
443 var info = record.arg;
444
445 if (! info) {
446 context.method = "throw";
447 context.arg = new TypeError("iterator result is not an object");
448 context.delegate = null;
449 return ContinueSentinel;
450 }
451
452 if (info.done) {
453 // Assign the result of the finished delegate to the temporary
454 // variable specified by delegate.resultName (see delegateYield).
455 context[delegate.resultName] = info.value;
456
457 // Resume execution at the desired location (see delegateYield).
458 context.next = delegate.nextLoc;
459
460 // If context.method was "throw" but the delegate handled the
461 // exception, let the outer generator proceed normally. If
462 // context.method was "next", forget context.arg since it has been
463 // "consumed" by the delegate iterator. If context.method was
464 // "return", allow the original .return call to continue in the
465 // outer generator.
466 if (context.method !== "return") {
467 context.method = "next";
468 context.arg = undefined$1;
469 }
470
471 } else {
472 // Re-yield the result returned by the delegate method.
473 return info;
474 }
475
476 // The delegate iterator is finished, so forget it and continue with
477 // the outer generator.
478 context.delegate = null;
479 return ContinueSentinel;
480 }
481
482 // Define Generator.prototype.{next,throw,return} in terms of the
483 // unified ._invoke helper method.
484 defineIteratorMethods(Gp);
485
486 define(Gp, toStringTagSymbol, "Generator");
487
488 // A Generator should always return itself as the iterator object when the
489 // @@iterator function is called on it. Some browsers' implementations of the
490 // iterator prototype chain incorrectly implement this, causing the Generator
491 // object to not be returned from this call. This ensures that doesn't happen.
492 // See https://github.com/facebook/regenerator/issues/274 for more details.
493 Gp[iteratorSymbol] = function() {
494 return this;
495 };
496
497 Gp.toString = function() {
498 return "[object Generator]";
499 };
500
501 function pushTryEntry(locs) {
502 var entry = { tryLoc: locs[0] };
503
504 if (1 in locs) {
505 entry.catchLoc = locs[1];
506 }
507
508 if (2 in locs) {
509 entry.finallyLoc = locs[2];
510 entry.afterLoc = locs[3];
511 }
512
513 this.tryEntries.push(entry);
514 }
515
516 function resetTryEntry(entry) {
517 var record = entry.completion || {};
518 record.type = "normal";
519 delete record.arg;
520 entry.completion = record;
521 }
522
523 function Context(tryLocsList) {
524 // The root entry object (effectively a try statement without a catch
525 // or a finally block) gives us a place to store values thrown from
526 // locations where there is no enclosing try statement.
527 this.tryEntries = [{ tryLoc: "root" }];
528 tryLocsList.forEach(pushTryEntry, this);
529 this.reset(true);
530 }
531
532 exports.keys = function(object) {
533 var keys = [];
534 for (var key in object) {
535 keys.push(key);
536 }
537 keys.reverse();
538
539 // Rather than returning an object with a next method, we keep
540 // things simple and return the next function itself.
541 return function next() {
542 while (keys.length) {
543 var key = keys.pop();
544 if (key in object) {
545 next.value = key;
546 next.done = false;
547 return next;
548 }
549 }
550
551 // To avoid creating an additional object, we just hang the .value
552 // and .done properties off the next function object itself. This
553 // also ensures that the minifier will not anonymize the function.
554 next.done = true;
555 return next;
556 };
557 };
558
559 function values(iterable) {
560 if (iterable) {
561 var iteratorMethod = iterable[iteratorSymbol];
562 if (iteratorMethod) {
563 return iteratorMethod.call(iterable);
564 }
565
566 if (typeof iterable.next === "function") {
567 return iterable;
568 }
569
570 if (!isNaN(iterable.length)) {
571 var i = -1, next = function next() {
572 while (++i < iterable.length) {
573 if (hasOwn.call(iterable, i)) {
574 next.value = iterable[i];
575 next.done = false;
576 return next;
577 }
578 }
579
580 next.value = undefined$1;
581 next.done = true;
582
583 return next;
584 };
585
586 return next.next = next;
587 }
588 }
589
590 // Return an iterator with no values.
591 return { next: doneResult };
592 }
593 exports.values = values;
594
595 function doneResult() {
596 return { value: undefined$1, done: true };
597 }
598
599 Context.prototype = {
600 constructor: Context,
601
602 reset: function(skipTempReset) {
603 this.prev = 0;
604 this.next = 0;
605 // Resetting context._sent for legacy support of Babel's
606 // function.sent implementation.
607 this.sent = this._sent = undefined$1;
608 this.done = false;
609 this.delegate = null;
610
611 this.method = "next";
612 this.arg = undefined$1;
613
614 this.tryEntries.forEach(resetTryEntry);
615
616 if (!skipTempReset) {
617 for (var name in this) {
618 // Not sure about the optimal order of these conditions:
619 if (name.charAt(0) === "t" &&
620 hasOwn.call(this, name) &&
621 !isNaN(+name.slice(1))) {
622 this[name] = undefined$1;
623 }
624 }
625 }
626 },
627
628 stop: function() {
629 this.done = true;
630
631 var rootEntry = this.tryEntries[0];
632 var rootRecord = rootEntry.completion;
633 if (rootRecord.type === "throw") {
634 throw rootRecord.arg;
635 }
636
637 return this.rval;
638 },
639
640 dispatchException: function(exception) {
641 if (this.done) {
642 throw exception;
643 }
644
645 var context = this;
646 function handle(loc, caught) {
647 record.type = "throw";
648 record.arg = exception;
649 context.next = loc;
650
651 if (caught) {
652 // If the dispatched exception was caught by a catch block,
653 // then let that catch block handle the exception normally.
654 context.method = "next";
655 context.arg = undefined$1;
656 }
657
658 return !! caught;
659 }
660
661 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
662 var entry = this.tryEntries[i];
663 var record = entry.completion;
664
665 if (entry.tryLoc === "root") {
666 // Exception thrown outside of any try block that could handle
667 // it, so set the completion value of the entire function to
668 // throw the exception.
669 return handle("end");
670 }
671
672 if (entry.tryLoc <= this.prev) {
673 var hasCatch = hasOwn.call(entry, "catchLoc");
674 var hasFinally = hasOwn.call(entry, "finallyLoc");
675
676 if (hasCatch && hasFinally) {
677 if (this.prev < entry.catchLoc) {
678 return handle(entry.catchLoc, true);
679 } else if (this.prev < entry.finallyLoc) {
680 return handle(entry.finallyLoc);
681 }
682
683 } else if (hasCatch) {
684 if (this.prev < entry.catchLoc) {
685 return handle(entry.catchLoc, true);
686 }
687
688 } else if (hasFinally) {
689 if (this.prev < entry.finallyLoc) {
690 return handle(entry.finallyLoc);
691 }
692
693 } else {
694 throw new Error("try statement without catch or finally");
695 }
696 }
697 }
698 },
699
700 abrupt: function(type, arg) {
701 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
702 var entry = this.tryEntries[i];
703 if (entry.tryLoc <= this.prev &&
704 hasOwn.call(entry, "finallyLoc") &&
705 this.prev < entry.finallyLoc) {
706 var finallyEntry = entry;
707 break;
708 }
709 }
710
711 if (finallyEntry &&
712 (type === "break" ||
713 type === "continue") &&
714 finallyEntry.tryLoc <= arg &&
715 arg <= finallyEntry.finallyLoc) {
716 // Ignore the finally entry if control is not jumping to a
717 // location outside the try/catch block.
718 finallyEntry = null;
719 }
720
721 var record = finallyEntry ? finallyEntry.completion : {};
722 record.type = type;
723 record.arg = arg;
724
725 if (finallyEntry) {
726 this.method = "next";
727 this.next = finallyEntry.finallyLoc;
728 return ContinueSentinel;
729 }
730
731 return this.complete(record);
732 },
733
734 complete: function(record, afterLoc) {
735 if (record.type === "throw") {
736 throw record.arg;
737 }
738
739 if (record.type === "break" ||
740 record.type === "continue") {
741 this.next = record.arg;
742 } else if (record.type === "return") {
743 this.rval = this.arg = record.arg;
744 this.method = "return";
745 this.next = "end";
746 } else if (record.type === "normal" && afterLoc) {
747 this.next = afterLoc;
748 }
749
750 return ContinueSentinel;
751 },
752
753 finish: function(finallyLoc) {
754 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
755 var entry = this.tryEntries[i];
756 if (entry.finallyLoc === finallyLoc) {
757 this.complete(entry.completion, entry.afterLoc);
758 resetTryEntry(entry);
759 return ContinueSentinel;
760 }
761 }
762 },
763
764 "catch": function(tryLoc) {
765 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
766 var entry = this.tryEntries[i];
767 if (entry.tryLoc === tryLoc) {
768 var record = entry.completion;
769 if (record.type === "throw") {
770 var thrown = record.arg;
771 resetTryEntry(entry);
772 }
773 return thrown;
774 }
775 }
776
777 // The context.catch method must only be called with a location
778 // argument that corresponds to a known catch block.
779 throw new Error("illegal catch attempt");
780 },
781
782 delegateYield: function(iterable, resultName, nextLoc) {
783 this.delegate = {
784 iterator: values(iterable),
785 resultName: resultName,
786 nextLoc: nextLoc
787 };
788
789 if (this.method === "next") {
790 // Deliberately forget the last sent value so that we don't
791 // accidentally pass it on to the delegate.
792 this.arg = undefined$1;
793 }
794
795 return ContinueSentinel;
796 }
797 };
798
799 // Regardless of whether this script is executing as a CommonJS module
800 // or not, return the runtime object so that we can declare the variable
801 // regeneratorRuntime in the outer scope, which allows this module to be
802 // injected easily by `bin/regenerator --include-runtime script.js`.
803 return exports;
804
805}(
806 // If this script is executing as a CommonJS module, use module.exports
807 // as the regeneratorRuntime namespace. Otherwise create a new empty
808 // object. Either way, the resulting object will be used to initialize
809 // the regeneratorRuntime variable at the top of this file.
810 module.exports
811));
812
813try {
814 regeneratorRuntime = runtime;
815} catch (accidentalStrictMode) {
816 // This module should not be running in strict mode, so the above
817 // assignment should always work unless something is misconfigured. Just
818 // in case runtime.js accidentally runs in strict mode, we can escape
819 // strict mode using a global Function call. This could conceivably fail
820 // if a Content Security Policy forbids using Function, but in that case
821 // the proper solution is to fix the accidental strict mode problem. If
822 // you've misconfigured your bundler to force strict mode and applied a
823 // CSP to forbid Function, and you're not willing to fix either of those
824 // problems, please detail your unique predicament in a GitHub issue.
825 Function("r", "regeneratorRuntime = r")(runtime);
826}
827});
828
829var HttpRequestErrorHandler = /*#__PURE__*/function () {
830 function HttpRequestErrorHandler(logger, httpRequestErrorService, strategy) {
831 /**
832 * @var noThrowStrategies List of strategies excluded from error throwing
833 *
834 * @memberof HttpRequestHandler
835 */
836 this.noThrowStrategies = ['reject', 'silent'];
837 this.logger = logger;
838 this.httpRequestErrorService = httpRequestErrorService;
839 this.strategy = strategy;
840 }
841 /**
842 * Process and Error
843 *
844 * @param {*} error Error instance or message
845 * @throws Request error context
846 * @returns {void}
847 */
848
849
850 var _proto = HttpRequestErrorHandler.prototype;
851
852 _proto.process = function process(error) {
853 if (this.logger && this.logger.warn) {
854 this.logger.warn('API ERROR', error);
855 }
856
857 var errorContext = error;
858
859 if (typeof error === 'string') {
860 errorContext = new Error(error);
861 }
862
863 if (this.httpRequestErrorService) {
864 if (typeof this.httpRequestErrorService.process !== 'undefined') {
865 this.httpRequestErrorService.process(errorContext);
866 } else if (typeof this.httpRequestErrorService === 'function') {
867 this.httpRequestErrorService(errorContext);
868 }
869 }
870
871 if (!this.noThrowStrategies.includes(this.strategy)) {
872 throw errorContext;
873 }
874 };
875
876 return HttpRequestErrorHandler;
877}();
878
879/**
880 * Generic Request Handler
881 * It creates an Axios instance and handles requests within that instance
882 * It handles errors depending on a chosen error handling strategy
883 */
884
885var HttpRequestHandler = /*#__PURE__*/function () {
886 /**
887 * Creates an instance of HttpRequestHandler
888 *
889 * @param {string} baseURL Base URL for all API calls
890 * @param {number} timeout Request timeout
891 * @param {string} strategy Error Handling Strategy
892 * @param {string} flattenResponse Whether to flatten response "data" object within "data" one
893 * @param {*} logger Instance of Logger Class
894 * @param {*} httpRequestErrorService Instance of Error Service Class
895 *
896 * @memberof HttpRequestHandler
897 */
898 function HttpRequestHandler(_ref) {
899 var _ref$baseURL = _ref.baseURL,
900 baseURL = _ref$baseURL === void 0 ? '' : _ref$baseURL,
901 _ref$timeout = _ref.timeout,
902 timeout = _ref$timeout === void 0 ? null : _ref$timeout,
903 _ref$strategy = _ref.strategy,
904 strategy = _ref$strategy === void 0 ? null : _ref$strategy,
905 _ref$flattenResponse = _ref.flattenResponse,
906 flattenResponse = _ref$flattenResponse === void 0 ? null : _ref$flattenResponse,
907 _ref$logger = _ref.logger,
908 logger = _ref$logger === void 0 ? null : _ref$logger,
909 _ref$httpRequestError = _ref.httpRequestErrorService,
910 httpRequestErrorService = _ref$httpRequestError === void 0 ? null : _ref$httpRequestError,
911 config = _objectWithoutPropertiesLoose(_ref, ["baseURL", "timeout", "strategy", "flattenResponse", "logger", "httpRequestErrorService"]);
912
913 /**
914 * @var timeout Request timeout
915 *
916 * @memberof HttpRequestHandler
917 */
918 this.timeout = 30000;
919 /**
920 * @var strategy Request timeout
921 *
922 * @memberof HttpRequestHandler
923 */
924
925 this.strategy = 'silent';
926 /**
927 * @var flattenResponse Response flattening
928 *
929 * @memberof HttpRequestHandler
930 */
931
932 this.flattenResponse = true;
933 this.timeout = timeout !== null ? timeout : this.timeout;
934 this.strategy = strategy !== null ? strategy : this.strategy;
935 this.flattenResponse = flattenResponse !== null ? flattenResponse : this.flattenResponse;
936 this.logger = logger || global.console || window.console || null;
937 this.httpRequestErrorService = httpRequestErrorService;
938 this.requestInstance = axios.create(_extends({}, config, {
939 baseURL: baseURL,
940 timeout: this.timeout
941 }));
942 }
943 /**
944 * Get Provider Instance
945 *
946 * @returns {AxiosInstance} Provider's instance
947 * @memberof HttpRequestHandler
948 */
949
950
951 var _proto = HttpRequestHandler.prototype;
952
953 _proto.getInstance = function getInstance() {
954 return this.requestInstance;
955 }
956 /**
957 * Intercept Request
958 *
959 * @param {*} callback callback to use before request
960 * @returns {void}
961 * @memberof HttpRequestHandler
962 */
963 ;
964
965 _proto.interceptRequest = function interceptRequest(callback) {
966 this.getInstance().interceptors.request.use(callback);
967 }
968 /**
969 * POST Request
970 *
971 * @param {string} url Url
972 * @param {*} data Payload
973 * @param {AxiosRequestConfig} config Config
974 * @throws {Error} If request fails
975 * @returns {Promise} Request response or error info
976 * @memberof HttpRequestHandler
977 */
978 ;
979
980 _proto.post = function post(url, data, config) {
981 if (data === void 0) {
982 data = null;
983 }
984
985 if (config === void 0) {
986 config = null;
987 }
988
989 return this.handleRequest({
990 type: 'post',
991 url: url,
992 data: data,
993 config: config
994 });
995 }
996 /**
997 * GET Request
998 *
999 * @param {string} url Url
1000 * @param {*} data Payload
1001 * @param {AxiosRequestConfig} config Config
1002 * @throws {Error} If request fails
1003 * @returns {Promise} Request response or error info
1004 * @memberof HttpRequestHandler
1005 */
1006 ;
1007
1008 _proto.get = function get(url, data, config) {
1009 if (data === void 0) {
1010 data = null;
1011 }
1012
1013 if (config === void 0) {
1014 config = null;
1015 }
1016
1017 return this.handleRequest({
1018 type: 'get',
1019 url: url,
1020 data: data,
1021 config: config
1022 });
1023 }
1024 /**
1025 * PUT Request
1026 *
1027 * @param {string} url Url
1028 * @param {*} data Payload
1029 * @param {AxiosRequestConfig} config Config
1030 * @throws {Error} If request fails
1031 * @returns {Promise} Request response or error info
1032 * @memberof HttpRequestHandler
1033 */
1034 ;
1035
1036 _proto.put = function put(url, data, config) {
1037 if (data === void 0) {
1038 data = null;
1039 }
1040
1041 if (config === void 0) {
1042 config = null;
1043 }
1044
1045 return this.handleRequest({
1046 type: 'put',
1047 url: url,
1048 data: data,
1049 config: config
1050 });
1051 }
1052 /**
1053 * DELETE Request
1054 *
1055 * @param {string} url Url
1056 * @param {*} data Payload
1057 * @param {AxiosRequestConfig} config Config
1058 * @throws {Error} If request fails
1059 * @returns {Promise} Request response or error info
1060 * @memberof HttpRequestHandler
1061 */
1062 ;
1063
1064 _proto["delete"] = function _delete(url, data, config) {
1065 if (data === void 0) {
1066 data = null;
1067 }
1068
1069 if (config === void 0) {
1070 config = null;
1071 }
1072
1073 return this.handleRequest({
1074 type: 'delete',
1075 url: url,
1076 data: data,
1077 config: config
1078 });
1079 }
1080 /**
1081 * PATCH Request
1082 *
1083 * @param {string} url Url
1084 * @param {*} data Payload
1085 * @param {AxiosRequestConfig} config Config
1086 * @throws {Error} If request fails
1087 * @returns {Promise} Request response or error info
1088 * @memberof HttpRequestHandler
1089 */
1090 ;
1091
1092 _proto.patch = function patch(url, data, config) {
1093 if (data === void 0) {
1094 data = null;
1095 }
1096
1097 if (config === void 0) {
1098 config = null;
1099 }
1100
1101 return this.handleRequest({
1102 type: 'patch',
1103 url: url,
1104 data: data,
1105 config: config
1106 });
1107 }
1108 /**
1109 * HEAD Request
1110 *
1111 * @param {string} url Url
1112 * @param {*} data Payload
1113 * @param {AxiosRequestConfig} config Config
1114 * @throws {Error} If request fails
1115 * @returns {Promise} Request response or error info
1116 * @memberof HttpRequestHandler
1117 */
1118 ;
1119
1120 _proto.head = function head(url, data, config) {
1121 if (data === void 0) {
1122 data = null;
1123 }
1124
1125 if (config === void 0) {
1126 config = null;
1127 }
1128
1129 return this.handleRequest({
1130 type: 'head',
1131 url: url,
1132 data: data,
1133 config: config
1134 });
1135 }
1136 /**
1137 * Get Provider Instance
1138 *
1139 * @param {Error} err Error instance
1140 * @returns {AxiosInstance} Provider's instance
1141 * @memberof HttpRequestHandler
1142 */
1143 ;
1144
1145 _proto.processRequestError = function processRequestError(err) {
1146 return new HttpRequestErrorHandler(this.logger, this.httpRequestErrorService, this.strategy).process(err);
1147 }
1148 /**
1149 * Handle Request depending on used strategy
1150 *
1151 * @param {object} payload Payload
1152 * @param {string} payload.type Request type
1153 * @param {string} payload.url Request url
1154 * @param {*} payload.data Request data
1155 * @param {AxiosRequestConfig} payload.config Config to modify request
1156 * @throws {Error}
1157 * @returns {Promise} Response Data
1158 * @memberof HttpRequestHandler
1159 */
1160 ;
1161
1162 _proto.handleRequest =
1163 /*#__PURE__*/
1164 function () {
1165 var _handleRequest = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee(_ref2) {
1166 var _extends2;
1167
1168 var type, url, _ref2$data, data, _ref2$config, config, response, requestConfig, key;
1169
1170 return runtime_1.wrap(function _callee$(_context) {
1171 while (1) {
1172 switch (_context.prev = _context.next) {
1173 case 0:
1174 type = _ref2.type, url = _ref2.url, _ref2$data = _ref2.data, data = _ref2$data === void 0 ? null : _ref2$data, _ref2$config = _ref2.config, config = _ref2$config === void 0 ? null : _ref2$config;
1175 response = null;
1176 requestConfig = config || {};
1177 key = type === 'get' || type === 'head' ? 'params' : 'data';
1178 requestConfig = _extends({}, requestConfig, (_extends2 = {
1179 url: url,
1180 method: type
1181 }, _extends2[key] = data || {}, _extends2));
1182 _context.t0 = this.strategy;
1183 _context.next = _context.t0 === 'silent' ? 8 : _context.t0 === 'reject' ? 22 : _context.t0 === 'throwError' ? 33 : 33;
1184 break;
1185
1186 case 8:
1187 _context.prev = 8;
1188 _context.next = 11;
1189 return this.requestInstance.request(requestConfig);
1190
1191 case 11:
1192 response = _context.sent;
1193 _context.next = 21;
1194 break;
1195
1196 case 14:
1197 _context.prev = 14;
1198 _context.t1 = _context["catch"](8);
1199 this.processRequestError(_context.t1);
1200 _context.next = 19;
1201 return new Promise(function () {
1202 return null;
1203 });
1204
1205 case 19:
1206 response = _context.sent;
1207 return _context.abrupt("return", response);
1208
1209 case 21:
1210 return _context.abrupt("break", 36);
1211
1212 case 22:
1213 _context.prev = 22;
1214 _context.next = 25;
1215 return this.requestInstance.request(requestConfig);
1216
1217 case 25:
1218 response = _context.sent;
1219 _context.next = 32;
1220 break;
1221
1222 case 28:
1223 _context.prev = 28;
1224 _context.t2 = _context["catch"](22);
1225 this.processRequestError(_context.t2);
1226 return _context.abrupt("return", Promise.reject(_context.t2));
1227
1228 case 32:
1229 return _context.abrupt("break", 36);
1230
1231 case 33:
1232 _context.next = 35;
1233 return this.requestInstance.request(requestConfig);
1234
1235 case 35:
1236 response = _context.sent;
1237
1238 case 36:
1239 return _context.abrupt("return", this.processResponseData(response));
1240
1241 case 37:
1242 case "end":
1243 return _context.stop();
1244 }
1245 }
1246 }, _callee, this, [[8, 14], [22, 28]]);
1247 }));
1248
1249 function handleRequest(_x) {
1250 return _handleRequest.apply(this, arguments);
1251 }
1252
1253 return handleRequest;
1254 }() // eslint-disable-next-line class-methods-use-this
1255 ;
1256
1257 _proto.processResponseData = function processResponseData(response) {
1258 if (response.data) {
1259 if (!this.flattenResponse) {
1260 return response;
1261 } // Special case of data property within Axios data object
1262 // This is in fact a proper response but we may want to flatten it
1263 // To ease developers' lives when obtaining the response
1264
1265
1266 if (typeof response.data === 'object' && response.data.data && Object.keys(response.data).length === 1) {
1267 return response.data.data;
1268 }
1269
1270 return response.data;
1271 }
1272
1273 return null;
1274 };
1275
1276 return HttpRequestHandler;
1277}();
1278
1279HttpRequestHandler = /*#__PURE__*/__decorate([/*#__PURE__*/CatchAll(function (err, ctx) {
1280 return ctx.processRequestError(err);
1281})], HttpRequestHandler);
1282
1283/**
1284 * Handles dispatching of API requests
1285 */
1286
1287var ApiHandler = /*#__PURE__*/function () {
1288 /**
1289 * Creates an instance of API Handler
1290 *
1291 * @param {string} apiUrl Base URL for all API calls
1292 * @param {number} timeout Request timeout
1293 * @param {string} strategy Error Handling Strategy
1294 * @param {string} flattenResponse Whether to flatten response "data" object within "data" one
1295 * @param {*} logger Instance of Logger Class
1296 * @param {*} httpRequestErrorService Instance of Error Service Class
1297 *
1298 * @memberof ApiHandler
1299 */
1300 function ApiHandler(_ref) {
1301 var apiUrl = _ref.apiUrl,
1302 apiEndpoints = _ref.apiEndpoints,
1303 _ref$timeout = _ref.timeout,
1304 timeout = _ref$timeout === void 0 ? null : _ref$timeout,
1305 _ref$strategy = _ref.strategy,
1306 strategy = _ref$strategy === void 0 ? null : _ref$strategy,
1307 _ref$flattenResponse = _ref.flattenResponse,
1308 flattenResponse = _ref$flattenResponse === void 0 ? null : _ref$flattenResponse,
1309 _ref$logger = _ref.logger,
1310 logger = _ref$logger === void 0 ? null : _ref$logger,
1311 _ref$httpRequestError = _ref.httpRequestErrorService,
1312 httpRequestErrorService = _ref$httpRequestError === void 0 ? null : _ref$httpRequestError,
1313 config = _objectWithoutPropertiesLoose(_ref, ["apiUrl", "apiEndpoints", "timeout", "strategy", "flattenResponse", "logger", "httpRequestErrorService"]);
1314
1315 /**
1316 * Api Url
1317 *
1318 * @memberof ApiHandler
1319 */
1320 this.apiUrl = '';
1321 this.apiUrl = apiUrl;
1322 this.apiEndpoints = apiEndpoints;
1323 this.logger = logger;
1324 this.httpRequestHandler = new HttpRequestHandler(_extends({}, config, {
1325 baseURL: this.apiUrl,
1326 timeout: timeout,
1327 strategy: strategy,
1328 flattenResponse: flattenResponse,
1329 logger: logger,
1330 httpRequestErrorService: httpRequestErrorService
1331 }));
1332 }
1333 /**
1334 * Get Provider Instance
1335 *
1336 * @returns {AxiosInstance} Provider's instance
1337 * @memberof ApiHandler
1338 */
1339
1340
1341 var _proto = ApiHandler.prototype;
1342
1343 _proto.getInstance = function getInstance() {
1344 return this.httpRequestHandler.getInstance();
1345 }
1346 /**
1347 * Maps all API requests
1348 *
1349 * @param {*} prop Caller
1350 * @returns {Function} Tailored request function
1351 * @memberof ApiHandler
1352 */
1353 ;
1354
1355 _proto.__get = function __get(prop) {
1356 if (prop in this) {
1357 return this[prop];
1358 } // Prevent handler from running for non-existent endpoints
1359
1360
1361 if (!this.apiEndpoints[prop]) {
1362 return this.handleNonImplemented.bind(this, prop);
1363 }
1364
1365 return this.handleRequest.bind(this, prop);
1366 }
1367 /**
1368 * Handle Single API Request
1369 *
1370 * @param {*} args Arguments
1371 * @returns {Promise} Resolvable API provider promise
1372 * @memberof ApiHandler
1373 */
1374 ;
1375
1376 _proto.handleRequest =
1377 /*#__PURE__*/
1378 function () {
1379 var _handleRequest = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/runtime_1.mark(function _callee() {
1380 var prop,
1381 api,
1382 queryParams,
1383 uriParams,
1384 requestConfig,
1385 uri,
1386 requestData,
1387 responseData,
1388 _args = arguments;
1389 return runtime_1.wrap(function _callee$(_context) {
1390 while (1) {
1391 switch (_context.prev = _context.next) {
1392 case 0:
1393 prop = _args.length <= 0 ? undefined : _args[0];
1394 api = this.apiEndpoints[prop];
1395 queryParams = (_args.length <= 1 ? undefined : _args[1]) || {};
1396 uriParams = (_args.length <= 2 ? undefined : _args[2]) || {};
1397 requestConfig = (_args.length <= 3 ? undefined : _args[3]) || {};
1398 uri = api.url.replace(/:[a-z]+/ig, function (str) {
1399 return uriParams[str.substr(1)] ? uriParams[str.substr(1)] : str;
1400 });
1401 requestData = _extends({}, queryParams);
1402 responseData = null;
1403 _context.next = 10;
1404 return this.httpRequestHandler[api.method](uri, requestData, requestConfig);
1405
1406 case 10:
1407 responseData = _context.sent;
1408 return _context.abrupt("return", responseData);
1409
1410 case 12:
1411 case "end":
1412 return _context.stop();
1413 }
1414 }
1415 }, _callee, this);
1416 }));
1417
1418 function handleRequest() {
1419 return _handleRequest.apply(this, arguments);
1420 }
1421
1422 return handleRequest;
1423 }()
1424 /**
1425 * Triggered when trying to use non-existent endpoints
1426 * @param prop Method Name
1427 * @returns {Promise}
1428 * @memberof ApiHandler
1429 */
1430 ;
1431
1432 _proto.handleNonImplemented = function handleNonImplemented(prop) {
1433 if (this.logger && this.logger.log) {
1434 this.logger.log(prop + " endpoint not implemented.");
1435 }
1436
1437 return Promise.resolve(null);
1438 };
1439
1440 return ApiHandler;
1441}();
1442
1443ApiHandler = /*#__PURE__*/__decorate([applyMagic], ApiHandler);
1444var createApiFetcher = function createApiFetcher(options) {
1445 return new ApiHandler(options);
1446};
1447
1448export { ApiHandler, HttpRequestErrorHandler, HttpRequestHandler, createApiFetcher };
1449//# sourceMappingURL=axios-multi-api.esm.js.map