@rabbitio/ui-kit 1.0.0-beta.37 → 1.0.0-beta.39

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/dist/index.umd.js CHANGED
@@ -1,12 +1,13 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('bignumber.js'), require('axios'), require('eventbusjs')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'react', 'bignumber.js', 'axios', 'eventbusjs'], factory) :
4
- (global = global || self, factory(global.uiKit = {}, global.react, global.bignumber_js, global.axios, global.eventbusjs));
5
- })(this, (function (exports, React, bignumber_js, axios, EventBusInstance) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('bignumber.js'), require('axios'), require('uuid'), require('jshashes'), require('eventbusjs')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'react', 'bignumber.js', 'axios', 'uuid', 'jshashes', 'eventbusjs'], factory) :
4
+ (global = global || self, factory(global.uiKit = {}, global.react, global.bignumber_js, global.axios, global.uuid, global.jshashes, global.eventbusjs));
5
+ })(this, (function (exports, React, bignumber_js, axios, uuid, Hashes, EventBusInstance) {
6
6
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
7
7
 
8
8
  var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
9
9
  var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
10
+ var Hashes__default = /*#__PURE__*/_interopDefaultLegacy(Hashes);
10
11
  var EventBusInstance__default = /*#__PURE__*/_interopDefaultLegacy(EventBusInstance);
11
12
 
12
13
  function createCommonjsModule(fn) {
@@ -1627,7 +1628,7 @@
1627
1628
  return Logger;
1628
1629
  }();
1629
1630
 
1630
- function _catch$4(body, recover) {
1631
+ function _catch$8(body, recover) {
1631
1632
  try {
1632
1633
  var result = body();
1633
1634
  } catch (e) {
@@ -1643,7 +1644,7 @@
1643
1644
  setState = _useState[1];
1644
1645
  return React.useCallback(function (functionToBeCalled, event) {
1645
1646
  try {
1646
- var _temp = _catch$4(function () {
1647
+ var _temp = _catch$8(function () {
1647
1648
  return Promise.resolve(functionToBeCalled(event)).then(function () {});
1648
1649
  }, function (error) {
1649
1650
  Logger.logError(error, (functionToBeCalled == null ? void 0 : functionToBeCalled.name) || "errorBoundaryTrigger", "Caught by ErrorBoundary");
@@ -1681,6 +1682,96 @@
1681
1682
  return [reference, setReferredState];
1682
1683
  }
1683
1684
 
1685
+ var handleClickOutside = function handleClickOutside(exceptionsRefs, callback) {
1686
+ function handleClick(event) {
1687
+ var isExceptionClicked = exceptionsRefs.find(function (ref) {
1688
+ return (ref == null ? void 0 : ref.current) && ref.current.contains(event.target);
1689
+ });
1690
+ if (!isExceptionClicked) {
1691
+ callback();
1692
+ }
1693
+ }
1694
+ document.addEventListener("click", handleClick);
1695
+ return function () {
1696
+ return document.removeEventListener("click", handleClick);
1697
+ };
1698
+ };
1699
+
1700
+ var PARAMETER_VALUES_SEPARATOR = "|*|"; // Sting that with high probability will not be in the user's data
1701
+
1702
+ /**
1703
+ * Adds specified parameter with values to the URL query string
1704
+ *
1705
+ * @param parameterName - String - name of the parameter
1706
+ * @param values - Array of String values
1707
+ * @param updateURLCallback - callback that will be called with the updated query string. Can be used to save it to URL
1708
+ */
1709
+ function saveQueryParameterAndValues(parameterName, values, updateURLCallback) {
1710
+ if (updateURLCallback === void 0) {
1711
+ updateURLCallback = function updateURLCallback(newQueryString) {};
1712
+ }
1713
+ var parametersAndValues = parseSearchString();
1714
+ parametersAndValues = parametersAndValues.filter(function (parameterAndValues) {
1715
+ return parameterAndValues[0] !== parameterName;
1716
+ });
1717
+ var parameterValuesForURL = encodeURIComponent(values.join(PARAMETER_VALUES_SEPARATOR));
1718
+ parametersAndValues.push([parameterName, parameterValuesForURL]);
1719
+ var newQueryString = "?" + parametersAndValues.map(function (parameterAndValues) {
1720
+ return parameterAndValues.join("=");
1721
+ }).join("&");
1722
+ updateURLCallback(newQueryString);
1723
+ return newQueryString;
1724
+ }
1725
+
1726
+ /**
1727
+ * Removes specified parameter with values from the URL query string
1728
+ *
1729
+ * @param parameterName - String - name of the parameter
1730
+ * @param updateURLCallback - callback that will be called with the updated query string. Can be used to save it to URL
1731
+ */
1732
+ // TODO: [tests, moderate] units required the same as or other functions in this module
1733
+ function removeQueryParameterAndValues(parameterName, updateURLCallback) {
1734
+ if (updateURLCallback === void 0) {
1735
+ updateURLCallback = function updateURLCallback(newQueryString) {};
1736
+ }
1737
+ var parametersAndValues = parseSearchString();
1738
+ parametersAndValues = parametersAndValues.filter(function (parameterAndValues) {
1739
+ return parameterAndValues[0] !== parameterName;
1740
+ });
1741
+ var newQueryString = "?" + parametersAndValues.map(function (parameterAndValues) {
1742
+ return parameterAndValues.join("=");
1743
+ }).join("&");
1744
+ updateURLCallback(newQueryString);
1745
+ return newQueryString;
1746
+ }
1747
+
1748
+ /**
1749
+ * Retrieves parameter values from the URL query string.
1750
+ *
1751
+ * If there are several parameters with the same name in the URL then all their values are returned
1752
+ *
1753
+ * @param name {string} - parameter name
1754
+ * @return {string[]} [] - if the parameter is not present in URL. [""] - if parameter present but has empty value
1755
+ */
1756
+ function getQueryParameterValues(name) {
1757
+ return parseSearchString().filter(function (parameterAndValue) {
1758
+ return parameterAndValue[0] === name;
1759
+ }).reduce(function (allValues, parameterAndValue) {
1760
+ var values = decodeURIComponent(parameterAndValue[1] || "").split(PARAMETER_VALUES_SEPARATOR);
1761
+ return [].concat(allValues, values);
1762
+ }, []);
1763
+ }
1764
+ function parseSearchString() {
1765
+ var _window$location$sear;
1766
+ var trimmed = (((_window$location$sear = window.location.search) == null ? void 0 : _window$location$sear.slice(1)) || "").trim();
1767
+ return trimmed && trimmed.split("&").map(function (parameterAndValue) {
1768
+ return parameterAndValue.split("=");
1769
+ }) || [];
1770
+ }
1771
+ function getQueryParameterSingleValue(name) {
1772
+ return (getQueryParameterValues(name) || [])[0];
1773
+ }
1774
+
1684
1775
  /**
1685
1776
  * This function improves the passed error object (its message) by adding the passed function name
1686
1777
  * and additional message to it.
@@ -1709,6 +1800,17 @@
1709
1800
  additionalMessage && (message += additionalMessage + " ");
1710
1801
  return message;
1711
1802
  }
1803
+ function logErrorOrOutputToConsole(e) {
1804
+ try {
1805
+ // TODO: [dev] remove this after few weeks of testing output in real life
1806
+ // eslint-disable-next-line no-console
1807
+ console.log("BEFORE SAFE", e);
1808
+ Logger.log("logErrorOrOutputToConsole", safeStringify(e));
1809
+ } catch (e) {
1810
+ // eslint-disable-next-line no-console
1811
+ console.log("logErrorOrOutputToConsole", e);
1812
+ }
1813
+ }
1712
1814
 
1713
1815
  var FiatCurrenciesService = /*#__PURE__*/function () {
1714
1816
  function FiatCurrenciesService() {}
@@ -2580,7 +2682,109 @@
2580
2682
  return Cache;
2581
2683
  }();
2582
2684
 
2583
- function _catch$3(body, recover) {
2685
+ function _catch$7(body, recover) {
2686
+ try {
2687
+ var result = body();
2688
+ } catch (e) {
2689
+ return recover(e);
2690
+ }
2691
+ if (result && result.then) {
2692
+ return result.then(void 0, recover);
2693
+ }
2694
+ return result;
2695
+ }
2696
+ function postponeExecution(execution, timeoutMS) {
2697
+ if (timeoutMS === void 0) {
2698
+ timeoutMS = 1000;
2699
+ }
2700
+ return new Promise(function (resolve, reject) {
2701
+ setTimeout(function () {
2702
+ try {
2703
+ var _temp = _catch$7(function () {
2704
+ return Promise.resolve(execution()).then(function (_execution) {
2705
+ resolve(_execution);
2706
+ });
2707
+ }, function (e) {
2708
+ reject(e);
2709
+ });
2710
+ return Promise.resolve(_temp && _temp.then ? _temp.then(function () {}) : void 0);
2711
+ } catch (e) {
2712
+ return Promise.reject(e);
2713
+ }
2714
+ }, timeoutMS);
2715
+ });
2716
+ }
2717
+
2718
+ var AxiosAdapter = /*#__PURE__*/function () {
2719
+ function AxiosAdapter() {}
2720
+ AxiosAdapter.call = function call(method) {
2721
+ try {
2722
+ var _arguments = arguments;
2723
+ return Promise.resolve(axios__default["default"][method].apply(axios__default["default"], [].slice.call(_arguments, 1)));
2724
+ } catch (e) {
2725
+ return Promise.reject(e);
2726
+ }
2727
+ };
2728
+ AxiosAdapter.get = function get() {
2729
+ try {
2730
+ var _arguments2 = arguments;
2731
+ return Promise.resolve(axios__default["default"].get.apply(axios__default["default"], [].slice.call(_arguments2)));
2732
+ } catch (e) {
2733
+ return Promise.reject(e);
2734
+ }
2735
+ };
2736
+ AxiosAdapter.post = function post() {
2737
+ try {
2738
+ var _arguments3 = arguments;
2739
+ return Promise.resolve(axios__default["default"].post.apply(axios__default["default"], [].slice.call(_arguments3)));
2740
+ } catch (e) {
2741
+ return Promise.reject(e);
2742
+ }
2743
+ };
2744
+ AxiosAdapter.put = function put() {
2745
+ try {
2746
+ var _arguments4 = arguments;
2747
+ return Promise.resolve(axios__default["default"].put.apply(axios__default["default"], [].slice.call(_arguments4)));
2748
+ } catch (e) {
2749
+ return Promise.reject(e);
2750
+ }
2751
+ };
2752
+ AxiosAdapter["delete"] = function _delete() {
2753
+ try {
2754
+ var _arguments5 = arguments;
2755
+ return Promise.resolve(axios__default["default"]["delete"].apply(axios__default["default"], [].slice.call(_arguments5)));
2756
+ } catch (e) {
2757
+ return Promise.reject(e);
2758
+ }
2759
+ };
2760
+ AxiosAdapter.patch = function patch() {
2761
+ try {
2762
+ var _arguments6 = arguments;
2763
+ return Promise.resolve(axios__default["default"].patch.apply(axios__default["default"], [].slice.call(_arguments6)));
2764
+ } catch (e) {
2765
+ return Promise.reject(e);
2766
+ }
2767
+ };
2768
+ AxiosAdapter.options = function options() {
2769
+ try {
2770
+ var _arguments7 = arguments;
2771
+ return Promise.resolve(axios__default["default"].options.apply(axios__default["default"], [].slice.call(_arguments7)));
2772
+ } catch (e) {
2773
+ return Promise.reject(e);
2774
+ }
2775
+ };
2776
+ AxiosAdapter.head = function head() {
2777
+ try {
2778
+ var _arguments8 = arguments;
2779
+ return Promise.resolve(axios__default["default"].head.apply(axios__default["default"], [].slice.call(_arguments8)));
2780
+ } catch (e) {
2781
+ return Promise.reject(e);
2782
+ }
2783
+ };
2784
+ return AxiosAdapter;
2785
+ }();
2786
+
2787
+ function _catch$6(body, recover) {
2584
2788
  try {
2585
2789
  var result = body();
2586
2790
  } catch (e) {
@@ -2596,7 +2800,7 @@
2596
2800
  EmailsApi.sendEmail = function sendEmail(subject, body) {
2597
2801
  try {
2598
2802
  var _this = this;
2599
- var _temp = _catch$3(function () {
2803
+ var _temp = _catch$6(function () {
2600
2804
  var url = window.location.protocol + "//" + window.location.host + "/api/v1/" + _this.serverEndpointEntity;
2601
2805
  return Promise.resolve(axios__default["default"].post(url, {
2602
2806
  subject: subject,
@@ -2614,6 +2818,1825 @@
2614
2818
  }();
2615
2819
  EmailsApi.serverEndpointEntity = "emails";
2616
2820
 
2821
+ /**
2822
+ * This util helps to avoid duplicated calls to a shared resource.
2823
+ * It tracks is there currently active calculation for the specific cache id and make all other requests
2824
+ * with the same cache id waiting for this active calculation to be finished. When the calculation ends
2825
+ * the resolver allows all the waiting requesters to get the data from cache and start their own calculations.
2826
+ *
2827
+ * This class should be instantiated inside some other service where you need to request some resource concurrently.
2828
+ * Rules:
2829
+ * 1. When you need to make a request inside your main service call 'getCachedOrWaitForCachedOrAcquireLock'
2830
+ * on the instance of this class and await for the result. If the flag allowing to start calculation is true
2831
+ * then you can request data inside your main service. Otherwise you should use the cached data as an another
2832
+ * requester just finished the most resent requesting and there is actual data in the cache that
2833
+ * is returned to you here.
2834
+ * 1.1 Also you can acquire a lock directly if you don't want to get cached data. Use the corresponding method 'acquireLock'.
2835
+ *
2836
+ * 2. If you start requesting (when you successfully acquired the lock) then after receiving the result of your
2837
+ * requesting you should call the 'saveCachedData' so the retrieved data will appear in the cache.
2838
+ *
2839
+ * 3. If you successfully acquired the lock then you should after calling the 'saveCachedData' call
2840
+ * the 'releaseLock' - this is mandatory to release the lock and allow other requesters to perform their requests.
2841
+ * WARNING: If for any reason you forget to call this method then this class instance will wait perpetually for
2842
+ * the lock releasing and all your attempts to request the data will constantly fail. So usually call it
2843
+ * inside the 'finally' block.
2844
+ *
2845
+ * TODO: [tests, critical++] add unit tests - massively used logic and can produce sophisticated concurrency bugs
2846
+ */
2847
+
2848
+ function _settle$2(pact, state, value) {
2849
+ if (!pact.s) {
2850
+ if (value instanceof _Pact$2) {
2851
+ if (value.s) {
2852
+ if (state & 1) {
2853
+ state = value.s;
2854
+ }
2855
+ value = value.v;
2856
+ } else {
2857
+ value.o = _settle$2.bind(null, pact, state);
2858
+ return;
2859
+ }
2860
+ }
2861
+ if (value && value.then) {
2862
+ value.then(_settle$2.bind(null, pact, state), _settle$2.bind(null, pact, 2));
2863
+ return;
2864
+ }
2865
+ pact.s = state;
2866
+ pact.v = value;
2867
+ const observer = pact.o;
2868
+ if (observer) {
2869
+ observer(pact);
2870
+ }
2871
+ }
2872
+ }
2873
+
2874
+ /**
2875
+ * Util class to control access to a resource when it can be called in parallel for the same result.
2876
+ * (E.g. getting today coins-fiat rates from some API).
2877
+ */
2878
+ var _Pact$2 = /*#__PURE__*/function () {
2879
+ function _Pact() {}
2880
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
2881
+ var result = new _Pact();
2882
+ var state = this.s;
2883
+ if (state) {
2884
+ var callback = state & 1 ? onFulfilled : onRejected;
2885
+ if (callback) {
2886
+ try {
2887
+ _settle$2(result, 1, callback(this.v));
2888
+ } catch (e) {
2889
+ _settle$2(result, 2, e);
2890
+ }
2891
+ return result;
2892
+ } else {
2893
+ return this;
2894
+ }
2895
+ }
2896
+ this.o = function (_this) {
2897
+ try {
2898
+ var value = _this.v;
2899
+ if (_this.s & 1) {
2900
+ _settle$2(result, 1, onFulfilled ? onFulfilled(value) : value);
2901
+ } else if (onRejected) {
2902
+ _settle$2(result, 1, onRejected(value));
2903
+ } else {
2904
+ _settle$2(result, 2, value);
2905
+ }
2906
+ } catch (e) {
2907
+ _settle$2(result, 2, e);
2908
+ }
2909
+ };
2910
+ return result;
2911
+ };
2912
+ return _Pact;
2913
+ }();
2914
+ function _isSettledPact$2(thenable) {
2915
+ return thenable instanceof _Pact$2 && thenable.s & 1;
2916
+ }
2917
+ function _for$1(test, update, body) {
2918
+ var stage;
2919
+ for (;;) {
2920
+ var shouldContinue = test();
2921
+ if (_isSettledPact$2(shouldContinue)) {
2922
+ shouldContinue = shouldContinue.v;
2923
+ }
2924
+ if (!shouldContinue) {
2925
+ return result;
2926
+ }
2927
+ if (shouldContinue.then) {
2928
+ stage = 0;
2929
+ break;
2930
+ }
2931
+ var result = body();
2932
+ if (result && result.then) {
2933
+ if (_isSettledPact$2(result)) {
2934
+ result = result.s;
2935
+ } else {
2936
+ stage = 1;
2937
+ break;
2938
+ }
2939
+ }
2940
+ if (update) {
2941
+ var updateValue = update();
2942
+ if (updateValue && updateValue.then && !_isSettledPact$2(updateValue)) {
2943
+ stage = 2;
2944
+ break;
2945
+ }
2946
+ }
2947
+ }
2948
+ var pact = new _Pact$2();
2949
+ var reject = _settle$2.bind(null, pact, 2);
2950
+ (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
2951
+ return pact;
2952
+ function _resumeAfterBody(value) {
2953
+ result = value;
2954
+ do {
2955
+ if (update) {
2956
+ updateValue = update();
2957
+ if (updateValue && updateValue.then && !_isSettledPact$2(updateValue)) {
2958
+ updateValue.then(_resumeAfterUpdate).then(void 0, reject);
2959
+ return;
2960
+ }
2961
+ }
2962
+ shouldContinue = test();
2963
+ if (!shouldContinue || _isSettledPact$2(shouldContinue) && !shouldContinue.v) {
2964
+ _settle$2(pact, 1, result);
2965
+ return;
2966
+ }
2967
+ if (shouldContinue.then) {
2968
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
2969
+ return;
2970
+ }
2971
+ result = body();
2972
+ if (_isSettledPact$2(result)) {
2973
+ result = result.v;
2974
+ }
2975
+ } while (!result || !result.then);
2976
+ result.then(_resumeAfterBody).then(void 0, reject);
2977
+ }
2978
+ function _resumeAfterTest(shouldContinue) {
2979
+ if (shouldContinue) {
2980
+ result = body();
2981
+ if (result && result.then) {
2982
+ result.then(_resumeAfterBody).then(void 0, reject);
2983
+ } else {
2984
+ _resumeAfterBody(result);
2985
+ }
2986
+ } else {
2987
+ _settle$2(pact, 1, result);
2988
+ }
2989
+ }
2990
+ function _resumeAfterUpdate() {
2991
+ if (shouldContinue = test()) {
2992
+ if (shouldContinue.then) {
2993
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
2994
+ } else {
2995
+ _resumeAfterTest(shouldContinue);
2996
+ }
2997
+ } else {
2998
+ _settle$2(pact, 1, result);
2999
+ }
3000
+ }
3001
+ }
3002
+ function _catch$5(body, recover) {
3003
+ try {
3004
+ var result = body();
3005
+ } catch (e) {
3006
+ return recover(e);
3007
+ }
3008
+ if (result && result.then) {
3009
+ return result.then(void 0, recover);
3010
+ }
3011
+ return result;
3012
+ }
3013
+ var CacheAndConcurrentRequestsResolver = /*#__PURE__*/function () {
3014
+ /**
3015
+ * @param bio {string} unique identifier for the exact service
3016
+ * @param cache {Cache} cache
3017
+ * @param cacheTtl {number|null} time to live for cache ms. 0 or null means the cache cannot expire
3018
+ * @param [maxCallAttemptsToWaitForAlreadyRunningRequest=100] {number} number of request allowed to do waiting for
3019
+ * result before we fail the original request. Use custom value only if you need to make the attempts count
3020
+ * and polling interval changes.
3021
+ * @param [timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished=1000] {number}
3022
+ * timeout ms for polling for a result. if you change maxCallAttemptsToWaitForAlreadyRunningRequest
3023
+ * then this parameter maybe also require the custom value.
3024
+ * @param [removeExpiredCacheAutomatically=true] {boolean}
3025
+ */
3026
+ function CacheAndConcurrentRequestsResolver(bio, cache, cacheTtl, removeExpiredCacheAutomatically, maxCallAttemptsToWaitForAlreadyRunningRequest, timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished) {
3027
+ if (removeExpiredCacheAutomatically === void 0) {
3028
+ removeExpiredCacheAutomatically = true;
3029
+ }
3030
+ if (maxCallAttemptsToWaitForAlreadyRunningRequest === void 0) {
3031
+ maxCallAttemptsToWaitForAlreadyRunningRequest = 100;
3032
+ }
3033
+ if (timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished === void 0) {
3034
+ timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished = 1000;
3035
+ }
3036
+ if (cacheTtl != null && cacheTtl < timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished * 2) {
3037
+ /*
3038
+ * During the lifetime of this service e.g. if the data is being retrieved slowly we can get
3039
+ * RACE CONDITION when we constantly retrieve data and during retrieval it is expired, so we are trying
3040
+ * to retrieve it again and again.
3041
+ * We have a protection mechanism that we will wait no more than
3042
+ * maxCallAttemptsToWaitForAlreadyRunningRequest * timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished
3043
+ * but this additional check is aimed to reduce potential loading time for some requests.
3044
+ */
3045
+ throw new Error("DEV: Wrong parameters passed to construct " + bio + " - TTL " + cacheTtl + " should be 2 times greater than " + timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished);
3046
+ }
3047
+ this._bio = bio;
3048
+ this._cache = cache;
3049
+ this._cacheTtlMs = cacheTtl != null ? cacheTtl : null;
3050
+ this._maxExecutionTimeMs = maxCallAttemptsToWaitForAlreadyRunningRequest * timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished;
3051
+ this._removeExpiredCacheAutomatically = removeExpiredCacheAutomatically;
3052
+ this._requestsManager = new ManagerOfRequestsToTheSameResource(bio, maxCallAttemptsToWaitForAlreadyRunningRequest, timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished);
3053
+ }
3054
+
3055
+ /**
3056
+ * When using this service this is the major method you should call to get data by cache id.
3057
+ * This method checks is there cached data and ether
3058
+ * - returns you flag that you can start requesting data from the shared resource
3059
+ * - or if there is already started calculation waits until it is finished (removed from this service)
3060
+ * and returns you the retrieved data
3061
+ * - or just returns you the cached data
3062
+ *
3063
+ * 'canStartDataRetrieval' equal true means that the lock was acquired, and you should manually call 'saveCachedData'
3064
+ * if needed and then 'releaseLock' to mark this calculation as finished so other
3065
+ * requesters can take their share of the resource.
3066
+ *
3067
+ * @param cacheId {string}
3068
+ * @return {Promise<({
3069
+ * canStartDataRetrieval: true,
3070
+ * cachedData: any,
3071
+ * lockId: string
3072
+ * }|{
3073
+ * canStartDataRetrieval: false,
3074
+ * cachedData: any
3075
+ * })>}
3076
+ */
3077
+ var _proto = CacheAndConcurrentRequestsResolver.prototype;
3078
+ _proto.getCachedOrWaitForCachedOrAcquireLock = function getCachedOrWaitForCachedOrAcquireLock(cacheId) {
3079
+ try {
3080
+ var _this = this;
3081
+ return Promise.resolve(_catch$5(function () {
3082
+ function _temp2() {
3083
+ var _cached, _cached2;
3084
+ return calculationId ? {
3085
+ canStartDataRetrieval: true,
3086
+ cachedData: (_cached = cached) != null ? _cached : cachedDataBackupIsPresentButExpired,
3087
+ lockId: calculationId
3088
+ } : {
3089
+ canStartDataRetrieval: false,
3090
+ cachedData: (_cached2 = cached) != null ? _cached2 : cachedDataBackupIsPresentButExpired
3091
+ };
3092
+ }
3093
+ var startedAtTimestamp = Date.now();
3094
+ var cached = _this._cache.get(cacheId);
3095
+ var cachedDataBackupIsPresentButExpired = null;
3096
+ if (cached != null && !_this._removeExpiredCacheAutomatically) {
3097
+ var lastUpdateTimestamp = _this._cache.getLastUpdateTimestamp(cacheId);
3098
+ if ((lastUpdateTimestamp != null ? lastUpdateTimestamp : 0) + _this._cacheTtlMs < Date.now()) {
3099
+ /*
3100
+ * Here we are manually clearing 'cached' value retrieved from cache to force the data loading.
3101
+ * But we save its value first to the backup variable to be able to return this value if ongoing
3102
+ * requesting fails.
3103
+ */
3104
+ cachedDataBackupIsPresentButExpired = cached;
3105
+ cached = null;
3106
+ }
3107
+ }
3108
+ var calculationId = null;
3109
+ var isRetrievedCacheExpired = true;
3110
+ var isWaitingForActiveCalculationSucceeded;
3111
+ var weStillHaveSomeTimeToProceedExecution = true;
3112
+ var _temp = _for$1(function () {
3113
+ return calculationId == null && cached == null && !!isRetrievedCacheExpired && !!weStillHaveSomeTimeToProceedExecution;
3114
+ }, void 0, function () {
3115
+ return Promise.resolve(_this._requestsManager.startCalculationOrWaitForActiveToFinish(cacheId)).then(function (result) {
3116
+ calculationId = typeof result === "string" ? result : null;
3117
+ isWaitingForActiveCalculationSucceeded = typeof result === "boolean" ? result : null;
3118
+ cached = _this._cache.get(cacheId);
3119
+ isRetrievedCacheExpired = isWaitingForActiveCalculationSucceeded && cached == null;
3120
+ weStillHaveSomeTimeToProceedExecution = Date.now() - startedAtTimestamp < _this._maxExecutionTimeMs;
3121
+ });
3122
+ });
3123
+ return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
3124
+ }, function (e) {
3125
+ improveAndRethrow(e, _this._bio + ".getCachedOrWaitForCachedOrAcquireLock");
3126
+ }));
3127
+ } catch (e) {
3128
+ return Promise.reject(e);
3129
+ }
3130
+ }
3131
+ /**
3132
+ * Returns just the current cache value for the given id.
3133
+ * Doesn't wait for the active calculation, doesn't acquire lock, just retrieves the current cache as it is.
3134
+ *
3135
+ * @param cacheId {string}
3136
+ * @return {any}
3137
+ */
3138
+ ;
3139
+ _proto.getCached = function getCached(cacheId) {
3140
+ try {
3141
+ return this._cache.get(cacheId);
3142
+ } catch (e) {
3143
+ improveAndRethrow(e, "getCached");
3144
+ }
3145
+ };
3146
+ _proto._getTtl = function _getTtl() {
3147
+ return this._removeExpiredCacheAutomatically ? this._cacheTtlMs : null;
3148
+ }
3149
+
3150
+ /**
3151
+ * Directly acquires the lock despite on cached data availability.
3152
+ * So if this method returns result === true you can start the data retrieval.
3153
+ *
3154
+ * @param cacheId {string}
3155
+ * @return {Promise<{ result: true, lockId: string }|{ result: false }>}
3156
+ */;
3157
+ _proto.acquireLock = function acquireLock(cacheId) {
3158
+ try {
3159
+ var _this2 = this;
3160
+ return Promise.resolve(_catch$5(function () {
3161
+ return Promise.resolve(_this2._requestsManager.acquireLock(cacheId));
3162
+ }, function (e) {
3163
+ improveAndRethrow(e, "acquireLock");
3164
+ }));
3165
+ } catch (e) {
3166
+ return Promise.reject(e);
3167
+ }
3168
+ }
3169
+ /**
3170
+ * This method should be called only if you acquired a lock successfully.
3171
+ *
3172
+ * If the current lock id is not equal to the passed one the passed data will be ignored.
3173
+ * Or you can do the synchronous data merging on your side and pass the
3174
+ * wasDataMergedSynchronouslyWithMostRecentCacheState=true so your data will be stored
3175
+ * despite on the lockId.
3176
+ * WARNING: you should do this only if you are sure you perform the synchronous update.
3177
+ *
3178
+ * @param cacheId {string}
3179
+ * @param lockId {string}
3180
+ * @param data {any}
3181
+ * @param [sessionDependentData=true] {boolean}
3182
+ * @param [wasDataMergedSynchronouslyWithMostRecentCacheState=false]
3183
+ */
3184
+ ;
3185
+ _proto.saveCachedData = function saveCachedData(cacheId, lockId, data, sessionDependentData, wasDataMergedSynchronouslyWithMostRecentCacheState) {
3186
+ if (sessionDependentData === void 0) {
3187
+ sessionDependentData = true;
3188
+ }
3189
+ if (wasDataMergedSynchronouslyWithMostRecentCacheState === void 0) {
3190
+ wasDataMergedSynchronouslyWithMostRecentCacheState = false;
3191
+ }
3192
+ try {
3193
+ if (wasDataMergedSynchronouslyWithMostRecentCacheState || this._requestsManager.isTheLockActiveOne(cacheId, lockId)) {
3194
+ /* We save passed data only if the <caller> has the currently acquired lockId.
3195
+ * If the passed lockId is not the active one it means that other code cleared/stopped the lock
3196
+ * acquired by the <caller> recently due to some urgent/more prior changes.
3197
+ *
3198
+ * But we allow user to pass the 'wasDataMergedSynchronouslyWithMostRecentCacheState' flag
3199
+ * that tells us that the user had taken the most recent cache value and merged his new data
3200
+ * with that cached value (AFTER possibly performing async data retrieval). This means that we
3201
+ * can ignore the fact that his lockId is no more relevant and save the passed data
3202
+ * as it is synchronously merged with the most recent cached data. (Synchronously merged means that
3203
+ * the lost update cannot occur during the merge time as JS execute the synchronous functions\
3204
+ * till the end).
3205
+ */
3206
+ if (sessionDependentData) {
3207
+ this._cache.putSessionDependentData(cacheId, data, this._getTtl());
3208
+ } else {
3209
+ this._cache.put(cacheId, data, this._getTtl());
3210
+ }
3211
+ }
3212
+ } catch (e) {
3213
+ improveAndRethrow(e, this._bio + ".saveCachedData");
3214
+ }
3215
+ }
3216
+
3217
+ /**
3218
+ * Should be called then and only then if you successfully acquired a lock with the lock id.
3219
+ *
3220
+ * @param cacheId {string}
3221
+ * @param lockId {string}
3222
+ */;
3223
+ _proto.releaseLock = function releaseLock(cacheId, lockId) {
3224
+ try {
3225
+ if (this._requestsManager.isTheLockActiveOne(cacheId, lockId)) {
3226
+ this._requestsManager.finishActiveCalculation(cacheId);
3227
+ }
3228
+ } catch (e) {
3229
+ improveAndRethrow(e, this._bio + ".releaseLock");
3230
+ }
3231
+ }
3232
+
3233
+ /**
3234
+ * Actualized currently present cached data by key. Applies the provided function to the cached data.
3235
+ *
3236
+ * @param cacheId {string} id of cache entry
3237
+ * @param synchronousCurrentCacheProcessor (function|null} synchronous function accepting cache entry. Should return
3238
+ * an object in following format:
3239
+ * {
3240
+ * isModified: boolean,
3241
+ * data: any
3242
+ * }
3243
+ * the flag signals whether data was changed during the processing or not
3244
+ * @param [sessionDependent=true] {boolean} whether to mark the cache entry as session-dependent
3245
+ */;
3246
+ _proto.actualizeCachedData = function actualizeCachedData(cacheId, synchronousCurrentCacheProcessor, sessionDependent) {
3247
+ if (sessionDependent === void 0) {
3248
+ sessionDependent = true;
3249
+ }
3250
+ try {
3251
+ var cached = this._cache.get(cacheId);
3252
+ var result = synchronousCurrentCacheProcessor(cached);
3253
+ if (result != null && result.isModified && (result == null ? void 0 : result.data) != null) {
3254
+ if (sessionDependent) {
3255
+ this._cache.putSessionDependentData(cacheId, result == null ? void 0 : result.data, this._getTtl());
3256
+ } else {
3257
+ this._cache.put(cacheId, result == null ? void 0 : result.data, this._getTtl());
3258
+ }
3259
+
3260
+ /* Here we call the lock releasing to ensure the currently active calculation will be ignored.
3261
+ * This is needed to ensure no 'lost update'.
3262
+ * Lost update can occur if we change data in this method and after that some calculation finishes
3263
+ * having the earlier data as its base to calculate its data set result. And the earlier data
3264
+ * has no changes applied inside this method, so we will lose them.
3265
+ *
3266
+ * This is not so good solution: ideally, we should acquire lock before performing any data updating.
3267
+ * But the goal of this method is to provide an instant ability to update the cached data.
3268
+ * And if we start acquiring the lock here the data update can be postponed significantly.
3269
+ * And this kills the desired nature of this method.
3270
+ * So we better lose some data retrieval (means abusing the resource a bit) than lose
3271
+ * the instant update expected after this method execution.
3272
+ */
3273
+ this._requestsManager.finishActiveCalculation(cacheId);
3274
+ }
3275
+ } catch (e) {
3276
+ improveAndRethrow(e, this._bio + ".actualizeCachedData");
3277
+ }
3278
+ };
3279
+ _proto.invalidate = function invalidate(key) {
3280
+ this._cache.invalidate(key);
3281
+ this._requestsManager.finishActiveCalculation(key);
3282
+ };
3283
+ _proto.invalidateContaining = function invalidateContaining(keyPart) {
3284
+ this._cache.invalidateContaining(keyPart);
3285
+ this._requestsManager.finishAllActiveCalculations(keyPart);
3286
+ };
3287
+ _proto.markAsExpiredButDontRemove = function markAsExpiredButDontRemove(key) {
3288
+ if (this._removeExpiredCacheAutomatically) {
3289
+ this._cache.markCacheItemAsExpiredButDontRemove(key, this._cacheTtlMs);
3290
+ } else {
3291
+ this._cache.setLastUpdateTimestamp(key, Date.now() - this._cacheTtlMs - 1);
3292
+ }
3293
+ this._requestsManager.finishAllActiveCalculations(key);
3294
+ };
3295
+ return CacheAndConcurrentRequestsResolver;
3296
+ }();
3297
+ var ManagerOfRequestsToTheSameResource = /*#__PURE__*/function () {
3298
+ /**
3299
+ * @param bio {string} resource-related identifier for logging
3300
+ * @param [maxPollsCount=100] {number} max number of attempts to wait when waiting for a lock acquisition
3301
+ * @param [timeoutDuration=1000] {number} timeout between the polls for a lock acquisition
3302
+ */
3303
+ function ManagerOfRequestsToTheSameResource(bio, maxPollsCount, timeoutDuration) {
3304
+ if (maxPollsCount === void 0) {
3305
+ maxPollsCount = 100;
3306
+ }
3307
+ if (timeoutDuration === void 0) {
3308
+ timeoutDuration = 1000;
3309
+ }
3310
+ this.bio = bio;
3311
+ this.maxPollsCount = maxPollsCount;
3312
+ this.timeoutDuration = timeoutDuration;
3313
+ this._activeCalculationsIds = new Map();
3314
+ this._nextCalculationIds = new Map();
3315
+ }
3316
+
3317
+ /**
3318
+ * If there is no active calculation just creates uuid and returns it.
3319
+ * If there is active calculation waits until it removed from the active calculation uuid variable.
3320
+ *
3321
+ * @param requestHash {string}
3322
+ * @return {Promise<string|boolean>} returns uuid of new active calculation or true if waiting for active
3323
+ * calculation succeed or false if max attempts count exceeded
3324
+ */
3325
+ var _proto2 = ManagerOfRequestsToTheSameResource.prototype;
3326
+ _proto2.startCalculationOrWaitForActiveToFinish = function startCalculationOrWaitForActiveToFinish(requestHash) {
3327
+ try {
3328
+ var _exit;
3329
+ var _this3 = this;
3330
+ var _temp3 = _catch$5(function () {
3331
+ var activeCalculationIdForHash = _this3._activeCalculationsIds.get(requestHash);
3332
+ if (activeCalculationIdForHash == null) {
3333
+ var id = uuid.v4();
3334
+ _this3._activeCalculationsIds.set(requestHash, id);
3335
+ _exit = 1;
3336
+ return id;
3337
+ }
3338
+ return Promise.resolve(_this3._waitForCalculationIdToFinish(requestHash, activeCalculationIdForHash, 0)).then(function (_await$_this3$_waitFo) {
3339
+ _exit = 1;
3340
+ return _await$_this3$_waitFo;
3341
+ });
3342
+ }, function (e) {
3343
+ Logger.logError(e, "startCalculationOrWaitForActiveToFinish_" + _this3.bio);
3344
+ });
3345
+ return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function (_result3) {
3346
+ return _exit ? _result3 : null;
3347
+ }) : _exit ? _temp3 : null);
3348
+ } catch (e) {
3349
+ return Promise.reject(e);
3350
+ }
3351
+ }
3352
+ /**
3353
+ * Acquires lock to the resource by the provided hash.
3354
+ *
3355
+ * @param requestHash {string}
3356
+ * @return {Promise<{ result: true, lockId: string }|{ result: false }>} result is true if the lock is successfully
3357
+ * acquired, false if the max allowed time to wait for acquisition expired or any unexpected error occurs
3358
+ * during the waiting.
3359
+ */
3360
+ ;
3361
+ _proto2.acquireLock = function acquireLock(requestHash) {
3362
+ try {
3363
+ var _this4 = this;
3364
+ return Promise.resolve(_catch$5(function () {
3365
+ var _this4$_nextCalculati;
3366
+ var activeId = _this4._activeCalculationsIds.get(requestHash);
3367
+ var nextId = uuid.v4();
3368
+ if (activeId == null) {
3369
+ _this4._activeCalculationsIds.set(requestHash, nextId);
3370
+ return {
3371
+ result: true,
3372
+ lockId: nextId
3373
+ };
3374
+ }
3375
+ var currentNext = (_this4$_nextCalculati = _this4._nextCalculationIds.get(requestHash)) != null ? _this4$_nextCalculati : [];
3376
+ currentNext.push(nextId);
3377
+ _this4._nextCalculationIds.set(requestHash, currentNext);
3378
+ return Promise.resolve(_this4._waitForCalculationIdToFinish(requestHash, activeId, 0, nextId)).then(function (waitingResult) {
3379
+ return {
3380
+ result: waitingResult,
3381
+ lockId: waitingResult ? nextId : undefined
3382
+ };
3383
+ });
3384
+ }, function (e) {
3385
+ improveAndRethrow(e, "acquireLock");
3386
+ }));
3387
+ } catch (e) {
3388
+ return Promise.reject(e);
3389
+ }
3390
+ }
3391
+ /**
3392
+ * Clears active calculation id.
3393
+ * WARNING: if you forget to call this method the start* one will perform maxPollsCount attempts before finishing
3394
+ * @param requestHash {string} hash of request. Helps to distinct the request for the same resource but
3395
+ * having different request parameters and hold a dedicated calculation id per this hash
3396
+ */
3397
+ ;
3398
+ _proto2.finishActiveCalculation = function finishActiveCalculation(requestHash) {
3399
+ if (requestHash === void 0) {
3400
+ requestHash = "default";
3401
+ }
3402
+ try {
3403
+ var _this$_nextCalculatio;
3404
+ this._activeCalculationsIds["delete"](requestHash);
3405
+ var next = (_this$_nextCalculatio = this._nextCalculationIds.get(requestHash)) != null ? _this$_nextCalculatio : [];
3406
+ if (next.length) {
3407
+ this._activeCalculationsIds.set(requestHash, next[0]);
3408
+ this._nextCalculationIds.set(requestHash, next.slice(1));
3409
+ }
3410
+ } catch (e) {
3411
+ improveAndRethrow(e, "finishActiveCalculation");
3412
+ }
3413
+ };
3414
+ _proto2.finishAllActiveCalculations = function finishAllActiveCalculations(keyPart) {
3415
+ var _this5 = this;
3416
+ if (keyPart === void 0) {
3417
+ keyPart = "";
3418
+ }
3419
+ try {
3420
+ Array.from(this._activeCalculationsIds.keys()).forEach(function (hash) {
3421
+ if (typeof hash === "string" && new RegExp(keyPart).test(hash)) {
3422
+ _this5.finishActiveCalculation(hash);
3423
+ }
3424
+ });
3425
+ } catch (e) {
3426
+ improveAndRethrow(e, "finishAllActiveCalculations");
3427
+ }
3428
+ }
3429
+
3430
+ /**
3431
+ * @param requestHash {string}
3432
+ * @param lockId {string}
3433
+ * @return {boolean}
3434
+ */;
3435
+ _proto2.isTheLockActiveOne = function isTheLockActiveOne(requestHash, lockId) {
3436
+ try {
3437
+ return this._activeCalculationsIds.get(requestHash) === lockId;
3438
+ } catch (e) {
3439
+ improveAndRethrow(e, "isTheLockActiveOne");
3440
+ }
3441
+ }
3442
+
3443
+ /**
3444
+ * @param requestHash {string}
3445
+ * @param activeCalculationId {string|null}
3446
+ * @param [attemptIndex=0] {number}
3447
+ * @param waitForCalculationId {string|null} if you want to wait for an exact id to appear as active then pass this parameter
3448
+ * @return {Promise<boolean>} true
3449
+ * - if the given calculation id is no more an active one
3450
+ * - or it is equal to waitForCalculationId
3451
+ * false
3452
+ * - if waiting period exceeds the max allowed waiting time or unexpected error occurs
3453
+ * @private
3454
+ */;
3455
+ _proto2._waitForCalculationIdToFinish = function _waitForCalculationIdToFinish(requestHash, activeCalculationId, attemptIndex, waitForCalculationId) {
3456
+ if (attemptIndex === void 0) {
3457
+ attemptIndex = 0;
3458
+ }
3459
+ if (waitForCalculationId === void 0) {
3460
+ waitForCalculationId = null;
3461
+ }
3462
+ try {
3463
+ var _this6 = this;
3464
+ try {
3465
+ if (attemptIndex + 1 > _this6.maxPollsCount) {
3466
+ // Max number of polls for active calculation id change is achieved. So we return false.
3467
+ return Promise.resolve(false);
3468
+ }
3469
+ var currentId = _this6._activeCalculationsIds.get(requestHash);
3470
+ if (waitForCalculationId == null ? currentId !== activeCalculationId : currentId === waitForCalculationId) {
3471
+ /* We return true depending on the usage of this function:
3472
+ * 1. if there is calculation id that we should wait for to become an active then we return true only
3473
+ * if this id becomes the active one.
3474
+ *
3475
+ * Theoretically we can fail to wait for the desired calculation id. This can be caused by wrong use of
3476
+ * this service or by any other mistakes/errors. But this waiting function will return false anyway if
3477
+ * the number of polls done exceeds the max allowed.
3478
+ *
3479
+ * 2. if we just wait for the currently active calculation id to be finished then we return true
3480
+ * when we notice that the current active id differs from the original passed into this function.
3481
+ */
3482
+ return Promise.resolve(true);
3483
+ } else {
3484
+ /* The original calculation id is still the active one, so we are scheduling a new attempt to check
3485
+ * whether the active calculation id changed or not in timeoutDuration milliseconds.
3486
+ */
3487
+ var it = _this6;
3488
+ return Promise.resolve(new Promise(function (resolve, reject) {
3489
+ setTimeout(function () {
3490
+ try {
3491
+ resolve(it._waitForCalculationIdToFinish(requestHash, activeCalculationId, attemptIndex + 1));
3492
+ } catch (e) {
3493
+ reject(e);
3494
+ }
3495
+ }, _this6.timeoutDuration);
3496
+ }));
3497
+ }
3498
+ } catch (e) {
3499
+ Logger.logError(e, "_waitForCalculationIdToFinish", "Failed to wait for active calculation id change.");
3500
+ return Promise.resolve(false);
3501
+ }
3502
+ } catch (e) {
3503
+ return Promise.reject(e);
3504
+ }
3505
+ };
3506
+ return ManagerOfRequestsToTheSameResource;
3507
+ }();
3508
+
3509
+ // TODO: [refactoring, low] Consider removing this logic task_id=c360f2af75764bde8badd9ff1cc00d48
3510
+ var ConcurrentCalculationsMetadataHolder = /*#__PURE__*/function () {
3511
+ function ConcurrentCalculationsMetadataHolder() {
3512
+ this._calculations = {};
3513
+ }
3514
+ var _proto = ConcurrentCalculationsMetadataHolder.prototype;
3515
+ _proto.startCalculation = function startCalculation(domain, calculationsHistoryMaxLength) {
3516
+ if (calculationsHistoryMaxLength === void 0) {
3517
+ calculationsHistoryMaxLength = 100;
3518
+ }
3519
+ if (!this._calculations[domain]) {
3520
+ this._calculations[domain] = [];
3521
+ }
3522
+ if (this._calculations[domain].length > calculationsHistoryMaxLength) {
3523
+ this._calculations[domain] = this._calculations[domain].slice(Math.round(calculationsHistoryMaxLength * 0.2));
3524
+ }
3525
+ var newCalculation = {
3526
+ startTimestamp: Date.now(),
3527
+ endTimestamp: null,
3528
+ uuid: uuid.v4()
3529
+ };
3530
+ this._calculations[domain].push(newCalculation);
3531
+ return newCalculation.uuid;
3532
+ };
3533
+ _proto.endCalculation = function endCalculation(domain, uuid, isFailed) {
3534
+ if (isFailed === void 0) {
3535
+ isFailed = false;
3536
+ }
3537
+ try {
3538
+ var _calculation$endTimes, _calculation$startTim, _calculation$uuid;
3539
+ var calculation = this._calculations[domain].find(function (calculation) {
3540
+ return (calculation == null ? void 0 : calculation.uuid) === uuid;
3541
+ });
3542
+ if (calculation) {
3543
+ calculation.endTimestamp = Date.now();
3544
+ calculation.isFiled = isFailed;
3545
+ }
3546
+ var elapsed = ((((_calculation$endTimes = calculation == null ? void 0 : calculation.endTimestamp) != null ? _calculation$endTimes : 0) - ((_calculation$startTim = calculation == null ? void 0 : calculation.startTimestamp) != null ? _calculation$startTim : 0)) / 1000).toFixed(1);
3547
+ Logger.log("endCalculation", elapsed + " ms: " + domain + "." + ((_calculation$uuid = calculation == null ? void 0 : calculation.uuid) != null ? _calculation$uuid : "").slice(0, 7));
3548
+ return calculation;
3549
+ } catch (e) {
3550
+ Logger.logError(e, "endCalculation");
3551
+ }
3552
+ };
3553
+ _proto.isCalculationLate = function isCalculationLate(domain, uuid) {
3554
+ var queue = this._calculations[domain];
3555
+ var analysingCalculation = queue.find(function (item) {
3556
+ return item.uuid === uuid;
3557
+ });
3558
+ return analysingCalculation && !!queue.find(function (calculation) {
3559
+ return calculation.endTimestamp != null && calculation.startTimestamp > analysingCalculation.startTimestamp;
3560
+ });
3561
+ };
3562
+ _proto.printCalculationsWaitingMoreThanSpecifiedSeconds = function printCalculationsWaitingMoreThanSpecifiedSeconds(waitingLastsMs) {
3563
+ var _this = this;
3564
+ if (waitingLastsMs === void 0) {
3565
+ waitingLastsMs = 2000;
3566
+ }
3567
+ var calculations = Object.keys(this._calculations).map(function (domain) {
3568
+ return _this._calculations[domain].map(function (c) {
3569
+ return _extends({}, c, {
3570
+ domain: domain
3571
+ });
3572
+ });
3573
+ }).flat().filter(function (c) {
3574
+ return c.endTimestamp === null && Date.now() - c.startTimestamp > waitingLastsMs;
3575
+ });
3576
+ Logger.log("printCalculationsWaitingMoreThanSpecifiedSeconds", "Calculations waiting more than " + (waitingLastsMs / 1000).toFixed(1) + "s:\n" + calculations.map(function (c) {
3577
+ return c.domain + "." + c.uuid.slice(0, 8) + ": " + (Date.now() - c.startTimestamp) + "\n";
3578
+ }));
3579
+ };
3580
+ return ConcurrentCalculationsMetadataHolder;
3581
+ }();
3582
+ var concurrentCalculationsMetadataHolder = new ConcurrentCalculationsMetadataHolder();
3583
+
3584
+ var ExternalServicesStatsCollector = /*#__PURE__*/function () {
3585
+ function ExternalServicesStatsCollector() {
3586
+ this.stats = new Map();
3587
+ }
3588
+ var _proto = ExternalServicesStatsCollector.prototype;
3589
+ _proto.externalServiceFailed = function externalServiceFailed(serviceUrl, message) {
3590
+ try {
3591
+ var processMessage = function processMessage(stat, errorMessage) {
3592
+ var _stat$errors, _errorMessage;
3593
+ var errors = (_stat$errors = stat.errors) != null ? _stat$errors : {};
3594
+ errorMessage = (_errorMessage = errorMessage) != null ? _errorMessage : "";
3595
+ if (errorMessage.match(/.*network.+error.*/i)) {
3596
+ errors["networkError"] = (errors["networkError"] || 0) + 1;
3597
+ } else if (errorMessage.match(/.*timeout.+exceeded.*/i)) {
3598
+ errors["timeoutExceeded"] = (errors["timeoutExceeded"] || 0) + 1;
3599
+ } else if (errors["other"]) {
3600
+ errors["other"].push(message);
3601
+ } else {
3602
+ errors["other"] = [message];
3603
+ }
3604
+ stat.errors = errors;
3605
+ };
3606
+ if (this.stats.has(serviceUrl)) {
3607
+ var stat = this.stats.get(serviceUrl);
3608
+ stat.callsCount += 1;
3609
+ stat.failsCount += 1;
3610
+ processMessage(stat, message);
3611
+ } else {
3612
+ this.stats.set(serviceUrl, {
3613
+ callsCount: 1,
3614
+ failsCount: 1
3615
+ });
3616
+ processMessage(this.stats.get(serviceUrl), message);
3617
+ }
3618
+ } catch (e) {
3619
+ improveAndRethrow(e, "externalServiceFailed");
3620
+ }
3621
+ };
3622
+ _proto.externalServiceCalledWithoutError = function externalServiceCalledWithoutError(serviceUrl) {
3623
+ try {
3624
+ if (this.stats.has(serviceUrl)) {
3625
+ var stat = this.stats.get(serviceUrl);
3626
+ stat.callsCount += 1;
3627
+ } else {
3628
+ this.stats.set(serviceUrl, {
3629
+ callsCount: 1,
3630
+ failsCount: 0
3631
+ });
3632
+ }
3633
+ } catch (e) {
3634
+ improveAndRethrow(e, "externalServiceCalledWithoutError");
3635
+ }
3636
+ }
3637
+
3638
+ /**
3639
+ * Returns statistics about external services failures.
3640
+ * Provides how many calls were performed and what the percent of failed calls. Also returns errors stat.
3641
+ *
3642
+ * @return {Array<object>} Array of objects of type { failsPerCent: number, calls: number }
3643
+ * sorted by the highest fails percent desc
3644
+ */;
3645
+ _proto.getStats = function getStats() {
3646
+ var _this = this;
3647
+ try {
3648
+ return Array.from(this.stats.keys()).map(function (key) {
3649
+ var _stat$errors2;
3650
+ var stat = _this.stats.get(key);
3651
+ return {
3652
+ url: key,
3653
+ failsPerCent: (stat.failsCount / stat.callsCount * 100).toFixed(2),
3654
+ calls: stat.callsCount,
3655
+ errors: (_stat$errors2 = stat.errors) != null ? _stat$errors2 : []
3656
+ };
3657
+ }).sort(function (s1, s2) {
3658
+ return s1.failsPerCent - s2.failsPerCent;
3659
+ });
3660
+ } catch (e) {
3661
+ Logger.logError(e, "getStats");
3662
+ }
3663
+ };
3664
+ return ExternalServicesStatsCollector;
3665
+ }();
3666
+
3667
+ /**
3668
+ * TODO: [refactoring, critical] update backend copy of this service. Also there is a task to extract this
3669
+ * service and other related to it stuff to dedicated npm package task_id=b008ee5e4a3f42c08c73831c4bb3db4e
3670
+ *
3671
+ * Template service needed to avoid duplication of the same logic when we need to call
3672
+ * external APIs to retrieve some data. The idea is to use several API providers to retrieve the same data. It helps to
3673
+ * improve the reliability of a data retrieval.
3674
+ */
3675
+
3676
+ function _catch$4(body, recover) {
3677
+ try {
3678
+ var result = body();
3679
+ } catch (e) {
3680
+ return recover(e);
3681
+ }
3682
+ if (result && result.then) {
3683
+ return result.then(void 0, recover);
3684
+ }
3685
+ return result;
3686
+ }
3687
+ function _settle$1(pact, state, value) {
3688
+ if (!pact.s) {
3689
+ if (value instanceof _Pact$1) {
3690
+ if (value.s) {
3691
+ if (state & 1) {
3692
+ state = value.s;
3693
+ }
3694
+ value = value.v;
3695
+ } else {
3696
+ value.o = _settle$1.bind(null, pact, state);
3697
+ return;
3698
+ }
3699
+ }
3700
+ if (value && value.then) {
3701
+ value.then(_settle$1.bind(null, pact, state), _settle$1.bind(null, pact, 2));
3702
+ return;
3703
+ }
3704
+ pact.s = state;
3705
+ pact.v = value;
3706
+ var observer = pact.o;
3707
+ if (observer) {
3708
+ observer(pact);
3709
+ }
3710
+ }
3711
+ }
3712
+ var _Pact$1 = /*#__PURE__*/function () {
3713
+ function _Pact() {}
3714
+ _Pact.prototype.then = function (onFulfilled, onRejected) {
3715
+ var result = new _Pact();
3716
+ var state = this.s;
3717
+ if (state) {
3718
+ var callback = state & 1 ? onFulfilled : onRejected;
3719
+ if (callback) {
3720
+ try {
3721
+ _settle$1(result, 1, callback(this.v));
3722
+ } catch (e) {
3723
+ _settle$1(result, 2, e);
3724
+ }
3725
+ return result;
3726
+ } else {
3727
+ return this;
3728
+ }
3729
+ }
3730
+ this.o = function (_this) {
3731
+ try {
3732
+ var value = _this.v;
3733
+ if (_this.s & 1) {
3734
+ _settle$1(result, 1, onFulfilled ? onFulfilled(value) : value);
3735
+ } else if (onRejected) {
3736
+ _settle$1(result, 1, onRejected(value));
3737
+ } else {
3738
+ _settle$1(result, 2, value);
3739
+ }
3740
+ } catch (e) {
3741
+ _settle$1(result, 2, e);
3742
+ }
3743
+ };
3744
+ return result;
3745
+ };
3746
+ return _Pact;
3747
+ }();
3748
+ function _isSettledPact$1(thenable) {
3749
+ return thenable instanceof _Pact$1 && thenable.s & 1;
3750
+ }
3751
+ function _for(test, update, body) {
3752
+ var stage;
3753
+ for (;;) {
3754
+ var shouldContinue = test();
3755
+ if (_isSettledPact$1(shouldContinue)) {
3756
+ shouldContinue = shouldContinue.v;
3757
+ }
3758
+ if (!shouldContinue) {
3759
+ return result;
3760
+ }
3761
+ if (shouldContinue.then) {
3762
+ stage = 0;
3763
+ break;
3764
+ }
3765
+ var result = body();
3766
+ if (result && result.then) {
3767
+ if (_isSettledPact$1(result)) {
3768
+ result = result.s;
3769
+ } else {
3770
+ stage = 1;
3771
+ break;
3772
+ }
3773
+ }
3774
+ if (update) {
3775
+ var updateValue = update();
3776
+ if (updateValue && updateValue.then && !_isSettledPact$1(updateValue)) {
3777
+ stage = 2;
3778
+ break;
3779
+ }
3780
+ }
3781
+ }
3782
+ var pact = new _Pact$1();
3783
+ var reject = _settle$1.bind(null, pact, 2);
3784
+ (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
3785
+ return pact;
3786
+ function _resumeAfterBody(value) {
3787
+ result = value;
3788
+ do {
3789
+ if (update) {
3790
+ updateValue = update();
3791
+ if (updateValue && updateValue.then && !_isSettledPact$1(updateValue)) {
3792
+ updateValue.then(_resumeAfterUpdate).then(void 0, reject);
3793
+ return;
3794
+ }
3795
+ }
3796
+ shouldContinue = test();
3797
+ if (!shouldContinue || _isSettledPact$1(shouldContinue) && !shouldContinue.v) {
3798
+ _settle$1(pact, 1, result);
3799
+ return;
3800
+ }
3801
+ if (shouldContinue.then) {
3802
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
3803
+ return;
3804
+ }
3805
+ result = body();
3806
+ if (_isSettledPact$1(result)) {
3807
+ result = result.v;
3808
+ }
3809
+ } while (!result || !result.then);
3810
+ result.then(_resumeAfterBody).then(void 0, reject);
3811
+ }
3812
+ function _resumeAfterTest(shouldContinue) {
3813
+ if (shouldContinue) {
3814
+ result = body();
3815
+ if (result && result.then) {
3816
+ result.then(_resumeAfterBody).then(void 0, reject);
3817
+ } else {
3818
+ _resumeAfterBody(result);
3819
+ }
3820
+ } else {
3821
+ _settle$1(pact, 1, result);
3822
+ }
3823
+ }
3824
+ function _resumeAfterUpdate() {
3825
+ if (shouldContinue = test()) {
3826
+ if (shouldContinue.then) {
3827
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
3828
+ } else {
3829
+ _resumeAfterTest(shouldContinue);
3830
+ }
3831
+ } else {
3832
+ _settle$1(pact, 1, result);
3833
+ }
3834
+ }
3835
+ }
3836
+ function _finallyRethrows$1(body, finalizer) {
3837
+ try {
3838
+ var result = body();
3839
+ } catch (e) {
3840
+ return finalizer(true, e);
3841
+ }
3842
+ if (result && result.then) {
3843
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
3844
+ }
3845
+ return finalizer(false, result);
3846
+ }
3847
+ function _do(body, test) {
3848
+ var awaitBody;
3849
+ do {
3850
+ var result = body();
3851
+ if (result && result.then) {
3852
+ if (_isSettledPact$1(result)) {
3853
+ result = result.v;
3854
+ } else {
3855
+ awaitBody = true;
3856
+ break;
3857
+ }
3858
+ }
3859
+ var shouldContinue = test();
3860
+ if (_isSettledPact$1(shouldContinue)) {
3861
+ shouldContinue = shouldContinue.v;
3862
+ }
3863
+ if (!shouldContinue) {
3864
+ return result;
3865
+ }
3866
+ } while (!shouldContinue.then);
3867
+ var pact = new _Pact$1();
3868
+ var reject = _settle$1.bind(null, pact, 2);
3869
+ (awaitBody ? result.then(_resumeAfterBody) : shouldContinue.then(_resumeAfterTest)).then(void 0, reject);
3870
+ return pact;
3871
+ function _resumeAfterBody(value) {
3872
+ result = value;
3873
+ for (;;) {
3874
+ shouldContinue = test();
3875
+ if (_isSettledPact$1(shouldContinue)) {
3876
+ shouldContinue = shouldContinue.v;
3877
+ }
3878
+ if (!shouldContinue) {
3879
+ break;
3880
+ }
3881
+ if (shouldContinue.then) {
3882
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
3883
+ return;
3884
+ }
3885
+ result = body();
3886
+ if (result && result.then) {
3887
+ if (_isSettledPact$1(result)) {
3888
+ result = result.v;
3889
+ } else {
3890
+ result.then(_resumeAfterBody).then(void 0, reject);
3891
+ return;
3892
+ }
3893
+ }
3894
+ }
3895
+ _settle$1(pact, 1, result);
3896
+ }
3897
+ function _resumeAfterTest(shouldContinue) {
3898
+ if (shouldContinue) {
3899
+ do {
3900
+ result = body();
3901
+ if (result && result.then) {
3902
+ if (_isSettledPact$1(result)) {
3903
+ result = result.v;
3904
+ } else {
3905
+ result.then(_resumeAfterBody).then(void 0, reject);
3906
+ return;
3907
+ }
3908
+ }
3909
+ shouldContinue = test();
3910
+ if (_isSettledPact$1(shouldContinue)) {
3911
+ shouldContinue = shouldContinue.v;
3912
+ }
3913
+ if (!shouldContinue) {
3914
+ _settle$1(pact, 1, result);
3915
+ return;
3916
+ }
3917
+ } while (!shouldContinue.then);
3918
+ shouldContinue.then(_resumeAfterTest).then(void 0, reject);
3919
+ } else {
3920
+ _settle$1(pact, 1, result);
3921
+ }
3922
+ }
3923
+ }
3924
+ function _forTo$1(array, body, check) {
3925
+ var i = -1,
3926
+ pact,
3927
+ reject;
3928
+ function _cycle(result) {
3929
+ try {
3930
+ while (++i < array.length && (!check || !check())) {
3931
+ result = body(i);
3932
+ if (result && result.then) {
3933
+ if (_isSettledPact$1(result)) {
3934
+ result = result.v;
3935
+ } else {
3936
+ result.then(_cycle, reject || (reject = _settle$1.bind(null, pact = new _Pact$1(), 2)));
3937
+ return;
3938
+ }
3939
+ }
3940
+ }
3941
+ if (pact) {
3942
+ _settle$1(pact, 1, result);
3943
+ } else {
3944
+ pact = result;
3945
+ }
3946
+ } catch (e) {
3947
+ _settle$1(pact || (pact = new _Pact$1()), 2, e);
3948
+ }
3949
+ }
3950
+ _cycle();
3951
+ return pact;
3952
+ }
3953
+ var RobustExternalAPICallerService = /*#__PURE__*/function () {
3954
+ RobustExternalAPICallerService.getStats = function getStats() {
3955
+ this.statsCollector.getStats();
3956
+ }
3957
+
3958
+ /**
3959
+ * @param bio {string} service name for logging
3960
+ * @param providersData {ExternalApiProvider[]} array of providers
3961
+ * @param [logger] {function} function to be used for logging
3962
+ */;
3963
+ function RobustExternalAPICallerService(bio, providersData, logger) {
3964
+ providersData.forEach(function (provider) {
3965
+ if (!provider.endpoint && provider.endpoint !== "" || !provider.httpMethod) {
3966
+ throw new Error("Wrong format of providers data for: " + JSON.stringify(provider));
3967
+ }
3968
+ });
3969
+
3970
+ // We add niceFactor - just number to order the providers array by. It is helpful to call
3971
+ // less robust APIs only if more robust fails
3972
+ this.providers = providersData;
3973
+ providersData.forEach(function (provider) {
3974
+ return provider.resetNiceFactor();
3975
+ });
3976
+ this.bio = bio;
3977
+ this._logger = Logger.logError;
3978
+ }
3979
+ var _proto = RobustExternalAPICallerService.prototype;
3980
+ /**
3981
+ * Performs data retrieval from external APIs. Tries providers till the data is retrieved.
3982
+ *
3983
+ * @param parametersValues {array} array of values of the parameters for URL query string [and/or body]
3984
+ * @param timeoutMS {number} http timeout to wait for response. If provider has its specific timeout value then it is used
3985
+ * @param [cancelToken] {object|undefined} axios token to force-cancel requests from high-level code
3986
+ * @param [attemptsCount] {number|undefined} number of attempts to be performed
3987
+ * @param [doNotFailForNowData] {boolean|undefined} pass true if you do not want us to throw an error if we retrieved null data from all the providers
3988
+ * @return {Promise<any>} resolving to retrieved data (or array of results if specific provider requires
3989
+ * several requests. NOTE: we flatten nested arrays - results of each separate request done for the specific provider)
3990
+ * @throws Error if requests to all providers are failed
3991
+ */
3992
+ _proto.callExternalAPI = function callExternalAPI(parametersValues, timeoutMS, cancelToken, attemptsCount, doNotFailForNowData) {
3993
+ if (parametersValues === void 0) {
3994
+ parametersValues = [];
3995
+ }
3996
+ if (timeoutMS === void 0) {
3997
+ timeoutMS = 3500;
3998
+ }
3999
+ if (cancelToken === void 0) {
4000
+ cancelToken = null;
4001
+ }
4002
+ if (attemptsCount === void 0) {
4003
+ attemptsCount = 1;
4004
+ }
4005
+ if (doNotFailForNowData === void 0) {
4006
+ doNotFailForNowData = false;
4007
+ }
4008
+ try {
4009
+ var _this = this;
4010
+ var result;
4011
+ var calculationUuid = concurrentCalculationsMetadataHolder.startCalculation(_this.bio);
4012
+ return Promise.resolve(_finallyRethrows$1(function () {
4013
+ return _catch$4(function () {
4014
+ function _temp5() {
4015
+ var _result2, _result3;
4016
+ if (((_result2 = result) == null ? void 0 : _result2.data) == null) {
4017
+ // TODO: [feature, moderate] looks like we should not fail for null data as it is strange - the provider will fail when processing data internally
4018
+ var error = new Error("Failed to retrieve data. It means all attempts have been failed. DEV: add more attempts to this data retrieval");
4019
+ if (!doNotFailForNowData) {
4020
+ throw error;
4021
+ } else {
4022
+ _this._logger(error, _this.bio + ".callExternalAPI");
4023
+ }
4024
+ }
4025
+ return (_result3 = result) == null ? void 0 : _result3.data;
4026
+ }
4027
+ var i = 0;
4028
+ var _temp4 = _for(function () {
4029
+ var _result4, _result5;
4030
+ return (i < attemptsCount || !!((_result4 = result) != null && _result4.shouldBeForceRetried)) && ((_result5 = result) == null ? void 0 : _result5.data) == null;
4031
+ }, function () {
4032
+ return ++i;
4033
+ }, function () {
4034
+ /**
4035
+ * We use rpsFactor to improve re-attempting to call the providers if the last attempt resulted with
4036
+ * the fail due to abused RPSes of some (most part of) providers.
4037
+ * The _performCallAttempt in such a case will return increased rpsFactor inside the result object.
4038
+ */
4039
+ var rpsFactor = result ? result.rpsFactor : RobustExternalAPICallerService.defaultRPSFactor;
4040
+ result = null;
4041
+ var _temp3 = _catch$4(function () {
4042
+ function _temp2() {
4043
+ var _result$errors;
4044
+ if ((_result$errors = result.errors) != null && _result$errors.length) {
4045
+ var errors = result.errors;
4046
+ _this._logger(new Error("Failed at attempt " + i + ". " + errors.length + " errors. Messages: " + safeStringify(errors.map(function (error) {
4047
+ return error.message;
4048
+ })) + ": " + safeStringify(errors) + "."), _this.bio + ".callExternalAPI", "", true);
4049
+ }
4050
+ }
4051
+ var _temp = function (_result6) {
4052
+ if (i === 0 && !((_result6 = result) != null && _result6.shouldBeForceRetried)) {
4053
+ return Promise.resolve(_this._performCallAttempt(parametersValues, timeoutMS, cancelToken, rpsFactor, doNotFailForNowData)).then(function (_this$_performCallAtt) {
4054
+ result = _this$_performCallAtt;
4055
+ });
4056
+ } else {
4057
+ var maxRps = Math.max.apply(Math, _this.providers.map(function (provider) {
4058
+ var _provider$getRps;
4059
+ return (_provider$getRps = provider.getRps()) != null ? _provider$getRps : 0;
4060
+ }));
4061
+ var waitingTimeMs = maxRps ? 1000 / (maxRps / rpsFactor) : 0;
4062
+ return Promise.resolve(new Promise(function (resolve, reject) {
4063
+ setTimeout(function () {
4064
+ try {
4065
+ var _temp6 = _catch$4(function () {
4066
+ return Promise.resolve(_this._performCallAttempt(parametersValues, timeoutMS, cancelToken, rpsFactor, doNotFailForNowData)).then(function (_this$_performCallAtt2) {
4067
+ resolve(_this$_performCallAtt2);
4068
+ });
4069
+ }, function (e) {
4070
+ reject(e);
4071
+ });
4072
+ return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(function () {}) : void 0);
4073
+ } catch (e) {
4074
+ return Promise.reject(e);
4075
+ }
4076
+ }, waitingTimeMs);
4077
+ })).then(function (_Promise) {
4078
+ result = _Promise;
4079
+ });
4080
+ }
4081
+ }();
4082
+ return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
4083
+ }, function (e) {
4084
+ _this._logger(e, _this.bio + ".callExternalAPI", "Failed to perform external providers calling");
4085
+ });
4086
+ if (_temp3 && _temp3.then) return _temp3.then(function () {});
4087
+ });
4088
+ return _temp4 && _temp4.then ? _temp4.then(_temp5) : _temp5(_temp4);
4089
+ }, function (e) {
4090
+ improveAndRethrow(e, _this.bio + ".callExternalAPI");
4091
+ });
4092
+ }, function (_wasThrown, _result) {
4093
+ concurrentCalculationsMetadataHolder.endCalculation(_this.bio, calculationUuid);
4094
+ if (_wasThrown) throw _result;
4095
+ return _result;
4096
+ }));
4097
+ } catch (e) {
4098
+ return Promise.reject(e);
4099
+ }
4100
+ };
4101
+ _proto._performCallAttempt = function _performCallAttempt(parametersValues, timeoutMS, cancelToken, rpsFactor, doNotFailForNowData) {
4102
+ try {
4103
+ var _temp15 = function _temp15() {
4104
+ var _data;
4105
+ // If we are declining more than 50% of providers (by exceeding RPS) then we note that it better to retry the whole process of providers requesting
4106
+ var shouldBeForceRetried = data == null && countOfRequestsDeclinedByRps > Math.floor(providers.length * 0.5);
4107
+ var rpsMultiplier = shouldBeForceRetried ? RobustExternalAPICallerService.rpsMultiplier : 1;
4108
+ return {
4109
+ data: (_data = data) != null ? _data : null,
4110
+ shouldBeForceRetried: shouldBeForceRetried,
4111
+ rpsFactor: rpsFactor * rpsMultiplier,
4112
+ errors: errors
4113
+ };
4114
+ };
4115
+ var _this2 = this;
4116
+ var providers = _this2._reorderProvidersByNiceFactor();
4117
+ var data = undefined,
4118
+ providerIndex = 0,
4119
+ countOfRequestsDeclinedByRps = 0,
4120
+ errors = [];
4121
+ var _temp14 = _for(function () {
4122
+ return !data && providerIndex < providers.length;
4123
+ }, void 0, function () {
4124
+ var provider = providers[providerIndex];
4125
+ if (provider.isRpsExceeded()) {
4126
+ /**
4127
+ * Current provider's RPS is exceeded, so we try next provider. Also, we count such cases to make
4128
+ * a decision about the force-retry need.
4129
+ */
4130
+ ++providerIndex;
4131
+ ++countOfRequestsDeclinedByRps;
4132
+ return;
4133
+ }
4134
+ var _temp13 = _finallyRethrows$1(function () {
4135
+ return _catch$4(function () {
4136
+ var _provider$specificHea;
4137
+ function _temp12() {
4138
+ if (iterationsData.length) {
4139
+ if (httpMethods.length > 1) {
4140
+ data = provider.incorporateIterationsData(iterationsData);
4141
+ } else {
4142
+ data = iterationsData[0];
4143
+ }
4144
+ } else if (!doNotFailForNowData) {
4145
+ RobustExternalAPICallerService.statsCollector.externalServiceFailed(provider.getApiGroupId(), "Response data was null for some reason");
4146
+ punishProvider(provider);
4147
+ }
4148
+ }
4149
+ var axiosConfig = _extends({}, cancelToken ? {
4150
+ cancelToken: cancelToken
4151
+ } : {}, {
4152
+ timeout: provider.timeout || timeoutMS,
4153
+ headers: (_provider$specificHea = provider.specificHeaders) != null ? _provider$specificHea : {}
4154
+ });
4155
+ var httpMethods = Array.isArray(provider.httpMethod) ? provider.httpMethod : [provider.httpMethod];
4156
+ var iterationsData = [];
4157
+ var _temp11 = _forTo$1(httpMethods, function (subRequestIndex) {
4158
+ function _temp10() {
4159
+ var responsesDataForPages = responsesForPages.map(function (response) {
4160
+ return provider.getDataByResponse(response, parametersValues, subRequestIndex, iterationsData);
4161
+ });
4162
+ var allData = responsesDataForPages;
4163
+ if (Array.isArray(responsesDataForPages[0])) {
4164
+ allData = responsesDataForPages.flat();
4165
+ } else if (responsesDataForPages.length === 1) {
4166
+ allData = responsesDataForPages[0];
4167
+ }
4168
+ iterationsData.push(allData);
4169
+ }
4170
+ var query = provider.composeQueryString(parametersValues, subRequestIndex);
4171
+ var endpoint = "" + provider.endpoint + query;
4172
+ var axiosParams = [endpoint, axiosConfig];
4173
+ if (["post", "put", "patch"].find(function (method) {
4174
+ return method === httpMethods[subRequestIndex];
4175
+ })) {
4176
+ var _provider$composeBody;
4177
+ var body = (_provider$composeBody = provider.composeBody(parametersValues, subRequestIndex)) != null ? _provider$composeBody : null;
4178
+ axiosParams.splice(1, 0, body);
4179
+ }
4180
+ var pageNumber = 0;
4181
+ var responsesForPages = [];
4182
+ var hasNextPage = provider.doesSupportPagination();
4183
+ var _temp9 = _do(function () {
4184
+ function _temp8() {
4185
+ if (hasNextPage) {
4186
+ hasNextPage = !provider.checkWhetherResponseIsForLastPage(responsesForPages[pageNumber - 1], responsesForPages[pageNumber], pageNumber, subRequestIndex);
4187
+ }
4188
+ pageNumber++;
4189
+ }
4190
+ var _temp7 = function () {
4191
+ if (subRequestIndex === 0 && pageNumber === 0) {
4192
+ provider.actualizeLastCalledTimestamp();
4193
+ return Promise.resolve(AxiosAdapter.call.apply(AxiosAdapter, [httpMethods[subRequestIndex]].concat(axiosParams))).then(function (_AxiosAdapter$call) {
4194
+ responsesForPages[pageNumber] = _AxiosAdapter$call;
4195
+ RobustExternalAPICallerService.statsCollector.externalServiceCalledWithoutError(provider.getApiGroupId());
4196
+ });
4197
+ } else {
4198
+ if (pageNumber > 0) {
4199
+ var actualizedParams = provider.changeQueryParametersForPageNumber(parametersValues, responsesForPages[pageNumber - 1], pageNumber, subRequestIndex);
4200
+ var _query = provider.composeQueryString(actualizedParams, subRequestIndex);
4201
+ axiosParams[0] = "" + provider.endpoint + _query;
4202
+ }
4203
+ /**
4204
+ * For second and more request we postpone each request to not exceed RPS
4205
+ * of current provider. We use rpsFactor to dynamically increase the rps to avoid
4206
+ * too frequent calls if we continue failing to retrieve the data due to RPS exceeding.
4207
+ * TODO: [dev] test RPS factor logic (units or integration)
4208
+ */
4209
+
4210
+ var waitingTimeMS = provider.getRps() ? 1000 / (provider.getRps() / rpsFactor) : 0;
4211
+ var postponeUntilRpsExceeded = function postponeUntilRpsExceeded(recursionLevel) {
4212
+ if (recursionLevel === void 0) {
4213
+ recursionLevel = 0;
4214
+ }
4215
+ try {
4216
+ return Promise.resolve(postponeExecution(function () {
4217
+ try {
4218
+ var _temp17 = function _temp17(_result8) {
4219
+ if (_exit) return _result8;
4220
+ provider.actualizeLastCalledTimestamp();
4221
+ return Promise.resolve(AxiosAdapter.call.apply(AxiosAdapter, [httpMethods[subRequestIndex]].concat(axiosParams)));
4222
+ };
4223
+ var _exit;
4224
+ var maxCountOfPostponingAttempts = 2;
4225
+ var _temp16 = function () {
4226
+ if (provider.isRpsExceeded() && recursionLevel < maxCountOfPostponingAttempts) {
4227
+ return Promise.resolve(postponeUntilRpsExceeded(recursionLevel + 1)).then(function (_await$postponeUntilR) {
4228
+ _exit = 1;
4229
+ return _await$postponeUntilR;
4230
+ });
4231
+ }
4232
+ }();
4233
+ return Promise.resolve(_temp16 && _temp16.then ? _temp16.then(_temp17) : _temp17(_temp16));
4234
+ } catch (e) {
4235
+ return Promise.reject(e);
4236
+ }
4237
+ }, waitingTimeMS));
4238
+ } catch (e) {
4239
+ return Promise.reject(e);
4240
+ }
4241
+ };
4242
+ return Promise.resolve(postponeUntilRpsExceeded()).then(function (_postponeUntilRpsExce) {
4243
+ responsesForPages[pageNumber] = _postponeUntilRpsExce;
4244
+ });
4245
+ }
4246
+ }();
4247
+ return _temp7 && _temp7.then ? _temp7.then(_temp8) : _temp8(_temp7);
4248
+ }, function () {
4249
+ return !!hasNextPage;
4250
+ });
4251
+ return _temp9 && _temp9.then ? _temp9.then(_temp10) : _temp10(_temp9);
4252
+ });
4253
+ return _temp11 && _temp11.then ? _temp11.then(_temp12) : _temp12(_temp11);
4254
+ }, function (e) {
4255
+ punishProvider(provider);
4256
+ RobustExternalAPICallerService.statsCollector.externalServiceFailed(provider.getApiGroupId(), e == null ? void 0 : e.message);
4257
+ errors.push(e);
4258
+ });
4259
+ }, function (_wasThrown2, _result7) {
4260
+ providerIndex++;
4261
+ if (_wasThrown2) throw _result7;
4262
+ return _result7;
4263
+ });
4264
+ if (_temp13 && _temp13.then) return _temp13.then(function () {});
4265
+ });
4266
+ return Promise.resolve(_temp14 && _temp14.then ? _temp14.then(_temp15) : _temp15(_temp14));
4267
+ } catch (e) {
4268
+ return Promise.reject(e);
4269
+ }
4270
+ };
4271
+ _proto._reorderProvidersByNiceFactor = function _reorderProvidersByNiceFactor() {
4272
+ var providersCopy = [].concat(this.providers);
4273
+ return providersCopy.sort(function (p1, p2) {
4274
+ return p2.niceFactor - p1.niceFactor;
4275
+ });
4276
+ };
4277
+ return RobustExternalAPICallerService;
4278
+ }();
4279
+ RobustExternalAPICallerService.statsCollector = new ExternalServicesStatsCollector();
4280
+ RobustExternalAPICallerService.defaultRPSFactor = 1;
4281
+ RobustExternalAPICallerService.rpsMultiplier = 1.05;
4282
+ function punishProvider(provider) {
4283
+ provider.niceFactor = provider.niceFactor - 1;
4284
+ }
4285
+
4286
+ /**
4287
+ * Extended edit of RobustExternalApiCallerService supporting cache and management of concurrent requests
4288
+ * to the same resource.
4289
+ * TODO: [tests, critical] Massively used logic
4290
+ */
4291
+
4292
+ function _catch$3(body, recover) {
4293
+ try {
4294
+ var result = body();
4295
+ } catch (e) {
4296
+ return recover(e);
4297
+ }
4298
+ if (result && result.then) {
4299
+ return result.then(void 0, recover);
4300
+ }
4301
+ return result;
4302
+ }
4303
+ function _finallyRethrows(body, finalizer) {
4304
+ try {
4305
+ var result = body();
4306
+ } catch (e) {
4307
+ return finalizer(true, e);
4308
+ }
4309
+ if (result && result.then) {
4310
+ return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
4311
+ }
4312
+ return finalizer(false, result);
4313
+ }
4314
+ var CachedRobustExternalApiCallerService = /*#__PURE__*/function () {
4315
+ /**
4316
+ * @param bio {string} unique service identifier
4317
+ * @param cache {Cache} cache instance
4318
+ * @param providersData {ExternalApiProvider[]} array of providers
4319
+ * @param [cacheTtlMs=10000] {number} time to live for cache ms
4320
+ * @param [maxCallAttemptsToWaitForAlreadyRunningRequest=50] {number} see details in CacheAndConcurrentRequestsResolver
4321
+ * @param [timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished=3000] {number} see details in CacheAndConcurrentRequestsResolver
4322
+ * @param [removeExpiredCacheAutomatically=true] {boolean} whether to remove cached data automatically when ttl exceeds
4323
+ * @param [mergeCachedAndNewlyRetrievedData=null] {function} function accepting cached data, newly retrieved data and id field name for list items
4324
+ * and merging them. use if needed
4325
+ */
4326
+ function CachedRobustExternalApiCallerService(bio, cache, providersData, cacheTtlMs, removeExpiredCacheAutomatically, mergeCachedAndNewlyRetrievedData, maxCallAttemptsToWaitForAlreadyRunningRequest, timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished) {
4327
+ if (cacheTtlMs === void 0) {
4328
+ cacheTtlMs = 10000;
4329
+ }
4330
+ if (removeExpiredCacheAutomatically === void 0) {
4331
+ removeExpiredCacheAutomatically = true;
4332
+ }
4333
+ if (mergeCachedAndNewlyRetrievedData === void 0) {
4334
+ mergeCachedAndNewlyRetrievedData = null;
4335
+ }
4336
+ if (maxCallAttemptsToWaitForAlreadyRunningRequest === void 0) {
4337
+ maxCallAttemptsToWaitForAlreadyRunningRequest = 100;
4338
+ }
4339
+ if (timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished === void 0) {
4340
+ timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished = 1000;
4341
+ }
4342
+ this._provider = new RobustExternalAPICallerService("cached_" + bio, providersData, Logger.logError);
4343
+ this._cacheTtlMs = cacheTtlMs;
4344
+ this._cahceAndRequestsResolver = new CacheAndConcurrentRequestsResolver(bio, cache, cacheTtlMs, removeExpiredCacheAutomatically, maxCallAttemptsToWaitForAlreadyRunningRequest, timeoutBetweenAttemptsToCheckWhetherAlreadyRunningRequestFinished);
4345
+ this._cahceIds = [];
4346
+ this._mergeCachedAndNewlyRetrievedData = mergeCachedAndNewlyRetrievedData;
4347
+ }
4348
+
4349
+ /**
4350
+ * Calls the external API or returns data from cache. Just waits if the same data already requested.
4351
+ *
4352
+ * @param parametersValues {array} array of values of the parameters for URL query string [and/or body]
4353
+ * @param timeoutMS {number} http timeout to wait for response. If provider has its specific timeout value then it is used
4354
+ * @param [cancelToken] {object|undefined} axios token to force-cancel requests from high-level code
4355
+ * @param [attemptsCount] {number|undefined} number of attempts to be performed
4356
+ * @param [customHashFunctionForParams] {function|undefined} function without params calculating the hash to be
4357
+ * added to bio of the service to compose a unique parameters-specific cache id
4358
+ * @param [doNotFailForNowData] {boolean|undefined} pass true if you do not want us to throw an error if we retrieved null data from all the providers
4359
+ * @return {Promise<any>} resolving to retrieved data (or array of results if specific provider requires
4360
+ * several requests. NOTE: we flatten nested arrays - results of each separate request done for the specific provider)
4361
+ * @throws Error if requests to all providers are failed
4362
+ */
4363
+ var _proto = CachedRobustExternalApiCallerService.prototype;
4364
+ _proto.callExternalAPICached = function callExternalAPICached(parametersValues, timeoutMS, cancelToken, attemptsCount, customHashFunctionForParams, doNotFailForNowData) {
4365
+ if (parametersValues === void 0) {
4366
+ parametersValues = [];
4367
+ }
4368
+ if (timeoutMS === void 0) {
4369
+ timeoutMS = 3500;
4370
+ }
4371
+ if (cancelToken === void 0) {
4372
+ cancelToken = null;
4373
+ }
4374
+ if (attemptsCount === void 0) {
4375
+ attemptsCount = 1;
4376
+ }
4377
+ if (customHashFunctionForParams === void 0) {
4378
+ customHashFunctionForParams = null;
4379
+ }
4380
+ if (doNotFailForNowData === void 0) {
4381
+ doNotFailForNowData = false;
4382
+ }
4383
+ try {
4384
+ var _this = this;
4385
+ var loggerSource = _this._provider.bio + ".callExternalAPICached";
4386
+ var cacheId;
4387
+ var result;
4388
+ return Promise.resolve(_finallyRethrows(function () {
4389
+ return _catch$3(function () {
4390
+ cacheId = _this._calculateCacheId(parametersValues, customHashFunctionForParams);
4391
+ return Promise.resolve(_this._cahceAndRequestsResolver.getCachedOrWaitForCachedOrAcquireLock(cacheId)).then(function (_this$_cahceAndReques) {
4392
+ var _result2, _result4;
4393
+ result = _this$_cahceAndReques;
4394
+ return (_result2 = result) != null && _result2.canStartDataRetrieval ? Promise.resolve(_this._provider.callExternalAPI(parametersValues, timeoutMS, cancelToken, attemptsCount, doNotFailForNowData)).then(function (data) {
4395
+ var canPerformMerge = typeof _this._mergeCachedAndNewlyRetrievedData === "function";
4396
+ if (canPerformMerge) {
4397
+ var mostRecentCached = _this._cahceAndRequestsResolver.getCached(cacheId);
4398
+ data = _this._mergeCachedAndNewlyRetrievedData(mostRecentCached, data, parametersValues);
4399
+ }
4400
+ if (data != null) {
4401
+ var _result3;
4402
+ _this._cahceAndRequestsResolver.saveCachedData(cacheId, (_result3 = result) == null ? void 0 : _result3.lockId, data, true, canPerformMerge);
4403
+ _this._cahceIds.indexOf(cacheId) < 0 && _this._cahceIds.push(cacheId);
4404
+ }
4405
+ return data;
4406
+ }) : (_result4 = result) == null ? void 0 : _result4.cachedData;
4407
+ });
4408
+ }, function (e) {
4409
+ improveAndRethrow(e, loggerSource);
4410
+ });
4411
+ }, function (_wasThrown, _result) {
4412
+ var _result5;
4413
+ _this._cahceAndRequestsResolver.releaseLock(cacheId, (_result5 = result) == null ? void 0 : _result5.lockId);
4414
+ if (_wasThrown) throw _result;
4415
+ return _result;
4416
+ }));
4417
+ } catch (e) {
4418
+ return Promise.reject(e);
4419
+ }
4420
+ };
4421
+ _proto.invalidateCaches = function invalidateCaches() {
4422
+ var _this2 = this;
4423
+ this._cahceIds.forEach(function (key) {
4424
+ return _this2._cahceAndRequestsResolver.invalidate(key);
4425
+ });
4426
+ };
4427
+ _proto.actualizeCachedData = function actualizeCachedData(params, synchronousCurrentCacheProcessor, customHashFunctionForParams, sessionDependent, actualizedAtTimestamp) {
4428
+ if (customHashFunctionForParams === void 0) {
4429
+ customHashFunctionForParams = null;
4430
+ }
4431
+ if (sessionDependent === void 0) {
4432
+ sessionDependent = true;
4433
+ }
4434
+ var cacheId = this._calculateCacheId(params, customHashFunctionForParams);
4435
+ this._cahceAndRequestsResolver.actualizeCachedData(cacheId, synchronousCurrentCacheProcessor, sessionDependent);
4436
+ };
4437
+ _proto.markCacheAsExpiredButDontRemove = function markCacheAsExpiredButDontRemove(parametersValues, customHashFunctionForParams) {
4438
+ try {
4439
+ this._cahceAndRequestsResolver.markAsExpiredButDontRemove(this._calculateCacheId(parametersValues, customHashFunctionForParams));
4440
+ } catch (e) {
4441
+ improveAndRethrow(e, "markCacheAsExpiredButDontRemove");
4442
+ }
4443
+ };
4444
+ _proto._calculateCacheId = function _calculateCacheId(parametersValues, customHashFunctionForParams) {
4445
+ if (customHashFunctionForParams === void 0) {
4446
+ customHashFunctionForParams = null;
4447
+ }
4448
+ try {
4449
+ var hash = typeof customHashFunctionForParams === "function" ? customHashFunctionForParams(parametersValues) : !parametersValues ? "" : new Hashes__default["default"].SHA512().hex(safeStringify(parametersValues));
4450
+ return this._provider.bio + "-" + hash;
4451
+ } catch (e) {
4452
+ improveAndRethrow(e, this._provider.bio + "_calculateCacheId");
4453
+ }
4454
+ };
4455
+ return CachedRobustExternalApiCallerService;
4456
+ }();
4457
+
4458
+ /**
4459
+ * Utils class needed to perform cancelling of axios request inside some process.
4460
+ * Provides cancel state and axios token for HTTP requests
4461
+ */
4462
+ var CancelProcessing = /*#__PURE__*/function () {
4463
+ function CancelProcessing() {
4464
+ this._cancelToken = axios__default["default"].CancelToken.source();
4465
+ this._isCanceled = false;
4466
+ }
4467
+ var _proto = CancelProcessing.prototype;
4468
+ _proto.cancel = function cancel() {
4469
+ this._isCanceled = true;
4470
+ this._cancelToken.cancel();
4471
+ };
4472
+ _proto.isCanceled = function isCanceled() {
4473
+ return this._isCanceled;
4474
+ };
4475
+ _proto.getToken = function getToken() {
4476
+ return this._cancelToken.token;
4477
+ };
4478
+ CancelProcessing.instance = function instance() {
4479
+ return new CancelProcessing();
4480
+ };
4481
+ return CancelProcessing;
4482
+ }();
4483
+
4484
+ var ExternalApiProvider = /*#__PURE__*/function () {
4485
+ /**
4486
+ * Creates an instance of external api provider.
4487
+ *
4488
+ * If you need sub-request then use 'subRequestIndex' to check current request index in functions below.
4489
+ * Also use array for 'httpMethod'.
4490
+ *
4491
+ * If the endpoint of dedicated provider has pagination then you should customize the behavior using
4492
+ * "changeQueryParametersForPageNumber", "checkWhetherResponseIsForLastPage".
4493
+ *
4494
+ * We perform RPS counting all over the App to avoid blocking our clients due to abuses of the providers.
4495
+ *
4496
+ * @param endpoint {string} URL to the provider's endpoint. Note: you can customize it using composeQueryString
4497
+ * @param [httpMethod] {string|string[]} one of "get", "post", "put", "patch", "delete" or an array of these values
4498
+ * for request having sub-requests
4499
+ * @param [timeout] {number} number of milliseconds to wait for the response
4500
+ * @param [apiGroup] {ApiGroup} singleton object containing parameters of API group. Helpful when you use the same
4501
+ * api for different providers to avoid hardcoding RPS inside each provider what can cause mistakes
4502
+ * @param [specificHeaders] {Object} contains specific keys (headers) and values (their content) if needed for this provider
4503
+ * @param [maxPageLength] {number} optional number of items per page if the request supports pagination
4504
+ */
4505
+ function ExternalApiProvider(endpoint, httpMethod, timeout, apiGroup, specificHeaders, maxPageLength) {
4506
+ var _maxPageLength, _specificHeaders;
4507
+ if (specificHeaders === void 0) {
4508
+ specificHeaders = {};
4509
+ }
4510
+ if (maxPageLength === void 0) {
4511
+ maxPageLength = Number.MAX_SAFE_INTEGER;
4512
+ }
4513
+ this.endpoint = endpoint;
4514
+ this.httpMethod = httpMethod != null ? httpMethod : "get";
4515
+ // TODO: [refactoring, critical] We have two timeouts for robust data retrieval - here and inside the service method call, need to remain the only
4516
+ this.timeout = timeout != null ? timeout : 10000;
4517
+ // TODO: [refactoring, critical] We need single place for all RPSes as we use them as hardcoded constants now inside different services
4518
+ this.apiGroup = apiGroup;
4519
+ this.maxPageLength = (_maxPageLength = maxPageLength) != null ? _maxPageLength : Number.MAX_SAFE_INTEGER;
4520
+ this.niceFactor = 1;
4521
+ this.specificHeaders = (_specificHeaders = specificHeaders) != null ? _specificHeaders : {};
4522
+ }
4523
+ var _proto = ExternalApiProvider.prototype;
4524
+ _proto.getRps = function getRps() {
4525
+ var _this$apiGroup$rps;
4526
+ return (_this$apiGroup$rps = this.apiGroup.rps) != null ? _this$apiGroup$rps : 2;
4527
+ };
4528
+ _proto.isRpsExceeded = function isRpsExceeded() {
4529
+ return this.apiGroup.isRpsExceeded();
4530
+ };
4531
+ _proto.actualizeLastCalledTimestamp = function actualizeLastCalledTimestamp() {
4532
+ this.apiGroup.actualizeLastCalledTimestamp();
4533
+ };
4534
+ _proto.getApiGroupId = function getApiGroupId() {
4535
+ return this.apiGroup.id;
4536
+ }
4537
+
4538
+ /**
4539
+ * Some endpoint can require several sub requests. Example is one request to get confirmed transactions
4540
+ * and another request for unconfirmed transactions. You should override this method to return true for such requests.
4541
+ *
4542
+ * @return {boolean} true if this provider requires several requests to retrieve the data
4543
+ */;
4544
+ _proto.doesRequireSubRequests = function doesRequireSubRequests() {
4545
+ return false;
4546
+ }
4547
+
4548
+ /**
4549
+ * Some endpoint support pagination. Override this method if so and implement corresponding methods.
4550
+ *
4551
+ * @return {boolean} true if this provider requires several requests to retrieve the data
4552
+ */;
4553
+ _proto.doesSupportPagination = function doesSupportPagination() {
4554
+ return false;
4555
+ }
4556
+
4557
+ /**
4558
+ * Composes a query string to be added to the endpoint of this provider.
4559
+ *
4560
+ * @param params {any[]} params array passed to the RobustExternalAPICallerService
4561
+ * @param [subRequestIndex] {number} optional number of the sub-request the call is performed for
4562
+ * @returns {string} query string to be concatenated with endpoint
4563
+ */;
4564
+ _proto.composeQueryString = function composeQueryString(params, subRequestIndex) {
4565
+ return "";
4566
+ }
4567
+
4568
+ /**
4569
+ * Composes a body to be added to the request
4570
+ *
4571
+ * @param params {any[]} params array passed to the RobustExternalAPICallerService
4572
+ * @param [subRequestIndex] {number} optional number of the sub-request the call is performed for
4573
+ * @returns {string}
4574
+ */;
4575
+ _proto.composeBody = function composeBody(params, subRequestIndex) {
4576
+ return "";
4577
+ }
4578
+
4579
+ /**
4580
+ * Extracts data from the response and returns it
4581
+ *
4582
+ * @param response {Object} HTTP response returned by provider
4583
+ * @param [params] {any[]} params array passed to the RobustExternalAPICallerService
4584
+ * @param [subRequestIndex] {number} optional number of the sub-request the call is performed for
4585
+ * @param iterationsData {any[]} array of data retrieved from previous sub-requests
4586
+ * @returns {any}
4587
+ */;
4588
+ _proto.getDataByResponse = function getDataByResponse(response, params, subRequestIndex, iterationsData) {
4589
+ return [];
4590
+ }
4591
+
4592
+ /**
4593
+ * Function changing the query string according to page number and previous response
4594
+ * Only for endpoints supporting pagination
4595
+ *
4596
+ * @param params {any[]} params array passed to the RobustExternalAPICallerService
4597
+ * @param previousResponse {Object} HTTP response returned by provider for previous call (previous page)
4598
+ * @param pageNumber {number} new page number. We count from 0. You need to manually increment with 1 if your
4599
+ * provider counts pages starting with 1
4600
+ * @param [subRequestIndex] {number} optional number of the sub-request the call is performed for
4601
+ * @returns {any[]}
4602
+ */;
4603
+ _proto.changeQueryParametersForPageNumber = function changeQueryParametersForPageNumber(params, previousResponse, pageNumber, subRequestIndex) {
4604
+ return params;
4605
+ }
4606
+
4607
+ /**
4608
+ * Function checking whether the response is for the last page to stop requesting for a next page.
4609
+ * Only for endpoints supporting pagination.
4610
+ *
4611
+ * @param previousResponse {Object} HTTP response returned by provider for previous call (previous page)
4612
+ * @param currentResponse {Object} HTTP response returned by provider for current call (current page, next after the previous)
4613
+ * @param currentPageNumber {number} current page number (for current response)
4614
+ * @param [subRequestIndex] {number} optional number of the sub-request the call is performed for
4615
+ * @returns {boolean}
4616
+ */;
4617
+ _proto.checkWhetherResponseIsForLastPage = function checkWhetherResponseIsForLastPage(previousResponse, currentResponse, currentPageNumber, subRequestIndex) {
4618
+ return true;
4619
+ }
4620
+
4621
+ /**
4622
+ * Resets the nice factor to default value
4623
+ */;
4624
+ _proto.resetNiceFactor = function resetNiceFactor() {
4625
+ this.niceFactor = 1;
4626
+ }
4627
+
4628
+ /**
4629
+ * Internal method used for requests requiring sub-requests.
4630
+ *
4631
+ * @param iterationsData {any[]} iterations data retrieved from getDataByResponse called per sub-request.
4632
+ * @return {any} by default flatten the passed iterations data array. Should be redefined if you need another logic.
4633
+ */;
4634
+ _proto.incorporateIterationsData = function incorporateIterationsData(iterationsData) {
4635
+ return iterationsData.flat();
4636
+ };
4637
+ return ExternalApiProvider;
4638
+ }();
4639
+
2617
4640
  var ExistingSwap =
2618
4641
  /**
2619
4642
  * @param swapId {string}
@@ -4588,26 +6611,39 @@
4588
6611
 
4589
6612
  exports.AmountUtils = AmountUtils;
4590
6613
  exports.AssetIcon = AssetIcon;
6614
+ exports.AxiosAdapter = AxiosAdapter;
4591
6615
  exports.BaseSwapCreationInfo = BaseSwapCreationInfo;
4592
6616
  exports.Blockchain = Blockchain;
4593
6617
  exports.Button = Button;
4594
6618
  exports.Cache = Cache;
6619
+ exports.CacheAndConcurrentRequestsResolver = CacheAndConcurrentRequestsResolver;
6620
+ exports.CachedRobustExternalApiCallerService = CachedRobustExternalApiCallerService;
6621
+ exports.CancelProcessing = CancelProcessing;
4595
6622
  exports.Coin = Coin;
4596
6623
  exports.EmailsApi = EmailsApi;
4597
6624
  exports.ExistingSwap = ExistingSwap;
4598
6625
  exports.ExistingSwapWithFiatData = ExistingSwapWithFiatData;
6626
+ exports.ExternalApiProvider = ExternalApiProvider;
4599
6627
  exports.FiatCurrenciesService = FiatCurrenciesService;
4600
6628
  exports.LoadingDots = LoadingDots;
4601
6629
  exports.Logger = Logger;
4602
6630
  exports.LogsStorage = LogsStorage;
4603
6631
  exports.Protocol = Protocol;
4604
6632
  exports.PublicSwapService = PublicSwapService;
6633
+ exports.RobustExternalAPICallerService = RobustExternalAPICallerService;
4605
6634
  exports.SupportChat = SupportChat;
4606
6635
  exports.SwapProvider = SwapProvider;
4607
6636
  exports.SwapUtils = SwapUtils;
4608
6637
  exports.SwapspaceSwapProvider = SwapspaceSwapProvider;
6638
+ exports.getQueryParameterSingleValue = getQueryParameterSingleValue;
6639
+ exports.getQueryParameterValues = getQueryParameterValues;
6640
+ exports.handleClickOutside = handleClickOutside;
4609
6641
  exports.improveAndRethrow = improveAndRethrow;
6642
+ exports.logErrorOrOutputToConsole = logErrorOrOutputToConsole;
6643
+ exports.postponeExecution = postponeExecution;
6644
+ exports.removeQueryParameterAndValues = removeQueryParameterAndValues;
4610
6645
  exports.safeStringify = safeStringify;
6646
+ exports.saveQueryParameterAndValues = saveQueryParameterAndValues;
4611
6647
  exports.useCallHandlingErrors = useCallHandlingErrors;
4612
6648
  exports.useReferredState = useReferredState;
4613
6649