diff --git a/src/lib/amazon-connect-websocket-manager.js b/src/lib/amazon-connect-websocket-manager.js index ef6e85c..1197271 100644 --- a/src/lib/amazon-connect-websocket-manager.js +++ b/src/lib/amazon-connect-websocket-manager.js @@ -4,7 +4,7 @@ const global = typeof global !== 'undefined' ? global : global.connect = global.connect || {}; const currentWebsocketManager = connect.WebSocketManager; -!function(e){var t={};function n(o){if(t[o])return t[o].exports;var r=t[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,n),r.l=!0,r.exports}n.m=e,n.c=t,n.d=function(e,t,o){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(n.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(o,r,function(t){return e[t]}.bind(null,r));return o},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=10)}([function(e,t){function n(t){return e.exports=n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,n(t)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){function n(e,t){for(var n=0;n=0),c.type){case"b":n=parseInt(n,10).toString(2);break;case"c":n=String.fromCharCode(parseInt(n,10));break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,c.width?parseInt(c.width):0);break;case"e":n=c.precision?parseFloat(n).toExponential(c.precision):parseFloat(n).toExponential();break;case"f":n=c.precision?parseFloat(n).toFixed(c.precision):parseFloat(n);break;case"g":n=c.precision?String(Number(n.toPrecision(c.precision))):parseFloat(n);break;case"o":n=(parseInt(n,10)>>>0).toString(8);break;case"s":n=String(n),n=c.precision?n.substring(0,c.precision):n;break;case"t":n=String(!!n),n=c.precision?n.substring(0,c.precision):n;break;case"T":n=Object.prototype.toString.call(n).slice(8,-1).toLowerCase(),n=c.precision?n.substring(0,c.precision):n;break;case"u":n=parseInt(n,10)>>>0;break;case"v":n=n.valueOf(),n=c.precision?n.substring(0,c.precision):n;break;case"x":n=(parseInt(n,10)>>>0).toString(16);break;case"X":n=(parseInt(n,10)>>>0).toString(16).toUpperCase()}r.json.test(c.type)?b+=n:(!r.number.test(c.type)||p&&!c.sign?d="":(d=p?"+":"-",n=n.toString().replace(r.sign,"")),u=c.pad_char?"0"===c.pad_char?"0":c.pad_char.charAt(1):" ",l=c.width-(d+n).length,s=c.width&&l>0?u.repeat(l):"",b+=c.align?d+n+s:"0"===u?d+s+n:s+d+n)}return b}var s=Object.create(null);function u(e){if(s[e])return s[e];for(var t,n=e,o=[],i=0;n;){if(null!==(t=r.text.exec(n)))o.push(t[0]);else if(null!==(t=r.modulo.exec(n)))o.push("%");else{if(null===(t=r.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){i|=1;var a=[],c=t[2],u=[];if(null===(u=r.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a.push(u[1]);""!==(c=c.substring(u[0].length));)if(null!==(u=r.key_access.exec(c)))a.push(u[1]);else{if(null===(u=r.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");a.push(u[1])}t[2]=a}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:t[0],param_no:t[1],keys:t[2],sign:t[3],pad_char:t[4],align:t[5],width:t[6],precision:t[7],type:t[8]})}n=n.substring(t[0].length)}return s[e]=o}t.sprintf=i,t.vsprintf=a,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=a,void 0===(o=function(){return{sprintf:i,vsprintf:a}}.call(t,n,t,e))||(e.exports=o))}()},function(e,t,n){var o=n(8);e.exports=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&o(e,t)},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t,n){var o=n(0).default,r=n(9);e.exports=function(e,t){if(t&&("object"===o(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return r(e)},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){e.exports=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){function n(t,o){return e.exports=n=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},e.exports.__esModule=!0,e.exports.default=e.exports,n(t,o)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t){e.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e},e.exports.__esModule=!0,e.exports.default=e.exports},function(e,t,n){"use strict";n.r(t),n.d(t,"WebSocketManager",(function(){return Ne}));var o=n(0),r=n.n(o),i=n(4),a="NULL",c="CLIENT_LOGGER",s="DEBUG",u="AMZ_WEB_SOCKET_MANAGER:",l="Network offline",p="Network online, connecting to WebSocket server",d="Network offline, ignoring this getWebSocketConnConfig request",f="Heartbeat response not received",g="aws/ping deep heartbeat response not received",b="Heartbeat response received",v="aws/ping deep heartbeat received",m="Sending heartbeat",y="Sending aws/ping deep heartbeat",h="Failed to send heartbeat since WebSocket is not open",S="Failed to send aws/ping deep heartbeat since WebSocket is not open",k="Deep Heartbeat is successful. WebSocketManager has received 200 response from aws/ping",w="Deep Heartbeat failed. WebSocketManager does not receive 200 response from aws/ping",C="Generic topic failed.",O="WebSocket connection established!",T="WebSocket connection is closed",L="WebSocketManager Error, error_event: ",x="Scheduling WebSocket reinitialization, after delay ",_="WebSocket URL cannot be used to establish connection",I="WebSocket Initialization failed - Terminating and cleaning subscriptions",W="Terminating WebSocket Manager",N="Fetching new WebSocket connection configuration",F="Successfully fetched webSocket connection configuration",E="Failed to fetch webSocket connection configuration",M="Retrying fetching new WebSocket connection configuration",D="Initializing Websocket Manager",R="Initializing Websocket Manager Failure callback registered",A="Websocket connection open callback registered",j="Websocket connection close callback registered",H="Websocket connection gain callback registered",P="Websocket connection lost callback registered",G="Websocket subscription failure callback registered",z="Reset Websocket state",U="WebSocketManager Message Error",q="Message received for topic ",B="Invalid incoming message",J="WebsocketManager invoke callbacks for topic success ",V="aws/subscribe",X="aws/unsubscribe",$="aws/heartbeat",K="aws/ping",Z="connected",Q="disconnected",Y={assertTrue:function(e,t){if(!e)throw new Error(t)},assertNotNull:function(e,t){return Y.assertTrue(null!==e&&void 0!==r()(e),Object(i.sprintf)("%s must be provided",t||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,t){if(!Array.isArray(e))throw new Error(t+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==r()(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},ee=new RegExp("^(wss://)\\w*"),te=new RegExp("^(ws://127.0.0.1:)");Y.validWSUrl=function(e){return ee.test(e)||te.test(e)},Y.getSubscriptionResponse=function(e,t,n){return{topic:e,content:{status:t?"success":"failure",topics:n}}},Y.assertIsObject=function(e,t){if(!Y.isObject(e))throw new Error(t+" is not an object!")},Y.addJitter=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;t=Math.min(t,1);var n=Math.random()>.5?1:-1;return Math.floor(e+n*e*Math.random()*t)},Y.isNetworkOnline=function(){return navigator.onLine},Y.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var ne=Y,oe=n(5),re=n.n(oe),ie=n(6),ae=n.n(ie),ce=n(3),se=n.n(ce),ue=n(7),le=n.n(ue),pe=n(1),de=n.n(pe),fe=n(2),ge=n.n(fe);function be(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,o=se()(e);if(t){var r=se()(this).constructor;n=Reflect.construct(o,arguments,r)}else n=o.apply(this,arguments);return ae()(this,n)}}function ve(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function me(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:"";if(this.hasClientLogger()){var n="string"==typeof t?t:JSON.stringify(t,Te()),o="string"==typeof this.logMetaData?this.logMetaData:JSON.stringify(this.logMetaData,Te()),r="".concat(Oe(e)," ").concat(n);switch(o&&(r+=" ".concat(o)),e){case Se.DEBUG:return this._clientLogger.debug(r)||r;case Se.INFO:return this._clientLogger.info(r)||r;case Se.WARN:return this._clientLogger.warn(r)||r;case Se.ERROR:return this._clientLogger.error(r)||r;case Se.ADVANCED_LOG:return this._advancedLogWriter?this._clientLogger[this._advancedLogWriter](r)||r:""}}}},{key:"isLevelEnabled",value:function(e){return e>=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.prefix||he;return e.logMetaData&&this.setLogMetaData(e.logMetaData),new Ce(this,me({prefix:t,logMetaData:this.logMetaData},e))}},{key:"setLogMetaData",value:function(e){this.logMetaData=e}},{key:"updateLoggerConfig",value:function(e){var t=e||{};this._level=t.level||Se.INFO,this._advancedLogWriter="warn",t.advancedLogWriter&&(this._advancedLogWriter=t.advancedLogWriter),t.customizedLogger&&"object"===r()(t.customizedLogger)?this.useClientLogger=!0:this.useClientLogger=!1,this._clientLogger=t.logger||this.selectLogger(t),this._logsDestination=a,t.debug&&(this._logsDestination=s),t.logger&&(this._logsDestination=c)}},{key:"selectLogger",value:function(e){return e.customizedLogger&&"object"===r()(e.customizedLogger)?e.customizedLogger:e.useDefaultLogger?Le():null}}]),e}(),we=function(){function e(){de()(this,e)}return ge()(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}},{key:"advancedLog",value:function(){}}]),e}(),Ce=function(e){re()(n,e);var t=be(n);function n(e,o){var r;return de()(this,n),(r=t.call(this)).options=o||{},r.prefix=o.prefix||he,r.excludeTimestamp=o.excludeTimestamp,r.logManager=e,r}return ge()(n,[{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:2e3;de()(this,e),this.numAttempts=0,this.executor=t,this.hasActiveReconnection=!1,this.defaultRetry=n}return ge()(e,[{key:"retry",value:function(){var e=this;this.hasActiveReconnection||(this.hasActiveReconnection=!0,setTimeout((function(){e._execute()}),this._getDelay()))}},{key:"_execute",value:function(){this.hasActiveReconnection=!1,this.executor(),this.numAttempts++}},{key:"connected",value:function(){this.numAttempts=0}},{key:"_getDelay",value:function(){var e=Math.pow(2,this.numAttempts)*this.defaultRetry;return e<=3e4?e:3e4}},{key:"getIsConnected",value:function(){return!this.numAttempts}}]),e}(),_e=null,Ie=function(){var e=_e.getLogger({prefix:u,excludeTimestamp:!0}),t=ne.isNetworkOnline(),n={primary:null,secondary:null},o={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},r={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},i={pendingResponse:!1,intervalHandle:null},a={pendingResponse:!1,intervalHandle:null},c={initFailure:new Set,getWebSocketTransport:null,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set,deepHeartbeatSuccess:new Set,deepHeartbeatFailure:new Set,topicFailure:new Set},s={connConfig:null,promiseHandle:null,promiseCompleted:!0},Y={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},ee={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},te=new xe((function(){Ie()})),oe=new Set([V,X,$,K]),re=setInterval((function(){if(t!==ne.isNetworkOnline()){if(!(t=ne.isNetworkOnline()))return void Fe(e.advancedLog(l));var n=pe();t&&(!n||se(n,WebSocket.CLOSING)||se(n,WebSocket.CLOSED))&&(Fe(e.advancedLog(p)),Ie())}}),250),ie=function(t,n){t.forEach((function(t){try{t(n)}catch(t){Fe(e.error("Error executing callback",t))}}))},ae=function(e){if(null===e)return"NULL";switch(e.readyState){case WebSocket.CONNECTING:return"CONNECTING";case WebSocket.OPEN:return"OPEN";case WebSocket.CLOSING:return"CLOSING";case WebSocket.CLOSED:return"CLOSED";default:return"UNDEFINED"}},ce=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";Fe(e.debug("["+t+"] Primary WebSocket: "+ae(n.primary)+" | Secondary WebSocket: "+ae(n.secondary)))},se=function(e,t){return e&&e.readyState===t},ue=function(e){return se(e,WebSocket.OPEN)},le=function(e){return null===e||void 0===e.readyState||se(e,WebSocket.CLOSED)},pe=function(){return null!==n.secondary?n.secondary:n.primary},de=function(){return ue(pe())},fe=function(){if(a.pendingResponse&&(Fe(e.debug(g)),ie(c.deepHeartbeatFailure,{timestamp:Date.now(),error:"aws/ping response is not received"}),clearInterval(a.intervalHandle),a.pendingResponse=!1),i.pendingResponse)return Fe(e.warn(f)),clearInterval(i.intervalHandle),i.intervalHandle=null,i.pendingResponse=!1,void Ie();de()?(Fe(e.debug(y)),pe().send(Te(K)),a.pendingResponse=!0,Fe(e.debug(m)),pe().send(Te($)),i.pendingResponse=!0):(Fe(e.debug(S)),ie(c.deepHeartbeatFailure,{timestamp:Date.now(),error:"Unable to send message to aws/ping because websocket connection is not established."}),Fe(e.warn(h)),ce("sendHeartBeat"),Ie())},ge=function(){Fe(e.advancedLog(z)),o.exponentialBackOffTime=1e3,i.pendingResponse=!1,a.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearInterval(a.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId),i.intervalHandle=null},be=function(){ee.consecutiveFailedSubscribeAttempts=0,ee.consecutiveNoResponseRequest=0,clearInterval(ee.responseCheckIntervalId),clearInterval(ee.reSubscribeIntervalId)},ve=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},me=function(){te.connected();try{Fe(e.advancedLog(O)),ce("webSocketOnOpen"),null!==o.connState&&o.connState!==Q||ie(c.connectionGain),o.connState=Z;var t=Date.now();ie(c.connectionOpen,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,noOpenConnectionsTimestamp:r.noOpenConnectionsTimestamp,connectionEstablishedTime:t,timeToConnect:t-r.connectionAttemptStartTime,timeWithoutConnection:r.noOpenConnectionsTimestamp?t-r.noOpenConnectionsTimestamp:null}),ve(),ge(),pe().openTimestamp=Date.now(),0===Y.subscribed.size&&ue(n.secondary)&&ke(n.primary,"[Primary WebSocket] Closing WebSocket"),(Y.subscribed.size>0||Y.pending.size>0)&&(ue(n.secondary)&&Fe(e.info("Subscribing secondary websocket to topics of primary websocket")),Y.subscribed.forEach((function(e){Y.subscriptionHistory.add(e),Y.pending.add(e)})),Y.subscribed.clear(),Se()),fe(),null!==i.intervalHandle&&clearInterval(i.intervalHandle),i.intervalHandle=setInterval(fe,1e4);var a=1e3*s.connConfig.webSocketTransport.transportLifeTimeInSeconds;Fe(e.debug("Scheduling WebSocket manager reconnection, after delay "+a+" ms")),o.lifeTimeTimeoutHandle=setTimeout((function(){Fe(e.debug("Starting scheduled WebSocket manager reconnection")),Ie()}),a)}catch(t){Fe(e.error("Error after establishing WebSocket connection",t))}},ye=function(t){ce("webSocketOnError"),Fe(e.advancedLog(L,t)),te.getIsConnected()?Ie():te.retry()},he=function(t){var o=JSON.parse(t.data);switch(o.topic){case V:if(Fe(e.debug("Subscription Message received from webSocket server")),ee.requestCompleted=!0,ee.consecutiveNoResponseRequest=0,"success"===o.content.status)ee.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach((function(e){Y.subscriptionHistory.delete(e),Y.pending.delete(e),Y.subscribed.add(e)})),0===Y.subscriptionHistory.size?ue(n.secondary)&&(Fe(e.debug("Successfully subscribed secondary websocket to all topics of primary websocket")),ke(n.primary,"[Primary WebSocket] Closing WebSocket")):Se(),ie(c.subscriptionUpdate,o);else{if(clearInterval(ee.reSubscribeIntervalId),++ee.consecutiveFailedSubscribeAttempts,5===ee.consecutiveFailedSubscribeAttempts)return ie(c.subscriptionFailure,o),void(ee.consecutiveFailedSubscribeAttempts=0);ee.reSubscribeIntervalId=setInterval((function(){Se()}),500)}break;case $:Fe(e.debug(b)),i.pendingResponse=!1,null===i.intervalHandle&&(i.intervalHandle=setInterval(fe,1e4));break;case K:Fe(e.debug(v)),a.pendingResponse=!1,200===o.statusCode?ie(c.deepHeartbeatSuccess,{timestamp:Date.now()}):ie(c.deepHeartbeatFailure,{timestamp:Date.now(),statusCode:o.statusCode,statusContent:o.statusContent});break;default:if(o.topic){if(Fe(e.advancedLog(q,o.topic)),ue(n.primary)&&ue(n.secondary)&&0===Y.subscriptionHistory.size&&this===n.primary)return void Fe(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===c.allMessage.size&&0===c.topic.size)return void Fe(e.warn("No registered callback listener for Topic",o.topic));Fe(e.advancedLog(J,o.topic)),ie(c.allMessage,o),c.topic.has(o.topic)&&ie(c.topic.get(o.topic),o)}else o.message?(Fe(e.advancedLog(U,o)),ie(c.topicFailure,{timestamp:Date.now(),errorMessage:o.message,connectionId:o.connectionId,requestId:o.requestId})):Fe(e.advancedLog(B,o))}},Se=function t(){if(ee.consecutiveNoResponseRequest>3)return Fe(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void ie(c.subscriptionFailure,ne.getSubscriptionResponse(V,!1,Array.from(Y.pending)));de()?0!==Array.from(Y.pending).length&&(clearInterval(ee.responseCheckIntervalId),pe().send(Te(V,{topics:Array.from(Y.pending)})),ee.requestCompleted=!1,ee.responseCheckIntervalId=setInterval((function(){ee.requestCompleted||(++ee.consecutiveNoResponseRequest,t())}),1e3)):Fe(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},ke=function(t,n){se(t,WebSocket.CONNECTING)||se(t,WebSocket.OPEN)?t.close(1e3,n):Fe(e.warn("Ignoring WebSocket Close request, WebSocket State: "+ae(t)))},we=function(e){ke(n.primary,"[Primary] WebSocket "+e),ke(n.secondary,"[Secondary] WebSocket "+e)},Ce=function(){r.connectWebSocketRetryCount++;var t=ne.addJitter(o.exponentialBackOffTime,.3);Date.now()+t<=s.connConfig.urlConnValidTime?(Fe(e.advancedLog(x)),o.exponentialTimeoutHandle=setTimeout((function(){return We()}),t),o.exponentialBackOffTime*=2):(Fe(e.advancedLog(_)),Ie())},Oe=function(t){ge(),be(),Fe(e.advancedLog(I,t)),o.websocketInitFailed=!0,we(W),clearInterval(re),ie(c.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:t}),ve()},Te=function(e,t){return JSON.stringify({topic:e,content:t})},Le=function(t){return!!(ne.isObject(t)&&ne.isObject(t.webSocketTransport)&&ne.isNonEmptyString(t.webSocketTransport.url)&&ne.validWSUrl(t.webSocketTransport.url)&&1e3*t.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(Fe(e.error("Invalid WebSocket Connection Configuration",t)),!1)},Ie=function(){if(ne.isNetworkOnline())if(o.websocketInitFailed)Fe(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(s.promiseCompleted)return ge(),Fe(e.advancedLog(N)),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),s.promiseCompleted=!1,s.promiseHandle=c.getWebSocketTransport(),s.promiseHandle.then((function(t){return s.promiseCompleted=!0,Fe(e.advancedLog(F)),Le(t)?(s.connConfig=t,s.connConfig.urlConnValidTime=Date.now()+85e3,We()):(Oe("Invalid WebSocket connection configuration: "+t),{webSocketConnectionFailed:!0})}),(function(t){return s.promiseCompleted=!0,Fe(e.advancedLog(E,t)),ne.isNetworkFailure(t)?(Fe(e.advancedLog(M,t)),te.retry()):Oe("Failed to fetch webSocket connection configuration: "+JSON.stringify(t)),{webSocketConnectionFailed:!0}}));Fe(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else Fe(e.advancedLog(d))},We=function(){if(o.websocketInitFailed)return Fe(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!ne.isNetworkOnline())return Fe(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};Fe(e.advancedLog(D)),ce("initWebSocket");try{if(Le(s.connConfig)){var t=null;return ue(n.primary)?(Fe(e.debug("Primary Socket connection is already open")),se(n.secondary,WebSocket.CONNECTING)||(Fe(e.debug("Establishing a secondary web-socket connection")),te.numAttempts=0,n.secondary=Ne()),t=n.secondary):(se(n.primary,WebSocket.CONNECTING)||(Fe(e.debug("Establishing a primary web-socket connection")),n.primary=Ne()),t=n.primary),o.webSocketInitCheckerTimeoutId=setTimeout((function(){ue(t)||Ce()}),1e3),{webSocketConnectionFailed:!1}}}catch(t){return Fe(e.error("Error Initializing web-socket-manager",t)),Oe("Failed to initialize new WebSocket: "+t.message),{webSocketConnectionFailed:!0}}},Ne=function(){var t=new WebSocket(s.connConfig.webSocketTransport.url);return t.addEventListener("open",me),t.addEventListener("message",he),t.addEventListener("error",ye),t.addEventListener("close",(function(i){return function(t,i){Fe(e.advancedLog(T,t)),ce("webSocketOnClose before-cleanup"),ie(c.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),le(n.primary)&&(n.primary=null),le(n.secondary)&&(n.secondary=null),o.reconnectWebSocket&&(ue(n.primary)||ue(n.secondary)?le(n.primary)&&ue(n.secondary)&&(Fe(e.debug("[Primary] WebSocket Cleanly Closed")),n.primary=n.secondary,n.secondary=null):(Fe(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===Q?Fe(e.info("Ignoring connectionLost callback invocation")):(ie(c.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),r.noOpenConnectionsTimestamp=Date.now()),o.connState=Q,Ie()),ce("webSocketOnClose after-cleanup"))}(i,t)})),t},Fe=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(t){if(ne.assertTrue(ne.isFunction(t),"transportHandle must be a function"),null===c.getWebSocketTransport)return c.getWebSocketTransport=t,Ie();Fe(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(t){return Fe(e.advancedLog(R)),ne.assertTrue(ne.isFunction(t),"cb must be a function"),c.initFailure.add(t),o.websocketInitFailed&&t(),function(){return c.initFailure.delete(t)}},this.onConnectionOpen=function(t){return Fe(e.advancedLog(A)),ne.assertTrue(ne.isFunction(t),"cb must be a function"),c.connectionOpen.add(t),function(){return c.connectionOpen.delete(t)}},this.onConnectionClose=function(t){return Fe(e.advancedLog(j)),ne.assertTrue(ne.isFunction(t),"cb must be a function"),c.connectionClose.add(t),function(){return c.connectionClose.delete(t)}},this.onConnectionGain=function(t){return Fe(e.advancedLog(H)),ne.assertTrue(ne.isFunction(t),"cb must be a function"),c.connectionGain.add(t),de()&&t(),function(){return c.connectionGain.delete(t)}},this.onConnectionLost=function(t){return Fe(e.advancedLog(P)),ne.assertTrue(ne.isFunction(t),"cb must be a function"),c.connectionLost.add(t),o.connState===Q&&t(),function(){return c.connectionLost.delete(t)}},this.onSubscriptionUpdate=function(e){return ne.assertTrue(ne.isFunction(e),"cb must be a function"),c.subscriptionUpdate.add(e),function(){return c.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(t){return Fe(e.advancedLog(G)),ne.assertTrue(ne.isFunction(t),"cb must be a function"),c.subscriptionFailure.add(t),function(){return c.subscriptionFailure.delete(t)}},this.onMessage=function(e,t){return ne.assertNotNull(e,"topicName"),ne.assertTrue(ne.isFunction(t),"cb must be a function"),c.topic.has(e)?c.topic.get(e).add(t):c.topic.set(e,new Set([t])),function(){return c.topic.get(e).delete(t)}},this.onAllMessage=function(e){return ne.assertTrue(ne.isFunction(e),"cb must be a function"),c.allMessage.add(e),function(){return c.allMessage.delete(e)}},this.subscribeTopics=function(e){ne.assertNotNull(e,"topics"),ne.assertIsList(e),e.forEach((function(e){Y.subscribed.has(e)||Y.pending.add(e)})),ee.consecutiveNoResponseRequest=0,Se()},this.sendMessage=function(t){if(ne.assertIsObject(t,"payload"),void 0===t.topic||oe.has(t.topic))Fe(e.warn("Cannot send message, Invalid topic: "+t.topic));else{try{t=JSON.stringify(t)}catch(n){return void Fe(e.warn("Error stringify message",t))}de()?pe().send(t):Fe(e.warn("Cannot send message, web socket connection is not open"))}},this.onDeepHeartbeatSuccess=function(t){return Fe(e.advancedLog(k)),ne.assertTrue(ne.isFunction(t),"cb must be a function"),c.deepHeartbeatSuccess.add(t),function(){return c.deepHeartbeatSuccess.delete(t)}},this.onDeepHeartbeatFailure=function(t){return Fe(e.advancedLog(w)),ne.assertTrue(ne.isFunction(t),"cb must be a function"),c.deepHeartbeatFailure.add(t),function(){return c.deepHeartbeatFailure.delete(t)}},this.onTopicFailure=function(t){return Fe(e.advancedLog(C)),ne.assertTrue(ne.isFunction(t),"cb must be a function"),c.topicFailure.add(t),function(){return c.topicFailure.delete(t)}},this.closeWebSocket=function(){ge(),be(),o.reconnectWebSocket=!1,clearInterval(re),we("User request to close WebSocket")},this.terminateWebSocketManager=Oe},We={create:function(e){return _e||(_e=new ke(e)),_e.hasLogMetaData()||_e.setLogMetaData(e),new Ie},setGlobalConfig:function(e){var t=e&&e.loggerConfig;_e||(_e=new ke),_e.updateLoggerConfig(t);var n=e&&e.webSocketManagerConfig,o=n&&n.isNetworkOnline;o&&"function"==typeof o&&(ne.isNetworkOnline=o)},LogLevel:Se,Logger:ye};global.connect=global.connect||{},connect.WebSocketManager=We;var Ne=We;t.default=Ne}]); +(()=>{var e={975:(e,n,t)=>{var o;!function(){"use strict";var r={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function i(e){return function(e,n){var t,o,c,a,s,u,l,d,p,f=1,g=e.length,b="";for(o=0;o=0),a.type){case"b":t=parseInt(t,10).toString(2);break;case"c":t=String.fromCharCode(parseInt(t,10));break;case"d":case"i":t=parseInt(t,10);break;case"j":t=JSON.stringify(t,null,a.width?parseInt(a.width):0);break;case"e":t=a.precision?parseFloat(t).toExponential(a.precision):parseFloat(t).toExponential();break;case"f":t=a.precision?parseFloat(t).toFixed(a.precision):parseFloat(t);break;case"g":t=a.precision?String(Number(t.toPrecision(a.precision))):parseFloat(t);break;case"o":t=(parseInt(t,10)>>>0).toString(8);break;case"s":t=String(t),t=a.precision?t.substring(0,a.precision):t;break;case"t":t=String(!!t),t=a.precision?t.substring(0,a.precision):t;break;case"T":t=Object.prototype.toString.call(t).slice(8,-1).toLowerCase(),t=a.precision?t.substring(0,a.precision):t;break;case"u":t=parseInt(t,10)>>>0;break;case"v":t=t.valueOf(),t=a.precision?t.substring(0,a.precision):t;break;case"x":t=(parseInt(t,10)>>>0).toString(16);break;case"X":t=(parseInt(t,10)>>>0).toString(16).toUpperCase()}r.json.test(a.type)?b+=t:(!r.number.test(a.type)||d&&!a.sign?p="":(p=d?"+":"-",t=t.toString().replace(r.sign,"")),u=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",l=a.width-(p+t).length,s=a.width&&l>0?u.repeat(l):"",b+=a.align?p+t+s:"0"===u?p+s+t:s+p+t)}return b}(function(e){if(a[e])return a[e];for(var n,t=e,o=[],i=0;t;){if(null!==(n=r.text.exec(t)))o.push(n[0]);else if(null!==(n=r.modulo.exec(t)))o.push("%");else{if(null===(n=r.placeholder.exec(t)))throw new SyntaxError("[sprintf] unexpected placeholder");if(n[2]){i|=1;var c=[],s=n[2],u=[];if(null===(u=r.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(c.push(u[1]);""!==(s=s.substring(u[0].length));)if(null!==(u=r.key_access.exec(s)))c.push(u[1]);else{if(null===(u=r.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");c.push(u[1])}n[2]=c}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:n[0],param_no:n[1],keys:n[2],sign:n[3],pad_char:n[4],align:n[5],width:n[6],precision:n[7],type:n[8]})}t=t.substring(n[0].length)}return a[e]=o}(e),arguments)}function c(e,n){return i.apply(null,[e].concat(n||[]))}var a=Object.create(null);n.sprintf=i,n.vsprintf=c,"undefined"!=typeof window&&(window.sprintf=i,window.vsprintf=c,void 0===(o=function(){return{sprintf:i,vsprintf:c}}.call(n,t,n,e))||(e.exports=o))}()}},n={};function t(o){var r=n[o];if(void 0!==r)return r.exports;var i=n[o]={exports:{}};return e[o](i,i.exports,t),i.exports}(()=>{"use strict";function e(n){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(n)}var n=t(975),o="AMZ_WEB_SOCKET_MANAGER:",r="aws/subscribe",i="aws/heartbeat",c="aws/ping",a="disconnected",s={assertTrue:function(e,n){if(!e)throw new Error(n)},assertNotNull:function(t,o){return s.assertTrue(null!==t&&void 0!==e(t),(0,n.sprintf)("%s must be provided",o||"A value")),t},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,n){if(!Array.isArray(e))throw new Error(n+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(n){return!("object"!==e(n)||null===n)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},u=new RegExp("^(wss://)\\w*"),l=new RegExp("^(ws://127.0.0.1:)");s.validWSUrl=function(e){return u.test(e)||l.test(e)},s.getSubscriptionResponse=function(e,n,t){return{topic:e,content:{status:n?"success":"failure",topics:t}}},s.assertIsObject=function(e,n){if(!s.isObject(e))throw new Error(n+" is not an object!")},s.addJitter=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;n=Math.min(n,1);var t=Math.random()>.5?1:-1;return Math.floor(e+t*e*Math.random()*n)},s.isNetworkOnline=function(){return navigator.onLine},s.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};const d=s;function p(e,n){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,n){return e.__proto__=n,e},p(e,n)}function f(e){return f=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},f(e)}function g(e,n,t){return n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function b(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}function m(e,n){for(var t=0;t1&&void 0!==arguments[1]?arguments[1]:"";if(this.hasClientLogger()){var t="string"==typeof n?n:JSON.stringify(n,O()),o="string"==typeof this.logMetaData?this.logMetaData:JSON.stringify(this.logMetaData,O()),r="".concat(function(e){switch(e){case 10:return"DEBUG";case 20:return"INFO";case 30:return"WARN";case 40:return"ERROR";case 50:return"ADVANCED_LOG"}}(e)," ").concat(t);switch(o&&(r+=" ".concat(o)),e){case S.DEBUG:return this._clientLogger.debug(r)||r;case S.INFO:return this._clientLogger.info(r)||r;case S.WARN:return this._clientLogger.warn(r)||r;case S.ERROR:return this._clientLogger.error(r)||r;case S.ADVANCED_LOG:return this._advancedLogWriter?this._clientLogger[this._advancedLogWriter](r)||r:""}}}},{key:"isLevelEnabled",value:function(e){return e>=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.prefix||w;return e.logMetaData&&this.setLogMetaData(e.logMetaData),new L(this,function(e){for(var n=1;n1&&void 0!==arguments[1]?arguments[1]:2e3;b(this,e),this.numAttempts=0,this.executor=n,this.hasActiveReconnection=!1,this.defaultRetry=t}return v(e,[{key:"retry",value:function(){var e=this;this.hasActiveReconnection||(this.hasActiveReconnection=!0,setTimeout((function(){e._execute()}),this._getDelay()))}},{key:"_execute",value:function(){this.hasActiveReconnection=!1,this.executor(),this.numAttempts++}},{key:"connected",value:function(){this.numAttempts=0}},{key:"_getDelay",value:function(){var e=Math.pow(2,this.numAttempts)*this.defaultRetry;return e<=3e4?e:3e4}},{key:"getIsConnected",value:function(){return!this.numAttempts}}]),e}(),N=null,F=function(){var e=N.getLogger({prefix:o,excludeTimestamp:!0}),n=d.isNetworkOnline(),t={primary:null,secondary:null},s={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},u={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},l={pendingResponse:!1,intervalHandle:null},p={pendingResponse:!1,intervalHandle:null},f={initFailure:new Set,getWebSocketTransport:null,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set,deepHeartbeatSuccess:new Set,deepHeartbeatFailure:new Set,topicFailure:new Set},g={connConfig:null,promiseHandle:null,promiseCompleted:!0},b={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},m={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},v=new I((function(){U().catch((function(){}))})),h=new Set([r,"aws/unsubscribe",i,c]),y=setInterval((function(){if(n!==d.isNetworkOnline()){if(!(n=d.isNetworkOnline()))return void J(e.advancedLog("Network offline"));var t=O();n&&(!t||C(t,WebSocket.CLOSING)||C(t,WebSocket.CLOSED))&&(J(e.advancedLog("Network online, connecting to WebSocket server")),U().catch((function(){})))}}),250),k=function(n,t){n.forEach((function(n){try{n(t)}catch(n){J(e.error("Error executing callback",n))}}))},w=function(e){if(null===e)return"NULL";switch(e.readyState){case WebSocket.CONNECTING:return"CONNECTING";case WebSocket.OPEN:return"OPEN";case WebSocket.CLOSING:return"CLOSING";case WebSocket.CLOSED:return"CLOSED";default:return"UNDEFINED"}},S=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";J(e.debug("["+n+"] Primary WebSocket: "+w(t.primary)+" | Secondary WebSocket: "+w(t.secondary)))},C=function(e,n){return e&&e.readyState===n},T=function(e){return C(e,WebSocket.OPEN)},L=function(e){return null===e||void 0===e.readyState||C(e,WebSocket.CLOSED)},O=function(){return null!==t.secondary?t.secondary:t.primary},W=function(){return T(O())},F=function(){if(p.pendingResponse&&(J(e.debug("aws/ping deep heartbeat response not received")),k(f.deepHeartbeatFailure,{timestamp:Date.now(),error:"aws/ping response is not received"}),clearInterval(p.intervalHandle),p.pendingResponse=!1),l.pendingResponse)return J(e.warn("Heartbeat response not received")),clearInterval(l.intervalHandle),l.intervalHandle=null,l.pendingResponse=!1,void U().catch((function(){}));W()?(J(e.debug("Sending aws/ping deep heartbeat")),O().send(G(c)),p.pendingResponse=!0,J(e.debug("Sending heartbeat")),O().send(G(i)),l.pendingResponse=!0):(J(e.debug("Failed to send aws/ping deep heartbeat since WebSocket is not open")),k(f.deepHeartbeatFailure,{timestamp:Date.now(),error:"Unable to send message to aws/ping because websocket connection is not established."}),J(e.warn("Failed to send heartbeat since WebSocket is not open")),S("sendHeartBeat"),U().catch((function(){})))},_=function(){J(e.advancedLog("Reset Websocket state")),s.exponentialBackOffTime=1e3,l.pendingResponse=!1,p.pendingResponse=!1,s.reconnectWebSocket=!0,clearTimeout(s.lifeTimeTimeoutHandle),clearInterval(l.intervalHandle),clearInterval(p.intervalHandle),clearTimeout(s.exponentialTimeoutHandle),clearTimeout(s.webSocketInitCheckerTimeoutId),l.intervalHandle=null},E=function(){m.consecutiveFailedSubscribeAttempts=0,m.consecutiveNoResponseRequest=0,clearInterval(m.responseCheckIntervalId),clearInterval(m.reSubscribeIntervalId)},D=function(){u.connectWebSocketRetryCount=0,u.connectionAttemptStartTime=null,u.noOpenConnectionsTimestamp=null},R=function(){v.connected();try{J(e.advancedLog("WebSocket connection established!")),S("webSocketOnOpen"),null!==s.connState&&s.connState!==a||k(f.connectionGain),s.connState="connected";var n=Date.now();k(f.connectionOpen,{connectWebSocketRetryCount:u.connectWebSocketRetryCount,connectionAttemptStartTime:u.connectionAttemptStartTime,noOpenConnectionsTimestamp:u.noOpenConnectionsTimestamp,connectionEstablishedTime:n,timeToConnect:n-u.connectionAttemptStartTime,timeWithoutConnection:u.noOpenConnectionsTimestamp?n-u.noOpenConnectionsTimestamp:null}),D(),_(),O().openTimestamp=Date.now(),0===b.subscribed.size&&T(t.secondary)&&j(t.primary,"[Primary WebSocket] Closing WebSocket"),(b.subscribed.size>0||b.pending.size>0)&&(T(t.secondary)&&J(e.info("Subscribing secondary websocket to topics of primary websocket")),b.subscribed.forEach((function(e){b.subscriptionHistory.add(e),b.pending.add(e)})),b.subscribed.clear(),M()),F(),null!==l.intervalHandle&&clearInterval(l.intervalHandle),l.intervalHandle=setInterval(F,1e4);var o=1e3*g.connConfig.webSocketTransport.transportLifeTimeInSeconds;J(e.debug("Scheduling WebSocket manager reconnection, after delay "+o+" ms")),s.lifeTimeTimeoutHandle=setTimeout((function(){J(e.debug("Starting scheduled WebSocket manager reconnection")),U().catch((function(){}))}),o)}catch(n){J(e.error("Error after establishing WebSocket connection",n))}},x=function(n){S("webSocketOnError"),J(e.advancedLog("WebSocketManager Error, error_event: ",JSON.stringify(n))),v.getIsConnected()?U().catch((function(){})):v.retry()},A=function(n){if(void 0!==n.data&&""!==n.data){var o=JSON.parse(n.data);switch(o.topic){case r:if(J(e.debug("Subscription Message received from webSocket server")),m.requestCompleted=!0,m.consecutiveNoResponseRequest=0,"success"===o.content.status)m.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach((function(e){b.subscriptionHistory.delete(e),b.pending.delete(e),b.subscribed.add(e)})),0===b.subscriptionHistory.size?T(t.secondary)&&(J(e.debug("Successfully subscribed secondary websocket to all topics of primary websocket")),j(t.primary,"[Primary WebSocket] Closing WebSocket")):M(),k(f.subscriptionUpdate,o);else{if(clearInterval(m.reSubscribeIntervalId),++m.consecutiveFailedSubscribeAttempts,5===m.consecutiveFailedSubscribeAttempts)return k(f.subscriptionFailure,o),void(m.consecutiveFailedSubscribeAttempts=0);m.reSubscribeIntervalId=setInterval((function(){M()}),500)}break;case i:J(e.debug("Heartbeat response received")),l.pendingResponse=!1,null===l.intervalHandle&&(l.intervalHandle=setInterval(F,1e4));break;case c:J(e.debug("aws/ping deep heartbeat received")),p.pendingResponse=!1,200===o.statusCode?k(f.deepHeartbeatSuccess,{timestamp:Date.now()}):k(f.deepHeartbeatFailure,{timestamp:Date.now(),statusCode:o.statusCode,statusContent:o.statusContent});break;default:if(o.topic){if(J(e.advancedLog("Message received for topic ",o.topic)),T(t.primary)&&T(t.secondary)&&0===b.subscriptionHistory.size&&this===t.primary)return void J(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===f.allMessage.size&&0===f.topic.size)return void J(e.warn("No registered callback listener for Topic",o.topic));J(e.advancedLog("WebsocketManager invoke callbacks for topic success ",o.topic)),k(f.allMessage,o),f.topic.has(o.topic)&&k(f.topic.get(o.topic),o)}else o.message?(J(e.advancedLog("WebSocketManager Message Error",o)),k(f.topicFailure,{timestamp:Date.now(),errorMessage:o.message,connectionId:o.connectionId,requestId:o.requestId})):J(e.advancedLog("Invalid incoming message",o))}}else J(e.warn("An empty message has been received on Websocket. Ignoring"))},M=function n(){if(m.consecutiveNoResponseRequest>3)return J(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void k(f.subscriptionFailure,d.getSubscriptionResponse(r,!1,Array.from(b.pending)));W()?0!==Array.from(b.pending).length&&(clearInterval(m.responseCheckIntervalId),O().send(G(r,{topics:Array.from(b.pending)})),m.requestCompleted=!1,m.responseCheckIntervalId=setInterval((function(){m.requestCompleted||(++m.consecutiveNoResponseRequest,n())}),1e3)):J(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},j=function(n,t){C(n,WebSocket.CONNECTING)||C(n,WebSocket.OPEN)?n.close(1e3,t):J(e.warn("Ignoring WebSocket Close request, WebSocket State: "+w(n)))},H=function(e){j(t.primary,"[Primary] WebSocket "+e),j(t.secondary,"[Secondary] WebSocket "+e)},P=function(n){_(),E(),J(e.advancedLog("WebSocket Initialization failed - Terminating and cleaning subscriptions",n)),s.websocketInitFailed=!0,H("Terminating WebSocket Manager"),clearInterval(y),k(f.initFailure,{connectWebSocketRetryCount:u.connectWebSocketRetryCount,connectionAttemptStartTime:u.connectionAttemptStartTime,reason:n}),D()},G=function(e,n){return JSON.stringify({topic:e,content:n})},z=function(n){return!!(d.isObject(n)&&d.isObject(n.webSocketTransport)&&d.isNonEmptyString(n.webSocketTransport.url)&&d.validWSUrl(n.webSocketTransport.url)&&1e3*n.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(J(e.error("Invalid WebSocket Connection Configuration",n)),!1)},U=function(){return d.isNetworkOnline()?s.websocketInitFailed?(J(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request")),Promise.resolve({webSocketConnectionFailed:!0})):g.promiseCompleted?(_(),J(e.advancedLog("Fetching new WebSocket connection configuration")),u.connectionAttemptStartTime=u.connectionAttemptStartTime||Date.now(),g.promiseCompleted=!1,g.promiseHandle=f.getWebSocketTransport(),g.promiseHandle.then((function(n){return g.promiseCompleted=!0,J(e.advancedLog("Successfully fetched webSocket connection configuration")),z(n)?(g.connConfig=n,g.connConfig.urlConnValidTime=Date.now()+85e3,q()):(P("Invalid WebSocket connection configuration: "+n),{webSocketConnectionFailed:!0})}),(function(n){return g.promiseCompleted=!0,J(e.advancedLog("Failed to fetch webSocket connection configuration",n)),d.isNetworkFailure(n)?(J(e.advancedLog("Retrying fetching new WebSocket connection configuration",n)),v.retry()):P("Failed to fetch webSocket connection configuration: "+JSON.stringify(n)),{webSocketConnectionFailed:!0}}))):(J(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored")),Promise.resolve({webSocketConnectionFailed:!0})):(J(e.advancedLog("Network offline, ignoring this getWebSocketConnConfig request")),Promise.resolve({webSocketConnectionFailed:!0}))},q=function(){if(s.websocketInitFailed)return J(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!d.isNetworkOnline())return J(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};J(e.advancedLog("Initializing Websocket Manager")),S("initWebSocket");try{if(z(g.connConfig)){var n=null;return T(t.primary)?(J(e.debug("Primary Socket connection is already open")),C(t.secondary,WebSocket.CONNECTING)||(J(e.debug("Establishing a secondary web-socket connection")),v.numAttempts=0,t.secondary=B()),n=t.secondary):(C(t.primary,WebSocket.CONNECTING)||(J(e.debug("Establishing a primary web-socket connection")),t.primary=B()),n=t.primary),s.webSocketInitCheckerTimeoutId=setTimeout((function(){T(n)||function(){u.connectWebSocketRetryCount++;var n=d.addJitter(s.exponentialBackOffTime,.3);Date.now()+n<=g.connConfig.urlConnValidTime?(J(e.advancedLog("Scheduling WebSocket reinitialization, after delay "+n+" ms")),s.exponentialTimeoutHandle=setTimeout((function(){return q()}),n),s.exponentialBackOffTime*=2):(J(e.advancedLog("WebSocket URL cannot be used to establish connection")),U().catch((function(){})))}()}),1e3),{webSocketConnectionFailed:!1}}}catch(n){return J(e.error("Error Initializing web-socket-manager",n)),P("Failed to initialize new WebSocket: "+n.message),{webSocketConnectionFailed:!0}}},B=function(){var n=new WebSocket(g.connConfig.webSocketTransport.url);return n.addEventListener("open",R),n.addEventListener("message",A),n.addEventListener("error",x),n.addEventListener("close",(function(o){return function(n,o){var r={openTimestamp:o.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-o.openTimestamp,code:n.code,reason:n.reason,wasClean:n.wasClean},i="Close Code: ".concat(r.code," - Reason: ").concat(r.reason," - WasClean: ").concat(r.wasClean),c="OpenTimestamp: ".concat(r.openTimestamp," - CloseTimestamp: ").concat(r.closeTimestamp," - ConnectionDuration: ").concat(r.connectionDuration);J(e.advancedLog("WebSocket connection is closed. ",i)),J(e.advancedLog("Closed WebSocket connection duration: ",c)),S("webSocketOnClose before-cleanup"),k(f.connectionClose,r),L(t.primary)&&(t.primary=null),L(t.secondary)&&(t.secondary=null),s.reconnectWebSocket&&(T(t.primary)||T(t.secondary)?L(t.primary)&&T(t.secondary)&&(J(e.debug("[Primary] WebSocket Cleanly Closed")),t.primary=t.secondary,t.secondary=null):(J(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),s.connState===a?J(e.info("Ignoring connectionLost callback invocation")):(k(f.connectionLost,{openTimestamp:o.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-o.openTimestamp,code:n.code,reason:n.reason}),u.noOpenConnectionsTimestamp=Date.now()),s.connState=a,U().catch((function(){}))),S("webSocketOnClose after-cleanup"))}(o,n)})),n},J=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(n){if(d.assertTrue(d.isFunction(n),"transportHandle must be a function"),null===f.getWebSocketTransport)return f.getWebSocketTransport=n,U();J(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(n){return J(e.advancedLog("Initializing Websocket Manager Failure callback registered")),d.assertTrue(d.isFunction(n),"cb must be a function"),f.initFailure.add(n),s.websocketInitFailed&&n(),function(){return f.initFailure.delete(n)}},this.onConnectionOpen=function(n){return J(e.advancedLog("Websocket connection open callback registered")),d.assertTrue(d.isFunction(n),"cb must be a function"),f.connectionOpen.add(n),function(){return f.connectionOpen.delete(n)}},this.onConnectionClose=function(n){return J(e.advancedLog("Websocket connection close callback registered")),d.assertTrue(d.isFunction(n),"cb must be a function"),f.connectionClose.add(n),function(){return f.connectionClose.delete(n)}},this.onConnectionGain=function(n){return J(e.advancedLog("Websocket connection gain callback registered")),d.assertTrue(d.isFunction(n),"cb must be a function"),f.connectionGain.add(n),W()&&n(),function(){return f.connectionGain.delete(n)}},this.onConnectionLost=function(n){return J(e.advancedLog("Websocket connection lost callback registered")),d.assertTrue(d.isFunction(n),"cb must be a function"),f.connectionLost.add(n),s.connState===a&&n(),function(){return f.connectionLost.delete(n)}},this.onSubscriptionUpdate=function(e){return d.assertTrue(d.isFunction(e),"cb must be a function"),f.subscriptionUpdate.add(e),function(){return f.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(n){return J(e.advancedLog("Websocket subscription failure callback registered")),d.assertTrue(d.isFunction(n),"cb must be a function"),f.subscriptionFailure.add(n),function(){return f.subscriptionFailure.delete(n)}},this.onMessage=function(e,n){return d.assertNotNull(e,"topicName"),d.assertTrue(d.isFunction(n),"cb must be a function"),f.topic.has(e)?f.topic.get(e).add(n):f.topic.set(e,new Set([n])),function(){return f.topic.get(e).delete(n)}},this.onAllMessage=function(e){return d.assertTrue(d.isFunction(e),"cb must be a function"),f.allMessage.add(e),function(){return f.allMessage.delete(e)}},this.subscribeTopics=function(e){d.assertNotNull(e,"topics"),d.assertIsList(e),e.forEach((function(e){b.subscribed.has(e)||b.pending.add(e)})),m.consecutiveNoResponseRequest=0,M()},this.sendMessage=function(n){if(d.assertIsObject(n,"payload"),void 0===n.topic||h.has(n.topic))J(e.warn("Cannot send message, Invalid topic: "+n.topic));else{try{n=JSON.stringify(n)}catch(t){return void J(e.warn("Error stringify message",n))}W()?O().send(n):J(e.warn("Cannot send message, web socket connection is not open"))}},this.onDeepHeartbeatSuccess=function(n){return J(e.advancedLog("Websocket deep heartbeat success callback registered")),d.assertTrue(d.isFunction(n),"cb must be a function"),f.deepHeartbeatSuccess.add(n),function(){return f.deepHeartbeatSuccess.delete(n)}},this.onDeepHeartbeatFailure=function(n){return J(e.advancedLog("Websocket deep heartbeat failure callback registered")),d.assertTrue(d.isFunction(n),"cb must be a function"),f.deepHeartbeatFailure.add(n),function(){return f.deepHeartbeatFailure.delete(n)}},this.onTopicFailure=function(n){return J(e.advancedLog("Websocket topic failure callback registered")),d.assertTrue(d.isFunction(n),"cb must be a function"),f.topicFailure.add(n),function(){return f.topicFailure.delete(n)}},this.closeWebSocket=function(){_(),E(),s.reconnectWebSocket=!1,clearInterval(y),H("User request to close WebSocket")},this.terminateWebSocketManager=P},_={create:function(e){return N||(N=new C(e)),N.hasLogMetaData()||N.setLogMetaData(e),new F},setGlobalConfig:function(e){var n=e&&e.loggerConfig;N||(N=new C),N.updateLoggerConfig(n);var t=e&&e.webSocketManagerConfig,o=t&&t.isNetworkOnline;o&&"function"==typeof o&&(d.isNetworkOnline=o)},LogLevel:S,Logger:k};global.connect=global.connect||{},connect.WebSocketManager=_})()})(); //# sourceMappingURL=amazon-connect-websocket-manager.js.map const WebSocketManager = connect.WebSocketManager; diff --git a/src/lib/amazon-connect-websocket-manager.js.map b/src/lib/amazon-connect-websocket-manager.js.map index 29cca8d..7e88672 100644 --- a/src/lib/amazon-connect-websocket-manager.js.map +++ b/src/lib/amazon-connect-websocket-manager.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap","webpack:///./node_modules/@babel/runtime/helpers/typeof.js","webpack:///./node_modules/@babel/runtime/helpers/classCallCheck.js","webpack:///./node_modules/@babel/runtime/helpers/createClass.js","webpack:///./node_modules/@babel/runtime/helpers/getPrototypeOf.js","webpack:///./node_modules/sprintf-js/src/sprintf.js","webpack:///./node_modules/@babel/runtime/helpers/inherits.js","webpack:///./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js","webpack:///./node_modules/@babel/runtime/helpers/defineProperty.js","webpack:///./node_modules/@babel/runtime/helpers/setPrototypeOf.js","webpack:///./node_modules/@babel/runtime/helpers/assertThisInitialized.js","webpack:///./src/constants.js","webpack:///./src/utils.js","webpack:///./src/log.js","webpack:///./src/retryProvider.js","webpack:///./src/webSocketManager.js","webpack:///./src/index.js"],"names":["installedModules","__webpack_require__","moduleId","exports","module","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","_typeof","obj","iterator","constructor","instance","Constructor","TypeError","_defineProperties","target","props","length","descriptor","configurable","writable","protoProps","staticProps","_getPrototypeOf","setPrototypeOf","getPrototypeOf","__proto__","re","not_string","not_bool","not_type","not_primitive","number","numeric_arg","json","not_json","text","modulo","placeholder","key_access","index_access","sign","sprintf","sprintf_format","sprintf_parse","arguments","vsprintf","fmt","argv","apply","concat","parse_tree","arg","k","ph","pad","pad_character","pad_length","is_positive","cursor","tree_length","output","keys","undefined","Error","param_no","test","type","Function","isNaN","parseInt","toString","String","fromCharCode","JSON","stringify","width","precision","parseFloat","toExponential","toFixed","Number","toPrecision","substring","slice","toLowerCase","valueOf","toUpperCase","replace","pad_char","charAt","repeat","align","sprintf_cache","match","_fmt","arg_names","exec","push","SyntaxError","field_list","replacement_field","field_match","window","subClass","superClass","assertThisInitialized","self","_setPrototypeOf","ReferenceError","LOGS_DESTINATION","LOG_MESSAGES","ROUTE_KEY","CONN_STATE","Utils","premise","message","assertTrue","Array","isArray","wsRegex","RegExp","localWsRegex","validWSUrl","wsUrl","getSubscriptionResponse","routeKey","isSuccess","topicList","topic","content","status","topics","assertIsObject","isObject","addJitter","base","maxJitter","Math","min","random","floor","isNetworkOnline","navigator","onLine","isNetworkFailure","reason","_debug","Logger","data","DEFAULT_PREFIX","LogLevel","DEBUG","INFO","WARN","ERROR","ADVANCED_LOG","LogManagerImpl","logMetaData","this","updateLoggerConfig","level","logStatement","hasClientLogger","log1","removeCircularReference","log2","logStringValue","getLogLevelByValue","_clientLogger","debug","info","warn","error","_advancedLogWriter","_level","options","prefix","setLogMetaData","console","LoggerWrapperImpl","inputConfig","config","advancedLogWriter","customizedLogger","useClientLogger","logger","selectLogger","_logsDestination","useDefaultLogger","createConsoleLogger","LoggerWrapper","logManagerInstance","logManager","args","_log","isLevelEnabled","writeToClientLogger","_shouldLog","_convertToSingleStatement","_writeToClientLogger","date","Date","now","toISOString","index","_convertToString","isString","isFunction","toStringResult","seen","WeakSet","has","add","RetryProvider","executor","defaultRetry","numAttempts","hasActiveReconnection","setTimeout","_execute","_getDelay","calculatedDelay","pow","WebSocketManager","enableDeepHeartbeat","getLogger","online","webSocket","primary","secondary","reconnectConfig","reconnectWebSocket","websocketInitFailed","exponentialBackOffTime","exponentialTimeoutHandle","lifeTimeTimeoutHandle","webSocketInitCheckerTimeoutId","connState","metrics","connectWebSocketRetryCount","connectionAttemptStartTime","noOpenConnectionsTimestamp","heartbeatConfig","pendingResponse","intervalHandle","deepHeartbeatConfig","callbacks","initFailure","Set","getWebSocketTransport","subscriptionUpdate","subscriptionFailure","Map","allMessage","connectionGain","connectionLost","connectionOpen","connectionClose","deepHeartbeatSuccess","deepHeartbeatFailure","topicFailure","webSocketConfig","connConfig","promiseHandle","promiseCompleted","topicSubscription","subscribed","pending","subscriptionHistory","topicSubscriptionConfig","responseCheckIntervalId","requestCompleted","reSubscribeIntervalId","consecutiveFailedSubscribeAttempts","consecutiveNoResponseRequest","reconnectionClient","getWebSocketConnConfig","invalidSendMessageRouteKeys","networkConnectivityChecker","setInterval","advancedLog","sendInternalLogToServer","ws","getDefaultWebSocket","isWebSocketState","WebSocket","CLOSING","CLOSED","invokeCallbacks","response","forEach","callback","getWebSocketStates","readyState","CONNECTING","OPEN","printWebSocketState","event","webSocketStateCode","isWebSocketOpen","isWebSocketClosed","isDefaultWebSocketOpen","sendHeartBeat","timestamp","clearInterval","send","createWebSocketPayload","resetWebSocketState","clearTimeout","resetSubscriptions","resetMetrics","webSocketOnOpen","connected","connectionEstablishedTime","timeToConnect","timeWithoutConnection","openTimestamp","size","closeSpecificWebSocket","clear","subscribePendingTopics","webSocketLifetimeTimeout","webSocketTransport","transportLifeTimeInSeconds","webSocketOnError","getIsConnected","retry","webSocketOnMessage","parse","topicName","statusCode","statusContent","errorMessage","connectionId","requestId","from","close","closeWebSocket","retryWebSocketInitialization","waitTime","urlConnValidTime","initWebSocket","terminateWebSocketManager","validWebSocketConnConfig","isNonEmptyString","url","then","webSocketConnectionFailed","getNewWebSocket","addEventListener","closeTimestamp","connectionDuration","code","webSocketOnClose","logEntry","init","transportHandle","onInitFailure","cb","onConnectionOpen","onConnectionClose","onConnectionGain","onConnectionLost","onSubscriptionUpdate","onSubscriptionFailure","onMessage","assertNotNull","set","onAllMessage","subscribeTopics","assertIsList","sendMessage","payload","deepHeartbeatHandler","onDeepHeartbeatSuccess","onDeepHeartbeatFailure","onTopicFailure","WebSocketManagerObject","hasLogMetaData","setGlobalConfig","loggerConfig","webSocketManagerConfig","customIsNetworkOnline","global","connect"],"mappings":"aACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QAKfF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAAXiB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAeb,EAASiB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAeb,EAAS,aAAc,CAAEmB,OAAO,KAQvDrB,EAAoBsB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQrB,EAAoBqB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,OAAO,MAGvB,GAFA1B,EAAoBkB,EAAEO,GACtBX,OAAOC,eAAeU,EAAI,UAAW,CAAET,YAAY,EAAMK,MAAOA,IACtD,EAAPE,GAA4B,iBAATF,EAAmB,IAAI,IAAIM,KAAON,EAAOrB,EAAoBU,EAAEe,EAAIE,EAAK,SAASA,GAAO,OAAON,EAAMM,IAAQC,KAAK,KAAMD,IAC9I,OAAOF,GAIRzB,EAAoB6B,EAAI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mC,GAAmBhC,mBAAmB6N,GAEtC,IAAMC,EAAyBxM,GAAUA,EAAOwM,uBAC1CC,EAAwBD,GAA0BA,EAAuBhP,gBAC3EiP,GAA0D,mBAA1BA,IAChC7Q,GAAM4B,gBAAkBiP,IAO5BxO,SAAUA,GACVH,OAAQA,ICl6BZ4O,OAAOC,QAAUD,OAAOC,SAAW,GACnCA,QAAQjK,iBAAmB0J,GAEpB,IAAM1J,GAAmB0J,GAEjB1J","file":"amazon-connect-websocket-manager.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 10);\n","function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(obj);\n}\n\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nmodule.exports = _classCallCheck, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nfunction _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}\n\nmodule.exports = _createClass, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _getPrototypeOf(o) {\n module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n return _getPrototypeOf(o);\n}\n\nmodule.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","/* global window, exports, define */\n\n!function() {\n 'use strict'\n\n var re = {\n not_string: /[^s]/,\n not_bool: /[^t]/,\n not_type: /[^T]/,\n not_primitive: /[^v]/,\n number: /[diefg]/,\n numeric_arg: /[bcdiefguxX]/,\n json: /[j]/,\n not_json: /[^j]/,\n text: /^[^\\x25]+/,\n modulo: /^\\x25{2}/,\n placeholder: /^\\x25(?:([1-9]\\d*)\\$|\\(([^)]+)\\))?(\\+)?(0|'[^$])?(-)?(\\d+)?(?:\\.(\\d+))?([b-gijostTuvxX])/,\n key: /^([a-z_][a-z_\\d]*)/i,\n key_access: /^\\.([a-z_][a-z_\\d]*)/i,\n index_access: /^\\[(\\d+)\\]/,\n sign: /^[+-]/\n }\n\n function sprintf(key) {\n // `arguments` is not an array, but should be fine for this call\n return sprintf_format(sprintf_parse(key), arguments)\n }\n\n function vsprintf(fmt, argv) {\n return sprintf.apply(null, [fmt].concat(argv || []))\n }\n\n function sprintf_format(parse_tree, argv) {\n var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign\n for (i = 0; i < tree_length; i++) {\n if (typeof parse_tree[i] === 'string') {\n output += parse_tree[i]\n }\n else if (typeof parse_tree[i] === 'object') {\n ph = parse_tree[i] // convenience purposes only\n if (ph.keys) { // keyword argument\n arg = argv[cursor]\n for (k = 0; k < ph.keys.length; k++) {\n if (arg == undefined) {\n throw new Error(sprintf('[sprintf] Cannot access property \"%s\" of undefined value \"%s\"', ph.keys[k], ph.keys[k-1]))\n }\n arg = arg[ph.keys[k]]\n }\n }\n else if (ph.param_no) { // positional argument (explicit)\n arg = argv[ph.param_no]\n }\n else { // positional argument (implicit)\n arg = argv[cursor++]\n }\n\n if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {\n arg = arg()\n }\n\n if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {\n throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))\n }\n\n if (re.number.test(ph.type)) {\n is_positive = arg >= 0\n }\n\n switch (ph.type) {\n case 'b':\n arg = parseInt(arg, 10).toString(2)\n break\n case 'c':\n arg = String.fromCharCode(parseInt(arg, 10))\n break\n case 'd':\n case 'i':\n arg = parseInt(arg, 10)\n break\n case 'j':\n arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)\n break\n case 'e':\n arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()\n break\n case 'f':\n arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)\n break\n case 'g':\n arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)\n break\n case 'o':\n arg = (parseInt(arg, 10) >>> 0).toString(8)\n break\n case 's':\n arg = String(arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 't':\n arg = String(!!arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'T':\n arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'u':\n arg = parseInt(arg, 10) >>> 0\n break\n case 'v':\n arg = arg.valueOf()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'x':\n arg = (parseInt(arg, 10) >>> 0).toString(16)\n break\n case 'X':\n arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()\n break\n }\n if (re.json.test(ph.type)) {\n output += arg\n }\n else {\n if (re.number.test(ph.type) && (!is_positive || ph.sign)) {\n sign = is_positive ? '+' : '-'\n arg = arg.toString().replace(re.sign, '')\n }\n else {\n sign = ''\n }\n pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '\n pad_length = ph.width - (sign + arg).length\n pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''\n output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)\n }\n }\n }\n return output\n }\n\n var sprintf_cache = Object.create(null)\n\n function sprintf_parse(fmt) {\n if (sprintf_cache[fmt]) {\n return sprintf_cache[fmt]\n }\n\n var _fmt = fmt, match, parse_tree = [], arg_names = 0\n while (_fmt) {\n if ((match = re.text.exec(_fmt)) !== null) {\n parse_tree.push(match[0])\n }\n else if ((match = re.modulo.exec(_fmt)) !== null) {\n parse_tree.push('%')\n }\n else if ((match = re.placeholder.exec(_fmt)) !== null) {\n if (match[2]) {\n arg_names |= 1\n var field_list = [], replacement_field = match[2], field_match = []\n if ((field_match = re.key.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {\n if ((field_match = re.key_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else if ((field_match = re.index_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n }\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n match[2] = field_list\n }\n else {\n arg_names |= 2\n }\n if (arg_names === 3) {\n throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')\n }\n\n parse_tree.push(\n {\n placeholder: match[0],\n param_no: match[1],\n keys: match[2],\n sign: match[3],\n pad_char: match[4],\n align: match[5],\n width: match[6],\n precision: match[7],\n type: match[8]\n }\n )\n }\n else {\n throw new SyntaxError('[sprintf] unexpected placeholder')\n }\n _fmt = _fmt.substring(match[0].length)\n }\n return sprintf_cache[fmt] = parse_tree\n }\n\n /**\n * export to either browser or node.js\n */\n /* eslint-disable quote-props */\n if (typeof exports !== 'undefined') {\n exports['sprintf'] = sprintf\n exports['vsprintf'] = vsprintf\n }\n if (typeof window !== 'undefined') {\n window['sprintf'] = sprintf\n window['vsprintf'] = vsprintf\n\n if (typeof define === 'function' && define['amd']) {\n define(function() {\n return {\n 'sprintf': sprintf,\n 'vsprintf': vsprintf\n }\n })\n }\n }\n /* eslint-enable quote-props */\n}(); // eslint-disable-line\n","var setPrototypeOf = require(\"./setPrototypeOf.js\");\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n Object.defineProperty(subClass, \"prototype\", {\n writable: false\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}\n\nmodule.exports = _inherits, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var _typeof = require(\"./typeof.js\")[\"default\"];\n\nvar assertThisInitialized = require(\"./assertThisInitialized.js\");\n\nfunction _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n } else if (call !== void 0) {\n throw new TypeError(\"Derived constructors may only return object or undefined\");\n }\n\n return assertThisInitialized(self);\n}\n\nmodule.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _setPrototypeOf(o, p) {\n module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n return _setPrototypeOf(o, p);\n}\n\nmodule.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}\n\nmodule.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","\nexport const LOGS_DESTINATION = {\n NULL: \"NULL\",\n CLIENT_LOGGER: \"CLIENT_LOGGER\",\n DEBUG: \"DEBUG\"\n};\n\nexport const MIN_WEBSOCKET_LIFETIME_MS = 300000;\nexport const HEARTBEAT_INTERVAL_MS = 10000;\nexport const WEBSOCKET_URL_VALID_TIME_MS = 85000;\nexport const TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS = 500;\nexport const MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS = 5;\nexport const MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS = 1000;\nexport const MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE = 3;\nexport const NETWORK_CONN_CHECK_INTERVAL_MS = 250;\nexport const WEBSOCKET_REINIT_JITTER = 0.3;\nexport const WEBSOCKET_RETRY_RATE_MS = 2000;\nexport const MAX_WEBSOCKET_RETRY_RATE_MS = 30000;\n\nexport const NETWORK_FAILURE = 'NetworkingError';\n\nexport const LOG_MESSAGES = {\n DEFAULT_PREFIX: \"AMZ_WEB_SOCKET_MANAGER:\",\n NETWORK_OFFLINE: \"Network offline\",\n NETWORK_ONLINE: \"Network online, connecting to WebSocket server\",\n NETWORK_OFFLINE_WARNING: \"Network offline, ignoring this getWebSocketConnConfig request\",\n NO_HEARTBEAT: \"Heartbeat response not received\",\n NO_DEEP_HEARTBEAT: \"aws/ping deep heartbeat response not received\",\n HEARTBEAT_RECEIVED: \"Heartbeat response received\",\n DEEP_HEARTBEAT_RECEIVED: \"aws/ping deep heartbeat received\",\n SENDING_HEARTBEAT: \"Sending heartbeat\",\n SENDING_DEEP_HEARTBEAT: \"Sending aws/ping deep heartbeat\",\n FAILED_HEARTBEAT: \"Failed to send heartbeat since WebSocket is not open\",\n FAILED_DEEP_HEARTBEAT: \"Failed to send aws/ping deep heartbeat since WebSocket is not open\",\n DEEP_HEARTBEAT_SUCCESS: \"Deep Heartbeat is successful. WebSocketManager has received 200 response from aws/ping\",\n DEEP_HEARTBEAT_FAILURE: \"Deep Heartbeat failed. WebSocketManager does not receive 200 response from aws/ping\",\n TOPIC_FAILURE: \"Generic topic failed.\",\n WEBSOCKET_CONNECTION_ESTABLISHED: \"WebSocket connection established!\",\n WEBSOCKET_CONNECTION_CLOSED: \"WebSocket connection is closed\",\n WEBSOCKET_CONNECTION_ERROR: \"WebSocketManager Error, error_event: \",\n WEBSOCKET_REINITIALIZATION: \"Scheduling WebSocket reinitialization, after delay \",\n WEBSOCKET_REINITIALIZATION_TIMEOUT: \"WebSocket URL cannot be used to establish connection\",\n WEBSOCKET_INITIALIZATION_FAILED: \"WebSocket Initialization failed - Terminating and cleaning subscriptions\",\n WEBSOCKET_TERMINATED: \"Terminating WebSocket Manager\",\n WEBSOCKET_NEW_CONNECTION: \"Fetching new WebSocket connection configuration\",\n WEBSOCKET_CONNECTION_SUCCESS: \"Successfully fetched webSocket connection configuration\",\n WEBSOCKET_CONNECTION_FAILURE: \"Failed to fetch webSocket connection configuration\",\n WEBSOCKET_CONNECTION_RETRY: \"Retrying fetching new WebSocket connection configuration\",\n WEBSOCKET_INIT: \"Initializing Websocket Manager\",\n WEBSOCKET_INIT_FAILURE: \"Initializing Websocket Manager Failure callback registered\",\n WEBSOCKET_CONNECTION_OPEN: \"Websocket connection open callback registered\",\n WEBSOCKET_CONNECTION_CLOSE: \"Websocket connection close callback registered\",\n WEBSOCKET_CONNECTION_GAIN: \"Websocket connection gain callback registered\",\n WEBSOCKET_CONNECTION_LOST: \"Websocket connection lost callback registered\",\n WEBSOCKET_SUBSCRIPTION_FAILURE: \"Websocket subscription failure callback registered\",\n WEBSOCKET_RESET: \"Reset Websocket state\",\n WEBSOCKET_MESSAGE_ERROR: \"WebSocketManager Message Error\",\n WEBSOCKET_MESSAGE_RECEIVED: \"Message received for topic \",\n WEBSOCKET_MESSAGE_INVALID: \"Invalid incoming message\",\n WEBSOCKET_MESSAGE_SUCCESS: \"WebsocketManager invoke callbacks for topic success \",\n};\n\nexport const ROUTE_KEY = {\n SUBSCRIBE: \"aws/subscribe\",\n UNSUBSCRIBE: \"aws/unsubscribe\",\n HEARTBEAT: \"aws/heartbeat\",\n DEEP_HEARTBEAT: \"aws/ping\"\n};\n\nexport const CONN_STATE = {\n CONNECTED: \"connected\",\n DISCONNECTED: \"disconnected\"\n};\n","import { sprintf } from \"sprintf-js\";\nimport { NETWORK_FAILURE } from './constants';\n\nconst Utils = {};\n\n/**\n * Asserts that a premise is true.\n */\nUtils.assertTrue = function(premise, message) {\n if (!premise) {\n throw new Error(message);\n }\n};\n\n/**\n * Asserts that a value is not null or undefined.\n */\nUtils.assertNotNull = function(value, name) {\n Utils.assertTrue(\n value !== null && typeof value !== undefined,\n sprintf(\"%s must be provided\", name || \"A value\")\n );\n return value;\n};\n\nUtils.isNonEmptyString = function(value) {\n return typeof value === \"string\" && value.length > 0;\n};\n\nUtils.assertIsList = function(value, key) {\n if (!Array.isArray(value)) {\n throw new Error(key + \" is not an array\");\n }\n};\n\n/**\n * Determine if the given value is a callable function type.\n * Borrowed from Underscore.js.\n */\nUtils.isFunction = function(obj) {\n return !!(obj && obj.constructor && obj.call && obj.apply);\n};\n\nUtils.isObject = function(value) {\n return !(typeof value !== \"object\" || value === null);\n};\n\nUtils.isString = function(value) {\n return typeof value === \"string\";\n};\n\nUtils.isNumber = function(value) {\n return typeof value === \"number\";\n};\n\nconst wsRegex = new RegExp(\"^(wss://)\\\\w*\");\nconst localWsRegex = new RegExp(\"^(ws://127.0.0.1:)\");\nUtils.validWSUrl = function (wsUrl) {\n return wsRegex.test(wsUrl) || localWsRegex.test(wsUrl);\n};\n\nUtils.getSubscriptionResponse = (routeKey, isSuccess, topicList) => {\n return {\n topic: routeKey,\n content : {\n status: isSuccess ? \"success\" : \"failure\",\n topics: topicList\n }\n };\n};\n\nUtils.assertIsObject = function(value, key) {\n if (!Utils.isObject(value)) {\n throw new Error(key + \" is not an object!\");\n }\n};\n\nUtils.addJitter = function (base, maxJitter = 1) {\n maxJitter = Math.min(maxJitter, 1.0);\n const sign = Math.random() > 0.5 ? 1 : -1;\n return Math.floor(base + sign * base * Math.random() * maxJitter);\n};\n\nUtils.isNetworkOnline = () => navigator.onLine;\n\nUtils.isNetworkFailure = (reason) => {\n if(reason._debug && reason._debug.type) {\n return reason._debug.type === NETWORK_FAILURE;\n }\n return false;\n};\n\nexport default Utils;\n","import Utils from \"./utils\";\nimport { LOGS_DESTINATION, LOG_MESSAGES } from \"./constants\";\n\n/*eslint-disable no-unused-vars*/\nclass Logger {\n debug(data) {}\n\n info(data) {}\n\n warn(data) {}\n\n error(data) {}\n\n advancedLog(data) {}\n}\n/*eslint-enable no-unused-vars*/\n\nconst DEFAULT_PREFIX = LOG_MESSAGES.DEFAULT_PREFIX;\nconst LogLevel = {\n DEBUG: 10,\n INFO: 20,\n WARN: 30,\n ERROR: 40,\n ADVANCED_LOG: 50,\n};\n\nclass LogManagerImpl {\n constructor(logMetaData) {\n this.logMetaData = logMetaData || '';\n this.updateLoggerConfig();\n }\n\n hasLogMetaData() {\n return !!this.logMetaData;\n }\n\n writeToClientLogger(level, logStatement = '') {\n if (!this.hasClientLogger()) {\n return;\n }\n const log1 = typeof logStatement === \"string\" ? logStatement : JSON.stringify(logStatement, removeCircularReference());\n const log2 = typeof this.logMetaData === \"string\" ? this.logMetaData : JSON.stringify(this.logMetaData, removeCircularReference());\n const logStringValue = `${getLogLevelByValue(level)} ${log1} ${log2}`;\n switch (level) {\n case LogLevel.DEBUG:\n return this._clientLogger.debug(logStringValue) || logStringValue;\n case LogLevel.INFO:\n return this._clientLogger.info(logStringValue) || logStringValue;\n case LogLevel.WARN:\n return this._clientLogger.warn(logStringValue) || logStringValue;\n case LogLevel.ERROR:\n return this._clientLogger.error(logStringValue) || logStringValue;\n case LogLevel.ADVANCED_LOG:\n if(!this._advancedLogWriter) return '';\n return this._clientLogger[this._advancedLogWriter](logStringValue) || logStringValue;\n }\n }\n\n isLevelEnabled(level) {\n return level >= this._level;\n }\n\n hasClientLogger() {\n return this._clientLogger !== null;\n }\n\n getLogger(options = {}) {\n var prefix = options.prefix || DEFAULT_PREFIX;\n if (options.logMetaData) {\n this.setLogMetaData(options.logMetaData);\n }\n if (!this.logMetaData) {\n console.info(\"*********Missing required option: WebSocketManager:logMetaData**********\");\n }\n return new LoggerWrapperImpl(this, { prefix, logMetaData: this.logMetaData, ...options });\n }\n\n setLogMetaData(logMetaData) {\n this.logMetaData = logMetaData;\n }\n\n updateLoggerConfig(inputConfig) {\n var config = inputConfig || {};\n this._level = config.level || LogLevel.INFO;\n //enabled advancedLogWriter\n this._advancedLogWriter = \"warn\";\n if (config.advancedLogWriter) {\n this._advancedLogWriter = config.advancedLogWriter;\n }\n\n if(config.customizedLogger && typeof config.customizedLogger === \"object\") {\n this.useClientLogger = true;\n }\n this._clientLogger = config.logger || this.selectLogger(config);\n\n this._logsDestination = LOGS_DESTINATION.NULL;\n if (config.debug) {\n this._logsDestination = LOGS_DESTINATION.DEBUG;\n }\n if (config.logger) {\n this._logsDestination = LOGS_DESTINATION.CLIENT_LOGGER;\n }\n }\n\n selectLogger(config) {\n if(config.customizedLogger && typeof config.customizedLogger === \"object\") {\n return config.customizedLogger;\n }\n if(config.useDefaultLogger) {\n return createConsoleLogger();\n }\n return null;\n }\n}\n\nclass LoggerWrapper {\n debug() {}\n\n info() {}\n\n warn() {}\n\n error() {}\n\n advancedLog() {}\n}\n\nclass LoggerWrapperImpl extends LoggerWrapper {\n constructor(logManagerInstance, options) {\n super();\n this.options = options || {};\n this.prefix = options.prefix || DEFAULT_PREFIX;\n this.logManager = logManagerInstance;\n }\n\n debug(...args) {\n return this._log(LogLevel.DEBUG, args);\n }\n\n info(...args) {\n return this._log(LogLevel.INFO, args);\n }\n\n warn(...args) {\n return this._log(LogLevel.WARN, args);\n }\n\n error(...args) {\n return this._log(LogLevel.ERROR, args);\n }\n\n advancedLog(...args) {\n return this._log(LogLevel.ADVANCED_LOG, args);\n }\n\n _shouldLog(level) {\n return this.logManager.hasClientLogger() && this.logManager.isLevelEnabled(level);\n }\n\n _writeToClientLogger(level, logStatement) {\n return this.logManager.writeToClientLogger(level, logStatement);\n }\n\n _log(level, args) {\n if (this._shouldLog(level)) {\n var logStatement = this.logManager.useClientLogger ? args : this._convertToSingleStatement(args);\n return this._writeToClientLogger(level, logStatement);\n }\n }\n\n _convertToSingleStatement(args) {\n var date = new Date(Date.now()).toISOString();\n var logStatement = `[${date}]`;\n if (this.prefix) {\n logStatement += this.prefix + \" \";\n }\n if (this.options) {\n this.options.prefix ? logStatement += \" \" + this.options.prefix + \":\" : logStatement += \"\";\n }\n for (var index = 0; index < args.length; index++) {\n var arg = args[index];\n logStatement += this._convertToString(arg) + \" \";\n }\n return logStatement;\n }\n\n _convertToString(arg) {\n try {\n if (!arg) {\n return \"\";\n }\n if (Utils.isString(arg)) {\n return arg;\n }\n if (Utils.isObject(arg) && Utils.isFunction(arg.toString)) {\n var toStringResult = arg.toString();\n if (toStringResult !== \"[object Object]\") {\n return toStringResult;\n }\n }\n return JSON.stringify(arg);\n } catch (error) {\n console.error(\"Error while converting argument to string\", arg, error);\n return \"\";\n }\n }\n}\n\nfunction getLogLevelByValue(value) {\n switch(value) {\n case 10: return \"DEBUG\";\n case 20: return \"INFO\";\n case 30: return \"WARN\";\n case 40: return \"ERROR\";\n case 50: return \"ADVANCED_LOG\";\n }\n}\n\nfunction removeCircularReference() {\n const seen = new WeakSet();\n\n return (key, value) => {\n if (typeof value === \"object\" && value !== null) {\n if (seen.has(value)) {\n return;\n }\n seen.add(value);\n }\n return value;\n };\n}\n\nvar createConsoleLogger = () => {\n var logger = new LoggerWrapper();\n logger.debug = (...args) => console.debug.apply(window.console, [].concat(args));\n logger.info = (...args) => console.info.apply(window.console, [].concat(args));\n logger.warn = (...args) => console.warn.apply(window.console, [].concat(args));\n logger.error = (...args) => console.error.apply(window.console, [].concat(args));\n return logger;\n};\n\nexport { LogManagerImpl, Logger, LogLevel };\n","import { WEBSOCKET_RETRY_RATE_MS, MAX_WEBSOCKET_RETRY_RATE_MS } from './constants';\n\nclass RetryProvider {\n constructor(executor, defaultRetry = WEBSOCKET_RETRY_RATE_MS) {\n this.numAttempts = 0;\n this.executor = executor;\n this.hasActiveReconnection = false;\n this.defaultRetry = defaultRetry;\n }\n\n retry() {\n // Don't kickoff another reconnection attempt if we have one pending\n if (!this.hasActiveReconnection) {\n this.hasActiveReconnection = true;\n setTimeout(() => {\n this._execute();\n }, this._getDelay());\n }\n }\n\n _execute() {\n this.hasActiveReconnection = false;\n this.executor();\n this.numAttempts++;\n }\n\n connected() {\n this.numAttempts = 0;\n }\n\n _getDelay() {\n const calculatedDelay = Math.pow(2, this.numAttempts) * this.defaultRetry;\n return calculatedDelay <= MAX_WEBSOCKET_RETRY_RATE_MS ? calculatedDelay : MAX_WEBSOCKET_RETRY_RATE_MS;\n }\n\n getIsConnected() {\n return !this.numAttempts;\n }\n}\n\nexport { RetryProvider };","import Utils from \"./utils\";\nimport { LogManagerImpl, LogLevel, Logger } from \"./log\";\nimport {\n MIN_WEBSOCKET_LIFETIME_MS,\n WEBSOCKET_URL_VALID_TIME_MS,\n HEARTBEAT_INTERVAL_MS,\n ROUTE_KEY,\n CONN_STATE,\n MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS,\n TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS,\n MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS,\n MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE,\n NETWORK_CONN_CHECK_INTERVAL_MS,\n WEBSOCKET_REINIT_JITTER,\n LOG_MESSAGES,\n} from \"./constants\";\nimport { RetryProvider } from './retryProvider';\n\nlet logManagerInstance = null;\nconst WebSocketManager = function () {\n let enableDeepHeartbeat = false;\n\n const logger = logManagerInstance.getLogger({ prefix: LOG_MESSAGES.DEFAULT_PREFIX });\n\n let online = Utils.isNetworkOnline();\n\n let webSocket = {\n primary: null,\n secondary: null\n };\n\n let reconnectConfig = {\n reconnectWebSocket: true,\n websocketInitFailed: false,\n exponentialBackOffTime: 1000,\n exponentialTimeoutHandle: null,\n lifeTimeTimeoutHandle: null,\n webSocketInitCheckerTimeoutId: null,\n connState: null\n };\n\n let metrics = {\n connectWebSocketRetryCount: 0,\n connectionAttemptStartTime: null,\n noOpenConnectionsTimestamp: null\n };\n\n let heartbeatConfig = {\n pendingResponse: false,\n intervalHandle: null\n };\n\n let deepHeartbeatConfig = {\n pendingResponse: false,\n intervalHandle: null\n };\n\n let callbacks = {\n initFailure: new Set(),\n getWebSocketTransport: null,\n subscriptionUpdate: new Set(),\n subscriptionFailure: new Set(),\n topic: new Map(),\n allMessage: new Set(),\n connectionGain: new Set(),\n connectionLost: new Set(),\n connectionOpen: new Set(),\n connectionClose: new Set(),\n deepHeartbeatSuccess: new Set(),\n deepHeartbeatFailure: new Set(),\n topicFailure: new Set(),\n };\n\n let webSocketConfig = {\n connConfig: null,\n promiseHandle: null,\n promiseCompleted: true\n };\n\n let topicSubscription = {\n subscribed: new Set(),\n pending: new Set(),\n subscriptionHistory: new Set()\n };\n\n let topicSubscriptionConfig = {\n responseCheckIntervalId: null,\n requestCompleted: true,\n reSubscribeIntervalId: null,\n consecutiveFailedSubscribeAttempts: 0,\n consecutiveNoResponseRequest: 0\n };\n\n const reconnectionClient = new RetryProvider(() => { getWebSocketConnConfig(); });\n\n const invalidSendMessageRouteKeys = new Set([ROUTE_KEY.SUBSCRIBE, ROUTE_KEY.UNSUBSCRIBE, ROUTE_KEY.HEARTBEAT, ROUTE_KEY.DEEP_HEARTBEAT]);\n\n const networkConnectivityChecker = setInterval(function () {\n if (online !== Utils.isNetworkOnline()) {\n online = Utils.isNetworkOnline();\n if (!online) {\n logger.advancedLog(LOG_MESSAGES.NETWORK_OFFLINE);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.NETWORK_OFFLINE));\n\n return;\n }\n const ws = getDefaultWebSocket();\n if (online && (!ws || isWebSocketState(ws, WebSocket.CLOSING) || isWebSocketState(ws, WebSocket.CLOSED))) {\n logger.advancedLog(LOG_MESSAGES.NETWORK_ONLINE);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.NETWORK_ONLINE));\n\n getWebSocketConnConfig();\n }\n }\n }, NETWORK_CONN_CHECK_INTERVAL_MS);\n\n const invokeCallbacks = function (callbacks, response) {\n callbacks.forEach(function (callback) {\n try {\n callback(response);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error executing callback\", error));\n }\n });\n };\n\n const getWebSocketStates = function (ws) {\n if (ws === null) return \"NULL\";\n switch (ws.readyState) {\n case WebSocket.CONNECTING:\n return \"CONNECTING\";\n case WebSocket.OPEN:\n return \"OPEN\";\n case WebSocket.CLOSING:\n return \"CLOSING\";\n case WebSocket.CLOSED:\n return \"CLOSED\";\n default:\n return \"UNDEFINED\";\n }\n };\n\n const printWebSocketState = function (event = \"\") {\n sendInternalLogToServer(logger.debug(\"[\" + event + \"] Primary WebSocket: \" + getWebSocketStates(webSocket.primary)\n + \" | \" + \"Secondary WebSocket: \" + getWebSocketStates(webSocket.secondary)));\n };\n\n const isWebSocketState = function (ws, webSocketStateCode) {\n return ws && ws.readyState === webSocketStateCode;\n };\n\n const isWebSocketOpen = function (ws) {\n return isWebSocketState(ws, WebSocket.OPEN);\n };\n\n const isWebSocketClosed = function (ws) {\n // undefined check is to address the limitation of testing framework\n return ws === null || ws.readyState === undefined || isWebSocketState(ws, WebSocket.CLOSED);\n };\n\n /**\n * This function is meant to handle the scenario when we have two web-sockets open\n * in such a scenario we always select secondary web-socket since all future operations\n * are supposed to be done by this secondary web-socket\n */\n const getDefaultWebSocket = function () {\n if (webSocket.secondary !== null) {\n return webSocket.secondary;\n }\n return webSocket.primary;\n };\n\n const isDefaultWebSocketOpen = function () {\n return isWebSocketOpen(getDefaultWebSocket());\n };\n\n const sendHeartBeat = function () {\n if (enableDeepHeartbeat && deepHeartbeatConfig.pendingResponse) {\n logger.advancedLog(LOG_MESSAGES.NO_DEEP_HEARTBEAT);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.NO_DEEP_HEARTBEAT));\n // trigger deepHeartbeatFailure - no response is received \n invokeCallbacks(callbacks.deepHeartbeatFailure, {\n timestamp: Date.now(),\n error: \"aws/ping response is not received\",\n });\n\n clearInterval(deepHeartbeatConfig.intervalHandle);\n deepHeartbeatConfig.pendingResponse = false;\n }\n if (heartbeatConfig.pendingResponse) {\n logger.advancedLog(LOG_MESSAGES.NO_HEARTBEAT);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.NO_HEARTBEAT));\n\n clearInterval(heartbeatConfig.intervalHandle);\n heartbeatConfig.intervalHandle = null;\n heartbeatConfig.pendingResponse = false;\n getWebSocketConnConfig();\n return;\n }\n if (isDefaultWebSocketOpen()) {\n if (enableDeepHeartbeat) {\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.SENDING_DEEP_HEARTBEAT));\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.DEEP_HEARTBEAT));\n deepHeartbeatConfig.pendingResponse = true;\n }\n\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.SENDING_HEARTBEAT));\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.HEARTBEAT));\n heartbeatConfig.pendingResponse = true;\n } else {\n if (enableDeepHeartbeat) {\n logger.advancedLog(LOG_MESSAGES.FAILED_DEEP_HEARTBEAT);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.FAILED_DEEP_HEARTBEAT));\n // trigger deepHeartbeatFailure - message is unable to be sent to aws/ping because websocket connection is not established.\n invokeCallbacks(callbacks.deepHeartbeatFailure, {\n timestamp: Date.now(),\n error: \"Unable to send message to aws/ping because websocket connection is not established.\"\n });\n }\n\n logger.advancedLog(LOG_MESSAGES.FAILED_HEARTBEAT);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.FAILED_HEARTBEAT));\n\n printWebSocketState(\"sendHeartBeat\");\n getWebSocketConnConfig();\n }\n };\n\n const resetWebSocketState = function () {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_RESET);\n reconnectConfig.exponentialBackOffTime = 1000;\n heartbeatConfig.pendingResponse = false;\n deepHeartbeatConfig.pendingResponse = false;\n\n reconnectConfig.reconnectWebSocket = true;\n\n clearTimeout(reconnectConfig.lifeTimeTimeoutHandle);\n clearInterval(heartbeatConfig.intervalHandle);\n clearInterval(deepHeartbeatConfig.intervalHandle);\n clearTimeout(reconnectConfig.exponentialTimeoutHandle);\n clearTimeout(reconnectConfig.webSocketInitCheckerTimeoutId);\n\n heartbeatConfig.intervalHandle = null;\n };\n\n const resetSubscriptions = function () {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n };\n\n const resetMetrics = function () {\n metrics.connectWebSocketRetryCount = 0;\n metrics.connectionAttemptStartTime = null;\n metrics.noOpenConnectionsTimestamp = null;\n };\n\n const webSocketOnOpen = function () {\n // Mark connection as successful; reset the number of reconnect attempts to 0.\n reconnectionClient.connected();\n\n try {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_ESTABLISHED);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.WEBSOCKET_CONNECTION_ESTABLISHED));\n\n printWebSocketState(\"webSocketOnOpen\");\n if (reconnectConfig.connState === null || reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n invokeCallbacks(callbacks.connectionGain);\n }\n reconnectConfig.connState = CONN_STATE.CONNECTED;\n\n // Report number of retries to open and record ws open time\n const now = Date.now();\n invokeCallbacks(callbacks.connectionOpen, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n noOpenConnectionsTimestamp: metrics.noOpenConnectionsTimestamp,\n connectionEstablishedTime: now,\n timeToConnect: now - metrics.connectionAttemptStartTime,\n timeWithoutConnection:\n metrics.noOpenConnectionsTimestamp ? now - metrics.noOpenConnectionsTimestamp : null\n });\n\n resetMetrics();\n resetWebSocketState();\n getDefaultWebSocket().openTimestamp = Date.now(); // record open time\n\n // early closure of primary web socket\n if (topicSubscription.subscribed.size === 0 && isWebSocketOpen(webSocket.secondary)) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n if (topicSubscription.subscribed.size > 0 || topicSubscription.pending.size > 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Subscribing secondary websocket to topics of primary websocket\"));\n }\n topicSubscription.subscribed.forEach(topic => {\n topicSubscription.subscriptionHistory.add(topic);\n topicSubscription.pending.add(topic);\n });\n topicSubscription.subscribed.clear();\n subscribePendingTopics();\n }\n\n sendHeartBeat();\n if (heartbeatConfig.intervalHandle !== null) {\n clearInterval(heartbeatConfig.intervalHandle);\n }\n heartbeatConfig.intervalHandle = setInterval(sendHeartBeat, HEARTBEAT_INTERVAL_MS);\n\n const webSocketLifetimeTimeout = webSocketConfig.connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000;\n sendInternalLogToServer(logger.debug(\"Scheduling WebSocket manager reconnection, after delay \" + webSocketLifetimeTimeout + \" ms\"));\n\n reconnectConfig.lifeTimeTimeoutHandle = setTimeout(function () {\n sendInternalLogToServer(logger.debug(\"Starting scheduled WebSocket manager reconnection\"));\n\n getWebSocketConnConfig();\n }, webSocketLifetimeTimeout);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error after establishing WebSocket connection\", error));\n }\n };\n\n const webSocketOnClose = function (event, ws) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_CLOSED, JSON.stringify(event));\n sendInternalLogToServer(logger.info(LOG_MESSAGES.WEBSOCKET_CONNECTION_CLOSED, JSON.stringify(event)));\n\n printWebSocketState(\"webSocketOnClose before-cleanup\");\n\n invokeCallbacks(callbacks.connectionClose, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n\n if (isWebSocketClosed(webSocket.primary)) {\n webSocket.primary = null;\n }\n if (isWebSocketClosed(webSocket.secondary)) {\n webSocket.secondary = null;\n }\n if (!reconnectConfig.reconnectWebSocket) {\n return;\n }\n if (!isWebSocketOpen(webSocket.primary) && !isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.warn(\"Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection\"));\n\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n /**\n * This check is required in the scenario where WS Server shuts-down and closes all active\n * WS Client connections and WS Server takes about a minute to become active again, in this\n * scenario WS Client's onClose is triggered and then WSM start reconnect logic immediately but all\n * connect request to WS Server would fail and WS Client's onError callback would be triggered\n * followed WS Client's onClose callback and hence \"connectionLost\" callback would be invoked several\n * times and this behavior is redundant\n */\n sendInternalLogToServer(logger.info(\"Ignoring connectionLost callback invocation\"));\n } else {\n invokeCallbacks(callbacks.connectionLost, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n metrics.noOpenConnectionsTimestamp = Date.now();\n }\n reconnectConfig.connState = CONN_STATE.DISCONNECTED;\n getWebSocketConnConfig();\n } else if (isWebSocketClosed(webSocket.primary) && isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"[Primary] WebSocket Cleanly Closed\"));\n\n webSocket.primary = webSocket.secondary;\n webSocket.secondary = null;\n }\n printWebSocketState(\"webSocketOnClose after-cleanup\");\n };\n\n const webSocketOnError = function (event) {\n printWebSocketState(\"webSocketOnError\");\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_ERROR, JSON.stringify(event));\n sendInternalLogToServer(logger.error(LOG_MESSAGES.WEBSOCKET_CONNECTION_ERROR, JSON.stringify(event)));\n const isConnected = reconnectionClient.getIsConnected();\n\n if (isConnected) {\n getWebSocketConnConfig();\n } else {\n reconnectionClient.retry();\n }\n };\n\n const webSocketOnMessage = function (event) {\n const response = JSON.parse(event.data);\n\n switch (response.topic) {\n\n case ROUTE_KEY.SUBSCRIBE: {\n sendInternalLogToServer(logger.debug(\"Subscription Message received from webSocket server\", event.data));\n\n topicSubscriptionConfig.requestCompleted = true;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n\n if (response.content.status === \"success\") {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n response.content.topics.forEach(topicName => {\n topicSubscription.subscriptionHistory.delete(topicName);\n topicSubscription.pending.delete(topicName);\n topicSubscription.subscribed.add(topicName);\n });\n if (topicSubscription.subscriptionHistory.size === 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Successfully subscribed secondary websocket to all topics of primary websocket\"));\n\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n } else {\n subscribePendingTopics();\n }\n invokeCallbacks(callbacks.subscriptionUpdate, response);\n\n } else {\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n ++topicSubscriptionConfig.consecutiveFailedSubscribeAttempts;\n if (topicSubscriptionConfig.consecutiveFailedSubscribeAttempts === MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS) {\n invokeCallbacks(callbacks.subscriptionFailure, response);\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n return;\n }\n topicSubscriptionConfig.reSubscribeIntervalId = setInterval(function () {\n subscribePendingTopics();\n }, TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS);\n }\n break;\n }\n case ROUTE_KEY.HEARTBEAT: {\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.HEARTBEAT_RECEIVED));\n heartbeatConfig.pendingResponse = false;\n if (heartbeatConfig.intervalHandle === null) {\n heartbeatConfig.intervalHandle = setInterval(sendHeartBeat, HEARTBEAT_INTERVAL_MS);\n }\n break;\n }\n case ROUTE_KEY.DEEP_HEARTBEAT: {\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.DEEP_HEARTBEAT_RECEIVED));\n deepHeartbeatConfig.pendingResponse = false;\n \n if (response.statusCode === 200) {// trigger deepHeartbeatSuccess if 200 response is received\n invokeCallbacks(callbacks.deepHeartbeatSuccess, {\n timestamp: Date.now(),\n });\n } else {//trigger deepHeartbeatFailure if 500 response is received\n invokeCallbacks(callbacks.deepHeartbeatFailure, {\n timestamp: Date.now(),\n statusCode: response.statusCode,\n statusContent: response.statusContent,\n });\n }\n break;\n }\n default: {\n if (response.topic) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_RECEIVED, response.topic);\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.WEBSOCKET_MESSAGE_RECEIVED + response.topic));\n\n if (isWebSocketOpen(webSocket.primary) && isWebSocketOpen(webSocket.secondary)\n && topicSubscription.subscriptionHistory.size === 0 && this === webSocket.primary) {\n /**\n * This block is to handle scenario when both primary and secondary socket have subscribed to\n * a common topic but we are facing difficulty in closing the primary socket, then in this\n * situation messages will be received by both primary and secondary web socket\n */\n sendInternalLogToServer(logger.warn(\"Ignoring Message for Topic \" + response.topic + \", to avoid duplicates\"));\n\n return;\n }\n\n if (callbacks.allMessage.size === 0 && callbacks.topic.size === 0) {\n sendInternalLogToServer(logger.warn('No registered callback listener for Topic', response.topic));\n\n return;\n }\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_SUCCESS, response.topic);\n invokeCallbacks(callbacks.allMessage, response);\n if (callbacks.topic.has(response.topic)) {\n invokeCallbacks(callbacks.topic.get(response.topic), response);\n }\n\n } else if (response.message) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_ERROR, response);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.WEBSOCKET_MESSAGE_ERROR, response));\n\n // trigger topicFailure if Forbidden message OR Timeout message is received\n invokeCallbacks(callbacks.topicFailure, {\n timestamp: Date.now(),\n errorMessage: response.message,\n connectionId: response.connectionId,\n requestId: response.requestId,\n });\n } else {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_INVALID, response);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.WEBSOCKET_MESSAGE_INVALID, response));\n }\n }\n }\n };\n\n const subscribePendingTopics = function () {\n if (topicSubscriptionConfig.consecutiveNoResponseRequest > MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response\"));\n\n invokeCallbacks(callbacks.subscriptionFailure, Utils.getSubscriptionResponse(ROUTE_KEY.SUBSCRIBE, false, Array.from(topicSubscription.pending)));\n return;\n }\n if (!isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics call since Default WebSocket is not open\"));\n\n return;\n }\n if (Array.from(topicSubscription.pending).length === 0) {\n return;\n }\n\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.SUBSCRIBE, {\n \"topics\": Array.from(topicSubscription.pending)\n }));\n topicSubscriptionConfig.requestCompleted = false;\n\n // This callback ensure that some response was received for subscription request\n topicSubscriptionConfig.responseCheckIntervalId = setInterval(function () {\n if (!topicSubscriptionConfig.requestCompleted) {\n ++topicSubscriptionConfig.consecutiveNoResponseRequest;\n subscribePendingTopics();\n }\n }, MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS);\n };\n\n const closeSpecificWebSocket = function (ws, reason) {\n if (isWebSocketState(ws, WebSocket.CONNECTING) || isWebSocketState(ws, WebSocket.OPEN)) {\n ws.close(1000, reason);\n } else {\n sendInternalLogToServer(logger.warn(\"Ignoring WebSocket Close request, WebSocket State: \" + getWebSocketStates(ws)));\n }\n };\n\n const closeWebSocket = function (reason) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary] WebSocket \" + reason);\n closeSpecificWebSocket(webSocket.secondary, \"[Secondary] WebSocket \" + reason);\n };\n\n const retryWebSocketInitialization = function () {\n metrics.connectWebSocketRetryCount++;\n const waitTime = Utils.addJitter(reconnectConfig.exponentialBackOffTime, WEBSOCKET_REINIT_JITTER);\n if (Date.now() + waitTime <= webSocketConfig.connConfig.urlConnValidTime) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_REINITIALIZATION);\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.WEBSOCKET_REINITIALIZATION + waitTime + \" ms\"));\n\n reconnectConfig.exponentialTimeoutHandle = setTimeout(() => initWebSocket(), waitTime);\n reconnectConfig.exponentialBackOffTime *= 2;\n } else {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_REINITIALIZATION_TIMEOUT);\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.WEBSOCKET_REINITIALIZATION_TIMEOUT));\n\n getWebSocketConnConfig();\n }\n };\n\n const terminateWebSocketManager = function (response) {\n resetWebSocketState();\n resetSubscriptions();\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_INITIALIZATION_FAILED, response);\n sendInternalLogToServer(logger.error(LOG_MESSAGES.WEBSOCKET_INITIALIZATION_FAILED));\n\n reconnectConfig.websocketInitFailed = true;\n closeWebSocket(LOG_MESSAGES.WEBSOCKET_TERMINATED);\n clearInterval(networkConnectivityChecker);\n invokeCallbacks(callbacks.initFailure, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n reason: response\n });\n resetMetrics();\n };\n\n const createWebSocketPayload = function (key, content) {\n return JSON.stringify({\n \"topic\": key,\n \"content\": content\n });\n };\n\n const sendMessage = function (payload) {\n Utils.assertIsObject(payload, \"payload\");\n if (payload.topic === undefined || invalidSendMessageRouteKeys.has(payload.topic)) {\n sendInternalLogToServer(logger.warn(\"Cannot send message, Invalid topic\", payload));\n\n return;\n }\n try {\n payload = JSON.stringify(payload);\n } catch (error) {\n sendInternalLogToServer(logger.warn(\"Error stringify message\", payload));\n\n return;\n }\n if (isDefaultWebSocketOpen()) {\n getDefaultWebSocket().send(payload);\n } else {\n sendInternalLogToServer(logger.warn(\"Cannot send message, web socket connection is not open\"));\n }\n };\n\n const subscribeTopics = function (topics) {\n Utils.assertNotNull(topics, 'topics');\n Utils.assertIsList(topics);\n\n topics.forEach(topic => {\n if (!topicSubscription.subscribed.has(topic)) {\n topicSubscription.pending.add(topic);\n }\n });\n // This ensure all participant-request to subscribe to topic chat are served at least once\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n subscribePendingTopics();\n };\n\n const validWebSocketConnConfig = function (connConfig) {\n if (Utils.isObject(connConfig) && Utils.isObject(connConfig.webSocketTransport)\n && Utils.isNonEmptyString(connConfig.webSocketTransport.url)\n && Utils.validWSUrl(connConfig.webSocketTransport.url) &&\n connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000 >= MIN_WEBSOCKET_LIFETIME_MS) {\n return true;\n }\n sendInternalLogToServer(logger.error(\"Invalid WebSocket Connection Configuration\", connConfig));\n\n return false;\n };\n\n const getWebSocketConnConfig = function () {\n if (!Utils.isNetworkOnline()) {\n logger.advancedLog(LOG_MESSAGES.NETWORK_OFFLINE_WARNING);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.NETWORK_OFFLINE_WARNING));\n\n return;\n }\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.debug(\"WebSocket Init had failed, ignoring this getWebSocketConnConfig request\"));\n return;\n }\n if (!webSocketConfig.promiseCompleted) {\n sendInternalLogToServer(logger.debug(\"There is an ongoing getWebSocketConnConfig request, this request will be ignored\"));\n return;\n }\n resetWebSocketState();\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_NEW_CONNECTION);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.WEBSOCKET_NEW_CONNECTION));\n\n metrics.connectionAttemptStartTime = metrics.connectionAttemptStartTime || Date.now();\n webSocketConfig.promiseCompleted = false;\n webSocketConfig.promiseHandle = callbacks.getWebSocketTransport();\n return webSocketConfig.promiseHandle\n .then(function (response) {\n webSocketConfig.promiseCompleted = true;\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_SUCCESS);\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.WEBSOCKET_CONNECTION_SUCCESS, response));\n\n if (!validWebSocketConnConfig(response)) {\n terminateWebSocketManager(\"Invalid WebSocket connection configuration: \" + response);\n return { webSocketConnectionFailed: true };\n }\n webSocketConfig.connConfig = response;\n // Ideally this URL validity time should be provided by server\n webSocketConfig.connConfig.urlConnValidTime = Date.now() + WEBSOCKET_URL_VALID_TIME_MS;\n return initWebSocket();\n },\n function (reason) {\n webSocketConfig.promiseCompleted = true;\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_FAILURE);\n sendInternalLogToServer(logger.error(LOG_MESSAGES.WEBSOCKET_CONNECTION_FAILURE, reason));\n\n // If our connection fails because of network failure, we want to retry\n if (Utils.isNetworkFailure(reason)) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_RETRY + JSON.stringify(reason));\n sendInternalLogToServer(logger.info(LOG_MESSAGES.WEBSOCKET_CONNECTION_RETRY + JSON.stringify(reason)));\n reconnectionClient.retry();\n } else {\n // If we're not going to retry, we should terminate WSM\n terminateWebSocketManager(\"Failed to fetch webSocket connection configuration: \" + JSON.stringify(reason));\n }\n return { webSocketConnectionFailed: true };\n });\n };\n\n const initWebSocket = function () {\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.info(\"web-socket initializing had failed, aborting re-init\"));\n\n return { webSocketConnectionFailed: true };\n }\n if (!Utils.isNetworkOnline()) {\n sendInternalLogToServer(logger.warn(\"System is offline aborting web-socket init\"));\n\n return { webSocketConnectionFailed: true };\n }\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_INIT);\n sendInternalLogToServer(logger.info(LOG_MESSAGES.WEBSOCKET_INIT));\n\n printWebSocketState(\"initWebSocket\");\n try {\n if (validWebSocketConnConfig(webSocketConfig.connConfig)) {\n let ws = null;\n if (isWebSocketOpen(webSocket.primary)) {\n sendInternalLogToServer(logger.debug(\"Primary Socket connection is already open\"));\n\n if (!isWebSocketState(webSocket.secondary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a secondary web-socket connection\"));\n reconnectionClient.numAttempts = 0;\n webSocket.secondary = getNewWebSocket();\n }\n ws = webSocket.secondary;\n } else {\n if (!isWebSocketState(webSocket.primary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a primary web-socket connection\"));\n\n webSocket.primary = getNewWebSocket();\n }\n ws = webSocket.primary;\n }\n\n // WebSocket creation is async task hence we Wait for 1sec before any potential retry\n reconnectConfig.webSocketInitCheckerTimeoutId = setTimeout(function () {\n if (!isWebSocketOpen(ws)) {\n retryWebSocketInitialization();\n }\n }, 1000);\n return { webSocketConnectionFailed: false };\n }\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error Initializing web-socket-manager\", error));\n\n terminateWebSocketManager(\"Failed to initialize new WebSocket: \" + error.message);\n return { webSocketConnectionFailed: true };\n }\n };\n\n const getNewWebSocket = function () {\n let ws = new WebSocket(webSocketConfig.connConfig.webSocketTransport.url);\n ws.addEventListener(\"open\", webSocketOnOpen);\n ws.addEventListener(\"message\", webSocketOnMessage);\n ws.addEventListener(\"error\", webSocketOnError);\n ws.addEventListener(\"close\", event => webSocketOnClose(event, ws));\n return ws;\n };\n\n const onConnectionOpen = function (cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_OPEN);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionOpen.add(cb);\n return () => callbacks.connectionOpen.delete(cb);\n };\n\n const onConnectionClose = function (cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_CLOSE);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionClose.add(cb);\n return () => callbacks.connectionClose.delete(cb);\n };\n\n const onConnectionGain = function (cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_GAIN);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionGain.add(cb);\n if (isDefaultWebSocketOpen()) {\n cb();\n }\n return () => callbacks.connectionGain.delete(cb);\n };\n\n const onConnectionLost = function (cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_LOST);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionLost.add(cb);\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n cb();\n }\n return () => callbacks.connectionLost.delete(cb);\n };\n\n const onInitFailure = function (cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_INIT_FAILURE);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.initFailure.add(cb);\n if (reconnectConfig.websocketInitFailed) {\n cb();\n }\n return () => callbacks.initFailure.delete(cb);\n };\n\n const init = function (transportHandle) {\n Utils.assertTrue(Utils.isFunction(transportHandle), 'transportHandle must be a function');\n if (callbacks.getWebSocketTransport !== null) {\n sendInternalLogToServer(logger.warn(\"Web Socket Manager was already initialized\"));\n return;\n }\n callbacks.getWebSocketTransport = transportHandle;\n\n return getWebSocketConnConfig();\n };\n\n const onSubscriptionUpdate = function (cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionUpdate.add(cb);\n return () => callbacks.subscriptionUpdate.delete(cb);\n };\n\n const onSubscriptionFailure = function (cb) {\n logger.advancedLog(LOG_MESSAGES.WEBSOCKET_SUBSCRIPTION_FAILURE);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionFailure.add(cb);\n return () => callbacks.subscriptionFailure.delete(cb);\n };\n\n const onMessage = function (topicName, cb) {\n Utils.assertNotNull(topicName, 'topicName');\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n if (callbacks.topic.has(topicName)) {\n callbacks.topic.get(topicName).add(cb);\n } else {\n callbacks.topic.set(topicName, new Set([cb]));\n }\n return () => callbacks.topic.get(topicName).delete(cb);\n };\n\n const onAllMessage = function (cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.allMessage.add(cb);\n return () => callbacks.allMessage.delete(cb);\n };\n\n const sendInternalLogToServer = function (logEntry) {\n if (logEntry && typeof logEntry.sendInternalLogToServer === \"function\")\n logEntry.sendInternalLogToServer();\n\n return logEntry;\n };\n\n const deepHeartbeatHandler = function () {\n enableDeepHeartbeat = true;\n };\n\n const onDeepHeartbeatSuccess = function (cb) {\n logger.advancedLog(LOG_MESSAGES.DEEP_HEARTBEAT_SUCCESS);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.deepHeartbeatSuccess.add(cb);\n return () => callbacks.deepHeartbeatSuccess.delete(cb);\n };\n\n const onDeepHeartbeatFailure = function (cb) {\n logger.advancedLog(LOG_MESSAGES.DEEP_HEARTBEAT_FAILURE);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.deepHeartbeatFailure.add(cb);\n return () => callbacks.deepHeartbeatFailure.delete(cb);\n };\n\n const onTopicFailure = function (cb) {\n logger.advancedLog(LOG_MESSAGES.TOPIC_FAILURE);\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.topicFailure.add(cb);\n return () => callbacks.topicFailure.delete(cb);\n };\n\n this.init = init;\n this.onInitFailure = onInitFailure;\n this.onConnectionOpen = onConnectionOpen;\n this.onConnectionClose = onConnectionClose;\n this.onConnectionGain = onConnectionGain;\n this.onConnectionLost = onConnectionLost;\n this.onSubscriptionUpdate = onSubscriptionUpdate;\n this.onSubscriptionFailure = onSubscriptionFailure;\n this.onMessage = onMessage;\n this.onAllMessage = onAllMessage;\n this.subscribeTopics = subscribeTopics;\n this.sendMessage = sendMessage;\n this.deepHeartbeatHandler = deepHeartbeatHandler;\n this.onDeepHeartbeatSuccess = onDeepHeartbeatSuccess;\n this.onDeepHeartbeatFailure = onDeepHeartbeatFailure;\n this.onTopicFailure = onTopicFailure;\n\n this.closeWebSocket = function () {\n resetWebSocketState();\n resetSubscriptions();\n reconnectConfig.reconnectWebSocket = false;\n clearInterval(networkConnectivityChecker);\n closeWebSocket(\"User request to close WebSocket\");\n };\n\n this.terminateWebSocketManager = terminateWebSocketManager;\n};\n\nconst WebSocketManagerConstructor = (logMetaData) => {\n if (!logManagerInstance) {\n logManagerInstance = new LogManagerImpl(logMetaData);\n }\n if (!logManagerInstance.hasLogMetaData()) {\n logManagerInstance.setLogMetaData(logMetaData);\n }\n if (!logMetaData) {\n console.info(\"********Missing metaData for logs from websocketManager: initialize websocketManager using create(metaData)*******\");\n }\n return new WebSocketManager();\n};\n\nconst setGlobalConfig = config => {\n const loggerConfig = config && config.loggerConfig;\n if (!logManagerInstance) {\n logManagerInstance = new LogManagerImpl();\n }\n logManagerInstance.updateLoggerConfig(loggerConfig);\n\n const webSocketManagerConfig = config && config.webSocketManagerConfig;\n const customIsNetworkOnline = webSocketManagerConfig && webSocketManagerConfig.isNetworkOnline;\n if (customIsNetworkOnline && typeof customIsNetworkOnline === \"function\") {\n Utils.isNetworkOnline = customIsNetworkOnline;\n }\n};\n\nconst WebSocketManagerObject = {\n create: WebSocketManagerConstructor,\n setGlobalConfig: setGlobalConfig,\n LogLevel: LogLevel,\n Logger: Logger,\n};\n\nexport { WebSocketManagerObject };\n","/*eslint no-unused-vars: \"off\"*/\nimport { WebSocketManagerObject } from \"./webSocketManager\";\n\nglobal.connect = global.connect || {};\nconnect.WebSocketManager = WebSocketManagerObject;\n\nexport const WebSocketManager = WebSocketManagerObject;\n\nexport default WebSocketManager;"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"amazon-connect-websocket-manager.js","mappings":"2BAAA,OAEC,WACG,aAEA,IAAIA,EAAK,CACLC,WAAY,OACZC,SAAU,OACVC,SAAU,OACVC,cAAe,OACfC,OAAQ,UACRC,YAAa,eACbC,KAAM,MACNC,SAAU,OACVC,KAAM,YACNC,OAAQ,WACRC,YAAa,2FACbC,IAAK,sBACLC,WAAY,wBACZC,aAAc,aACdC,KAAM,SAGV,SAASC,EAAQJ,GAEb,OAOJ,SAAwBK,EAAYC,GAChC,IAAiDC,EAAkBC,EAAGC,EAAGC,EAAIC,EAAKC,EAAeC,EAAYC,EAAaX,EAAtHY,EAAS,EAAGC,EAAcX,EAAWY,OAAaC,EAAS,GAC/D,IAAKV,EAAI,EAAGA,EAAIQ,EAAaR,IACzB,GAA6B,iBAAlBH,EAAWG,GAClBU,GAAUb,EAAWG,QAEpB,GAA6B,iBAAlBH,EAAWG,GAAiB,CAExC,IADAE,EAAKL,EAAWG,IACTW,KAEH,IADAZ,EAAMD,EAAKS,GACNN,EAAI,EAAGA,EAAIC,EAAGS,KAAKF,OAAQR,IAAK,CACjC,GAAWW,MAAPb,EACA,MAAM,IAAIc,MAAMjB,EAAQ,gEAAiEM,EAAGS,KAAKV,GAAIC,EAAGS,KAAKV,EAAE,KAEnHF,EAAMA,EAAIG,EAAGS,KAAKV,GACtB,MAGAF,EADKG,EAAGY,SACFhB,EAAKI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AC5B,kBAAMvH,EAAUY,qBAAV,OAAsC2G,EAA5C,CACV,EA6BDlN,KAAKkO,uBA3B0B,SAAUhB,GAIrC,OAHArF,EAAwBnG,EAAOoG,YZlyBb,yDYmyBlBtM,EAAMK,WAAWL,EAAM2H,WAAW+J,GAAK,yBACvCvH,EAAUa,qBAAqB9C,IAAIwJ,GAC5B,kBAAMvH,EAAUa,qBAAV,OAAsC0G,EAA5C,CACV,EAuBDlN,KAAKmO,eArBkB,SAAUjB,GAI7B,OAHArF,EAAwBnG,EAAOoG,YZxyBtB,gDYyyBTtM,EAAMK,WAAWL,EAAM2H,WAAW+J,GAAK,yBACvCvH,EAAUc,aAAa/C,IAAIwJ,GACpB,kBAAMvH,EAAUc,aAAV,OAA8ByG,EAApC,CACV,EAkBDlN,KAAKuL,eAAiB,WAClB/B,IACAE,IACA/E,EAAgBC,oBAAqB,EACrCyE,cAAc1B,GACd4D,EAAe,kCAClB,EAEDvL,KAAKwL,0BAA4BA,CACpC,EA0BK4C,EAAyB,CAC3B7T,OAzBgC,SAACwF,GAOjC,OANKmC,IACDA,EAAqB,IAAIpC,EAAeC,IAEvCmC,EAAmBmM,kBACpBnM,EAAmBf,eAAepB,GAE/B,IAAIsE,CACd,EAkBGiK,gBAhBoB,SAAAhN,GACpB,IAAMiN,EAAejN,GAAUA,EAAOiN,aACjCrM,IACDA,EAAqB,IAAIpC,GAE7BoC,EAAmBjC,mBAAmBsO,GAEtC,IAAMC,EAAyBlN,GAAUA,EAAOkN,uBAC1CC,EAAwBD,GAA0BA,EAAuBlR,gBAC3EmR,GAA0D,mBAA1BA,IAChCjT,EAAM8B,gBAAkBmR,EAE/B,EAKGjP,SAAUA,EACVH,OAAQA,GCt4BZqP,OAAOC,QAAUD,OAAOC,SAAW,CAAC,EACpCA,QAAQtK,iBAAmB+J,C","sources":["webpack://@amzn/amazon-connect-websocket-manager/./node_modules/sprintf-js/src/sprintf.js","webpack://@amzn/amazon-connect-websocket-manager/webpack/bootstrap","webpack://@amzn/amazon-connect-websocket-manager/./node_modules/@babel/runtime/helpers/esm/typeof.js","webpack://@amzn/amazon-connect-websocket-manager/./src/constants.js","webpack://@amzn/amazon-connect-websocket-manager/./src/utils.js","webpack://@amzn/amazon-connect-websocket-manager/./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","webpack://@amzn/amazon-connect-websocket-manager/./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js","webpack://@amzn/amazon-connect-websocket-manager/./node_modules/@babel/runtime/helpers/esm/defineProperty.js","webpack://@amzn/amazon-connect-websocket-manager/./node_modules/@babel/runtime/helpers/esm/classCallCheck.js","webpack://@amzn/amazon-connect-websocket-manager/./node_modules/@babel/runtime/helpers/esm/createClass.js","webpack://@amzn/amazon-connect-websocket-manager/./node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js","webpack://@amzn/amazon-connect-websocket-manager/./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","webpack://@amzn/amazon-connect-websocket-manager/./src/log.js","webpack://@amzn/amazon-connect-websocket-manager/./node_modules/@babel/runtime/helpers/esm/inherits.js","webpack://@amzn/amazon-connect-websocket-manager/./src/retryProvider.js","webpack://@amzn/amazon-connect-websocket-manager/./src/webSocketManager.js","webpack://@amzn/amazon-connect-websocket-manager/./src/index.js"],"sourcesContent":["/* global window, exports, define */\n\n!function() {\n 'use strict'\n\n var re = {\n not_string: /[^s]/,\n not_bool: /[^t]/,\n not_type: /[^T]/,\n not_primitive: /[^v]/,\n number: /[diefg]/,\n numeric_arg: /[bcdiefguxX]/,\n json: /[j]/,\n not_json: /[^j]/,\n text: /^[^\\x25]+/,\n modulo: /^\\x25{2}/,\n placeholder: /^\\x25(?:([1-9]\\d*)\\$|\\(([^)]+)\\))?(\\+)?(0|'[^$])?(-)?(\\d+)?(?:\\.(\\d+))?([b-gijostTuvxX])/,\n key: /^([a-z_][a-z_\\d]*)/i,\n key_access: /^\\.([a-z_][a-z_\\d]*)/i,\n index_access: /^\\[(\\d+)\\]/,\n sign: /^[+-]/\n }\n\n function sprintf(key) {\n // `arguments` is not an array, but should be fine for this call\n return sprintf_format(sprintf_parse(key), arguments)\n }\n\n function vsprintf(fmt, argv) {\n return sprintf.apply(null, [fmt].concat(argv || []))\n }\n\n function sprintf_format(parse_tree, argv) {\n var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign\n for (i = 0; i < tree_length; i++) {\n if (typeof parse_tree[i] === 'string') {\n output += parse_tree[i]\n }\n else if (typeof parse_tree[i] === 'object') {\n ph = parse_tree[i] // convenience purposes only\n if (ph.keys) { // keyword argument\n arg = argv[cursor]\n for (k = 0; k < ph.keys.length; k++) {\n if (arg == undefined) {\n throw new Error(sprintf('[sprintf] Cannot access property \"%s\" of undefined value \"%s\"', ph.keys[k], ph.keys[k-1]))\n }\n arg = arg[ph.keys[k]]\n }\n }\n else if (ph.param_no) { // positional argument (explicit)\n arg = argv[ph.param_no]\n }\n else { // positional argument (implicit)\n arg = argv[cursor++]\n }\n\n if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {\n arg = arg()\n }\n\n if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {\n throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))\n }\n\n if (re.number.test(ph.type)) {\n is_positive = arg >= 0\n }\n\n switch (ph.type) {\n case 'b':\n arg = parseInt(arg, 10).toString(2)\n break\n case 'c':\n arg = String.fromCharCode(parseInt(arg, 10))\n break\n case 'd':\n case 'i':\n arg = parseInt(arg, 10)\n break\n case 'j':\n arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)\n break\n case 'e':\n arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()\n break\n case 'f':\n arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)\n break\n case 'g':\n arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)\n break\n case 'o':\n arg = (parseInt(arg, 10) >>> 0).toString(8)\n break\n case 's':\n arg = String(arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 't':\n arg = String(!!arg)\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'T':\n arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'u':\n arg = parseInt(arg, 10) >>> 0\n break\n case 'v':\n arg = arg.valueOf()\n arg = (ph.precision ? arg.substring(0, ph.precision) : arg)\n break\n case 'x':\n arg = (parseInt(arg, 10) >>> 0).toString(16)\n break\n case 'X':\n arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()\n break\n }\n if (re.json.test(ph.type)) {\n output += arg\n }\n else {\n if (re.number.test(ph.type) && (!is_positive || ph.sign)) {\n sign = is_positive ? '+' : '-'\n arg = arg.toString().replace(re.sign, '')\n }\n else {\n sign = ''\n }\n pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '\n pad_length = ph.width - (sign + arg).length\n pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''\n output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)\n }\n }\n }\n return output\n }\n\n var sprintf_cache = Object.create(null)\n\n function sprintf_parse(fmt) {\n if (sprintf_cache[fmt]) {\n return sprintf_cache[fmt]\n }\n\n var _fmt = fmt, match, parse_tree = [], arg_names = 0\n while (_fmt) {\n if ((match = re.text.exec(_fmt)) !== null) {\n parse_tree.push(match[0])\n }\n else if ((match = re.modulo.exec(_fmt)) !== null) {\n parse_tree.push('%')\n }\n else if ((match = re.placeholder.exec(_fmt)) !== null) {\n if (match[2]) {\n arg_names |= 1\n var field_list = [], replacement_field = match[2], field_match = []\n if ((field_match = re.key.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {\n if ((field_match = re.key_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else if ((field_match = re.index_access.exec(replacement_field)) !== null) {\n field_list.push(field_match[1])\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n }\n }\n else {\n throw new SyntaxError('[sprintf] failed to parse named argument key')\n }\n match[2] = field_list\n }\n else {\n arg_names |= 2\n }\n if (arg_names === 3) {\n throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')\n }\n\n parse_tree.push(\n {\n placeholder: match[0],\n param_no: match[1],\n keys: match[2],\n sign: match[3],\n pad_char: match[4],\n align: match[5],\n width: match[6],\n precision: match[7],\n type: match[8]\n }\n )\n }\n else {\n throw new SyntaxError('[sprintf] unexpected placeholder')\n }\n _fmt = _fmt.substring(match[0].length)\n }\n return sprintf_cache[fmt] = parse_tree\n }\n\n /**\n * export to either browser or node.js\n */\n /* eslint-disable quote-props */\n if (typeof exports !== 'undefined') {\n exports['sprintf'] = sprintf\n exports['vsprintf'] = vsprintf\n }\n if (typeof window !== 'undefined') {\n window['sprintf'] = sprintf\n window['vsprintf'] = vsprintf\n\n if (typeof define === 'function' && define['amd']) {\n define(function() {\n return {\n 'sprintf': sprintf,\n 'vsprintf': vsprintf\n }\n })\n }\n }\n /* eslint-enable quote-props */\n}(); // eslint-disable-line\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}","\nexport const LOGS_DESTINATION = {\n NULL: \"NULL\",\n CLIENT_LOGGER: \"CLIENT_LOGGER\",\n DEBUG: \"DEBUG\"\n};\n\nexport const MIN_WEBSOCKET_LIFETIME_MS = 300000;\nexport const HEARTBEAT_INTERVAL_MS = 10000;\nexport const WEBSOCKET_URL_VALID_TIME_MS = 85000;\nexport const TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS = 500;\nexport const MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS = 5;\nexport const MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS = 1000;\nexport const MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE = 3;\nexport const NETWORK_CONN_CHECK_INTERVAL_MS = 250;\nexport const WEBSOCKET_REINIT_JITTER = 0.3;\nexport const WEBSOCKET_RETRY_RATE_MS = 2000;\nexport const MAX_WEBSOCKET_RETRY_RATE_MS = 30000;\n\nexport const NETWORK_FAILURE = 'NetworkingError';\n\nexport const LOG_MESSAGES = {\n DEFAULT_PREFIX: \"AMZ_WEB_SOCKET_MANAGER:\",\n NETWORK_OFFLINE: \"Network offline\",\n NETWORK_ONLINE: \"Network online, connecting to WebSocket server\",\n NETWORK_OFFLINE_WARNING: \"Network offline, ignoring this getWebSocketConnConfig request\",\n NO_HEARTBEAT: \"Heartbeat response not received\",\n NO_DEEP_HEARTBEAT: \"aws/ping deep heartbeat response not received\",\n HEARTBEAT_RECEIVED: \"Heartbeat response received\",\n DEEP_HEARTBEAT_RECEIVED: \"aws/ping deep heartbeat received\",\n SENDING_HEARTBEAT: \"Sending heartbeat\",\n SENDING_DEEP_HEARTBEAT: \"Sending aws/ping deep heartbeat\",\n FAILED_HEARTBEAT: \"Failed to send heartbeat since WebSocket is not open\",\n FAILED_DEEP_HEARTBEAT: \"Failed to send aws/ping deep heartbeat since WebSocket is not open\",\n DEEP_HEARTBEAT_SUCCESS: \"Websocket deep heartbeat success callback registered\",\n DEEP_HEARTBEAT_FAILURE: \"Websocket deep heartbeat failure callback registered\",\n TOPIC_FAILURE: \"Websocket topic failure callback registered\",\n WEBSOCKET_CONNECTION_ESTABLISHED: \"WebSocket connection established!\",\n WEBSOCKET_CONNECTION_CLOSED: \"WebSocket connection is closed. \",\n WEBSOCKET_CONNECTION_DURATION: \"Closed WebSocket connection duration: \",\n WEBSOCKET_CONNECTION_ERROR: \"WebSocketManager Error, error_event: \",\n WEBSOCKET_REINITIALIZATION: \"Scheduling WebSocket reinitialization, after delay \",\n WEBSOCKET_REINITIALIZATION_TIMEOUT: \"WebSocket URL cannot be used to establish connection\",\n WEBSOCKET_INITIALIZATION_FAILED: \"WebSocket Initialization failed - Terminating and cleaning subscriptions\",\n WEBSOCKET_TERMINATED: \"Terminating WebSocket Manager\",\n WEBSOCKET_NEW_CONNECTION: \"Fetching new WebSocket connection configuration\",\n WEBSOCKET_CONNECTION_SUCCESS: \"Successfully fetched webSocket connection configuration\",\n WEBSOCKET_CONNECTION_FAILURE: \"Failed to fetch webSocket connection configuration\",\n WEBSOCKET_CONNECTION_RETRY: \"Retrying fetching new WebSocket connection configuration\",\n WEBSOCKET_INIT: \"Initializing Websocket Manager\",\n WEBSOCKET_INIT_FAILURE: \"Initializing Websocket Manager Failure callback registered\",\n WEBSOCKET_CONNECTION_OPEN: \"Websocket connection open callback registered\",\n WEBSOCKET_CONNECTION_CLOSE: \"Websocket connection close callback registered\",\n WEBSOCKET_CONNECTION_GAIN: \"Websocket connection gain callback registered\",\n WEBSOCKET_CONNECTION_LOST: \"Websocket connection lost callback registered\",\n WEBSOCKET_SUBSCRIPTION_FAILURE: \"Websocket subscription failure callback registered\",\n WEBSOCKET_RESET: \"Reset Websocket state\",\n WEBSOCKET_MESSAGE_ERROR: \"WebSocketManager Message Error\",\n WEBSOCKET_MESSAGE_RECEIVED: \"Message received for topic \",\n WEBSOCKET_MESSAGE_INVALID: \"Invalid incoming message\",\n WEBSOCKET_MESSAGE_SUCCESS: \"WebsocketManager invoke callbacks for topic success \",\n};\n\nexport const ROUTE_KEY = {\n SUBSCRIBE: \"aws/subscribe\",\n UNSUBSCRIBE: \"aws/unsubscribe\",\n HEARTBEAT: \"aws/heartbeat\",\n DEEP_HEARTBEAT: \"aws/ping\"\n};\n\nexport const CONN_STATE = {\n CONNECTED: \"connected\",\n DISCONNECTED: \"disconnected\"\n};\n","import { sprintf } from \"sprintf-js\";\nimport { NETWORK_FAILURE } from './constants';\n\nconst Utils = {};\n\n/**\n * Asserts that a premise is true.\n */\nUtils.assertTrue = function(premise, message) {\n if (!premise) {\n throw new Error(message);\n }\n};\n\n/**\n * Asserts that a value is not null or undefined.\n */\nUtils.assertNotNull = function(value, name) {\n Utils.assertTrue(\n value !== null && typeof value !== undefined,\n sprintf(\"%s must be provided\", name || \"A value\")\n );\n return value;\n};\n\nUtils.isNonEmptyString = function(value) {\n return typeof value === \"string\" && value.length > 0;\n};\n\nUtils.assertIsList = function(value, key) {\n if (!Array.isArray(value)) {\n throw new Error(key + \" is not an array\");\n }\n};\n\n/**\n * Determine if the given value is a callable function type.\n * Borrowed from Underscore.js.\n */\nUtils.isFunction = function(obj) {\n return !!(obj && obj.constructor && obj.call && obj.apply);\n};\n\nUtils.isObject = function(value) {\n return !(typeof value !== \"object\" || value === null);\n};\n\nUtils.isString = function(value) {\n return typeof value === \"string\";\n};\n\nUtils.isNumber = function(value) {\n return typeof value === \"number\";\n};\n\nconst wsRegex = new RegExp(\"^(wss://)\\\\w*\");\nconst localWsRegex = new RegExp(\"^(ws://127.0.0.1:)\");\nUtils.validWSUrl = function (wsUrl) {\n return wsRegex.test(wsUrl) || localWsRegex.test(wsUrl);\n};\n\nUtils.getSubscriptionResponse = (routeKey, isSuccess, topicList) => {\n return {\n topic: routeKey,\n content : {\n status: isSuccess ? \"success\" : \"failure\",\n topics: topicList\n }\n };\n};\n\nUtils.assertIsObject = function(value, key) {\n if (!Utils.isObject(value)) {\n throw new Error(key + \" is not an object!\");\n }\n};\n\nUtils.addJitter = function (base, maxJitter = 1) {\n maxJitter = Math.min(maxJitter, 1.0);\n const sign = Math.random() > 0.5 ? 1 : -1;\n return Math.floor(base + sign * base * Math.random() * maxJitter);\n};\n\nUtils.isNetworkOnline = () => navigator.onLine;\n\nUtils.isNetworkFailure = (reason) => {\n if(reason._debug && reason._debug.type) {\n return reason._debug.type === NETWORK_FAILURE;\n }\n return false;\n};\n\nexport default Utils;\n","export default function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}","export default function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n}","export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}","export default function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}","function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n}\n\nexport default function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n}","import _typeof from \"./typeof.js\";\nimport assertThisInitialized from \"./assertThisInitialized.js\";\nexport default function _possibleConstructorReturn(self, call) {\n if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) {\n return call;\n } else if (call !== void 0) {\n throw new TypeError(\"Derived constructors may only return object or undefined\");\n }\n\n return assertThisInitialized(self);\n}","export default function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return self;\n}","import Utils from \"./utils\";\nimport { LOGS_DESTINATION, LOG_MESSAGES } from \"./constants\";\n\n/*eslint-disable no-unused-vars*/\nclass Logger {\n debug(data) {}\n\n info(data) {}\n\n warn(data) {}\n\n error(data) {}\n\n advancedLog(data) {}\n}\n/*eslint-enable no-unused-vars*/\n\nconst DEFAULT_PREFIX = LOG_MESSAGES.DEFAULT_PREFIX;\nconst LogLevel = {\n DEBUG: 10,\n INFO: 20,\n WARN: 30,\n ERROR: 40,\n ADVANCED_LOG: 50,\n};\n\nclass LogManagerImpl {\n constructor(logMetaData) {\n this.logMetaData = logMetaData || '';\n this.updateLoggerConfig();\n }\n\n hasLogMetaData() {\n return !!this.logMetaData;\n }\n\n writeToClientLogger(level, logStatement = '') {\n if (!this.hasClientLogger()) {\n return;\n }\n const log1 = typeof logStatement === \"string\" ? logStatement : JSON.stringify(logStatement, removeCircularReference());\n const log2 = typeof this.logMetaData === \"string\" ? this.logMetaData : JSON.stringify(this.logMetaData, removeCircularReference());\n let logStringValue = `${getLogLevelByValue(level)} ${log1}`;\n if (log2) logStringValue += ` ${log2}`;\n switch (level) {\n case LogLevel.DEBUG:\n return this._clientLogger.debug(logStringValue) || logStringValue;\n case LogLevel.INFO:\n return this._clientLogger.info(logStringValue) || logStringValue;\n case LogLevel.WARN:\n return this._clientLogger.warn(logStringValue) || logStringValue;\n case LogLevel.ERROR:\n return this._clientLogger.error(logStringValue) || logStringValue;\n case LogLevel.ADVANCED_LOG:\n if(!this._advancedLogWriter) return '';\n return this._clientLogger[this._advancedLogWriter](logStringValue) || logStringValue;\n }\n }\n\n isLevelEnabled(level) {\n return level >= this._level;\n }\n\n hasClientLogger() {\n return this._clientLogger !== null;\n }\n\n getLogger(options = {}) {\n var prefix = options.prefix || DEFAULT_PREFIX;\n if (options.logMetaData) {\n this.setLogMetaData(options.logMetaData);\n }\n return new LoggerWrapperImpl(this, { prefix, logMetaData: this.logMetaData, ...options });\n }\n\n setLogMetaData(logMetaData) {\n this.logMetaData = logMetaData;\n }\n\n updateLoggerConfig(inputConfig) {\n var config = inputConfig || {};\n this._level = config.level || LogLevel.INFO;\n //enabled advancedLogWriter\n this._advancedLogWriter = \"warn\";\n if (config.advancedLogWriter) {\n this._advancedLogWriter = config.advancedLogWriter;\n }\n\n if(config.customizedLogger && typeof config.customizedLogger === \"object\") {\n this.useClientLogger = true;\n } else {\n this.useClientLogger = false;\n }\n this._clientLogger = config.logger || this.selectLogger(config);\n\n this._logsDestination = LOGS_DESTINATION.NULL;\n if (config.debug) {\n this._logsDestination = LOGS_DESTINATION.DEBUG;\n }\n if (config.logger) {\n this._logsDestination = LOGS_DESTINATION.CLIENT_LOGGER;\n }\n }\n\n selectLogger(config) {\n if(config.customizedLogger && typeof config.customizedLogger === \"object\") {\n return config.customizedLogger;\n }\n if(config.useDefaultLogger) {\n return createConsoleLogger();\n }\n return null;\n }\n}\n\nclass LoggerWrapper {\n debug() {}\n\n info() {}\n\n warn() {}\n\n error() {}\n\n advancedLog() {}\n}\n\nclass LoggerWrapperImpl extends LoggerWrapper {\n constructor(logManagerInstance, options) {\n super();\n this.options = options || {};\n this.prefix = options.prefix || DEFAULT_PREFIX;\n this.excludeTimestamp = options.excludeTimestamp;\n this.logManager = logManagerInstance;\n }\n\n debug(...args) {\n return this._log(LogLevel.DEBUG, args);\n }\n\n info(...args) {\n return this._log(LogLevel.INFO, args);\n }\n\n warn(...args) {\n return this._log(LogLevel.WARN, args);\n }\n\n error(...args) {\n return this._log(LogLevel.ERROR, args);\n }\n\n advancedLog(...args) {\n return this._log(LogLevel.ADVANCED_LOG, args);\n }\n\n _shouldLog(level) {\n return this.logManager.hasClientLogger() && this.logManager.isLevelEnabled(level);\n }\n\n _writeToClientLogger(level, logStatement) {\n return this.logManager.writeToClientLogger(level, logStatement);\n }\n\n _log(level, args) {\n if (this._shouldLog(level)) {\n var logStatement = this.logManager.useClientLogger ? args : this._convertToSingleStatement(args);\n return this._writeToClientLogger(level, logStatement);\n }\n }\n\n _convertToSingleStatement(args) {\n var date = new Date(Date.now()).toISOString();\n var logStatement = this.excludeTimestamp ? '' : `[${date}] `;\n if (this.prefix || this.options.prefix) {\n logStatement += (this.options.prefix || this.prefix) + \":\";\n }\n for (var index = 0; index < args.length; index++) {\n var arg = args[index];\n logStatement += this._convertToString(arg) + \" \";\n }\n return logStatement;\n }\n\n _convertToString(arg) {\n try {\n if (!arg) {\n return \"\";\n }\n if (Utils.isString(arg)) {\n return arg;\n }\n if (Utils.isObject(arg) && Utils.isFunction(arg.toString)) {\n var toStringResult = arg.toString();\n if (!toStringResult.startsWith(\"[object\")) {\n return toStringResult;\n }\n }\n return JSON.stringify(arg);\n } catch (error) {\n console.error(\"Error while converting argument to string\", arg, error);\n return \"\";\n }\n }\n}\n\nfunction getLogLevelByValue(value) {\n switch(value) {\n case 10: return \"DEBUG\";\n case 20: return \"INFO\";\n case 30: return \"WARN\";\n case 40: return \"ERROR\";\n case 50: return \"ADVANCED_LOG\";\n }\n}\n\nfunction removeCircularReference() {\n const seen = new WeakSet();\n\n return (key, value) => {\n if (typeof value === \"object\" && value !== null) {\n if (seen.has(value)) {\n return;\n }\n seen.add(value);\n }\n return value;\n };\n}\n\nvar createConsoleLogger = () => {\n var logger = new LoggerWrapper();\n logger.debug = (...args) => console.debug.apply(window.console, [].concat(args));\n logger.info = (...args) => console.info.apply(window.console, [].concat(args));\n logger.warn = (...args) => console.warn.apply(window.console, [].concat(args));\n logger.error = (...args) => console.error.apply(window.console, [].concat(args));\n return logger;\n};\n\nexport { LogManagerImpl, Logger, LogLevel };\n","import setPrototypeOf from \"./setPrototypeOf.js\";\nexport default function _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n Object.defineProperty(subClass, \"prototype\", {\n writable: false\n });\n if (superClass) setPrototypeOf(subClass, superClass);\n}","import { WEBSOCKET_RETRY_RATE_MS, MAX_WEBSOCKET_RETRY_RATE_MS } from './constants';\n\nclass RetryProvider {\n constructor(executor, defaultRetry = WEBSOCKET_RETRY_RATE_MS) {\n this.numAttempts = 0;\n this.executor = executor;\n this.hasActiveReconnection = false;\n this.defaultRetry = defaultRetry;\n }\n\n retry() {\n // Don't kickoff another reconnection attempt if we have one pending\n if (!this.hasActiveReconnection) {\n this.hasActiveReconnection = true;\n setTimeout(() => {\n this._execute();\n }, this._getDelay());\n }\n }\n\n _execute() {\n this.hasActiveReconnection = false;\n this.executor();\n this.numAttempts++;\n }\n\n connected() {\n this.numAttempts = 0;\n }\n\n _getDelay() {\n const calculatedDelay = Math.pow(2, this.numAttempts) * this.defaultRetry;\n return calculatedDelay <= MAX_WEBSOCKET_RETRY_RATE_MS ? calculatedDelay : MAX_WEBSOCKET_RETRY_RATE_MS;\n }\n\n getIsConnected() {\n return !this.numAttempts;\n }\n}\n\nexport { RetryProvider };","import Utils from \"./utils\";\nimport { LogManagerImpl, LogLevel, Logger } from \"./log\";\nimport {\n MIN_WEBSOCKET_LIFETIME_MS,\n WEBSOCKET_URL_VALID_TIME_MS,\n HEARTBEAT_INTERVAL_MS,\n ROUTE_KEY,\n CONN_STATE,\n MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS,\n TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS,\n MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS,\n MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE,\n NETWORK_CONN_CHECK_INTERVAL_MS,\n WEBSOCKET_REINIT_JITTER,\n LOG_MESSAGES,\n} from \"./constants\";\nimport { RetryProvider } from './retryProvider';\n\nlet logManagerInstance = null;\nconst WebSocketManager = function () {\n\n const logger = logManagerInstance.getLogger({ prefix: LOG_MESSAGES.DEFAULT_PREFIX, excludeTimestamp: true });\n\n let online = Utils.isNetworkOnline();\n\n let webSocket = {\n primary: null,\n secondary: null\n };\n\n let reconnectConfig = {\n reconnectWebSocket: true,\n websocketInitFailed: false,\n exponentialBackOffTime: 1000,\n exponentialTimeoutHandle: null,\n lifeTimeTimeoutHandle: null,\n webSocketInitCheckerTimeoutId: null,\n connState: null\n };\n\n let metrics = {\n connectWebSocketRetryCount: 0,\n connectionAttemptStartTime: null,\n noOpenConnectionsTimestamp: null\n };\n\n let heartbeatConfig = {\n pendingResponse: false,\n intervalHandle: null\n };\n\n let deepHeartbeatConfig = {\n pendingResponse: false,\n intervalHandle: null\n };\n\n let callbacks = {\n initFailure: new Set(),\n getWebSocketTransport: null,\n subscriptionUpdate: new Set(),\n subscriptionFailure: new Set(),\n topic: new Map(),\n allMessage: new Set(),\n connectionGain: new Set(),\n connectionLost: new Set(),\n connectionOpen: new Set(),\n connectionClose: new Set(),\n deepHeartbeatSuccess: new Set(),\n deepHeartbeatFailure: new Set(),\n topicFailure: new Set(),\n };\n\n let webSocketConfig = {\n connConfig: null,\n promiseHandle: null,\n promiseCompleted: true\n };\n\n let topicSubscription = {\n subscribed: new Set(),\n pending: new Set(),\n subscriptionHistory: new Set()\n };\n\n let topicSubscriptionConfig = {\n responseCheckIntervalId: null,\n requestCompleted: true,\n reSubscribeIntervalId: null,\n consecutiveFailedSubscribeAttempts: 0,\n consecutiveNoResponseRequest: 0\n };\n\n const reconnectionClient = new RetryProvider(() => { getWebSocketConnConfig().catch(() => {}); });\n\n const invalidSendMessageRouteKeys = new Set([ROUTE_KEY.SUBSCRIBE, ROUTE_KEY.UNSUBSCRIBE, ROUTE_KEY.HEARTBEAT, ROUTE_KEY.DEEP_HEARTBEAT]);\n\n const networkConnectivityChecker = setInterval(function () {\n if (online !== Utils.isNetworkOnline()) {\n online = Utils.isNetworkOnline();\n if (!online) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.NETWORK_OFFLINE));\n return;\n }\n const ws = getDefaultWebSocket();\n if (online && (!ws || isWebSocketState(ws, WebSocket.CLOSING) || isWebSocketState(ws, WebSocket.CLOSED))) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.NETWORK_ONLINE));\n getWebSocketConnConfig().catch(() => {});\n }\n }\n }, NETWORK_CONN_CHECK_INTERVAL_MS);\n\n const invokeCallbacks = function (callbacks, response) {\n callbacks.forEach(function (callback) {\n try {\n callback(response);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error executing callback\", error));\n }\n });\n };\n\n const getWebSocketStates = function (ws) {\n if (ws === null) return \"NULL\";\n switch (ws.readyState) {\n case WebSocket.CONNECTING:\n return \"CONNECTING\";\n case WebSocket.OPEN:\n return \"OPEN\";\n case WebSocket.CLOSING:\n return \"CLOSING\";\n case WebSocket.CLOSED:\n return \"CLOSED\";\n default:\n return \"UNDEFINED\";\n }\n };\n\n const printWebSocketState = function (event = \"\") {\n sendInternalLogToServer(logger.debug(\"[\" + event + \"] Primary WebSocket: \" + getWebSocketStates(webSocket.primary)\n + \" | \" + \"Secondary WebSocket: \" + getWebSocketStates(webSocket.secondary)));\n };\n\n const isWebSocketState = function (ws, webSocketStateCode) {\n return ws && ws.readyState === webSocketStateCode;\n };\n\n const isWebSocketOpen = function (ws) {\n return isWebSocketState(ws, WebSocket.OPEN);\n };\n\n const isWebSocketClosed = function (ws) {\n // undefined check is to address the limitation of testing framework\n return ws === null || ws.readyState === undefined || isWebSocketState(ws, WebSocket.CLOSED);\n };\n\n /**\n * This function is meant to handle the scenario when we have two web-sockets open\n * in such a scenario we always select secondary web-socket since all future operations\n * are supposed to be done by this secondary web-socket\n */\n const getDefaultWebSocket = function () {\n if (webSocket.secondary !== null) {\n return webSocket.secondary;\n }\n return webSocket.primary;\n };\n\n const isDefaultWebSocketOpen = function () {\n return isWebSocketOpen(getDefaultWebSocket());\n };\n\n const sendHeartBeat = function () {\n if (deepHeartbeatConfig.pendingResponse) {\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.NO_DEEP_HEARTBEAT));\n // trigger deepHeartbeatFailure - no response is received \n invokeCallbacks(callbacks.deepHeartbeatFailure, {\n timestamp: Date.now(),\n error: \"aws/ping response is not received\",\n });\n\n clearInterval(deepHeartbeatConfig.intervalHandle);\n deepHeartbeatConfig.pendingResponse = false;\n }\n if (heartbeatConfig.pendingResponse) {\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.NO_HEARTBEAT));\n\n clearInterval(heartbeatConfig.intervalHandle);\n heartbeatConfig.intervalHandle = null;\n heartbeatConfig.pendingResponse = false;\n getWebSocketConnConfig().catch(() => {});\n return;\n }\n if (isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.SENDING_DEEP_HEARTBEAT));\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.DEEP_HEARTBEAT));\n deepHeartbeatConfig.pendingResponse = true;\n\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.SENDING_HEARTBEAT));\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.HEARTBEAT));\n heartbeatConfig.pendingResponse = true;\n } else {\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.FAILED_DEEP_HEARTBEAT));\n // trigger deepHeartbeatFailure - message is unable to be sent to aws/ping because websocket connection is not established.\n invokeCallbacks(callbacks.deepHeartbeatFailure, {\n timestamp: Date.now(),\n error: \"Unable to send message to aws/ping because websocket connection is not established.\"\n });\n\n sendInternalLogToServer(logger.warn(LOG_MESSAGES.FAILED_HEARTBEAT));\n\n printWebSocketState(\"sendHeartBeat\");\n getWebSocketConnConfig().catch(() => {});\n }\n };\n\n const resetWebSocketState = function () {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_RESET));\n reconnectConfig.exponentialBackOffTime = 1000;\n heartbeatConfig.pendingResponse = false;\n deepHeartbeatConfig.pendingResponse = false;\n\n reconnectConfig.reconnectWebSocket = true;\n\n clearTimeout(reconnectConfig.lifeTimeTimeoutHandle);\n clearInterval(heartbeatConfig.intervalHandle);\n clearInterval(deepHeartbeatConfig.intervalHandle);\n clearTimeout(reconnectConfig.exponentialTimeoutHandle);\n clearTimeout(reconnectConfig.webSocketInitCheckerTimeoutId);\n\n heartbeatConfig.intervalHandle = null;\n };\n\n const resetSubscriptions = function () {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n };\n\n const resetMetrics = function () {\n metrics.connectWebSocketRetryCount = 0;\n metrics.connectionAttemptStartTime = null;\n metrics.noOpenConnectionsTimestamp = null;\n };\n\n const webSocketOnOpen = function () {\n // Mark connection as successful; reset the number of reconnect attempts to 0.\n reconnectionClient.connected();\n\n try {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_ESTABLISHED));\n\n printWebSocketState(\"webSocketOnOpen\");\n if (reconnectConfig.connState === null || reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n invokeCallbacks(callbacks.connectionGain);\n }\n reconnectConfig.connState = CONN_STATE.CONNECTED;\n\n // Report number of retries to open and record ws open time\n const now = Date.now();\n invokeCallbacks(callbacks.connectionOpen, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n noOpenConnectionsTimestamp: metrics.noOpenConnectionsTimestamp,\n connectionEstablishedTime: now,\n timeToConnect: now - metrics.connectionAttemptStartTime,\n timeWithoutConnection:\n metrics.noOpenConnectionsTimestamp ? now - metrics.noOpenConnectionsTimestamp : null\n });\n\n resetMetrics();\n resetWebSocketState();\n getDefaultWebSocket().openTimestamp = Date.now(); // record open time\n\n // early closure of primary web socket\n if (topicSubscription.subscribed.size === 0 && isWebSocketOpen(webSocket.secondary)) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n if (topicSubscription.subscribed.size > 0 || topicSubscription.pending.size > 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.info(\"Subscribing secondary websocket to topics of primary websocket\"));\n }\n topicSubscription.subscribed.forEach(topic => {\n topicSubscription.subscriptionHistory.add(topic);\n topicSubscription.pending.add(topic);\n });\n topicSubscription.subscribed.clear();\n subscribePendingTopics();\n }\n\n sendHeartBeat();\n if (heartbeatConfig.intervalHandle !== null) {\n clearInterval(heartbeatConfig.intervalHandle);\n }\n heartbeatConfig.intervalHandle = setInterval(sendHeartBeat, HEARTBEAT_INTERVAL_MS);\n\n const webSocketLifetimeTimeout = webSocketConfig.connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000;\n sendInternalLogToServer(logger.debug(\"Scheduling WebSocket manager reconnection, after delay \" + webSocketLifetimeTimeout + \" ms\"));\n\n reconnectConfig.lifeTimeTimeoutHandle = setTimeout(function () {\n sendInternalLogToServer(logger.debug(\"Starting scheduled WebSocket manager reconnection\"));\n\n getWebSocketConnConfig().catch(() => {});\n }, webSocketLifetimeTimeout);\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error after establishing WebSocket connection\", error));\n }\n };\n\n const webSocketOnClose = function (event, ws) {\n const webSocketCloseDetails = {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean\n };\n const closeEventDetails = `Close Code: ${webSocketCloseDetails.code} - Reason: ${webSocketCloseDetails.reason} - WasClean: ${webSocketCloseDetails.wasClean}`;\n const connectionDetails = `OpenTimestamp: ${webSocketCloseDetails.openTimestamp} - CloseTimestamp: ${webSocketCloseDetails.closeTimestamp} - ConnectionDuration: ${webSocketCloseDetails.connectionDuration}`;\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_CLOSED, closeEventDetails));\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_DURATION, connectionDetails));\n\n printWebSocketState(\"webSocketOnClose before-cleanup\");\n\n invokeCallbacks(callbacks.connectionClose, webSocketCloseDetails);\n\n if (isWebSocketClosed(webSocket.primary)) {\n webSocket.primary = null;\n }\n if (isWebSocketClosed(webSocket.secondary)) {\n webSocket.secondary = null;\n }\n if (!reconnectConfig.reconnectWebSocket) {\n return;\n }\n if (!isWebSocketOpen(webSocket.primary) && !isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.warn(\"Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection\"));\n\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n /**\n * This check is required in the scenario where WS Server shuts-down and closes all active\n * WS Client connections and WS Server takes about a minute to become active again, in this\n * scenario WS Client's onClose is triggered and then WSM start reconnect logic immediately but all\n * connect request to WS Server would fail and WS Client's onError callback would be triggered\n * followed WS Client's onClose callback and hence \"connectionLost\" callback would be invoked several\n * times and this behavior is redundant\n */\n sendInternalLogToServer(logger.info(\"Ignoring connectionLost callback invocation\"));\n } else {\n invokeCallbacks(callbacks.connectionLost, {\n openTimestamp: ws.openTimestamp,\n closeTimestamp: Date.now(),\n connectionDuration: Date.now() - ws.openTimestamp,\n code: event.code,\n reason: event.reason\n });\n metrics.noOpenConnectionsTimestamp = Date.now();\n }\n reconnectConfig.connState = CONN_STATE.DISCONNECTED;\n getWebSocketConnConfig().catch(() => {});\n } else if (isWebSocketClosed(webSocket.primary) && isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.debug(\"[Primary] WebSocket Cleanly Closed\"));\n\n webSocket.primary = webSocket.secondary;\n webSocket.secondary = null;\n }\n printWebSocketState(\"webSocketOnClose after-cleanup\");\n };\n\n const webSocketOnError = function (event) {\n printWebSocketState(\"webSocketOnError\");\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_ERROR, JSON.stringify(event)));\n const isConnected = reconnectionClient.getIsConnected();\n\n if (isConnected) {\n getWebSocketConnConfig().catch(() => {});\n } else {\n reconnectionClient.retry();\n }\n };\n\n const webSocketOnMessage = function (event) {\n if (typeof event.data === \"undefined\" || event.data === \"\") {\n sendInternalLogToServer(logger.warn(\"An empty message has been received on Websocket. Ignoring\"));\n return;\n }\n const response = JSON.parse(event.data);\n\n switch (response.topic) {\n\n case ROUTE_KEY.SUBSCRIBE: {\n sendInternalLogToServer(logger.debug(\"Subscription Message received from webSocket server\"));\n\n topicSubscriptionConfig.requestCompleted = true;\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n\n if (response.content.status === \"success\") {\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n response.content.topics.forEach(topicName => {\n topicSubscription.subscriptionHistory.delete(topicName);\n topicSubscription.pending.delete(topicName);\n topicSubscription.subscribed.add(topicName);\n });\n if (topicSubscription.subscriptionHistory.size === 0) {\n if (isWebSocketOpen(webSocket.secondary)) {\n sendInternalLogToServer(logger.debug(\"Successfully subscribed secondary websocket to all topics of primary websocket\"));\n\n closeSpecificWebSocket(webSocket.primary, \"[Primary WebSocket] Closing WebSocket\");\n }\n } else {\n subscribePendingTopics();\n }\n invokeCallbacks(callbacks.subscriptionUpdate, response);\n\n } else {\n clearInterval(topicSubscriptionConfig.reSubscribeIntervalId);\n ++topicSubscriptionConfig.consecutiveFailedSubscribeAttempts;\n if (topicSubscriptionConfig.consecutiveFailedSubscribeAttempts === MAX_CONSECUTIVE_FAILED_SUB_ATTEMPTS) {\n invokeCallbacks(callbacks.subscriptionFailure, response);\n topicSubscriptionConfig.consecutiveFailedSubscribeAttempts = 0;\n return;\n }\n topicSubscriptionConfig.reSubscribeIntervalId = setInterval(function () {\n subscribePendingTopics();\n }, TOPIC_SUBSCRIPTION_RETRY_INTERVAL_MS);\n }\n break;\n }\n case ROUTE_KEY.HEARTBEAT: {\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.HEARTBEAT_RECEIVED));\n heartbeatConfig.pendingResponse = false;\n if (heartbeatConfig.intervalHandle === null) {\n heartbeatConfig.intervalHandle = setInterval(sendHeartBeat, HEARTBEAT_INTERVAL_MS);\n }\n break;\n }\n case ROUTE_KEY.DEEP_HEARTBEAT: {\n sendInternalLogToServer(logger.debug(LOG_MESSAGES.DEEP_HEARTBEAT_RECEIVED));\n deepHeartbeatConfig.pendingResponse = false;\n \n if (response.statusCode === 200) {// trigger deepHeartbeatSuccess if 200 response is received\n invokeCallbacks(callbacks.deepHeartbeatSuccess, {\n timestamp: Date.now(),\n });\n } else {//trigger deepHeartbeatFailure if 500 response is received\n invokeCallbacks(callbacks.deepHeartbeatFailure, {\n timestamp: Date.now(),\n statusCode: response.statusCode,\n statusContent: response.statusContent,\n });\n }\n break;\n }\n default: {\n if (response.topic) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_RECEIVED, response.topic));\n\n if (isWebSocketOpen(webSocket.primary) && isWebSocketOpen(webSocket.secondary)\n && topicSubscription.subscriptionHistory.size === 0 && this === webSocket.primary) {\n /**\n * This block is to handle scenario when both primary and secondary socket have subscribed to\n * a common topic but we are facing difficulty in closing the primary socket, then in this\n * situation messages will be received by both primary and secondary web socket\n */\n sendInternalLogToServer(logger.warn(\"Ignoring Message for Topic \" + response.topic + \", to avoid duplicates\"));\n\n return;\n }\n\n if (callbacks.allMessage.size === 0 && callbacks.topic.size === 0) {\n sendInternalLogToServer(logger.warn('No registered callback listener for Topic', response.topic));\n\n return;\n }\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_SUCCESS, response.topic));\n invokeCallbacks(callbacks.allMessage, response);\n if (callbacks.topic.has(response.topic)) {\n invokeCallbacks(callbacks.topic.get(response.topic), response);\n }\n\n } else if (response.message) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_ERROR, response));\n\n // trigger topicFailure if Forbidden message OR Timeout message is received\n invokeCallbacks(callbacks.topicFailure, {\n timestamp: Date.now(),\n errorMessage: response.message,\n connectionId: response.connectionId,\n requestId: response.requestId,\n });\n } else {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_MESSAGE_INVALID, response));\n }\n }\n }\n };\n\n const subscribePendingTopics = function () {\n if (topicSubscriptionConfig.consecutiveNoResponseRequest > MAX_CONSECUTIVE_SUB_REQUEST_WITH_NO_RESPONSE) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response\"));\n\n invokeCallbacks(callbacks.subscriptionFailure, Utils.getSubscriptionResponse(ROUTE_KEY.SUBSCRIBE, false, Array.from(topicSubscription.pending)));\n return;\n }\n if (!isDefaultWebSocketOpen()) {\n sendInternalLogToServer(logger.warn(\"Ignoring subscribePendingTopics call since Default WebSocket is not open\"));\n\n return;\n }\n if (Array.from(topicSubscription.pending).length === 0) {\n return;\n }\n\n clearInterval(topicSubscriptionConfig.responseCheckIntervalId);\n\n getDefaultWebSocket().send(createWebSocketPayload(ROUTE_KEY.SUBSCRIBE, {\n \"topics\": Array.from(topicSubscription.pending)\n }));\n topicSubscriptionConfig.requestCompleted = false;\n\n // This callback ensure that some response was received for subscription request\n topicSubscriptionConfig.responseCheckIntervalId = setInterval(function () {\n if (!topicSubscriptionConfig.requestCompleted) {\n ++topicSubscriptionConfig.consecutiveNoResponseRequest;\n subscribePendingTopics();\n }\n }, MAX_WAIT_TIME_SUB_REQUEST_WITH_NO_RESPONSE_MS);\n };\n\n const closeSpecificWebSocket = function (ws, reason) {\n if (isWebSocketState(ws, WebSocket.CONNECTING) || isWebSocketState(ws, WebSocket.OPEN)) {\n ws.close(1000, reason);\n } else {\n sendInternalLogToServer(logger.warn(\"Ignoring WebSocket Close request, WebSocket State: \" + getWebSocketStates(ws)));\n }\n };\n\n const closeWebSocket = function (reason) {\n closeSpecificWebSocket(webSocket.primary, \"[Primary] WebSocket \" + reason);\n closeSpecificWebSocket(webSocket.secondary, \"[Secondary] WebSocket \" + reason);\n };\n\n const retryWebSocketInitialization = function () {\n metrics.connectWebSocketRetryCount++;\n const waitTime = Utils.addJitter(reconnectConfig.exponentialBackOffTime, WEBSOCKET_REINIT_JITTER);\n if (Date.now() + waitTime <= webSocketConfig.connConfig.urlConnValidTime) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_REINITIALIZATION + waitTime + \" ms\"));\n\n reconnectConfig.exponentialTimeoutHandle = setTimeout(() => initWebSocket(), waitTime);\n reconnectConfig.exponentialBackOffTime *= 2;\n } else {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_REINITIALIZATION_TIMEOUT));\n\n getWebSocketConnConfig().catch(() => {});\n }\n };\n\n const terminateWebSocketManager = function (response) {\n resetWebSocketState();\n resetSubscriptions();\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_INITIALIZATION_FAILED, response));\n\n reconnectConfig.websocketInitFailed = true;\n closeWebSocket(LOG_MESSAGES.WEBSOCKET_TERMINATED);\n clearInterval(networkConnectivityChecker);\n invokeCallbacks(callbacks.initFailure, {\n connectWebSocketRetryCount: metrics.connectWebSocketRetryCount,\n connectionAttemptStartTime: metrics.connectionAttemptStartTime,\n reason: response\n });\n resetMetrics();\n };\n\n const createWebSocketPayload = function (key, content) {\n return JSON.stringify({\n \"topic\": key,\n \"content\": content\n });\n };\n\n const sendMessage = function (payload) {\n Utils.assertIsObject(payload, \"payload\");\n if (payload.topic === undefined || invalidSendMessageRouteKeys.has(payload.topic)) {\n sendInternalLogToServer(logger.warn(\"Cannot send message, Invalid topic: \" + payload.topic));\n\n return;\n }\n try {\n payload = JSON.stringify(payload);\n } catch (error) {\n sendInternalLogToServer(logger.warn(\"Error stringify message\", payload));\n\n return;\n }\n if (isDefaultWebSocketOpen()) {\n getDefaultWebSocket().send(payload);\n } else {\n sendInternalLogToServer(logger.warn(\"Cannot send message, web socket connection is not open\"));\n }\n };\n\n const subscribeTopics = function (topics) {\n Utils.assertNotNull(topics, 'topics');\n Utils.assertIsList(topics);\n\n topics.forEach(topic => {\n if (!topicSubscription.subscribed.has(topic)) {\n topicSubscription.pending.add(topic);\n }\n });\n // This ensure all participant-request to subscribe to topic chat are served at least once\n topicSubscriptionConfig.consecutiveNoResponseRequest = 0;\n subscribePendingTopics();\n };\n\n const validWebSocketConnConfig = function (connConfig) {\n if (Utils.isObject(connConfig) && Utils.isObject(connConfig.webSocketTransport)\n && Utils.isNonEmptyString(connConfig.webSocketTransport.url)\n && Utils.validWSUrl(connConfig.webSocketTransport.url) &&\n connConfig.webSocketTransport.transportLifeTimeInSeconds * 1000 >= MIN_WEBSOCKET_LIFETIME_MS) {\n return true;\n }\n sendInternalLogToServer(logger.error(\"Invalid WebSocket Connection Configuration\", connConfig));\n\n return false;\n };\n\n const getWebSocketConnConfig = function () {\n if (!Utils.isNetworkOnline()) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.NETWORK_OFFLINE_WARNING));\n return Promise.resolve({ webSocketConnectionFailed: true });\n }\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.debug(\"WebSocket Init had failed, ignoring this getWebSocketConnConfig request\"));\n return Promise.resolve({ webSocketConnectionFailed: true });\n }\n if (!webSocketConfig.promiseCompleted) {\n sendInternalLogToServer(logger.debug(\"There is an ongoing getWebSocketConnConfig request, this request will be ignored\"));\n return Promise.resolve({ webSocketConnectionFailed: true });\n }\n resetWebSocketState();\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_NEW_CONNECTION));\n\n metrics.connectionAttemptStartTime = metrics.connectionAttemptStartTime || Date.now();\n webSocketConfig.promiseCompleted = false;\n webSocketConfig.promiseHandle = callbacks.getWebSocketTransport();\n return webSocketConfig.promiseHandle\n .then(function (response) {\n webSocketConfig.promiseCompleted = true;\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_SUCCESS));\n\n if (!validWebSocketConnConfig(response)) {\n terminateWebSocketManager(\"Invalid WebSocket connection configuration: \" + response);\n return { webSocketConnectionFailed: true };\n }\n webSocketConfig.connConfig = response;\n // Ideally this URL validity time should be provided by server\n webSocketConfig.connConfig.urlConnValidTime = Date.now() + WEBSOCKET_URL_VALID_TIME_MS;\n return initWebSocket();\n },\n function (reason) {\n webSocketConfig.promiseCompleted = true;\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_FAILURE, reason));\n\n // If our connection fails because of network failure, we want to retry\n if (Utils.isNetworkFailure(reason)) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_RETRY, reason));\n reconnectionClient.retry();\n } else {\n // If we're not going to retry, we should terminate WSM\n terminateWebSocketManager(\"Failed to fetch webSocket connection configuration: \" + JSON.stringify(reason));\n }\n return { webSocketConnectionFailed: true };\n });\n };\n\n const initWebSocket = function () {\n if (reconnectConfig.websocketInitFailed) {\n sendInternalLogToServer(logger.info(\"web-socket initializing had failed, aborting re-init\"));\n\n return { webSocketConnectionFailed: true };\n }\n if (!Utils.isNetworkOnline()) {\n sendInternalLogToServer(logger.warn(\"System is offline aborting web-socket init\"));\n\n return { webSocketConnectionFailed: true };\n }\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_INIT));\n\n printWebSocketState(\"initWebSocket\");\n try {\n if (validWebSocketConnConfig(webSocketConfig.connConfig)) {\n let ws = null;\n if (isWebSocketOpen(webSocket.primary)) {\n sendInternalLogToServer(logger.debug(\"Primary Socket connection is already open\"));\n\n if (!isWebSocketState(webSocket.secondary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a secondary web-socket connection\"));\n reconnectionClient.numAttempts = 0;\n webSocket.secondary = getNewWebSocket();\n }\n ws = webSocket.secondary;\n } else {\n if (!isWebSocketState(webSocket.primary, WebSocket.CONNECTING)) {\n sendInternalLogToServer(logger.debug(\"Establishing a primary web-socket connection\"));\n\n webSocket.primary = getNewWebSocket();\n }\n ws = webSocket.primary;\n }\n\n // WebSocket creation is async task hence we Wait for 1sec before any potential retry\n reconnectConfig.webSocketInitCheckerTimeoutId = setTimeout(function () {\n if (!isWebSocketOpen(ws)) {\n retryWebSocketInitialization();\n }\n }, 1000);\n return { webSocketConnectionFailed: false };\n }\n } catch (error) {\n sendInternalLogToServer(logger.error(\"Error Initializing web-socket-manager\", error));\n\n terminateWebSocketManager(\"Failed to initialize new WebSocket: \" + error.message);\n return { webSocketConnectionFailed: true };\n }\n };\n\n const getNewWebSocket = function () {\n let ws = new WebSocket(webSocketConfig.connConfig.webSocketTransport.url);\n ws.addEventListener(\"open\", webSocketOnOpen);\n ws.addEventListener(\"message\", webSocketOnMessage);\n ws.addEventListener(\"error\", webSocketOnError);\n ws.addEventListener(\"close\", event => webSocketOnClose(event, ws));\n return ws;\n };\n\n const onConnectionOpen = function (cb) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_OPEN));\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionOpen.add(cb);\n return () => callbacks.connectionOpen.delete(cb);\n };\n\n const onConnectionClose = function (cb) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_CLOSE));\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionClose.add(cb);\n return () => callbacks.connectionClose.delete(cb);\n };\n\n const onConnectionGain = function (cb) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_GAIN));\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionGain.add(cb);\n if (isDefaultWebSocketOpen()) {\n cb();\n }\n return () => callbacks.connectionGain.delete(cb);\n };\n\n const onConnectionLost = function (cb) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_CONNECTION_LOST));\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.connectionLost.add(cb);\n if (reconnectConfig.connState === CONN_STATE.DISCONNECTED) {\n cb();\n }\n return () => callbacks.connectionLost.delete(cb);\n };\n\n const onInitFailure = function (cb) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_INIT_FAILURE));\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.initFailure.add(cb);\n if (reconnectConfig.websocketInitFailed) {\n cb();\n }\n return () => callbacks.initFailure.delete(cb);\n };\n\n const init = function (transportHandle) {\n Utils.assertTrue(Utils.isFunction(transportHandle), 'transportHandle must be a function');\n if (callbacks.getWebSocketTransport !== null) {\n sendInternalLogToServer(logger.warn(\"Web Socket Manager was already initialized\"));\n return;\n }\n callbacks.getWebSocketTransport = transportHandle;\n\n return getWebSocketConnConfig();\n };\n\n const onSubscriptionUpdate = function (cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionUpdate.add(cb);\n return () => callbacks.subscriptionUpdate.delete(cb);\n };\n\n const onSubscriptionFailure = function (cb) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.WEBSOCKET_SUBSCRIPTION_FAILURE));\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.subscriptionFailure.add(cb);\n return () => callbacks.subscriptionFailure.delete(cb);\n };\n\n const onMessage = function (topicName, cb) {\n Utils.assertNotNull(topicName, 'topicName');\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n if (callbacks.topic.has(topicName)) {\n callbacks.topic.get(topicName).add(cb);\n } else {\n callbacks.topic.set(topicName, new Set([cb]));\n }\n return () => callbacks.topic.get(topicName).delete(cb);\n };\n\n const onAllMessage = function (cb) {\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.allMessage.add(cb);\n return () => callbacks.allMessage.delete(cb);\n };\n\n const sendInternalLogToServer = function (logEntry) {\n if (logEntry && typeof logEntry.sendInternalLogToServer === \"function\")\n logEntry.sendInternalLogToServer();\n\n return logEntry;\n };\n\n const onDeepHeartbeatSuccess = function (cb) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.DEEP_HEARTBEAT_SUCCESS));\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.deepHeartbeatSuccess.add(cb);\n return () => callbacks.deepHeartbeatSuccess.delete(cb);\n };\n\n const onDeepHeartbeatFailure = function (cb) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.DEEP_HEARTBEAT_FAILURE));\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.deepHeartbeatFailure.add(cb);\n return () => callbacks.deepHeartbeatFailure.delete(cb);\n };\n\n const onTopicFailure = function (cb) {\n sendInternalLogToServer(logger.advancedLog(LOG_MESSAGES.TOPIC_FAILURE));\n Utils.assertTrue(Utils.isFunction(cb), 'cb must be a function');\n callbacks.topicFailure.add(cb);\n return () => callbacks.topicFailure.delete(cb);\n };\n\n this.init = init;\n this.onInitFailure = onInitFailure;\n this.onConnectionOpen = onConnectionOpen;\n this.onConnectionClose = onConnectionClose;\n this.onConnectionGain = onConnectionGain;\n this.onConnectionLost = onConnectionLost;\n this.onSubscriptionUpdate = onSubscriptionUpdate;\n this.onSubscriptionFailure = onSubscriptionFailure;\n this.onMessage = onMessage;\n this.onAllMessage = onAllMessage;\n this.subscribeTopics = subscribeTopics;\n this.sendMessage = sendMessage;\n this.onDeepHeartbeatSuccess = onDeepHeartbeatSuccess;\n this.onDeepHeartbeatFailure = onDeepHeartbeatFailure;\n this.onTopicFailure = onTopicFailure;\n\n this.closeWebSocket = function () {\n resetWebSocketState();\n resetSubscriptions();\n reconnectConfig.reconnectWebSocket = false;\n clearInterval(networkConnectivityChecker);\n closeWebSocket(\"User request to close WebSocket\");\n };\n\n this.terminateWebSocketManager = terminateWebSocketManager;\n};\n\nconst WebSocketManagerConstructor = (logMetaData) => {\n if (!logManagerInstance) {\n logManagerInstance = new LogManagerImpl(logMetaData);\n }\n if (!logManagerInstance.hasLogMetaData()) {\n logManagerInstance.setLogMetaData(logMetaData);\n }\n return new WebSocketManager();\n};\n\nconst setGlobalConfig = config => {\n const loggerConfig = config && config.loggerConfig;\n if (!logManagerInstance) {\n logManagerInstance = new LogManagerImpl();\n }\n logManagerInstance.updateLoggerConfig(loggerConfig);\n\n const webSocketManagerConfig = config && config.webSocketManagerConfig;\n const customIsNetworkOnline = webSocketManagerConfig && webSocketManagerConfig.isNetworkOnline;\n if (customIsNetworkOnline && typeof customIsNetworkOnline === \"function\") {\n Utils.isNetworkOnline = customIsNetworkOnline;\n }\n};\n\nconst WebSocketManagerObject = {\n create: WebSocketManagerConstructor,\n setGlobalConfig: setGlobalConfig,\n LogLevel: LogLevel,\n Logger: Logger,\n};\n\nexport { WebSocketManagerObject };\n","/*eslint no-unused-vars: \"off\"*/\nimport { WebSocketManagerObject } from \"./webSocketManager\";\n\nglobal.connect = global.connect || {};\nconnect.WebSocketManager = WebSocketManagerObject;\n\nexport const WebSocketManager = WebSocketManagerObject;\n\nexport default WebSocketManager;"],"names":["re","not_string","not_bool","not_type","not_primitive","number","numeric_arg","json","not_json","text","modulo","placeholder","key","key_access","index_access","sign","sprintf","parse_tree","argv","arg","i","k","ph","pad","pad_character","pad_length","is_positive","cursor","tree_length","length","output","keys","undefined","Error","param_no","test","type","Function","isNaN","TypeError","parseInt","toString","String","fromCharCode","JSON","stringify","width","precision","parseFloat","toExponential","toFixed","Number","toPrecision","substring","Object","prototype","call","slice","toLowerCase","valueOf","toUpperCase","replace","pad_char","charAt","repeat","align","sprintf_format","fmt","sprintf_cache","match","_fmt","arg_names","exec","push","SyntaxError","field_list","replacement_field","field_match","sprintf_parse","arguments","vsprintf","apply","concat","create","exports","window","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","module","__webpack_modules__","_typeof","obj","Symbol","iterator","constructor","LOG_MESSAGES","ROUTE_KEY","CONN_STATE","Utils","premise","message","value","name","assertTrue","Array","isArray","wsRegex","RegExp","localWsRegex","validWSUrl","wsUrl","getSubscriptionResponse","routeKey","isSuccess","topicList","topic","content","status","topics","assertIsObject","isObject","addJitter","base","maxJitter","Math","min","random","floor","isNetworkOnline","navigator","onLine","isNetworkFailure","reason","_debug","_setPrototypeOf","o","p","setPrototypeOf","bind","__proto__","_getPrototypeOf","getPrototypeOf","_defineProperty","defineProperty","enumerable","configurable","writable","_classCallCheck","instance","Constructor","_defineProperties","target","props","descriptor","_createClass","protoProps","staticProps","self","ReferenceError","Logger","data","DEFAULT_PREFIX","LogLevel","DEBUG","INFO","WARN","ERROR","ADVANCED_LOG","LogManagerImpl","logMetaData","this","updateLoggerConfig","level","logStatement","hasClientLogger","log1","removeCircularReference","log2","logStringValue","getLogLevelByValue","_clientLogger","debug","info","warn","error","_advancedLogWriter","_level","options","prefix","setLogMetaData","LoggerWrapperImpl","inputConfig","config","advancedLogWriter","customizedLogger","useClientLogger","logger","selectLogger","_logsDestination","useDefaultLogger","createConsoleLogger","LoggerWrapper","subClass","superClass","logManagerInstance","excludeTimestamp","logManager","args","_log","isLevelEnabled","writeToClientLogger","_shouldLog","_convertToSingleStatement","_writeToClientLogger","date","Date","now","toISOString","index","_convertToString","isString","isFunction","toStringResult","startsWith","console","seen","WeakSet","has","add","RetryProvider","executor","defaultRetry","numAttempts","hasActiveReconnection","setTimeout","_execute","_getDelay","calculatedDelay","pow","WebSocketManager","getLogger","online","webSocket","primary","secondary","reconnectConfig","reconnectWebSocket","websocketInitFailed","exponentialBackOffTime","exponentialTimeoutHandle","lifeTimeTimeoutHandle","webSocketInitCheckerTimeoutId","connState","metrics","connectWebSocketRetryCount","connectionAttemptStartTime","noOpenConnectionsTimestamp","heartbeatConfig","pendingResponse","intervalHandle","deepHeartbeatConfig","callbacks","initFailure","Set","getWebSocketTransport","subscriptionUpdate","subscriptionFailure","Map","allMessage","connectionGain","connectionLost","connectionOpen","connectionClose","deepHeartbeatSuccess","deepHeartbeatFailure","topicFailure","webSocketConfig","connConfig","promiseHandle","promiseCompleted","topicSubscription","subscribed","pending","subscriptionHistory","topicSubscriptionConfig","responseCheckIntervalId","requestCompleted","reSubscribeIntervalId","consecutiveFailedSubscribeAttempts","consecutiveNoResponseRequest","reconnectionClient","getWebSocketConnConfig","invalidSendMessageRouteKeys","networkConnectivityChecker","setInterval","sendInternalLogToServer","advancedLog","ws","getDefaultWebSocket","isWebSocketState","WebSocket","CLOSING","CLOSED","invokeCallbacks","response","forEach","callback","getWebSocketStates","readyState","CONNECTING","OPEN","printWebSocketState","event","webSocketStateCode","isWebSocketOpen","isWebSocketClosed","isDefaultWebSocketOpen","sendHeartBeat","timestamp","clearInterval","send","createWebSocketPayload","resetWebSocketState","clearTimeout","resetSubscriptions","resetMetrics","webSocketOnOpen","connected","connectionEstablishedTime","timeToConnect","timeWithoutConnection","openTimestamp","size","closeSpecificWebSocket","clear","subscribePendingTopics","webSocketLifetimeTimeout","webSocketTransport","transportLifeTimeInSeconds","webSocketOnError","getIsConnected","retry","webSocketOnMessage","parse","topicName","statusCode","statusContent","get","errorMessage","connectionId","requestId","from","close","closeWebSocket","terminateWebSocketManager","validWebSocketConnConfig","isNonEmptyString","url","Promise","resolve","webSocketConnectionFailed","then","urlConnValidTime","initWebSocket","getNewWebSocket","waitTime","retryWebSocketInitialization","addEventListener","webSocketCloseDetails","closeTimestamp","connectionDuration","code","wasClean","closeEventDetails","connectionDetails","webSocketOnClose","logEntry","init","transportHandle","onInitFailure","cb","onConnectionOpen","onConnectionClose","onConnectionGain","onConnectionLost","onSubscriptionUpdate","onSubscriptionFailure","onMessage","assertNotNull","set","onAllMessage","subscribeTopics","assertIsList","sendMessage","payload","onDeepHeartbeatSuccess","onDeepHeartbeatFailure","onTopicFailure","WebSocketManagerObject","hasLogMetaData","setGlobalConfig","loggerConfig","webSocketManagerConfig","customIsNetworkOnline","global","connect"],"sourceRoot":""} \ No newline at end of file