text: 'use strict';
  
  function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  
  var coreHttp = _interopDefault(require('@azure/core-http'));
  
  var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  
  function unwrapExports (x) {
  	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  }
  
  function createCommonjsModule(fn, module) {
  	return module = { exports: {} }, fn(module, module.exports), module.exports;
  }
  
  var tsregistrar = createCommonjsModule(function (module, exports) {
  !function(t,e){module.exports=e();}(commonjsGlobal,function(){return function(t){function e(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var r={};return e.m=t,e.c=r,e.i=function(t){return t},e.d=function(t,r,n){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:n});},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=1)}([function(t,e,r){function n(t){try{return JSON.stringify(t)}catch(e){return "Unable to serialize object of type "+typeof t}}Object.defineProperty(e,"__esModule",{value:!0}),e.toJson=n;var o=function(){function t(){this.start=Date.now();}return Object.defineProperty(t.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"startTime",{get:function(){return this.start},enumerable:!0,configurable:!0}),t.prototype.reset=function(){this.start=Date.now();},t}();e.Timespan=o;},function(t,e,r){function n(t,e,r){return new f(t,e,r)}var o=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);};return function(e,r){function n(){this.constructor=e;}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n);}}(),i=this&&this.__awaiter||function(t,e,r,n){return new(r||(r=Promise))(function(o,i){function s(t){try{c(n.next(t));}catch(t){i(t);}}function a(t){try{c(n.throw(t));}catch(t){i(t);}}function c(t){t.done?o(t.value):new r(function(e){e(t.value);}).then(s,a);}c((n=n.apply(t,e||[])).next());})},s=this&&this.__generator||function(t,e){function r(t){return function(e){return n([t,e])}}function n(r){if(o)throw new TypeError("Generator is already executing.");for(;c;)try{if(o=1,i&&(s=2&r[0]?i.return:r[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,r[1])).done)return s;switch(i=0,s&&(r=[2&r[0],s.value]),r[0]){case 0:case 1:s=r;break;case 4:return c.label++,{value:r[1],done:!1};case 5:c.label++,i=r[1],r=[0];continue;case 7:r=c.ops.pop(),c.trys.pop();continue;default:if(s=c.trys,!(s=s.length>0&&s[s.length-1])&&(6===r[0]||2===r[0])){c=0;continue}if(3===r[0]&&(!s||r[1]>s[0]&&r[1]<s[3])){c.label=r[1];break}if(6===r[0]&&c.label<s[1]){c.label=s[1],s=r;break}if(s&&c.label<s[2]){c.label=s[2],c.ops.push(r);break}s[2]&&c.ops.pop(),c.trys.pop();continue}r=e.call(t,c);}catch(t){r=[6,t],i=0;}finally{o=s=0;}if(5&r[0])throw r[1];return {value:r[0]?r[1]:void 0,done:!0}}var o,i,s,a,c={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return a={next:r(0),throw:r(1),return:r(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a};Object.defineProperty(e,"__esModule",{value:!0});var a=r(0),c=function(t){function e(e){var r=t.call(this,e)||this;return r.name="CancelationError",r}return o(e,t),e}(Error),u=function(){function t(e,r,n){this.logger=e,this.maxBackoffInMs=r,this.initialDelay=n,this.backoffCount=0,this.id=++t.idCounter;}return t.prototype.delay=function(t){var e=this;if(void 0!==this.timerHandle)throw new Error("Retry sequence logical failure");if(-1===this.backoffCount)return new Promise(function(t,e){e(new c("Cancelled"));});var r=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info("[RegistrarClient] Backing off "+t+" for "+r+" milliseconds with ID "+this.id),new Promise(function(n,o){e.cancelFunc=o,e.timerHandle=setTimeout(function(){e.logger.info("[RegistrarClient] Back off for "+t+" with ID "+e.id+" complete"),e.timerHandle=void 0,n();},r);})},t.prototype.cancel=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off"),clearTimeout(this.timerHandle),void 0!==this.cancelFunc&&this.cancelFunc(new c("Cancelled"))),this.backoffCount=-1;},t.prototype.calculateNextBackoffMs=function(){var t=1+.4*(Math.random()-.5),e=this.initialDelay*Math.pow(2,this.backoffCount)*t;return e=Math.round(e),Math.min(this.maxBackoffInMs,e)},t.idCounter=0,t}(),f=function(){function t(t,e,r){this.logger=t,this.skypeTokenProvider=e,this.options=r,this.backoffs={};}return t.prototype.setTelemetryLogger=function(t){this.eventLogger=t;},t.prototype.register=function(t,e){return i(this,void 0,void 0,function(){return s(this,function(r){switch(r.label){case 0:return [4,this.performRegistration(t,e,"pr_set_registration")];case 1:return r.sent(),this.cachedRegistrationParams=[t,e],[2]}})})},t.prototype.unregister=function(){return i(this,void 0,void 0,function(){var t;return s(this,function(e){switch(e.label){case 0:return this.logger.info("[RegistrarClient] sending unregister request"),t=new Request(this.options.registrarUrl+"/"+this.options.registrationId,{method:"DELETE",mode:"cors",headers:new Headers({accept:"application/json, text/javascript"})}),[4,this.callRegistrar(t,"pr_delete_registration")];case 1:return e.sent(),[2]}})})},t.prototype.cancelPendingRequests=function(){var t=this;Object.keys(this.backoffs).forEach(function(e){t.backoffs[e].cancel();}),this.backoffs={};},t.prototype.resendRegistration=function(){return i(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:if(!this.cachedRegistrationParams)throw new Error("Re-registration failed because there is no registration parameters cached");return [4,this.performRegistration(this.cachedRegistrationParams[0],this.cachedRegistrationParams[1],"pr_resend_registration")];case 1:return t.sent(),[2]}})})},t.prototype.performRegistration=function(t,e,r){return i(this,void 0,void 0,function(){var n,o;return s(this,function(i){switch(i.label){case 0:return this.logger.info("[RegistrarClient] Sending register request"),n={clientDescription:t,registrationId:this.options.registrationId,nodeId:"",transports:e},o=new Request(this.options.registrarUrl,{method:"POST",mode:"cors",headers:new Headers({"content-type":"application/json",accept:"application/json, text/javascript"}),body:a.toJson(n)}),[4,this.callRegistrar(o,r)];case 1:return i.sent(),[2]}})})},t.prototype.startBackoff=function(){var t=new u(this.logger,this.options.maxRetryDelayMs,this.options.initialRetryDelayMs);return this.backoffs[t.id]=t,t},t.prototype.stopBackoff=function(t){t.cancel(),delete this.backoffs[t.id];},t.prototype.getSkypeToken=function(){return i(this,void 0,void 0,function(){var t,e,r,n;return s(this,function(o){switch(o.label){case 0:t=this.startBackoff(),o.label=1;case 1:return o.trys.push([1,3,,8]),this.logger.info("[RegistrarClient] Asking for a new skypetoken"),[4,this.skypeTokenProvider(!0)];case 2:return e=o.sent(),this.stopBackoff(t),[2,e];case 3:r=o.sent(),o.label=4;case 4:return o.trys.push([4,6,,7]),[4,t.delay("Fetching a new skypetoken")];case 5:return o.sent(),[3,8];case 6:throw n=o.sent(),this.stopBackoff(t),n;case 7:return [3,8];case 8:return [3,1];case 9:return [2]}})})},t.prototype.callRegistrar=function(t,e){return i(this,void 0,void 0,function(){var r,n,o,i,c,u,f,l,h;return s(this,function(s){switch(s.label){case 0:return r=this.startBackoff(),[4,this.skypeTokenProvider(!1)];case 1:n=s.sent(),this.setSkypeTokenHeader(t,n),o=new a.Timespan,s.label=2;case 2:i=void 0,s.label=3;case 3:return s.trys.push([3,8,13,14]),c=t.clone(),[4,this.fetchWithTimeout(c)];case 4:return i=s.sent(),401!==i.status?[3,6]:(u=this.setSkypeTokenHeader,f=[t],[4,this.getSkypeToken()]);case 5:return u.apply(this,f.concat([s.sent()])),[3,15];case 6:if(i.status>=500&&i.status<600)throw new Error("Fetch for '"+t.url+"' failed with "+i.status+" "+i.statusText);s.label=7;case 7:return [3,14];case 8:l=s.sent(),this.logger.error("[RegistrarClient] Request failed with "+l),s.label=9;case 9:return s.trys.push([9,11,,12]),[4,r.delay("Registrar call retry")];case 10:return s.sent(),[3,15];case 11:throw h=s.sent(),this.logger.error("[RegistrarClient] Request cancelled"),this.stopBackoff(r),h;case 12:return [3,14];case 13:return this.sendTelemetryEvent(e,t,i,o),[7];case 14:if(this.stopBackoff(r),i.ok)return [2,i];throw new Error("Fetch for '"+t.url+"' failed with "+i.status+" "+i.statusText);case 15:return [3,2];case 16:return [2]}})})},t.prototype.setSkypeTokenHeader=function(t,e){t.headers.set("X-Skypetoken",e);},t.prototype.fetchWithTimeout=function(t){var e=this;return new Promise(function(r,n){fetch(t).then(r).catch(n),0!==e.options.requestTimeoutMs&&setTimeout(n,e.options.requestTimeoutMs,new Error("Fetch for '"+t.url+"' timed out"));})},t.prototype.sendTelemetryEvent=function(t,e,r,n){if(void 0!==this.eventLogger){var o={name:t,properties:{url:{value:e.url},result_code:{value:void 0!==r?r.status:0},begin_timestamp:{value:n.startTime},elapsed:{value:n.duration}}};this.eventLogger.logEvent(o);}},t}();e.RegistrarClient=f,e.createRegistrarClient=n;}])});
  
  });
  
  unwrapExports(tsregistrar);
  
  var tstrouter = createCommonjsModule(function (module, exports) {
  !function(t,e){module.exports=e(tsregistrar);}(commonjsGlobal,function(__WEBPACK_EXTERNAL_MODULE_20__){return function(t){function e(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return t[o].call(r.exports,r,r.exports,e),r.l=!0,r.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,o){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:o});},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=19)}([function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var o=function(){function t(t,e){this.name=t,this.logger=e;}return t.prototype.debug=function(t){this.logger.debug("["+this.name+"] "+t);},t.prototype.info=function(t){this.logger.info("["+this.name+"] "+t);},t.prototype.warn=function(t){this.logger.warn("["+this.name+"] "+t);},t.prototype.error=function(t){this.logger.error("["+this.name+"] "+t);},t}();e.Logger=o;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var o=function(){function t(){}return t}();e.HttpHeaders=o;!function(t){t[t.Unknown=0]="Unknown",t[t.Connected=2]="Connected",t[t.Disconnected=3]="Disconnected",t[t.Switching=9]="Switching";}(e.TrouterState||(e.TrouterState={}));!function(t){t[t.Unknown=0]="Unknown",t[t.Active=1]="Active",t[t.Inactive=2]="Inactive";}(e.UserActivityState||(e.UserActivityState={}));},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0}),e.constants={TROUTER_INIT:"trouterinit",TROUTER_READY_EVENT:"trouterReadyEvent",TROUTER_READY_TIMEOUT:"trouterReadyTimeout",TROUTER_TOKEN_REQUEST:"trouterTokenRequest",TROUTER_TOKEN_GET_SUCCEEDED:"trouterTokenGetSucceeded",TROUTER_TOKEN_GET_FAILED:"trouterTokenGetFailed",TROUTER_RECONNECTING:"trouterReconnecting",RENEWAL:"renewal",NEW_CONNECTION:"newConnection",ENDPOINT_REGISTRATION_FAILED:"endpointRegistrationFailed"},e.CLIENT_VERSION="2020.37.01.1",e.HANDLED_MESSAGE_ACK=200,e.UNHANDLED_MESSAGE_ACK=404,e.FAILED_MESSAGE_ACK=500;},function(t,e,n){function o(t){try{return JSON.stringify(t)}catch(e){return "Unable to serialize object of type "+typeof t}}function r(t){var e=Math.round((new Date).getTime()/1e3);return void 0!==t&&t>e?t-e:0}function i(t){return Math.round((new Date).getTime()/1e3)+t}Object.defineProperty(e,"__esModule",{value:!0}),e.toJson=o,e.calculateTtlInSec=r,e.calculateExpireTsInSec=i;var s=function(){function t(){this.start=Date.now();}return Object.defineProperty(t.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"startTime",{get:function(){return this.start},enumerable:!0,configurable:!0}),t.prototype.reset=function(){this.start=Date.now();},t}();e.Timespan=s;},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this");}catch(t){"object"==typeof window&&(n=window);}t.exports=n;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var o=n(3),r=function(){function t(t,e,n,o,r,i,s){this.connectionId=t,this.connectedClientId=e,this.domId=n,this.unsecureUrl=o,this.url=r,this.c2cUrlBase=i,this.expirationTsSec=s;}return t.prototype.getRemainingTtlInSec=function(){return o.calculateTtlInSec(this.expirationTsSec)},t}();e.ServerState=r;!function(t){t[t.Unknown=0]="Unknown",t[t.Modified=1]="Modified",t[t.Snapshot=2]="Snapshot",t[t.Connected=3]="Connected";}(e.UserActivityEventReason||(e.UserActivityEventReason={}));},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var o=n(2),r=function(){function t(t){this.logger=t,this.messageHandlers=[];}return t.prototype.register=function(t){if(this.messageHandlers.some(function(e){return e===t}))throw new Error("Registering the same handler twice is not allowed");this.messageHandlers.push(t);},t.prototype.clear=function(){this.logger.debug("Clearing message handlers"),this.messageHandlers=[];},t.prototype.active=function(){return this.messageHandlers.length>0},t.prototype.handleMessage=function(t){for(var e={resultCode:o.UNHANDLED_MESSAGE_ACK,isHandled:!1},n=0,r=this.messageHandlers;n<r.length;n++){var i=r[n],s=this.safeExecuteHandle(i,t);if(void 0!==s&&(void 0===s.isHandled||s.isHandled))return void 0===s.resultCode&&(s.resultCode=o.HANDLED_MESSAGE_ACK),s}return e},t.prototype.safeExecuteHandle=function(t,e){try{return t.handleMessage(e)}catch(t){return void this.logger.warn("A trouter message handler is throwing exceptions. exception: "+t)}},t}();e.MessageHandlerRegistry=r;},function(t,e,n){function o(t){var e,n=this;return function(o){return r(n,void 0,void 0,function(){return i(this,function(n){return o&&(e=void 0),[2,new Promise(function(n,r){t(o).then(function(t){e=t,n(t);}).catch(function(t){void 0!==e&&e.length>0&&n(e),r(t);});})]})})}}var r=this&&this.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(r,i){function s(t){try{a(o.next(t));}catch(t){i(t);}}function c(t){try{a(o.throw(t));}catch(t){i(t);}}function a(t){t.done?r(t.value):new n(function(e){e(t.value);}).then(s,c);}a((o=o.apply(t,e||[])).next());})},i=this&&this.__generator||function(t,e){function n(t){return function(e){return o([t,e])}}function o(n){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,i&&(s=2&n[0]?i.return:n[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,n[1])).done)return s;switch(i=0,s&&(n=[2&n[0],s.value]),n[0]){case 0:case 1:s=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,i=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(s=a.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){a.label=n[1];break}if(6===n[0]&&a.label<s[1]){a.label=s[1],s=n;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(n);break}s[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a);}catch(t){n=[6,t],i=0;}finally{r=s=0;}if(5&n[0])throw n[1];return {value:n[0]?n[1]:void 0,done:!0}}var r,i,s,c,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return c={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c};Object.defineProperty(e,"__esModule",{value:!0}),e.addCacheAsBackupTo=o;},function(t,e,n){var o=this&&this.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(r,i){function s(t){try{a(o.next(t));}catch(t){i(t);}}function c(t){try{a(o.throw(t));}catch(t){i(t);}}function a(t){t.done?r(t.value):new n(function(e){e(t.value);}).then(s,c);}a((o=o.apply(t,e||[])).next());})},r=this&&this.__generator||function(t,e){function n(t){return function(e){return o([t,e])}}function o(n){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,i&&(s=2&n[0]?i.return:n[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,n[1])).done)return s;switch(i=0,s&&(n=[2&n[0],s.value]),n[0]){case 0:case 1:s=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,i=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(s=a.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){a.label=n[1];break}if(6===n[0]&&a.label<s[1]){a.label=s[1],s=n;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(n);break}s[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a);}catch(t){n=[6,t],i=0;}finally{r=s=0;}if(5&n[0])throw n[1];return {value:n[0]?n[1]:void 0,done:!0}}var r,i,s,c,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return c={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c};Object.defineProperty(e,"__esModule",{value:!0});var i=n(3),s=n(1),c=n(0),a=n(16),u=n(18),h=function(){function t(t,e,n,o){this.logFunc=t,this.options=e,this.tokenProvider=n,this.listener=o,this.logger=new c.Logger("Manager",t),this.logger.info("Created TrouterManager with options "+i.toJson(this.options)),this.fsm=new u.TrouterManagerFsm(t,this),this.baseEndpointUrl="",this.processedMessageLoss={};}return t.prototype.start=function(){this.fsm.start();},t.prototype.stop=function(){this.fsm.stop();},t.prototype.configure=function(t){this.options=t,void 0!==this.firstConnection&&this.firstConnection.configure(t),void 0!==this.secondConnection&&this.secondConnection.configure(t),this.logger.info("Reconfigured TrouterManager with options "+i.toJson(this.options));},t.prototype.checkConnection=function(t){void 0!==this.firstConnection&&this.firstConnection.checkConnection(t),void 0!==this.secondConnection&&this.secondConnection.checkConnection(t);},t.prototype.resendRegistration=function(){return o(this,void 0,void 0,function(){return r(this,function(t){return void 0!==this.secondConnection?(this.logger.info("Resending registration on the second/new connection"),[2,this.secondConnection.resendRegistration()]):void 0!==this.firstConnection?(this.logger.info("Resending registration on the first/current connection"),[2,this.firstConnection.resendRegistration()]):(this.logger.info("No connection to resend registration on, will be done upon (re)connect"),[2])})})},t.prototype.getServerState=function(){if(void 0!==this.firstConnection)return this.firstConnection.getServerState()},t.prototype.getState=function(){return this.fsm.getState()},t.prototype.startFirstConnection=function(){this.firstConnection=new a.TrouterConnection(this.logFunc,this.options,this,this.tokenProvider),this.firstConnection.start();},t.prototype.startSecondConnection=function(){var t=void 0!==this.firstConnection?this.firstConnection.getUserActivityState():s.UserActivityState.Unknown;this.secondConnection=new a.TrouterConnection(this.logFunc,this.options,this,this.tokenProvider,t),this.secondConnection.start();},t.prototype.stopFirstConnection=function(t){void 0!==this.firstConnection&&(this.firstConnection.stop(t),this.storedFirstConnection=this.firstConnection,this.firstConnection=void 0);},t.prototype.stopSecondConnection=function(t){void 0!==this.secondConnection&&(this.secondConnection.stop(t),this.secondConnection=void 0);},t.prototype.stopSecondConnectionDelayed=function(){if(void 0!==this.secondConnection){var t=this.secondConnection;this.secondConnection=void 0,this.logger.info("Closing an inactive connection in "+Math.round(this.options.lingeringConnectionDelayMs/1e3)+"s"),setTimeout(function(){t.stop(!0);},this.options.lingeringConnectionDelayMs);}},t.prototype.switchConnections=function(){var t=this.firstConnection;this.firstConnection=this.secondConnection,this.secondConnection=t;},t.prototype.doesSecondConnectionExist=function(){return void 0!==this.secondConnection},t.prototype.dispatchConnected=function(){if(void 0!==this.firstConnection){var t=this.firstConnection.getServerState(),e="/"===t.url.slice(-1)?t.url.slice(0,-1):t.url,n={baseEndpointUrl:e,newEndpointUrl:e!==this.baseEndpointUrl,c2cUrlBase:t.c2cUrlBase,clientId:t.connectedClientId,connectionId:t.connectionId,connectionTtlSec:t.getRemainingTtlInSec()};this.baseEndpointUrl=e,this.listener.onTrouterConnected(t.url,n);}},t.prototype.dispatchReconnecting=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected();},t.prototype.dispatchStopped=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected();},t.prototype.onDownstreamRequest=function(t,e,n){var o={id:e.id,method:e.method,path:"/"+e.shortUrl,body:e.body,headers:e.headers},r={id:e.id,status:0,headers:{},body:"",send:function(){return r.status<=100||r.status>=999?3:(n.writeHead(r.status,r.headers),n.end(r.body))}};this.listener.onTrouterRequest(o,r);},t.prototype.onConnected=function(t){this.fsm.onConnected(t===this.firstConnection);},t.prototype.onRegistered=function(t){this.fsm.onRegistered(t===this.firstConnection);},t.prototype.onReconnecting=function(t){this.fsm.onReconnecting(t===this.firstConnection);},t.prototype.onReconnectIsRequired=function(t){this.fsm.onReconnectionRequired(t===this.firstConnection);},t.prototype.onDisconnected=function(t){this.fsm.onDisconnected(t===this.storedFirstConnection);},t.prototype.setUserActivityState=function(t){if(void 0!==this.secondConnection)return this.logger.info("Setting user activity state "+s.UserActivityState[t]+" on the second/new connection"),void this.secondConnection.setUserActivityState(t);if(void 0!==this.firstConnection)return this.logger.info("Setting user activity state "+s.UserActivityState[t]+" on the first/current connection"),void this.firstConnection.setUserActivityState(t);throw new Error("setUserActivityState called too early")},t.prototype.onTrouterMessageLost=function(t){var e=this;if(this.listener.onTrouterMessageLoss)if(t&&t.length){var n=t.filter(function(t){return void 0!==e.processedMessageLoss[t.tag+"-"+t.etag]});if(n.length&&(this.logger.warn("onTrouterMessageLoss - removing duplicates and sending event to server"),this.sendProcessedDroppedIndicators(n),t=t.filter(function(t){return void 0===e.processedMessageLoss[t.tag+"-"+t.etag]}),!t.length))return void this.logger.warn("onTrouterMessageLoss - All the data are duplicated");var o=this.listener.onTrouterMessageLoss(t.map(function(t){return t.tag}));if(!o)return void this.logger.warn("onTrouterMessageLoss - flow tags have not been processed by listeners");t.forEach(function(t){e.processedMessageLoss[t.tag+"-"+t.etag]="";}),this.sendProcessedDroppedIndicators(t);}else this.logger.warn("onTrouterMessageLoss - no flow tags have been provided");},t.prototype.sendProcessedDroppedIndicators=function(t){return void 0!==this.firstConnection?void this.firstConnection.sendProcessedDroppedIndicators(t):void 0!==this.secondConnection?void this.secondConnection.sendProcessedDroppedIndicators(t):void 0},t}();e.TrouterManager=h;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var o=function(){function t(t){this.logger=t;}return t.prototype.getPromise=function(){var t=this;return void 0!==this.url?(this.logger.debug("[TrouterUrlPromise] returning previously resolved url: "+this.url),Promise.resolve(this.url)):(void 0===this.pendingPromise?(this.logger.debug("[TrouterUrlPromise] creating and returning promise"),this.pendingPromise=new Promise(function(e,n){t.pendingPromiseResolveRef=e,t.pendingPromiseRejectRef=n;})):this.logger.debug("[TrouterUrlPromise] returning existing promise"),this.pendingPromise)},t.prototype.resolveUrl=function(t){this.url=t,this.logger.debug("[TrouterUrlPromise] got url: "+this.url);var e=this.pendingPromiseResolveRef;this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,void 0!==e&&(this.logger.debug("[TrouterUrlPromise] resolving promise"),e(t));},t.prototype.rejectUrl=function(t){this.logger.debug("[TrouterUrlPromise] aborting");var e=this.pendingPromiseRejectRef;this.url=void 0,this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,void 0!==e&&(this.logger.debug("[TrouterUrlPromise] rejecting promise"),e(t));},t.prototype.resetUrl=function(){this.logger.debug("[TrouterUrlPromise] resetting url"),this.url=void 0;},t}();e.TrouterUrlPromise=o;},function(module,exports,__webpack_require__){(function(global,module){!function(t,e){var n=t;n.version="0.9.6",n.protocol=1,n.transports=[],n.j=[],n.sockets={},n.connect=function(t,o){var r,i,s=n.util.parseUri(t);e&&e.location&&(s.protocol=s.protocol||e.location.protocol.slice(0,-1),s.host=s.host||(e.document?e.document.domain:e.location.hostname),s.port=s.port||e.location.port),r=n.util.uniqueUri(s);var c={host:s.host,secure:"https"==s.protocol,port:s.port||("https"==s.protocol?443:80),query:s.query||""};return n.util.merge(c,o),!c["force new connection"]&&n.sockets[r]||(i=new n.Socket(c)),!c["force new connection"]&&i&&(n.sockets[r]=i),i=i||n.sockets[r],i.of(s.path.length>1?s.path:"")};}(module.exports,void 0===global?window:global);var io=module.exports;!function(t,e){var n=t.util={},o=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];n.parseUri=function(t){for(var e=o.exec(t||""),n={},i=14;i--;)n[r[i]]=e[i]||"";return n},n.uniqueUri=function(t){var n=t.protocol,o=t.host,r=t.port;return "document"in e?(o=o||document.domain,r=r||("https"==n&&"https:"!==document.location.protocol?443:document.location.port)):(o=o||"localhost",r||"https"!=n||(r=443)),(n||"http")+"://"+o+":"+(r||80)},n.query=function(t,e){var o=n.chunkQuery(t||""),r=[];n.merge(o,n.chunkQuery(e||""));for(var i in o)o.hasOwnProperty(i)&&r.push(i+"="+o[i]);return r.length?"?"+r.join("&"):""},n.chunkQuery=function(t){for(var e,n={},o=t.split("&"),r=0,i=o.length;r<i;++r)e=o[r].split("="),e[0]&&(n[e[0]]=e[1]);return n};var i=!1;n.load=function(t){if("document"in e&&"complete"===document.readyState||i)return t();n.on(e,"load",t,!1);},n.on=function(t,e,n,o){t.attachEvent?t.attachEvent("on"+e,n):t.addEventListener&&t.addEventListener(e,n,o);},n.request=function(t){if(t&&"undefined"!=typeof XDomainRequest)return new XDomainRequest;if("undefined"!=typeof XMLHttpRequest&&(!t||n.ua.hasCORS))return new XMLHttpRequest;if(!t)try{return new(window[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}return null},"undefined"!=typeof window&&n.load(function(){i=!0;}),n.defer=function(t){if(!n.ua.webkit||"undefined"!=typeof importScripts)return t();n.load(function(){setTimeout(t,100);});},n.merge=function(t,e,o,r){var i,s=r||[],c=void 0===o?2:o;for(i in e)e.hasOwnProperty(i)&&n.indexOf(s,i)<0&&("object"==typeof t[i]&&c?n.merge(t[i],e[i],c-1,s):(t[i]=e[i],s.push(e[i])));return t},n.mixin=function(t,e){n.merge(t.prototype,e.prototype);},n.inherit=function(t,e){function n(){}n.prototype=e.prototype,t.prototype=new n;},n.isArray=Array.isArray||function(t){return "[object Array]"===Object.prototype.toString.call(t)},n.intersect=function(t,e){for(var o=[],r=t.length>e.length?t:e,i=t.length>e.length?e:t,s=0,c=i.length;s<c;s++)~n.indexOf(r,i[s])&&o.push(i[s]);return o},n.indexOf=function(t,e,n){for(var o=t.length,n=n<0?n+o<0?0:n+o:n||0;n<o&&t[n]!==e;n++);return o<=n?-1:n},n.toArray=function(t){for(var e=[],n=0,o=t.length;n<o;n++)e.push(t[n]);return e},n.ua={},n.ua.hasCORS="undefined"!=typeof XMLHttpRequest&&function(){try{var t=new XMLHttpRequest;}catch(t){return !1}return void 0!=t.withCredentials}(),n.ua.webkit="undefined"!=typeof navigator&&/webkit/i.test(navigator.userAgent);}(void 0!==io?io:module.exports,void 0===global?window:global),function(t,e){function n(){}t.EventEmitter=n,n.prototype.on=function(t,n){return this.$events||(this.$events={}),this.$events[t]?e.util.isArray(this.$events[t])?this.$events[t].push(n):this.$events[t]=[this.$events[t],n]:this.$events[t]=n,this},n.prototype.addListener=n.prototype.on,n.prototype.once=function(t,e){function n(){o.removeListener(t,n),e.apply(this,arguments);}var o=this;return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,n){if(this.$events&&this.$events[t]){var o=this.$events[t];if(e.util.isArray(o)){for(var r=-1,i=0,s=o.length;i<s;i++)if(o[i]===n||o[i].listener&&o[i].listener===n){r=i;break}if(r<0)return this;o.splice(r,1),o.length||delete this.$events[t];}else (o===n||o.listener&&o.listener===n)&&delete this.$events[t];}return this},n.prototype.removeAllListeners=function(t){return this.$events&&this.$events[t]&&(this.$events[t]=null),this},n.prototype.listeners=function(t){return this.$events||(this.$events={}),this.$events[t]||(this.$events[t]=[]),e.util.isArray(this.$events[t])||(this.$events[t]=[this.$events[t]]),this.$events[t]},n.prototype.emit=function(t){if(!this.$events)return !1;var n=this.$events[t];if(!n)return !1;var o=Array.prototype.slice.call(arguments,1);if("function"==typeof n)n.apply(this,o);else {if(!e.util.isArray(n))return !1;for(var r=n.slice(),i=0,s=r.length;i<s;i++)r[i].apply(this,o);}return !0};}(void 0!==io?io:module.exports,void 0!==io?io:module.parent.exports),function(exports,nativeJSON){function f(t){return t<10?"0"+t:t}function date(t,e){return isFinite(t.valueOf())?t.getUTCFullYear()+"-"+f(t.getUTCMonth()+1)+"-"+f(t.getUTCDate())+"T"+f(t.getUTCHours())+":"+f(t.getUTCMinutes())+":"+f(t.getUTCSeconds())+"Z":null}function quote(t){return escapable.lastIndex=0,escapable.test(t)?'"'+t.replace(escapable,function(t){var e=meta[t];return "string"==typeof e?e:"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+t+'"'}function str(t,e){var n,o,r,i,s,c=gap,a=e[t];switch(a instanceof Date&&(a=date(t)),"function"==typeof rep&&(a=rep.call(e,t,a)),typeof a){case"string":return quote(a);case"number":return isFinite(a)?String(a):"null";case"boolean":case"null":return String(a);case"object":if(!a)return "null";if(gap+=indent,s=[],"[object Array]"===Object.prototype.toString.apply(a)){for(i=a.length,n=0;n<i;n+=1)s[n]=str(n,a)||"null";return r=0===s.length?"[]":gap?"[\n"+gap+s.join(",\n"+gap)+"\n"+c+"]":"["+s.join(",")+"]",gap=c,r}if(rep&&"object"==typeof rep)for(i=rep.length,n=0;n<i;n+=1)"string"==typeof rep[n]&&(o=rep[n],(r=str(o,a))&&s.push(quote(o)+(gap?": ":":")+r));else for(o in a)Object.prototype.hasOwnProperty.call(a,o)&&(r=str(o,a))&&s.push(quote(o)+(gap?": ":":")+r);return r=0===s.length?"{}":gap?"{\n"+gap+s.join(",\n"+gap)+"\n"+c+"}":"{"+s.join(",")+"}",gap=c,r}}if(nativeJSON&&nativeJSON.parse)return exports.JSON={parse:nativeJSON.parse,stringify:nativeJSON.stringify};var JSON=exports.JSON={},cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;JSON.stringify=function(t,e,n){var o;if(gap="",indent="","number"==typeof n)for(o=0;o<n;o+=1)indent+=" ";else "string"==typeof n&&(indent=n);if(rep=e,e&&"function"!=typeof e&&("object"!=typeof e||"number"!=typeof e.length))throw new Error("JSON.stringify");return str("",{"":t})},JSON.parse=function(text,reviver){function walk(t,e){var n,o,r=t[e];if(r&&"object"==typeof r)for(n in r)Object.prototype.hasOwnProperty.call(r,n)&&(o=walk(r,n),void 0!==o?r[n]=o:delete r[n]);return reviver.call(t,e,r)}var j;if(text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(t){return "\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)})),/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")};}(void 0!==io?io:module.exports,"undefined"!=typeof JSON?JSON:void 0),function(t,e){var n=t.parser={},o=n.packets=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],r=n.reasons=["transport not supported","client not handshaken","unauthorized"],i=n.advice=["reconnect"],s=e.JSON,c=e.util.indexOf;n.encodePacket=function(t){var e=c(o,t.type),n=t.id||"",a=t.endpoint||"",u=t.ack,h=null;switch(t.type){case"error":var l=t.reason?c(r,t.reason):"",p=t.advice?c(i,t.advice):"";""===l&&""===p||(h=l+(""!==p?"+"+p:""));break;case"message":""!==t.data&&(h=t.data);break;case"event":var d={name:t.name};t.args&&t.args.length&&(d.args=t.args),h=s.stringify(d);break;case"json":h=s.stringify(t.data);break;case"connect":t.qs&&(h=t.qs);break;case"ack":h=t.ackId+(t.args&&t.args.length?"+"+s.stringify(t.args):"");}var f=[e,n+("data"==u?"+":""),a];return null!==h&&void 0!==h&&f.push(h),f.join(":")},n.encodePayload=function(t){var e="";if(1==t.length)return t[0];for(var n=0,o=t.length;n<o;n++){e+="�"+t[n].length+"�"+t[n];}return e};var a=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;n.decodePacket=function(t){var e=t.match(a);if(!e)return {};var n=e[2]||"",t=e[5]||"",c={type:o[e[1]],endpoint:e[4]||""};switch(n&&(c.id=n,e[3]?c.ack="data":c.ack=!0),c.type){case"error":var e=t.split("+");c.reason=r[e[0]]||"",c.advice=i[e[1]]||"";break;case"message":c.data=t||"";break;case"event":try{var u=s.parse(t);c.name=u.name,c.args=u.args;}catch(t){}c.args=c.args||[];break;case"json":try{c.data=s.parse(t);}catch(t){}break;case"connect":c.qs=t||"";break;case"ack":var e=t.match(/^([0-9]+)(\+)?(.*)/);if(e&&(c.ackId=e[1],c.args=[],e[3]))try{c.args=e[3]?s.parse(e[3]):[];}catch(t){}}return c},n.decodePayload=function(t){if("�"==t.charAt(0)){for(var e=[],o=1,r="";o<t.length;o++)"�"==t.charAt(o)?(e.push(n.decodePacket(t.substr(o+1).substr(0,r))),o+=Number(r)+1,r=""):r+=t.charAt(o);return e}return [n.decodePacket(t)]};}(void 0!==io?io:module.exports,void 0!==io?io:module.parent.exports),function(t,e){function n(t,e){this.socket=t,this.sessid=e,this.connectErrorCallback=void 0,this.isOpened=!1;}t.Transport=n,e.util.mixin(n,e.EventEmitter),n.prototype.onData=function(t){if(this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout(),""!==t){var n=e.parser.decodePayload(t);if(n&&n.length)for(var o=0,r=n.length;o<r;o++)this.onPacket(n[o]);}return this},n.prototype.onPacket=function(t){return this.socket.setHeartbeatTimeout(),"heartbeat"==t.type?this.onHeartbeat():("connect"==t.type&&""==t.endpoint&&this.onConnect(),"error"==t.type&&"reconnect"==t.advice&&(this.isOpened=!1),this.socket.onPacket(t),this)},n.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var t=this;this.closeTimeout=setTimeout(function(){t.onDisconnect();},this.socket.closeTimeout);}},n.prototype.onDisconnect=function(){return this.close&&this.isOpened&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},n.prototype.onConnect=function(){return this.socket.onConnect(),this.connectErrorCallback=void 0,this},n.prototype.clearCloseTimeout=function(){this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null);},n.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout);},n.prototype.packet=function(t){this.send(e.parser.encodePacket(t));},n.prototype.onHeartbeat=function(t){this.packet({type:"heartbeat"});},n.prototype.onOpen=function(){this.isOpened=!0,this.clearCloseTimeout(),this.socket.onOpen();},n.prototype.onClose=function(){this.isOpened=!1,this.socket.onClose(),this.onDisconnect();},n.prototype.prepareUrl=function(){var t=this.socket.options;return this.scheme()+"://"+t.host+":"+t.port+"/"+t.resource+"/"+e.protocol+"/"+this.name+"/"+this.sessid},n.prototype.ready=function(t,e){e.call(this);},n.prototype.clearEventHandlers=function(){return this};}(void 0!==io?io:module.exports,void 0!==io?io:module.parent.exports),function(t,e,n){function o(t){if(this.options={port:80,secure:!1,document:"document"in n&&document,resource:"socket.io",transports:e.transports.slice(),"connect timeout":1e4,"try multiple transports":!0,reconnect:!0,"reconnection delay":500,"reconnection limit":1/0,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":!0,"auto connect":!0,"flash policy port":10843},e.util.merge(this.options,t),this.connected=!1,this.open=!1,this.connecting=!1,this.reconnecting=!1,this.namespaces={},this.buffer=[],this.doBuffer=!1,this.options["sync disconnect on unload"]&&(!this.isXDomain()||e.util.ua.hasCORS)){var o=this;e.util.on(n,"unload",function(){o.disconnectSync();},!1);}this.options["auto connect"]&&this.connect();}function r(){}t.Socket=o,e.util.mixin(o,e.EventEmitter),o.prototype.of=function(t){return this.namespaces[t]||(this.namespaces[t]=new e.SocketNamespace(this,t),""!==t&&this.namespaces[t].packet({type:"connect"})),this.namespaces[t]},o.prototype.publish=function(){this.emit.apply(this,arguments);var t;for(var e in this.namespaces)this.namespaces.hasOwnProperty(e)&&(t=this.of(e),t.$emit.apply(t,arguments));},o.prototype.handshake=function(t){function n(e){e instanceof Error?o.onError(e.message):t.apply(null,e.split(":"));}var o=this,i=this.options,s=["http"+(i.secure?"s":"")+":/",i.host+":"+i.port,i.resource,e.protocol,e.util.query(this.options.query,"t="+ +new Date)].join("/");if(this.isXDomain()&&!e.util.ua.hasCORS){var c=document.getElementsByTagName("script")[0],a=document.createElement("script");a.src=s+"&jsonp="+e.j.length,c.parentNode.insertBefore(a,c),e.j.push(function(t){n(t),a.parentNode.removeChild(a);});}else {var u=e.util.request();u.open("GET",s,!0),u.withCredentials=!0,u.onreadystatechange=function(){4==u.readyState&&(u.onreadystatechange=r,200==u.status?n(u.responseText):!o.reconnecting&&o.onError(u.responseText));},u.send(null);}},o.prototype.getTransport=function(t){for(var n,o=t||this.transports,r=0;n=o[r];r++)if(e.Transport[n]&&e.Transport[n].check(this)&&(!this.isXDomain()||e.Transport[n].xdomainCheck()))return new e.Transport[n](this,this.sessionid);return null},o.prototype.connect=function(t){if(this.connecting)return this;var n=this;return this.handshake(function(o,r,i,s){function c(){if(!n.connected)if(n.connecting=!1,clearTimeout(n.connectTimeoutTimer),n.options["try multiple transports"]){for(;n.remainingTransports.length>0&&n.remainingTransports.splice(0,1)[0]!=n.transport.name;);n.remainingTransports.length?a(n.remainingTransports):n.publish("connect_failed");}else n.publish("connect_failed");}function a(t){if(n.transport&&(n.transport.clearTimeouts(),n.transport.clearEventHandlers()),n.transport=n.getTransport(t),!n.transport)return n.publish("connect_failed");n.transport.ready(n,function(){n.connecting=!0,n.publish("connecting",n.transport.name),n.transport.open(c),n.options["connect timeout"]&&(n.connectTimeoutTimer=setTimeout(function(){c();},n.options["connect timeout"]));});}n.sessionid=o,n.closeTimeout=1e3*i+2e3,n.heartbeatTimeout=1e3*r+2e3,n.transports=s?e.util.intersect(s.split(","),n.options.transports):n.options.transports,n.setHeartbeatTimeout(),n.remainingTransports=n.transports.slice(0),a(n.transports),n.once("connect",function(){clearTimeout(n.connectTimeoutTimer),t&&"function"==typeof t&&t();});}),this},o.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);var t=this;this.heartbeatTimeoutTimer=setTimeout(function(){t.transport.onClose();},this.heartbeatTimeout);},o.prototype.packet=function(t){return this.connected&&!this.doBuffer?this.transport.packet(t):this.buffer.push(t),this},o.prototype.setBuffer=function(t){this.doBuffer=t,!t&&this.connected&&this.buffer.length&&(this.transport.payload(this.buffer),this.buffer=[]);},o.prototype.disconnect=function(){return (this.connected||this.connecting)&&(this.open&&this.of("").packet({type:"disconnect"}),this.onDisconnect("booted")),this},o.prototype.disconnectSync=function(){var t=e.util.request(),n=this.resource+"/"+e.protocol+"/"+this.sessionid;t.open("GET",n,!0),this.onDisconnect("booted");},o.prototype.isXDomain=function(){var t=n.location.port||("https:"==n.location.protocol?443:80);return this.options.host!==n.location.hostname||this.options.port!=t},o.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit("connect"));},o.prototype.onOpen=function(){this.open=!0;},o.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer);},o.prototype.onPacket=function(t){this.of(t.endpoint).onPacket(t);},o.prototype.onError=function(t){t&&t.advice&&"reconnect"===t.advice&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish("error",t&&t.reason?t.reason:t);},o.prototype.onDisconnect=function(t){var e=this.connected,n=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1,(e||n)&&(this.transport.close(),this.transport.clearTimeouts(),e&&(this.publish("disconnect",t),"booted"!=t&&this.options.reconnect&&!this.reconnecting&&this.reconnect()));},o.prototype.reconnect=function(){function t(){if(n.connected){for(var t in n.namespaces)n.namespaces.hasOwnProperty(t)&&""!==t&&n.namespaces[t].packet({type:"connect"});n.publish("reconnect",n.transport.name,n.reconnectionAttempts);}clearTimeout(n.reconnectionTimer),n.removeListener("connect_failed",e),n.removeListener("connect",e),n.reconnecting=!1,delete n.reconnectionAttempts,delete n.reconnectionDelay,delete n.reconnectionTimer,delete n.redoTransports,n.options["try multiple transports"]=r;}function e(){if(n.reconnecting)return n.connected?t():n.connecting&&n.reconnecting?n.reconnectionTimer=setTimeout(e,1e3):void(n.reconnectionAttempts++>=o?n.redoTransports?(n.publish("reconnect_failed"),t()):(n.on("connect_failed",e),n.options["try multiple transports"]=!0,n.transport=n.getTransport(),n.redoTransports=!0,n.connect()):(n.reconnectionDelay<i&&(n.reconnectionDelay*=2),n.connect(),n.publish("reconnecting",n.reconnectionDelay,n.reconnectionAttempts),n.reconnectionTimer=setTimeout(e,n.reconnectionDelay)))}this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options["reconnection delay"];var n=this,o=this.options["max reconnection attempts"],r=this.options["try multiple transports"],i=this.options["reconnection limit"];this.options["try multiple transports"]=!1,this.reconnectionTimer=setTimeout(e,this.reconnectionDelay),this.on("connect",e);};}(void 0!==io?io:module.exports,void 0!==io?io:module.parent.exports,void 0===global?window:global),function(t,e){function n(t,e){this.socket=t,this.name=e||"",this.flags={},this.json=new o(this,"json"),this.ackPackets=0,this.acks={};}function o(t,e){this.namespace=t,this.name=e;}t.SocketNamespace=n,e.util.mixin(n,e.EventEmitter),n.prototype.$emit=e.EventEmitter.prototype.emit,n.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},n.prototype.packet=function(t){return t.endpoint=this.name,this.socket.packet(t),this.flags={},this},n.prototype.send=function(t,e){var n={type:this.flags.json?"json":"message",data:t};return "function"==typeof e&&(n.id=++this.ackPackets,n.ack=!0,this.acks[n.id]=e),this.packet(n)},n.prototype.emit=function(t){var e=Array.prototype.slice.call(arguments,1),n=e[e.length-1],o={type:"event",name:t};return "function"==typeof n&&(o.id=++this.ackPackets,o.ack="data",this.acks[o.id]=n,e=e.slice(0,e.length-1)),o.args=e,this.packet(o)},n.prototype.disconnect=function(){return ""===this.name?this.socket.disconnect():(this.packet({type:"disconnect"}),this.$emit("disconnect")),this},n.prototype.onPacket=function(t){function n(){o.packet({type:"ack",args:e.util.toArray(arguments),ackId:t.id});}var o=this;switch(t.type){case"connect":this.$emit("connect");break;case"disconnect":""===this.name?this.socket.onDisconnect(t.reason||"booted"):this.$emit("disconnect",t.reason);break;case"message":case"json":var r=["message",t.data];"data"==t.ack?r.push(n):t.ack&&this.packet({type:"ack",ackId:t.id}),this.$emit.apply(this,r);break;case"event":var r=[t.name].concat(t.args);"data"==t.ack&&r.push(n),this.$emit.apply(this,r);break;case"ack":this.acks[t.ackId]&&(this.acks[t.ackId].apply(this,t.args),delete this.acks[t.ackId]);break;case"error":t.advice?this.socket.onError(t):"unauthorized"==t.reason?this.$emit("connect_failed",t.reason):this.$emit("error",t.reason);}},o.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments);},o.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments);};}(void 0!==io?io:module.exports,void 0!==io?io:module.parent.exports),function(t,e,n){function o(t){e.Transport.apply(this,arguments);}function r(){}t.websocket=o,e.util.inherit(o,e.Transport),o.prototype.name="websocket",o.prototype.open=function(t){var o,r=e.util.query(this.socket.options.query),i=this;return this.connectErrorCallback=t,o||(o=n.MozWebSocket||n.WebSocket),this.websocket=new o(this.prepareUrl()+r),this.websocket.onopen=function(){i.onOpen(),i.socket.setBuffer(!1);},this.websocket.onmessage=function(t){i.onData(t.data);},this.websocket.onclose=function(){i.onClose(),i.socket.setBuffer(!0);},this.websocket.onerror=function(t){i.onError(t);},this},o.prototype.send=function(t){return this.websocket.send(t),this},o.prototype.payload=function(t){for(var e=0,n=t.length;e<n;e++)this.packet(t[e]);return this},o.prototype.close=function(){return this.websocket.close(),this},o.prototype.onError=function(t){void 0!==this.connectErrorCallback&&(this.connectErrorCallback(),this.connectErrorCallback=void 0),this.socket.onError(t);},o.prototype.scheme=function(){return this.socket.options.secure?"wss":"ws"},o.check=function(){return "WebSocket"in n&&!("__addTask"in WebSocket)||"MozWebSocket"in n},o.xdomainCheck=function(){return !0},o.prototype.clearEventHandlers=function(){return this.websocket&&(this.websocket.onopen=this.websocket.onmessage=this.websocket.onclose=this.websocket.onerror=r),this},e.transports.push("websocket");}(void 0!==io?io.Transport:module.exports,void 0!==io?io:module.parent.exports,void 0===global?window:global),function(t,e,n){function o(t){t&&(e.Transport.apply(this,arguments),this.sendBuffer=[]);}function r(){}t.XHR=o,e.util.inherit(o,e.Transport),o.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},o.prototype.payload=function(t){for(var n=[],o=0,r=t.length;o<r;o++)n.push(e.parser.encodePacket(t[o]));this.send(e.parser.encodePayload(n));},o.prototype.send=function(t){return this.post(t),this},o.prototype.post=function(t){function e(){4==this.readyState&&(this.onreadystatechange=r,i.posting=!1,200==this.status?(i.socket.setBuffer(!1),clearTimeout(i.sendXHR.ackTimeoutTimer)):i.onClose());}function o(){this.onload=r,i.socket.setBuffer(!1);}var i=this;this.socket.setBuffer(!0),this.sendXHR=this.request("POST"),n.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=o:this.sendXHR.onreadystatechange=e,this.sendXHR.send(t),i.sendXHR.ackTimeoutTimer=setTimeout(function(){i.onClose();},i.socket.options.ackTimeoutMs);},o.prototype.close=function(){return this.onClose(),this},o.prototype.request=function(t){var n=e.util.request(this.socket.isXDomain()),o=e.util.query(this.socket.options.query,"t="+ +new Date);if(n.open(t||"GET",this.prepareUrl()+o,!0),"POST"==t)try{n.setRequestHeader?n.setRequestHeader("Content-type","text/plain;charset=UTF-8"):n.contentType="text/plain";}catch(t){}return n},o.prototype.scheme=function(){return this.socket.options.secure?"https":"http"},o.check=function(t,o){try{var r=e.util.request(o),i=n.XDomainRequest&&r instanceof XDomainRequest,s=t&&t.options&&t.options.secure?"https:":"http:",c=s!=n.location.protocol;if(r&&(!i||!c))return !0}catch(t){}return !1},o.xdomainCheck=function(){return o.check(null,!0)},o.prototype.clearEventHandlers=function(){return this.sendXHR&&(this.sendXHR.onreadystatechange=this.sendXHR.onload=r),this};}(void 0!==io?io.Transport:module.exports,void 0!==io?io:module.parent.exports,void 0===global?window:global),function(t,e,n){function o(){e.Transport.XHR.apply(this,arguments);}function r(){}t["xhr-polling"]=o,e.util.inherit(o,e.Transport.XHR),e.util.merge(o,e.Transport.XHR),o.prototype.name="xhr-polling",o.prototype.open=function(t){var n=this;return n.connectErrorCallback=t,e.Transport.XHR.prototype.open.call(n),!1},o.prototype.get=function(){function t(){4==this.readyState&&(this.onreadystatechange=r,200==this.status?(i.connectErrorCallback=void 0,i.onData(this.responseText),i.get()):(i.onClose(),void 0!==i.connectErrorCallback&&(i.connectErrorCallback(),i.connectErrorCallback=void 0)));}function e(){i.connectErrorCallback=void 0,this.onload=r,this.onerror=r,i.onData(this.responseText),i.get();}function o(){i.onClose(),void 0!==i.connectErrorCallback&&(i.connectErrorCallback(),i.connectErrorCallback=void 0);}if(this.isOpened){var i=this;this.xhr=this.request(),n.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=e,this.xhr.onerror=o):this.xhr.onreadystatechange=t,this.xhr.send(null);}},o.prototype.onClose=function(){if(e.Transport.XHR.prototype.onClose.call(this),this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=r;try{this.xhr.abort();}catch(t){}this.xhr=null;}},o.prototype.ready=function(t,n){var o=this;e.util.defer(function(){n.call(o);});},o.prototype.clearEventHandlers=function(){return e.Transport.XHR.prototype.clearEventHandlers.call(this),this.xhr&&(this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=r),this},e.transports.push("xhr-polling");}(void 0!==io?io.Transport:module.exports,void 0!==io?io:module.parent.exports,void 0===global?window:global),exports.io=io;}).call(exports,__webpack_require__(4),__webpack_require__(13)(module));},function(t,e,n){(function(e,o){/*!
   * @overview es6-promise - a tiny implementation of Promises/A+.
   * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
   * @license   Licensed under MIT license
   *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
   * @version   4.0.5
   */
  !function(e,n){t.exports=n();}(0,function(){function t(t){return "function"==typeof t||"object"==typeof t&&null!==t}function r(t){return "function"==typeof t}function i(t){$=t;}function s(t){V=t;}function c(){return void 0!==X?function(){X(u);}:a()}function a(){var t=setTimeout;return function(){return t(u,1)}}function u(){for(var t=0;t<J;t+=2){(0, Y[t])(Y[t+1]),Y[t]=void 0,Y[t+1]=void 0;}J=0;}function h(t,e){var n=arguments,o=this,r=new this.constructor(p);void 0===r[tt]&&O(r);var i=o._state;return i?function(){var t=n[i-1];V(function(){return _(i,r,t,o._result)});}():C(o,r,t,e),r}function l(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(p);return k(n,t),n}function p(){}function d(){return new TypeError("You cannot resolve a promise with itself")}function f(){return new TypeError("A promises callback cannot return that same promise.")}function g(t){try{return t.then}catch(t){return rt.error=t,rt}}function m(t,e,n,o){try{t.call(e,n,o);}catch(t){return t}}function v(t,e,n){V(function(t){var o=!1,r=m(n,e,function(n){o||(o=!0,e!==n?k(t,n):w(t,n));},function(e){o||(o=!0,b(t,e));},"Settle: "+(t._label||" unknown promise"));!o&&r&&(o=!0,b(t,r));},t);}function y(t,e){e._state===nt?w(t,e._result):e._state===ot?b(t,e._result):C(e,void 0,function(e){return k(t,e)},function(e){return b(t,e)});}function T(t,e,n){e.constructor===t.constructor&&n===h&&e.constructor.resolve===l?y(t,e):n===rt?b(t,rt.error):void 0===n?w(t,e):r(n)?v(t,e,n):w(t,e);}function k(e,n){e===n?b(e,d()):t(n)?T(e,n,g(n)):w(e,n);}function S(t){t._onerror&&t._onerror(t._result),R(t);}function w(t,e){t._state===et&&(t._result=e,t._state=nt,0!==t._subscribers.length&&V(R,t));}function b(t,e){t._state===et&&(t._state=ot,t._result=e,V(S,t));}function C(t,e,n,o){var r=t._subscribers,i=r.length;t._onerror=null,r[i]=e,r[i+nt]=n,r[i+ot]=o,0===i&&t._state&&V(R,t);}function R(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var o=void 0,r=void 0,i=t._result,s=0;s<e.length;s+=3)o=e[s],r=e[s+n],o?_(n,o,r,i):r(i);t._subscribers.length=0;}}function I(){this.error=null;}function E(t,e){try{return t(e)}catch(t){return it.error=t,it}}function _(t,e,n,o){var i=r(n),s=void 0,c=void 0,a=void 0,u=void 0;if(i){if(s=E(n,o),s===it?(u=!0,c=s.error,s=null):a=!0,e===s)return void b(e,f())}else s=o,a=!0;e._state!==et||(i&&a?k(e,s):u?b(e,c):t===nt?w(e,s):t===ot&&b(e,s));}function M(t,e){try{e(function(e){k(t,e);},function(e){b(t,e);});}catch(e){b(t,e);}}function P(){return st++}function O(t){t[tt]=st++,t._state=void 0,t._result=void 0,t._subscribers=[];}function U(t,e){this._instanceConstructor=t,this.promise=new t(p),this.promise[tt]||O(this.promise),F(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?w(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&w(this.promise,this._result))):b(this.promise,x());}function x(){return new Error("Array Methods must be provided an Array")}function A(t){return new U(this,t).promise}function D(t){var e=this;return new e(F(t)?function(n,o){for(var r=t.length,i=0;i<r;i++)e.resolve(t[i]).then(n,o);}:function(t,e){return e(new TypeError("You must pass an array to race."))})}function L(t){var e=this,n=new e(p);return b(n,t),n}function j(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function q(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function N(t){this[tt]=P(),this._result=this._state=void 0,this._subscribers=[],p!==t&&("function"!=typeof t&&j(),this instanceof N?M(this,t):q());}function H(){var t=void 0;if(void 0!==o)t=o;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")();}catch(t){throw new Error("polyfill failed because global object is unavailable in this environment")}var e=t.Promise;if(e){var n=null;try{n=Object.prototype.toString.call(e.resolve());}catch(t){}if("[object Promise]"===n&&!e.cast)return}t.Promise=N;}var B=void 0;B=Array.isArray?Array.isArray:function(t){return "[object Array]"===Object.prototype.toString.call(t)};var F=B,J=0,X=void 0,$=void 0,V=function(t,e){Y[J]=t,Y[J+1]=e,2===(J+=2)&&($?$(u):Z());},G="undefined"!=typeof window?window:void 0,K=G||{},W=K.MutationObserver||K.WebKitMutationObserver,Q="undefined"==typeof self&&void 0!==e&&"[object process]"==={}.toString.call(e),z="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,Y=new Array(1e3),Z=void 0;Z=Q?function(){return function(){return e.nextTick(u)}}():W?function(){var t=0,e=new W(u),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2;}}():z?function(){var t=new MessageChannel;return t.port1.onmessage=u,function(){return t.port2.postMessage(0)}}():void 0===G?function(){try{var t=n(21);return X=t.runOnLoop||t.runOnContext,c()}catch(t){return a()}}():a();var tt=Math.random().toString(36).substring(16),et=void 0,nt=1,ot=2,rt=new I,it=new I,st=0;return U.prototype._enumerate=function(){for(var t=this.length,e=this._input,n=0;this._state===et&&n<t;n++)this._eachEntry(e[n],n);},U.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,o=n.resolve;if(o===l){var r=g(t);if(r===h&&t._state!==et)this._settledAt(t._state,e,t._result);else if("function"!=typeof r)this._remaining--,this._result[e]=t;else if(n===N){var i=new n(p);T(i,t,r),this._willSettleAt(i,e);}else this._willSettleAt(new n(function(e){return e(t)}),e);}else this._willSettleAt(o(t),e);},U.prototype._settledAt=function(t,e,n){var o=this.promise;o._state===et&&(this._remaining--,t===ot?b(o,n):this._result[e]=n),0===this._remaining&&w(o,this._result);},U.prototype._willSettleAt=function(t,e){var n=this;C(t,void 0,function(t){return n._settledAt(nt,e,t)},function(t){return n._settledAt(ot,e,t)});},N.all=A,N.race=D,N.resolve=l,N.reject=L,N._setScheduler=i,N._setAsap=s,N._asap=V,N.prototype={constructor:N,then:h,catch:function(t){return this.then(null,t)}},N.polyfill=H,N.Promise=N,N});}).call(e,n(12),n(4));},function(t,e){function n(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function r(t){if(h===setTimeout)return setTimeout(t,0);if((h===n||!h)&&setTimeout)return h=setTimeout,setTimeout(t,0);try{return h(t,0)}catch(e){try{return h.call(null,t,0)}catch(e){return h.call(this,t,0)}}}function i(t){if(l===clearTimeout)return clearTimeout(t);if((l===o||!l)&&clearTimeout)return l=clearTimeout,clearTimeout(t);try{return l(t)}catch(e){try{return l.call(null,t)}catch(e){return l.call(this,t)}}}function s(){g&&d&&(g=!1,d.length?f=d.concat(f):m=-1,f.length&&c());}function c(){if(!g){var t=r(s);g=!0;for(var e=f.length;e;){for(d=f,f=[];++m<e;)d&&d[m].run();m=-1,e=f.length;}d=null,g=!1,i(t);}}function a(t,e){this.fun=t,this.array=e;}function u(){}var h,l,p=t.exports={};!function(){try{h="function"==typeof setTimeout?setTimeout:n;}catch(t){h=n;}try{l="function"==typeof clearTimeout?clearTimeout:o;}catch(t){l=o;}}();var d,f=[],g=!1,m=-1;p.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];f.push(new a(t,e)),1!==f.length||g||r(c);},a.prototype.run=function(){this.fun.apply(null,this.array);},p.title="browser",p.browser=!0,p.env={},p.argv=[],p.version="",p.versions={},p.on=u,p.addListener=u,p.once=u,p.off=u,p.removeListener=u,p.removeAllListeners=u,p.emit=u,p.prependListener=u,p.prependOnceListener=u,p.listeners=function(t){return []},p.binding=function(t){throw new Error("process.binding is not supported")},p.cwd=function(){return "/"},p.chdir=function(t){throw new Error("process.chdir is not supported")},p.umask=function(){return 0};},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t};},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var o=n(3),r=n(2),i=n(0),s=function(){function t(t){this.id=t,this.status=200,this.headers={},this.body="";}return t}();e.ResponseData=s;var c;!function(t){t.Connected="trouter_js_client_connected",t.Disconnected="trouter_js_client_disconnected",t.Error="trouter_js_client_error",t.Progress="trouter_js_client_progress",t.Response="trouter_js_client_response",t.Request="trouter_js_client_request",t.CheckConnection="trouter_js_client_check_connection",t.Registration="trouter_js_client_registration",t.Unregistration="trouter_js_client_unregistration";}(c=e.ClientEventName||(e.ClientEventName={}));var a=function(){function t(t,e,n,o,r){this.stepName=t,this.operation=e,this.delta=n,this.ts=o,this.error=r;}return t}();e.TrackerStep=a;var u=function(){function t(){}return t}();e.Properties=u;var h=function(){function t(){this.numberOfPingReplies=0,this.connectedTimestamp=0,this.isNewUrl=!1,this.transportType="",this.connectionNumber=0;}return t}(),l=function(){function t(){this.enabled=!1,this.numberOfStepsToMaintain=40,this.logHealthCheckError=!1,this.sendProgressTimeoutSecs=55,this.logSendPingError=!1,this.maxBackoffInMs=12e4,this.trouter_js_client_connected=!1,this.trouter_js_client_disconnected=!1,this.trouter_js_client_error=!1,this.trouter_js_client_progress=!1,this.trouter_js_client_response=!1,this.trouter_js_client_request=!1,this.trouter_js_client_registration=!1,this.trouter_js_client_unregistration=!1,this.trouter_js_client_check_connection=!0;}return t}(),p=function(){function t(t,e,n,r,s,c,a){this.clientId=e,this.clientInfo=n,this.getServerState=r,this.endpointId=s,this.clientCorrelationID=c,this.environment=a,this.logger=new i.Logger("ConnectionTracker",t),this.clientCorrelationID=void 0!==c?c:"",this.steps=[],this.connectionAttempt=0,this.totalStepCount=0,this.beginTimestamp=new o.Timespan,this.eventLogSettings=new l,this.connectedInfo=new h;}return t.prototype.enable=function(t){this.eventLogSettings.enabled=!0,this.eventLogger=t;},t.prototype.disable=function(){this.eventLogSettings.enabled=!1;},t.prototype.sendProgress=function(t){this.steps.length>0&&this.sendTelemetry(c.Progress,t,this.steps);},t.prototype.cancelProgressTimer=function(){void 0!==this.progressTimeout&&(clearTimeout(this.progressTimeout),this.progressTimeout=void 0);},t.prototype.resetProgressSendTimer=function(){var t=this;this.cancelProgressTimer(),void 0!==this.eventLogSettings.sendProgressTimeoutSecs&&this.eventLogSettings.sendProgressTimeoutSecs>0&&(this.progressTimeout=setTimeout(function(){t.sendProgress({reason:"timeout",timeoutSecs:t.eventLogSettings.sendProgressTimeoutSecs});},1e3*this.eventLogSettings.sendProgressTimeoutSecs));},t.prototype.setConnectedInfo=function(t,e){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=Date.now(),this.connectedInfo.isNewUrl=t,this.connectedInfo.transportType=e,++this.connectedInfo.connectionNumber;},t.prototype.clearConnectedInfo=function(){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=0,this.connectedInfo.isNewUrl=!0,this.connectedInfo.transportType="";},t.prototype.copyProperties=function(t,e){for(var n=0,o=Object.keys(e);n<o.length;n++){var r=o[n];e.hasOwnProperty(r)&&void 0!==e[r]&&(t[r.replace(/-/g,"_")]={value:e[r]});}},t.prototype.increasePingResponseCount=function(){++this.connectedInfo.numberOfPingReplies;},t.prototype.sendTelemetry=function(t,e,n){try{if(!0===this.eventLogSettings.enabled&&!0===this.eventLogSettings[t]&&void 0!==this.eventLogger){var i=this.getServerState(),s={name:t,properties:{connectionAttempt:{value:this.connectionAttempt},epid:{value:this.endpointId},clientCorrelationID:{value:this.clientCorrelationID},steps:{value:o.toJson(n)},clientID:{value:this.clientId},eventVersion:{value:3},environment:{value:this.environment},cv:{value:r.CLIENT_VERSION},ua:{value:this.clientInfo.ua},connectionId:{value:i.connectionId},connectedClientId:{value:i.connectedClientId},domId:{value:i.domId},url:{value:i.unsecureUrl},surl:{value:i.url},ttlInSecs:{value:i.getRemainingTtlInSec()},numberOfPingReplies:{value:this.connectedInfo.numberOfPingReplies},connectedTimestamp:{value:this.connectedInfo.connectedTimestamp},isNewUrl:{value:this.connectedInfo.isNewUrl},transportType:{value:this.connectedInfo.transportType},connectionNumber:{value:this.connectedInfo.connectionNumber}}};this.copyProperties(s.properties,e),this.eventLogger.logEvent(s);}}catch(e){this.logger.warn("error in sending event "+t+": "+o.toJson(e));}},t.prototype.createStep=function(t,e,n){return new a(t,e,this.beginTimestamp.duration,Date.now(),n)},t.prototype.addStep=function(t,e,n){if(!1!==this.eventLogSettings.enabled&&(0===this.steps.length&&this.beginTimestamp.reset(),this.steps.push(this.createStep(t,e,n)),++this.totalStepCount,void 0!==this.eventLogSettings.numberOfStepsToMaintain&&this.steps.length>this.eventLogSettings.numberOfStepsToMaintain)){var o=this.steps.slice(0);this.steps.length=0,this.sendTelemetry(c.Progress,{reason:"flush"},o);}},t.prototype.trackStart=function(t){this.addStep(t,"start");},t.prototype.trackEnd=function(t){this.addStep(t,"end");},t.prototype.trackError=function(t,e,n,o){void 0===n&&(n=!0),"health"===t&&!0!==this.eventLogSettings.logHealthCheckError||"ping"===t&&!1===this.eventLogSettings.logSendPingError||(void 0===o&&(o="error"),!0===n&&this.addStep(t,o,e),this.sendTelemetry(c.Error,{},[this.createStep(t,o,e)]));},t.prototype.trackProgress=function(t,e){this.addStep(t,e);},t.prototype.trackConnected=function(t,e){this.setConnectedInfo(t,e);var n=this.steps.slice(0),o=this.totalStepCount,r=this.beginTimestamp.duration;this.steps.length=0,this.totalStepCount=0,this.sendTelemetry(c.Connected,{stepCount:n.length,totalStepCount:o,connectionEstablishmentMs_Total:r},n),this.cancelProgressTimer();},t.prototype.trackDisconnected=function(t){t.sessionLengthMS=Date.now()-this.connectedInfo.connectedTimestamp,this.sendTelemetry(c.Disconnected,t,[]),this.resetProgressSendTimer();},t.prototype.trackNewConnection=function(){++this.connectionAttempt;},t.prototype.trackRequest=function(t,e){var n={};void 0!==e&&(n.hasError=!0,n.error=e);try{if(t){n.requestID=t.id,n.httpMethod=t.method,n.url=t.url,n.bodyLength=t.body.length,n.shortUrl=t.shortUrl,n.requestTimeStamp=t.startTS,n.correlationVector=t.correlationVector;for(var r=t.headers,i=0,s=Object.keys(r);i<s.length;i++){var a=s[i];r.hasOwnProperty(a)&&(n[a]=r[a]);}}}catch(t){n.hasError=!0,n.error=n.error+" error creating request context "+o.toJson(t);}this.sendTelemetry(c.Request,n,[]);},t.prototype.trackResponse=function(t,e,n,r){var i={};void 0!==r&&(i.hasError=!0,i.error=r);try{if(i.responseTimestamp=void 0!==n?n.sentTS:Date.now(),t){i.requestID=t.id,i.httpMethod=t.method,i.shortUrl=t.shortUrl,i.correlationVector=t.correlationVector;for(var s=t.headers,a=0,u=Object.keys(s);a<u.length;a++){var h=u[a];s.hasOwnProperty(h)&&(i[h]=s[h]);}}n&&(i.latencyMS=e,i.responseCode=n.status,i.responseLength=n.body.length);}catch(t){i.hasError=!0,i.error=i.error+" error creating response context "+o.toJson(t);}this.sendTelemetry(c.Response,i,[]);},t.prototype.sendResponseError=function(t,e,n){this.trackResponse(e,void 0,n,t);},t.prototype.close=function(){this.sendProgress({reason:"closed"}),this.steps.length=0,this.cancelProgressTimer();},t.prototype.mergeSettings=function(t){if(t){this.eventLogSettings.numberOfStepsToMaintain=Math.min(40,Math.max(10,void 0!==t.numberOfStepsToMaintain?t.numberOfStepsToMaintain:0));var e=Math.min(3600,Math.max(55,void 0!==t.sendProgressTimeoutSecs?t.sendProgressTimeoutSecs:0));this.eventLogSettings.logHealthCheckError=t.logHealthCheckError,this.eventLogSettings.logSendPingError=t.logSendPingError;for(var n=0,o=Object.keys(c).map(function(t){return c[t]});n<o.length;n++){var r=o[n];t.hasOwnProperty(r)&&void 0!==t[r]&&(this.eventLogSettings[r]=t[r]);}this.eventLogSettings.sendProgressTimeoutSecs!==e&&(this.eventLogSettings.sendProgressTimeoutSecs=e,this.resetProgressSendTimer());}},t}();e.ConnectionTracker=p;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var o=function(){function t(t,e){this.logger=t,this.maxBackoffInMs=e,this.backoffId=0,this.backoffCount=0;}return t.calculateNextBackoffMs=function(t,e){var n=1+.4*(Math.random()-.5),o=1e3*Math.pow(2,t)*n;return o=Math.round(o),Math.min(e,o)},t.prototype.setMaxBackoffMs=function(t){this.maxBackoffInMs=t;},t.prototype.backoff=function(e,n){var o=this;void 0!==this.timerHandle&&(this.logger.debug("Clearing current back off"),clearTimeout(this.timerHandle),this.timerHandle=void 0);var r=t.calculateNextBackoffMs(this.backoffCount,this.maxBackoffInMs);this.backoffId++,this.backoffCount++,this.logger.info("Backing off "+e+" for "+r+" milliseconds with ID "+this.backoffId),this.timerHandle=setTimeout(function(){o.logger.info("Back off for "+e+" with ID "+o.backoffId+" complete, invoking handler"),o.timerHandle=void 0,n();},r);},t.prototype.reset=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off"),clearTimeout(this.timerHandle),this.timerHandle=void 0),this.backoffCount=0;},t}();e.ExponentialBackoff=o;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var o=n(20),r=n(11),i=n(3),s=n(14),c=n(2),a=n(15),u=n(1),h=n(5),l=n(0),p=n(17),d=n(10),f=function(){function t(){this.cv=c.CLIENT_VERSION,this.ua="",this.hr="",this.v="";}return t}(),g=function(){function t(){this["force new connection"]=!0,this.reconnect=!1,this.query="",this.ackTimeoutMs=5e3;}return t}(),m="MS-CV",v=function(){function t(t){this.cvCounter=0;var e=JSON.parse(t);this.startTS=e.hasOwnProperty("startTS")?e.startTS:0,this.url=e.hasOwnProperty("url")?e.url:"",this.shortUrl=e.hasOwnProperty("shortUrl")?e.shortUrl:"",this.body=e.hasOwnProperty("body")?e.body:"",this.headers=e.hasOwnProperty("headers")?e.headers:{},this.id=e.hasOwnProperty("id")&&"number"==typeof e.id?e.id:-1,this.method=e.hasOwnProperty("method")?e.method:"",this.replied=!1,this.timedout=!1,this.timeoutTimerId=0,this.receivedCv=this.headers[m],this.updateCvHeader();}return Object.defineProperty(t.prototype,"correlationVector",{get:function(){return this.receivedCv?this.receivedCv+"."+this.cvCounter:""},enumerable:!0,configurable:!0}),t.prototype.on=function(t,e){"data"===t?this.dataCallback=e:"end"===t&&("function"==typeof this.dataCallback&&this.dataCallback(this.body),e());},t.prototype.incrementCorrelationVector=function(){++this.cvCounter,this.updateCvHeader();},t.prototype.updateCvHeader=function(){var t=this.correlationVector;t&&(this.headers[m]=t);},t}(),y=function(){function t(t,e,n){this.request=t,this.responseData=e,this.sendResponse=n;}return t.prototype.writeHead=function(t,e){this.responseData.status=t,this.responseData.headers=e;},t.prototype.write=function(t){this.responseData.body+=t;},t.prototype.end=function(t){return t&&(this.responseData.body+=t),this.sendResponse(this.request,this.responseData)},t}(),T=function(){function t(t){this.name=t,this.args={},this.timeoutTimerId=0;}return t}(),k=function(){function t(t,e,n,r,i){var h=this;this.options=e,this.manager=n,this.tokenProvider=r,this.connectionId="",this.inIncallMode=!1,this.connectionAttempt=0,this.connectedClientId="",this.c2cUrlBase="",this.pendingTimers={},this.UNKNOWN_TRANSPORT="unknown_transport",this.logger=new l.Logger("Connection",t),this.timeoutOptions=this.options.timeoutOptions,this.healthBackoff=new a.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.tokenBackoff=new a.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.clientID=Date.now(),"undefined"!=typeof window&&window.location&&(this.domId=window.location.hostname),this.clientInfo=new f,this.clientInfo.cv=c.CLIENT_VERSION,this.clientInfo.ua="",this.options&&this.options.clientInfo&&(this.clientInfo.ua=this.safeString(this.options.clientInfo.ua),this.clientInfo.v=this.safeString(this.options.clientInfo.v)),this.connectionTracker=new s.ConnectionTracker(t,this.clientID,this.clientInfo,function(){return h.getServerState()},this.options.endpointId,this.options.clientCorrelationID,this.options.environment),this.applyConnectionTrackerOptions(e);var d=this.options.incallModeTimeoutMs>0;if(this.fsm=new p.TrouterFsm(t,this,d),e.registration){var g={registrarUrl:e.registration.registrarUrl,registrationId:e.registration.registrationId,requestTimeoutMs:e.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:e.timeoutOptions.maxBackoffMs};this.registrarClient=o.createRegistrarClient(t,this.tokenProvider,g);}this.userActivityState=i||u.UserActivityState.Unknown;}return t.prototype.start=function(){this.logger.info("Starting"),this.fsm.start();},t.prototype.stop=function(t){this.logger.info("Stopping"),this.connectionTracker.close(),this.fsm.stop(t);},t.prototype.configure=function(t){var e=this.options.trouterUrl!==t.trouterUrl;this.options=t,this.applyConnectionTrackerOptions(t),e&&this.onTrouterReconnect();},t.prototype.checkConnection=function(t){this.logger.info("checkConnection called with "+t),this.fsm.checkConnection(t),t&&this.connectionTracker.sendTelemetry(s.ClientEventName.CheckConnection,{disconnectDetected:t},[]);},t.prototype.getServerState=function(){return new h.ServerState(this.connectionId,this.connectedClientId,this.domId?this.domId:"",this.allocateResult?this.allocateResult.url:"",this.allocateResult?this.allocateResult.surl:"",this.c2cUrlBase,this.connectionExpireTimestampInSecs)},t.prototype.getUserActivityState=function(){return this.userActivityState},t.prototype.getToken=function(t,e){var n=this;this.logger.info("Getting token "+(e?"with backoff":"without backoff"));var o=function(){n.connectionTracker.trackStart("token"),n.tokenProvider(!t).then(function(t){n.logger.debug("token is received"),n.connectionTracker.trackEnd("token"),n.fsm.onTokenReceived(t);}).catch(function(e){var o=i.toJson(e.stack);n.logger.error("Getting token failed, will retry after timeout. Error: "+o),n.connectionTracker.trackError("token",o),n.getToken(t,!0);});};e?this.tokenBackoff.backoff("getting token",o):(this.tokenBackoff.reset(),o());},t.prototype.startConnectionTimer=function(){var t=this;this.stopConnectionTimer(),this.logger.debug("Starting connection timeout for "+this.timeoutOptions.connectionTimeoutMs+" ms"),this.connectionTimeoutId=setTimeout(function(){t.logger.info("Connection timeout is fired"),t.fsm.onConnectingTimeout();},this.timeoutOptions.connectionTimeoutMs);},t.prototype.stopConnectionTimer=function(){this.connectionTimeoutId&&(this.logger.debug("Stopping connection timeout"),clearTimeout(this.connectionTimeoutId),this.connectionTimeoutId=void 0);},t.prototype.startPingTimer=function(){var t=this;"websocket"===this.transportTypeName?(this.logger.debug("Starting ping timeout for "+this.timeoutOptions.pingTimeoutMs+" ms"),this.pingTimerId=setInterval(function(){t.logger.info("Ping interval fired"),t.fsm.onPingInterval();},this.timeoutOptions.pingTimeoutMs)):this.logger.debug("Not starting ping for transport "+this.transportTypeName);},t.prototype.stopPingTimer=function(){this.pingTimerId&&(this.logger.debug("Stopping ping timeout"),this.clearPingResponseTimer(),clearInterval(this.pingTimerId),this.pingTimerId=void 0);},t.prototype.shouldSkipRegistration=function(){return void 0===this.options.registration},t.prototype.hasCustomRegisterTtl=function(){return this.options.registration&&this.options.registration.registrarTtlSec},t.prototype.startRegisterTimer=function(){var t=this;if(void 0!==this.registrationTimerId)return void this.logger.error("Another registration timer is set - don't create another one");var e=this.getRegistrationTtl()-30;this.logger.debug("Starting registration timeout for "+e+" sec"),this.registrationTimerId=setTimeout(function(){t.logger.info("Registration timeout is fired"),t.registrationTimerId=void 0,t.fsm.onRegistrationTimeout();},1e3*e);},t.prototype.stopRegisterTimer=function(){this.registrationTimerId&&(this.logger.debug("Stopping registration timeout"),clearTimeout(this.registrationTimerId),this.registrationTimerId=void 0);},t.prototype.resendRegistration=function(){if(!this.registrarClient)throw new Error("Trouter Client not configured to handle registrations");return this.registrarClient.resendRegistration()},t.prototype.buildSocketIoUrlParams=function(){if(!this.allocateResult)throw new Error("Allocate result is undefined in buildSocketIoUrlParams()");var t={};if(this.allocateResult.connectparams)for(var e=this.allocateResult.connectparams,n=0,o=Object.keys(e);n<o.length;n++){var r=o[n];e.hasOwnProperty(r)&&void 0!==e[r]&&(t[r]=e[r]);}return t.v="v4",t.tc=encodeURI(i.toJson(this.clientInfo)),t.timeout=this.timeoutOptions.pingTimeoutMs/1e3,t.auth="true",this.options.endpointId&&(t.epid=this.options.endpointId),this.userActivityState!==u.UserActivityState.Unknown&&(t.userActivity=encodeURI(i.toJson(this.createUserActivityObject(this.userActivityState)))),this.appendConnectedClientIds(this.buildQuery(t),!0)},t.prototype.startSocketIo=function(){var t=this;if(this.logger.info("Starting socket io"),this.connectionTracker.trackStart("connectSocket"),!this.allocateResult)throw new Error("Allocate result is undefined in startSocketIo()");var e=this.options.ioOptions||new g;if(e["force new connection"]=!0,e.reconnect=!1,e.query=this.buildSocketIoUrlParams(),this.logger.info("connecting to "+this.allocateResult.socketio+"?"+e.query),this.stopSocketIo(),this.socket=(this.options.io||d).connect(this.allocateResult.socketio,e),void 0===this.socket)throw new Error("Can't create Socket.io object");this.socket.on("connecting",function(e){t.onSocketConnecting(e);}),this.socket.on("connect",function(){t.onSocketConnect();}),this.socket.on("connect_failed",function(e){t.onSocketConnectFailed(e);}),this.socket.on("disconnect",function(){t.onSocketDisconnect();}),this.socket.on("reconnect",function(){t.onSocketReconnect();}),this.socket.on("reconnect_failed",function(e){t.onSocketReconnectFailed(e);}),this.socket.on("reconnecting",function(){t.onSocketReconnecting();}),this.socket.on("error",function(e){t.onSocketError(e);}),this.socket.on("message",function(e){t.onSocketMessage(e);}),this.socket.on("trouter.connected",function(e){t.onTrouterConnected(e);}),this.socket.on("trouter.reconnect",function(){t.onTrouterReconnect();}),this.socket.on("trouter.message_loss",function(e){t.onTrouterMessageLoss(e);});},t.prototype.stopSocketIo=function(){if(this.socket){this.logger.info("clearing socket.io");try{for(var t=0,e=["connecting","connect","connect_failed","disconnect","reconnect","reconnect_failed","reconnecting","error","message","trouter.connected","trouter.reconnect","trouter.message_loss"];t<e.length;t++){var n=e[t];this.socket.removeAllListeners(n);}this.socket.disconnect(),this.logger.debug("cleared socket"),this.socket=void 0;}catch(t){this.logger.error("exception in disconnecting previous socket. Error: "+i.toJson(t.stack));}}},t.prototype.dispatchConnected=function(){this.logger.info("dispatching connected"),this.manager.onConnected(this);},t.prototype.dispatchRegistered=function(){this.logger.info("dispatching connected"),this.manager.onRegistered(this);},t.prototype.dispatchDownstreamRequest=function(t){var e=this;this.logger.info("dispatching downstream request");try{var n=new y(t,new s.ResponseData(t.id),function(t,n){return e.logger.info("sending response to downstream"),e.sendResponse(t,n)});this.manager.onDownstreamRequest(this,t,n);}catch(t){this.logger.error("exception in socket.on message. Error : "+i.toJson(t.stack));}},t.prototype.dispatchReconnecting=function(){this.logger.info("dispatching reconnecting"),this.manager.onReconnecting(this);},t.prototype.dispatchReconnectIsRequired=function(){this.logger.info("dispatching reconnect is required by server"),this.manager.onReconnectIsRequired(this);},t.prototype.dispatchDisconnected=function(){this.logger.info("dispatching disconnected"),this.manager.onDisconnected(this);},t.prototype.dispatchTrouterMessageLost=function(t){this.logger.info("dispatching trouter lost message"),this.manager.onTrouterMessageLost(t);},t.prototype.sendProcessedDroppedIndicators=function(t){var e=this;try{this.logger.info("emitting processed flow tags to the server");var n=new T("trouter.processed_message_loss");n.args={droppedIndicators:t},this.sendDownstreamEvent(n,function(){e.logger.info("emitted processed flow tags to the server");});}catch(t){var o=i.toJson(t.stack);this.logger.error("unable to send processed message loss event. Error: "+o),this.connectionTracker.trackError("trouter.processed_message_loss",o,!1);}},t.prototype.resetAllocationConnectionParams=function(){this.allocateResult&&(this.logger.info("Resetting allocation connection parameters"),this.allocateResult.connectparams=void 0);},t.prototype.sendAllocateRequest=function(t){var e=this;this.connectionAttempt++,this.connectionTracker.trackNewConnection();var n=this.appendCorrelationIds(this.options.trouterUrl,!1);this.allocateResult&&this.allocateResult.connectparams&&(n+="&"+this.buildQuery(this.allocateResult.connectparams),this.allocateResult.connectparams.v||(n+="&v=v4"));var o=new Request(n,{method:"POST",mode:"cors",headers:new Headers({"X-Skypetoken":t,"Content-Type":"text/plain"})});this.logger.info("sendAllocateRequest: POST "+n),this.connectionTracker.trackStart("allocation");var r=-1;this.fetchWithTimeout(o,this.timeoutOptions.fetchTimeoutMs).then(function(t){if(r=t.status,!t.ok)throw new Error(t.statusText);var n=t.headers.get("content-type");if(!n||"application/json"!==n&&"application/json;"!==n.substring(0,17))throw new Error("Content-type '"+n+"' is unexpected");return e.connectionTracker.trackEnd("allocation"),t.json()}).then(function(t){e.onAllocationResponse(t);}).catch(function(t){var n=t+", status code "+r;e.logger.error("Allocation request failed. Error: "+n),e.connectionTracker.trackError("allocation",n),e.fsm.onAllocationFailed(401===r);});},t.prototype.sendPingRequest=function(){var t=this;if(this.socket&&void 0===this.pingResponseTimerId)try{this.logger.info("emitting ping event"),this.socket.emit("ping",function(){t.onPingResponse();}),this.pingResponseTimerId=setTimeout(function(){t.logger.error("Ping response timeout is fired"),t.clearPingResponseTimer(),t.fsm.onPingResponseTimeout();},this.timeoutOptions.pongTimeoutMs);}catch(t){var e=i.toJson(t.stack);this.logger.error("unable to send ping. Error: "+e),this.connectionTracker.trackError("ping",e,!1);}},t.prototype.setUserActivityState=function(t){var e=t!==this.userActivityState;this.userActivityState=t,this.fsm.onSetUserActivityState(t,e);},t.prototype.sendUserActivityState=function(t,e){this.userActivityState!==u.UserActivityState.Unknown&&("websocket"===this.transportTypeName&&e?t===h.UserActivityEventReason.Connected?this.sendUserActivityStateMultiple(2):this.sendUserActivityStateMultiple(1):"xhr-polling"===this.transportTypeName&&t===h.UserActivityEventReason.Modified&&this.fsm.forceReconnect());},t.prototype.sendRegisterRequest=function(){var t=this;if(!this.options.registration||!this.registrarClient)throw new Error("Internal error - options.registration is undefined");if(!this.allocateResult)throw new Error("Allocate result is undefined in sendRegisterRequest()");this.logger.info("sending register request");var e=new i.Timespan;this.connectionTracker.trackStart("registration"),this.registrarClient.register({appId:this.options.registration.pnhAppId,aesKey:"",languageId:"en-US",platform:this.options.registration.platform,templateKey:this.options.registration.pnhTemplateKey,platformUIVersion:this.options.registration.platformUIVersion,productContext:this.options.registration.productContext},{TROUTER:[{context:this.options.registration.context,path:this.allocateResult.surl,ttl:this.getRegistrationTtl()}]}).then(function(){t.logger.info("Register request successful"),t.connectionTracker.trackEnd("registration"),t.fsm.onRegistrationSucceed(),t.connectionTracker.sendTelemetry(s.ClientEventName.Registration,{duration:e.duration},[]);}).catch(function(n){t.logger.error("Register request failed. Error: "+n),t.connectionTracker.trackError("registration",n.message),t.connectionTracker.sendTelemetry(s.ClientEventName.Registration,{duration:e.duration},[]);});},t.prototype.sendUnregisterRequest=function(){var t=this;this.logger.info("sending unregister request");var e=new i.Timespan;if(!this.options.registration||!this.registrarClient)throw new Error("Internal error - options.registration is undefined");this.connectionTracker.trackStart("unregistration"),this.registrarClient.unregister().then(function(){t.logger.info("Unregister request successful"),t.connectionTracker.trackEnd("unregistration"),t.fsm.onUnregistrationSucceed(),t.connectionTracker.sendTelemetry(s.ClientEventName.Unregistration,{duration:e.duration},[]);}).catch(function(n){t.logger.error("Unregister request failed. Error: "+n),t.connectionTracker.trackError("unregistration",n.message),t.fsm.onUnregistrationFailed(!1),t.connectionTracker.sendTelemetry(s.ClientEventName.Unregistration,{duration:e.duration},[]);});},t.prototype.fetchWithTimeout=function(t,e){return new r.Promise(function(n,o){fetch(t).then(n).catch(o),0!==e&&setTimeout(o,e,new Error("Fetch for '"+t.url+"' timed out"));})},t.prototype.resetTokenBackoff=function(){this.tokenBackoff.reset();},t.prototype.resetRegisterBackoff=function(){this.registrarClient&&this.registrarClient.cancelPendingRequests();},t.prototype.clearTimers=function(){this.logger.debug("Clearing all pending downstream events related timers");for(var t=0,e=Object.keys(this.pendingTimers);t<e.length;t++){var n=e[t];this.clearTimer(Number(n));}},t.prototype.restartIncallModeTimer=function(){var t=this;this.clearIncallModeTimerId(),this.logger.debug("Restarting incall mode timer"),this.incallModeTimerId=setTimeout(function(){t.logger.info("Call mode timer fired"),t.fsm.onIncallModeTimer();},this.options.incallModeTimeoutMs);},t.prototype.enterIncallMode=function(){this.logger.info("Entering incall mode"),this.timeoutOptions=this.options.incallTimeoutOptions,this.healthBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!0;},t.prototype.exitIncallMode=function(){this.logger.info("Exiting incall mode"),this.clearIncallModeTimerId(),this.timeoutOptions=this.options.timeoutOptions,this.healthBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!1;},t.prototype.isIncallMode=function(){return this.inIncallMode},t.prototype.onSocketConnecting=function(t){this.logger.info("onSocketConnecting("+t+")"),this.transportTypeName=t,this.connectionTracker.trackProgress("connecting",this.transportTypeName),this.fsm.onConnecting();},t.prototype.onSocketConnect=function(){this.logger.info("onSocketConnect");},t.prototype.onSocketConnectFailed=function(t){this.logger.error("onSocketConnectFailed"),this.connectionTracker.trackError("connect_failed",t,!0,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),this.fsm.onConnectingFailed();},t.prototype.onSocketDisconnect=function(){this.logger.error("onSocketDisconnect"),this.connectionTracker.trackDisconnected({serverClosed:!this.fsm.isActive()}),this.connectionTracker.clearConnectedInfo(),this.fsm.onSocketError(void 0),this.connectionExpireTimestampInSecs=void 0;},t.prototype.onSocketReconnect=function(){this.logger.error("onSocketReconnect"),this.fsm.onTrouterConnected();},t.prototype.onSocketReconnectFailed=function(t){this.logger.error("onSocketReconnectFailed with '"+t+"'"),this.fsm.onSocketError("string"==typeof t?t:void 0);},t.prototype.onSocketReconnecting=function(){this.logger.error("onSocketReconnecting");},t.prototype.onSocketError=function(t){this.logger.error("onSocketError with '"+i.toJson(t)+"'"),this.connectionTracker.trackError("connectSocket",t),this.fsm.onSocketError("string"==typeof t?t:void 0);},t.prototype.onSocketMessage=function(t){var e=this;this.logger.info("onSocketMessage");var n;try{n=new v(t);var o=n.headers&&n.headers["X-Microsoft-Skype-Chain-ID"],r=o?" Chain-Id "+o:"";this.logger.info("Received request N "+n.id+r+" CV "+n.correlationVector+" to '"+n.url+"'"),n.startTS=Date.now(),n.url&&this.urlPath&&0===n.url.indexOf(this.urlPath)&&(n.shortUrl=n.url.substring(this.urlPath.length));}catch(t){var c=i.toJson(t.stack);return this.logger.error("unable to parse request. Error: "+c),this.connectionTracker.trackRequest(void 0,c),void this.connectionTracker.sendResponseError("unable to parse request, error: "+t)}n.timeoutTimerId=setTimeout(function(){if(!n.replied){e.logger.error("Request "+n.id+" timed out");var t=new s.ResponseData(n.id);t.status=504,t.headers={"Trouter-Responder":"ClientLib"},e.sendResponse(n,t),n.timedout=!0;}},this.timeoutOptions.requestTimeoutMs);try{this.connectionTracker.trackRequest(n),this.fsm.onDownstreamRequest(n);}catch(t){this.logger.error("exception in socket.on message. Error: "+i.toJson(t.stack)),this.connectionTracker.sendResponseError(t.message,n,void 0);}},t.prototype.onTrouterConnected=function(t){if(!this.allocateResult)return void this.logger.error("Invalid internal state - received onTrouterConnected while allocateResult is not set");this.logger.info("onTrouterConnected: "+this.allocateResult.url),this.socket&&this.socket.socket&&this.socket.socket.options&&this.socket.socket.options.query&&(this.socket.socket.options.query+="&connected=true"),this.urlPath=this.allocateResult.url.replace(/https?:\/\/([A-z0-9\:\$\-\_\.\+\!\*\"\(\)\,]*)\//,"/");var e=this.connectedUrl!==this.allocateResult.url;this.connectedUrl=this.allocateResult.url,this.connectionExpireTimestampInSecs=i.calculateExpireTsInSec(t.ttl),this.connectionTracker.trackEnd("connectSocket"),this.connectionTracker.trackConnected(e,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),this.fsm.onTrouterConnected();},t.prototype.onTrouterReconnect=function(){this.logger.info("onTrouterReconnect"),this.fsm.onReconnectRequired();},t.prototype.onTrouterMessageLoss=function(t){this.logger.info("onTrouterMessageLoss"),this.fsm.onTrouterMessageLost(t.droppedIndicators);},t.prototype.onAllocationResponse=function(t){this.logger.info("Received allocation response "+JSON.stringify(t)),this.allocateResult=t;var e=+t.ttl;if(this.connectionExpireTimestampInSecs=i.calculateExpireTsInSec(e),this.connectionId=this.allocateResult.id||"",this.connectedClientId=this.allocateResult.ccid,this.logger.info("connected client id set {connectedClientId:"+this.connectedClientId+"}"),this.c2cUrlBase=t.curlb||"",""===this.c2cUrlBase){var n=t.surl.indexOf("://");n>=0&&(n=t.surl.indexOf("/",n+3))>=5&&":3443"===t.surl.substr(n-5,5)&&(this.c2cUrlBase=t.surl.substr(0,n-5));}this.fsm.onAllocationSucceed();},t.prototype.onPingResponse=function(){this.logger.info("onPingResponse"),this.connectionTracker.increasePingResponseCount(),this.clearPingResponseTimer(),this.fsm.onPingResponse();},t.prototype.clearPingResponseTimer=function(){void 0!==this.pingResponseTimerId&&(clearTimeout(this.pingResponseTimerId),this.pingResponseTimerId=void 0);},t.prototype.buildQuery=function(t){for(var e=[],n=0,o=Object.keys(t);n<o.length;n++){var r=o[n];t.hasOwnProperty(r)&&void 0!==t[r]&&e.push(r+"="+t[r]);}return e.join("&")},t.prototype.appendConnectedClientIds=function(t,e){var n="";t.indexOf("ccid=")<0&&(n="ccid="+this.connectedClientId+"&"),this.domId&&(n+="dom="+this.domId+"&"),n.length>0&&(n=n.slice(0,-1));var o=e||-1!==t.indexOf("?")?"&":"?";return this.appendCorrelationIds(t+o+n,e)},t.prototype.appendCorrelationIds=function(t,e){var n=e||-1!==t.indexOf("?")?"&":"?";return t.indexOf("cor_id")<0?""+t+n+"cor_id="+this.options.clientCorrelationID+"&con_num="+this.clientID+"_"+this.connectionAttempt:t},t.prototype.getHealthUrl=function(t){return t.substring(0,t.lastIndexOf("/a"))+"/h"},t.prototype.safeString=function(t){return "string"==typeof t?t:""},t.prototype.sendResponse=function(t,e){if(t.timedout)return this.logger.error("Request "+t.id+" already timed out"),1;if(t.replied)return this.logger.error("Response for request "+t.id+" already sent"),2;clearTimeout(t.timeoutTimerId),t.timeoutTimerId=0,t.replied=!0,e.headers=e.headers||{};var n=t.correlationVector;this.logger.info("Sending response for request N "+t.id+" CV "+n+" with status "+e.status),n&&(e.headers[m]=n),t.headers&&t.headers["trouter-request"]&&!e.headers["trouter-request"]&&(e.headers["trouter-request"]=t.headers["trouter-request"]);var o=Date.now()-t.startTS;if(e.headers["trouter-client"]=i.toJson({cd:o}),this.logger.debug("response: "+i.toJson(e)),!this.socket)return this.connectionTracker.sendResponseError("no socket",t,e),4;try{return this.socket.send(i.toJson(e)),e.sentTS=Date.now(),t.incrementCorrelationVector(),this.connectionTracker.trackResponse(t,o,e),"websocket"===this.transportTypeName&&this.sendPingRequest(),0}catch(n){var r="unable to send data on response.end. Error: "+i.toJson(n.stack);return this.logger.error(r),this.connectionTracker.sendResponseError(r,t,e),4}},t.prototype.sendUserActivityStateMultiple=function(t){var e=this,n=new T("user.activity");n.args=this.createUserActivityObject(this.userActivityState),this.logger.debug("Sending user activity '"+u.UserActivityState[this.userActivityState]+"', remaining "+(t-1)),this.sendDownstreamEvent(n,function(){if(e.onDownstreamEventResponse(n),e.clearTimer(n.timeoutTimerId),t>1){var o=setTimeout(function(){e.clearTimer(o),e.sendUserActivityStateMultiple(t-1);},e.options.userActivitySecondResendDelayMs);e.registerTimer(o,"user.activity/resend");}}),n.timeoutTimerId=setTimeout(function(){e.logger.error("Activity state response timeout is fired"),e.fsm.onActivityStateResponseTimeout(),e.clearTimer(n.timeoutTimerId);},this.timeoutOptions.userActivityResponseTimeoutMs),this.registerTimer(n.timeoutTimerId,"user.activity/response");},t.prototype.sendDownstreamEvent=function(t,e){this.logger.info("Sending downstream event "+t.name),this.socket&&this.socket.emit(t.name,t.args,e);},t.prototype.onDownstreamEventResponse=function(t){this.logger.info("onDownstreamEventResponse("+t.name+")");},t.prototype.registerTimer=function(t,e){this.logger.debug("registering timer "+t+" -> "+e),this.pendingTimers[t]=e;},t.prototype.clearTimer=function(t){var e=this.pendingTimers[t];this.logger.debug("clearing timer "+t+" -> "+e),delete this.pendingTimers[t],clearTimeout(t);},t.prototype.getRegistrationTtl=function(){var t=i.calculateTtlInSec(this.connectionExpireTimestampInSecs);return this.logger.debug("Current connectionID will expire in "+t+" seconds"),this.options.registration&&this.options.registration.registrarTtlSec&&t>0?Math.min(this.options.registration.registrarTtlSec,t):this.options.registration&&this.options.registration.registrarTtlSec?this.options.registration.registrarTtlSec:t>0?t:3600},t.prototype.clearIncallModeTimerId=function(){void 0!==this.incallModeTimerId&&(this.logger.debug("Clearing in-call mode timer"),clearTimeout(this.incallModeTimerId),this.incallModeTimerId=void 0);},t.prototype.applyConnectionTrackerOptions=function(t){try{t.eventLogger&&"function"==typeof t.eventLogger.logEvent?(this.connectionTracker.mergeSettings(t.telemetrySettings),this.connectionTracker.enable(t.eventLogger)):this.logger.warn("Trouter client event logging disabled due to invalid configuration.");}catch(t){this.logger.warn("Trouter client event logging disabled. Error: "+i.toJson(t.stack)),this.connectionTracker.disable();}},t.prototype.createUserActivityObject=function(t){var e;switch(t){case u.UserActivityState.Active:e="active";break;case u.UserActivityState.Inactive:e="inactive";break;case u.UserActivityState.Unknown:e="unknown";break;default:e="undefined";}return {state:e}},t}();e.TrouterConnection=k;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var o,r=n(1),i=n(5),s=n(0);!function(t){t[t.Initial=0]="Initial",t[t.RetrievingToken=1]="RetrievingToken",t[t.Allocating=2]="Allocating",t[t.Handshaking=3]="Handshaking",t[t.Connecting=4]="Connecting",t[t.Connected=5]="Connected",t[t.UnregisteringRetrievingToken=6]="UnregisteringRetrievingToken",t[t.Unregistering=7]="Unregistering";}(o=e.State||(e.State={}));var c;!function(t){t[t.Initial=0]="Initial",t[t.RetrievingToken=1]="RetrievingToken",t[t.Registering=2]="Registering",t[t.Registered=3]="Registered",t[t.NotRegistered=4]="NotRegistered";}(c||(c={}));var a=function(){function t(t,e,n){this.worker=e,this.incallModeEnabled=n,this.state=o.Initial,this.connectionErrors=0,this.logger=new s.Logger("ConnectionFsm",t),this.connectedSubstate=c.Initial,this.userActivityState=r.UserActivityState.Unknown;}return t.prototype.getState=function(){return this.state},t.prototype.isActive=function(){return this.state===o.Allocating||this.state===o.Connected||this.state===o.Handshaking||this.state===o.Connecting||this.state===o.RetrievingToken},t.prototype.start=function(){return this.state===o.Initial?(this.setState(o.RetrievingToken),this.worker.getToken(!0,!1),!0):(this.showIgnored("start"),!1)},t.prototype.stop=function(t){t&&(this.connectedSubstate=c.Initial),this.worker.isIncallMode()&&this.worker.exitIncallMode(),this.worker.resetTokenBackoff(),this.worker.resetRegisterBackoff(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearTimers(),this.state!==o.Connecting&&this.state!==o.Handshaking&&this.state!==o.Connected||this.worker.stopSocketIo(),this.isRegistered()?(this.setState(o.UnregisteringRetrievingToken),this.worker.stopRegisterTimer(),this.worker.getToken(!0,!1)):(this.setState(o.Initial),this.worker.dispatchDisconnected());},t.prototype.onTokenReceived=function(t){this.state===o.RetrievingToken?(this.setState(o.Allocating),this.worker.startConnectionTimer(),this.worker.sendAllocateRequest(t)):this.state===o.Connected&&this.connectedSubstate===c.RetrievingToken?(this.connectedSubstate=c.Registering,this.worker.sendRegisterRequest()):this.state===o.UnregisteringRetrievingToken?(this.setState(o.Unregistering),this.worker.sendUnregisterRequest()):this.showIgnored("onTokenReceived");},t.prototype.checkConnection=function(t){t&&this.onPingInterval();},t.prototype.onAllocationSucceed=function(){return this.state===o.Allocating?(this.setState(o.Handshaking),this.connectedSubstate=c.Initial,this.worker.startSocketIo(),!0):(this.showIgnored("onAllocationSucceed"),!1)},t.prototype.onAllocationFailed=function(t){this.state===o.Allocating?(this.setState(o.RetrievingToken),this.worker.stopConnectionTimer(),this.worker.getToken(!t,!0)):this.showIgnored("onAllocationFailed");},t.prototype.onConnectingTimeout=function(){this.state===o.Allocating||this.state===o.Connecting||this.state===o.Handshaking?(this.setState(o.RetrievingToken),this.resetAllocationIfNecessary(void 0),this.worker.stopSocketIo(),this.worker.getToken(!0,!1)):this.showIgnored("onConnectingTimeout");},t.prototype.onConnecting=function(){this.state===o.Handshaking?this.setState(o.Connecting):this.showIgnored("onConnecting");},t.prototype.onConnectingFailed=function(){this.state===o.Connecting?this.onConnectingTimeout():this.state===o.Handshaking?(this.logger.error("Unexpected error in Socket.io - no valid transports"),this.onConnectingTimeout()):this.showIgnored("onConnectingFailed");},t.prototype.onSocketError=function(t){this.state===o.Handshaking||this.state===o.Connected?(this.worker.stopSocketIo(),this.worker.stopPingTimer(),this.worker.clearTimers(),this.worker.stopConnectionTimer(),this.state!==o.Connected&&this.worker.resetAllocationConnectionParams(),this.setState(o.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(!0,!1)):this.showIgnored("onSocketError");},t.prototype.onTrouterConnected=function(){this.state===o.Connecting?(this.setState(o.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(i.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.connectionErrors=0,this.worker.shouldSkipRegistration()?(this.connectedSubstate=c.NotRegistered,this.worker.dispatchRegistered()):(this.connectedSubstate=c.RetrievingToken,this.worker.getToken(!0,!1))):this.showIgnored("onTrouterConnected");},t.prototype.onReconnectRequired=function(){this.worker.dispatchReconnectIsRequired();},t.prototype.onDownstreamRequest=function(t){this.state===o.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest(t)):this.showIgnored("onDownstreamRequest");},t.prototype.onTrouterMessageLost=function(t){this.state===o.Connected?this.worker.dispatchTrouterMessageLost(t):this.showIgnored("onTrouterMessageLost");},t.prototype.onPingInterval=function(){this.state===o.Connected?this.worker.sendPingRequest():this.showIgnored("onPingInterval");},t.prototype.onPingResponseTimeout=function(){this.onMissedResponse("onPingResponseTimeout");},t.prototype.onPingResponse=function(){this.state===o.Connected||this.showIgnored("onPingResponse");},t.prototype.onRegistrationFailed=function(t){this.state===o.Connected&&this.connectedSubstate===c.Registering?(this.connectedSubstate=c.RetrievingToken,this.worker.getToken(!t,!0)):this.showIgnored("onRegistrationFailed");},t.prototype.onRegistrationSucceed=function(){this.state===o.Connected?(this.connectedSubstate===c.Registering&&(this.connectedSubstate=c.Registered,this.worker.dispatchRegistered()),this.worker.hasCustomRegisterTtl()&&this.worker.startRegisterTimer()):this.showIgnored("onRegistrationSucceed");},t.prototype.onRegistrationTimeout=function(){this.state===o.Connected&&this.connectedSubstate!==c.NotRegistered?(this.connectedSubstate=c.RetrievingToken,this.worker.getToken(!0,!1)):this.showIgnored("onRegistrationTimeout");},t.prototype.onUnregistrationFailed=function(t){this.state===o.Unregistering?(this.setState(o.UnregisteringRetrievingToken),this.worker.getToken(!t,!t)):this.showIgnored("onUnregistrationFailed");},t.prototype.onUnregistrationSucceed=function(){this.state===o.Unregistering?(this.setState(o.Initial),this.worker.dispatchDisconnected()):this.showIgnored("onUnregistrationSucceed");},t.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===o.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored("onIncallModeTimer");},t.prototype.onSetUserActivityState=function(t,e){e?(this.logger.info("Changing user activity state to '"+r.UserActivityState[t]+"'"),this.worker.sendUserActivityState(i.UserActivityEventReason.Modified,this.state===o.Connected)):this.logger.debug("Not changing the same user activity state '"+r.UserActivityState[t]+"'");},t.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse("onActivityStateResponseTimeout");},t.prototype.forceReconnect=function(){this.setState(o.RetrievingToken),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearTimers(),this.worker.stopSocketIo(),this.worker.dispatchReconnecting(),this.worker.getToken(!0,!1);},t.prototype.onMissedResponse=function(t){this.state===o.Connected?(this.setState(o.RetrievingToken),this.worker.stopPingTimer(),this.worker.clearTimers(),this.worker.stopSocketIo(),this.worker.dispatchReconnecting(),this.worker.getToken(!0,!1)):this.showIgnored(t);},t.prototype.showIgnored=function(t){this.logger.debug("Ignoring event '"+t+"' in state '"+o[this.state]+"'");},t.prototype.setState=function(t){if(this.logger.info("Switching from state '"+o[this.state]+"' to state '"+o[t]+"'"),this.state===t)return void this.logger.error("Attempt to switching into the current state '"+o[t]+"'");this.state=t;},t.prototype.resetAllocationIfNecessary=function(t){this.connectionErrors++,this.connectionErrors>=2||void 0!==t&&/^4\d\d /.test(t)?(this.logger.error("Connection error count is "+this.connectionErrors+" - will reset allocation"),this.connectionErrors=0):this.logger.info("Connection error count is "+this.connectionErrors+" - will NOT reset allocation");},t.prototype.isRegistered=function(){return this.connectedSubstate===c.Registered||this.connectedSubstate===c.Registering},t.prototype.switchToIncallModeIfEnabled=function(){this.incallModeEnabled&&(this.worker.isIncallMode()||(this.worker.enterIncallMode(),this.worker.stopPingTimer(),this.worker.startPingTimer()),this.worker.restartIncallModeTimer());},t}();e.TrouterFsm=a;},function(t,e,n){Object.defineProperty(e,"__esModule",{value:!0});var o=n(1),r=n(0),i=function(){function t(t,e){this.worker=e,this.state=o.TrouterState.Unknown,this.logger=new r.Logger("ManagerFsm",t);}return t.prototype.start=function(){this.state===o.TrouterState.Unknown?(this.setState(o.TrouterState.Disconnected),this.worker.startFirstConnection()):this.showIgnored("start");},t.prototype.stop=function(){this.state!==o.TrouterState.Unknown?(this.setState(o.TrouterState.Unknown),this.worker.stopFirstConnection(!1),this.worker.stopSecondConnection(!1)):this.showIgnored("stop");},t.prototype.getState=function(){return this.state},t.prototype.onConnected=function(t){this.state===o.TrouterState.Disconnected&&t?this.worker.doesSecondConnectionExist()?this.setState(o.TrouterState.Switching):(this.setState(o.TrouterState.Connected),this.worker.dispatchConnected()):this.showIgnored("onConnected("+t+")");},t.prototype.onRegistered=function(t){this.state!==o.TrouterState.Disconnected||t?this.state!==o.TrouterState.Switching||t?this.showIgnored("onRegistered("+t+")"):(this.setState(o.TrouterState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnectionDelayed(),this.worker.dispatchConnected()):(this.setState(o.TrouterState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnection(!0),this.worker.dispatchConnected());},t.prototype.onReconnecting=function(t){this.state===o.TrouterState.Connected&&t?(this.setState(o.TrouterState.Disconnected),this.worker.dispatchReconnecting()):this.state===o.TrouterState.Switching&&t?(this.setState(o.TrouterState.Disconnected),this.worker.dispatchReconnecting()):this.showIgnored("onReconnecting("+t+")");},t.prototype.onReconnectionRequired=function(t){this.state===o.TrouterState.Connected&&t?(this.setState(o.TrouterState.Switching),this.worker.startSecondConnection()):this.state===o.TrouterState.Disconnected&&t?this.worker.startSecondConnection():this.showIgnored("onReconnectionRequired("+t+")");},t.prototype.onDisconnected=function(t){this.state===o.TrouterState.Unknown&&t?this.worker.dispatchStopped():this.showIgnored("onDisconnected("+t+")");},t.prototype.showIgnored=function(t){this.logger.info("Ignoring event '"+t+"' in state '"+o.TrouterState[this.state]+"'");},t.prototype.setState=function(t){if(this.logger.info("Switching from state '"+o.TrouterState[this.state]+"' to state '"+o.TrouterState[t]+"'"),this.state===t)return void this.logger.error("Attempt to switching into the current state '"+o.TrouterState[t]+"'");this.state=t;},t}();e.TrouterManagerFsm=i;},function(t,e,n){function o(t,e){if(!e)return t;var n=a({},t,{enabled:e.TelemetryEnabled});return void 0!==e.ClientTelemetryEventEnabled&&(n=a({},n,e.ClientTelemetryEventEnabled)),n}function r(t,e){return {clientInfo:{ua:t.trouterSettings.productName,v:t.trouterSettings.version},ioOptions:{ackTimeoutMs:5e3},clientCorrelationID:t.trouterSettings.sessionId,environment:t.trouterSettings.environment,telemetrySettings:o(t.telemetryConfig.settings,e),eventLogger:t.telemetryConfig.eventLogger,endpointId:t.trouterSettings.registrationId,trouterUrl:e&&e.TrouterConnectionUrl||t.trouterSettings.trouterServiceUrl,registration:t.trouterSettings.registrarServiceUrl?{registrarUrl:t.trouterSettings.registrarServiceUrl,registrationId:t.trouterSettings.registrationId||"",pnhAppId:t.trouterSettings.pnhAppId||"",platform:t.trouterSettings.platform||"",pnhTemplateKey:t.trouterSettings.pnhTemplate||"",platformUIVersion:t.trouterSettings.platformUIVersion||"",productContext:t.trouterSettings.pnhProductContext||void 0,context:t.trouterSettings.pnhContext||"",registrarTtlSec:(t.trouterSettings.maxRegistrationTimeInMs||0)/1e3}:void 0,timeoutOptions:a({connectionTimeoutMs:t.trouterSettings.trouterConnectTimeoutInMs||3e4,fetchTimeoutMs:1e4,pingTimeoutMs:4e4,pongTimeoutMs:5e3,maxBackoffMs:3e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},t.trouterSettings.timeoutOptions),incallTimeoutOptions:a({connectionTimeoutMs:1e4,fetchTimeoutMs:5e3,pingTimeoutMs:5e3,pongTimeoutMs:2e3,maxBackoffMs:1e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},t.trouterSettings.incallTimeoutOptions),incallModeTimeoutMs:t.trouterSettings.incallModeTimeoutMs||0,lingeringConnectionDelayMs:6e4,userActivitySecondResendDelayMs:t.trouterSettings.userActivitySecondResendDelayMs||1e4}}function i(t){return new y(t)}function s(){return l.CLIENT_VERSION}function c(t,e){var n=t.indexOf("://");if(n>=0){var o=t.indexOf("/",n+3);if(o>=0)return e+t.substr(o)}return ""}var a=this&&this.__assign||Object.assign||function(t){for(var e,n=1,o=arguments.length;n<o;n++){e=arguments[n];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);}return t},u=this&&this.__awaiter||function(t,e,n,o){return new(n||(n=Promise))(function(r,i){function s(t){try{a(o.next(t));}catch(t){i(t);}}function c(t){try{a(o.throw(t));}catch(t){i(t);}}function a(t){t.done?r(t.value):new n(function(e){e(t.value);}).then(s,c);}a((o=o.apply(t,e||[])).next());})},h=this&&this.__generator||function(t,e){function n(t){return function(e){return o([t,e])}}function o(n){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,i&&(s=2&n[0]?i.return:n[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,n[1])).done)return s;switch(i=0,s&&(n=[2&n[0],s.value]),n[0]){case 0:case 1:s=n;break;case 4:return a.label++,{value:n[1],done:!1};case 5:a.label++,i=n[1],n=[0];continue;case 7:n=a.ops.pop(),a.trys.pop();continue;default:if(s=a.trys,!(s=s.length>0&&s[s.length-1])&&(6===n[0]||2===n[0])){a=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]<s[3])){a.label=n[1];break}if(6===n[0]&&a.label<s[1]){a.label=s[1],s=n;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(n);break}s[2]&&a.ops.pop(),a.trys.pop();continue}n=e.call(t,a);}catch(t){n=[6,t],i=0;}finally{r=s=0;}if(5&n[0])throw n[1];return {value:n[0]?n[1]:void 0,done:!0}}var r,i,s,c,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return c={next:n(0),throw:n(1),return:n(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c};Object.defineProperty(e,"__esModule",{value:!0});var l=n(2),p=n(1);e.TrouterState=p.TrouterState,e.UserActivityState=p.UserActivityState;var d=n(0),f=n(6),g=n(7),m=n(8),v=n(9),y=function(){function t(t){this.logProvider=t,this.stateChangedListeners=[],this.logger=new d.Logger("Trouter",t),this.trouterUrlPromise=new v.TrouterUrlPromise(t),this.messageHandlers=new f.MessageHandlerRegistry(t),this.listeners={},this.connectionInfo=null,this.logger.info("Created TrouterService version "+l.CLIENT_VERSION);}return t.prototype.start=function(t){if(this.logger.info("Start"),!t.trouterSettings.disableInternalSkypeTokenCache){var e=t.skypeTokenProvider;t.skypeTokenProvider=g.addCacheAsBackupTo(e);}this.trouterCfg=t;var n=r(t,this.ecsCfg);void 0===this.trouterServer&&(this.trouterServer=new m.TrouterManager(this.logProvider,n,t.skypeTokenProvider,this)),this.trouterServer.start();},t.prototype.stop=function(){this.logger.info("close connection"),this.trouterUrlPromise.rejectUrl(new Error("TrouterService is stopped")),void 0!==this.trouterServer&&this.trouterServer.stop();},t.prototype.setEcsConfig=function(t){return u(this,void 0,void 0,function(){var e=this;return h(this,function(n){return [2,new Promise(function(n,o){if(e.ecsCfg=t.TrouterJScriptClient,e.logger.info("Setting ECS configuration to "+JSON.stringify(e.ecsCfg)),void 0!==e.trouterServer&&void 0!==e.trouterCfg){var i=r(e.trouterCfg,e.ecsCfg);e.trouterServer.configure(i);}n();})]})})},t.prototype.checkConnection=function(t){void 0!==this.trouterServer&&this.trouterServer.checkConnection(t||!1);},t.prototype.resendRegistration=function(){return u(this,void 0,void 0,function(){return h(this,function(t){if(!this.trouterServer)throw new Error("resendRegistration called too early");return [2,this.trouterServer.resendRegistration()]})})},t.prototype.registerListener=function(t,e){return ""===e||"/"!==e[0]||e.indexOf("?")>=0||e.indexOf("#")>=0?(this.logger.error("Listener path '"+e+"' is not valid"),!1):this.listeners[e]?(this.logger.error("Another listener is already registered for path '"+e+"'"),!1):(this.listeners[e]=t,this.logger.debug("Listener for path '"+e+"' registered"),this.connectionInfo&&t.onTrouterConnected(this.connectionInfo.baseEndpointUrl+e,this.connectionInfo),!0)},t.prototype.unregisterListener=function(t){for(var e=[],n=0,o=Object.keys(this.listeners);n<o.length;n++){var r=o[n];this.listeners[r]===t&&e.push(r);}if(0===e.length)return !1;for(var i=0,s=e;i<s.length;i++){var r=s[i];delete this.listeners[r];}return this.logger.debug("Listener for path(s) '"+e.join("', '")+"' unregistered"),!0},t.prototype.onTrouterConnected=function(t,e){this.logger.debug("Trouter is now connected");for(var n=0,o=Object.keys(this.listeners);n<o.length;n++){var r=o[n];try{this.listeners[r].onTrouterConnected(e.baseEndpointUrl+r,e);}catch(t){this.logger.error("Listener '"+r+"' threw an exception from onTrouterConnected(): "+t);}}this.connectionInfo=e,this.trouterUrlPromise.resolveUrl(t),this.notifyStateChanged(p.TrouterState.Connected,{url:t,getRemainingTtlInSec:function(){return e.connectionTtlSec}});},t.prototype.onTrouterDisconnected=function(){this.logger.debug("Trouter is now disconnected"),this.connectionInfo=null;for(var t=0,e=Object.keys(this.listeners);t<e.length;t++){var n=e[t],o=this.listeners[n].onTrouterDisconnected;if(o)try{o();}catch(t){this.logger.error("Listener '"+n+"' threw an exception from onTrouterDisconnected(): "+t);}}this.notifyStateChanged(p.TrouterState.Disconnected);},t.prototype.onTrouterRequest=function(t,e){for(var n="",o=0,r=Object.keys(this.listeners);o<r.length;o++){var i=r[o];t.path.substring(0,i.length)===i&&i.length>n.length&&(n=i);}if(""===n)this.tryMessageHandlers(t,e)||(e.status=404,e.headers={"Trouter-Responder":"ClientLib"},e.send());else try{this.listeners[n].onTrouterRequest(t,e);}catch(t){this.logger.error("Listener '"+n+"' threw an exception from onTrouterRequest(): "+t),e.status=500,e.headers={"Trouter-Responder":"ClientLib"},e.send();}},t.prototype.onTrouterMessageLoss=function(t){this.logger.info("onTrouterMessageLoss called with value "+t);for(var e=!0,n=0,o=Object.keys(this.listeners);n<o.length;n++){var r=o[n],i=this.listeners[r].onTrouterMessageLoss;if(i)try{e=i(t)&&e,void 0===e&&(this.logger.error("Listener '"+r+"' did not response with boolean value onTrouterMessageLoss()"),e=!1);}catch(t){this.logger.error("Listener '"+r+"' threw an exception from onTrouterMessageLoss(): "+t),e=!1;}}return e},t.prototype.setUserActivityState=function(t){if(t!==p.UserActivityState.Active&&t!==p.UserActivityState.Inactive)throw new Error("setUserActivityState called with unsupported value "+t);if(this.logger.info("setUserActivityState called with value "+p.UserActivityState[t]),!this.trouterServer||this.state()===p.TrouterState.Unknown)throw new Error("setUserActivityState called too early");this.trouterServer.setUserActivityState(t);},t.prototype.state=function(){return void 0!==this.trouterServer?this.trouterServer.getState():p.TrouterState.Unknown},t.prototype.getServerState=function(){if(void 0!==this.trouterServer)return this.trouterServer.getServerState()},t.prototype.getTrouterUrlAsync=function(){return void 0!==this.trouterServer?this.trouterUrlPromise.getPromise():Promise.reject(new Error("TrouterService has not been started"))},t.prototype.onStateChanged=function(t){if(this.logger.info("onStateChanged called"),void 0===t)this.stateChangedListeners=this.stateChangedListeners.filter(function(t){return void 0===t.wrappedCallback});else {this.offStateChanged(t);var e=function(e,n){t(e,n?n.url:"");};e.wrappedCallback=t,this.stateChangedListeners.push(e);}},t.prototype.offStateChanged=function(t){this.logger.info("offStateChanged called");var e=this.stateChangedListeners.length;return this.stateChangedListeners=this.stateChangedListeners.filter(function(e){return e.wrappedCallback!==t}),e>this.stateChangedListeners.length},t.prototype.addCallback=function(t){this.logger.info("addListener called"),-1===this.stateChangedListeners.indexOf(t,0)&&void 0!==t&&this.stateChangedListeners.push(t);},t.prototype.removeCallback=function(t){this.logger.info("removeListener called");var e=this.stateChangedListeners.indexOf(t,0);return e>-1&&(this.stateChangedListeners.splice(e,1),!0)},t.prototype.registerMessageHandler=function(t){this.logger.info("registerMessageHandler is called"),this.messageHandlers.register(t);},t.prototype.clearMessageHandlers=function(){this.logger.info("clearMessageHandlers is called"),this.messageHandlers.clear();},t.prototype.notifyStateChanged=function(t,e){var n=this;this.logger.info("notifyStateChanged called, will forward to "+this.stateChangedListeners.length+" listeners"),this.stateChangedListeners.forEach(function(o){try{o(t,e);}catch(t){n.logger.error("Error in callback "+t);}});},t.prototype.tryMessageHandlers=function(t,e){if(!this.messageHandlers.active())return !1;var n,o=null;try{n=JSON.parse(t.body),o=n&&(n.evt||n.eventId)||null;}catch(t){}var r={eventId:o,url:(this.connectionInfo?this.connectionInfo.baseEndpointUrl:"")+t.path,body:n,rawBody:t.body,headers:t.headers},i=this.messageHandlers.handleMessage(r);return !!i.isHandled&&(e.status=i.resultCode,i.responseHeaders&&(e.headers=i.responseHeaders),i.responseBody&&(e.body=i.responseBody),e.send(),!0)},t}();e.TrouterService=y,e.createTrouterService=i,e.getTrouterServiceVersion=s,e.replaceTrouterUrlBase=c;},function(t,e){t.exports=__WEBPACK_EXTERNAL_MODULE_20__;},function(t,e){}])});
  
  });
  
  unwrapExports(tstrouter);
  
  var TrouterUtils = createCommonjsModule(function (module, exports) {
  // Copyright (c) Microsoft Corporation.
  // Licensed under the MIT license.
  exports.__esModule = true;
  var eventIds = new Map([
      ["chatMessageReceived", 200],
      ["typingIndicatorReceived", 245],
      ["readReceiptReceived", 246],
      ["chatMessageEdited", 247],
      ["chatMessageDeleted", 248],
      ["chatThreadCreated", 257],
      ["chatThreadPropertiesUpdated", 258],
      ["chatThreadDeleted", 259],
      ["participantsAdded", 260],
      ["participantsRemoved", 261]
  ]);
  var publicTeamsUserPrefix = '8:orgid:';
  var dodTeamsUserPrefix = '8:dod:';
  var gcchTeamsUserPrefix = '8:gcch:';
  var teamsVisitorUserPrefix = '8:teamsvisitor:';
  var phoneNumberPrefix = '4:';
  var acsUserPrefix = '8:acs:';
  var spoolUserPrefix = '8:spool:';
  exports.toMessageHandler = function (event, listener) {
      var eventId = eventIds.get(event);
      return {
          handleMessage: function (message) {
              var genericPayload = null;
              if (message === null || message === void 0 ? void 0 : message.rawBody) {
                  genericPayload = JSON.parse(message.rawBody);
              }
              if (genericPayload === null || genericPayload._eventId !== eventId) {
                  return undefined;
              }
              var eventPayload = toEventPayload(event, genericPayload);
              if (eventPayload === null) {
                  return undefined;
              }
              listener(eventPayload);
              return { isHandled: true, resultCode: 200 };
          }
      };
  };
  var toEventPayload = function (event, genericPayload) {
      if (event === "chatMessageReceived") {
          var payload = genericPayload;
          var eventPayload = {
              threadId: payload.groupId,
              sender: constructIdentifierKindFromMri(payload.senderId),
              senderDisplayName: payload.senderDisplayName,
              recipient: constructIdentifierKindFromMri("8:" + payload.recipientId),
              id: payload.messageId,
              createdOn: new Date(payload.originalArrivalTime),
              version: payload.version,
              type: payload.messageType,
              message: payload.messageBody
          };
          return eventPayload;
      }
      if (event === "chatMessageEdited") {
          var payload = genericPayload;
          var eventPayload = {
              threadId: payload.groupId,
              sender: constructIdentifierKindFromMri(payload.senderId),
              senderDisplayName: payload.senderDisplayName,
              recipient: constructIdentifierKindFromMri("8:" + payload.recipientId),
              id: payload.messageId,
              createdOn: new Date(payload.originalArrivalTime),
              version: payload.version,
              message: payload.messageBody,
              editedOn: new Date(payload.edittime),
              type: payload.messageType
          };
          return eventPayload;
      }
      if (event === "chatMessageDeleted") {
          var payload = genericPayload;
          var eventPayload = {
              threadId: payload.groupId,
              sender: constructIdentifierKindFromMri(payload.senderId),
              senderDisplayName: payload.senderDisplayName,
              recipient: constructIdentifierKindFromMri("8:" + payload.recipientId),
              id: payload.messageId,
              createdOn: new Date(payload.originalArrivalTime),
              version: payload.version,
              deletedOn: new Date(payload.deletetime),
              type: payload.messageType
          };
          return eventPayload;
      }
      if (event === "typingIndicatorReceived") {
          var payload = genericPayload;
          var eventPayload = {
              threadId: payload.groupId,
              sender: constructIdentifierKindFromMri(payload.senderId),
              senderDisplayName: "",
              recipient: constructIdentifierKindFromMri("8:" + payload.recipientId),
              version: payload.version,
              receivedOn: new Date(payload.originalArrivalTime)
          };
          return eventPayload;
      }
      if (event === "readReceiptReceived") {
          var payload = genericPayload;
          var readReceiptMessageBody = JSON.parse(payload.messageBody);
          var consumptionHorizon = readReceiptMessageBody.consumptionhorizon.split(";");
          var eventPayload = {
              threadId: payload.groupId,
              sender: constructIdentifierKindFromMri(payload.senderId),
              senderDisplayName: "",
              recipient: constructIdentifierKindFromMri("8:" + payload.recipientId),
              chatMessageId: payload.messageId,
              readOn: new Date(+consumptionHorizon[1])
          };
          return eventPayload;
      }
      if (event === "chatThreadCreated") {
          var payload = genericPayload;
          var createdByPayload = JSON.parse(unescape(payload.createdBy));
          var membersPayload = JSON.parse(unescape(payload.members));
          var propertiesPayload = JSON.parse(unescape(payload.properties));
          var createdBy = {
              id: constructIdentifierKindFromMri(createdByPayload.participantId),
              displayName: createdByPayload.displayName
          };
          var chatParticipants = membersPayload.map(function (m) {
              return {
                  id: constructIdentifierKindFromMri(m.participantId),
                  displayName: m.displayName
              };
          });
          var eventPayload = {
              threadId: payload.threadId,
              createdOn: new Date(payload.createTime),
              createdBy: createdBy,
              version: payload.version,
              participants: chatParticipants,
              properties: propertiesPayload
          };
          return eventPayload;
      }
      if (event === "chatThreadPropertiesUpdated") {
          var payload = genericPayload;
          var updatedByPayload = JSON.parse(unescape(payload.editedBy));
          var propertiesPayload = JSON.parse(unescape(payload.properties));
          var updatedBy = {
              id: constructIdentifierKindFromMri(updatedByPayload.participantId),
              displayName: updatedByPayload.displayName
          };
          var eventPayload = {
              threadId: payload.threadId,
              updatedOn: new Date(payload.editTime),
              updatedBy: updatedBy,
              version: payload.version,
              properties: propertiesPayload
          };
          return eventPayload;
      }
      if (event === "chatThreadDeleted") {
          var payload = genericPayload;
          var deletedByPayload = JSON.parse(unescape(payload.deletedBy));
          var deletedBy = {
              id: constructIdentifierKindFromMri(deletedByPayload.participantId),
              displayName: deletedByPayload.displayName
          };
          var eventPayload = {
              threadId: payload.threadId,
              deletedOn: new Date(payload.deleteTime),
              deletedBy: deletedBy,
              version: payload.version
          };
          return eventPayload;
      }
      if (event === "participantsAdded") {
          var payload = genericPayload;
          var addedByPayload = JSON.parse(unescape(payload.addedBy));
          var participantsAddedPayload = JSON.parse(unescape(payload.participantsAdded));
          var addedBy = {
              id: constructIdentifierKindFromMri(addedByPayload.participantId),
              displayName: addedByPayload.displayName
          };
          var chatParticipants = participantsAddedPayload.map(function (m) {
              return {
                  id: constructIdentifierKindFromMri(m.participantId),
                  displayName: m.displayName,
                  shareHistoryTime: new Date(m.shareHistoryTime)
              };
          });
          var eventPayload = {
              threadId: payload.threadId,
              addedOn: new Date(payload.time),
              addedBy: addedBy,
              version: payload.version,
              participantsAdded: chatParticipants
          };
          return eventPayload;
      }
      if (event === "participantsRemoved") {
          var payload = genericPayload;
          var removedByPayload = JSON.parse(unescape(payload.removedBy));
          var participantsRemovedPayload = JSON.parse(unescape(payload.participantsRemoved));
          var removedBy = {
              id: constructIdentifierKindFromMri(removedByPayload.participantId),
              displayName: removedByPayload.displayName
          };
          var chatParticipants = participantsRemovedPayload.map(function (m) {
              return {
                  id: constructIdentifierKindFromMri(m.participantId),
                  displayName: m.displayName,
                  shareHistoryTime: new Date(m.shareHistoryTime)
              };
          });
          var eventPayload = {
              threadId: payload.threadId,
              removedOn: new Date(payload.time),
              removedBy: removedBy,
              version: payload.version,
              participantsRemoved: chatParticipants
          };
          return eventPayload;
      }
      return null;
  };
  exports.toLogProvider = function (logger) {
      return {
          log: function () {
              var message = [];
              for (var _i = 0; _i < arguments.length; _i++) {
                  message[_i] = arguments[_i];
              }
              return logger.info(message);
          },
          warn: function () {
              var message = [];
              for (var _i = 0; _i < arguments.length; _i++) {
                  message[_i] = arguments[_i];
              }
              return logger.warning(message);
          },
          error: function () {
              var message = [];
              for (var _i = 0; _i < arguments.length; _i++) {
                  message[_i] = arguments[_i];
              }
              return logger.error(message);
          },
          debug: function () {
              var message = [];
              for (var _i = 0; _i < arguments.length; _i++) {
                  message[_i] = arguments[_i];
              }
              return logger.verbose(message);
          },
          info: function () {
              var message = [];
              for (var _i = 0; _i < arguments.length; _i++) {
                  message[_i] = arguments[_i];
              }
              return logger.verbose(message);
          }
      };
  };
  exports.toTelemetrySender = function (logger) {
      return {
          logEvent: function (clientEvent) { return logger.info(clientEvent); }
      };
  };
  var constructIdentifierKindFromMri = function (mri) {
      if (mri.startsWith(publicTeamsUserPrefix)) {
          return { kind: "microsoftTeamsUser", rawId: mri, microsoftTeamsUserId: mri.substring(publicTeamsUserPrefix.length), isAnonymous: false, cloud: 'public' };
      }
      else if (mri.startsWith(dodTeamsUserPrefix)) {
          return { kind: "microsoftTeamsUser", rawId: mri, microsoftTeamsUserId: mri.substring(dodTeamsUserPrefix.length), isAnonymous: false, cloud: 'dod' };
      }
      else if (mri.startsWith(gcchTeamsUserPrefix)) {
          return { kind: "microsoftTeamsUser", rawId: mri, microsoftTeamsUserId: mri.substring(gcchTeamsUserPrefix.length), isAnonymous: false, cloud: 'gcch' };
      }
      else if (mri.startsWith(teamsVisitorUserPrefix)) {
          return { kind: "microsoftTeamsUser", rawId: mri, microsoftTeamsUserId: mri.substring(teamsVisitorUserPrefix.length), isAnonymous: true };
      }
      else if (mri.startsWith(phoneNumberPrefix)) {
          return { kind: "phoneNumber", rawId: mri, phoneNumber: mri.substring(phoneNumberPrefix.length) };
      }
      else if (mri.startsWith(acsUserPrefix) || mri.startsWith(spoolUserPrefix)) {
          return { kind: "communicationUser", communicationUserId: mri };
      }
      else {
          return { kind: "unknown", id: mri };
      }
  };
  });
  
  unwrapExports(TrouterUtils);
  var TrouterUtils_1 = TrouterUtils.toMessageHandler;
  var TrouterUtils_2 = TrouterUtils.toLogProvider;
  var TrouterUtils_3 = TrouterUtils.toTelemetrySender;
  
  var TrouterSettings = createCommonjsModule(function (module, exports) {
  exports.__esModule = true;
  
  var defaultSettings = {
      version: "1.0.0",
      registrationId: "",
      sessionId: "",
      pnhAppId: "AcsWeb",
      pnhTemplate: "AcsWeb_Chat_1.0",
      platform: "SPOOL",
      platformUIVersion: "0.0.0",
      environment: "",
      productName: "acs-chat-web",
      trouterServiceUrl: "https://go.trouter.skype.com/v4/a",
      registrarServiceUrl: "https://edge.skype.com/registrar/prod/v3/registrations",
      registrarRefreshTimeoutInMs: 350000,
      timeoutOptions: {
          connectionTimeoutMs: 20000,
          fetchTimeoutMs: 10000,
          pingTimeoutMs: 40000,
          pongTimeoutMs: 5000,
          maxBackoffMs: 50000,
          requestTimeoutMs: 5000
      },
      maxRegistrationTimeInMs: 7200000
  };
  exports.createSettings = function (options) {
      var _a;
      var settings = defaultSettings;
      settings.registrationId = coreHttp.generateUuid();
      settings.sessionId = coreHttp.generateUuid();
      settings.maxRegistrationTimeInMs = (_a = options === null || options === void 0 ? void 0 : options.registrationTimeInMs) !== null && _a !== void 0 ? _a : defaultSettings.maxRegistrationTimeInMs;
      return settings;
  };
  exports.defaultTelemetrySettings = {
      // TBD Can we hook up OpenTelemetry?
      enabled: false
  };
  });
  
  unwrapExports(TrouterSettings);
  var TrouterSettings_1 = TrouterSettings.createSettings;
  var TrouterSettings_2 = TrouterSettings.defaultTelemetrySettings;
  
  var SignalingClient = createCommonjsModule(function (module, exports) {
  // Copyright (c) Microsoft Corporation.
  // Licensed under the MIT license.
  var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
      function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  };
  var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
      var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
      return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
      function verb(n) { return function (v) { return step([n, v]); }; }
      function step(op) {
          if (f) throw new TypeError("Generator is already executing.");
          while (_) try {
              if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
              if (y = 0, t) op = [op[0] & 2, t.value];
              switch (op[0]) {
                  case 0: case 1: t = op; break;
                  case 4: _.label++; return { value: op[1], done: false };
                  case 5: _.label++; y = op[1]; op = [0]; continue;
                  case 7: op = _.ops.pop(); _.trys.pop(); continue;
                  default:
                      if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                      if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                      if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                      if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                      if (t[2]) _.ops.pop();
                      _.trys.pop(); continue;
              }
              op = body.call(thisArg, _);
          } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
          if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
      }
  };
  exports.__esModule = true;
  
  
  
  var ConnectionState;
  (function (ConnectionState) {
      ConnectionState[ConnectionState["Unknown"] = 0] = "Unknown";
      ConnectionState[ConnectionState["Connected"] = 2] = "Connected";
      ConnectionState[ConnectionState["Disconnected"] = 3] = "Disconnected";
      ConnectionState[ConnectionState["Switching"] = 9] = "Switching";
  })(ConnectionState = exports.ConnectionState || (exports.ConnectionState = {}));
  var CommunicationSignalingClient = /** @class */ (function () {
      function CommunicationSignalingClient(credential, logger, options) {
          var _this = this;
          this.logger = logger;
          this.stateChangedListener = null;
          this.trouter = tstrouter.createTrouterService(TrouterUtils.toLogProvider(logger));
          this.config = {
              trouterSettings: TrouterSettings.createSettings(options),
              skypeTokenProvider: function () { return __awaiter(_this, void 0, void 0, function () { var _a, _b; return __generator(this, function (_c) {
                  switch (_c.label) {
                      case 0:
                          _b = (_a = Promise).resolve;
                          return [4 /*yield*/, credential.getToken()];
                      case 1: return [2 /*return*/, _b.apply(_a, [(_c.sent()).token])];
                  }
              }); }); },
              telemetryConfig: {
                  eventLogger: TrouterUtils.toTelemetrySender(logger),
                  settings: TrouterSettings.defaultTelemetrySettings
              }
          };
      }
      CommunicationSignalingClient.prototype.start = function () {
          this.trouter.start(this.config);
      };
      CommunicationSignalingClient.prototype.stop = function () {
          this.trouter.offStateChanged(this.stateChangedListener);
          this.trouter.clearMessageHandlers();
          this.trouter.stop();
      };
      CommunicationSignalingClient.prototype.on = function (event, listener) {
          if (event === "connectionChanged") {
              this.trouter.offStateChanged(this.stateChangedListener);
              this.stateChangedListener = function (state, _url) { return listener(state); };
              this.trouter.onStateChanged(this.stateChangedListener);
              return;
          }
          this.trouter.registerMessageHandler(TrouterUtils.toMessageHandler(event, listener));
      };
      return CommunicationSignalingClient;
  }());
  exports.CommunicationSignalingClient = CommunicationSignalingClient;
  });
  
  unwrapExports(SignalingClient);
  var SignalingClient_1 = SignalingClient.ConnectionState;
  var SignalingClient_2 = SignalingClient.CommunicationSignalingClient;
  
  var src = createCommonjsModule(function (module, exports) {
  // Copyright (c) Microsoft Corporation.
  // Licensed under the MIT license.
  function __export(m) {
      for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  }
  exports.__esModule = true;
  __export(SignalingClient);
  });
  
  var index = unwrapExports(src);
  
  module.exports = index;
  //# sourceMappingURL=index.js.map
  