UNPKG

wealthica-sdk-js

Version:

Official Wealthica JS SDK for the Browser & NodeJS

1,128 lines (1,018 loc) 1.41 MB
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(global, () => { return /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 31732 (__unused_webpack_module, exports, __webpack_require__) { "use strict"; function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports, "__esModule", ({value:!0}));var axios=_interopDefault(__webpack_require__(79329)),__assign=function(){return(__assign=Object.assign||function(e){for(var n,t=1,r=arguments.length;t<r;t++)for(var o in n=arguments[t])Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o]);return e}).apply(this,arguments)},__awaiter=function(e,n,t,r){return new(t||(t=Promise))(function(o,s){function a(e){try{i(r.next(e))}catch(e){s(e)}}function R(e){try{i(r.throw(e))}catch(e){s(e)}}function i(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t(function(e){e(n)})).then(a,R)}i((r=r.apply(e,n||[])).next())})},__generator=function(e,n){var t,r,o,s,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:R(0),throw:R(1),return:R(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function R(R){return function(i){return function(R){if(t)throw new TypeError("Generator is already executing.");for(;s&&(s=0,R[0]&&(a=0)),a;)try{if(t=1,r&&(o=2&R[0]?r.return:R[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,R[1])).done)return o;switch(r=0,o&&(R=[2&R[0],o.value]),R[0]){case 0:case 1:o=R;break;case 4:return a.label++,{value:R[1],done:!1};case 5:a.label++,r=R[1],R=[0];continue;case 7:R=a.ops.pop(),a.trys.pop();continue;default:if(!(o=(o=a.trys).length>0&&o[o.length-1])&&(6===R[0]||2===R[0])){a=0;continue}if(3===R[0]&&(!o||R[1]>o[0]&&R[1]<o[3])){a.label=R[1];break}if(6===R[0]&&a.label<o[1]){a.label=o[1],o=R;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(R);break}o[2]&&a.ops.pop(),a.trys.pop();continue}R=n.call(e,a)}catch(e){R=[6,e],r=0}finally{t=o=0}if(5&R[0])throw R[1];return{value:R[0]?R[1]:void 0,done:!0}}([R,i])}}},toNumber=function(e){return e instanceof Date?e.getTime():"number"==typeof e||null===e||void 0===e?e:Number(e)},isWithin=function(e,n,t){return t>=e&&t<=n},isPromise=function(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then},DEFAULT_HEADERS={Accept:"application/json","Content-Type":"application/json"},DEFAULT_CONFIG={timeout:0},NONE=null,CLIENT_ERROR="CLIENT_ERROR",SERVER_ERROR="SERVER_ERROR",TIMEOUT_ERROR="TIMEOUT_ERROR",CONNECTION_ERROR="CONNECTION_ERROR",NETWORK_ERROR="NETWORK_ERROR",UNKNOWN_ERROR="UNKNOWN_ERROR",CANCEL_ERROR="CANCEL_ERROR",TIMEOUT_ERROR_CODES=["ECONNABORTED"],NODEJS_CONNECTION_ERROR_CODES=["ENOTFOUND","ECONNREFUSED","ECONNRESET"],STATUS_ERROR_CODES=["ERR_BAD_REQUEST","ERR_BAD_RESPONSE"],in200s=function(e){return isWithin(200,299,e)},in400s=function(e){return isWithin(400,499,e)},in500s=function(e){return isWithin(500,599,e)},getProblemFromError=function(e){return"Network Error"===e.message?NETWORK_ERROR:axios.isCancel(e)?CANCEL_ERROR:e.code?STATUS_ERROR_CODES.includes(e.code)?getProblemFromStatus(e.response.status):TIMEOUT_ERROR_CODES.includes(e.code)?TIMEOUT_ERROR:NODEJS_CONNECTION_ERROR_CODES.includes(e.code)?CONNECTION_ERROR:UNKNOWN_ERROR:getProblemFromStatus(e.response?e.response.status:null)},getProblemFromStatus=function(e){return e?in200s(e)?NONE:in400s(e)?CLIENT_ERROR:in500s(e)?SERVER_ERROR:UNKNOWN_ERROR:UNKNOWN_ERROR},create=function(e){var n,t=__assign(__assign({},DEFAULT_HEADERS),e.headers||{});if(e.axiosInstance)n=e.axiosInstance;else{var r=__assign(__assign({},e),{headers:void 0}),o=__assign(__assign({},DEFAULT_CONFIG),r);n=axios.create(o)}var s=[],a=[],R=[],i=[],u=[],E=function(e,r){return t[e]=r,n},c=function(e){return function(n,t,r){return void 0===t&&(t={}),void 0===r&&(r={}),O(__assign(__assign({},r),{url:n,params:t,method:e}))}},l=function(e){return function(n,t,r){return void 0===r&&(r={}),O(__assign(__assign({},r),{url:n,method:e,data:t}))}},O=function(e){return __awaiter(void 0,void 0,void 0,function(){var r,o,s,i;return __generator(this,function(u){switch(u.label){case 0:if(e.headers=__assign(__assign({},t),e.headers),a.length>0&&a.forEach(function(n){return n(e)}),!(R.length>0))return[3,6];r=0,u.label=1;case 1:return r<R.length?(o=R[r](e),isPromise(o)?[4,o]:[3,3]):[3,6];case 2:return u.sent(),[3,5];case 3:return[4,o(e)];case 4:u.sent(),u.label=5;case 5:return r++,[3,1];case 6:return s=toNumber(new Date),i=function(e){return __awaiter(void 0,void 0,void 0,function(){var n;return __generator(this,function(t){switch(t.label){case 0:return[4,N(s,e)];case 1:return n=t.sent(),[2,_(n)]}})})},[2,n.request(e).then(i).catch(i)]}})})},_=function(e){return s.forEach(function(n){try{n(e)}catch(e){}}),e},N=function(e,n){return __awaiter(void 0,void 0,void 0,function(){var t,r,o,s,a,R,E,c,l,O,_,N,f,p,T,d,C;return __generator(this,function(h){switch(h.label){case 0:if(t=toNumber(new Date),r=t-e,o=n instanceof Error||axios.isCancel(n),s=n,a=n,R=o?a.response:s,E=R&&R.status||null,c=o?getProblemFromError(n):getProblemFromStatus(E),l=o?a:null,O=in200s(E),_=n.config||null,N=R&&R.headers||null,f=null!==(C=R&&R.data)&&void 0!==C?C:null,p={duration:r,problem:c,originalError:l,ok:O,status:E,headers:N,config:_,data:f},i.length>0&&i.forEach(function(e){return e(p)}),!(u.length>0))return[3,6];T=0,h.label=1;case 1:return T<u.length?(d=u[T](p),isPromise(d)?[4,d]:[3,3]):[3,6];case 2:return h.sent(),[3,5];case 3:return[4,d(p)];case 4:h.sent(),h.label=5;case 5:return T++,[3,1];case 6:return[2,p]}})})};return{axiosInstance:n,monitors:s,addMonitor:function(e){s.push(e)},requestTransforms:a,asyncRequestTransforms:R,responseTransforms:i,asyncResponseTransforms:u,addRequestTransform:function(e){return a.push(e)},addAsyncRequestTransform:function(e){return R.push(e)},addResponseTransform:function(e){return i.push(e)},addAsyncResponseTransform:function(e){return u.push(e)},setHeader:E,setHeaders:function(e){return Object.keys(e).forEach(function(n){return E(n,e[n])}),n},deleteHeader:function(e){return delete t[e],n},headers:t,setBaseURL:function(e){return n.defaults.baseURL=e,n},getBaseURL:function(){return n.defaults.baseURL},any:O,get:c("get"),delete:c("delete"),head:c("head"),post:l("post"),put:l("put"),patch:l("patch"),link:c("link"),unlink:c("unlink")}},isCancel=axios.isCancel,CancelToken=axios.CancelToken,apisauce={DEFAULT_HEADERS:DEFAULT_HEADERS,NONE:NONE,CLIENT_ERROR:CLIENT_ERROR,SERVER_ERROR:SERVER_ERROR,TIMEOUT_ERROR:TIMEOUT_ERROR,CONNECTION_ERROR:CONNECTION_ERROR,NETWORK_ERROR:NETWORK_ERROR,UNKNOWN_ERROR:UNKNOWN_ERROR,create:create,isCancel:isCancel,CancelToken:CancelToken};exports.DEFAULT_HEADERS=DEFAULT_HEADERS,exports.NONE=NONE,exports.CLIENT_ERROR=CLIENT_ERROR,exports.SERVER_ERROR=SERVER_ERROR,exports.TIMEOUT_ERROR=TIMEOUT_ERROR,exports.CONNECTION_ERROR=CONNECTION_ERROR,exports.NETWORK_ERROR=NETWORK_ERROR,exports.UNKNOWN_ERROR=UNKNOWN_ERROR,exports.CANCEL_ERROR=CANCEL_ERROR,exports.getProblemFromError=getProblemFromError,exports.getProblemFromStatus=getProblemFromStatus,exports.create=create,exports.isCancel=isCancel,exports.CancelToken=CancelToken,exports["default"]=apisauce; /***/ }, /***/ 21873 (module, __unused_webpack_exports, __webpack_require__) { module.exports = { parallel : __webpack_require__(18798), serial : __webpack_require__(52081), serialOrdered : __webpack_require__(90028) }; /***/ }, /***/ 74555 (module) { // API module.exports = abort; /** * Aborts leftover active jobs * * @param {object} state - current state object */ function abort(state) { Object.keys(state.jobs).forEach(clean.bind(state)); // reset leftover jobs state.jobs = {}; } /** * Cleans up leftover job by invoking abort function for the provided job id * * @this state * @param {string|number} key - job id to abort */ function clean(key) { if (typeof this.jobs[key] == 'function') { this.jobs[key](); } } /***/ }, /***/ 72313 (module, __unused_webpack_exports, __webpack_require__) { var defer = __webpack_require__(70405); // API module.exports = async; /** * Runs provided callback asynchronously * even if callback itself is not * * @param {function} callback - callback to invoke * @returns {function} - augmented callback */ function async(callback) { var isAsync = false; // check if async happened defer(function() { isAsync = true; }); return function async_callback(err, result) { if (isAsync) { callback(err, result); } else { defer(function nextTick_callback() { callback(err, result); }); } }; } /***/ }, /***/ 70405 (module) { module.exports = defer; /** * Runs provided function on next iteration of the event loop * * @param {function} fn - function to run */ function defer(fn) { var nextTick = typeof setImmediate == 'function' ? setImmediate : ( typeof process == 'object' && typeof process.nextTick == 'function' ? process.nextTick : null ); if (nextTick) { nextTick(fn); } else { setTimeout(fn, 0); } } /***/ }, /***/ 78051 (module, __unused_webpack_exports, __webpack_require__) { var async = __webpack_require__(72313) , abort = __webpack_require__(74555) ; // API module.exports = iterate; /** * Iterates over each job object * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {object} state - current job status * @param {function} callback - invoked when all elements processed */ function iterate(list, iterator, state, callback) { // store current index var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; state.jobs[key] = runJob(iterator, key, list[key], function(error, output) { // don't repeat yourself // skip secondary callbacks if (!(key in state.jobs)) { return; } // clean up jobs delete state.jobs[key]; if (error) { // don't process rest of the results // stop still active jobs // and reset the list abort(state); } else { state.results[key] = output; } // return salvaged results callback(error, state.results); }); } /** * Runs iterator over provided job element * * @param {function} iterator - iterator to invoke * @param {string|number} key - key/index of the element in the list of jobs * @param {mixed} item - job description * @param {function} callback - invoked after iterator is done with the job * @returns {function|mixed} - job abort function or something else */ function runJob(iterator, key, item, callback) { var aborter; // allow shortcut if iterator expects only two arguments if (iterator.length == 2) { aborter = iterator(item, async(callback)); } // otherwise go with full three arguments else { aborter = iterator(item, key, async(callback)); } return aborter; } /***/ }, /***/ 19500 (module) { // API module.exports = state; /** * Creates initial state object * for iteration over list * * @param {array|object} list - list to iterate over * @param {function|null} sortMethod - function to use for keys sort, * or `null` to keep them as is * @returns {object} - initial state object */ function state(list, sortMethod) { var isNamedList = !Array.isArray(list) , initState = { index : 0, keyedList: isNamedList || sortMethod ? Object.keys(list) : null, jobs : {}, results : isNamedList ? {} : [], size : isNamedList ? Object.keys(list).length : list.length } ; if (sortMethod) { // sort array keys based on it's values // sort object's keys just on own merit initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) { return sortMethod(list[a], list[b]); }); } return initState; } /***/ }, /***/ 26276 (module, __unused_webpack_exports, __webpack_require__) { var abort = __webpack_require__(74555) , async = __webpack_require__(72313) ; // API module.exports = terminator; /** * Terminates jobs in the attached state context * * @this AsyncKitState# * @param {function} callback - final callback to invoke after termination */ function terminator(callback) { if (!Object.keys(this.jobs).length) { return; } // fast forward iteration index this.index = this.size; // abort jobs abort(this); // send back results we have so far async(callback)(null, this.results); } /***/ }, /***/ 18798 (module, __unused_webpack_exports, __webpack_require__) { var iterate = __webpack_require__(78051) , initState = __webpack_require__(19500) , terminator = __webpack_require__(26276) ; // Public API module.exports = parallel; /** * Runs iterator over provided array elements in parallel * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function parallel(list, iterator, callback) { var state = initState(list); while (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, function(error, result) { if (error) { callback(error, result); return; } // looks like it's the last one if (Object.keys(state.jobs).length === 0) { callback(null, state.results); return; } }); state.index++; } return terminator.bind(state, callback); } /***/ }, /***/ 52081 (module, __unused_webpack_exports, __webpack_require__) { var serialOrdered = __webpack_require__(90028); // Public API module.exports = serial; /** * Runs iterator over provided array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serial(list, iterator, callback) { return serialOrdered(list, iterator, null, callback); } /***/ }, /***/ 90028 (module, __unused_webpack_exports, __webpack_require__) { var iterate = __webpack_require__(78051) , initState = __webpack_require__(19500) , terminator = __webpack_require__(26276) ; // Public API module.exports = serialOrdered; // sorting helpers module.exports.ascending = ascending; module.exports.descending = descending; /** * Runs iterator over provided sorted array elements in series * * @param {array|object} list - array or object (named list) to iterate over * @param {function} iterator - iterator to run * @param {function} sortMethod - custom sort function * @param {function} callback - invoked when all elements processed * @returns {function} - jobs terminator */ function serialOrdered(list, iterator, sortMethod, callback) { var state = initState(list, sortMethod); iterate(list, iterator, state, function iteratorHandler(error, result) { if (error) { callback(error, result); return; } state.index++; // are we there yet? if (state.index < (state['keyedList'] || list).length) { iterate(list, iterator, state, iteratorHandler); return; } // done here callback(null, state.results); }); return terminator.bind(state, callback); } /* * -- Sort methods */ /** * sort helper to sort array elements in ascending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function ascending(a, b) { return a < b ? -1 : a > b ? 1 : 0; } /** * sort helper to sort array elements in descending order * * @param {mixed} a - an item to compare * @param {mixed} b - an item to compare * @returns {number} - comparison result */ function descending(a, b) { return -1 * ascending(a, b); } /***/ }, /***/ 73049 (module, __unused_webpack_exports, __webpack_require__) { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); } function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* global window */ var _require = __webpack_require__(31732), create = _require.create; var jwt = __webpack_require__(44040); var _require2 = __webpack_require__(3832), API_URL = _require2.API_URL, CONNECT_URL = _require2.CONNECT_URL; var createResources = __webpack_require__(31951); var _require3 = __webpack_require__(65948), isBrowser = _require3.isBrowser, isNode = _require3.isNode, isReactNative = _require3.isReactNative, appendWealthicaIframe = _require3.appendWealthicaIframe, appendWealthicaForm = _require3.appendWealthicaForm; var CALLBACK_CONNECTION = '_onConnection'; var CALLBACK_ERROR = '_onError'; var CALLBACK_EVENT = '_onEvent'; var API = /*#__PURE__*/function () { function API(config) { _classCallCheck(this, API); this.config = _objectSpread({}, config); this.config.baseURL = this.config.baseURL || API_URL; this.config.connectURL = this.config.connectURL || CONNECT_URL; var _this$config = this.config, clientId = _this$config.clientId, secret = _this$config.secret; this.isBrowser = isBrowser(); this.isNode = isNode(); this.isReactNative = isReactNative(); this.isClient = this.isBrowser || this.isReactNative; // TODO add an error code for each SDK error if (!clientId || typeof clientId !== 'string') { throw new Error('Please provide a valid Wealthica clientId.'); } if (!this.isClient && (!secret || typeof secret !== 'string')) { throw new Error('Please provide a valid Wealthica secret.'); } if (this.isClient) { var auth = config.auth || {}; this.config.authEndpoint = this.config.authEndpoint || '/wealthica/auth'; this.config.auth = { params: auth.params || {}, headers: auth.headers || {} }; this.authApi = create({ headers: this.config.auth.headers }); } this._token = {}; this._onWidgetMessage = this._onMessage.bind(this); this._widgetOpened = false; this._widgetActive = false; this._features = null; } return _createClass(API, [{ key: "_init", value: function _init() { var _this$config2 = this.config, loginName = _this$config2.loginName, baseURL = _this$config2.baseURL; // Data & token endpoints do not require authentication this.api = create({ baseURL: baseURL }); var dataResources = createResources(this, ['providers', 'teams']); Object.assign(this, dataResources); if (loginName) return this.login(loginName); return this; } }, { key: "login", value: function login(loginName) { if (!this.isClient && (!loginName || typeof loginName !== 'string')) { throw new Error('Please provide a valid loginName.'); } var baseURL = this.config.baseURL; // Create new user instance, without loginName so it does not recursively loop on init var user = new API(_objectSpread(_objectSpread({}, this.config), {}, { loginName: null })); user._init(); // Initiate user api & resource helpers user.userApi = create({ baseURL: baseURL }); user.userApi.addAsyncRequestTransform(/*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(request) { var _t; return _regenerator().w(function (_context) { while (1) switch (_context.n) { case 0: _t = "Bearer "; _context.n = 1; return user.getToken(); case 1: request.headers.Authorization = _t.concat.call(_t, _context.v); return _context.a(2, request); } }, _callee); })); return function (_x) { return _ref.apply(this, arguments); }; }()); var userResources = createResources(user, ['institutions', 'history', 'transactions', 'positions']); Object.assign(user, userResources); user.config.loginName = loginName; return user; } }, { key: "getToken", value: function () { var _getToken = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() { var options, currentTime, payload, token, _args2 = arguments; return _regenerator().w(function (_context2) { while (1) switch (_context2.n) { case 0: options = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}; // Get a new token if the old one has < minimumLifetime left currentTime = new Date().valueOf(); payload = this._token.payload; token = this._token.token; if (!(!payload || currentTime > (payload.exp - (options.minimumLifetime || 10)) * 1000)) { _context2.n = 2; break; } _context2.n = 1; return this.fetchToken(); case 1: token = _context2.v; case 2: return _context2.a(2, token); } }, _callee2, this); })); function getToken() { return _getToken.apply(this, arguments); } return getToken; }() }, { key: "fetchToken", value: function () { var _fetchToken = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() { var response, _ref2, token, payload; return _regenerator().w(function (_context3) { while (1) switch (_context3.n) { case 0: _context3.n = 1; return this.isClient ? this._fetchTokenClient() : this._fetchTokenNode(); case 1: response = _context3.v; if (!(!response.ok && !response.token)) { _context3.n = 2; break; } throw response.originalError; case 2: _ref2 = response.data || response, token = _ref2.token; payload = jwt.decode(token); this._token = { token: token, payload: payload }; return _context3.a(2, this._token.token); } }, _callee3, this); })); function fetchToken() { return _fetchToken.apply(this, arguments); } return fetchToken; }() }, { key: "_fetchTokenNode", value: function _fetchTokenNode() { var _this$config3 = this.config, clientId = _this$config3.clientId, secret = _this$config3.secret, loginName = _this$config3.loginName; return this.api.post('/auth/token', { clientId: clientId, secret: secret }, { headers: { loginName: loginName } }); } }, { key: "_fetchTokenClient", value: function _fetchTokenClient() { var _this$config4 = this.config, auth = _this$config4.auth, authEndpoint = _this$config4.authEndpoint, authorizer = _this$config4.authorizer; var params = auth.params; if (typeof authorizer === 'function') { return new Promise(function (resolve, reject) { authorizer(function (error, result) { if (error) { reject(error); return; } if (!result || _typeof(result) !== 'object' || !result.token) { reject(new Error('Invalid authorizer result. Expecting `{ token: "the token" }`.')); return; } resolve(result); // expected result = { token: 'the token' } }); }); } return this.authApi.post(authEndpoint, params); } }, { key: "getTeam", value: function getTeam() { return this.teams.info(); } }, { key: "getConnectData", value: function () { var _getConnectData = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() { var options, provider, institutionId, connectionRoute, state, _options$origin, origin, lang, _options$redirectURI, redirectURI, providers, disabledProviders, _options$providerGrou, providerGroups, theme, providersPerLine, features, webhookURI, _this$config5, clientId, connectURL, _url, token, query, queryString, url, _args4 = arguments, _t2; return _regenerator().w(function (_context4) { while (1) switch (_context4.p = _context4.n) { case 0: options = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : {}; provider = options.provider, institutionId = options.institutionId, connectionRoute = options.connectionRoute, state = options.state, _options$origin = options.origin, origin = _options$origin === void 0 ? this.isBrowser ? window.location.origin : undefined : _options$origin, lang = options.lang, _options$redirectURI = options.redirectURI, redirectURI = _options$redirectURI === void 0 ? this.config.redirectURI : _options$redirectURI, providers = options.providers, disabledProviders = options.disabledProviders, _options$providerGrou = options.providerGroups, providerGroups = _options$providerGrou === void 0 ? ['core'] : _options$providerGrou, theme = options.theme, providersPerLine = options.providersPerLine, features = options.features, webhookURI = options.webhookURI; _this$config5 = this.config, clientId = _this$config5.clientId, connectURL = _this$config5.connectURL; // Validate webhookURI if provided if (!webhookURI) { _context4.n = 4; break; } _context4.p = 1; _url = new URL(webhookURI); if (!(_url.protocol !== 'https:')) { _context4.n = 2; break; } throw new Error('Webhook URI must use HTTPS protocol'); case 2: _context4.n = 4; break; case 3: _context4.p = 3; _t2 = _context4.v; throw new Error("Invalid webhook URI: ".concat(_t2.message)); case 4: _context4.n = 5; return this.getToken({ minimumLifetime: 600 }); case 5: token = _context4.v; query = { client_id: clientId, redirect_uri: redirectURI, state: state, lang: lang || 'en', origin: origin, // 'provider' param in priority, skip 'providers' param if 'provider' is set providers: !provider && Array.isArray(providers) && providers.length ? providers.join(',') : undefined, disabled_providers: disabledProviders && Array.isArray(disabledProviders) && disabledProviders.length ? disabledProviders.join(',') : undefined, provider_groups: providerGroups.join(','), theme: ['light', 'dark'].includes(theme) ? theme : 'light', providers_per_line: providersPerLine && ['1', '2'].includes(providersPerLine.toString()) ? providersPerLine.toString() : '2', features: features, webhook_uri: webhookURI }; // Cleanup blank params Object.keys(query).forEach(function (key) { return [undefined, null, ''].includes(query[key]) && delete query[key]; }); queryString = new URLSearchParams(query).toString(); url = provider ? "".concat(connectURL, "/connect/").concat(provider) : "".concat(connectURL, "/connect"); // Return verify-mfa or reconnect url if institutionId is passed in if (institutionId && connectionRoute === 'verify-mfa') { url = "".concat(connectURL, "/verify-mfa/").concat(institutionId); } else if (institutionId) { url = "".concat(connectURL, "/reconnect/").concat(institutionId); } return _context4.a(2, { url: "".concat(url, "?").concat(queryString), token: token }); } }, _callee4, this, [[1, 3]]); })); function getConnectData() { return _getConnectData.apply(this, arguments); } return getConnectData; }() }, { key: "connect", value: function connect() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this._connect(options); return this; // return the instance so we can chain the callbacks } }, { key: "reconnect", value: function reconnect(institutionId) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (!institutionId || typeof institutionId !== 'string') { throw new Error('Please provide a valid institutionId.'); } this._connect(_objectSpread({ institutionId: institutionId }, options)); return this; // return the instance so we can chain the callbacks } }, { key: "verifyMfa", value: function verifyMfa(institutionId) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (!institutionId || typeof institutionId !== 'string') { throw new Error('Please provide a valid institutionId.'); } this._connect(_objectSpread({ institutionId: institutionId, connectionRoute: 'verify-mfa' }, options)); return this; // return the instance so we can chain the callbacks } }, { key: "onConnection", value: function onConnection(callback) { if (typeof callback !== 'function') throw new Error('Callback must be a function.'); this[CALLBACK_CONNECTION] = callback.bind(this); return this; // chaining support } }, { key: "onError", value: function onError(callback) { if (typeof callback !== 'function') throw new Error('Callback must be a function.'); this[CALLBACK_ERROR] = callback.bind(this); return this; // chaining support } }, { key: "onEvent", value: function onEvent(callback) { if (typeof callback !== 'function') throw new Error('Callback must be a function.'); this[CALLBACK_EVENT] = callback.bind(this); return this; // chaining support } }, { key: "_connect", value: function _connect() { var _this = this; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.isBrowser) throw new Error('Only supported in Browser.'); _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() { var provider, providers, disabledProviders, providerGroups, institutionId, connectionRoute, lang, theme, providersPerLine, features, connectionType, origin, webhookURI, _yield$_this$getConne, url, token, _t3; return _regenerator().w(function (_context5) { while (1) switch (_context5.p = _context5.n) { case 0: _context5.p = 0; _this._widgetOpened = true; provider = options.provider, providers = options.providers, disabledProviders = options.disabledProviders, providerGroups = options.providerGroups, institutionId = options.institutionId, connectionRoute = options.connectionRoute, lang = options.lang, theme = options.theme, providersPerLine = options.providersPerLine, features = options.features, connectionType = options.connectionType, origin = options.origin, webhookURI = options.webhookURI; // Store features for timeout calculation _this._features = features; _context5.n = 1; return _this.getConnectData({ provider: provider, providers: providers, disabledProviders: disabledProviders, providerGroups: providerGroups, institutionId: institutionId, connectionRoute: connectionRoute, lang: lang, theme: theme, providersPerLine: providersPerLine, features: features, origin: origin, webhookURI: webhookURI }); case 1: _yield$_this$getConne = _context5.v; url = _yield$_this$getConne.url; token = _yield$_this$getConne.token; _this.iframe = appendWealthicaIframe(); // GET is only for dev because it's not secure if (connectionType === 'GET') { _this.widget = window.open("".concat(url, "&token=").concat(token), _this.iframe.name); } else { _this.widget = window.open('', _this.iframe.name); _this.form = appendWealthicaForm({ url: url, token: token, iframe: _this.iframe }); _this.form.submit(); } _this.widget.focus(); _this._widgetActive = true; _this._addListeners(); _this._addWatchers(); _context5.n = 3; break; case 2: _context5.p = 2; _t3 = _context5.v; _this._closeWidgetWithError(500, _t3.message || 'Connection refused'); case 3: return _context5.a(2); } }, _callee5, null, [[0, 2]]); }))(); } }, { key: "_onMessage", value: function _onMessage(_ref4) { var origin = _ref4.origin, data = _ref4.data; var result = data; try { // Try parsing message data as JSON result = JSON.parse(data); } catch (err) { // Do nothing } // Skip if not a Wealthica message if (!result.wealthica) return; if (origin !== this.config.connectURL && !/\.wealthica\.com$/.test(new URL(origin).hostname)) { throw new Error("Calling Wealthica from unauthorized origin ".concat(origin)); } switch (result.event) { case 'success': { // Connection success this._triggerCallback(CALLBACK_CONNECTION, { institution: result.institution, provider: result.provider }); break; } case 'error': { // Connection error this._triggerCallback(CALLBACK_ERROR, { error: result.error }); break; } case 'close': { // Widget closed by user action, close right away this._closeWidgetWithError(400, 'Connection closed'); break; } default: { // Other events throughout the connection process this._triggerCallback(CALLBACK_EVENT, result); } } } }, { key: "_addWatchers", value: function _addWatchers() { var _this2 = this; // Determine timeout based on features var hasQuickRetry = this._features && this._features.split(',').map(function (f) { return f.trim(); }).includes('quick_retry'); var timeoutMinutes = hasQuickRetry ? 30 : 10; // Watch for widget timeout var timeoutWatcher = setTimeout(function () { _this2._closeWidgetWithError(400, 'Connection timeout'); }, timeoutMinutes * 60 * 1000); // Watch for widget status (whether closed by user or successfully finished) and clean it up var doneWatcher = setInterval(function () { if (_this2._widgetActive) { // Handle edge case where widget is closed unexpectedly (by browser extensions, via browser // console etc.) if (_this2.widget.closed) { _this2._closeWidgetWithError(400, 'Connection closed'); } } else { // If widget is marked as inactive, clear timeout and close it _this2._removeListeners(); clearInterval(doneWatcher); clearTimeout(timeoutWatcher); _this2._closeWidget(); } }, 1000); } /* eslint-disable camelcase */ }, { key: "_closeWidgetWithError", value: function _closeWidgetWithError(error_type, message) { this._closeWidget(); this._triggerCallback(CALLBACK_ERROR, { error: { error_type: error_type, message: message } }); /* eslint-enable camelcase */ } }, { key: "_closeWidget", value: function _closeWidget() { this._widgetActive = false; // Close the widget window object if (this.widget && !this.widget.closed) { this.widget.close(); } // Delete the iframe and form if (this.iframe) this.iframe.remove(); if (this.form) this.form.remove(); } }, { key: "_triggerCallback", value: function _triggerCallback(callback) { var payload = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // onConnection and onError callbacks are only triggered once per widget session. if ([CALLBACK_CONNECTION, CALLBACK_ERROR].includes(callback)) { // Mark widget as inactive, so it's cleaned up by the doneWatcher. this._widgetActive = false; var additionalData = null; if (this._widgetOpened) { this._widgetOpened = false; if (callback === CALLBACK_CONNECTION) { additionalData = { // Institution type passed only on success, // on error it appears in error object, so we don't need to duplicate it provider: payload.provider }; } if (this[callback]) { this[callback](payload.institution || payload.error, additionalData); } } return; } if (callback === CALLBACK_EVENT && this[callback]) { this[callback](payload.event, payload.data); } } }, { key: "_addListeners", value: function _addListeners() { window.addEventListener('message', this._onWidgetMessage, false); } }, { key: "_removeListeners", value: function _removeListeners() { window.removeEventListener('message', this._onWidgetMessage, false); } }]); }(); module.exports = API; /***/ }, /***/ 3832 (module) { var BASE_API_URL = 'https://api.wealthica.com'; var CONNECT_URL = 'https://connect.wealthica.com'; var API_VERSION = 'v1'; var API_URL = "".concat(BASE_API_URL, "/").concat(API_VERSION); module.exports = { BASE_API_URL: BASE_API_URL, CONNECT_URL: CONNECT_URL, API_VERSION: API_VERSION, API_URL: API_URL }; /***/ }, /***/ 44497 (module, __unused_webpack_exports, __webpack_require__) { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } __webpack_require__(84315); __webpack_require__(7452); var API = __webpack_require__(73049); var Wealthica = /*#__PURE__*/function () { function Wealthica() { _classCallCheck(this, Wealthica); } return _createClass(Wealthica, [{ key: "init", value: // eslint-disable-next-line class-methods-use-this function init() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var api = new API(config); return api._init(); } }]); }(); module.exports = new Wealthica(); /***/ }, /***/ 33043 (module, __unused_webpack_exports, __webpack_require__) { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e._