UNPKG

@testrtc/watchrtc-sdk

Version:

Monitor your WebRTC application by collecting WebRTC statistics from end users

1 lines 306 kB
!function(e,a){"object"==typeof exports&&"object"==typeof module?module.exports=a():"function"==typeof define&&define.amd?define([],a):"object"==typeof exports?exports.watchRTC=a():e.watchRTC=a()}(this,(function(){return(()=>{var e={288:(e,a)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});var n=1e3,r=function(){function e(){this.backoff_delay=n,this.exponentialRetries=0,this.numRetries=0,this.timerId=null,this.waiting=!1}return Object.defineProperty(e.prototype,"delayMs",{get:function(){return this.backoff_delay},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.backoff_delay=n,this.exponentialRetries=0,this.numRetries=0,this.unWait(!0)},e.prototype.next=function(){var e;return this.exponentialRetries=this.exponentialRetries?2*this.exponentialRetries:1,this.backoff_delay=Math.min(128e3,(e=this.exponentialRetries,n*e+Math.floor(3e3*Math.random()))),this.numRetries++,this.backoff_delay},Object.defineProperty(e.prototype,"attempts",{get:function(){return this.numRetries},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"MAX_RETRIES_FOR_FIRST_CONNECTION",{get:function(){return 15},enumerable:!1,configurable:!0}),e.prototype.wait=function(e){this.waiting=!0,this.timerId=e},e.prototype.unWait=function(e){this.waiting=!1,this.timerId&&e&&clearTimeout(this.timerId),this.timerId=null},Object.defineProperty(e.prototype,"isWaiting",{get:function(){return this.waiting},enumerable:!1,configurable:!0}),e}();a.default=r},304:function(e,a){"use strict";var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var a,n=1,r=arguments.length;n<r;n++)for(var o in a=arguments[n])Object.prototype.hasOwnProperty.call(a,o)&&(e[o]=a[o]);return e},n.apply(this,arguments)},r=this&&this.__rest||function(e,a){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&a.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)a.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n};Object.defineProperty(a,"__esModule",{value:!0}),a.extractSuccessCandidatePairsIPs=a.getSuccessCandidatePairIPs=void 0;var o=function(e,a,n){var r=a[n+"CandidateId"];if(r){var o=e[r];if(!o)for(var i=0,d=Object.entries(e);i<d.length;i++){var t=d[i],c=t[0],g=t[1];c.includes(r)&&(o=g)}return o}},i=function(e){var a,n,r,o,i,d,t=(null===(a=null==e?void 0:e.localCandidate)||void 0===a?void 0:a.ip)||(null===(n=null==e?void 0:e.localCandidate)||void 0===n?void 0:n.address)||(null===(r=null==e?void 0:e.localCandidate)||void 0===r?void 0:r.ipAddress),c=(null===(o=null==e?void 0:e.remoteCandidate)||void 0===o?void 0:o.ip)||(null===(i=null==e?void 0:e.remoteCandidate)||void 0===i?void 0:i.address)||(null===(d=null==e?void 0:e.remoteCandidate)||void 0===d?void 0:d.ipAddress);return t&&c?{local:t,remote:c}:null};a.getSuccessCandidatePairIPs=function(e){var a=e.selectedCandidatePairId,n=r(e,["selectedCandidatePairId"]);if(a){var o=n[a];if(c=i(o))return c}else for(var d=0,t=Object.values(n);d<t.length;d++){var c;if(("succeeded"===(o=t[d]).state||(null==o?void 0:o.selected))&&(c=i(o))&&(o.selected||o.activeCandidatePair))return c}return null},a.extractSuccessCandidatePairsIPs=function(e){if(!e)return null;var r=function(e){for(var a=[],n=0,r=Object.entries(e);n<r.length;n++){var o=r[n],i=o[0],d=o[1];"candidate-pair"===(null==d?void 0:d.type)&&a.push(i)}return a}(e);if(!r.length)return null;for(var i={},d=0,t=r;d<t.length;d++){var c=t[d],g=e[c];if(g){var m=o(e,g,"local"),s=o(e,g,"remote");i[c]||(i[c]={}),i[c]=n(n({},g),{localCandidate:m,remoteCandidate:s})}}var l=function(e){for(var a=0,n=Object.values(e);a<n.length;a++){var r=n[a].selectedCandidatePairId;if(r)return r}return null}(e);return l&&(i.selectedCandidatePairId=l),(0,a.getSuccessCandidatePairIPs)(i)}},408:function(e,a){"use strict";var n=this&&this.__awaiter||function(e,a,n,r){return new(n||(n=Promise))((function(o,i){function d(e){try{c(r.next(e))}catch(e){i(e)}}function t(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var a;e.done?o(e.value):(a=e.value,a instanceof n?a:new n((function(e){e(a)}))).then(d,t)}c((r=r.apply(e,a||[])).next())}))},r=this&&this.__generator||function(e,a){var n,r,o,i,d={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:t(0),throw:t(1),return:t(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function t(t){return function(c){return function(t){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,t[0]&&(d=0)),d;)try{if(n=1,r&&(o=2&t[0]?r.return:t[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,t[1])).done)return o;switch(r=0,o&&(t=[2&t[0],o.value]),t[0]){case 0:case 1:o=t;break;case 4:return d.label++,{value:t[1],done:!1};case 5:d.label++,r=t[1],t=[0];continue;case 7:t=d.ops.pop(),d.trys.pop();continue;default:if(!((o=(o=d.trys).length>0&&o[o.length-1])||6!==t[0]&&2!==t[0])){d=0;continue}if(3===t[0]&&(!o||t[1]>o[0]&&t[1]<o[3])){d.label=t[1];break}if(6===t[0]&&d.label<o[1]){d.label=o[1],o=t;break}if(o&&d.label<o[2]){d.label=o[2],d.ops.push(t);break}o[2]&&d.ops.pop(),d.trys.pop();continue}t=a.call(e,d)}catch(e){t=[6,e],r=0}finally{n=o=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,c])}}};Object.defineProperty(a,"__esModule",{value:!0}),a.detectAdvancedPlatform=void 0;var o=/^mozilla\/\d\.\d\W/,i=/(\w+)\/(\d+\.\d+(?:\.\d+)?(?:\.\d+)?)/g,d=/^(cri|gec|edg)/,t=Array.isArray,c="userAgentData"in window.navigator?window.navigator.userAgentData:null,g=window.navigator.userAgent,m={iOS:/iphone/,iPadOS:/ipad|macintosh/,Android:/android/},s={Windows:/win/,macOS:/macintosh/,Linux:/linux/};a.detectAdvancedPlatform=function(e,a){return n(void 0,void 0,void 0,(function(){var n,l,p,u,v,f,h,x,b,y,k,w,S,C,T,q,I,_,z,R,P,L;return r(this,(function(r){switch(r.label){case 0:return g="string"==typeof e?e:g,(c="string"==typeof a?a:c)?[4,c.getHighEntropyValues(["architecture","bitness","brands","mobile","model","platform","platformVersion","uaFullVersion","fullVersionList","wow64"])]:[3,2];case 1:return n=r.sent(),l=n.fullVersionList.find((function(e){var a;return"object"==typeof e&&e.brand&&"Chromium"!==e.brand&&(null===(a=e.brand)||void 0===a||a.includes("Brand"),!0)})),p=l&&l.brand?l.brand.replace("Google ","").replace("Microsoft ",""):n.fullVersionList&&Array.isArray(n.fullVersionList)&&n.fullVersionList.length>0&&n.fullVersionList[0].brand||"unknown",u=n.uaFullVersion,v=n.platform,R=n.platformVersion,f=n.bitness,"Windows"===v&&(h=parseInt(R.split(".")[0]),R=h>=13?11:h>0?10:8),"x86"===n.architecture?"64"===n.bitness?f="x86_64":"32"===n.bitness&&(f="x86"):"arm"===n.architecture?"64"===n.bitness?f="ARM64":"32"===n.bitness&&(f="ARM32"):f=n.architecture+" "+n.bitness,[2,{name:p,version:u,majorVersion:u.split(".")[0],nameMajorVersion:"".concat(p,"/").concat(u.split(".")[0]),os:v,osVersion:R,nameVersion:"".concat(p,"/").concat(u),nameOs:"".concat(p,"/").concat(v),nameVersionOs:"".concat(p,"/").concat(u,"/").concat(v),architecture:f,mobile:n.mobile,model:n.model}];case 2:if(g)return x=g.toLowerCase().replace(o,""),b=Object.keys(m).find((function(e){return m[e].test(x)&&window.navigator.maxTouchPoints>=1})),y=Object.keys(s).find((function(e){return s[e].test(x)})),k=b||y,w=x.match(i),S=/version\/(\d+(\.\d+)*)/,C=x.match(S),T=t(C)?C[1]:null,q=w&&(w.length>2&&d.test(w[1])?1:0),I=w&&w[w.length-1-(q||0)].split("/"),_=I&&I[0],z=T||I&&I[1],R=z,P=x.match(/os (\d+_\d+(_\d+)?)/),"crios"===_&&(_="Chrome",R=P?P[1].replace(/_/g,"."):R),x.includes("edg/")&&(L=x.match(/edg\/(\d+\.\d+)/),_="Edge",z=L&&L[1]),[2,{name:_=(O=_||"").charAt(0).toUpperCase()+O.slice(1),version:z,majorVersion:null==z?void 0:z.split(".")[0],nameMajorVersion:"".concat(_,"/").concat(null==z?void 0:z.split(".")[0]),os:k,osVersion:R,nameVersion:"".concat(_,"/").concat(z),nameOs:"".concat(_,"/").concat(k),nameVersionOs:"".concat(_,"/").concat(z,"/").concat(k)}];r.label=3;case 3:return[2]}var O}))}))}},819:(e,a)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});var n=function(){function e(){this.devices=[]}return e.prototype.setDevices=function(e){if(0!==this.devices.length){var a=function(e,a){function n(e){return e.reduce((function(e,a){return e[a.deviceId]=a,e}),{})}var r=n(a),o=n(e);return{addedDevices:e.filter((function(e){return!r[e.deviceId]})),removedDevices:a.filter((function(e){return!o[e.deviceId]}))}}(e,this.devices);return this.devices=e,a}this.devices=e},e}();a.default=n},607:(e,a,n)=>{"use strict";a.ap=a.Tk=a.Vk=a.b1=a.zP=a.$j=a.dL=a.aM=a.vP=a.xt=a.Zt=a.UN=a.IO=a.zl=a.v6=a.S1=void 0,n(699);var r=n(231),o=n(593);a.S1=function(e,a){e&&e.rtcRoomId&&(0,o.sanitize)(e.rtcRoomId,{propertyName:"rtcRoomId",maxLength:128,protectionType:"hacking"}),e&&e.rtcPeerId&&(0,o.sanitize)(e.rtcPeerId||"",{propertyName:"rtcPeerId",maxLength:128,protectionType:"hacking"}),e&&e.keys&&(Object.keys(e.keys).forEach((function(e){(0,o.sanitize)(e,{propertyName:"keys",maxLength:32,protectionType:"alphanumeric"})})),Object.values(e.keys).forEach((function(e){"string"==typeof e&&(0,o.sanitize)(e,{propertyName:"keys",maxLength:512,protectionType:"hacking"})}))),(0,r.initSDK)(e||{},[""],a)},a.v6=function(e){e.rtcRoomId&&(0,o.sanitize)(e.rtcRoomId,{propertyName:"rtcRoomId",maxLength:128,protectionType:"hacking"}),e.rtcPeerId&&(0,o.sanitize)(e.rtcPeerId||"",{propertyName:"rtcPeerId",maxLength:128,protectionType:"hacking"}),e.keys&&(Object.keys(e.keys).forEach((function(e){(0,o.sanitize)(e,{propertyName:"keys",maxLength:32,protectionType:"alphanumeric"})})),Object.values(e.keys).forEach((function(e){"string"==typeof e&&(0,o.sanitize)(e,{propertyName:"keys",maxLength:512,protectionType:"hacking"})}))),(0,r.setConfig)(e)},a.zl=function(e){},a.IO=function(e,a){a&&(0,o.sanitize)(a,{propertyName:"comment",maxLength:2e3,protectionType:"hacking"}),(0,r.setUserRating)(e,a)},a.UN=function(e){Object.keys(e).forEach((function(e){(0,o.sanitize)(e,{propertyName:"keys",maxLength:32,protectionType:"alphanumeric"})})),Object.values(e).forEach((function(e){"string"==typeof e&&(0,o.sanitize)(e,{propertyName:"keys",maxLength:512,protectionType:"hacking"})})),(0,r.addKeys)(e)},a.Zt=function(){(0,r.disableDataCollection)()},a.xt=function(){(0,r.enableDataCollection)()},a.vP=function(e){e.name&&(0,o.sanitize)(e.name,{propertyName:"event",maxLength:128,protectionType:"hacking"}),e.parameters&&"object"==typeof e.parameters&&Object.values(e.parameters).forEach((function(e){"string"==typeof e&&(0,o.sanitize)(e,{propertyName:"event",maxLength:128,protectionType:"hacking"})})),(0,r.addEvent)(e)},a.aM=function(e,a){(0,o.sanitize)(a,{propertyName:"name",maxLength:128,protectionType:"hacking"}),(0,r.mapStream)(e,a)},a.dL=function(e,a){(0,o.sanitize)(a,{propertyName:"name",maxLength:128,protectionType:"hacking"}),(0,r.mapTrack)(e,a)},a.$j=function(){(0,r.connect)()},a.zP=function(){(0,r.disconnect)()},a.b1=function(e){(0,r.registerOnStatsListener)(e)},a.Vk=function(e){(0,r.persistentEnd)(e)},a.Tk=function(e,a){(0,o.sanitize)(e,{propertyName:"roomId",maxLength:128,protectionType:"hacking"}),(0,o.sanitize)(e,{propertyName:"peerId",maxLength:128,protectionType:"hacking"}),(0,r.persistentStart)(e,a)},a.ap=function(e){(0,r.registerStateListener)(e)},a.default={init:a.S1,addTags:a.zl,setUserRating:a.IO,addKeys:a.UN,setConfig:a.v6,disableDataCollection:a.Zt,enableDataCollection:a.xt,addEvent:a.vP,mapStream:a.aM,mapTrack:a.dL,connect:a.$j,disconnect:a.zP,addStatsListener:a.b1,persistentEnd:a.Vk,persistentStart:a.Tk,addStateListener:a.ap,qualityrtc:{run:r.qrtcRun,stop:r.qrtcStop}}},231:function(e,a,n){"use strict";var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var a,n=1,r=arguments.length;n<r;n++)for(var o in a=arguments[n])Object.prototype.hasOwnProperty.call(a,o)&&(e[o]=a[o]);return e},r.apply(this,arguments)},o=this&&this.__awaiter||function(e,a,n,r){return new(n||(n=Promise))((function(o,i){function d(e){try{c(r.next(e))}catch(e){i(e)}}function t(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var a;e.done?o(e.value):(a=e.value,a instanceof n?a:new n((function(e){e(a)}))).then(d,t)}c((r=r.apply(e,a||[])).next())}))},i=this&&this.__generator||function(e,a){var n,r,o,i,d={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:t(0),throw:t(1),return:t(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function t(t){return function(c){return function(t){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,t[0]&&(d=0)),d;)try{if(n=1,r&&(o=2&t[0]?r.return:t[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,t[1])).done)return o;switch(r=0,o&&(t=[2&t[0],o.value]),t[0]){case 0:case 1:o=t;break;case 4:return d.label++,{value:t[1],done:!1};case 5:d.label++,r=t[1],t=[0];continue;case 7:t=d.ops.pop(),d.trys.pop();continue;default:if(!((o=(o=d.trys).length>0&&o[o.length-1])||6!==t[0]&&2!==t[0])){d=0;continue}if(3===t[0]&&(!o||t[1]>o[0]&&t[1]<o[3])){d.label=t[1];break}if(6===t[0]&&d.label<o[1]){d.label=o[1],o=t;break}if(o&&d.label<o[2]){d.label=o[2],d.ops.push(t);break}o[2]&&d.ops.pop(),d.trys.pop();continue}t=a.call(e,d)}catch(e){t=[6,e],r=0}finally{n=o=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,c])}}},d=this&&this.__spreadArray||function(e,a,n){if(n||2===arguments.length)for(var r,o=0,i=a.length;o<i;o++)!r&&o in a||(r||(r=Array.prototype.slice.call(a,0,o)),r[o]=a[o]);return e.concat(r||Array.prototype.slice.call(a))},t=this;Object.defineProperty(a,"__esModule",{value:!0}),a.qrtcStop=a.qrtcRun=a.persistentStart=a.persistentEnd=a.registerStateListener=a.registerOnStatsListener=a.disconnect=a.connect=a.mapPC=a.mapTrack=a.mapStream=a.addEvent=a.enableDataCollection=a.disableDataCollection=a.addKeys=a.setUserRating=a.setConfig=a.initSDK=a.sdkLogWithoutTrace=a.sdkLog=void 0;var c,g,m,s,l=n(85),p=n(911),u=n(593),v=n(288),f=n(912),h=n(412),x=n(304),b=n(408),y=n(819),k="undefined"!=typeof window,w=k?window:n.g,S=!!k&&!!w.mozRTCPeerConnection,C=(!!k&&!S&&w.RTCPeerConnection&&w.navigator.webkitGetUserMedia,{}),T=0,q=0,I={},_={rtcRoomId:void 0,rtcPeerId:void 0,projectId:void 0},z=null,R=null,P=null,L=0,O=!1,j=!1,D=0,E=!1,M=!1,N=null,A=null,U=!0,W=new v.default,F=new f.default,J=!1,K=new y.default,V="",B=!1;a.sdkLog=(0,u.getSdkLogger)((function(){return null==z?void 0:z.logLevel})),a.sdkLogWithoutTrace=(0,u.getSdkLogWithoutTrace)((function(){return null==z?void 0:z.logLevel}));var G=function(e){return e?"".concat(e.kind,":").concat(e.id," state:").concat(e.readyState," muted:").concat(e.muted," label:").concat(e.label):"no track"},H={},$=function(e){var n,d,t=e.forceRecreate,g=void 0!==t&&t,s=e.reconnecting,l=void 0!==s&&s,p=e.pcId,v=void 0===p?"PC_unknown":p,f=e.nailUp,x=void 0!==f&&f;if(null==P?void 0:P.isDisabledDataCollection())(0,a.sdkLog)("debug","connection ignored - disabledDataCollection [".concat(v,"]"));else if((0,a.sdkLog)("debug","connection requested by [".concat(v,"]"),{forceRecreate:g,reconnecting:l,isManualDisconnect:M,isManualConnect:E,tryingToConnectSocket:O,watchrtcConfig:JSON.stringify(z),disabled:null==P?void 0:P.isDisabledDataCollection(),openChannels:JSON.stringify(C)}),W.isWaiting)(0,a.sdkLog)("debug","connection ignored - already waiting for a new attempt");else{var y=(null===(d=null==P?void 0:P.connection)||void 0===d?void 0:d.readyState)===w.WebSocket.OPEN;if(E||!M||y){if(M=!1,y){if(!(0,u.isRoomIdOrPeerIdChanged)(_,z)||!g)return void(0,a.sdkLog)("debug","connection ignored - already opened [".concat(v,"]"));(0,a.sdkLog)("debug","connection ignored - already connected but RoomId or PeerId changed. Closing WS connection. [".concat(v,"]")),null==P||P.close()}var k=(0,u.countOfValidConnections)(C);if(!E&&k<1&&!O)(0,a.sdkLog)("debug","connection ignored - previous connect call not finished or missing peer connection [".concat(v,"]"),{openChannels:JSON.stringify(C),connectionCount:k,tryingToConnectSocket:O,isManualConnect:E});else{if(!(0,u.validateConfig)(z))return O=!1,(0,a.sdkLog)("error","connection ignored - invalid config [".concat(v,"]"),{watchrtcConfig:z}),void(A&&A({connectionStatus:"disconnected",reason:V="clientRejectedNoRetry"}));z.keys&&Object.keys(z.keys||{}).forEach((function(e){"string"==typeof z.keys[e]&&(z.keys[e]=[z.keys[e]])}));var S=!!z.rtcToken,T=(0,u.getConnectionData)("ws",S?z.rtcToken:z.rtcApiKey,z.proxyUrl);P||(0,a.sdkLog)("debug","connection ignored - socket wasn't initialized [".concat(v,"]")),O=!0,(0,a.sdkLog)("info","connecting... [".concat(v,"]")),X(x);var q=Date.now(),R=((n={})[S?"token":"apiKey"]=T.key,n.timestamp=Date.now().toString(),n.apiVersion="v1",n.sessionId=w.watchRTCSessionId,n.newConnection=U?"true":"false",n),L=Object.entries(R).map((function(e){var a=e[0],n=e[1];return"".concat(a,"=").concat(n)})).join("&");null==P||P.connect({url:"".concat(T.url,"?").concat(L),options:{cleanOldTraces:U},onData:function(e){return o(void 0,void 0,void 0,(function(){var n,o,d,t,g,s,p,f;return i(this,(function(i){switch(i.label){case 0:for(n=0,o=Object.entries(e);n<o.length;n++)d=o[n],t=d[0],g=d[1],I[t]=g;return _.projectId=e.projectId,O=!1,z.allowBrowserLogCollection=Boolean(e.collectConsoleLogEnabled),z.allowBrowserLogCollection?!(null===(f=null==z?void 0:z.console)||void 0===f?void 0:f.override)&&e.collectConsoleLogLevel&&(0,u.setConsoleLevel)(e.collectConsoleLogLevel,c):((0,u.restoreOriginalConsoleMethods)(),(null==P?void 0:P.buffer)&&(P.buffer=P.buffer.filter((function(e){return"log"!==e[0]})))),(0,a.sdkLog)("info","connection established - watchRTCConnectionId: ".concat(e.connectionId," sdkVersion:").concat(h.default," [").concat(v,"]")),e.interval!==z.collectionInterval&&(s=z.collectionInterval,z.collectionInterval=e.interval,ee(),X(),(0,a.sdkLog)("error","Collection interval mismatch - connection state reset"),c({data:["collectionIntervalChange",null,{oldInterval:s}]})),c({data:["watchrtc",v,r(r(r({},z),e),{agentId:w.watchRTCAgentId,sdkVersion:h.default})]}),l&&((0,a.sdkLogWithoutTrace)("debug","reconnect"),c({data:["reconnect",null,null]}),(0,a.addEvent)({name:"reconnect",type:"local"})),m&&c({data:["hardware",null,m]}),[4,(0,b.detectAdvancedPlatform)(navigator.userAgent,navigator.userAgentData)];case 1:return p=i.sent(),(0,a.sdkLogWithoutTrace)("debug","advanced userAgent",p),c({data:["userAgentData",null,p]}),[2]}}))}))},onError:function(e,n){(0,a.sdkLogWithoutTrace)("debug","connection - onError ".concat(n)),"auth"===n?(j=!0,O=!1,V="serverRejectedNoRetry"):"connection"===n?V="cantConnectToServer":"timeout"===n&&(V="connectedNotResponding")},onOpen:function(){if(U=!1,V="",A&&A({connectionStatus:"connected"}),l){var e=Date.now()-D;c({data:["reconnectDuration",null,e]})}j=!1;var n=Date.now()-q;(0,a.sdkLog)("info","connection opened. Opening time - ".concat(n," ms [").concat(v,"]").concat(W.attempts>0?" - retried ".concat(W.attempts," times}"):"")),W.reset()},onClose:function(e){V=V||"disconnectedPrematurely",A&&A({connectionStatus:"disconnected",reason:V}),(0,a.sdkLog)(["applicationDisconnected"].includes(V)?"info":"error","connection closed - reason: ".concat(V," | watchRTCConnectionId: ").concat((null==I?void 0:I.connectionId)||"null"," [").concat(v,"]"));var n=e.code,r=e.reason,o=e.wasClean;if((0,a.sdkLogWithoutTrace)("debug","close event. authFailed: ".concat(j," code: ").concat(n," reason: ").concat(r," wasClean: ").concat(o," connectionStateReason: ").concat(V),{authFailed:j,code:n,reason:r,wasClean:o}),j)(0,a.sdkLogWithoutTrace)("debug","websocket authFailed");else if(!M&&!["applicationDisconnected"].includes(V)){var i=W.next();(0,a.sdkLogWithoutTrace)("debug","reconnecting - wait ".concat(i,"ms before new attempt ").concat(W.attempts)),D=Date.now();var d=setTimeout((function(){W.unWait(!1),$({reconnecting:!0,pcId:v})}),i);W.wait(d)}},onNewReference:function(e){(0,a.sdkLogWithoutTrace)("debug","update new stats ref");for(var n=0,r=Object.values(C);n<r.length;n++)r[n].statsRef=e}})}}else(0,a.sdkLog)("debug","connection ignored - already closed and should not be reopened. [".concat(v,"]"))}},X=function(e){return void 0===e&&(e=!1),o(void 0,void 0,void 0,(function(){var n,d,t,m,s;return i(this,(function(l){switch(l.label){case 0:return n=function(){return o(void 0,void 0,void 0,(function(){var e,n,o,d,t,m,s,l,p;return i(this,(function(i){switch(i.label){case 0:return 0!==(0,u.countOfValidConnections)(C)?[3,1]:((null==z?void 0:z.logGetStats)&&(0,a.sdkLog)("debug","getStatsInterval. No valid connections at this time"),L&&L+2e4<Date.now()&&(U=!0,O=!1,w.clearInterval(g),V="applicationDisconnected",null==P||P.close(),(0,a.sdkLog)("info","Last connection closed. watchRTCConnectionId: ".concat(null==I?void 0:I.connectionId," sdkVersion: ").concat(h.default))),[3,8]);case 1:return L=Date.now(),e={connections:{},streams:{}},B&&z.collectionInterval>u.TESTRTC_COMPANION_STATS_TIMEOUT?[4,(0,u.getTestRTCCompanionStats)()]:[3,3];case 2:(n=i.sent())&&(o=(0,u.companionStatsToReport)(n),(0,a.sdkLogWithoutTrace)("debug","getStatsInterval. hardware",o),c({data:["hardwareStats",null,o]})),i.label=3;case 3:d=0,t=Object.values(C),i.label=4;case 4:return d<t.length?(m=t[d],(null==z?void 0:z.logGetStats)&&(0,a.sdkLogWithoutTrace)("debug","getStatsInterval. ".concat(m.id," signalingState: ").concat(m.pc.signalingState)),"closed"===m.pc.signalingState?[3,6]:[4,Z(m)]):[3,7];case 5:s=i.sent(),l=s.peer,p=s.streams,e.connections=r(r({},e.connections),l),e.streams=r(r({},e.streams),p),i.label=6;case 6:return d++,[3,4];case 7:N&&N(e),i.label=8;case 8:return[2]}}))}))},g?[3,2]:[4,n()];case 1:return l.sent(),[3,3];case 2:w.clearInterval(g),l.label=3;case 3:if(e)for((0,a.sdkLogWithoutTrace)("debug","startStatsCollection - nail up"),d=function(e){"closed"!==e.pc.signalingState&&e.pc.getStats(null).then((function(a){var n={};S?a.forEach((function(e){n["".concat(e.type,"_").concat(e.id)]=e})):n=(0,u.map2obj)(a),e.statsRef=JSON.parse(JSON.stringify(n))}))},t=0,m=Object.values(C);t<m.length;t++)s=m[t],d(s);return g=w.setInterval((function(){return o(this,void 0,void 0,(function(){return i(this,(function(e){switch(e.label){case 0:return[4,n()];case 1:return e.sent(),[2]}}))}))}),z.collectionInterval),[2]}}))}))},Z=function(e){return new Promise((function(n,r){if(e){var o=e.id,i=e.pc,d=e.prev,t=e.statsRef;i.getStats(null).then((function(r){(null==z?void 0:z.logGetStats)&&(0,a.sdkLogWithoutTrace)("debug","getStats res",{res:r});var i={};S?r.forEach((function(e){i["".concat(e.type,"_").concat(e.id)]=e})):i=(0,u.map2obj)(r);var g=JSON.parse(JSON.stringify(i));if(i=(0,u.applyPatchForRTT)(d,i),g.getStatsId=++q,F.stash(g),t&&(i=(0,u.subtractNailUpReferenceStats)(t,i)),!J){var m=(0,x.extractSuccessCandidatePairsIPs)(i);m&&(J=!0,c({data:["candidatePairIPs",o,m]}))}var s=(0,u.deltaCompression)(d,i);s.getStatsId=g.getStatsId,(null==z?void 0:z.logGetStats)&&(0,a.sdkLogWithoutTrace)("debug","getStats(null) [".concat(o,"]"),{data:s}),null!==(null==s?void 0:s.timestamp)&&(null==s?void 0:s.timestamp)!==-1/0?c({data:["getstats",o,s]}):c({data:["nostats",null,null]}),e.prev=g,n((0,u.exposeApplicationStatsForPC)(o,d,i,H))}))}}))};a.initSDK=function(e,n,d){var g,v;if(w.watchRTCInitialized)(0,a.sdkLogWithoutTrace)("info","init. watchRTC SDK already has been initialized");else if(w.RTCPeerConnection){if(!(-1!==w.RTCPeerConnection.toString().indexOf("[native code]"))&&k&&(0,a.sdkLog)("info","init. RTCPeerConnection object has been already overridden"),w.watchRTCInitialized=!0,w.watchRTCSessionId=(0,u.generateID)(),w.watchRTCAgentId=(0,u.generateID)(),setTimeout((function(){return o(void 0,void 0,void 0,(function(){var e,n,r,o,d,t;return i(this,(function(i){switch(i.label){case 0:return i.trys.push([0,5,,6]),e=Date.now(),[4,(0,u.getHardwareInfo)()];case 1:return n=i.sent(),(r=Date.now()-e)<=5e4?(m=n,(0,a.sdkLog)("debug","getHardware",{hardwareInfo:m})):(0,a.sdkLog)("debug","getHardware failure: getHardwareTime: ".concat(r),{hardwareInfo:m}),[4,(0,u.getTestRTCCompanionInfo)()];case 2:return o=i.sent(),(B=Boolean(o))?[4,(0,u.getTestRTCCompanionStats)()]:[3,4];case 3:d=i.sent(),m.testrtcCompanion={info:o,stats:d},i.label=4;case 4:return[3,6];case 5:return t=i.sent(),(0,a.sdkLog)("error","Error. Get hardware info: ".concat(t.message)),[3,6];case 6:return[2]}}))}))}),0),k){var f=new URLSearchParams(location.search);f.has("watchrtc")&&"debug"===f.get("watchrtc")&&(e.logLevel="debug")}if(P=(null==d?void 0:d.socketService)||new l.default,R=(null==d?void 0:d.httpService)||new p.default,e.collectionInterval=null!==(g=e.collectionInterval)&&void 0!==g?g:8e3,e.logLevel=e.logLevel||"info",z=e,_.rtcRoomId=z.rtcRoomId,_.rtcPeerId=z.rtcPeerId,c=P.trace,P.setStatsStorage(F),z.wsUrl&&(0,a.sdkLog)("info",'"wsUrl" config property is deprecated. Use "proxyUrl" instead of it'),z.proxyUrl&&(0,a.sdkLog)("info",'"proxyUrl" is used'),(null==z?void 0:z.debug)&&(0,a.sdkLog)("info",'"debug" config property is deprecated. Use "logLevel" instead of it'),n.forEach((function(e){if(w[e+"RTCPeerConnection"]){var n=w[e+"RTCPeerConnection"],o=function(e,o){(null==e?void 0:e.watchrtc)&&(z=r(r({},z),e.watchrtc),_.rtcRoomId=z.rtcRoomId,_.rtcPeerId=z.rtcPeerId);var i=new n(e,o),d="PC_"+T++;return i.__rtcStatsId=d,i.__localTracks=[],C[d]={id:d,pc:i,validConnection:!1},e||(e={nullConfig:!0}),((e=JSON.parse(JSON.stringify(e)))&&e.iceServers||[]).forEach((function(e){delete e.credential})),(null==e?void 0:e.watchrtc)&&delete e.watchrtc,e.browserType=S?"moz":"webkit",(0,a.sdkLog)("debug","new RTCPeerConnection called.",{config:JSON.stringify(e),constraints:o}),c({data:["create",d,e]}),o&&c({data:["constraints",d,o]}),i.addEventListener("icecandidate",(function(e){(0,a.sdkLogWithoutTrace)("debug","onicecandidate id:[".concat(d,"], candidate:[").concat(e.candidate,"]")),c({data:["onicecandidate",d,e.candidate]})})),i.addEventListener("icecandidateerror",(function(e){(0,a.sdkLogWithoutTrace)("debug","onicecandidateerror id:[".concat(d,"], error:[").concat(e.errorCode,":").concat(e.errorText,"]")),c({data:["onicecandidateerror",d,"".concat(e.errorCode,":").concat(e.errorText)]})})),i.addEventListener("addstream",(function(e){c({data:["onaddstream",d,e.stream.id+" "+e.stream.getTracks().map((function(e){return e.kind+":"+e.id}))]})})),i.addEventListener("track",(function(e){c({data:["ontrack",d,G(e.track)+" "+e.streams.map((function(e){return"stream:"+e.id}))]}),i.__localTracks||(i.__localTracks=[]),i.__localTracks.push(e.track),e.track.addEventListener("ended",i.__trackPC.call(t,e.streams))})),i.addEventListener("removestream",(function(e){c({data:["onremovestream",d,e.stream.id+" "+e.stream.getTracks().map((function(e){return e.kind+":"+e.id}))]})})),i.addEventListener("signalingstatechange",(function(){C[d]&&!C[d].validConnection?setTimeout((function(){"closed"!==i.connectionState&&"closed"!==i.iceConnectionState?(0,u.existingOtherValidConnection)(C,d)?(0,a.sdkLogWithoutTrace)("debug","signalingstatechange id:[".concat(d,"]. WS connection opening not triggered - multiple valid connections"),{openChannels:JSON.stringify(C)}):C[d].validConnection?(0,a.sdkLogWithoutTrace)("debug","signalingstatechange id:[".concat(d,"]. WS connection opening not triggered - connection already opened"),{openChannels:JSON.stringify(C)}):(C[d].validConnection=!0,(0,a.sdkLogWithoutTrace)("debug","signalingstatechange id:[".concat(d,"]. forceRecreate websocket connection"),{openChannels:JSON.stringify(C)}),$({forceRecreate:!0,pcId:d})):(0,a.sdkLogWithoutTrace)("debug","signalingstatechange id:[".concat(d,"] peer connection closed - don't try to open a connection"),{openChannels:JSON.stringify(C)})}),3e3):(0,a.sdkLog)("debug","signalingstatechange id:[".concat(d,"]. WS connection opening not triggered - peer connection not in channels or was already opened"),{openChannels:JSON.stringify(C)}),c({data:["onsignalingstatechange",d,i.signalingState]})})),i.addEventListener("iceconnectionstatechange",(function(){(0,a.sdkLogWithoutTrace)("debug","oniceconnectionstatechange id:[".concat(d,"], state:[").concat(i.iceConnectionState,"]")),c({data:["oniceconnectionstatechange",d,i.iceConnectionState]})})),i.addEventListener("icegatheringstatechange",(function(){(0,a.sdkLogWithoutTrace)("debug","onicegatheringstatechange id:[".concat(d,"], state:[").concat(i.iceGatheringState,"]")),c({data:["onicegatheringstatechange",d,i.iceGatheringState]})})),i.addEventListener("connectionstatechange",(function(){(0,a.sdkLogWithoutTrace)("debug","onconnectionstatechange id:[".concat(d,"], state:[").concat(i.connectionState,"]")),c({data:["onconnectionstatechange",d,i.connectionState]})})),i.addEventListener("negotiationneeded",(function(){(0,a.sdkLogWithoutTrace)("debug","onnegotiationneeded id:[".concat(d,"]")),c({data:["onnegotiationneeded",d,void 0]})})),i.addEventListener("datachannel",(function(e){(0,a.sdkLogWithoutTrace)("debug","ondatachannel id:[".concat(d,"], data:[").concat(e.channel.id," ").concat(e.channel.label,"]")),c({data:["ondatachannel",d,[e.channel.id,e.channel.label]]})})),i.__trackPC=function(e,a){a&&!Array.isArray(a)?c({data:["onlocaltrack",this.__rtcStatsId,"".concat(G(e)).concat(a?" "+a.id:"")]}):a&&Array.isArray(a)?c({data:["onlocaltrack",this.__rtcStatsId,"".concat(G(e)).concat(a?" "+a.map((function(e){return"stream:"+e.id})):"")]}):c({data:["onlocaltrack",this.__rtcStatsId,G(e)]})},(0,a.sdkLogWithoutTrace)("debug","RTCPeerConnection override complete [".concat(d,"].")),i};if("HTMLMediaElement"in w&&"setSinkId"in HTMLMediaElement.prototype){var i=HTMLMediaElement.prototype.setSinkId;HTMLMediaElement.prototype.setSinkId=function(){var e=arguments[0];return navigator.mediaDevices.enumerateDevices().then((function(a){var n=a.find((function(a){return a.deviceId===e}));n&&n.deviceId!==s&&c({data:["audioOutputChange",null,n.label]}),s=e})).catch((function(e){(0,a.sdkLog)("debug",e.message,{error:e})})),i.apply(this,arguments)}}if("RTCRtpTransceiver"in w&&"setCodecPreferences"in w.RTCRtpTransceiver.prototype){var d=w.RTCRtpTransceiver,g=d.prototype.setCodecPreferences;d.prototype.setCodecPreferences=function(){return c({data:["setCodecPreferences",this.__pcId,arguments]}),g.apply(this,arguments)}}if("RTCRtpSender"in w&&"setParameters"in w.RTCRtpSender.prototype){var m=(l=w.RTCRtpSender).prototype.setParameters;l.prototype.setParameters=function(){return c({data:["setParameters",this.__pcId,arguments]}),m.apply(this,arguments)}}if("RTCRtpSender"in w&&"replaceTrack"in w.RTCRtpSender.prototype){var l,p=(l=w.RTCRtpSender).prototype.replaceTrack;l.prototype.replaceTrack=function(){var e=arguments[0];if(e){c({data:["replaceTrack",this.__pcId,G(e)]});var a=this.track;a&&a.label!==e.label&&c({data:["".concat(e.kind,"InputChange"),this.__pcId,e.label]})}else c({data:["replaceTrack",this.__pcId,null]});return p.apply(this,arguments)}}["addTransceiver"].forEach((function(e){var a=n.prototype[e];a&&(n.prototype[e]=function(){var n="";arguments[1]&&arguments[1].streams&&(n=arguments[1].streams.map((function(e){return"stream:"+e.id})).join(";"));var o="string"==typeof arguments[0]?arguments[0]:arguments[0].kind+":"+arguments[0].id+" "+arguments[0].label,i=arguments[1]?r(r({},arguments[1]),{streams:n}):null;c({data:[e,this.__rtcStatsId,[o,i]]});var d=a.apply(this,arguments);d.sender.__pcId=this.__rtcStatsId;var t=arguments[0];return"object"==typeof t&&(c({data:["onlocaltrack",this.__rtcStatsId,G(t)]}),this.__localTracks||(this.__localTracks=[]),this.__localTracks.push(t),t.addEventListener("ended",this.__trackPC.call(this,t))),d})})),["createDataChannel","restartIce"].forEach((function(e){var a=n.prototype[e];a&&(n.prototype[e]=function(){return c({data:[e,this.__rtcStatsId,arguments]}),a.apply(this,arguments)})})),["close"].forEach((function(e){var r=n.prototype[e];r&&(n.prototype[e]=function(){if(c({data:[e,this.__rtcStatsId,arguments]}),delete C[this.__rtcStatsId],this.__localTracks){for(var n=void 0;n=this.__localTracks.pop();)n.removeEventListener("ended",this.__trackPC),n=null;delete this.__localTracks}return(0,a.sdkLog)("debug","on RTCPeerConnection(".concat(this.__rtcStatsId,") close")),r.apply(this,arguments)})})),["addStream","removeStream"].forEach((function(e){var a=n.prototype[e];a&&(n.prototype[e]=function(){var n=this,r=arguments[0],o=r.getTracks().map((function(e){return e.kind+":"+e.id})).join(",");return c({data:[e,this.__rtcStatsId,r.id+" "+o]}),"addStream"===e&&r.getTracks().map((function(e){c({data:["onlocaltrack",n.__rtcStatsId,G(e)+" "+r.id]}),n.__localTracks||(n.__localTracks=[]),n.__localTracks.push(e),e.addEventListener("ended",n.__trackPC.call(n,e,r))})),a.apply(this,arguments)})})),["addTrack"].forEach((function(e){var a=n.prototype[e];a&&(n.prototype[e]=function(){var n=this,r=arguments[0],o=[].slice.call(arguments,1);c({data:[e,this.__rtcStatsId,G(r)+" "+(o.map((function(e){return"stream:"+e.id})).join(";")||"-")]}),c({data:["onlocaltrack",this.__rtcStatsId,G(r)+" "+o.map((function(e){return"stream:"+e.id}))]}),this.__localTracks||(this.__localTracks=[]),this.__localTracks.push(r),r.addEventListener("ended",this.__trackPC.call(this,r,o));var i=a.apply(this,arguments);i.__pcId=this.__rtcStatsId;var d=this.getTransceivers();return d&&d.forEach((function(e){e.__pcId=n.__rtcStatsId})),i})})),["removeTrack"].forEach((function(e){var a=n.prototype[e];a&&(n.prototype[e]=function(){var n=arguments[0].track;return c({data:[e,this.__rtcStatsId,n?G(n):"null"]}),a.apply(this,arguments)})})),["createOffer","createAnswer"].forEach((function(e){var r=n.prototype[e];r&&(n.prototype[e]=function(){var n,o=this.__rtcStatsId,i=arguments;return 1===arguments.length&&"object"==typeof arguments[0]?n=arguments[0]:3===arguments.length&&"object"==typeof arguments[2]&&(n=arguments[2]),c({data:[e,this.__rtcStatsId,n]}),"createOffer"===e&&n&&!0===n.iceRestart&&(0,a.addEvent)({name:"ice-restart",type:"local"}),r.apply(this,n?[n]:void 0).then((function(a){if(c({data:[e+"OnSuccess",o,a]}),!(i.length>0&&"function"==typeof i[0]))return a;i[0].apply(null,[a])}),(function(a){if(c({data:[e+"OnFailure",o,a.toString()]}),!(i.length>1&&"function"==typeof i[1]))throw a;i[1].apply(null,[a])}))})})),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(e){var a=n.prototype[e];a&&(n.prototype[e]=function(){var n=this.__rtcStatsId,r=arguments,o=this,i="setLocalDescription"===e&&(!r[0]||r[0]&&!r[0].sdp);return c({data:[e,this.__rtcStatsId,i?{parameterless:!0}:r[0]]}),a.apply(this,[r[0]]).then((function(){c({data:[e+"OnSuccess",n,i?null==o?void 0:o.localDescription:void 0]}),r.length>=2&&"function"==typeof r[1]&&r[1].apply(null,[])}),(function(a){if(c({data:[e+"OnFailure",n,a.toString()]}),!(r.length>=3&&"function"==typeof r[2]))throw a;r[2].apply(null,[a])}))})})),n.generateCertificate&&Object.defineProperty(o,"generateCertificate",{get:function(){return arguments.length?n.generateCertificate.apply(null,arguments):n.generateCertificate}}),w[e+"RTCPeerConnection"]=o,w[e+"RTCPeerConnection"].prototype=n.prototype,(0,a.sdkLogWithoutTrace)("debug","RTCPeerConnection prefixes override complete")}else(0,a.sdkLogWithoutTrace)("debug","RTCPeerConnection prefixes override failed")})),k){if(n.forEach((function(e){var a=e+(e.length?"GetUserMedia":"getUserMedia");if(navigator[a]){var n=navigator[a].bind(navigator);navigator[a]=function(){c({data:["getUserMedia",null,arguments[0]]});var e=arguments[1],a=arguments[2];n(arguments[0],(function(a){c({data:["getUserMediaOnSuccess",null,(0,u.dumpStream)(a)]}),e&&e(a)}),(function(e){var n=["getUserMediaOnFailure",null,e.name];c({data:n}),Q(n),a&&a(e)}))}.bind(navigator)}})),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){var h=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(){return c({data:["navigator.mediaDevices.getUserMedia",null,arguments[0]]}),h.apply(navigator.mediaDevices,arguments).then((function(e){return c({data:["navigator.mediaDevices.getUserMediaOnSuccess",null,(0,u.dumpStream)(e)]}),e}),(function(e){var a=["navigator.mediaDevices.getUserMediaOnFailure",null,e.name];return c({data:a}),Q(a),Promise.reject(e)}))}.bind(navigator.mediaDevices)}if(navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",(function(){(0,a.sdkLogWithoutTrace)("debug","ondevicechanged"),c({data:["ondevicechanged",null,null]})})),navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices){var x=navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);navigator.mediaDevices.enumerateDevices=function(){return x.apply(navigator.mediaDevices,arguments).then((function(e){var n,r,o=K.setDevices(e);return(null===(n=null==o?void 0:o.addedDevices)||void 0===n?void 0:n.length)>0&&((0,a.sdkLogWithoutTrace)("debug","ondeviceadded",o.addedDevices),c({data:["ondevicesadded",null,{devices:o.addedDevices||[]}]})),(null===(r=null==o?void 0:o.removedDevices)||void 0===r?void 0:r.length)>0&&((0,a.sdkLogWithoutTrace)("debug","ondeviceremoved",o.removedDevices),c({data:["ondevicesremoved",null,{devices:o.removedDevices||[]}]})),e}),(function(e){var a=["navigator.mediaDevices.enumerateDevicesOnFailure",null,e.name];return c({data:a}),Q(a),Promise.reject(e)}))}.bind(navigator.mediaDevices)}if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){var b=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getDisplayMedia=function(){return c({data:["navigator.mediaDevices.getDisplayMedia",null,arguments[0]]}),b.apply(navigator.mediaDevices,arguments).then((function(e){return c({data:["navigator.mediaDevices.getDisplayMediaOnSuccess",null,(0,u.dumpStream)(e)]}),e}),(function(e){var a=["navigator.mediaDevices.getDisplayMediaOnFailure",null,e.name];return c({data:a}),Q(a),Promise.reject(e)}))}.bind(navigator.mediaDevices)}}(null===(v=e.console)||void 0===v?void 0:v.level)&&(0,u.setConsoleLevel)(e.console.level,c)}else(0,a.sdkLogWithoutTrace)("info","init. RTCPeerConnection does not exist in global globalContext")},a.setConfig=function(e){var n;w.watchRTCInitialized?(!(!1===(null==z?void 0:z.allowBrowserLogCollection))&&!0===(null===(n=null==e?void 0:e.console)||void 0===n?void 0:n.override)&&e.console.level&&(0,u.setConsoleLevel)(e.console.level,c),"collectionInterval"in e&&delete e.collectionInterval,z=r(r({},z),e),_.rtcRoomId=z.rtcRoomId,_.rtcPeerId=z.rtcPeerId,(0,a.sdkLog)("debug","setConfig",{newWatchrtcConfig:JSON.stringify(e),watchrtcConfig:JSON.stringify(z)}),$({})):(0,a.sdkLog)("error","SDK is not initialized. Use 'init' function first.")},a.setUserRating=function(e,n){var r;if(!w.watchRTCInitialized)return(0,a.sdkLog)("error","SDK is not initialized. Use 'init' function first."),Promise.resolve({error:"SDK is not initialized. Use 'init' function first."});if(!(0,u.validateRating)(e))return Promise.resolve({error:"Rating is invalid"});if("serverRejectedNoRetry"===V)return(0,a.sdkLog)("error","SDK connection has been rejected - Rating can't be sent. Please check your SDK parameters."),Promise.resolve({error:"SDK connection has been rejected. Rating can't be sent. Please check your SDK parameters."});var o=(null===(r=null==P?void 0:P.connection)||void 0===r?void 0:r.readyState)===w.WebSocket.OPEN,i=["userRating",null,{rating:e,ratingComment:n}];return new Promise((function(e,a){o?c({data:i,options:{promiseFuncs:{resolve:e,reject:a}}}):Y.apply(void 0,i).then((function(){return e({})})).catch((function(a){return e({error:a})}))}))},a.addKeys=function(e){var n;if(w.watchRTCInitialized){Object.keys(e||{}).forEach((function(a){"string"==typeof e[a]&&(e[a]=[e[a]])}));var r=["keys",null,e],o=(null===(n=null==P?void 0:P.connection)||void 0===n?void 0:n.readyState)===w.WebSocket.OPEN,i=null==P?void 0:P.wasConnected;return new Promise((function(e,a){var n={promiseFuncs:{resolve:e,reject:a}};o?c({data:r,options:n}):i?Y.apply(void 0,r).then((function(){return e({})})).catch((function(a){return e({error:a})})):c({data:r,options:n})}))}(0,a.sdkLog)("error","SDK is not initialized. Use 'init' function first.")},a.disableDataCollection=function(){w.watchRTCInitialized?(c({data:["disableDataCollection",null,null]}),null==P||P.disableDataCollection()):(0,a.sdkLog)("error","SDK is not initialized. Use 'init' function first.")},a.enableDataCollection=function(){w.watchRTCInitialized?(c({data:["enableDataCollection",null,null]}),null==P||P.enableDataCollection()):(0,a.sdkLog)("error","SDK is not initialized. Use 'init' function first.")},a.addEvent=function(e){if(w.watchRTCInitialized){if((0,u.validateEvent)(e,C)){var n=r({},e),o=null;n.pc&&(o=n.pc.__rtcStatsId||null,delete n.pc);var i=["event",o,n];return new Promise((function(e,a){c({data:i,options:{promiseFuncs:{resolve:e,reject:a}}})}))}}else(0,a.sdkLog)("error","addEvent error. SDK is not initialized. Use 'init' function first.")},a.mapStream=function(e,n){if(w.watchRTCInitialized){if(e&&n){var r=["mapStream",null,{id:e,name:n}];(0,a.sdkLog)("info","mapStream method is deprecated. Please use mapTrack instead."),c({data:r})}}else(0,a.sdkLog)("error","mapStream error. SDK is not initialized. Use 'init' function first.")},a.mapTrack=function(e,n){w.watchRTCInitialized?!e||!n||(H[e]=n,c({data:["mapTrack",null,{id:e,name:n}]})):(0,a.sdkLog)("error","mapTrack error. SDK is not initialized. Use 'init' function first.")},a.mapPC=function(e,n){if(w.watchRTCInitialized){var r=e.__rtcStatsId;r&&n&&c({data:["mapPC",r,{pcName:r,displayName:n}]})}else(0,a.sdkLog)("error","mapTrack error. SDK is not initialized. Use 'init' function first.")},a.connect=function(){w.watchRTCInitialized?(U=!0,E=!0,W.reset(),(0,a.sdkLog)("debug","manual connect"),$({})):(0,a.sdkLog)("error","connect error. SDK is not initialized. Use 'init' function first.")},a.disconnect=function(){w.watchRTCInitialized?(E=!1,M=!0,U=!0,V="applicationDisconnected",null==P||P.close(),(0,a.sdkLog)("debug","manual disconnect")):(0,a.sdkLog)("error","disconnect error. SDK is not initialized. Use 'init' function first.")},a.registerOnStatsListener=function(e){N=e},a.registerStateListener=function(e){A=e};var Y=function(){for(var e,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];if(!_.rtcRoomId||!_.rtcPeerId){var o="Missing configuration parameters rtcPeerId and rtcRoomId to connect";return!_.rtcRoomId&&_.rtcPeerId?o="Missing configuration parameter rtcRoomId to connect":!_.rtcPeerId&&_.rtcRoomId&&(o="Missing configuration parameter rtcPeerId to connect"),(0,a.sdkLog)("error",o),Promise.reject(o)}if(!_.projectId&&!z.rtcApiKey)return o="Missing apiKey to enable trace before connection establishment",(0,a.sdkLog)("info",o),Promise.reject(o);var i=(0,u.getConnectionData)("http",z.rtcApiKey,z.proxyUrl);return R?R.trace.apply(R,d(["".concat(i.url,"/trace"),w.watchRTCSessionId,null!==(e=_.projectId)&&void 0!==e?e:i.key,_.rtcRoomId,_.rtcPeerId],n,!1)):Promise.reject("Invalid configuration of http service")},Q=function(e){var n,r=null==z?void 0:z.rtcApiKey,o=null==z?void 0:z.rtcRoomId,i=null==z?void 0:z.rtcPeerId;if(r&&o&&i){var d=(0,u.getConnectionData)("http",null==z?void 0:z.rtcApiKey,z.proxyUrl);e=e||(null==P?void 0:P.buffer)||[],null==R||R.trace("".concat(d.url,"/error"),w.watchRTCSessionId,null!==(n=_.projectId)&&void 0!==n?n:d.key,o,i,e)}else(0,a.sdkLog)("error","Cannot report an error. Please provide rtcApiKey, rtcRoomId and rtcPeerId ")};a.persistentEnd=function(e){w.watchRTCInitialized?(clearInterval(g),E=!1,M=!0,U=!0,V="applicationDisconnected",null==P||P.close(e),(0,a.sdkLog)("debug","persistentEnd. agentId: ".concat(w.watchRTCAgentId))):(0,a.sdkLog)("error","persistentEnd error. SDK is not initialized. Use 'init' function first.")};var ee=function(){var e;(0,a.sdkLogWithoutTrace)("debug","resetConnectionState agentId: ".concat(w.watchRTCAgentId));for(var n=0,r=Object.values(C);n<r.length;n++)r[n].prev=null;(null===(e=null==P?void 0:P.buffer)||void 0===e?void 0:e.length)&&(P.buffer=P.buffer.filter((function(e){return"getstats"!==e[0]})))};a.persistentStart=function(e,n){w.watchRTCInitialized?(w.watchRTCSessionId=(0,u.generateID)(),z=r(r({},z),{rtcRoomId:e,rtcPeerId:n}),_.rtcRoomId=e,_.rtcPeerId=n,E=!0,M=!1,ee(),$({nailUp:!0}),(0,a.sdkLog)("debug","persistentStart. agentId: ".concat(w.watchRTCAgentId),{watchrtcConfig:z})):(0,a.sdkLog)("error","persistentStart error. SDK is not initialized. Use 'init' function first.")};var ae=function(e){return new Promise((function(a,n){var r=document.createElement("script");r.src=e,r.onload=a,r.onerror=n,document.head.appendChild(r)}))},ne=!1;a.qrtcRun=function(e){var n=e.options,d=e.progressCallback;return o(void 0,void 0,void 0,(function(){var e,t,c,g,m,s,l,p,v,f,x,b,y,S;return i(this,(function(C){switch(C.label){case 0:if(!k)return(0,a.sdkLogWithoutTrace)("info","Cannot run qualityRTC test in non-browser environment"),[2];ne=!1,(0,a.disableDataCollection)(),C.label=1;case 1:return C.trys.push([1,,4,5]),t=(null==n?void 0:n.codeUrl)||"https://qualityrtc-sdk.s3.amazonaws.com/".concat(h.default,"/main.bundle.js"),c={},n&&Object.keys(n||{}).forEach((function(e){"string"==typeof n[e]&&(c[e]=n[e])})),g=(0,u.getConnectionData)("http",null==z?void 0:z.rtcApiKey,z.proxyUrl),m=!!(null==n?void 0:n.configUrl),s=m?"".concat(n.configUrl,"/.netlify/functions/get-config"):g.url+"/get-qualityrtc-config?apiKey=".concat(g.key,"&").concat(new URLSearchParams(c)),console.log("runNetworkTest: request to run, loading lib and config",{codeUrl:t,configUrl:s}),[4,Promise.all([(T=s,o(void 0,void 0,void 0,(function(){return i(this,(function(e){switch(e.label){case 0:return[4,fetch(T)];case 1:return[4,e.sent().json()];case 2:return[2,e.sent()]}}))}))),ae(t)])];case 2:if(l=C.sent(),p=l[0],v=l[1],console.log("runNetworkTest:JS code & config loaded",{codeLoad:v,configAnswer:p}),!(f=w.__qualityRTC))throw new Error("runNetworkTest:Failed to load qualityRTC, __qualityRTC is undefined");return x=function(e){return!ne&&(d&&d(e),!0)},b=m?p.config:p.jsonConfig.config,y=m?null==n?void 0:n.configUrl:new URL(p.url).origin,S=r(r({},b),{isProbe:!0,options:r(r(r({},b.options),n),{wakeLock:!0,netlifyBaseUrl:y})}),console.log("runNetworkTest: code & config loaded, running test",{config:S,configData:b,qualityRTC:f,netlifyBaseUrl:y}),[4,f.run({config:S,progressCallback:x})];case 3:return e=C.sent(),console.log("runNetworkTest:JS Test completed",{answer:e}),[3,5];case 4:return(0,a.enableDataCollection)(),[7];case 5:return[2,e]}var T}))}))},a.qrtcStop=function(){k?ne=!0:(0,a.sdkLogWithoutTrace)("info","Cannot run qualityRTC test in non-browser environment")}},527:(e,a)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),a.getStreamsFromStats=a.getTransportFromStats=void 0,a.getTransportFromStats=function(e,a){if(!a)return null;var n=Object.keys(a),r=n.filter((function(e){return"candidate-pair"===a[e].type&&a[e].nominated}));if(r.length>0){var o=a[r[0]],i=o.localCandidateId,d=o.remoteCandidateId,t=n.find((function(e){return"local-candidate"===a[e].type&&a[e].id===i})),c=n.find((function(e){return"remote-candidate"===a[e].type&&a[e].id===d}));if(t&&c){var g=a[t],m=a[c],s={};return s[e]={connection:"relay"===g.candidateType?"relay":"direct",transport:"relay"===g.candidateType?g.relayProtocol:"udp",address:"".concat(m.address,":").concat(m.port)},s}}return null},a.getStreamsFromStats=function(e,a,n,r){var o={},i=Object.keys(n);return i.filter((function(e){return"inbound-rtp"===n[e].type||"outbound-rtp"===n[e].type})).forEach((function(d){var t=n[d],c=a&&d in a?a[d]:null,g="inbound-rtp"===t.type?"inbound":"outbound",m=t.kind,s=t.remoteId in n?n[t.remoteId]:null,l=c&&c.remoteId in a?a[c.remoteId]:null,p=c?(t.timestamp-c.timestamp)/1e3:null,u={direction:g,kind:m,peerId:e};if("video"===m&&(u.frameWidth=t.frameWidth,u.frameHeight=t.frameHeight,u.framerate=t.framesPerSecond),"inbound-rtp"===t.type)u.jitter=t.jitter,u.mappedName=t.trackIdentifier in r?r[t.trackIdentifier]:null,u.bytesReceived=c?t.bytesReceived-c.bytesReceived:null,u.packetsReceived=c?t.packetsReceived-c.packetsReceived:null,u.packetsLost=c?t.packetsLost-c.packetsLost:null,u.packetsLoss=u.packetsLost+u.packetsReceived>0?100*u.packetsLost/(u.packetsLost+u.packetsReceived):null,u.bitrate=p?8*u.bytesReceived/p:null,u.roundTripTime=s&&"roundTripTime"in s?s.roundTripTime:null;else{u.bytesSent=c?t.bytesSent-c.bytesSent:null,u.packetsSent=c?t.packetsSent-c.packetsSent:null,u.bitrate=p?8*u.bytesSent/p:null,u.roundTripTime=s&&"roundTripTime"in s?s.roundTripTime:null,u.jitter=s&&"jitter"in s?s.jitter:null,u.packetsLost=s&&l?s.packetsLost-l.packetsLost:null,u.packetsLoss=s&&"fractionLost"in s?s.fractionLost:null;var v=i.find((function(e){return n[e].id===t.mediaSourceId}));if(v){var f=n[v].trackIdentifier;u.mappedName=f in r?r[f]:null}}var h=i.find((function(e){return n[e].id===t.codecId}));if(h){var x=n[h].mimeType||"";u.codec=x.includes("/")?x.split("/")[1]:x}o[n[d].id]=u})),o}},912:(e,a,n)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});var r=n(593),o=function(){function e(){this.store=[],this.current=null}return e.prototype.stash=function(e){this.current=e},e.prototype.storeRawStats=function(e){this.store.push(e)},e.prototype.flushRawStats=function(e){if(!e)return this.store=[],null;var a=this.store.findIndex((function(a){return a.getStatsId===e}));return a>-1&&this.store.splice(0,a),this.store[0]||null},Object.defineProperty(e.prototype,"referenceStats",{get:function(){return this.store[0]||null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"stashedStats",{get:function(){return this.current},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.store=[]},e.prototype.pickupNewReference=function(){return this.store.shift()},e.prototype.rewriteBuffer=function(e){var a=[],n=(0,r.subtractNailUpReferenceStats)(e,this.store[0]);a.push(n);for(var o=1;o<this.store.length;o++){var i=(0,r.subtractNailUpReferenceStats)(e,this.store[o]);a.push((0,r.deltaCompression)(n,i)),n=i}return a},e}();a.default=o},699:(e,a)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0})},593:function(e,a,n){"use strict";var r=this&&this.__assign||function(){return