diff --git a/.DS_Store b/.DS_Store index 01ea04b..5a49d7b 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/v2-0-beta.html b/v2-0-beta.html index 9d79f21..d3afe5c 100644 --- a/v2-0-beta.html +++ b/v2-0-beta.html @@ -1,18 +1,19 @@ - plivo webphone - - - - + plivo webphone + + + + - - +} + + +
- -
-
-
- - phone status: - Not ready... -
-
- - call status: - idle -
-
-
-
-
-
-
- -
-
-
-
- 1 -
-
-
-
-
-
- 2 -

- ABC

-
-
-
-
-
-
-
- 3 -

- DEF

-
-
-
-
-
-
-
- 4 -

- GHI

-
-
-
-
-
-
-
- 5 -

- JKL

-
-
-
-
-
-
-
- 6 -

- MNO

-
-
-
-
-
-
-
- 7 -

- PQRS

-
-
-
-
-
-
-
- 8 -

- TUV

-
-
-
-
-
-
-
- 9 -

- WXYZ

-
-
-
-
-
-
-
- * -
-
-
-
-
-
- 0 -

- +

-
-
-
-
-
-
-
- # -
-
-
-
-
-
- - -
-
-
-
-
-
-
-

Fetching...

-

Fetching...

-

00:00

-
-
-
-
-
- -

- Answer

-
-
-
- -

- Reject

-
-
-
- -

- Hangup

-
-
-
- -

- Hangup

-
-
-
- -

- Microphone

-
-
-
-
-
- -
- - Download - Ignore -
-
-
-
-
-
-
-
- - - - - - - - - - - - - - - - - - - + +
+
+
+ - phone status: + Not ready... +
+
+ - call status: + idle +
+
+
+
+
+
+
+ +
+
+
+
+ 1 +
+
+
+
+
+
+ 2 +

+ ABC

+
+
+
+
+
+
+
+ 3 +

+ DEF

+
+
+
+
+
+
+
+ 4 +

+ GHI

+
+
+
+
+
+
+
+ 5 +

+ JKL

+
+
+
+
+
+
+
+ 6 +

+ MNO

+
+
+
+
+
+
+
+ 7 +

+ PQRS

+
+
+
+
+
+
+
+ 8 +

+ TUV

+
+
+
+
+
+
+
+ 9 +

+ WXYZ

+
+
+
+
+
+
+
+ * +
+
+
+
+
+
+ 0 +

+ +

+
+
+
+
+
+
+
+ # +
+
+
+
+
+
+ + +
+
+
+
+
+
+
+

Fetching...

+

Fetching...

+

00:00

+
+
+
+
+
+ +

+ Answer

+
+
+
+ +

+ Reject

+
+
+
+ +

+ Hangup

+
+
+
+ +

+ Hangup

+
+
+
+ +

+ Microphone

+
+
+
+
+
+ +
+ + Download + Ignore +
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
- + +
+
+
- +
- - + + + + + \ No newline at end of file diff --git a/v2-0.html b/v2-0.html index 816bd44..15faf5c 100644 --- a/v2-0.html +++ b/v2-0.html @@ -8,1136 +8,1391 @@ -ß - +/* Idle State of the stars */ +.rating-stars ul > li.star > i.fa { + font-size:2.5em; /* Change the size of the stars */ + color:#ccc; /* Color on idle state */ +} +/* Hover state of the stars */ +.rating-stars ul > li.star.hover > i.fa { + color:#FFCC36; +} +/* Selected state of the stars */ +.rating-stars ul > li.star.selected > i.fa { + color:#FF912C; +} - + + +
+ +
+
+
+ - phone status: + Not ready... +
+
+ - call status: + idle +
+
+
+
+
+
+
+ +
+
+
+
+ 1 +
+
+
+
+
+
+ 2 +

+ ABC

+
+
+
+
+
+
+
+ 3 +

+ DEF

+
+
+
+
+
+
+
+ 4 +

+ GHI

+
+
+
+
+
+
+
+ 5 +

+ JKL

+
+
+
+
+
+
+
+ 6 +

+ MNO

+
+
+
+
+
+
+
+ 7 +

+ PQRS

+
+
+
+
+
+
+
+ 8 +

+ TUV

+
+
+
+
+
+
+
+ 9 +

+ WXYZ

+
+
+
+
+
+
+
+ * +
+
+
+
+
+
+ 0 +

+ +

+
+
+
+
+
+
+
+ # +
+
+
+
+
+
+ + +
+
+
+
+
+
+
+

Fetching...

+

Fetching...

+

00:00

+
+
+
+
+
+ +

+ Answer

+
+
+
+ +

+ Reject

+
+
+
+ +

+ Hangup

+
+
+
+ +

+ Hangup

+
+
+
+ +

+ Microphone

+
+
+
+
+
+ +
+ + Download + Ignore +
+
+
+
+
+
+
+
+ + -
- -
-
-
- - phone status: - Not ready... -
-
- - call status: - idle -
-
-
-
-
-
-
- -
-
-
-
- 1 -
-
-
-
-
-
- 2 -

- ABC

-
-
-
-
-
-
-
- 3 -

- DEF

-
-
-
-
-
-
-
- 4 -

- GHI

-
-
-
-
-
-
-
- 5 -

- JKL

-
-
-
-
-
-
-
- 6 -

- MNO

-
-
-
-
-
-
-
- 7 -

- PQRS

-
-
-
-
-
-
-
- 8 -

- TUV

-
-
-
-
-
-
-
- 9 -

- WXYZ

-
-
-
-
-
-
-
- * -
-
-
-
-
-
- 0 -

- +

-
-
-
-
-
-
-
- # -
-
-
-
-
-
- - -
-
-
-
-
-
-
-

Fetching...

-

Fetching...

-

00:00

-
-
-
-
-
- -

- Answer

-
-
-
- -

- Reject

-
-
-
- -

- Hangup

-
-
-
- -

- Hangup

-
-
-
- -

- Microphone

-
-
-
-
-
- -
- - Download - Ignore -
-
-
-
-
-
-
-
- - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + +
- + +
+
+
- +
- - - + + + + + \ No newline at end of file diff --git a/webApp-plivo/public/.DS_Store b/webApp-plivo/public/.DS_Store index 5008ddf..dee0e3e 100644 Binary files a/webApp-plivo/public/.DS_Store and b/webApp-plivo/public/.DS_Store differ diff --git a/webApp-plivo/public/js/customclient.js b/webApp-plivo/public/js/customclient.js index 60f0cdb..8fa15f9 100644 --- a/webApp-plivo/public/js/customclient.js +++ b/webApp-plivo/public/js/customclient.js @@ -62,7 +62,14 @@ function onPermissionNeeded(obj){ } function onConnectionChange(obj){ - customAlert( obj.state + " "+ obj.status , "info"); + console.log('onConnectionChange: ', obj); + if(obj.state === "connected" ){ + customAlert( obj.state , "info"); + }else if(obj.state === "disconnected"){ + customAlert( obj.state + " "+ obj.eventCode +" "+ obj.eventReason , "info"); + }else{ + console.log("unknown connection state "); + } } function onWebrtcNotSupported() { @@ -633,7 +640,7 @@ $('#sendFeedback').click(function(){ return; } var sendConsoleLogs = document.getElementById("sendConsoleLogs").checked; - plivoWebSdk.client.sendQualityFeedback(lastCallid,score,comment , sendConsoleLogs); + plivoWebSdk.client.sendQualityFeedback(lastCallid, score , comment , sendConsoleLogs); customAlert('Quality feedback ',lastCallid); }); @@ -764,7 +771,7 @@ micTest.onclick = function(){ clearRecPlayer.onclick = function(){ $('#recPlayerLayout').hide(); } -if(document.querySelector('streamAudioFile')){ +if(document.querySelector('#streamAudioFile')){ streamAudioFile.onchange = function(){ if(audioStreamContext){ audioStreamContext.close(); diff --git a/webApp-plivo/public/js/plivowebsdk.js b/webApp-plivo/public/js/plivowebsdk.js deleted file mode 100644 index 5d27d70..0000000 --- a/webApp-plivo/public/js/plivowebsdk.js +++ /dev/null @@ -1,29409 +0,0 @@ -/* Name: JsSIP Maintainer: José Luis Millán Copyright (c) 2012-2016 José Luis Millán License: The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ -/*Copyright (c) 2013-2016, callstats.io All rights reserved.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/ - -var Plivo = (function unpack(){var id=1, bundle=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o1000){ - // 1000 is normal websocket closed event , others codes as 1003,1006,1011 etc are for abnormal termination - var eventData = { "state": evt.code , "status" : evt.reason || "Websocket Disconnected"}; - //Adding a timeout for notifying connection change event every 5 seconds - if(lastConnectionChangeTime == 0 ){ - // First Time Event , dont wait to show notification - that.emit('onConnectionChange', eventData); - lastConnectionChangeTime = new Date(); - }else{ - var currentConnectionChangeTime = new Date(); - // Wait 10 seconds to emit the connection change event - if( ( ( currentConnectionChangeTime - lastConnectionChangeTime )/1000) > 10 ){ - that.emit('onConnectionChange', eventData); - lastConnectionChangeTime = new Date(); - } - } - } - }); - - this.phone.on('registered', function () { - that.userName = userName; - if(that.isLoggedIn === false) { - that.isLoggedIn = true; - that.emit('onLogin'); - Plivo.log.debug('logged in'); - - if(that.options.enableTracking && !that.callStats) { - that.options.appId? null : (that.options.appId = "380077084"); - // Temp fix for chrome 58 to get callback based getstats - window.csioChromeLegacyGetStats=true; - - that.callStats = new callstats(); - var configParams = { - disableBeforeUnloadHandler: false, // disables callstats.js's window.onbeforeunload parameter. - applicationVersion: '2.0.13' // Application version specified by the developer. - }; - // callbacks for callstats - var csInitCallback = function(err, msg) { - Plivo.log.debug('Stats Initializing Status: err= '+err + ' msg= '+msg); - }; - var csStatsCallback = function(stats){ - var streams = stats.streams; - processSteams.call(that,_emitter, streams); - if(window._PlivoDevLogging){ - console.log(streams); - } - } - // callstats initialize - if(SipLib.adapter.browserDetails.browser != 'chrome') - csStatsCallback = null; //still some issues in FF so don't go for getstats call back - /** - if appSecret is passed in option use it. Usefull if customer has their own callstats account - Or try to get token for appId - */ - if(that.callStats) { - var callStatsToken = that.options.appSecret || callStatsTokenCb(that); - that.callStats.initialize(that.options.appId, callStatsToken, userName, csInitCallback, csStatsCallback, configParams); - } - Plivo.log.debug('enableTracking initialized'); - } - } - }); - - this.phone.on('unregistered', function () { - Plivo.log.debug('Plivo client logged out'); - that.isLoggedIn = false; - - that.ringToneView.paused? null: documentUtil.stopAudio(constants.RINGTONE_ELEMENT_ID); - that.ringBackToneView.paused? null: documentUtil.stopAudio(constants.RINGBACK_ELEMENT_ID); - that.userName = null; - - that.emit('onLogout'); - }); - - this.phone.on('registrationFailed', function(error) { - that.isLoggedIn = false; - Plivo.log.debug('Login failed : ',error.cause); - that.userName = null; - that.emit('onLoginFailed', error.cause); - }); - - this.phone.on('newRTCSession', function (evt) { - Plivo.log.debug('new rtc session'); - if(that.callSession && that.callSession.connection.signalingState == 'closed'){ - Plivo.log.warn("Previous call doesn't end properly"); - that.callSession = null; - } - if (that.callSession) { - Plivo.log.debug('Already on call, sending busy signal.'); - - var opts = { - 'status_code': 486, - 'reason_phrase': 'Busy Here' - }; - - evt.session.terminate(opts); - return; - } - - that.callSession = evt.session; - - if (evt.originator === 'remote') { - that.callDirection = 'incoming'; - Plivo.log.info('<----- INCOMING ----->'); - that.connStage = []; - that.connStage.push('I-invite@'+dateMs()); - - that.callUUID = evt.request.getHeader('X-Calluuid') || null; - var caller = evt.request.getHeader('From'); - that.caller = caller.match(/:(.*)@/i)[1]; - - //custom sdp codec changes - try{ - evt.request.body = checkCodecPreference(that.options.codecs, evt.request.body); - }catch(err){ - Plivo.log.debug('checkCodecPreference err - ',err); - } - - - that.callSession.on('progress', function (evt) { - Plivo.log.debug('Incoming call progress'); - that.connStage.push('progress-180@'+dateMs()); - var callerUri = that.callSession.remote_identity.uri.toString(); - if(that.ringToneFlag !== false) { - Plivo.log.debug('ringtone enabled : ',that.ringToneFlag); - documentUtil.playAudio(constants.RINGTONE_ELEMENT_ID); - } - that.emit('onIncomingCall', callerUri.substring(4, callerUri.indexOf('@')) + '@'+constants.DOMAIN, extraHeaders); - Plivo.log.debug('Incoming Call Extra Headers : ',extraHeaders); - }); - - that.callSession.on('sdp', function(evt){ - Plivo.log.debug('Incoming call SDP processing done'); - }); - - that.callSession.on('accepted', function(evt){ - Plivo.log.info('Incoming call accepted'); - - callStart(that); // initialise callstats storage. - var inboundConn = that.callSession.connection || null; - inboundConn.oniceconnectionstatechange = function(evt){ - var iceState = inboundConn.iceConnectionState; - Plivo.log.debug('oniceconnectionstatechange:: '+iceState); - that.connStage.push("iceConnectionState-"+iceState+"@"+dateMs()); - //Notify network drops - iceConnectionCheck.call(that,iceState); - if (that.callStats && that.callUUID && inboundConn) { - if (iceState == 'failed' || iceState == 'disconnected') { - var errname = new DOMError(iceState, iceState); - that.callStats.reportError(inboundConn, that.callUUID, that.callStats.webRTCFunctions.iceConnectionFailure, errname); - } - } - } - }); - - that.callSession.on('confirmed', function (evt) { - Plivo.log.debug('Incoming call confirmed - '+that.callUUID); - that.connStage.push("confirmed@"+dateMs()); - - // disableRtpTimeOut if enabled - if(that.options.disableRtpTimeOut){ - that.callSession.connection.disableRtpTimeOut = true; - } - - var remoteStream = this.connection.getRemoteStreams()[0]; - if(!remoteStream){ - Plivo.log.error('Incoming call remoteStream does not exists'); - } - that.remoteView.srcObject = remoteStream; - - var peerConnectionCallback = function(message) { - Plivo.log.debug('Stats new fabric message: ' + message); - }; - //peer connection is established till here on incoming - if (that.callStats && this.connection) { - that.callStats.addNewFabric(this.connection, that.caller, that.callStats.fabricUsage.audio, that.callUUID, peerConnectionCallback); - } - that.ringToneView.paused? null : documentUtil.stopAudio(constants.RINGTONE_ELEMENT_ID); - that.ringBackToneView.paused? null : documentUtil.stopAudio(constants.RINGBACK_ELEMENT_ID); - - that.emit('onCallAnswered'); - Plivo.log.debug("Plivo Event: Post-Answer detecting OWA"); - setTimeout(owaNotification, 3000, this.connection, that); - }); - - that.callSession.on('icetimeout', function(sec){ - Plivo.log.debug('iceGathering timed out'); - _emitter(that,'network','warning','ice_timeout', sec, true, "Possible NAT/Firewall issue"); - }); - - that.callSession.on('failed', function(evt) { - Plivo.log.error('Call failed: ' + evt.cause); - that.connStage.push("failed@"+dateMs()); - - that.ringToneView.paused? null:documentUtil.stopAudio(constants.RINGTONE_ELEMENT_ID); - if (evt.cause == SipLib.C.causes.CANCELED && that.callDirection == 'incoming') { - that.emit('onIncomingCallCanceled'); - } - else { - that.emit('onCallFailed', evt.cause); - } - - if (that.callStats && that.callUUID && this.connection && !evt.cause.match('edia')) { // media err is not under signaling err - var errName,errMsg; - if (evt.message) { - errName = evt.cause; - errMsg = errName; - evt.message.status_code && (errMsg = String(evt.message.status_code) ); - } - var errname = new DOMError(errName, errMsg); - Plivo.log.debug(errname); - that.callStats.reportError(this.connection, that.callUUID, that.callStats.webRTCFunctions.signalingError, errname); - } - hangupClearance(that); - }); - - that.callSession.on('ended', function (evt) { - Plivo.log.debug('Incoming call ended - '+that.callUUID); - Plivo.log.info('Incoming call ended'); - that.connStage.push("ended@"+dateMs()); - - if (that.callStats) { - that.callStats.sendFabricEvent(this.connection, that.callStats.fabricEvent.fabricTerminated, that.callUUID); - } - that.emit('onCallTerminated',{"originator":evt.originator, "reason":evt.cause}); - hangupClearance(that); - }); - that.callSession.on('getusermediafailed', function(err){ - Plivo.log.error('getusermediafailed: '+err); - if (that.userName && that.callStats) { - err.message = "getusermediafailed"; - that.callStats.reportError(null, that.userName, that.callStats.webRTCFunctions.getUserMedia, err); - } - }); - that.callSession.on('peerconnection:createofferfailed', function(err){ - Plivo.log.error('peerconnection:createofferfailed: ',err); - if (that.userName && that.callStats) { - err.message = "peerconnection:createofferfailed"; - that.callStats.reportError(null, that.userName, that.callStats.webRTCFunctions.createOffer, err); - } - }); - that.callSession.on('peerconnection:createanswerfailed', function(err){ - Plivo.log.error('peerconnection:createanswerfailed: ', err); - if (that.userName && that.callStats) { - err.message = "peerconnection:createanswerfailed"; - that.callStats.reportError(null, that.userName, that.callStats.webRTCFunctions.createAnswer, err); - } - }); - that.callSession.on('peerconnection:setlocaldescriptionfailed', function(err){ - Plivo.log.error('peerconnection:setlocaldescriptionfailed: ', err); - if (that.userName && that.callStats) { - err.message = "peerconnection:setlocaldescriptionfailed"; - that.callStats.reportError(null, that.userName, that.callStats.webRTCFunctions.setLocalDescription, err); - } - }); - that.callSession.on('peerconnection:setremotedescriptionfailed', function(err){ - Plivo.log.error('peerconnection:setremotedescriptionfailed: ',err); - if(err.message && !err.message == 'pranswer not yet implemented'){ - if (that.userName && that.callStats) { - that.callStats.reportError(null, that.userName, that.callStats.webRTCFunctions.setRemoteDescription, err); - } - } - }); - - var request = evt.request; - var headers = request.headers; - var extraHeaders = headersUtil.receiveExtraHeader(request, headers); - - Plivo.log.debug('callSession - '+ that.callUUID); - - } else { - that.callDirection = 'outgoing'; - Plivo.log.debug('new RTCSession outgoing'); - that.emit('onCalling'); - } - }); - - this.phone.start(); - - return true; -}; - -Client.prototype.logout = function() { - Plivo.log.debug('logout() triggered!'); - if (this.callSession) { - Plivo.log.debug('Terminating an active call'); - this.callSession.terminate(); - } - this.connStage.push("logout()@"+dateMs()); - this.phone && this.phone.stop(); - this.emit('onLogout'); - return true; -}; - -Client.prototype.call = function(phoneNumber, extraHeaders) { - var that = this; - Plivo.log.info('<----- OUTGOING ----->'); - that.connStage = []; - Plivo.log.info('Outgoing call initialized to : '+ phoneNumber); - if (!this.isLoggedIn) { - Plivo.log.warn('Must be logged in before make a call'); - return false; - } - that.connStage.push("call()@"+dateMs()); - - function onCallFailed(reason){ - that.emit('onCallFailed', reason); - return true; - } - function readyForCall(){ - that.owaLastDetect.isOneWay=false; - return _createSession(that, extraHeaders, phoneNumber); - } - /** - Handle one way audio issues in chrome - check for every 1 hr - */ - if(that.options.preDetectOwa && that.browserDetails.browser == "chrome" && ( (new Date() - that.owaLastDetect.time) > that.owaDetectTime || that.owaLastDetect.isOneWay) ){ - detectOWA(function(res, err){ // @res {"bytesSent ": "366", audioInputLevel: "117"} - that.owaLastDetect.time = new Date(); - if(err){ - Plivo.log.error('Error in detecting microphone status ',err); - that.emit('onMediaPermission',{"status":"failure","error":err.name}); - onCallFailed('media - '+err.name); - return false; - }else{ - Plivo.log.debug('getUserMedia precheck ',res); - if( Number(res.bytesSent) == 0 && Number(res.audioInputLevel) == 0 ){ - _emitter(that,'audio','warning','no_microphone_access', 0, true, "chrome lost access to microphone - restart browser"); - that.owaLastDetect.isOneWay=true; - onCallFailed('no_microphone_access'); - return false; - } - if( Number(res.audioInputLevel) == 0 ){ - _emitter(that,'audio','warning','no_microphone_access', 0, true, "microphone is muted"); - } - } - // On no one way audio go to call ready mode - readyForCall(); - }); - }else{ - // Browsers other than chrome go to call ready mode - readyForCall(); - } -} - -Client.prototype.answer = function() { - Plivo.log.debug('answer - '+ this.callUUID); - var that = this; - var opts = {}; - - if (this.callSession) { - that.connStage.push("answer()@"+dateMs()); - - function mediaError(reason){ - that.reject(); - return true; - } - function readyForCall(){ - that.owaLastDetect.isOneWay=false; - opts.pcConfig = { - 'iceServers': [ - { 'urls': constants.STUN_SERVERS } - ] - }; - if(that.permOnClick){ - var audioConstraints = that.options.audioConstraints || true; - opts.mediaConstraints = { - audio: audioConstraints, - video: false - }; - }else{ - window.localStream? true : Plivo.log.warn('no localStream attached for this call'); - } - opts.mediaStream = window.localStream || null; - opts.rtcConstraints = that.options.dscp? ({"optional":[{"googDscp":true}]}) : null; - opts.sessionTimersExpires = constants.SESSION_TIMERS_EXPIRES; - try{ - if(that.callSession){ - that.callSession.answer(opts); - } - }catch(err){ - Plivo.log.error('error in answering : ',err); - that.emit('onIncomingCallCanceled',err); - } - that.ringToneView.paused? null : documentUtil.stopAudio(constants.RINGTONE_ELEMENT_ID); - return true; - } - /** - Handle One way audio issues for outgoing call in chrome - check for every 1 hr - */ - if(that.options.preDetectOwa && that.browserDetails.browser == "chrome" && ( (new Date() - that.owaLastDetect.time) > that.owaDetectTime || that.owaLastDetect.isOneWay) ){ - detectOWA(function(res, err){ // @res {"bytesSent ": "366", audioInputLevel: "117"} - that.owaLastDetect.time = new Date(); - if(err){ - Plivo.log.error('Error in detecting microphone status ',err); - that.emit('onMediaPermission',{"status":"failure","error":err.name}); - mediaError('media - '+err.name); - return false; - }else{ - Plivo.log.debug('getUserMedia precheck ',that.str(res)); - if( Number(res.bytesSent) == 0 && Number(res.audioInputLevel) == 0){ - _emitter(that,'audio','warning','no_microphone_access', 0, true, "chrome lost access to microphone - restart browser"); - that.owaLastDetect.isOneWay=true; - mediaError('no_microphone_access'); - return false; - } - if( Number(res.audioInputLevel) == 0 ){ - _emitter(that,'audio','warning','no_microphone_access', 0, true, "microphone is muted"); - } - } - // On no one way audio go to call ready mode - readyForCall(); - }); - }else{ - // Browsers other than chrome go to call ready mode - readyForCall(); - } - - } else { - Plivo.log.error('Incoming call answer() failed : no incoming call'); - return false; - } - return true; -}; - -Client.prototype.hangup = function () { - Plivo.log.debug('hangup - '+this.callUUID); - if (this.callSession) { - if(this.callSession.direction != "outgoing" && !isSessionConfirmed(this.callSession)){ - Plivo.log.warn('use of hangup() on unanswered call is deprecated. use reject() instead'); - } - try{ - Plivo.log.info('hangup initialized'); - Plivo.AppError({"name":"hangup","message":"hangup initialized","method":"hangup()"}); - this.callSession.terminate(); - this.ringBackToneView.paused? null: documentUtil.stopAudio(constants.RINGBACK_ELEMENT_ID); - }catch(err){ - Plivo.log.error('Could not hangup reason : ',err); - Plivo.AppError({"name":err.name,"message":err.message,"method":"hangup()"}); - } - } - else { - Plivo.log.warn('No call session exists to hangup'); - return false; - } - return true; -}; - -Client.prototype.reject = function () { - Plivo.log.debug('reject - '+this.callUUID); - if(!this.callSession){ - Plivo.log.warn('No call session exists to reject()'); - return false; - } - if(isSessionConfirmed(this.callSession)){ - Plivo.log.warn('call already answerd, please use hangup() method'); - return false; - } - if (this.callSession) { - var opts = { - 'status_code': 486, - 'reason_phrase': 'Busy Here' - }; - Plivo.log.info('rejecting call'); - Plivo.AppError({"name":"reject","message":"reject initialized","method":"reject()"}); - try{ - this.callSession.terminate(opts); - }catch(err){ - Plivo.log.error('error in rejecting call : ',err); - Plivo.AppError({"name":err.name,"message":err.message,"method":"reject()"}); - } - this.ringToneView.paused? null: documentUtil.stopAudio(constants.RINGTONE_ELEMENT_ID); - return true; - } -} - -Client.prototype.sendDtmf = function (digit) { - Plivo.log.debug('sendDtmf - '+this.callUUID); - if (typeof digit == 'undefined' || digit == null) { - return Plivo.log.warn('DTMF digit can not be null'); - } else if (typeof constants.DTMF_TONE_FLAG[digit] == 'undefined') { - return Plivo.log.warn(digit + ' is not a valid DTMF digit'); - } - - if (this.callSession) { - try { - Plivo.log.debug('sending dtmf digit ' + digit); - this.callSession.sendDTMF(digit); - if (digit === '*') { - return documentUtil.playAudio('dtmfstar'); - } else if (digit === '#') { - return documentUtil.playAudio('dtmfpound'); - } - return documentUtil.playAudio('dtmf' + digit); - } catch (err) { - Plivo.log.error('Call has not been confirmed cannot send DTMF'); - Plivo.AppError({"name":err.name,"message":err.message,"method":"sendDtmf()"}); - } - } else { - Plivo.log.warn('No call session exists to sendDtmf'); - } - -}; - -Client.prototype.mute = function () { - if (this.callSession) { - Plivo.log.debug('mute called'); - try{ - this.callSession.mute(); - if (this.callStats) { - this.callStats.sendFabricEvent(this.callSession.connection, this.callStats.fabricEvent.audioMute, this.callUUID); - } - }catch(err){ - Plivo.log.error('error in mute :',err); - Plivo.AppError({"name":err.name,"message":err.message,"method":"mute()"}); - } - - } else { - Plivo.log.warn('No call session exists to mute'); - return false; - } - - return true; -}; - -Client.prototype.unmute = function () { - if (this.callSession) { - Plivo.log.debug('unmute called'); - try{ - this.callSession.unmute(); - if (this.callStats) { - this.callStats.sendFabricEvent(this.callSession.connection, this.callStats.fabricEvent.audioUnmute, this.callUUID); - } - }catch(err){ - Plivo.log.error('error in unmute : ',err); - Plivo.AppError({"name":err.name,"message":err.message,"method":"unmute()"}); - } - } else { - Plivo.log.warn('No call session exists to unmute'); - return false; - } - - return true; -}; - -Client.prototype.setRingTone = function (val) { - if (val === false || val === null) { - this.ringToneFlag = false; - } - else if (typeof val === 'string') { - this.ringToneFlag = 'user'; - - Plivo.log.debug('setRingTone() url : '+val); - - this.ringToneView.src = val; - } - else { - this.ringToneFlag = true; - } - return true; -}; - -Client.prototype.setRingToneBack = function (val) { - if (val === false || val === null) { - this.ringToneBackFlag = false; - } - else if (typeof val == 'string') { - this.ringToneBackFlag = 'user'; - Plivo.log.debug('setRingToneBack() url : '+val); - this.ringBackToneView.src = val; - } - else { - this.ringToneBackFlag = true; - } - - return true; -}; - -Client.prototype.setConnectTone = function (val) { - if (!val) { - this.connectToneFlag = false; - } - else { - this.connectToneFlag = true; - } - return true; -}; - -Client.prototype.setDtmfTone = function (digit, url) { - if (url === false || url === null) { - constants.DTMF_TONE_FLAG[digit] = false; - } - else if (typeof url === 'string') { - Plivo.log.debug('set dtmf tone'); - constants.DTMF_TONE_FLAG[digit] = 'user'; - var elementName = 'dtmf' + digit; - var element = document.getElementById(elementName); - - element.src = url; - } - else { - constants.DTMF_TONE_FLAG[digit] = true; - } - - return true; -}; - -Client.prototype.getCallUUID = function () { - return this.callUUID; -}; - -Client.prototype.getLastCallUUID = function(){ - return this.lastCallUUID; -} -Client.prototype.setDebug = function (debug) { - if(debug && ['INFO','DEBUG','WARN','ERROR','ALL','OFF'].indexOf(debug) != -1){ - Plivo.log.setLevel(debug); - } -}; - -Client.prototype.getPeerConnection = function (){ - if (this.callSession && isSessionConfirmed(this.callSession)){ - return {"status":"success", "pc":this.callSession.connection }; - }else{ - return {"status":"called in wrong state", "pc":null}; - } -} - -Client.prototype.version = '2.0.13'; - -Client.prototype.webRTC = function(){ - return window.RTCPeerConnection? true : false; -} - -Client.prototype.supportedBrowsers = function(){ - return "Chrome, Firefox"; -} - -Client.prototype.sendQualityFeedback = function (callUUID, score, comment) { - var score = Number(score); - /* handle all failures */ - if(!this.callStats){ - Plivo.log.warn('Stats integration not configured, ignoring feedback'); - return; - } - // On logout don't allow to sendQuality fb - if(!this.userName){ - Plivo.log.error('sendQualityFeedback() userName is null, isLoggedIn : ' + this.isLoggedIn); - return; - } - if(!callUUID){ - Plivo.log.error('sendQualityFeedback() callUUID is mandatory'); - return; - } - if(comment && comment.toString().length > 200){ - Plivo.log.error('sendQualityFeedback() comment max length is 200 character'); - return; - } - if(!comment){ - Plivo.log.error('sendQualityFeedback() comment is mandatory') - } - /* Success */ - if( score > 0 && score <= 5){ // consider scores between 1-5 - var feedback ={ - userID: this.userName, - overall: score, - comment: comment - }; - var pcCallback = function(message) { - Plivo.log.debug('Stats sendFeedback status: ' + message); - }; - Plivo.log.debug('Feedback sent for callUUID : '+callUUID); - this.callStats.sendUserFeedback(callUUID, feedback, pcCallback); - }else{ - Plivo.log.error('sendQualityFeedback() score: '+score+' , score should be from 1-5 range'); - } -}; - -var owaNotification = function(connection, that) { - if (connection && connection.signalingState != "closed" && SipLib.adapter.browserDetails.browser == "chrome") { - var pc = connection; - pc.getStats(function (res) { - res.result().forEach(function(result) { - var report = result; - report.stat('bytesSent') && Plivo.log.debug("Bytes sent by WebSDK client: " + report.stat('bytesSent') + " audioInputLevel: " +report.stat('audioInputLevel')); - that.storage.audioCodec = report.stat("googCodecName"); // store audio codec - if (report.type === 'ssrc' && report.stat('mediaType') === 'audio' && parseInt(report.stat('bytesSent'), 10) === 0 && report.stat('audioInputLevel') === 0) { - Plivo.log.debug("One way audio detected"); - _emitter(that,'audio','warning','no_microphone_access', 0, true, "no access to your microphone"); - } - }); - },pc.getLocalStreams()[0].getAudioTracks()[0],function(err){console.log(err);}); - } -}; - -var _emitter = function(ClientInstance, group, level, type, value, active,desc){ - var msgTemplate = { "group":group, - "level":level, - "type":type, - "value":value, - "active":active, - "desc":desc || "" - }; - ClientInstance.emit('mediaMetrics', msgTemplate); -}; - -var _createSession = function(that, extraHeaders, phoneNumber) { - var opts = {}; - var destinationUri; - - if(phoneNumber){ - phoneNumber = String(phoneNumber); - } - - if (typeof phoneNumber === 'undefined' || phoneNumber === null || phoneNumber.length <= 0) { - Plivo.log.warn('Destination address cant be null and its length must be > 0'); - return false; - } - - if (that.callSession) { - Plivo.log.warn("Can't make another call while in call"); - return false; - } - - extraHeaders = extraHeaders || {}; - var cleanExtraHeaders = []; - - for (var key in extraHeaders) { - var value = extraHeaders[key]; - if (headersUtil.checkExtraHeaderKey(key) && headersUtil.checkExtraHeaderVal(value)) { - cleanExtraHeaders.push(key + ': ' + value); - Plivo.log.debug('valid hdr = ' + key + ' -> ' + value); - } else { - Plivo.log.debug('invalid hdr = ' + key + ' -> ' + value); - } - } - // client route region - if(that.options.clientRegion){ - cleanExtraHeaders.push("X-ClientRegion: "+that.options.clientRegion); - } - - if (phoneNumber.substring(0, 4) != 'sip:') { - destinationUri = 'sip:' + phoneNumber; - } else { - destinationUri = phoneNumber; - } - opts.sessionTimersExpires = constants.SESSION_TIMERS_EXPIRES; - - opts.pcConfig = { - 'iceServers': [ - { 'urls': constants.STUN_SERVERS } - ] - }; - - var audioConstraints = that.options.audioConstraints || true; - opts.mediaConstraints = { - audio: audioConstraints, - video: false - }; - opts.rtcConstraints = that.options.dscp? ({"optional":[{"googDscp":true}]}) : null; - opts.extraHeaders = cleanExtraHeaders; - opts.mediaStream = window.localStream || null; - - opts.eventHandlers = { - 'sending': function (evt) { - Plivo.log.debug('Outgoing call sending'); - that.connStage.push('O-invite@'+dateMs()); - var outboundConn = this.connection || null; - if(that.connectToneFlag !== false){ - documentUtil.playAudio(constants.CONNECT_TONE_ELEMENT_ID); - } - - //Adding remote stream - outboundConn.ontrack = function(evt){ - Plivo.log.debug('Outgoing call received addStream'); - that.connStage.push("addStream-success@"+dateMs()); - if(evt.streams[0]){ - /// on direct 200 OK with out 18x, we get The play() request was interrupted by a new load request. 100 timeout sec is workaround - setTimeout(function(){ - that.remoteView.srcObject = evt.streams[0]; - },100); - if(that.ringToneBackFlag && !isSessionConfirmed(that.callSession)){ - setTimeout(function(){ - if (!isSessionConfirmed(that.callSession)) { - that.remoteView.pause(); - } - },100) - }else if(!that.ringToneBackFlag && !isSessionConfirmed(that.callSession)){ - Plivo.log.debug('playAudio - MediaServer'); - } - }else{ - Plivo.log.error('Outgoing call addStream failure'); - that.connStage.push("addStream-failure@"+dateMs()); - } - }; - outboundConn.oniceconnectionstatechange = function(){ - var iceState = outboundConn.iceConnectionState; - Plivo.log.debug('oniceconnectionstatechange:: '+iceState); - that.connStage.push("iceConnectionState-"+iceState+"@"+dateMs()); - //Notify network drops - iceConnectionCheck.call(that,iceState); - if (that.callStats && that.callUUID && outboundConn) { - if (iceState == 'failed' || iceState == 'disconnected') { - Plivo.log.debug('iceState :: '+iceState) - var errname = new DOMError(iceState, iceState); - that.callStats.reportError(outboundConn, that.callUUID, that.callStats.webRTCFunctions.iceConnectionFailure, errname); - } - } - } - }, - 'sdp': function(evt){ - try{ - evt.sdp = checkCodecPreference(that.options.codecs, evt.sdp); - }catch(err){ - Plivo.log.debug('checkCodecPreference err - ',err); - } - - }, - 'progress': function (evt) { - - that.callSession = this; - that.callUUID = evt.response.getHeader('X-Calluuid'); - that.emit('onCallRemoteRinging'); - - if (that.callStats && this.connection) { - var peerConnectionCallback = function(message) { - Plivo.log.debug('Stats new fabric message: ' + message); - }; - var dest = this.request.headers.To.toString().match(/:(.*)@/i)[1]; - that.callStats.addNewFabric(this.connection, dest, that.callStats.fabricUsage.audio, that.callUUID, peerConnectionCallback); - } - - that.connStage.push("progress-"+evt.response.status_code+"@"+dateMs()); - Plivo.log.debug('Outgoing call progress',evt.response.status_code); - Plivo.log.debug('ringback tone enabled : '+that.ringToneBackFlag); - // Stop connect tone on 18x response - that.connectToneView.paused? null: documentUtil.stopAudio(constants.CONNECT_TONE_ELEMENT_ID); - - if(that.ringToneBackFlag){ - documentUtil.playAudio(constants.RINGBACK_ELEMENT_ID); - } - - if(evt.response.status_code == 183 && evt.response.body){ - Plivo.log.debug('callSession - '+that.callUUID); - // ringback tone is not enabled then use media server ringback tone - if(!that.ringToneBackFlag){ - that.ringBackToneView.paused? null : documentUtil.stopAudio(constants.RINGBACK_ELEMENT_ID); - return; - } - } - - }, - 'accepted': function (evt) { - var dest = evt.response.getHeader('To').match(/:(.*)@/i)[1]; - that.callUUID = evt.response.getHeader('X-Calluuid'); - Plivo.log.info('Outgoing call accepted'); - - var peerConnectionCallback = function(message) { - Plivo.log.debug('Stats new fabric message: ' + message); - }; - - callStart(that); - if (that.callStats && this.connection) { - that.callStats.addNewFabric(this.connection, dest, that.callStats.fabricUsage.audio, that.callUUID, peerConnectionCallback); - } - }, - 'confirmed': function (evt) { - Plivo.log.debug('Outgoing call confirmed - '+ that.callUUID); - that.connStage.push('confirmed@'+dateMs()); - that.remoteView.paused && that.remoteView.play(); - //disableRtpTimeOut if enabled - if(that.options.disableRtpTimeOut){ - that.callSession.connection.disableRtpTimeOut=true; - } - that.ringToneView.paused? null : documentUtil.stopAudio(constants.RINGTONE_ELEMENT_ID); - that.ringBackToneView.paused? null : documentUtil.stopAudio(constants.RINGBACK_ELEMENT_ID); - that.connectToneView.paused? null : documentUtil.stopAudio(constants.CONNECT_TONE_ELEMENT_ID); - - that.emit('onCallAnswered'); - setTimeout(owaNotification, 3000, this.connection, that); - }, - 'icetimeout': function(sec){ - Plivo.log.debug('iceGathering timed out'); - _emitter(that,'network','warning','ice_timeout', sec, true, "Possible NAT/Firewall issue"); - }, - 'failed': function (evt) { - Plivo.log.error('Outgoing call failed: ' + evt.cause); - that.connStage.push('failed@'+dateMs()); - that.ringBackToneView.paused? null : documentUtil.stopAudio(constants.RINGBACK_ELEMENT_ID); - that.connectToneView.paused? null : documentUtil.stopAudio(constants.CONNECT_TONE_ELEMENT_ID); - - if(evt.message) { - that.callUUID = evt.message.getHeader('X-CallUUID')||null; - } - - if (that.callStats && that.callUUID && !evt.cause.match('edia')) { // dont pass media errors as signalling err - var errName=evt.cause,errMsg=errName; - if (evt.message) { - evt.message.status_code && (errMsg = String(evt.message.status_code) ); - } - - var errname = new DOMError(errName, errMsg); - Plivo.log.debug(errname); - that.callStats.reportError(null, that.callUUID, that.callStats.webRTCFunctions.signalingError, errname); - } - - that.emit('onCallFailed', evt.cause); - hangupClearance(that); - }, - 'ended': function (evt) { - Plivo.log.debug('Outgoing call ended - '+that.callUUID); - Plivo.log.info('Outgoing call ended'); - that.connStage.push('ended@'+dateMs()); - - if (that.callStats) { - that.callStats.sendFabricEvent(this.connection, that.callStats.fabricEvent.fabricTerminated, that.callUUID); - } - that.emit('onCallTerminated',{"originator":evt.originator, "reason":evt.cause}); - Plivo.AppError({"name":"onCallTerminated","originator":evt.originator,"reason":evt.cause}); - hangupClearance(that); - }, - 'getusermediafailed': function(err){ - Plivo.log.error('getusermediafailed: '+err); - if (that.userName && that.callStats) { - err.message = "getusermediafailed"; - that.callStats.reportError(null, that.userName, that.callStats.webRTCFunctions.getUserMedia, err); - } - }, - 'peerconnection:createofferfailed': function(err){ - Plivo.log.error('peerconnection:createofferfailed: ',err); - if (that.userName && that.callStats) { - err.message = "peerconnection:createofferfailed"; - that.callStats.reportError(null, that.userName, that.callStats.webRTCFunctions.createOffer, err); - } - }, - 'peerconnection:createanswerfailed': function(err){ - Plivo.log.error('peerconnection:createanswerfailed: ', err); - if (that.userName && that.callStats) { - err.message = "peerconnection:createanswerfailed"; - that.callStats.reportError(null, that.userName, that.callStats.webRTCFunctions.createAnswer, err); - } - }, - 'peerconnection:setlocaldescriptionfailed': function(err){ - Plivo.log.error('peerconnection:setlocaldescriptionfailed: ', err); - if (that.userName && that.callStats) { - err.message = "peerconnection:setlocaldescriptionfailed"; - that.callStats.reportError(null, that.userName, that.callStats.webRTCFunctions.setLocalDescription, err); - } - }, - 'peerconnection:setremotedescriptionfailed': function(err){ - if(err.message && !/pranswer/.test(err.message)){ - Plivo.log.error('peerconnection:setremotedescriptionfailed: ',err); - if (that.userName && that.callStats) { - err.message = "peerconnection:setremotedescriptionfailed"; - that.callStats.reportError(null, that.userName, that.callStats.webRTCFunctions.setRemoteDescription, err); - } - } - } - }; - try { - that.phone.call(destinationUri, opts); - Plivo.log.debug('Outgoing call options : ',JSON.stringify(opts.mediaConstraints)); - } catch (err) { - Plivo.log.error('Failed to execute plivo.onCalling event handler',err); - Plivo.AppError({"name":err.name,"message":err.message,"method":"call()"}); - return false; - } - return true; -}; - -var dateMs = function(){ - var date = new Date(); - var msdate = (date).toISOString().substring(0, 10)+" "+date.toString().split(" ")[4]+"."+date.getMilliseconds(); - return msdate; -} - -var applyStatsSettings = function(that){ - var storage = that.storage - storage.local_audio = []; - storage.remote_audio = []; - storage.mosLocalMeasures = []; - storage.mosRemoteMeasures = []; - storage.jitterLocalMeasures = []; - storage.jitterRemoteMeasures = []; - storage.packetLossRemoteMeasures = []; - storage.packetLossLocalMeasures = []; - storage.rtt = []; - storage.audioCodec = null; - // maintain all active and inactive waring status here - storage.warning = { - audioLocalMeasures : false, - audioRemoteMeasures : false, - mosLocalMeasures : false, - mosRemoteMeasures : false, - jitterLocalMeasures : false, - jitterRemoteMeasures : false, - packetLossRemoteMeasures : false, - packetLossLocalMeasures : false, - rtt : false, - ice_connection : false - } - storage.startAnalysis = false; // dont start mos immediately after call answer , wait for 5 secs - setTimeout(function(){ - storage.startAnalysis = true; - Plivo.log.debug('Stats startAnalysis started'); - },5000); - return true; -} -var callStart = function(that){ - that.storage = {}; - return applyStatsSettings(that); -} -var callStatsTokenCb = function(that){ - var forcenew = true; - return function (forcenew,callback){ - Plivo.log.info('Stats token req...'); - var options = { - 'eventHandlers': { - 'succeeded': function(e){ - Plivo.log.info('Stats token success!'); - var getToken = JSON.parse(e.response.getHeader('x-token')); - if(getToken && getToken !== "0"){ - return callback(null,getToken.token); - }else{ - Plivo.log.error('Stats token failed with 0'); - return callback('token failed 0'); - } - }, - 'failed': function(e){ - if(e.response && e.response.status_code){ - Plivo.log.error('Stats token failed!',e.response.status_code); - return callback(e.response.status_code); - }else{ - Plivo.log.error('Stats token failed!'); - return callback('failed'); - } - } - }, - 'extraHeaders':['X-appID: '+that.options.appId,'X-userID: '+that.userName] - } - that.phone.sendMessage('admin', '-- Plivo web client --', options); - } -} - -var iceConnectionCheck = function(iceState){ - // If iceState goes to disconnected or failed trigger media metrics event - if( ["disconnected","failed"].indexOf(iceState) != -1){ - _emitter(this,'network','warning','ice_connection', iceState, true, "network drop"); - if(this.storage){ - this.storage.warning.ice_connection=true; - } - } - if(iceState == "connected" && this.storage && this.storage.warning.ice_connection === true){ - _emitter(this,'network','warning','ice_connection', iceState, false); - this.storage.warning.ice_connection=false; - } -} - -var detectOWA = function(cb){ - var localStream,pc1,pc2,servers=null; - pc1 = new RTCPeerConnection(servers); - pc2 = new RTCPeerConnection(servers); - navigator.mediaDevices.getUserMedia({audio:true,video:false}).then(function(stream){ - localStream = stream; - localOffer(pc1); - }).catch(errHandler); - pc1.onicecandidate = function (e){ - onIceCandidate(pc2,e); - } - pc2.onicecandidate = function (e){ - onIceCandidate(pc1,e) - } - function onIceCandidate(pc, event) { - if(!event.candidate){ return} - pc.addIceCandidate(event.candidate) - .then() - .catch(errHandler); - } - function errHandler(err){ - cb && cb(null,err); - } - - function localOffer(pc){ - pc.addStream(localStream); - pc.createOffer().then(function(des){ - pc.setLocalDescription(des).then(function(){ - remoteOffer(pc2,des); - }).catch(errHandler); - }).catch(errHandler); - } - function remoteOffer(pc, sdp){ - pc.setRemoteDescription(sdp).then(function() { - if(sdp.type == "offer"){ - pc.createAnswer().then(function(description){ - pc.setLocalDescription(description).then(function() { - }).catch(errHandler); - remoteOffer(pc1,description); - }).catch(errHandler); - } - }).catch(errHandler); - } - function stopStream(){ - if(localStream){ - localStream.getTracks().forEach(function(track) { - track.stop(); - localStream.removeTrack(track); - localStream=null; - }); - } - pc1.signalingState == "stable" && pc1.close(); - pc2.signalingState == "stable" && pc2.close(); - } - function getStats(){ - Plivo.log.debug('getUM precheck icestate : '+ pc1.iceConnectionState); - var statsCounter=0; - function processGetStats(){ - if(pc1.getLocalStreams()[0]){ - pc1.getStats(function (res) { - res.result().forEach(function(result) { - var report = result; - if (report.type === 'ssrc' && report.stat('mediaType') === 'audio') { - var cbr = {"bytesSent": report.stat('bytesSent'), "audioInputLevel":report.stat('audioInputLevel')}; - if(Number(cbr.audioInputLevel) <= 0 && statsCounter != 2){ - statsCounter++; - setTimeout(processGetStats,1000); - Plivo.log.debug('getUM precheck re-attempt: '+statsCounter); - }else{ - cb && cb(cbr,null); - setTimeout(stopStream,3000); // since siplib new getUM at next moment is throwing user denied media - } - } - }); - }, - pc1.getLocalStreams()[0].getAudioTracks()[0], - errHandler - ); - } - } - processGetStats(); - } - // Don't wait more than 500ms - setTimeout(getStats,500); -} - -var calcConnStage = function(obj){ - var alinObj = []; - var connStart; - for(var i=0; obj.length > i; i++){ - var row = obj[i].split('@'); - if(i == 0){ - connStart = row[1]; - alinObj.push(row[0] +' = '+ row[1]+"#"); - }else{ - var ms = ( new Date(row[1]) - new Date(connStart) ); - if(ms > 1000){ - ms = ms/1000; - ms = String(ms) + "s#"; - }else{ - ms = String(ms) + "ms#"; - } - alinObj.push(row[0] +' = '+ row[1] +' +'+ms ); - } - } - alinObj = JSON.stringify(alinObj); - alinObj = alinObj.replace(/[[",\]]/g,''); - alinObj = alinObj.replace(/#/g,'\n'); - return alinObj; -} - -var isSessionConfirmed = function(session){ - if(session){ - return session.is_confirmed - }else{ - Plivo.log.debug("session not available"); - return false - } -} - -var hangupClearance = function(that){ - // Audio element clearence - that.remoteView.pause(); - Plivo.AppError(calcConnStage(that.connStage),'log'); - that.callSession = null; - delete that.storage; - that.lastCallUUID = that.callUUID; // save the last call uuid for sending quality feedback - that.callUUID = null; - that.callDirection = null; - if ( window.localStream){ - if(SipLib.adapter.browserDetails.browser == 'chrome' || that.permOnClick){ // stop local streams only for chrome - try{ - window.localStream.getTracks().forEach(function(track){ - track.stop(); - window.localStream.removeTrack(track); - }); - window.localStream = null; - }catch(err){ - Plivo.log.debug('error on stop track in localStream : '+err.message); - } - } - } -} - -module.exports = Client; -},{"../sipLib/JsSIP":41,"./media/audioDevice":3,"./media/document":4,"./util/callAnalytics":5,"./util/codecPreference":6,"./util/constants":7,"./util/headers":8,"./util/logger":9,"./util/validateOptions":10,"events":13,"util":23}],3:[function(require,module,exports){ -var constants = require('../util/constants'); - -var availableDevices = function(filterBy){ - return new Promise( function(resolve,reject){ - navigator.mediaDevices.enumerateDevices() - // Array list of all devices - .then(function(e){ - //Array desc of a single device - var list =[]; - e.filter(function(dev){ - if(filterBy == "input"){ - if(dev.kind == "audioinput"){ - list.push(dev); - } - }else if(filterBy == "output"){ - if(dev.kind == "audiooutput"){ - list.push(dev); - } - }else{ - // push all audio input and output devices - if( !(/video/i).test(dev.kind) ){ - list.push(dev); - } - } - }); - resolve(list); - }) - .catch(function (error){ - reject(error); - }) - }); -} - -var revealAudioDevices = function(arg){ - return new Promise(function(resolve,reject){ - if(navigator.mediaDevices.getUserMedia) { - navigator.mediaDevices.getUserMedia({audio:true,video:false}) - .then(function(stream) { - if(arg == "returnStream"){ - resolve(stream); - }else{ - stream.getTracks().forEach(function(track) { - track.stop(); - }); - resolve("success"); - } - }) - .catch(function(err) { - Plivo.log.error('failed to get user media :: '+err.name); - reject(err.name); - }); - }else{ reject("no getUserMedia support"); } - }); -} - -var inputDevices = (function(){ - return { - set: function(deviceId){ - if(typeof deviceId == "string" && 'optional' in Plivo.audioConstraints){ - Plivo.audioConstraints.optional.push({"sourceId":deviceId}); - return true; - } - }, - get: function(){ - if(Plivo.audioConstraints.optional){ - var sourceId = Plivo.audioConstraints.optional.filter(function(e){ - return e["sourceId"]; - }); - if(sourceId.length > 0){ - return sourceId[0]["sourceId"]; - }else{ - return ""; - } - }else{ - return ""; - } - }, - reset: function(){ - if(Plivo.audioConstraints.optional){ - Plivo.audioConstraints.optional = Plivo.audioConstraints.optional.filter(function(e){ - return !e["sourceId"]; - }); - } - return true; - } - } -})(); - -var outputDevices = (function(){ - return { - set : function(deviceId){ - var speakerElement = document.querySelectorAll('[data-devicetype="speakerDevice"]'); - speakerElement.forEach(function(e){ - e.setSinkId && e.setSinkId(deviceId); - }); - return true; - }, - get: function(){ - var speakerElement = document.querySelector('[data-devicetype="speakerDevice"]'); - if(speakerElement.sinkId) - return speakerElement.sinkId; - }, - reset: function(){ - var speakerElement = document.querySelectorAll('[data-devicetype="speakerDevice"]'); - speakerElement.forEach(function(e){ - e.setSinkId && e.setSinkId(""); - }); - return true; - }, - media: function(source){ - var sourceMap = { - dtmf : "dtmfstar", - ringback: constants.RINGBACK_ELEMENT_ID - } - if(source && source in sourceMap){ - return document.getElementById(sourceMap[source]); - }else{ - return document.getElementById(constants.RINGBACK_ELEMENT_ID); - } - } - } -})(); - -var ringtoneDevices = (function(){ - return { - set : function(deviceId){ - var ringToneElement = document.getElementById(constants.RINGTONE_ELEMENT_ID); - ringToneElement.setSinkId && ringToneElement.setSinkId(deviceId); - return true; - }, - get: function(){ - var ringToneElement = document.getElementById(constants.RINGTONE_ELEMENT_ID); - if(ringToneElement.sinkId) - return ringToneElement.sinkId; - }, - reset: function(){ - var ringToneElement = document.getElementById(constants.RINGTONE_ELEMENT_ID); - ringToneElement.setSinkId && ringToneElement.setSinkId(""); - return true; - }, - media: function(){ - return document.getElementById(constants.RINGTONE_ELEMENT_ID); - } - } -})(); - -/* - @param store true/false - true to store in Client for reference -*/ -var audioDevDictionary = function(store){ - var that = this; - return new Promise( function(resolve,reject){ - availableDevices().then(function(e){ - var audioRef = []; - e.forEach(function(dev){ - // If device label is not set then audioRef should be null - if(dev.label){ - var strObj = JSON.stringify(dev); - audioRef.push(strObj); - }else{ - audioRef = null; - } - }); - if(store){ - that.audioDevDic = audioRef; - resolve(true); - }else{ - resolve(audioRef); // If you don't want to store then receive as cb - } - }).catch(function(err){ - Plivo.log.error('Error availableDevices() ',err); - reject(err); - }); - }); -} - -var checkAudioDevChange = function(){ - var that = this; - var deviceAdded, deviceRemoved; - audioDevDictionary().then(function(audioRef){ - if(that.audioDevDic && audioRef){ - //Check if device is newly added with new device change audioRef - audioRef.forEach(function(e){ - if(that.audioDevDic.indexOf(e) == -1){ // If not present - deviceAdded = JSON.parse(e); - /* - Setting USB audio device as default in mac sound settings will create below - 1. fire new default device obj for USB audio - 2. fire new device obj with proper lable name for USB audio - So ignore any new default device object, since we reference point '2' - */ - if(!/default/i.test(deviceAdded.deviceId)){ - that.emit('audioDeviceChange',{change:"added",device:deviceAdded}); - } - } - }); - //Check if device is removed with exising audioDic - that.audioDevDic.forEach(function(e){ - if(audioRef.indexOf(e) == -1){ // If not present - deviceRemoved = JSON.parse(e); - /* - Ignore any default device object which is removed - */ - if(!/default/i.test(deviceRemoved.deviceId)){ - that.emit('audioDeviceChange',{change:"removed",device:deviceRemoved}); - } - } - }); - } - if(!that.audioDevDic){ - that.emit('audioDeviceChange',{change:"",device:""}); - } - if(audioRef){ //Update existing audioDevDic - that.audioDevDic = audioRef; - } - }).catch(function(err){ - Plivo.log.error('Error checkAudioDevChange() ',err); - }); -} - -module.exports.inputDevices = inputDevices; -module.exports.outputDevices = outputDevices; -module.exports.ringtoneDevices = ringtoneDevices; -module.exports.revealAudioDevices = revealAudioDevices; -module.exports.availableDevices = availableDevices; -module.exports.audioDevDictionary = audioDevDictionary; -module.exports.checkAudioDevChange = checkAudioDevChange; -},{"../util/constants":7}],4:[function(require,module,exports){ -'use strict'; -var constants = require('../util/constants'); - -var setup = function(options, cb) { - var remoteView = document.createElement('audio'); - remoteView.id = constants.REMOTE_VIEW_ID; - remoteView.hidden = true; - remoteView.autoplay = true; - remoteView.width = 0; - remoteView.height = 0; - remoteView.setAttribute('data-devicetype','speakerDevice'); - document.body.appendChild(remoteView); - - var audioConnectingElement = document.createElement('audio'); - audioConnectingElement.id = constants.CONNECT_TONE_ELEMENT_ID; - audioConnectingElement.loop = 'loop'; - audioConnectingElement.src = constants.CONNECT_TONE_URL; - audioConnectingElement.setAttribute('data-devicetype','speakerDevice'); - document.body.appendChild(audioConnectingElement); - - var audioRingBackElement = document.createElement('audio'); - audioRingBackElement.id = constants.RINGBACK_ELEMENT_ID; - audioRingBackElement.loop = 'loop'; - audioRingBackElement.src = constants.RINGTONE_URL; - audioRingBackElement.setAttribute('data-devicetype','speakerDevice'); - document.body.appendChild(audioRingBackElement); - - var audioRingToneElement = document.createElement('audio'); - audioRingToneElement.id = constants.RINGTONE_ELEMENT_ID; - audioRingToneElement.loop = 'loop'; - audioRingToneElement.src = constants.RINGTONE_URL; - audioRingToneElement.setAttribute('data-devicetype','ringtoneDevice'); - document.body.appendChild(audioRingToneElement); - - var format = 'mp3'; - var baseUrl = 'https://cdn.plivo.com/sdk/browser/audio/dtmf-'; - - var addDTMFTone = function (baseUrl, digit, format) { - var id = 'dtmf' + digit; - var src = baseUrl + digit + '.' + format; - var obj = document.createElement('audio'); - obj.id = id; - obj.src = src; - obj.setAttribute('data-devicetype','speakerDevice'); - document.body.appendChild(obj); - }; - - for (var i = 0; i <= 9; i++) { - addDTMFTone(baseUrl, i, format); - } - - addDTMFTone(baseUrl, 'star', format); - addDTMFTone(baseUrl, 'pound', format); - - if(options.permOnClick){ - window.localStream = null; - cb({status:'success',stream:false}); - }else{ - getLocalMedia(options.audioConstraints,function(evt){ - cb(evt); - }); - } -}; - -var getLocalMedia = function(audioConstraints, cb){ - if (navigator.mediaDevices.getUserMedia) { - navigator.mediaDevices.getUserMedia({audio: audioConstraints,video: false}) - .then(function(stream) { - window.localStream = stream; - Plivo.log.debug('getUserMedia success'); - cb({'status':'success','stream':true}); - }) - .catch(function(err) { - Plivo.log.error('failed to get user media :: '+err.name); - cb({'status':'failure','error':err.name}); - }); - }else{ - Plivo.log.error('getUserMedia not available'); - cb({status:'failure','error':'getUserMedia not supported'}); - } -} - -var playAudio = function(elementId) { - try { - document.getElementById(elementId).play(); - Plivo.log.debug('playAudio - '+elementId); - } catch (e) { - Plivo.log.debug('failed to play audio for elementId ' + elementId + ' Cause: ' + e); - } -}; - -var stopAudio = function(elementId) { - try { - document.getElementById(elementId).pause(); - Plivo.log.debug('stopAudio - '+elementId); - } catch (e) { - Plivo.log.debug('failed to stop audio for elementId ' + elementId + ' Cause: ' + e); - } -}; - -var maskPage = function () { - var tag = document.createElement('div'); - tag.id = "plivo_mask"; - document.body.insertBefore(tag, document.body.firstChild); - tag.style.position = "fixed"; - tag.style.top = "0"; - tag.style.left = "0"; - tag.style.width = "100%"; - tag.style.height = "100%"; - tag.style.background = "#000"; - tag.style.opacity = "0.8"; - tag.style.filter = "alpha(opacity=80)"; - tag.style.zindex = "50"; -}; - -module.exports.setup = setup; -module.exports.getLocalMedia = getLocalMedia; -module.exports.playAudio = playAudio; -module.exports.stopAudio = stopAudio; -module.exports.maskPage = maskPage; -},{"../util/constants":7}],5:[function(require,module,exports){ -var processSteams = function(_emitter, streams){ - var that = this; - function processAudioLevel(type,val){ - var audioObj = that.storage[type]; - if(audioObj.length == 2){ // Check at every 3 collection - audioObj.push(Number(val)); - - // unchanged volume level is processed here; - var identicalCollector = {}; - var audioVol = null; // most identical audio volume gets updated here - audioObj.forEach(function(val){ - identicalCollector[val] = identicalCollector[val] + 1 || 1; - }); - for(var vol in identicalCollector){ - if(identicalCollector[vol] >=2){ // if 2 or more vol is same out of 3 sample - audioVol = Number(vol); - } - } - if(typeof audioVol == "number"){ //identical volumes like 0, 8 are considered to mute - that.storage.warning[type] = true; - if(audioVol > 1){ - Plivo.log.debug('Same audioLevel detected for '+type+" : ",that.str(audioObj)); - }else{ - Plivo.log.debug('Audio mute detected for '+type+" : ",that.str(audioObj)); - } - _emitter(that,'audio','warning','no_audio_received', audioVol, true, type); - }else{ - that.storage.warning[type] ? (that.storage.warning[type]=false, _emitter(that,'audio','warning','no_audio_received', 0, false, type)) : null; - } - }else{ - audioObj.push(Number(val)); - } - if(audioObj.length == 3) - audioObj.splice(0,2) // remove first 2, after every 3 samples - } - function processRtt(type, val){ - var val = Number(val); - var rttObj = that.storage[type]; - if(rttObj.length == 2){ - rttObj.push(val); - // console.debug('processRtt',rttObj); - var totRttObj = rttObj.filter(function (item, pos){ - return item > 400; - }); - if(totRttObj.length >= 2){ - var rttSum = totRttObj.reduce(function(sum, val){ - return sum + val; - }); - var rttAvg = (rttSum / totRttObj.length ).toFixed(2); - that.storage.warning[type] = true; - Plivo.log.debug(type+" : getting high rtt : ",that.str(totRttObj)); - _emitter(that,'network','warning','high_rtt', rttAvg, true, 'high latency'); - }else{ - that.storage.warning[type] ? (that.storage.warning[type]=false, _emitter(that,'network','warning','high_rtt', 0, false)) : null; - } - }else{ - rttObj.push(val); - } - if(rttObj.length == 3) - rttObj.splice(0,2) // remove first 2, after every 3 samples - } - function processJitter(type,val){ - var val = Number(val); - var jitterObj = that.storage[type]; - if(jitterObj.length == 2){ - jitterObj.push(val); - // console.debug('processJitter',jitterObj); - var totJitterObj = jitterObj.filter(function (item, pos){ - return item > 30; - }); - if(totJitterObj.length >= 2){ - var jitterSum = totJitterObj.reduce(function(sum, val){ - return sum + val; - }); - var jitterAvg = jitterSum / totJitterObj.length; - that.storage.warning[type] = true; - Plivo.log.debug(type+" : getting high jitter rate : ",that.str(totJitterObj)); - _emitter(that,'network','warning','high_jitter', jitterAvg, true, type); - }else{ - that.storage.warning[type] ? (that.storage.warning[type]=false, _emitter(that,'network','warning','high_jitter', 0, false, type)) : null; - } - }else{ - jitterObj.push(val); - } - if(jitterObj.length == 3) - jitterObj.splice(0,2) // remove first 2, after every 3 samples - } - function processMos(type,val){ - // Ignore first 3 MOS score of a new call, since first 2-3 mos comes as fair - var mosObj = that.storage[type]; - if(mosObj.length == 2){ - mosObj.push(val); - // console.debug('processMos',mosObj); - var totMosObj = mosObj.filter(function (item, pos){ - if(that.storage.audioCodec == "opus"){ // for opus alone look for "bad" mos - return item == 'bad'; - }else{ - return item != 'excellent'; - } - }); - if(totMosObj.length >= 2){ - that.storage.warning[type] = true; - Plivo.log.debug(type+" : getting low mos : ",that.str(mosObj)); - _emitter(that,'network','warning','low_mos', totMosObj[0], true, type); - }else{ - that.storage.warning[type] ? (that.storage.warning[type]=false, _emitter(that,'network','warning','low_mos', 0, false, type)) : null; - } - }else{ - mosObj.push(val); - } - if(mosObj.length == 3) - mosObj.splice(0,2) // remove first 2, after every 3 samples - } - function processPacketLoss(type, val){ - var val = Number(val); - var plossObj = that.storage[type]; - if(plossObj.length == 2){ // Check at every 3 collection - plossObj.push(val); - // console.debug('processPacketLoss',plossObj); - var totPlossObj = plossObj.filter(function (item, pos){ - if(that.storage.audioCodec == "opus"){ - return item >= 0.10; // greater than 10% - }else{ - return item >= 0.02; // greater than 2% - } - }); - if(totPlossObj.length >= 2){ - var plossSum = totPlossObj.reduce(function (sum, val){ - return sum + val; - }); - var plossAvg = plossSum / totPlossObj.length; - plossAvg = plossAvg.toFixed(3); - that.storage.warning[type] = true; - Plivo.log.debug(type+' : ploss score value is high :',that.str(totPlossObj)); - _emitter(that,'network','warning','high_packetloss', plossAvg, true, type); - }else{ - that.storage.warning[type] ? (that.storage.warning[type]=false,_emitter(that,'network','warning','high_packetloss', 0, false, type)): null; - } - }else{ - plossObj.push(val); - } - if(plossObj.length == 3) - plossObj.splice(0,2) // remove first 2, after every 3 samples - } - - // actual handler - if(!that.storage || !that.storage.startAnalysis){ // start only if startAnalysis becomes true - return; - } - - for( var key in streams){ - //local - if("audioInputLevel" in streams[key]){ - var obj = streams[key], - fractionLoss = obj.fractionLoss? obj.fractionLoss.toFixed(2) : 0, - bitrate = obj.bitrate ? obj.bitrate.toFixed(2) : 0, - quality = obj.quality || null, - rtt = obj.rtt || 0, - jitter = obj.jitter || 0, - audioInputLevel=obj.audioInputLevel || 0; - processAudioLevel("local_audio", audioInputLevel); - processRtt("rtt",rtt); - processJitter('jitterLocalMeasures',jitter); - // processMos('local',quality); - processPacketLoss('packetLossLocalMeasures',fractionLoss); - // remote - }else if("audioOutputLevel" in streams[key]){ - var obj = streams[key], - fractionLoss = obj.fractionLoss? obj.fractionLoss.toFixed(2) : 0, - bitrate = obj.bitrate ? obj.bitrate.toFixed(2) : 0, - quality = obj.quality || null, - jitter = obj.jitter || 0, - audioOutputLevel=obj.audioOutputLevel || 0; - processAudioLevel("remote_audio", audioOutputLevel); - processJitter('jitterRemoteMeasures',jitter); - processMos('mosRemoteMeasures',quality); - processPacketLoss('packetLossRemoteMeasures',fractionLoss); - } - } -} - -module.exports = processSteams; -},{}],6:[function(require,module,exports){ -var codecPref = function(prefCodecs, sdp){ - - function getPayloadValue(codec, sdp){ - var reg = new RegExp( 'a=rtpmap:.* '+codec+'(.*)', 'ig'); - if(sdp.match(reg)){ - return sdp.match(reg)[0].split(' ')[0].match(/\d+/); - }else{ - return false; - } - } - - function clearCodec(payloadVal, sdp){ - var reg; - payloadVal.forEach(function(codec){ - var val = getPayloadValue(codec,sdp); - // clear in rtpmap - reg = new RegExp ('\na=rtpmap:.*'+codec+'\/.*','ig'); - sdp = sdp.replace(reg,''); - // clear in fmtp - reg = new RegExp ('\na=fmtp:'+val+' (.*)','ig'); - sdp = sdp.replace(reg,''); - // clear in rtcp - reg = new RegExp ('\na=rtcp-fb:'+val+' (.*)','ig'); - sdp = sdp.replace(reg,''); - }); - return sdp; - } - - if(prefCodecs.length > 0){ - var totalList = ['OPUS','G722','PCMA','PCMU','ISAC','CN']; - var codecListName = prefCodecs; - var codecListVal = ""; - codecListName.forEach(function(codec){ - var index = totalList.indexOf(codec); - if(index > -1){ - totalList.splice(index, 1); - } - var codecPayloadVal = getPayloadValue(codec,sdp); - if(codecPayloadVal) - codecListVal += codecPayloadVal + " "; - }); - codecListVal = codecListVal.slice(0,-1); - sdp = sdp.replace(sdp.match(/m=audio .*[a-z] (.*)/i)[1],codecListVal); - sdp = clearCodec(totalList,sdp); - } - return sdp; -} - -module.exports = codecPref -},{}],7:[function(require,module,exports){ -'use strict'; - -//webrtc settings -module.exports.DEFAULT_LOG_LEVEL = 'INFO'; -module.exports.DOMAIN = 'phone.plivo.com'; -module.exports.WS_SERVERS = 'wss://phone.plivo.com:5063'; -module.exports.REGISTER_EXPIRES_SECONDS = 120; -module.exports.SESSION_TIMERS_EXPIRES = 300; -module.exports.WS_RECOVERY_MAX_INTERVAL = 20; -module.exports.WS_RECOVERY_MIN_INTERVAL = 2; -module.exports.DEFAULT_CODECS = ['OPUS','PCMU']; -module.exports.STUN_SERVERS = ['stun:stun.l.google.com:19302','stun:stun1.l.google.com:19302']; -module.exports.LIB_NAME = 'plivojs'; -module.exports.DEBUG_MODES = ['INFO','DEBUG','WARN','ERROR','ALL','ALL-PLAIN','OFF']; -module.exports.REGION = ["usa_west","usa_east","australia","europe","asia","south_america"]; -//document settings -module.exports.RINGTONE_URL = 'https://cdn.plivo.com/sdk/browser/audio/us-ring.mp3'; -module.exports.CONNECT_TONE_URL = 'https://cdn.plivo.com/sdk/browser/audio/connect-tone.mp3'; -module.exports.SELF_VIEW_ID = 'plivo_webrtc_selfview'; -module.exports.REMOTE_VIEW_ID = 'plivo_webrtc_remoteview'; // depreciate it. Since remote view is needed only for Video -module.exports.RINGBACK_ELEMENT_ID = 'plivo_ringbacktone'; -module.exports.RINGTONE_ELEMENT_ID = 'plivo_ringtone'; -module.exports.CONNECT_TONE_ELEMENT_ID = 'plivo_connect_tone'; -module.exports.DTMF_TONE_FLAG = { - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - '#': true, - '*': true -}; - -module.exports.DEFAULT_COMMENTS = ['bad-audio', 'call-dropped', 'wrong-callerid', 'post-dial-delay', 'dtmf-not-captured', 'audio-latency', 'unsolicited-call', 'one-way-audio', 'no-audio', 'never-connected'] - -var DEFAULT_OFFER_OPTIONS = {}; -if (typeof navigator !== 'undefined' && navigator.mozGetUserMedia) { - DEFAULT_OFFER_OPTIONS = { - offerToReceiveAudio: true - }; -} else { - DEFAULT_OFFER_OPTIONS.mandatory = { - OfferToReceiveAudio: true - }; -} -module.exports.DEFAULT_OFFER_OPTIONS = DEFAULT_OFFER_OPTIONS; - -},{}],8:[function(require,module,exports){ -'use strict'; - -var checkExtraHeaderKey = function (key) { - //key started by X-Ph- - if (key.substr(0, 5) != "X-Ph-" && key.substr(0, 5) != "X-PH-") { - return false; - } - - //key only contain [A-Z], [a-z] and [0-9], max length = 24 - //19 = 24 - 5 - var keyRegex = /^([a-z0-9A-Z]){1,19}$/; - return keyRegex.test(key.substr(5)) !== false; -}; - -var checkExtraHeaderVal = function (value) { - //value only contain [A-Z], [a-z], [0-9] and '%', max length = 48 - var valRegex = /^([a-z0-9A-Z_\-\+\(\)%]){1,120}$/; //+-_() added to Customer headers on 13th April as per callstats.io request - return valRegex.test(value) !== false; -}; - -var receiveExtraHeader = function(request, headers) { - var cleanExtraHeaders = {}; - for (var key in headers) { - var val = request.getHeader(key); - if (checkExtraHeaderKey(key) && checkExtraHeaderVal(val)) { - cleanExtraHeaders[key] = val; - } - } - - return cleanExtraHeaders; -}; - -module.exports.checkExtraHeaderKey = checkExtraHeaderKey; -module.exports.checkExtraHeaderVal = checkExtraHeaderVal; -module.exports.receiveExtraHeader = receiveExtraHeader; - -},{}],9:[function(require,module,exports){ -var logger = function (options) { - options? options : (options = {}); - var allowedMethods = ['INFO','DEBUG','WARN','ERROR','ALL','OFF'] - ,logMethod = options.logMethod || "INFO" - ,enableDate = options.enableDate || false - ,loggingName = options.loggingName || ""; - var localStorage = (typeof chrome != 'undefined' && chrome.storage) ? chrome.storage.local : window.localStorage; - var logit = function(){ - function logging(){ - if(enableDate){ - var date = new Date(); - var msdate = (date).toISOString().substring(0, 10)+" "+date.toString().split(" ")[4]+"."+date.getMilliseconds(); - console.log("["+msdate+"]" + " ["+filter+"] "+loggingName+" :: ",arg1,arg2); - }else{ - console.log("["+filter+"] "+loggingName+" :: ",arg1,arg2); - } - } - var filter = arguments[0].toUpperCase() // will give info/debug/warn/error etc - ,args = arguments[1] - ,arg1 = args[0] || "" - ,arg2 = args[1] || ""; - if(logMethod == "DEBUG" || logMethod == "ALL"){ - logging(); - }else if(logMethod == filter){ - logging(); - }else{ - return; - } - } - return { - info: function(){ - logit('info',arguments); - }, - debug: function(){ - logit('debug',arguments); - }, - warn: function(){ - logit('warn',arguments); - }, - error: function(){ - logit('error',arguments); - }, - setLevel: function(method){ - method = method.toUpperCase(); - if(allowedMethods.indexOf(method) != -1){ // in allowed methods? - logMethod = method; - if(['DEBUG','ALL'].indexOf(method) == -1){ // if not debug/all! - localStorage.debug=""; - } - return 'logLevel is now : '+logMethod; - }else{ - return 'only : '+allowedMethods.toString() + ' are allowed in run time!' - } - }, - level: function(){ - return logMethod; - } - } -} -module.exports = logger; -},{}],10:[function(require,module,exports){ -var codecs = function (codecs, defaultCodecs){ - if(Object.prototype.toString.call(codecs) == "[object Array]"){ - var isCheckPassed=true; - codecs.forEach(function(codec){ - if(defaultCodecs.indexOf(codec) == -1){ - isCheckPassed = false; - Plivo.log.warn('Ignoring invalid codec - ',codec); - Plivo.log.debug('Allowed list: ',defaultCodecs); - } - }); - if(isCheckPassed){ - return true; - }else{ - return false; - } - }else{ - Plivo.log.error('Please send codecs in Array. Eg:',defaultCodecs); - return false; - } -} - -var isBoolean = function (key, val){ - if(typeof val == "boolean"){ - return true; - }else{ - Plivo.log.error(key +' has to be boolean. '+ val + ' is not accepted') - return false; - } -} - -var debug = function (mode, defaultModes) { - if(defaultModes.indexOf(mode) == -1){ - Plivo.log.error('debug method '+mode+' is not allowed'); - Plivo.log.debug('Allowed list for debug: ',defaultModes); - return false; - }else{ - return true; - } -} - -var region = function (name, defaultRegions){ - if(defaultRegions.indexOf(name) == -1){ - Plivo.log.error('region name '+ name + ' is not allowed'); - Plivo.log.debug('Allowed list for regions: ',defaultRegions); - return false; - }else{ - return true; - } -} - -module.exports = { - codecs: codecs, - isBoolean : isBoolean, - debug: debug, - region: region -} -},{}],11:[function(require,module,exports){ -(function (process){ -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = window._PlivoUseColorLog; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} - -}).call(this,require('_process')) -},{"./debug":12,"_process":15}],12:[function(require,module,exports){ - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - -exports.formatters = {}; - -/** - * Previous log timestamp. - */ - -var prevTime; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; - - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return exports.colors[Math.abs(hash) % exports.colors.length]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - return debug; -} - -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} - -},{"ms":14}],13:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; - -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } - throw TypeError('Uncaught, unspecified "error" event.'); - } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - len = arguments.length; - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - handler.apply(this, args); - } - } else if (isObject(handler)) { - len = arguments.length; - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - var m; - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.listenerCount = function(emitter, type) { - var ret; - if (!emitter._events || !emitter._events[type]) - ret = 0; - else if (isFunction(emitter._events[type])) - ret = 1; - else - ret = emitter._events[type].length; - return ret; -}; - -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - -},{}],14:[function(require,module,exports){ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - -},{}],15:[function(require,module,exports){ -// shim for using process in browser - -var process = module.exports = {}; -var queue = []; -var draining = false; - -function drainQueue() { - if (draining) { - return; - } - draining = true; - var currentQueue; - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - var i = -1; - while (++i < len) { - currentQueue[i](); - } - len = queue.length; - } - draining = false; -} -process.nextTick = function (fun) { - queue.push(fun); - if (!draining) { - setTimeout(drainQueue, 0); - } -}; - -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -// TODO(shtylman) -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],16:[function(require,module,exports){ -var grammar = module.exports = { - v: [{ - name: 'version', - reg: /^(\d*)$/ - }], - o: [{ //o=- 20518 0 IN IP4 203.0.113.1 - // NB: sessionId will be a String in most cases because it is huge - name: 'origin', - reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/, - names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'], - format: '%s %s %d %s IP%d %s' - }], - // default parsing of these only (though some of these feel outdated) - s: [{ name: 'name' }], - i: [{ name: 'description' }], - u: [{ name: 'uri' }], - e: [{ name: 'email' }], - p: [{ name: 'phone' }], - z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly.. - r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly - //k: [{}], // outdated thing ignored - t: [{ //t=0 0 - name: 'timing', - reg: /^(\d*) (\d*)/, - names: ['start', 'stop'], - format: '%d %d' - }], - c: [{ //c=IN IP4 10.47.197.26 - name: 'connection', - reg: /^IN IP(\d) (\S*)/, - names: ['version', 'ip'], - format: 'IN IP%d %s' - }], - b: [{ //b=AS:4000 - push: 'bandwidth', - reg: /^(TIAS|AS|CT|RR|RS):(\d*)/, - names: ['type', 'limit'], - format: '%s:%s' - }], - m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31 - // NB: special - pushes to session - // TODO: rtp/fmtp should be filtered by the payloads found here? - reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/, - names: ['type', 'port', 'protocol', 'payloads'], - format: '%s %d %s %s' - }], - a: [ - { //a=rtpmap:110 opus/48000/2 - push: 'rtp', - reg: /^rtpmap:(\d*) ([\w\-\.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/, - names: ['payload', 'codec', 'rate', 'encoding'], - format: function (o) { - return (o.encoding) ? - 'rtpmap:%d %s/%s/%s': - o.rate ? - 'rtpmap:%d %s/%s': - 'rtpmap:%d %s'; - } - }, - { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000 - //a=fmtp:111 minptime=10; useinbandfec=1 - push: 'fmtp', - reg: /^fmtp:(\d*) ([\S| ]*)/, - names: ['payload', 'config'], - format: 'fmtp:%d %s' - }, - { //a=control:streamid=0 - name: 'control', - reg: /^control:(.*)/, - format: 'control:%s' - }, - { //a=rtcp:65179 IN IP4 193.84.77.194 - name: 'rtcp', - reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/, - names: ['port', 'netType', 'ipVer', 'address'], - format: function (o) { - return (o.address != null) ? - 'rtcp:%d %s IP%d %s': - 'rtcp:%d'; - } - }, - { //a=rtcp-fb:98 trr-int 100 - push: 'rtcpFbTrrInt', - reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/, - names: ['payload', 'value'], - format: 'rtcp-fb:%d trr-int %d' - }, - { //a=rtcp-fb:98 nack rpsi - push: 'rtcpFb', - reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/, - names: ['payload', 'type', 'subtype'], - format: function (o) { - return (o.subtype != null) ? - 'rtcp-fb:%s %s %s': - 'rtcp-fb:%s %s'; - } - }, - { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset - //a=extmap:1/recvonly URI-gps-string - push: 'ext', - reg: /^extmap:(\d+)(?:\/(\w+))? (\S*)(?: (\S*))?/, - names: ['value', 'direction', 'uri', 'config'], - format: function (o) { - return 'extmap:%d' + (o.direction ? '/%s' : '%v') + ' %s' + (o.config ? ' %s' : ''); - } - }, - { //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32 - push: 'crypto', - reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/, - names: ['id', 'suite', 'config', 'sessionConfig'], - format: function (o) { - return (o.sessionConfig != null) ? - 'crypto:%d %s %s %s': - 'crypto:%d %s %s'; - } - }, - { //a=setup:actpass - name: 'setup', - reg: /^setup:(\w*)/, - format: 'setup:%s' - }, - { //a=mid:1 - name: 'mid', - reg: /^mid:([^\s]*)/, - format: 'mid:%s' - }, - { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a - name: 'msid', - reg: /^msid:(.*)/, - format: 'msid:%s' - }, - { //a=ptime:20 - name: 'ptime', - reg: /^ptime:(\d*)/, - format: 'ptime:%d' - }, - { //a=maxptime:60 - name: 'maxptime', - reg: /^maxptime:(\d*)/, - format: 'maxptime:%d' - }, - { //a=sendrecv - name: 'direction', - reg: /^(sendrecv|recvonly|sendonly|inactive)/ - }, - { //a=ice-lite - name: 'icelite', - reg: /^(ice-lite)/ - }, - { //a=ice-ufrag:F7gI - name: 'iceUfrag', - reg: /^ice-ufrag:(\S*)/, - format: 'ice-ufrag:%s' - }, - { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g - name: 'icePwd', - reg: /^ice-pwd:(\S*)/, - format: 'ice-pwd:%s' - }, - { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33 - name: 'fingerprint', - reg: /^fingerprint:(\S*) (\S*)/, - names: ['type', 'hash'], - format: 'fingerprint:%s %s' - }, - { //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host - //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 network-id 3 network-cost 10 - //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 network-id 3 network-cost 10 - //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0 network-id 3 network-cost 10 - //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0 network-id 3 network-cost 10 - push:'candidates', - reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/, - names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation', 'network-id', 'network-cost'], - format: function (o) { - var str = 'candidate:%s %d %s %d %s %d typ %s'; - - str += (o.raddr != null) ? ' raddr %s rport %d' : '%v%v'; - - // NB: candidate has three optional chunks, so %void middles one if it's missing - str += (o.tcptype != null) ? ' tcptype %s' : '%v'; - - if (o.generation != null) { - str += ' generation %d'; - } - - str += (o['network-id'] != null) ? ' network-id %d' : '%v'; - str += (o['network-cost'] != null) ? ' network-cost %d' : '%v'; - return str; - } - }, - { //a=end-of-candidates (keep after the candidates line for readability) - name: 'endOfCandidates', - reg: /^(end-of-candidates)/ - }, - { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ... - name: 'remoteCandidates', - reg: /^remote-candidates:(.*)/, - format: 'remote-candidates:%s' - }, - { //a=ice-options:google-ice - name: 'iceOptions', - reg: /^ice-options:(\S*)/, - format: 'ice-options:%s' - }, - { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1 - push: 'ssrcs', - reg: /^ssrc:(\d*) ([\w_]*)(?::(.*))?/, - names: ['id', 'attribute', 'value'], - format: function (o) { - var str = 'ssrc:%d'; - if (o.attribute != null) { - str += ' %s'; - if (o.value != null) { - str += ':%s'; - } - } - return str; - } - }, - { //a=ssrc-group:FEC 1 2 - //a=ssrc-group:FEC-FR 3004364195 1080772241 - push: 'ssrcGroups', - // token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 / %x41-5A / %x5E-7E - reg: /^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/, - names: ['semantics', 'ssrcs'], - format: 'ssrc-group:%s %s' - }, - { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV - name: 'msidSemantic', - reg: /^msid-semantic:\s?(\w*) (\S*)/, - names: ['semantic', 'token'], - format: 'msid-semantic: %s %s' // space after ':' is not accidental - }, - { //a=group:BUNDLE audio video - push: 'groups', - reg: /^group:(\w*) (.*)/, - names: ['type', 'mids'], - format: 'group:%s %s' - }, - { //a=rtcp-mux - name: 'rtcpMux', - reg: /^(rtcp-mux)/ - }, - { //a=rtcp-rsize - name: 'rtcpRsize', - reg: /^(rtcp-rsize)/ - }, - { //a=sctpmap:5000 webrtc-datachannel 1024 - name: 'sctpmap', - reg: /^sctpmap:([\w_\/]*) (\S*)(?: (\S*))?/, - names: ['sctpmapNumber', 'app', 'maxMessageSize'], - format: function (o) { - return (o.maxMessageSize != null) ? - 'sctpmap:%s %s %s' : - 'sctpmap:%s %s'; - } - }, - { //a=x-google-flag:conference - name: 'xGoogleFlag', - reg: /^x-google-flag:([^\s]*)/, - format: 'x-google-flag:%s' - }, - { //a=rid:1 send max-width=1280;max-height=720;max-fps=30;depend=0 - push: 'rids', - reg: /^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/, - names: ['id', 'direction', 'params'], - format: function (o) { - return (o.params) ? 'rid:%s %s %s' : 'rid:%s %s'; - } - }, - { //a=imageattr:97 send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] recv [x=330,y=250] - //a=imageattr:* send [x=800,y=640] recv * - //a=imageattr:100 recv [x=320,y=240] - push: 'imageattrs', - reg: new RegExp( - //a=imageattr:97 - '^imageattr:(\\d+|\\*)' + - //send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] - '[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)' + - //recv [x=330,y=250] - '(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?' - ), - names: ['pt', 'dir1', 'attrs1', 'dir2', 'attrs2'], - format: function (o) { - return 'imageattr:%s %s %s' + (o.dir2 ? ' %s %s' : ''); - } - }, - { //a=simulcast:send 1,2,3;~4,~5 recv 6;~7,~8 - //a=simulcast:recv 1;4,5 send 6;7 - name: 'simulcast', - reg: new RegExp( - //a=simulcast: - '^simulcast:' + - //send 1,2,3;~4,~5 - '(send|recv) ([a-zA-Z0-9\\-_~;,]+)' + - //space + recv 6;~7,~8 - '(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?' + - //end - '$' - ), - names: ['dir1', 'list1', 'dir2', 'list2'], - format: function (o) { - return 'simulcast:%s %s' + (o.dir2 ? ' %s %s' : ''); - } - }, - { //Old simulcast draft 03 (implemented by Firefox) - // https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-03 - //a=simulcast: recv pt=97;98 send pt=97 - //a=simulcast: send rid=5;6;7 paused=6,7 - name: 'simulcast_03', - reg: /^simulcast:[\s\t]+([\S+\s\t]+)$/, - names: ['value'], - format: 'simulcast: %s' - }, - { - //a=framerate:25 - //a=framerate:29.97 - name: 'framerate', - reg: /^framerate:(\d+(?:$|\.\d+))/, - format: 'framerate:%s' - }, - { // any a= that we don't understand is kepts verbatim on media.invalid - push: 'invalid', - names: ['value'] - } - ] -}; - -// set sensible defaults to avoid polluting the grammar with boring details -Object.keys(grammar).forEach(function (key) { - var objs = grammar[key]; - objs.forEach(function (obj) { - if (!obj.reg) { - obj.reg = /(.*)/; - } - if (!obj.format) { - obj.format = '%s'; - } - }); -}); - -},{}],17:[function(require,module,exports){ -var parser = require('./parser'); -var writer = require('./writer'); - -exports.write = writer; -exports.parse = parser.parse; -exports.parseFmtpConfig = parser.parseFmtpConfig; -exports.parseParams = parser.parseParams; -exports.parsePayloads = parser.parsePayloads; -exports.parseRemoteCandidates = parser.parseRemoteCandidates; -exports.parseImageAttributes = parser.parseImageAttributes; -exports.parseSimulcastStreamList = parser.parseSimulcastStreamList; - -},{"./parser":18,"./writer":19}],18:[function(require,module,exports){ -var toIntIfInt = function (v) { - return String(Number(v)) === v ? Number(v) : v; -}; - -var attachProperties = function (match, location, names, rawName) { - if (rawName && !names) { - location[rawName] = toIntIfInt(match[1]); - } - else { - for (var i = 0; i < names.length; i += 1) { - if (match[i+1] != null) { - location[names[i]] = toIntIfInt(match[i+1]); - } - } - } -}; - -var parseReg = function (obj, location, content) { - var needsBlank = obj.name && obj.names; - if (obj.push && !location[obj.push]) { - location[obj.push] = []; - } - else if (needsBlank && !location[obj.name]) { - location[obj.name] = {}; - } - var keyLocation = obj.push ? - {} : // blank object that will be pushed - needsBlank ? location[obj.name] : location; // otherwise, named location or root - - attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name); - - if (obj.push) { - location[obj.push].push(keyLocation); - } -}; - -var grammar = require('./grammar'); -var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/); - -exports.parse = function (sdp) { - var session = {} - , media = [] - , location = session; // points at where properties go under (one of the above) - - // parse lines we understand - sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) { - var type = l[0]; - var content = l.slice(2); - if (type === 'm') { - media.push({rtp: [], fmtp: []}); - location = media[media.length-1]; // point at latest media line - } - - for (var j = 0; j < (grammar[type] || []).length; j += 1) { - var obj = grammar[type][j]; - if (obj.reg.test(content)) { - return parseReg(obj, location, content); - } - } - }); - - session.media = media; // link it up - return session; -}; - -var paramReducer = function (acc, expr) { - var s = expr.split(/=(.+)/, 2); - if (s.length === 2) { - acc[s[0]] = toIntIfInt(s[1]); - } - return acc; -}; - -exports.parseParams = function (str) { - return str.split(/\;\s?/).reduce(paramReducer, {}); -}; - -// For backward compatibility - alias will be removed in 3.0.0 -exports.parseFmtpConfig = exports.parseParams; - -exports.parsePayloads = function (str) { - return str.split(' ').map(Number); -}; - -exports.parseRemoteCandidates = function (str) { - var candidates = []; - var parts = str.split(' ').map(toIntIfInt); - for (var i = 0; i < parts.length; i += 3) { - candidates.push({ - component: parts[i], - ip: parts[i + 1], - port: parts[i + 2] - }); - } - return candidates; -}; - -exports.parseImageAttributes = function (str) { - return str.split(' ').map(function (item) { - return item.substring(1, item.length-1).split(',').reduce(paramReducer, {}); - }); -}; - -exports.parseSimulcastStreamList = function (str) { - return str.split(';').map(function (stream) { - return stream.split(',').map(function (format) { - var scid, paused = false; - - if (format[0] !== '~') { - scid = toIntIfInt(format); - } else { - scid = toIntIfInt(format.substring(1, format.length)); - paused = true; - } - - return { - scid: scid, - paused: paused - }; - }); - }); -}; - -},{"./grammar":16}],19:[function(require,module,exports){ -var grammar = require('./grammar'); - -// customized util.format - discards excess arguments and can void middle ones -var formatRegExp = /%[sdv%]/g; -var format = function (formatStr) { - var i = 1; - var args = arguments; - var len = args.length; - return formatStr.replace(formatRegExp, function (x) { - if (i >= len) { - return x; // missing argument - } - var arg = args[i]; - i += 1; - switch (x) { - case '%%': - return '%'; - case '%s': - return String(arg); - case '%d': - return Number(arg); - case '%v': - return ''; - } - }); - // NB: we discard excess arguments - they are typically undefined from makeLine -}; - -var makeLine = function (type, obj, location) { - var str = obj.format instanceof Function ? - (obj.format(obj.push ? location : location[obj.name])) : - obj.format; - - var args = [type + '=' + str]; - if (obj.names) { - for (var i = 0; i < obj.names.length; i += 1) { - var n = obj.names[i]; - if (obj.name) { - args.push(location[obj.name][n]); - } - else { // for mLine and push attributes - args.push(location[obj.names[i]]); - } - } - } - else { - args.push(location[obj.name]); - } - return format.apply(null, args); -}; - -// RFC specified order -// TODO: extend this with all the rest -var defaultOuterOrder = [ - 'v', 'o', 's', 'i', - 'u', 'e', 'p', 'c', - 'b', 't', 'r', 'z', 'a' -]; -var defaultInnerOrder = ['i', 'c', 'b', 'a']; - - -module.exports = function (session, opts) { - opts = opts || {}; - // ensure certain properties exist - if (session.version == null) { - session.version = 0; // 'v=0' must be there (only defined version atm) - } - if (session.name == null) { - session.name = ' '; // 's= ' must be there if no meaningful name set - } - session.media.forEach(function (mLine) { - if (mLine.payloads == null) { - mLine.payloads = ''; - } - }); - - var outerOrder = opts.outerOrder || defaultOuterOrder; - var innerOrder = opts.innerOrder || defaultInnerOrder; - var sdp = []; - - // loop through outerOrder for matching properties on session - outerOrder.forEach(function (type) { - grammar[type].forEach(function (obj) { - if (obj.name in session && session[obj.name] != null) { - sdp.push(makeLine(type, obj, session)); - } - else if (obj.push in session && session[obj.push] != null) { - session[obj.push].forEach(function (el) { - sdp.push(makeLine(type, obj, el)); - }); - } - }); - }); - - // then for each media line, follow the innerOrder - session.media.forEach(function (mLine) { - sdp.push(makeLine('m', grammar.m[0], mLine)); - - innerOrder.forEach(function (type) { - grammar[type].forEach(function (obj) { - if (obj.name in mLine && mLine[obj.name] != null) { - sdp.push(makeLine(type, obj, mLine)); - } - else if (obj.push in mLine && mLine[obj.push] != null) { - mLine[obj.push].forEach(function (el) { - sdp.push(makeLine(type, obj, el)); - }); - } - }); - }); - }); - - return sdp.join('\r\n') + '\r\n'; -}; - -},{"./grammar":16}],20:[function(require,module,exports){ - /* eslint-env node */ -'use strict'; - -// SDP helpers. -var SDPUtils = {}; - -// Generate an alphanumeric identifier for cname or mids. -// TODO: use UUIDs instead? https://gist.github.com/jed/982883 -SDPUtils.generateIdentifier = function() { - return Math.random().toString(36).substr(2, 10); -}; - -// The RTCP CNAME used by all peerconnections from the same JS. -SDPUtils.localCName = SDPUtils.generateIdentifier(); - -// Splits SDP into lines, dealing with both CRLF and LF. -SDPUtils.splitLines = function(blob) { - return blob.trim().split('\n').map(function(line) { - return line.trim(); - }); -}; -// Splits SDP into sessionpart and mediasections. Ensures CRLF. -SDPUtils.splitSections = function(blob) { - var parts = blob.split('\nm='); - return parts.map(function(part, index) { - return (index > 0 ? 'm=' + part : part).trim() + '\r\n'; - }); -}; - -// Returns lines that start with a certain prefix. -SDPUtils.matchPrefix = function(blob, prefix) { - return SDPUtils.splitLines(blob).filter(function(line) { - return line.indexOf(prefix) === 0; - }); -}; - -// Parses an ICE candidate line. Sample input: -// candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8 -// rport 55996" -SDPUtils.parseCandidate = function(line) { - var parts; - // Parse both variants. - if (line.indexOf('a=candidate:') === 0) { - parts = line.substring(12).split(' '); - } else { - parts = line.substring(10).split(' '); - } - - var candidate = { - foundation: parts[0], - component: parts[1], - protocol: parts[2].toLowerCase(), - priority: parseInt(parts[3], 10), - ip: parts[4], - port: parseInt(parts[5], 10), - // skip parts[6] == 'typ' - type: parts[7] - }; - - for (var i = 8; i < parts.length; i += 2) { - switch (parts[i]) { - case 'raddr': - candidate.relatedAddress = parts[i + 1]; - break; - case 'rport': - candidate.relatedPort = parseInt(parts[i + 1], 10); - break; - case 'tcptype': - candidate.tcpType = parts[i + 1]; - break; - default: // extension handling, in particular ufrag - candidate[parts[i]] = parts[i + 1]; - break; - } - } - return candidate; -}; - -// Translates a candidate object into SDP candidate attribute. -SDPUtils.writeCandidate = function(candidate) { - var sdp = []; - sdp.push(candidate.foundation); - sdp.push(candidate.component); - sdp.push(candidate.protocol.toUpperCase()); - sdp.push(candidate.priority); - sdp.push(candidate.ip); - sdp.push(candidate.port); - - var type = candidate.type; - sdp.push('typ'); - sdp.push(type); - if (type !== 'host' && candidate.relatedAddress && - candidate.relatedPort) { - sdp.push('raddr'); - sdp.push(candidate.relatedAddress); // was: relAddr - sdp.push('rport'); - sdp.push(candidate.relatedPort); // was: relPort - } - if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') { - sdp.push('tcptype'); - sdp.push(candidate.tcpType); - } - return 'candidate:' + sdp.join(' '); -}; - -// Parses an ice-options line, returns an array of option tags. -// a=ice-options:foo bar -SDPUtils.parseIceOptions = function(line) { - return line.substr(14).split(' '); -} - -// Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input: -// a=rtpmap:111 opus/48000/2 -SDPUtils.parseRtpMap = function(line) { - var parts = line.substr(9).split(' '); - var parsed = { - payloadType: parseInt(parts.shift(), 10) // was: id - }; - - parts = parts[0].split('/'); - - parsed.name = parts[0]; - parsed.clockRate = parseInt(parts[1], 10); // was: clockrate - // was: channels - parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1; - return parsed; -}; - -// Generate an a=rtpmap line from RTCRtpCodecCapability or -// RTCRtpCodecParameters. -SDPUtils.writeRtpMap = function(codec) { - var pt = codec.payloadType; - if (codec.preferredPayloadType !== undefined) { - pt = codec.preferredPayloadType; - } - return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate + - (codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n'; -}; - -// Parses an a=extmap line (headerextension from RFC 5285). Sample input: -// a=extmap:2 urn:ietf:params:rtp-hdrext:toffset -// a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset -SDPUtils.parseExtmap = function(line) { - var parts = line.substr(9).split(' '); - return { - id: parseInt(parts[0], 10), - direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv', - uri: parts[1] - }; -}; - -// Generates a=extmap line from RTCRtpHeaderExtensionParameters or -// RTCRtpHeaderExtension. -SDPUtils.writeExtmap = function(headerExtension) { - return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) + - (headerExtension.direction && headerExtension.direction !== 'sendrecv' - ? '/' + headerExtension.direction - : '') + - ' ' + headerExtension.uri + '\r\n'; -}; - -// Parses an ftmp line, returns dictionary. Sample input: -// a=fmtp:96 vbr=on;cng=on -// Also deals with vbr=on; cng=on -SDPUtils.parseFmtp = function(line) { - var parsed = {}; - var kv; - var parts = line.substr(line.indexOf(' ') + 1).split(';'); - for (var j = 0; j < parts.length; j++) { - kv = parts[j].trim().split('='); - parsed[kv[0].trim()] = kv[1]; - } - return parsed; -}; - -// Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters. -SDPUtils.writeFmtp = function(codec) { - var line = ''; - var pt = codec.payloadType; - if (codec.preferredPayloadType !== undefined) { - pt = codec.preferredPayloadType; - } - if (codec.parameters && Object.keys(codec.parameters).length) { - var params = []; - Object.keys(codec.parameters).forEach(function(param) { - params.push(param + '=' + codec.parameters[param]); - }); - line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n'; - } - return line; -}; - -// Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input: -// a=rtcp-fb:98 nack rpsi -SDPUtils.parseRtcpFb = function(line) { - var parts = line.substr(line.indexOf(' ') + 1).split(' '); - return { - type: parts.shift(), - parameter: parts.join(' ') - }; -}; -// Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters. -SDPUtils.writeRtcpFb = function(codec) { - var lines = ''; - var pt = codec.payloadType; - if (codec.preferredPayloadType !== undefined) { - pt = codec.preferredPayloadType; - } - if (codec.rtcpFeedback && codec.rtcpFeedback.length) { - // FIXME: special handling for trr-int? - codec.rtcpFeedback.forEach(function(fb) { - lines += 'a=rtcp-fb:' + pt + ' ' + fb.type + - (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') + - '\r\n'; - }); - } - return lines; -}; - -// Parses an RFC 5576 ssrc media attribute. Sample input: -// a=ssrc:3735928559 cname:something -SDPUtils.parseSsrcMedia = function(line) { - var sp = line.indexOf(' '); - var parts = { - ssrc: parseInt(line.substr(7, sp - 7), 10) - }; - var colon = line.indexOf(':', sp); - if (colon > -1) { - parts.attribute = line.substr(sp + 1, colon - sp - 1); - parts.value = line.substr(colon + 1); - } else { - parts.attribute = line.substr(sp + 1); - } - return parts; -}; - -// Extracts the MID (RFC 5888) from a media section. -// returns the MID or undefined if no mid line was found. -SDPUtils.getMid = function(mediaSection) { - var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0]; - if (mid) { - return mid.substr(6); - } -} - -SDPUtils.parseFingerprint = function(line) { - var parts = line.substr(14).split(' '); - return { - algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge. - value: parts[1] - }; -}; - -// Extracts DTLS parameters from SDP media section or sessionpart. -// FIXME: for consistency with other functions this should only -// get the fingerprint line as input. See also getIceParameters. -SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) { - var lines = SDPUtils.matchPrefix(mediaSection + sessionpart, - 'a=fingerprint:'); - // Note: a=setup line is ignored since we use the 'auto' role. - // Note2: 'algorithm' is not case sensitive except in Edge. - return { - role: 'auto', - fingerprints: lines.map(SDPUtils.parseFingerprint) - }; -}; - -// Serializes DTLS parameters to SDP. -SDPUtils.writeDtlsParameters = function(params, setupType) { - var sdp = 'a=setup:' + setupType + '\r\n'; - params.fingerprints.forEach(function(fp) { - sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n'; - }); - return sdp; -}; -// Parses ICE information from SDP media section or sessionpart. -// FIXME: for consistency with other functions this should only -// get the ice-ufrag and ice-pwd lines as input. -SDPUtils.getIceParameters = function(mediaSection, sessionpart) { - var lines = SDPUtils.splitLines(mediaSection); - // Search in session part, too. - lines = lines.concat(SDPUtils.splitLines(sessionpart)); - var iceParameters = { - usernameFragment: lines.filter(function(line) { - return line.indexOf('a=ice-ufrag:') === 0; - })[0].substr(12), - password: lines.filter(function(line) { - return line.indexOf('a=ice-pwd:') === 0; - })[0].substr(10) - }; - return iceParameters; -}; - -// Serializes ICE parameters to SDP. -SDPUtils.writeIceParameters = function(params) { - return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + - 'a=ice-pwd:' + params.password + '\r\n'; -}; - -// Parses the SDP media section and returns RTCRtpParameters. -SDPUtils.parseRtpParameters = function(mediaSection) { - var description = { - codecs: [], - headerExtensions: [], - fecMechanisms: [], - rtcp: [] - }; - var lines = SDPUtils.splitLines(mediaSection); - var mline = lines[0].split(' '); - for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..] - var pt = mline[i]; - var rtpmapline = SDPUtils.matchPrefix( - mediaSection, 'a=rtpmap:' + pt + ' ')[0]; - if (rtpmapline) { - var codec = SDPUtils.parseRtpMap(rtpmapline); - var fmtps = SDPUtils.matchPrefix( - mediaSection, 'a=fmtp:' + pt + ' '); - // Only the first a=fmtp: is considered. - codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {}; - codec.rtcpFeedback = SDPUtils.matchPrefix( - mediaSection, 'a=rtcp-fb:' + pt + ' ') - .map(SDPUtils.parseRtcpFb); - description.codecs.push(codec); - // parse FEC mechanisms from rtpmap lines. - switch (codec.name.toUpperCase()) { - case 'RED': - case 'ULPFEC': - description.fecMechanisms.push(codec.name.toUpperCase()); - break; - default: // only RED and ULPFEC are recognized as FEC mechanisms. - break; - } - } - } - SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) { - description.headerExtensions.push(SDPUtils.parseExtmap(line)); - }); - // FIXME: parse rtcp. - return description; -}; - -// Generates parts of the SDP media section describing the capabilities / -// parameters. -SDPUtils.writeRtpDescription = function(kind, caps) { - var sdp = ''; - - // Build the mline. - sdp += 'm=' + kind + ' '; - sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs. - sdp += ' UDP/TLS/RTP/SAVPF '; - sdp += caps.codecs.map(function(codec) { - if (codec.preferredPayloadType !== undefined) { - return codec.preferredPayloadType; - } - return codec.payloadType; - }).join(' ') + '\r\n'; - - sdp += 'c=IN IP4 0.0.0.0\r\n'; - sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n'; - - // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb. - caps.codecs.forEach(function(codec) { - sdp += SDPUtils.writeRtpMap(codec); - sdp += SDPUtils.writeFmtp(codec); - sdp += SDPUtils.writeRtcpFb(codec); - }); - var maxptime = 0; - caps.codecs.forEach(function(codec) { - if (codec.maxptime > maxptime) { - maxptime = codec.maxptime; - } - }); - if (maxptime > 0) { - sdp += 'a=maxptime:' + maxptime + '\r\n'; - } - sdp += 'a=rtcp-mux\r\n'; - - caps.headerExtensions.forEach(function(extension) { - sdp += SDPUtils.writeExtmap(extension); - }); - // FIXME: write fecMechanisms. - return sdp; -}; - -// Parses the SDP media section and returns an array of -// RTCRtpEncodingParameters. -SDPUtils.parseRtpEncodingParameters = function(mediaSection) { - var encodingParameters = []; - var description = SDPUtils.parseRtpParameters(mediaSection); - var hasRed = description.fecMechanisms.indexOf('RED') !== -1; - var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1; - - // filter a=ssrc:... cname:, ignore PlanB-msid - var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') - .map(function(line) { - return SDPUtils.parseSsrcMedia(line); - }) - .filter(function(parts) { - return parts.attribute === 'cname'; - }); - var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc; - var secondarySsrc; - - var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID') - .map(function(line) { - var parts = line.split(' '); - parts.shift(); - return parts.map(function(part) { - return parseInt(part, 10); - }); - }); - if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) { - secondarySsrc = flows[0][1]; - } - - description.codecs.forEach(function(codec) { - if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) { - var encParam = { - ssrc: primarySsrc, - codecPayloadType: parseInt(codec.parameters.apt, 10), - rtx: { - ssrc: secondarySsrc - } - }; - encodingParameters.push(encParam); - if (hasRed) { - encParam = JSON.parse(JSON.stringify(encParam)); - encParam.fec = { - ssrc: secondarySsrc, - mechanism: hasUlpfec ? 'red+ulpfec' : 'red' - }; - encodingParameters.push(encParam); - } - } - }); - if (encodingParameters.length === 0 && primarySsrc) { - encodingParameters.push({ - ssrc: primarySsrc - }); - } - - // we support both b=AS and b=TIAS but interpret AS as TIAS. - var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b='); - if (bandwidth.length) { - if (bandwidth[0].indexOf('b=TIAS:') === 0) { - bandwidth = parseInt(bandwidth[0].substr(7), 10); - } else if (bandwidth[0].indexOf('b=AS:') === 0) { - bandwidth = parseInt(bandwidth[0].substr(5), 10); - } - encodingParameters.forEach(function(params) { - params.maxBitrate = bandwidth; - }); - } - return encodingParameters; -}; - -// parses http://draft.ortc.org/#rtcrtcpparameters* -SDPUtils.parseRtcpParameters = function(mediaSection) { - var rtcpParameters = {}; - - var cname; - // Gets the first SSRC. Note that with RTX there might be multiple - // SSRCs. - var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') - .map(function(line) { - return SDPUtils.parseSsrcMedia(line); - }) - .filter(function(obj) { - return obj.attribute === 'cname'; - })[0]; - if (remoteSsrc) { - rtcpParameters.cname = remoteSsrc.value; - rtcpParameters.ssrc = remoteSsrc.ssrc; - } - - // Edge uses the compound attribute instead of reducedSize - // compound is !reducedSize - var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize'); - rtcpParameters.reducedSize = rsize.length > 0; - rtcpParameters.compound = rsize.length === 0; - - // parses the rtcp-mux attrіbute. - // Note that Edge does not support unmuxed RTCP. - var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux'); - rtcpParameters.mux = mux.length > 0; - - return rtcpParameters; -}; - -// parses either a=msid: or a=ssrc:... msid lines and returns -// the id of the MediaStream and MediaStreamTrack. -SDPUtils.parseMsid = function(mediaSection) { - var parts; - var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:'); - if (spec.length === 1) { - parts = spec[0].substr(7).split(' '); - return {stream: parts[0], track: parts[1]}; - } - var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') - .map(function(line) { - return SDPUtils.parseSsrcMedia(line); - }) - .filter(function(parts) { - return parts.attribute === 'msid'; - }); - if (planB.length > 0) { - parts = planB[0].value.split(' '); - return {stream: parts[0], track: parts[1]}; - } -}; - -SDPUtils.writeSessionBoilerplate = function() { - // FIXME: sess-id should be an NTP timestamp. - return 'v=0\r\n' + - 'o=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\n' + - 's=-\r\n' + - 't=0 0\r\n'; -}; - -SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) { - var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps); - - // Map ICE parameters (ufrag, pwd) to SDP. - sdp += SDPUtils.writeIceParameters( - transceiver.iceGatherer.getLocalParameters()); - - // Map DTLS parameters to SDP. - sdp += SDPUtils.writeDtlsParameters( - transceiver.dtlsTransport.getLocalParameters(), - type === 'offer' ? 'actpass' : 'active'); - - sdp += 'a=mid:' + transceiver.mid + '\r\n'; - - if (transceiver.direction) { - sdp += 'a=' + transceiver.direction + '\r\n'; - } else if (transceiver.rtpSender && transceiver.rtpReceiver) { - sdp += 'a=sendrecv\r\n'; - } else if (transceiver.rtpSender) { - sdp += 'a=sendonly\r\n'; - } else if (transceiver.rtpReceiver) { - sdp += 'a=recvonly\r\n'; - } else { - sdp += 'a=inactive\r\n'; - } - - if (transceiver.rtpSender) { - // spec. - var msid = 'msid:' + stream.id + ' ' + - transceiver.rtpSender.track.id + '\r\n'; - sdp += 'a=' + msid; - - // for Chrome. - sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc + - ' ' + msid; - if (transceiver.sendEncodingParameters[0].rtx) { - sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc + - ' ' + msid; - sdp += 'a=ssrc-group:FID ' + - transceiver.sendEncodingParameters[0].ssrc + ' ' + - transceiver.sendEncodingParameters[0].rtx.ssrc + - '\r\n'; - } - } - // FIXME: this should be written by writeRtpDescription. - sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc + - ' cname:' + SDPUtils.localCName + '\r\n'; - if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) { - sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc + - ' cname:' + SDPUtils.localCName + '\r\n'; - } - return sdp; -}; - -// Gets the direction from the mediaSection or the sessionpart. -SDPUtils.getDirection = function(mediaSection, sessionpart) { - // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv. - var lines = SDPUtils.splitLines(mediaSection); - for (var i = 0; i < lines.length; i++) { - switch (lines[i]) { - case 'a=sendrecv': - case 'a=sendonly': - case 'a=recvonly': - case 'a=inactive': - return lines[i].substr(2); - default: - // FIXME: What should happen here? - } - } - if (sessionpart) { - return SDPUtils.getDirection(sessionpart); - } - return 'sendrecv'; -}; - -SDPUtils.getKind = function(mediaSection) { - var lines = SDPUtils.splitLines(mediaSection); - var mline = lines[0].split(' '); - return mline[0].substr(2); -}; - -SDPUtils.isRejected = function(mediaSection) { - return mediaSection.split(' ', 2)[1] === '0'; -}; - -// Expose public methods. -module.exports = SDPUtils; - -},{}],21:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],22:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],23:[function(require,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":22,"_process":15,"inherits":21}],24:[function(require,module,exports){ -/* - * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. - */ - /* eslint-env node */ - -'use strict'; - -// Shimming starts here. -(function() { - // Utils. - var utils = require('./utils'); - var logging = utils.log; - var browserDetails = utils.browserDetails; - // Export to the adapter global object visible in the browser. - module.exports.browserDetails = browserDetails; - module.exports.extractVersion = utils.extractVersion; - module.exports.disableLog = utils.disableLog; - - // Uncomment the line below if you want logging to occur, including logging - // for the switch statement below. Can also be turned on in the browser via - // adapter.disableLog(false), but then logging from the switch statement below - // will not appear. - // require('./utils').disableLog(false); - - // Browser shims. - var chromeShim = require('./chrome/chrome_shim') || null; - var edgeShim = require('./edge/edge_shim') || null; - var firefoxShim = require('./firefox/firefox_shim') || null; - var safariShim = require('./safari/safari_shim') || null; - - // Shim browser if found. - switch (browserDetails.browser) { - case 'chrome': - if (!chromeShim || !chromeShim.shimPeerConnection) { - logging('Chrome shim is not included in this adapter release.'); - return; - } - logging('adapter.js shimming chrome.'); - // Export to the adapter global object visible in the browser. - module.exports.browserShim = chromeShim; - - chromeShim.shimGetUserMedia(); - chromeShim.shimMediaStream(); - utils.shimCreateObjectURL(); - chromeShim.shimSourceObject(); - chromeShim.shimPeerConnection(); - chromeShim.shimOnTrack(); - chromeShim.shimGetSendersWithDtmf(); - break; - case 'firefox': - if (!firefoxShim || !firefoxShim.shimPeerConnection) { - logging('Firefox shim is not included in this adapter release.'); - return; - } - logging('adapter.js shimming firefox.'); - // Export to the adapter global object visible in the browser. - module.exports.browserShim = firefoxShim; - - firefoxShim.shimGetUserMedia(); - utils.shimCreateObjectURL(); - firefoxShim.shimSourceObject(); - firefoxShim.shimPeerConnection(); - firefoxShim.shimOnTrack(); - break; - case 'edge': - if (!edgeShim || !edgeShim.shimPeerConnection) { - logging('MS edge shim is not included in this adapter release.'); - return; - } - logging('adapter.js shimming edge.'); - // Export to the adapter global object visible in the browser. - module.exports.browserShim = edgeShim; - - edgeShim.shimGetUserMedia(); - utils.shimCreateObjectURL(); - edgeShim.shimPeerConnection(); - edgeShim.shimReplaceTrack(); - break; - case 'safari': - if (!safariShim) { - logging('Safari shim is not included in this adapter release.'); - return; - } - logging('adapter.js shimming safari.'); - // Export to the adapter global object visible in the browser. - module.exports.browserShim = safariShim; - - safariShim.shimCallbacksAPI(); - safariShim.shimAddStream(); - safariShim.shimOnAddStream(); - safariShim.shimGetUserMedia(); - break; - default: - logging('Unsupported browser!'); - } -})(); - -},{"./chrome/chrome_shim":25,"./edge/edge_shim":27,"./firefox/firefox_shim":30,"./safari/safari_shim":32,"./utils":33}],25:[function(require,module,exports){ - -/* - * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. - */ - /* eslint-env node */ -'use strict'; -var logging = require('../utils.js').log; -var browserDetails = require('../utils.js').browserDetails; - -var chromeShim = { - shimMediaStream: function() { - window.MediaStream = window.MediaStream || window.webkitMediaStream; - }, - - shimOnTrack: function() { - if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in - window.RTCPeerConnection.prototype)) { - Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', { - get: function() { - return this._ontrack; - }, - set: function(f) { - var self = this; - if (this._ontrack) { - this.removeEventListener('track', this._ontrack); - this.removeEventListener('addstream', this._ontrackpoly); - } - this.addEventListener('track', this._ontrack = f); - this.addEventListener('addstream', this._ontrackpoly = function(e) { - // onaddstream does not fire when a track is added to an existing - // stream. But stream.onaddtrack is implemented so we use that. - e.stream.addEventListener('addtrack', function(te) { - var receiver; - if (RTCPeerConnection.prototype.getReceivers) { - receiver = self.getReceivers().find(function(r) { - return r.track.id === te.track.id; - }); - } else { - receiver = {track: te.track}; - } - - var event = new Event('track'); - event.track = te.track; - event.receiver = receiver; - event.streams = [e.stream]; - self.dispatchEvent(event); - }); - e.stream.getTracks().forEach(function(track) { - var receiver; - if (RTCPeerConnection.prototype.getReceivers) { - receiver = self.getReceivers().find(function(r) { - return r.track.id === track.id; - }); - } else { - receiver = {track: track}; - } - var event = new Event('track'); - event.track = track; - event.receiver = receiver; - event.streams = [e.stream]; - this.dispatchEvent(event); - }.bind(this)); - }.bind(this)); - } - }); - } - }, - - shimGetSendersWithDtmf: function() { - if (typeof window === 'object' && window.RTCPeerConnection && - !('getSenders' in RTCPeerConnection.prototype) && - 'createDTMFSender' in RTCPeerConnection.prototype) { - RTCPeerConnection.prototype.getSenders = function() { - return this._senders || []; - }; - var origAddStream = RTCPeerConnection.prototype.addStream; - var origRemoveStream = RTCPeerConnection.prototype.removeStream; - - if (!RTCPeerConnection.prototype.addTrack) { - RTCPeerConnection.prototype.addTrack = function(track, stream) { - var pc = this; - if (pc.signalingState === 'closed') { - throw new DOMException( - 'The RTCPeerConnection\'s signalingState is \'closed\'.', - 'InvalidStateError'); - } - var streams = [].slice.call(arguments, 1); - if (streams.length !== 1 || - !streams[0].getTracks().find(function(t) { - return t === track; - })) { - // this is not fully correct but all we can manage without - // [[associated MediaStreams]] internal slot. - throw new DOMException( - 'The adapter.js addTrack polyfill only supports a single ' + - ' stream which is associated with the specified track.', - 'NotSupportedError'); - } - - pc._senders = pc._senders || []; - var alreadyExists = pc._senders.find(function(t) { - return t.track === track; - }); - if (alreadyExists) { - throw new DOMException('Track already exists.', - 'InvalidAccessError'); - } - - pc._streams = pc._streams || {}; - var oldStream = pc._streams[stream.id]; - if (oldStream) { - oldStream.addTrack(track); - pc.removeStream(oldStream); - pc.addStream(oldStream); - } else { - var newStream = new MediaStream([track]); - pc._streams[stream.id] = newStream; - pc.addStream(newStream); - } - - var sender = { - track: track, - get dtmf() { - if (this._dtmf === undefined) { - if (track.kind === 'audio') { - this._dtmf = pc.createDTMFSender(track); - } else { - this._dtmf = null; - } - } - return this._dtmf; - } - }; - pc._senders.push(sender); - return sender; - }; - } - RTCPeerConnection.prototype.addStream = function(stream) { - var pc = this; - pc._senders = pc._senders || []; - origAddStream.apply(pc, [stream]); - stream.getTracks().forEach(function(track) { - pc._senders.push({ - track: track, - get dtmf() { - if (this._dtmf === undefined) { - if (track.kind === 'audio') { - this._dtmf = pc.createDTMFSender(track); - } else { - this._dtmf = null; - } - } - return this._dtmf; - } - }); - }); - }; - - RTCPeerConnection.prototype.removeStream = function(stream) { - var pc = this; - pc._senders = pc._senders || []; - origRemoveStream.apply(pc, [stream]); - stream.getTracks().forEach(function(track) { - var sender = pc._senders.find(function(s) { - return s.track === track; - }); - if (sender) { - pc._senders.splice(pc._senders.indexOf(sender), 1); // remove sender - } - }); - }; - } - }, - - shimSourceObject: function() { - if (typeof window === 'object') { - if (window.HTMLMediaElement && - !('srcObject' in window.HTMLMediaElement.prototype)) { - // Shim the srcObject property, once, when HTMLMediaElement is found. - Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { - get: function() { - return this._srcObject; - }, - set: function(stream) { - var self = this; - // Use _srcObject as a private property for this shim - this._srcObject = stream; - if (this.src) { - URL.revokeObjectURL(this.src); - } - - if (!stream) { - this.src = ''; - return undefined; - } - this.src = URL.createObjectURL(stream); - // We need to recreate the blob url when a track is added or - // removed. Doing it manually since we want to avoid a recursion. - stream.addEventListener('addtrack', function() { - if (self.src) { - URL.revokeObjectURL(self.src); - } - self.src = URL.createObjectURL(stream); - }); - stream.addEventListener('removetrack', function() { - if (self.src) { - URL.revokeObjectURL(self.src); - } - self.src = URL.createObjectURL(stream); - }); - } - }); - } - } - }, - - shimPeerConnection: function() { - // The RTCPeerConnection object. - if (!window.RTCPeerConnection) { - window.RTCPeerConnection = function(pcConfig, pcConstraints) { - // Translate iceTransportPolicy to iceTransports, - // see https://code.google.com/p/webrtc/issues/detail?id=4869 - // this was fixed in M56 along with unprefixing RTCPeerConnection. - logging('PeerConnection'); - if (pcConfig && pcConfig.iceTransportPolicy) { - pcConfig.iceTransports = pcConfig.iceTransportPolicy; - } - - return new webkitRTCPeerConnection(pcConfig, pcConstraints); - }; - window.RTCPeerConnection.prototype = webkitRTCPeerConnection.prototype; - // wrap static methods. Currently just generateCertificate. - if (webkitRTCPeerConnection.generateCertificate) { - Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { - get: function() { - return webkitRTCPeerConnection.generateCertificate; - } - }); - } - } else { - // migrate from non-spec RTCIceServer.url to RTCIceServer.urls - var OrigPeerConnection = RTCPeerConnection; - window.RTCPeerConnection = function(pcConfig, pcConstraints) { - if (pcConfig && pcConfig.iceServers) { - var newIceServers = []; - for (var i = 0; i < pcConfig.iceServers.length; i++) { - var server = pcConfig.iceServers[i]; - if (!server.hasOwnProperty('urls') && - server.hasOwnProperty('url')) { - console.warn('RTCIceServer.url is deprecated! Use urls instead.'); - server = JSON.parse(JSON.stringify(server)); - server.urls = server.url; - newIceServers.push(server); - } else { - newIceServers.push(pcConfig.iceServers[i]); - } - } - pcConfig.iceServers = newIceServers; - } - return new OrigPeerConnection(pcConfig, pcConstraints); - }; - window.RTCPeerConnection.prototype = OrigPeerConnection.prototype; - // wrap static methods. Currently just generateCertificate. - Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { - get: function() { - return OrigPeerConnection.generateCertificate; - } - }); - } - - var origGetStats = RTCPeerConnection.prototype.getStats; - RTCPeerConnection.prototype.getStats = function(selector, - successCallback, errorCallback) { - var self = this; - var args = arguments; - - // If selector is a function then we are in the old style stats so just - // pass back the original getStats format to avoid breaking old users. - if (arguments.length > 0 && typeof selector === 'function') { - return origGetStats.apply(this, arguments); - } - - // When spec-style getStats is supported, return those when called with - // either no arguments or the selector argument is null. - if (origGetStats.length === 0 && (arguments.length === 0 || - typeof arguments[0] !== 'function')) { - return origGetStats.apply(this, []); - } - - var fixChromeStats_ = function(response) { - var standardReport = {}; - var reports = response.result(); - reports.forEach(function(report) { - var standardStats = { - id: report.id, - timestamp: report.timestamp, - type: { - localcandidate: 'local-candidate', - remotecandidate: 'remote-candidate' - }[report.type] || report.type - }; - report.names().forEach(function(name) { - standardStats[name] = report.stat(name); - }); - standardReport[standardStats.id] = standardStats; - }); - - return standardReport; - }; - - // shim getStats with maplike support - var makeMapStats = function(stats) { - return new Map(Object.keys(stats).map(function(key) { - return [key, stats[key]]; - })); - }; - - if (arguments.length >= 2) { - var successCallbackWrapper_ = function(response) { - args[1](makeMapStats(fixChromeStats_(response))); - }; - - return origGetStats.apply(this, [successCallbackWrapper_, - arguments[0]]); - } - - // promise-support - return new Promise(function(resolve, reject) { - origGetStats.apply(self, [ - function(response) { - resolve(makeMapStats(fixChromeStats_(response))); - }, reject]); - }).then(successCallback, errorCallback); - }; - - // add promise support -- natively available in Chrome 51 - if (browserDetails.version < 51) { - ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] - .forEach(function(method) { - var nativeMethod = RTCPeerConnection.prototype[method]; - RTCPeerConnection.prototype[method] = function() { - var args = arguments; - var self = this; - var promise = new Promise(function(resolve, reject) { - nativeMethod.apply(self, [args[0], resolve, reject]); - }); - if (args.length < 2) { - return promise; - } - return promise.then(function() { - args[1].apply(null, []); - }, - function(err) { - if (args.length >= 3) { - args[2].apply(null, [err]); - } - }); - }; - }); - } - - // promise support for createOffer and createAnswer. Available (without - // bugs) since M52: crbug/619289 - if (browserDetails.version < 52) { - ['createOffer', 'createAnswer'].forEach(function(method) { - var nativeMethod = RTCPeerConnection.prototype[method]; - RTCPeerConnection.prototype[method] = function() { - var self = this; - if (arguments.length < 1 || (arguments.length === 1 && - typeof arguments[0] === 'object')) { - var opts = arguments.length === 1 ? arguments[0] : undefined; - return new Promise(function(resolve, reject) { - nativeMethod.apply(self, [resolve, reject, opts]); - }); - } - return nativeMethod.apply(this, arguments); - }; - }); - } - - // shim implicit creation of RTCSessionDescription/RTCIceCandidate - ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] - .forEach(function(method) { - var nativeMethod = RTCPeerConnection.prototype[method]; - RTCPeerConnection.prototype[method] = function() { - arguments[0] = new ((method === 'addIceCandidate') ? - RTCIceCandidate : RTCSessionDescription)(arguments[0]); - return nativeMethod.apply(this, arguments); - }; - }); - - // support for addIceCandidate(null or undefined) - var nativeAddIceCandidate = - RTCPeerConnection.prototype.addIceCandidate; - RTCPeerConnection.prototype.addIceCandidate = function() { - if (!arguments[0]) { - if (arguments[1]) { - arguments[1].apply(null); - } - return Promise.resolve(); - } - return nativeAddIceCandidate.apply(this, arguments); - }; - } -}; - - -// Expose public methods. -module.exports = { - shimMediaStream: chromeShim.shimMediaStream, - shimOnTrack: chromeShim.shimOnTrack, - shimGetSendersWithDtmf: chromeShim.shimGetSendersWithDtmf, - shimSourceObject: chromeShim.shimSourceObject, - shimPeerConnection: chromeShim.shimPeerConnection, - shimGetUserMedia: require('./getusermedia') -}; - -},{"../utils.js":33,"./getusermedia":26}],26:[function(require,module,exports){ -/* - * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. - */ - /* eslint-env node */ -'use strict'; -var logging = require('../utils.js').log; -var browserDetails = require('../utils.js').browserDetails; - -// Expose public methods. -module.exports = function() { - var constraintsToChrome_ = function(c) { - if (typeof c !== 'object' || c.mandatory || c.optional) { - return c; - } - var cc = {}; - Object.keys(c).forEach(function(key) { - if (key === 'require' || key === 'advanced' || key === 'mediaSource') { - return; - } - var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; - if (r.exact !== undefined && typeof r.exact === 'number') { - r.min = r.max = r.exact; - } - var oldname_ = function(prefix, name) { - if (prefix) { - return prefix + name.charAt(0).toUpperCase() + name.slice(1); - } - return (name === 'deviceId') ? 'sourceId' : name; - }; - if (r.ideal !== undefined) { - cc.optional = cc.optional || []; - var oc = {}; - if (typeof r.ideal === 'number') { - oc[oldname_('min', key)] = r.ideal; - cc.optional.push(oc); - oc = {}; - oc[oldname_('max', key)] = r.ideal; - cc.optional.push(oc); - } else { - oc[oldname_('', key)] = r.ideal; - cc.optional.push(oc); - } - } - if (r.exact !== undefined && typeof r.exact !== 'number') { - cc.mandatory = cc.mandatory || {}; - cc.mandatory[oldname_('', key)] = r.exact; - } else { - ['min', 'max'].forEach(function(mix) { - if (r[mix] !== undefined) { - cc.mandatory = cc.mandatory || {}; - cc.mandatory[oldname_(mix, key)] = r[mix]; - } - }); - } - }); - if (c.advanced) { - cc.optional = (cc.optional || []).concat(c.advanced); - } - return cc; - }; - - var shimConstraints_ = function(constraints, func) { - constraints = JSON.parse(JSON.stringify(constraints)); - if (constraints && constraints.audio) { - constraints.audio = constraintsToChrome_(constraints.audio); - } - if (constraints && typeof constraints.video === 'object') { - // Shim facingMode for mobile & surface pro. - var face = constraints.video.facingMode; - face = face && ((typeof face === 'object') ? face : {ideal: face}); - var getSupportedFacingModeLies = browserDetails.version < 61; - - if ((face && (face.exact === 'user' || face.exact === 'environment' || - face.ideal === 'user' || face.ideal === 'environment')) && - !(navigator.mediaDevices.getSupportedConstraints && - navigator.mediaDevices.getSupportedConstraints().facingMode && - !getSupportedFacingModeLies)) { - delete constraints.video.facingMode; - var matches; - if (face.exact === 'environment' || face.ideal === 'environment') { - matches = ['back', 'rear']; - } else if (face.exact === 'user' || face.ideal === 'user') { - matches = ['front']; - } - if (matches) { - // Look for matches in label, or use last cam for back (typical). - return navigator.mediaDevices.enumerateDevices() - .then(function(devices) { - devices = devices.filter(function(d) { - return d.kind === 'videoinput'; - }); - var dev = devices.find(function(d) { - return matches.some(function(match) { - return d.label.toLowerCase().indexOf(match) !== -1; - }); - }); - if (!dev && devices.length && matches.indexOf('back') !== -1) { - dev = devices[devices.length - 1]; // more likely the back cam - } - if (dev) { - constraints.video.deviceId = face.exact ? {exact: dev.deviceId} : - {ideal: dev.deviceId}; - } - constraints.video = constraintsToChrome_(constraints.video); - logging('chrome: ' + JSON.stringify(constraints)); - return func(constraints); - }); - } - } - constraints.video = constraintsToChrome_(constraints.video); - } - logging('chrome: ' + JSON.stringify(constraints)); - return func(constraints); - }; - - var shimError_ = function(e) { - return { - name: { - ConstraintNotSatisfiedError: 'OverconstrainedError', - PermissionDeniedError: 'NotAllowedError', - TrackStartError: 'NotReadableError' - }[e.name] || e.name, - message: e.message, - constraint: e.constraintName, - toString: function() { - return this.name + (this.message && ': ') + this.message; - } - }; - }; - - var getUserMedia_ = function(constraints, onSuccess, onError) { - shimConstraints_(constraints, function(c) { - navigator.webkitGetUserMedia(c, onSuccess, function(e) { - onError(shimError_(e)); - }); - }); - }; - - navigator.getUserMedia = getUserMedia_; - - // Returns the result of getUserMedia as a Promise. - var getUserMediaPromise_ = function(constraints) { - return new Promise(function(resolve, reject) { - navigator.getUserMedia(constraints, resolve, reject); - }); - }; - - if (!navigator.mediaDevices) { - navigator.mediaDevices = { - getUserMedia: getUserMediaPromise_, - enumerateDevices: function() { - return new Promise(function(resolve) { - var kinds = {audio: 'audioinput', video: 'videoinput'}; - return MediaStreamTrack.getSources(function(devices) { - resolve(devices.map(function(device) { - return {label: device.label, - kind: kinds[device.kind], - deviceId: device.id, - groupId: ''}; - })); - }); - }); - }, - getSupportedConstraints: function() { - return { - deviceId: true, echoCancellation: true, facingMode: true, - frameRate: true, height: true, width: true - }; - } - }; - } - - // A shim for getUserMedia method on the mediaDevices object. - // TODO(KaptenJansson) remove once implemented in Chrome stable. - if (!navigator.mediaDevices.getUserMedia) { - navigator.mediaDevices.getUserMedia = function(constraints) { - return getUserMediaPromise_(constraints); - }; - } else { - // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia - // function which returns a Promise, it does not accept spec-style - // constraints. - var origGetUserMedia = navigator.mediaDevices.getUserMedia. - bind(navigator.mediaDevices); - navigator.mediaDevices.getUserMedia = function(cs) { - return shimConstraints_(cs, function(c) { - return origGetUserMedia(c).then(function(stream) { - if (c.audio && !stream.getAudioTracks().length || - c.video && !stream.getVideoTracks().length) { - stream.getTracks().forEach(function(track) { - track.stop(); - }); - throw new DOMException('', 'NotFoundError'); - } - return stream; - }, function(e) { - return Promise.reject(shimError_(e)); - }); - }); - }; - } - - // Dummy devicechange event methods. - // TODO(KaptenJansson) remove once implemented in Chrome stable. - if (typeof navigator.mediaDevices.addEventListener === 'undefined') { - navigator.mediaDevices.addEventListener = function() { - logging('Dummy mediaDevices.addEventListener called.'); - }; - } - if (typeof navigator.mediaDevices.removeEventListener === 'undefined') { - navigator.mediaDevices.removeEventListener = function() { - logging('Dummy mediaDevices.removeEventListener called.'); - }; - } -}; - -},{"../utils.js":33}],27:[function(require,module,exports){ -/* - * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. - */ - /* eslint-env node */ -'use strict'; - -var browserDetails = require('../utils').browserDetails; -var shimRTCPeerConnection = require('./rtcpeerconnection_shim'); - -module.exports = { - shimGetUserMedia: require('./getusermedia'), - shimPeerConnection: function() { - if (window.RTCIceGatherer) { - // ORTC defines an RTCIceCandidate object but no constructor. - // Not implemented in Edge. - if (!window.RTCIceCandidate) { - window.RTCIceCandidate = function(args) { - return args; - }; - } - // ORTC does not have a session description object but - // other browsers (i.e. Chrome) that will support both PC and ORTC - // in the future might have this defined already. - if (!window.RTCSessionDescription) { - window.RTCSessionDescription = function(args) { - return args; - }; - } - // this adds an additional event listener to MediaStrackTrack that signals - // when a tracks enabled property was changed. Workaround for a bug in - // addStream, see below. No longer required in 15025+ - if (browserDetails.version < 15025) { - var origMSTEnabled = Object.getOwnPropertyDescriptor( - MediaStreamTrack.prototype, 'enabled'); - Object.defineProperty(MediaStreamTrack.prototype, 'enabled', { - set: function(value) { - origMSTEnabled.set.call(this, value); - var ev = new Event('enabled'); - ev.enabled = value; - this.dispatchEvent(ev); - } - }); - } - } - window.RTCPeerConnection = shimRTCPeerConnection(browserDetails.version); - }, - shimReplaceTrack: function() { - // ORTC has replaceTrack -- https://github.com/w3c/ortc/issues/614 - if (window.RTCRtpSender && !('replaceTrack' in RTCRtpSender.prototype)) { - RTCRtpSender.prototype.replaceTrack = RTCRtpSender.prototype.setTrack; - } - } -}; - -},{"../utils":33,"./getusermedia":28,"./rtcpeerconnection_shim":29}],28:[function(require,module,exports){ -/* - * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. - */ - /* eslint-env node */ -'use strict'; - -// Expose public methods. -module.exports = function() { - var shimError_ = function(e) { - return { - name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name, - message: e.message, - constraint: e.constraint, - toString: function() { - return this.name; - } - }; - }; - - // getUserMedia error shim. - var origGetUserMedia = navigator.mediaDevices.getUserMedia. - bind(navigator.mediaDevices); - navigator.mediaDevices.getUserMedia = function(c) { - return origGetUserMedia(c).catch(function(e) { - return Promise.reject(shimError_(e)); - }); - }; -}; - -},{}],29:[function(require,module,exports){ -/* - * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. - */ - /* eslint-env node */ -'use strict'; - -var SDPUtils = require('sdp'); - -// sort tracks such that they follow an a-v-a-v... -// pattern. -function sortTracks(tracks) { - var audioTracks = tracks.filter(function(track) { - return track.kind === 'audio'; - }); - var videoTracks = tracks.filter(function(track) { - return track.kind === 'video'; - }); - tracks = []; - while (audioTracks.length || videoTracks.length) { - if (audioTracks.length) { - tracks.push(audioTracks.shift()); - } - if (videoTracks.length) { - tracks.push(videoTracks.shift()); - } - } - return tracks; -} - -// Edge does not like -// 1) stun: -// 2) turn: that does not have all of turn:host:port?transport=udp -// 3) turn: with ipv6 addresses -// 4) turn: occurring muliple times -function filterIceServers(iceServers, edgeVersion) { - var hasTurn = false; - iceServers = JSON.parse(JSON.stringify(iceServers)); - return iceServers.filter(function(server) { - if (server && (server.urls || server.url)) { - var urls = server.urls || server.url; - if (server.url && !server.urls) { - console.warn('RTCIceServer.url is deprecated! Use urls instead.'); - } - var isString = typeof urls === 'string'; - if (isString) { - urls = [urls]; - } - urls = urls.filter(function(url) { - var validTurn = url.indexOf('turn:') === 0 && - url.indexOf('transport=udp') !== -1 && - url.indexOf('turn:[') === -1 && - !hasTurn; - - if (validTurn) { - hasTurn = true; - return true; - } - return url.indexOf('stun:') === 0 && edgeVersion >= 14393; - }); - - delete server.url; - server.urls = isString ? urls[0] : urls; - return !!urls.length; - } - return false; - }); -} - -// Determines the intersection of local and remote capabilities. -function getCommonCapabilities(localCapabilities, remoteCapabilities) { - var commonCapabilities = { - codecs: [], - headerExtensions: [], - fecMechanisms: [] - }; - - var findCodecByPayloadType = function(pt, codecs) { - pt = parseInt(pt, 10); - for (var i = 0; i < codecs.length; i++) { - if (codecs[i].payloadType === pt || - codecs[i].preferredPayloadType === pt) { - return codecs[i]; - } - } - }; - - var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) { - var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs); - var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs); - return lCodec && rCodec && - lCodec.name.toLowerCase() === rCodec.name.toLowerCase(); - }; - - localCapabilities.codecs.forEach(function(lCodec) { - for (var i = 0; i < remoteCapabilities.codecs.length; i++) { - var rCodec = remoteCapabilities.codecs[i]; - if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() && - lCodec.clockRate === rCodec.clockRate) { - if (lCodec.name.toLowerCase() === 'rtx' && - lCodec.parameters && rCodec.parameters.apt) { - // for RTX we need to find the local rtx that has a apt - // which points to the same local codec as the remote one. - if (!rtxCapabilityMatches(lCodec, rCodec, - localCapabilities.codecs, remoteCapabilities.codecs)) { - continue; - } - } - rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy - // number of channels is the highest common number of channels - rCodec.numChannels = Math.min(lCodec.numChannels, - rCodec.numChannels); - // push rCodec so we reply with offerer payload type - commonCapabilities.codecs.push(rCodec); - - // determine common feedback mechanisms - rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) { - for (var j = 0; j < lCodec.rtcpFeedback.length; j++) { - if (lCodec.rtcpFeedback[j].type === fb.type && - lCodec.rtcpFeedback[j].parameter === fb.parameter) { - return true; - } - } - return false; - }); - // FIXME: also need to determine .parameters - // see https://github.com/openpeer/ortc/issues/569 - break; - } - } - }); - - localCapabilities.headerExtensions.forEach(function(lHeaderExtension) { - for (var i = 0; i < remoteCapabilities.headerExtensions.length; - i++) { - var rHeaderExtension = remoteCapabilities.headerExtensions[i]; - if (lHeaderExtension.uri === rHeaderExtension.uri) { - commonCapabilities.headerExtensions.push(rHeaderExtension); - break; - } - } - }); - - // FIXME: fecMechanisms - return commonCapabilities; -} - -// is action=setLocalDescription with type allowed in signalingState -function isActionAllowedInSignalingState(action, type, signalingState) { - return { - offer: { - setLocalDescription: ['stable', 'have-local-offer'], - setRemoteDescription: ['stable', 'have-remote-offer'] - }, - answer: { - setLocalDescription: ['have-remote-offer', 'have-local-pranswer'], - setRemoteDescription: ['have-local-offer', 'have-remote-pranswer'] - } - }[type][action].indexOf(signalingState) !== -1; -} - -module.exports = function(edgeVersion) { - var RTCPeerConnection = function(config) { - var self = this; - - var _eventTarget = document.createDocumentFragment(); - ['addEventListener', 'removeEventListener', 'dispatchEvent'] - .forEach(function(method) { - self[method] = _eventTarget[method].bind(_eventTarget); - }); - - this.needNegotiation = false; - - this.onicecandidate = null; - this.onaddstream = null; - this.ontrack = null; - this.onremovestream = null; - this.onsignalingstatechange = null; - this.oniceconnectionstatechange = null; - this.onicegatheringstatechange = null; - this.onnegotiationneeded = null; - this.ondatachannel = null; - this.canTrickleIceCandidates = null; - - this.localStreams = []; - this.remoteStreams = []; - this.getLocalStreams = function() { - return self.localStreams; - }; - this.getRemoteStreams = function() { - return self.remoteStreams; - }; - - this.localDescription = new RTCSessionDescription({ - type: '', - sdp: '' - }); - this.remoteDescription = new RTCSessionDescription({ - type: '', - sdp: '' - }); - this.signalingState = 'stable'; - this.iceConnectionState = 'new'; - this.iceGatheringState = 'new'; - - this.iceOptions = { - gatherPolicy: 'all', - iceServers: [] - }; - if (config && config.iceTransportPolicy) { - switch (config.iceTransportPolicy) { - case 'all': - case 'relay': - this.iceOptions.gatherPolicy = config.iceTransportPolicy; - break; - default: - // don't set iceTransportPolicy. - break; - } - } - this.usingBundle = config && config.bundlePolicy === 'max-bundle'; - - if (config && config.iceServers) { - this.iceOptions.iceServers = filterIceServers(config.iceServers, - edgeVersion); - } - this._config = config || {}; - - // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ... - // everything that is needed to describe a SDP m-line. - this.transceivers = []; - - // since the iceGatherer is currently created in createOffer but we - // must not emit candidates until after setLocalDescription we buffer - // them in this array. - this._localIceCandidatesBuffer = []; - }; - - RTCPeerConnection.prototype._emitGatheringStateChange = function() { - var event = new Event('icegatheringstatechange'); - this.dispatchEvent(event); - if (this.onicegatheringstatechange !== null) { - this.onicegatheringstatechange(event); - } - }; - - RTCPeerConnection.prototype._emitBufferedCandidates = function() { - var self = this; - var sections = SDPUtils.splitSections(self.localDescription.sdp); - // FIXME: need to apply ice candidates in a way which is async but - // in-order - this._localIceCandidatesBuffer.forEach(function(event) { - var end = !event.candidate || Object.keys(event.candidate).length === 0; - if (end) { - for (var j = 1; j < sections.length; j++) { - if (sections[j].indexOf('\r\na=end-of-candidates\r\n') === -1) { - sections[j] += 'a=end-of-candidates\r\n'; - } - } - } else { - sections[event.candidate.sdpMLineIndex + 1] += - 'a=' + event.candidate.candidate + '\r\n'; - } - self.localDescription.sdp = sections.join(''); - self.dispatchEvent(event); - if (self.onicecandidate !== null) { - self.onicecandidate(event); - } - if (!event.candidate && self.iceGatheringState !== 'complete') { - var complete = self.transceivers.every(function(transceiver) { - return transceiver.iceGatherer && - transceiver.iceGatherer.state === 'completed'; - }); - if (complete && self.iceGatheringStateChange !== 'complete') { - self.iceGatheringState = 'complete'; - self._emitGatheringStateChange(); - } - } - }); - this._localIceCandidatesBuffer = []; - }; - - RTCPeerConnection.prototype.getConfiguration = function() { - return this._config; - }; - - // internal helper to create a transceiver object. - // (whih is not yet the same as the WebRTC 1.0 transceiver) - RTCPeerConnection.prototype._createTransceiver = function(kind) { - var hasBundleTransport = this.transceivers.length > 0; - var transceiver = { - track: null, - iceGatherer: null, - iceTransport: null, - dtlsTransport: null, - localCapabilities: null, - remoteCapabilities: null, - rtpSender: null, - rtpReceiver: null, - kind: kind, - mid: null, - sendEncodingParameters: null, - recvEncodingParameters: null, - stream: null, - wantReceive: true - }; - if (this.usingBundle && hasBundleTransport) { - transceiver.iceTransport = this.transceivers[0].iceTransport; - transceiver.dtlsTransport = this.transceivers[0].dtlsTransport; - } else { - var transports = this._createIceAndDtlsTransports(); - transceiver.iceTransport = transports.iceTransport; - transceiver.dtlsTransport = transports.dtlsTransport; - } - this.transceivers.push(transceiver); - return transceiver; - }; - - RTCPeerConnection.prototype.addTrack = function(track, stream) { - var transceiver; - for (var i = 0; i < this.transceivers.length; i++) { - if (!this.transceivers[i].track && - this.transceivers[i].kind === track.kind) { - transceiver = this.transceivers[i]; - } - } - if (!transceiver) { - transceiver = this._createTransceiver(track.kind); - } - - transceiver.track = track; - transceiver.stream = stream; - transceiver.rtpSender = new RTCRtpSender(track, - transceiver.dtlsTransport); - - this._maybeFireNegotiationNeeded(); - return transceiver.rtpSender; - }; - - RTCPeerConnection.prototype.addStream = function(stream) { - var self = this; - if (edgeVersion >= 15025) { - this.localStreams.push(stream); - stream.getTracks().forEach(function(track) { - self.addTrack(track, stream); - }); - } else { - // Clone is necessary for local demos mostly, attaching directly - // to two different senders does not work (build 10547). - // Fixed in 15025 (or earlier) - var clonedStream = stream.clone(); - stream.getTracks().forEach(function(track, idx) { - var clonedTrack = clonedStream.getTracks()[idx]; - track.addEventListener('enabled', function(event) { - clonedTrack.enabled = event.enabled; - }); - }); - clonedStream.getTracks().forEach(function(track) { - self.addTrack(track, clonedStream); - }); - this.localStreams.push(clonedStream); - } - this._maybeFireNegotiationNeeded(); - }; - - RTCPeerConnection.prototype.removeStream = function(stream) { - var idx = this.localStreams.indexOf(stream); - if (idx > -1) { - this.localStreams.splice(idx, 1); - this._maybeFireNegotiationNeeded(); - } - }; - - RTCPeerConnection.prototype.getSenders = function() { - return this.transceivers.filter(function(transceiver) { - return !!transceiver.rtpSender; - }) - .map(function(transceiver) { - return transceiver.rtpSender; - }); - }; - - RTCPeerConnection.prototype.getReceivers = function() { - return this.transceivers.filter(function(transceiver) { - return !!transceiver.rtpReceiver; - }) - .map(function(transceiver) { - return transceiver.rtpReceiver; - }); - }; - - // Create ICE gatherer and hook it up. - RTCPeerConnection.prototype._createIceGatherer = function(mid, - sdpMLineIndex) { - var self = this; - var iceGatherer = new RTCIceGatherer(self.iceOptions); - iceGatherer.onlocalcandidate = function(evt) { - var event = new Event('icecandidate'); - event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex}; - - var cand = evt.candidate; - var end = !cand || Object.keys(cand).length === 0; - // Edge emits an empty object for RTCIceCandidateComplete‥ - if (end) { - // polyfill since RTCIceGatherer.state is not implemented in - // Edge 10547 yet. - if (iceGatherer.state === undefined) { - iceGatherer.state = 'completed'; - } - } else { - // RTCIceCandidate doesn't have a component, needs to be added - cand.component = 1; - event.candidate.candidate = SDPUtils.writeCandidate(cand); - } - - // update local description. - var sections = SDPUtils.splitSections(self.localDescription.sdp); - if (!end) { - sections[event.candidate.sdpMLineIndex + 1] += - 'a=' + event.candidate.candidate + '\r\n'; - } else { - sections[event.candidate.sdpMLineIndex + 1] += - 'a=end-of-candidates\r\n'; - } - self.localDescription.sdp = sections.join(''); - var transceivers = self._pendingOffer ? self._pendingOffer : - self.transceivers; - var complete = transceivers.every(function(transceiver) { - return transceiver.iceGatherer && - transceiver.iceGatherer.state === 'completed'; - }); - - // Emit candidate if localDescription is set. - // Also emits null candidate when all gatherers are complete. - switch (self.iceGatheringState) { - case 'new': - if (!end) { - self._localIceCandidatesBuffer.push(event); - } - if (end && complete) { - self._localIceCandidatesBuffer.push( - new Event('icecandidate')); - } - break; - case 'gathering': - self._emitBufferedCandidates(); - if (!end) { - self.dispatchEvent(event); - if (self.onicecandidate !== null) { - self.onicecandidate(event); - } - } - if (complete) { - self.dispatchEvent(new Event('icecandidate')); - if (self.onicecandidate !== null) { - self.onicecandidate(new Event('icecandidate')); - } - self.iceGatheringState = 'complete'; - self._emitGatheringStateChange(); - } - break; - case 'complete': - // should not happen... currently! - break; - default: // no-op. - break; - } - }; - return iceGatherer; - }; - - // Create ICE transport and DTLS transport. - RTCPeerConnection.prototype._createIceAndDtlsTransports = function() { - var self = this; - var iceTransport = new RTCIceTransport(null); - iceTransport.onicestatechange = function() { - self._updateConnectionState(); - }; - - var dtlsTransport = new RTCDtlsTransport(iceTransport); - dtlsTransport.ondtlsstatechange = function() { - self._updateConnectionState(); - }; - dtlsTransport.onerror = function() { - // onerror does not set state to failed by itself. - Object.defineProperty(dtlsTransport, 'state', - {value: 'failed', writable: true}); - self._updateConnectionState(); - }; - - return { - iceTransport: iceTransport, - dtlsTransport: dtlsTransport - }; - }; - - // Destroy ICE gatherer, ICE transport and DTLS transport. - // Without triggering the callbacks. - RTCPeerConnection.prototype._disposeIceAndDtlsTransports = function( - sdpMLineIndex) { - var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer; - if (iceGatherer) { - delete iceGatherer.onlocalcandidate; - delete this.transceivers[sdpMLineIndex].iceGatherer; - } - var iceTransport = this.transceivers[sdpMLineIndex].iceTransport; - if (iceTransport) { - delete iceTransport.onicestatechange; - delete this.transceivers[sdpMLineIndex].iceTransport; - } - var dtlsTransport = this.transceivers[sdpMLineIndex].dtlsTransport; - if (dtlsTransport) { - delete dtlsTransport.ondtlssttatechange; - delete dtlsTransport.onerror; - delete this.transceivers[sdpMLineIndex].dtlsTransport; - } - }; - - // Start the RTP Sender and Receiver for a transceiver. - RTCPeerConnection.prototype._transceive = function(transceiver, - send, recv) { - var params = getCommonCapabilities(transceiver.localCapabilities, - transceiver.remoteCapabilities); - if (send && transceiver.rtpSender) { - params.encodings = transceiver.sendEncodingParameters; - params.rtcp = { - cname: SDPUtils.localCName, - compound: transceiver.rtcpParameters.compound - }; - if (transceiver.recvEncodingParameters.length) { - params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc; - } - transceiver.rtpSender.send(params); - } - if (recv && transceiver.rtpReceiver) { - // remove RTX field in Edge 14942 - if (transceiver.kind === 'video' - && transceiver.recvEncodingParameters - && edgeVersion < 15019) { - transceiver.recvEncodingParameters.forEach(function(p) { - delete p.rtx; - }); - } - params.encodings = transceiver.recvEncodingParameters; - params.rtcp = { - cname: transceiver.rtcpParameters.cname, - compound: transceiver.rtcpParameters.compound - }; - if (transceiver.sendEncodingParameters.length) { - params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc; - } - transceiver.rtpReceiver.receive(params); - } - }; - - RTCPeerConnection.prototype.setLocalDescription = function(description) { - var self = this; - - if (!isActionAllowedInSignalingState('setLocalDescription', - description.type, this.signalingState)) { - var e = new Error('Can not set local ' + description.type + - ' in state ' + this.signalingState); - e.name = 'InvalidStateError'; - if (arguments.length > 2 && typeof arguments[2] === 'function') { - window.setTimeout(arguments[2], 0, e); - } - return Promise.reject(e); - } - - var sections; - var sessionpart; - if (description.type === 'offer') { - // FIXME: What was the purpose of this empty if statement? - // if (!this._pendingOffer) { - // } else { - if (this._pendingOffer) { - // VERY limited support for SDP munging. Limited to: - // * changing the order of codecs - sections = SDPUtils.splitSections(description.sdp); - sessionpart = sections.shift(); - sections.forEach(function(mediaSection, sdpMLineIndex) { - var caps = SDPUtils.parseRtpParameters(mediaSection); - self._pendingOffer[sdpMLineIndex].localCapabilities = caps; - }); - this.transceivers = this._pendingOffer; - delete this._pendingOffer; - } - } else if (description.type === 'answer') { - sections = SDPUtils.splitSections(self.remoteDescription.sdp); - sessionpart = sections.shift(); - var isIceLite = SDPUtils.matchPrefix(sessionpart, - 'a=ice-lite').length > 0; - sections.forEach(function(mediaSection, sdpMLineIndex) { - var transceiver = self.transceivers[sdpMLineIndex]; - var iceGatherer = transceiver.iceGatherer; - var iceTransport = transceiver.iceTransport; - var dtlsTransport = transceiver.dtlsTransport; - var localCapabilities = transceiver.localCapabilities; - var remoteCapabilities = transceiver.remoteCapabilities; - - var rejected = SDPUtils.isRejected(mediaSection); - - if (!rejected && !transceiver.isDatachannel) { - var remoteIceParameters = SDPUtils.getIceParameters( - mediaSection, sessionpart); - var remoteDtlsParameters = SDPUtils.getDtlsParameters( - mediaSection, sessionpart); - if (isIceLite) { - remoteDtlsParameters.role = 'server'; - } - - if (!self.usingBundle || sdpMLineIndex === 0) { - iceTransport.start(iceGatherer, remoteIceParameters, - isIceLite ? 'controlling' : 'controlled'); - dtlsTransport.start(remoteDtlsParameters); - } - - // Calculate intersection of capabilities. - var params = getCommonCapabilities(localCapabilities, - remoteCapabilities); - - // Start the RTCRtpSender. The RTCRtpReceiver for this - // transceiver has already been started in setRemoteDescription. - self._transceive(transceiver, - params.codecs.length > 0, - false); - } - }); - } - - this.localDescription = { - type: description.type, - sdp: description.sdp - }; - switch (description.type) { - case 'offer': - this._updateSignalingState('have-local-offer'); - break; - case 'answer': - this._updateSignalingState('stable'); - break; - default: - throw new TypeError('unsupported type "' + description.type + - '"'); - } - - // If a success callback was provided, emit ICE candidates after it - // has been executed. Otherwise, emit callback after the Promise is - // resolved. - var hasCallback = arguments.length > 1 && - typeof arguments[1] === 'function'; - if (hasCallback) { - var cb = arguments[1]; - window.setTimeout(function() { - cb(); - if (self.iceGatheringState === 'new') { - self.iceGatheringState = 'gathering'; - self._emitGatheringStateChange(); - } - self._emitBufferedCandidates(); - }, 0); - } - var p = Promise.resolve(); - p.then(function() { - if (!hasCallback) { - if (self.iceGatheringState === 'new') { - self.iceGatheringState = 'gathering'; - self._emitGatheringStateChange(); - } - // Usually candidates will be emitted earlier. - window.setTimeout(self._emitBufferedCandidates.bind(self), 500); - } - }); - return p; - }; - - RTCPeerConnection.prototype.setRemoteDescription = function(description) { - var self = this; - - if (!isActionAllowedInSignalingState('setRemoteDescription', - description.type, this.signalingState)) { - var e = new Error('Can not set remote ' + description.type + - ' in state ' + this.signalingState); - e.name = 'InvalidStateError'; - if (arguments.length > 2 && typeof arguments[2] === 'function') { - window.setTimeout(arguments[2], 0, e); - } - return Promise.reject(e); - } - - var streams = {}; - var receiverList = []; - var sections = SDPUtils.splitSections(description.sdp); - var sessionpart = sections.shift(); - var isIceLite = SDPUtils.matchPrefix(sessionpart, - 'a=ice-lite').length > 0; - var usingBundle = SDPUtils.matchPrefix(sessionpart, - 'a=group:BUNDLE ').length > 0; - this.usingBundle = usingBundle; - var iceOptions = SDPUtils.matchPrefix(sessionpart, - 'a=ice-options:')[0]; - if (iceOptions) { - this.canTrickleIceCandidates = iceOptions.substr(14).split(' ') - .indexOf('trickle') >= 0; - } else { - this.canTrickleIceCandidates = false; - } - - sections.forEach(function(mediaSection, sdpMLineIndex) { - var lines = SDPUtils.splitLines(mediaSection); - var kind = SDPUtils.getKind(mediaSection); - var rejected = SDPUtils.isRejected(mediaSection); - var protocol = lines[0].substr(2).split(' ')[2]; - - var direction = SDPUtils.getDirection(mediaSection, sessionpart); - var remoteMsid = SDPUtils.parseMsid(mediaSection); - - var mid = SDPUtils.getMid(mediaSection) || SDPUtils.generateIdentifier(); - - // Reject datachannels which are not implemented yet. - if (kind === 'application' && protocol === 'DTLS/SCTP') { - self.transceivers[sdpMLineIndex] = { - mid: mid, - isDatachannel: true - }; - return; - } - - var transceiver; - var iceGatherer; - var iceTransport; - var dtlsTransport; - var rtpReceiver; - var sendEncodingParameters; - var recvEncodingParameters; - var localCapabilities; - - var track; - // FIXME: ensure the mediaSection has rtcp-mux set. - var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection); - var remoteIceParameters; - var remoteDtlsParameters; - if (!rejected) { - remoteIceParameters = SDPUtils.getIceParameters(mediaSection, - sessionpart); - remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection, - sessionpart); - remoteDtlsParameters.role = 'client'; - } - recvEncodingParameters = - SDPUtils.parseRtpEncodingParameters(mediaSection); - - var rtcpParameters = SDPUtils.parseRtcpParameters(mediaSection); - - var isComplete = SDPUtils.matchPrefix(mediaSection, - 'a=end-of-candidates', sessionpart).length > 0; - var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:') - .map(function(cand) { - return SDPUtils.parseCandidate(cand); - }) - .filter(function(cand) { - return cand.component === '1' || cand.component === 1; - }); - if (description.type === 'offer' && !rejected) { - transceiver = self.transceivers[sdpMLineIndex] || - self._createTransceiver(kind); - transceiver.mid = mid; - - if (!transceiver.iceGatherer) { - transceiver.iceGatherer = usingBundle && sdpMLineIndex > 0 ? - self.transceivers[0].iceGatherer : - self._createIceGatherer(mid, sdpMLineIndex); - } - - if (isComplete && (!usingBundle || sdpMLineIndex === 0)) { - transceiver.iceTransport.setRemoteCandidates(cands); - } - - localCapabilities = RTCRtpReceiver.getCapabilities(kind); - - // filter RTX until additional stuff needed for RTX is implemented - // in adapter.js - if (edgeVersion < 15019) { - localCapabilities.codecs = localCapabilities.codecs.filter( - function(codec) { - return codec.name !== 'rtx'; - }); - } - - sendEncodingParameters = [{ - ssrc: (2 * sdpMLineIndex + 2) * 1001 - }]; - - if (direction === 'sendrecv' || direction === 'sendonly') { - rtpReceiver = new RTCRtpReceiver(transceiver.dtlsTransport, - kind); - - track = rtpReceiver.track; - // FIXME: does not work with Plan B. - if (remoteMsid) { - if (!streams[remoteMsid.stream]) { - streams[remoteMsid.stream] = new MediaStream(); - Object.defineProperty(streams[remoteMsid.stream], 'id', { - get: function() { - return remoteMsid.stream; - } - }); - } - Object.defineProperty(track, 'id', { - get: function() { - return remoteMsid.track; - } - }); - streams[remoteMsid.stream].addTrack(track); - receiverList.push([track, rtpReceiver, - streams[remoteMsid.stream]]); - } else { - if (!streams.default) { - streams.default = new MediaStream(); - } - streams.default.addTrack(track); - receiverList.push([track, rtpReceiver, streams.default]); - } - } - - transceiver.localCapabilities = localCapabilities; - transceiver.remoteCapabilities = remoteCapabilities; - transceiver.rtpReceiver = rtpReceiver; - transceiver.rtcpParameters = rtcpParameters; - transceiver.sendEncodingParameters = sendEncodingParameters; - transceiver.recvEncodingParameters = recvEncodingParameters; - - // Start the RTCRtpReceiver now. The RTPSender is started in - // setLocalDescription. - self._transceive(self.transceivers[sdpMLineIndex], - false, - direction === 'sendrecv' || direction === 'sendonly'); - } else if (description.type === 'answer' && !rejected) { - if (usingBundle && sdpMLineIndex > 0) { - self._disposeIceAndDtlsTransports(sdpMLineIndex); - self.transceivers[sdpMLineIndex].iceGatherer = - self.transceivers[0].iceGatherer; - self.transceivers[sdpMLineIndex].iceTransport = - self.transceivers[0].iceTransport; - self.transceivers[sdpMLineIndex].dtlsTransport = - self.transceivers[0].dtlsTransport; - if (self.transceivers[sdpMLineIndex].rtpSender) { - self.transceivers[sdpMLineIndex].rtpSender.setTransport( - self.transceivers[0].dtlsTransport); - } - if (self.transceivers[sdpMLineIndex].rtpReceiver) { - self.transceivers[sdpMLineIndex].rtpReceiver.setTransport( - self.transceivers[0].dtlsTransport); - } - } - transceiver = self.transceivers[sdpMLineIndex]; - iceGatherer = transceiver.iceGatherer; - iceTransport = transceiver.iceTransport; - dtlsTransport = transceiver.dtlsTransport; - rtpReceiver = transceiver.rtpReceiver; - sendEncodingParameters = transceiver.sendEncodingParameters; - localCapabilities = transceiver.localCapabilities; - - self.transceivers[sdpMLineIndex].recvEncodingParameters = - recvEncodingParameters; - self.transceivers[sdpMLineIndex].remoteCapabilities = - remoteCapabilities; - self.transceivers[sdpMLineIndex].rtcpParameters = rtcpParameters; - - if ((isIceLite || isComplete) && cands.length) { - iceTransport.setRemoteCandidates(cands); - } - if (!usingBundle || sdpMLineIndex === 0) { - iceTransport.start(iceGatherer, remoteIceParameters, - 'controlling'); - dtlsTransport.start(remoteDtlsParameters); - } - - self._transceive(transceiver, - direction === 'sendrecv' || direction === 'recvonly', - direction === 'sendrecv' || direction === 'sendonly'); - - if (rtpReceiver && - (direction === 'sendrecv' || direction === 'sendonly')) { - track = rtpReceiver.track; - if (remoteMsid) { - if (!streams[remoteMsid.stream]) { - streams[remoteMsid.stream] = new MediaStream(); - } - streams[remoteMsid.stream].addTrack(track); - receiverList.push([track, rtpReceiver, streams[remoteMsid.stream]]); - } else { - if (!streams.default) { - streams.default = new MediaStream(); - } - streams.default.addTrack(track); - receiverList.push([track, rtpReceiver, streams.default]); - } - } else { - // FIXME: actually the receiver should be created later. - delete transceiver.rtpReceiver; - } - } - }); - - this.remoteDescription = { - type: description.type, - sdp: description.sdp - }; - switch (description.type) { - case 'offer': - this._updateSignalingState('have-remote-offer'); - break; - case 'answer': - this._updateSignalingState('stable'); - break; - default: - throw new TypeError('unsupported type "' + description.type + - '"'); - } - Object.keys(streams).forEach(function(sid) { - var stream = streams[sid]; - if (stream.getTracks().length) { - self.remoteStreams.push(stream); - var event = new Event('addstream'); - event.stream = stream; - self.dispatchEvent(event); - if (self.onaddstream !== null) { - window.setTimeout(function() { - self.onaddstream(event); - }, 0); - } - - receiverList.forEach(function(item) { - var track = item[0]; - var receiver = item[1]; - if (stream.id !== item[2].id) { - return; - } - var trackEvent = new Event('track'); - trackEvent.track = track; - trackEvent.receiver = receiver; - trackEvent.streams = [stream]; - self.dispatchEvent(trackEvent); - if (self.ontrack !== null) { - window.setTimeout(function() { - self.ontrack(trackEvent); - }, 0); - } - }); - } - }); - - // check whether addIceCandidate({}) was called within four seconds after - // setRemoteDescription. - window.setTimeout(function() { - if (!(self && self.transceivers)) { - return; - } - self.transceivers.forEach(function(transceiver) { - if (transceiver.iceTransport && - transceiver.iceTransport.state === 'new' && - transceiver.iceTransport.getRemoteCandidates().length > 0) { - console.warn('Timeout for addRemoteCandidate. Consider sending ' + - 'an end-of-candidates notification'); - transceiver.iceTransport.addRemoteCandidate({}); - } - }); - }, 4000); - - if (arguments.length > 1 && typeof arguments[1] === 'function') { - window.setTimeout(arguments[1], 0); - } - return Promise.resolve(); - }; - - RTCPeerConnection.prototype.close = function() { - this.transceivers.forEach(function(transceiver) { - /* not yet - if (transceiver.iceGatherer) { - transceiver.iceGatherer.close(); - } - */ - if (transceiver.iceTransport) { - transceiver.iceTransport.stop(); - } - if (transceiver.dtlsTransport) { - transceiver.dtlsTransport.stop(); - } - if (transceiver.rtpSender) { - transceiver.rtpSender.stop(); - } - if (transceiver.rtpReceiver) { - transceiver.rtpReceiver.stop(); - } - }); - // FIXME: clean up tracks, local streams, remote streams, etc - this._updateSignalingState('closed'); - }; - - // Update the signaling state. - RTCPeerConnection.prototype._updateSignalingState = function(newState) { - this.signalingState = newState; - var event = new Event('signalingstatechange'); - this.dispatchEvent(event); - if (this.onsignalingstatechange !== null) { - this.onsignalingstatechange(event); - } - }; - - // Determine whether to fire the negotiationneeded event. - RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() { - var self = this; - if (this.signalingState !== 'stable' || this.needNegotiation === true) { - return; - } - this.needNegotiation = true; - window.setTimeout(function() { - if (self.needNegotiation === false) { - return; - } - self.needNegotiation = false; - var event = new Event('negotiationneeded'); - self.dispatchEvent(event); - if (self.onnegotiationneeded !== null) { - self.onnegotiationneeded(event); - } - }, 0); - }; - - // Update the connection state. - RTCPeerConnection.prototype._updateConnectionState = function() { - var self = this; - var newState; - var states = { - 'new': 0, - closed: 0, - connecting: 0, - checking: 0, - connected: 0, - completed: 0, - failed: 0 - }; - this.transceivers.forEach(function(transceiver) { - states[transceiver.iceTransport.state]++; - states[transceiver.dtlsTransport.state]++; - }); - // ICETransport.completed and connected are the same for this purpose. - states.connected += states.completed; - - newState = 'new'; - if (states.failed > 0) { - newState = 'failed'; - } else if (states.connecting > 0 || states.checking > 0) { - newState = 'connecting'; - } else if (states.disconnected > 0) { - newState = 'disconnected'; - } else if (states.new > 0) { - newState = 'new'; - } else if (states.connected > 0 || states.completed > 0) { - newState = 'connected'; - } - - if (newState !== self.iceConnectionState) { - self.iceConnectionState = newState; - var event = new Event('iceconnectionstatechange'); - this.dispatchEvent(event); - if (this.oniceconnectionstatechange !== null) { - this.oniceconnectionstatechange(event); - } - } - }; - - RTCPeerConnection.prototype.createOffer = function() { - var self = this; - if (this._pendingOffer) { - throw new Error('createOffer called while there is a pending offer.'); - } - var offerOptions; - if (arguments.length === 1 && typeof arguments[0] !== 'function') { - offerOptions = arguments[0]; - } else if (arguments.length === 3) { - offerOptions = arguments[2]; - } - - var numAudioTracks = this.transceivers.filter(function(t) { - return t.kind === 'audio'; - }).length; - var numVideoTracks = this.transceivers.filter(function(t) { - return t.kind === 'video'; - }).length; - - // Determine number of audio and video tracks we need to send/recv. - if (offerOptions) { - // Reject Chrome legacy constraints. - if (offerOptions.mandatory || offerOptions.optional) { - throw new TypeError( - 'Legacy mandatory/optional constraints not supported.'); - } - if (offerOptions.offerToReceiveAudio !== undefined) { - if (offerOptions.offerToReceiveAudio === true) { - numAudioTracks = 1; - } else if (offerOptions.offerToReceiveAudio === false) { - numAudioTracks = 0; - } else { - numAudioTracks = offerOptions.offerToReceiveAudio; - } - } - if (offerOptions.offerToReceiveVideo !== undefined) { - if (offerOptions.offerToReceiveVideo === true) { - numVideoTracks = 1; - } else if (offerOptions.offerToReceiveVideo === false) { - numVideoTracks = 0; - } else { - numVideoTracks = offerOptions.offerToReceiveVideo; - } - } - } - - this.transceivers.forEach(function(transceiver) { - if (transceiver.kind === 'audio') { - numAudioTracks--; - if (numAudioTracks < 0) { - transceiver.wantReceive = false; - } - } else if (transceiver.kind === 'video') { - numVideoTracks--; - if (numVideoTracks < 0) { - transceiver.wantReceive = false; - } - } - }); - - // Create M-lines for recvonly streams. - while (numAudioTracks > 0 || numVideoTracks > 0) { - if (numAudioTracks > 0) { - this._createTransceiver('audio'); - numAudioTracks--; - } - if (numVideoTracks > 0) { - this._createTransceiver('video'); - numVideoTracks--; - } - } - // reorder tracks - var transceivers = sortTracks(this.transceivers); - - var sdp = SDPUtils.writeSessionBoilerplate(); - transceivers.forEach(function(transceiver, sdpMLineIndex) { - // For each track, create an ice gatherer, ice transport, - // dtls transport, potentially rtpsender and rtpreceiver. - var track = transceiver.track; - var kind = transceiver.kind; - var mid = SDPUtils.generateIdentifier(); - transceiver.mid = mid; - - if (!transceiver.iceGatherer) { - transceiver.iceGatherer = self.usingBundle && sdpMLineIndex > 0 ? - transceivers[0].iceGatherer : - self._createIceGatherer(mid, sdpMLineIndex); - } - - var localCapabilities = RTCRtpSender.getCapabilities(kind); - // filter RTX until additional stuff needed for RTX is implemented - // in adapter.js - if (edgeVersion < 15019) { - localCapabilities.codecs = localCapabilities.codecs.filter( - function(codec) { - return codec.name !== 'rtx'; - }); - } - localCapabilities.codecs.forEach(function(codec) { - // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552 - // by adding level-asymmetry-allowed=1 - if (codec.name === 'H264' && - codec.parameters['level-asymmetry-allowed'] === undefined) { - codec.parameters['level-asymmetry-allowed'] = '1'; - } - }); - - // generate an ssrc now, to be used later in rtpSender.send - var sendEncodingParameters = [{ - ssrc: (2 * sdpMLineIndex + 1) * 1001 - }]; - if (track) { - // add RTX - if (edgeVersion >= 15019 && kind === 'video') { - sendEncodingParameters[0].rtx = { - ssrc: (2 * sdpMLineIndex + 1) * 1001 + 1 - }; - } - } - - if (transceiver.wantReceive) { - transceiver.rtpReceiver = new RTCRtpReceiver(transceiver.dtlsTransport, - kind); - } - - transceiver.localCapabilities = localCapabilities; - transceiver.sendEncodingParameters = sendEncodingParameters; - }); - - // always offer BUNDLE and dispose on return if not supported. - if (this._config.bundlePolicy !== 'max-compat') { - sdp += 'a=group:BUNDLE ' + transceivers.map(function(t) { - return t.mid; - }).join(' ') + '\r\n'; - } - sdp += 'a=ice-options:trickle\r\n'; - - transceivers.forEach(function(transceiver, sdpMLineIndex) { - sdp += SDPUtils.writeMediaSection(transceiver, - transceiver.localCapabilities, 'offer', transceiver.stream); - sdp += 'a=rtcp-rsize\r\n'; - }); - - this._pendingOffer = transceivers; - var desc = new RTCSessionDescription({ - type: 'offer', - sdp: sdp - }); - if (arguments.length && typeof arguments[0] === 'function') { - window.setTimeout(arguments[0], 0, desc); - } - return Promise.resolve(desc); - }; - - RTCPeerConnection.prototype.createAnswer = function() { - var sdp = SDPUtils.writeSessionBoilerplate(); - if (this.usingBundle) { - sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) { - return t.mid; - }).join(' ') + '\r\n'; - } - this.transceivers.forEach(function(transceiver, sdpMLineIndex) { - if (transceiver.isDatachannel) { - sdp += 'm=application 0 DTLS/SCTP 5000\r\n' + - 'c=IN IP4 0.0.0.0\r\n' + - 'a=mid:' + transceiver.mid + '\r\n'; - return; - } - - // FIXME: look at direction. - if (transceiver.stream) { - var localTrack; - if (transceiver.kind === 'audio') { - localTrack = transceiver.stream.getAudioTracks()[0]; - } else if (transceiver.kind === 'video') { - localTrack = transceiver.stream.getVideoTracks()[0]; - } - if (localTrack) { - // add RTX - if (edgeVersion >= 15019 && transceiver.kind === 'video') { - transceiver.sendEncodingParameters[0].rtx = { - ssrc: (2 * sdpMLineIndex + 2) * 1001 + 1 - }; - } - } - } - - // Calculate intersection of capabilities. - var commonCapabilities = getCommonCapabilities( - transceiver.localCapabilities, - transceiver.remoteCapabilities); - - var hasRtx = commonCapabilities.codecs.filter(function(c) { - return c.name.toLowerCase() === 'rtx'; - }).length; - if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) { - delete transceiver.sendEncodingParameters[0].rtx; - } - - sdp += SDPUtils.writeMediaSection(transceiver, commonCapabilities, - 'answer', transceiver.stream); - if (transceiver.rtcpParameters && - transceiver.rtcpParameters.reducedSize) { - sdp += 'a=rtcp-rsize\r\n'; - } - }); - - var desc = new RTCSessionDescription({ - type: 'answer', - sdp: sdp - }); - if (arguments.length && typeof arguments[0] === 'function') { - window.setTimeout(arguments[0], 0, desc); - } - return Promise.resolve(desc); - }; - - RTCPeerConnection.prototype.addIceCandidate = function(candidate) { - if (!candidate) { - for (var j = 0; j < this.transceivers.length; j++) { - this.transceivers[j].iceTransport.addRemoteCandidate({}); - if (this.usingBundle) { - return Promise.resolve(); - } - } - } else { - var mLineIndex = candidate.sdpMLineIndex; - if (candidate.sdpMid) { - for (var i = 0; i < this.transceivers.length; i++) { - if (this.transceivers[i].mid === candidate.sdpMid) { - mLineIndex = i; - break; - } - } - } - var transceiver = this.transceivers[mLineIndex]; - if (transceiver) { - var cand = Object.keys(candidate.candidate).length > 0 ? - SDPUtils.parseCandidate(candidate.candidate) : {}; - // Ignore Chrome's invalid candidates since Edge does not like them. - if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) { - return Promise.resolve(); - } - // Ignore RTCP candidates, we assume RTCP-MUX. - if (cand.component && - !(cand.component === '1' || cand.component === 1)) { - return Promise.resolve(); - } - transceiver.iceTransport.addRemoteCandidate(cand); - - // update the remoteDescription. - var sections = SDPUtils.splitSections(this.remoteDescription.sdp); - sections[mLineIndex + 1] += (cand.type ? candidate.candidate.trim() - : 'a=end-of-candidates') + '\r\n'; - this.remoteDescription.sdp = sections.join(''); - } - } - if (arguments.length > 1 && typeof arguments[1] === 'function') { - window.setTimeout(arguments[1], 0); - } - return Promise.resolve(); - }; - - RTCPeerConnection.prototype.getStats = function() { - var promises = []; - this.transceivers.forEach(function(transceiver) { - ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport', - 'dtlsTransport'].forEach(function(method) { - if (transceiver[method]) { - promises.push(transceiver[method].getStats()); - } - }); - }); - var cb = arguments.length > 1 && typeof arguments[1] === 'function' && - arguments[1]; - var fixStatsType = function(stat) { - return { - inboundrtp: 'inbound-rtp', - outboundrtp: 'outbound-rtp', - candidatepair: 'candidate-pair', - localcandidate: 'local-candidate', - remotecandidate: 'remote-candidate' - }[stat.type] || stat.type; - }; - return new Promise(function(resolve) { - // shim getStats with maplike support - var results = new Map(); - Promise.all(promises).then(function(res) { - res.forEach(function(result) { - Object.keys(result).forEach(function(id) { - result[id].type = fixStatsType(result[id]); - results.set(id, result[id]); - }); - }); - if (cb) { - window.setTimeout(cb, 0, results); - } - resolve(results); - }); - }); - }; - return RTCPeerConnection; -}; - -},{"sdp":20}],30:[function(require,module,exports){ -/* - * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. - */ - /* eslint-env node */ -'use strict'; - -var browserDetails = require('../utils').browserDetails; - -var firefoxShim = { - shimOnTrack: function() { - if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in - window.RTCPeerConnection.prototype)) { - Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', { - get: function() { - return this._ontrack; - }, - set: function(f) { - if (this._ontrack) { - this.removeEventListener('track', this._ontrack); - this.removeEventListener('addstream', this._ontrackpoly); - } - this.addEventListener('track', this._ontrack = f); - this.addEventListener('addstream', this._ontrackpoly = function(e) { - e.stream.getTracks().forEach(function(track) { - var event = new Event('track'); - event.track = track; - event.receiver = {track: track}; - event.streams = [e.stream]; - this.dispatchEvent(event); - }.bind(this)); - }.bind(this)); - } - }); - } - }, - - shimSourceObject: function() { - // Firefox has supported mozSrcObject since FF22, unprefixed in 42. - if (typeof window === 'object') { - if (window.HTMLMediaElement && - !('srcObject' in window.HTMLMediaElement.prototype)) { - // Shim the srcObject property, once, when HTMLMediaElement is found. - Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { - get: function() { - return this.mozSrcObject; - }, - set: function(stream) { - this.mozSrcObject = stream; - } - }); - } - } - }, - - shimPeerConnection: function() { - if (typeof window !== 'object' || !(window.RTCPeerConnection || - window.mozRTCPeerConnection)) { - return; // probably media.peerconnection.enabled=false in about:config - } - // The RTCPeerConnection object. - if (!window.RTCPeerConnection) { - window.RTCPeerConnection = function(pcConfig, pcConstraints) { - if (browserDetails.version < 38) { - // .urls is not supported in FF < 38. - // create RTCIceServers with a single url. - if (pcConfig && pcConfig.iceServers) { - var newIceServers = []; - for (var i = 0; i < pcConfig.iceServers.length; i++) { - var server = pcConfig.iceServers[i]; - if (server.hasOwnProperty('urls')) { - for (var j = 0; j < server.urls.length; j++) { - var newServer = { - url: server.urls[j] - }; - if (server.urls[j].indexOf('turn') === 0) { - newServer.username = server.username; - newServer.credential = server.credential; - } - newIceServers.push(newServer); - } - } else { - newIceServers.push(pcConfig.iceServers[i]); - } - } - pcConfig.iceServers = newIceServers; - } - } - return new mozRTCPeerConnection(pcConfig, pcConstraints); - }; - window.RTCPeerConnection.prototype = mozRTCPeerConnection.prototype; - - // wrap static methods. Currently just generateCertificate. - if (mozRTCPeerConnection.generateCertificate) { - Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { - get: function() { - return mozRTCPeerConnection.generateCertificate; - } - }); - } - - window.RTCSessionDescription = mozRTCSessionDescription; - window.RTCIceCandidate = mozRTCIceCandidate; - } - - // shim away need for obsolete RTCIceCandidate/RTCSessionDescription. - ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] - .forEach(function(method) { - var nativeMethod = RTCPeerConnection.prototype[method]; - RTCPeerConnection.prototype[method] = function() { - arguments[0] = new ((method === 'addIceCandidate') ? - RTCIceCandidate : RTCSessionDescription)(arguments[0]); - return nativeMethod.apply(this, arguments); - }; - }); - - // support for addIceCandidate(null or undefined) - var nativeAddIceCandidate = - RTCPeerConnection.prototype.addIceCandidate; - RTCPeerConnection.prototype.addIceCandidate = function() { - if (!arguments[0]) { - if (arguments[1]) { - arguments[1].apply(null); - } - return Promise.resolve(); - } - return nativeAddIceCandidate.apply(this, arguments); - }; - - // shim getStats with maplike support - var makeMapStats = function(stats) { - var map = new Map(); - Object.keys(stats).forEach(function(key) { - map.set(key, stats[key]); - map[key] = stats[key]; - }); - return map; - }; - - var modernStatsTypes = { - inboundrtp: 'inbound-rtp', - outboundrtp: 'outbound-rtp', - candidatepair: 'candidate-pair', - localcandidate: 'local-candidate', - remotecandidate: 'remote-candidate' - }; - - var nativeGetStats = RTCPeerConnection.prototype.getStats; - RTCPeerConnection.prototype.getStats = function(selector, onSucc, onErr) { - return nativeGetStats.apply(this, [selector || null]) - .then(function(stats) { - if (browserDetails.version < 48) { - stats = makeMapStats(stats); - } - if (browserDetails.version < 53 && !onSucc) { - // Shim only promise getStats with spec-hyphens in type names - // Leave callback version alone; misc old uses of forEach before Map - try { - stats.forEach(function(stat) { - stat.type = modernStatsTypes[stat.type] || stat.type; - }); - } catch (e) { - if (e.name !== 'TypeError') { - throw e; - } - // Avoid TypeError: "type" is read-only, in old versions. 34-43ish - stats.forEach(function(stat, i) { - stats.set(i, Object.assign({}, stat, { - type: modernStatsTypes[stat.type] || stat.type - })); - }); - } - } - return stats; - }) - .then(onSucc, onErr); - }; - } -}; - -// Expose public methods. -module.exports = { - shimOnTrack: firefoxShim.shimOnTrack, - shimSourceObject: firefoxShim.shimSourceObject, - shimPeerConnection: firefoxShim.shimPeerConnection, - shimGetUserMedia: require('./getusermedia') -}; - -},{"../utils":33,"./getusermedia":31}],31:[function(require,module,exports){ -/* - * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. - */ - /* eslint-env node */ -'use strict'; - -var logging = require('../utils').log; -var browserDetails = require('../utils').browserDetails; - -// Expose public methods. -module.exports = function() { - var shimError_ = function(e) { - return { - name: { - InternalError: 'NotReadableError', - NotSupportedError: 'TypeError', - PermissionDeniedError: 'NotAllowedError', - SecurityError: 'NotAllowedError' - }[e.name] || e.name, - message: { - 'The operation is insecure.': 'The request is not allowed by the ' + - 'user agent or the platform in the current context.' - }[e.message] || e.message, - constraint: e.constraint, - toString: function() { - return this.name + (this.message && ': ') + this.message; - } - }; - }; - - // getUserMedia constraints shim. - var getUserMedia_ = function(constraints, onSuccess, onError) { - var constraintsToFF37_ = function(c) { - if (typeof c !== 'object' || c.require) { - return c; - } - var require = []; - Object.keys(c).forEach(function(key) { - if (key === 'require' || key === 'advanced' || key === 'mediaSource') { - return; - } - var r = c[key] = (typeof c[key] === 'object') ? - c[key] : {ideal: c[key]}; - if (r.min !== undefined || - r.max !== undefined || r.exact !== undefined) { - require.push(key); - } - if (r.exact !== undefined) { - if (typeof r.exact === 'number') { - r. min = r.max = r.exact; - } else { - c[key] = r.exact; - } - delete r.exact; - } - if (r.ideal !== undefined) { - c.advanced = c.advanced || []; - var oc = {}; - if (typeof r.ideal === 'number') { - oc[key] = {min: r.ideal, max: r.ideal}; - } else { - oc[key] = r.ideal; - } - c.advanced.push(oc); - delete r.ideal; - if (!Object.keys(r).length) { - delete c[key]; - } - } - }); - if (require.length) { - c.require = require; - } - return c; - }; - constraints = JSON.parse(JSON.stringify(constraints)); - if (browserDetails.version < 38) { - logging('spec: ' + JSON.stringify(constraints)); - if (constraints.audio) { - constraints.audio = constraintsToFF37_(constraints.audio); - } - if (constraints.video) { - constraints.video = constraintsToFF37_(constraints.video); - } - logging('ff37: ' + JSON.stringify(constraints)); - } - return navigator.mozGetUserMedia(constraints, onSuccess, function(e) { - onError(shimError_(e)); - }); - }; - - // Returns the result of getUserMedia as a Promise. - var getUserMediaPromise_ = function(constraints) { - return new Promise(function(resolve, reject) { - getUserMedia_(constraints, resolve, reject); - }); - }; - - // Shim for mediaDevices on older versions. - if (!navigator.mediaDevices) { - navigator.mediaDevices = {getUserMedia: getUserMediaPromise_, - addEventListener: function() { }, - removeEventListener: function() { } - }; - } - navigator.mediaDevices.enumerateDevices = - navigator.mediaDevices.enumerateDevices || function() { - return new Promise(function(resolve) { - var infos = [ - {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''}, - {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''} - ]; - resolve(infos); - }); - }; - - if (browserDetails.version < 41) { - // Work around http://bugzil.la/1169665 - var orgEnumerateDevices = - navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices); - navigator.mediaDevices.enumerateDevices = function() { - return orgEnumerateDevices().then(undefined, function(e) { - if (e.name === 'NotFoundError') { - return []; - } - throw e; - }); - }; - } - if (browserDetails.version < 49) { - var origGetUserMedia = navigator.mediaDevices.getUserMedia. - bind(navigator.mediaDevices); - navigator.mediaDevices.getUserMedia = function(c) { - return origGetUserMedia(c).then(function(stream) { - // Work around https://bugzil.la/802326 - if (c.audio && !stream.getAudioTracks().length || - c.video && !stream.getVideoTracks().length) { - stream.getTracks().forEach(function(track) { - track.stop(); - }); - throw new DOMException('The object can not be found here.', - 'NotFoundError'); - } - return stream; - }, function(e) { - return Promise.reject(shimError_(e)); - }); - }; - } - navigator.getUserMedia = function(constraints, onSuccess, onError) { - if (browserDetails.version < 44) { - return getUserMedia_(constraints, onSuccess, onError); - } - // Replace Firefox 44+'s deprecation warning with unprefixed version. - console.warn('navigator.getUserMedia has been replaced by ' + - 'navigator.mediaDevices.getUserMedia'); - navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError); - }; -}; - -},{"../utils":33}],32:[function(require,module,exports){ -/* - * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. - */ -'use strict'; -var safariShim = { - // TODO: DrAlex, should be here, double check against LayoutTests - - // TODO: once the back-end for the mac port is done, add. - // TODO: check for webkitGTK+ - // shimPeerConnection: function() { }, - - shimAddStream: function() { - if (typeof window === 'object' && window.RTCPeerConnection && - !('addStream' in window.RTCPeerConnection.prototype)) { - RTCPeerConnection.prototype.addStream = function(stream) { - var self = this; - stream.getTracks().forEach(function(track) { - self.addTrack(track, stream); - }); - }; - } - }, - shimOnAddStream: function() { - if (typeof window === 'object' && window.RTCPeerConnection && - !('onaddstream' in window.RTCPeerConnection.prototype)) { - Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', { - get: function() { - return this._onaddstream; - }, - set: function(f) { - if (this._onaddstream) { - this.removeEventListener('addstream', this._onaddstream); - this.removeEventListener('track', this._onaddstreampoly); - } - this.addEventListener('addstream', this._onaddstream = f); - this.addEventListener('track', this._onaddstreampoly = function(e) { - var stream = e.streams[0]; - if (!this._streams) { - this._streams = []; - } - if (this._streams.indexOf(stream) >= 0) { - return; - } - this._streams.push(stream); - var event = new Event('addstream'); - event.stream = e.streams[0]; - this.dispatchEvent(event); - }.bind(this)); - } - }); - } - }, - shimCallbacksAPI: function() { - if (typeof window !== 'object' || !window.RTCPeerConnection) { - return; - } - var prototype = RTCPeerConnection.prototype; - var createOffer = prototype.createOffer; - var createAnswer = prototype.createAnswer; - var setLocalDescription = prototype.setLocalDescription; - var setRemoteDescription = prototype.setRemoteDescription; - var addIceCandidate = prototype.addIceCandidate; - - prototype.createOffer = function(successCallback, failureCallback) { - var options = (arguments.length >= 2) ? arguments[2] : arguments[0]; - var promise = createOffer.apply(this, [options]); - if (!failureCallback) { - return promise; - } - promise.then(successCallback, failureCallback); - return Promise.resolve(); - }; - - prototype.createAnswer = function(successCallback, failureCallback) { - var options = (arguments.length >= 2) ? arguments[2] : arguments[0]; - var promise = createAnswer.apply(this, [options]); - if (!failureCallback) { - return promise; - } - promise.then(successCallback, failureCallback); - return Promise.resolve(); - }; - - var withCallback = function(description, successCallback, failureCallback) { - var promise = setLocalDescription.apply(this, [description]); - if (!failureCallback) { - return promise; - } - promise.then(successCallback, failureCallback); - return Promise.resolve(); - }; - prototype.setLocalDescription = withCallback; - - withCallback = function(description, successCallback, failureCallback) { - var promise = setRemoteDescription.apply(this, [description]); - if (!failureCallback) { - return promise; - } - promise.then(successCallback, failureCallback); - return Promise.resolve(); - }; - prototype.setRemoteDescription = withCallback; - - withCallback = function(candidate, successCallback, failureCallback) { - var promise = addIceCandidate.apply(this, [candidate]); - if (!failureCallback) { - return promise; - } - promise.then(successCallback, failureCallback); - return Promise.resolve(); - }; - prototype.addIceCandidate = withCallback; - }, - shimGetUserMedia: function() { - if (!navigator.getUserMedia) { - if (navigator.webkitGetUserMedia) { - navigator.getUserMedia = navigator.webkitGetUserMedia.bind(navigator); - } else if (navigator.mediaDevices && - navigator.mediaDevices.getUserMedia) { - navigator.getUserMedia = function(constraints, cb, errcb) { - navigator.mediaDevices.getUserMedia(constraints) - .then(cb, errcb); - }.bind(navigator); - } - } - } -}; - -// Expose public methods. -module.exports = { - shimCallbacksAPI: safariShim.shimCallbacksAPI, - shimAddStream: safariShim.shimAddStream, - shimOnAddStream: safariShim.shimOnAddStream, - shimGetUserMedia: safariShim.shimGetUserMedia - // TODO - // shimPeerConnection: safariShim.shimPeerConnection -}; - -},{}],33:[function(require,module,exports){ -/* - * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. - * - * Use of this source code is governed by a BSD-style license - * that can be found in the LICENSE file in the root of the source - * tree. - */ - /* eslint-env node */ -'use strict'; - -var logDisabled_ = true; - -// Utility methods. -var utils = { - disableLog: function(bool) { - if (typeof bool !== 'boolean') { - return new Error('Argument type: ' + typeof bool + - '. Please use a boolean.'); - } - logDisabled_ = bool; - return (bool) ? 'adapter.js logging disabled' : - 'adapter.js logging enabled'; - }, - - log: function() { - if (typeof window === 'object') { - if (logDisabled_) { - return; - } - if (typeof console !== 'undefined' && typeof console.log === 'function') { - console.log.apply(console, arguments); - } - } - }, - - /** - * Extract browser version out of the provided user agent string. - * - * @param {!string} uastring userAgent string. - * @param {!string} expr Regular expression used as match criteria. - * @param {!number} pos position in the version string to be returned. - * @return {!number} browser version. - */ - extractVersion: function(uastring, expr, pos) { - var match = uastring.match(expr); - return match && match.length >= pos && parseInt(match[pos], 10); - }, - - /** - * Browser detector. - * - * @return {object} result containing browser and version - * properties. - */ - detectBrowser: function() { - // Returned result object. - var result = {}; - result.browser = null; - result.version = null; - - // Fail early if it's not a browser - if (typeof window === 'undefined' || !window.navigator) { - result.browser = 'Not a browser.'; - return result; - } - - // Firefox. - if (navigator.mozGetUserMedia) { - result.browser = 'firefox'; - result.version = this.extractVersion(navigator.userAgent, - /Firefox\/(\d+)\./, 1); - } else if (navigator.webkitGetUserMedia) { - // Chrome, Chromium, Webview, Opera, all use the chrome shim for now - if (window.webkitRTCPeerConnection) { - result.browser = 'chrome'; - result.version = this.extractVersion(navigator.userAgent, - /Chrom(e|ium)\/(\d+)\./, 2); - } else { // Safari (in an unpublished version) or unknown webkit-based. - if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) { - result.browser = 'safari'; - result.version = this.extractVersion(navigator.userAgent, - /AppleWebKit\/(\d+)\./, 1); - } else { // unknown webkit-based browser. - result.browser = 'Unsupported webkit-based browser ' + - 'with GUM support but no WebRTC support.'; - return result; - } - } - } else if (navigator.mediaDevices && - navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge. - result.browser = 'edge'; - result.version = this.extractVersion(navigator.userAgent, - /Edge\/(\d+).(\d+)$/, 2); - } else if (navigator.mediaDevices && - navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) { - // Safari, with webkitGetUserMedia removed. - result.browser = 'safari'; - result.version = this.extractVersion(navigator.userAgent, - /AppleWebKit\/(\d+)\./, 1); - } else { // Default fallthrough: not supported. - result.browser = 'Not a supported browser.'; - return result; - } - - return result; - }, - - // shimCreateObjectURL must be called before shimSourceObject to avoid loop. - - shimCreateObjectURL: function() { - if(true)return; - if (!(typeof window === 'object' && window.HTMLMediaElement && - 'srcObject' in window.HTMLMediaElement.prototype)) { - // Only shim CreateObjectURL using srcObject if srcObject exists. - return undefined; - } - - var nativeCreateObjectURL = URL.createObjectURL.bind(URL); - var nativeRevokeObjectURL = URL.revokeObjectURL.bind(URL); - var streams = new Map(), newId = 0; - - URL.createObjectURL = function(stream) { - if ('getTracks' in stream) { - var url = 'polyblob:' + (++newId); - streams.set(url, stream); - console.log('URL.createObjectURL(stream) is deprecated! ' + - 'Use elem.srcObject = stream instead!'); - return url; - } - return nativeCreateObjectURL(stream); - }; - URL.revokeObjectURL = function(url) { - nativeRevokeObjectURL(url); - streams.delete(url); - }; - - var dsc = Object.getOwnPropertyDescriptor(window.HTMLMediaElement.prototype, - 'src'); - Object.defineProperty(window.HTMLMediaElement.prototype, 'src', { - get: function() { - return dsc.get.apply(this); - }, - set: function(url) { - this.srcObject = streams.get(url) || null; - return dsc.set.apply(this, [url]); - } - }); - - var nativeSetAttribute = HTMLMediaElement.prototype.setAttribute; - HTMLMediaElement.prototype.setAttribute = function() { - if (arguments.length === 2 && - ('' + arguments[0]).toLowerCase() === 'src') { - this.srcObject = streams.get(arguments[1]) || null; - } - return nativeSetAttribute.apply(this, arguments); - }; - } -}; - -// Export. -module.exports = { - log: utils.log, - disableLog: utils.disableLog, - browserDetails: utils.detectBrowser(), - extractVersion: utils.extractVersion, - shimCreateObjectURL: utils.shimCreateObjectURL, - detectBrowser: utils.detectBrowser.bind(utils) -}; - -},{}],34:[function(require,module,exports){ -module.exports={ - "name": "plivowebsdk", - "title": "plivowebsdk", - "version": "2.0.13", - "description": "Plivo WebRTC sdk for use in chrome/firefox ", - "main": "./lib/index.js", - "directories": { - "example": "example" - }, - "scripts": { - "build": "node_modules/gulp/bin/gulp.js build" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/gigster-eng/PlivoWebSDK.git" - }, - "author": "", - "license": "ISC", - "bugs": { - "url": "https://github.com/gigster-eng/PlivoWebSDK/issues" - }, - "homepage": "https://github.com/gigster-eng/PlivoWebSDK#readme", - "dependencies": { - "uuid": "^2.0.3", - "debug": "^2.6.3", - "sdp-transform": "^2.3.0", - "webrtc-adapter": "^3.2.0" - }, - "devDependencies": { - "browserify": "^9.0.3", - "cheerio": "^0.18.0", - "del": "^2.0.2", - "disc": "^1.3.2", - "eslint": "^2.12.0", - "gulp": "^3.9.0", - "gulp-copy": "0.0.2", - "gulp-express": "^0.3.5", - "gulp-insert": "^0.5.0", - "gulp-istanbul": "^0.10.3", - "gulp-newer": "^1.0.0", - "gulp-rename": "^1.2.2", - "gulp-replace": "^0.5.4", - "gulp-uglify": "^1.4.2", - "gulp-util": "^3.0.7", - "jsdoc": "https://github.com/jsdoc3/jsdoc.git#e2fd9e75de9617aadfc3120331f020b2d66cff86", - "jshint": "^2.6.3", - "jshint-stylish": "^1.0.0", - "mkdirp": "^0.5.1", - "opener": "^1.4.2", - "promptly": "^0.2.0", - "release-tool": "^0.2.2", - "run-sequence": "^1.2.2", - "sinon": "^1.15.3", - "stream-from-promise": "^0.1.0", - "through2": "^2.0.0", - "vinyl-source-stream": "^1.1.0", - "gulp-footer" : "^1.0.5" - } -} - -},{}],35:[function(require,module,exports){ -var pkg = require('../package.json'); - -var C = { - USER_AGENT: pkg.title + ' ' + pkg.version, - - // SIP scheme - SIP: 'sip', - SIPS: 'sips', - - // End and Failure causes - causes: { - // Generic error causes - CONNECTION_ERROR: 'Connection Error', - REQUEST_TIMEOUT: 'Request Timeout', - SIP_FAILURE_CODE: 'SIP Failure Code', - INTERNAL_ERROR: 'Internal Error', - - // SIP error causes - BUSY: 'Busy', - REJECTED: 'Rejected', - REDIRECTED: 'Redirected', - UNAVAILABLE: 'Unavailable', - NOT_FOUND: 'Not Found', - ADDRESS_INCOMPLETE: 'Address Incomplete', - INCOMPATIBLE_SDP: 'Incompatible SDP', - MISSING_SDP: 'Missing SDP', - AUTHENTICATION_ERROR: 'Authentication Error', - - // Session error causes - BYE: 'Terminated', - WEBRTC_ERROR: 'WebRTC Error', - CANCELED: 'Canceled', - NO_ANSWER: 'No Answer', - EXPIRES: 'Expires', - NO_ACK: 'No ACK', - DIALOG_ERROR: 'Dialog Error', - USER_DENIED_MEDIA_ACCESS: 'User Denied Media Access', - BAD_MEDIA_DESCRIPTION: 'Bad Media Description', - RTP_TIMEOUT: 'RTP Timeout' - }, - - SIP_ERROR_CAUSES: { - REDIRECTED: [300,301,302,305,380], - BUSY: [486,600], - REJECTED: [403,603], - NOT_FOUND: [404,604], - UNAVAILABLE: [480,410,408,430], - ADDRESS_INCOMPLETE: [484, 424], - INCOMPATIBLE_SDP: [488,606], - AUTHENTICATION_ERROR:[401,407] - }, - - // SIP Methods - ACK: 'ACK', - BYE: 'BYE', - CANCEL: 'CANCEL', - INFO: 'INFO', - INVITE: 'INVITE', - MESSAGE: 'MESSAGE', - NOTIFY: 'NOTIFY', - OPTIONS: 'OPTIONS', - REGISTER: 'REGISTER', - REFER: 'REFER', - UPDATE: 'UPDATE', - SUBSCRIBE: 'SUBSCRIBE', - - /* SIP Response Reasons - * DOC: http://www.iana.org/assignments/sip-parameters - * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 - */ - REASON_PHRASE: { - 100: 'Trying', - 180: 'Ringing', - 181: 'Call Is Being Forwarded', - 182: 'Queued', - 183: 'Session Progress', - 199: 'Early Dialog Terminated', // draft-ietf-sipcore-199 - 200: 'OK', - 202: 'Accepted', // RFC 3265 - 204: 'No Notification', //RFC 5839 - 300: 'Multiple Choices', - 301: 'Moved Permanently', - 302: 'Moved Temporarily', - 305: 'Use Proxy', - 380: 'Alternative Service', - 400: 'Bad Request', - 401: 'Unauthorized', - 402: 'Payment Required', - 403: 'Forbidden', - 404: 'Not Found', - 405: 'Method Not Allowed', - 406: 'Not Acceptable', - 407: 'Proxy Authentication Required', - 408: 'Request Timeout', - 410: 'Gone', - 412: 'Conditional Request Failed', // RFC 3903 - 413: 'Request Entity Too Large', - 414: 'Request-URI Too Long', - 415: 'Unsupported Media Type', - 416: 'Unsupported URI Scheme', - 417: 'Unknown Resource-Priority', // RFC 4412 - 420: 'Bad Extension', - 421: 'Extension Required', - 422: 'Session Interval Too Small', // RFC 4028 - 423: 'Interval Too Brief', - 424: 'Bad Location Information', // RFC 6442 - 428: 'Use Identity Header', // RFC 4474 - 429: 'Provide Referrer Identity', // RFC 3892 - 430: 'Flow Failed', // RFC 5626 - 433: 'Anonymity Disallowed', // RFC 5079 - 436: 'Bad Identity-Info', // RFC 4474 - 437: 'Unsupported Certificate', // RFC 4744 - 438: 'Invalid Identity Header', // RFC 4744 - 439: 'First Hop Lacks Outbound Support', // RFC 5626 - 440: 'Max-Breadth Exceeded', // RFC 5393 - 469: 'Bad Info Package', // draft-ietf-sipcore-info-events - 470: 'Consent Needed', // RFC 5360 - 478: 'Unresolvable Destination', // Custom code copied from Kamailio. - 480: 'Temporarily Unavailable', - 481: 'Call/Transaction Does Not Exist', - 482: 'Loop Detected', - 483: 'Too Many Hops', - 484: 'Address Incomplete', - 485: 'Ambiguous', - 486: 'Busy Here', - 487: 'Request Terminated', - 488: 'Not Acceptable Here', - 489: 'Bad Event', // RFC 3265 - 491: 'Request Pending', - 493: 'Undecipherable', - 494: 'Security Agreement Required', // RFC 3329 - 500: 'JsSIP Internal Error', - 501: 'Not Implemented', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - 504: 'Server Time-out', - 505: 'Version Not Supported', - 513: 'Message Too Large', - 580: 'Precondition Failure', // RFC 3312 - 600: 'Busy Everywhere', - 603: 'Decline', - 604: 'Does Not Exist Anywhere', - 606: 'Not Acceptable' - }, - - ALLOWED_METHODS: 'INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO', - ACCEPTED_BODY_TYPES: 'application/sdp, application/dtmf-relay', - MAX_FORWARDS: 69, - SESSION_EXPIRES: 90, - MIN_SESSION_EXPIRES: 60 -}; - - -module.exports = C; - -},{"../package.json":34}],36:[function(require,module,exports){ -module.exports = Dialog; - - -var C = { - // Dialog states - STATUS_EARLY: 1, - STATUS_CONFIRMED: 2 -}; - -/** - * Expose C object. - */ -Dialog.C = C; - - -/** - * Dependencies. - */ -var debug = require('debug')('PlivoSIP:Dialog'); -var SIPMessage = require('./SIPMessage'); -var JsSIP_C = require('./Constants'); -var Transactions = require('./Transactions'); -var Dialog_RequestSender = require('./Dialog/RequestSender'); - - -// RFC 3261 12.1 -function Dialog(owner, message, type, state) { - var contact; - - this.uac_pending_reply = false; - this.uas_pending_reply = false; - - if(!message.hasHeader('contact')) { - return { - error: 'unable to create a Dialog without Contact header field' - }; - } - - if(message instanceof SIPMessage.IncomingResponse) { - state = (message.status_code < 200) ? C.STATUS_EARLY : C.STATUS_CONFIRMED; - } else { - // Create confirmed dialog if state is not defined - state = state || C.STATUS_CONFIRMED; - } - - contact = message.parseHeader('contact'); - - // RFC 3261 12.1.1 - if(type === 'UAS') { - this.id = { - call_id: message.call_id, - local_tag: message.to_tag, - remote_tag: message.from_tag, - toString: function() { - return this.call_id + this.local_tag + this.remote_tag; - } - }; - this.state = state; - this.remote_seqnum = message.cseq; - this.local_uri = message.parseHeader('to').uri; - this.remote_uri = message.parseHeader('from').uri; - this.remote_target = contact.uri; - this.route_set = message.getHeaders('record-route'); - } - // RFC 3261 12.1.2 - else if(type === 'UAC') { - this.id = { - call_id: message.call_id, - local_tag: message.from_tag, - remote_tag: message.to_tag, - toString: function() { - return this.call_id + this.local_tag + this.remote_tag; - } - }; - this.state = state; - this.local_seqnum = message.cseq; - this.local_uri = message.parseHeader('from').uri; - this.remote_uri = message.parseHeader('to').uri; - this.remote_target = contact.uri; - this.route_set = message.getHeaders('record-route').reverse(); - } - - this.owner = owner; - owner.ua.dialogs[this.id.toString()] = this; - debug('new ' + type + ' dialog created with status ' + (this.state === C.STATUS_EARLY ? 'EARLY': 'CONFIRMED')); -} - - -Dialog.prototype = { - update: function(message, type) { - this.state = C.STATUS_CONFIRMED; - - debug('dialog '+ this.id.toString() +' changed to CONFIRMED state'); - - if(type === 'UAC') { - // RFC 3261 13.2.2.4 - this.route_set = message.getHeaders('record-route').reverse(); - } - }, - - terminate: function() { - debug('dialog ' + this.id.toString() + ' deleted'); - delete this.owner.ua.dialogs[this.id.toString()]; - }, - - // RFC 3261 12.2.1.1 - createRequest: function(method, extraHeaders, body) { - var cseq, request; - extraHeaders = extraHeaders && extraHeaders.slice() || []; - - if(!this.local_seqnum) { this.local_seqnum = Math.floor(Math.random() * 10000); } - - cseq = (method === JsSIP_C.CANCEL || method === JsSIP_C.ACK) ? this.local_seqnum : this.local_seqnum += 1; - - request = new SIPMessage.OutgoingRequest( - method, - this.remote_target, - this.owner.ua, { - 'cseq': cseq, - 'call_id': this.id.call_id, - 'from_uri': this.local_uri, - 'from_tag': this.id.local_tag, - 'to_uri': this.remote_uri, - 'to_tag': this.id.remote_tag, - 'route_set': this.route_set - }, extraHeaders, body); - - request.dialog = this; - - return request; - }, - - // RFC 3261 12.2.2 - checkInDialogRequest: function(request) { - var self = this; - - if(!this.remote_seqnum) { - this.remote_seqnum = request.cseq; - } else if(request.cseq < this.remote_seqnum) { - //Do not try to reply to an ACK request. - if (request.method !== JsSIP_C.ACK) { - request.reply(500); - } - return false; - } else if(request.cseq > this.remote_seqnum) { - this.remote_seqnum = request.cseq; - } - - // RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR- - if (request.method === JsSIP_C.INVITE || (request.method === JsSIP_C.UPDATE && request.body)) { - if (this.uac_pending_reply === true) { - request.reply(491); - } else if (this.uas_pending_reply === true) { - var retryAfter = (Math.random() * 10 | 0) + 1; - request.reply(500, null, ['Retry-After:'+ retryAfter]); - return false; - } else { - this.uas_pending_reply = true; - request.server_transaction.on('stateChanged', function stateChanged(){ - if (this.state === Transactions.C.STATUS_ACCEPTED || - this.state === Transactions.C.STATUS_COMPLETED || - this.state === Transactions.C.STATUS_TERMINATED) { - - request.server_transaction.removeListener('stateChanged', stateChanged); - self.uas_pending_reply = false; - } - }); - } - - // RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted - if(request.hasHeader('contact')) { - request.server_transaction.on('stateChanged', function(){ - if (this.state === Transactions.C.STATUS_ACCEPTED) { - self.remote_target = request.parseHeader('contact').uri; - } - }); - } - } - else if (request.method === JsSIP_C.NOTIFY) { - // RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted - if(request.hasHeader('contact')) { - request.server_transaction.on('stateChanged', function(){ - if (this.state === Transactions.C.STATUS_COMPLETED) { - self.remote_target = request.parseHeader('contact').uri; - } - }); - } - } - - return true; - }, - - sendRequest: function(applicant, method, options) { - options = options || {}; - - var - extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], - body = options.body || null, - request = this.createRequest(method, extraHeaders, body), - request_sender = new Dialog_RequestSender(this, applicant, request); - - request_sender.send(); - - // Return the instance of OutgoingRequest - return request; - }, - - receiveRequest: function(request) { - //Check in-dialog request - if(!this.checkInDialogRequest(request)) { - return; - } - - this.owner.receiveRequest(request); - } -}; - -},{"./Constants":35,"./Dialog/RequestSender":37,"./SIPMessage":52,"./Transactions":55,"debug":11}],37:[function(require,module,exports){ -module.exports = DialogRequestSender; - -/** - * Dependencies. - */ -var JsSIP_C = require('../Constants'); -var Transactions = require('../Transactions'); -var RTCSession = require('../RTCSession'); -var RequestSender = require('../RequestSender'); - - -function DialogRequestSender(dialog, applicant, request) { - - this.dialog = dialog; - this.applicant = applicant; - this.request = request; - - // RFC3261 14.1 Modifying an Existing Session. UAC Behavior. - this.reattempt = false; - this.reattemptTimer = null; -} - - -DialogRequestSender.prototype = { - send: function() { - var - self = this, - request_sender = new RequestSender(this, this.dialog.owner.ua); - - request_sender.send(); - - // RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR- - if ((this.request.method === JsSIP_C.INVITE || (this.request.method === JsSIP_C.UPDATE && this.request.body)) && - request_sender.clientTransaction.state !== Transactions.C.STATUS_TERMINATED) { - this.dialog.uac_pending_reply = true; - request_sender.clientTransaction.on('stateChanged', function stateChanged(){ - if (this.state === Transactions.C.STATUS_ACCEPTED || - this.state === Transactions.C.STATUS_COMPLETED || - this.state === Transactions.C.STATUS_TERMINATED) { - - request_sender.clientTransaction.removeListener('stateChanged', stateChanged); - self.dialog.uac_pending_reply = false; - } - }); - } - }, - - onRequestTimeout: function() { - this.applicant.onRequestTimeout(); - }, - - onTransportError: function() { - this.applicant.onTransportError(); - }, - - receiveResponse: function(response) { - var self = this; - - // RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog. - if (response.status_code === 408 || response.status_code === 481) { - this.applicant.onDialogError(response); - } else if (response.method === JsSIP_C.INVITE && response.status_code === 491) { - if (this.reattempt) { - this.applicant.receiveResponse(response); - } else { - this.request.cseq.value = this.dialog.local_seqnum += 1; - this.reattemptTimer = setTimeout(function() { - if (self.applicant.owner.status !== RTCSession.C.STATUS_TERMINATED) { - self.reattempt = true; - self.request_sender.send(); - } - }, 1000); - } - } else { - this.applicant.receiveResponse(response); - } - } -}; - -},{"../Constants":35,"../RTCSession":45,"../RequestSender":51,"../Transactions":55}],38:[function(require,module,exports){ -module.exports = DigestAuthentication; - - -/** - * Dependencies. - */ -var debug = require('debug')('PlivoSIP:DigestAuthentication'); -var debugerror = require('debug')('PlivoSIP:ERROR:DigestAuthentication'); -debugerror.log = console.warn.bind(console); -var Utils = require('./Utils'); - - -function DigestAuthentication(credentials) { - this.credentials = credentials; - this.cnonce = null; - this.nc = 0; - this.ncHex = '00000000'; - this.algorithm = null; - this.realm = null; - this.nonce = null; - this.opaque = null; - this.stale = null; - this.qop = null; - this.method = null; - this.uri = null; - this.ha1 = null; - this.response = null; -} - - -DigestAuthentication.prototype.get = function(parameter) { - switch (parameter) { - case 'realm': - return this.realm; - - case 'ha1': - return this.ha1; - - default: - debugerror('get() | cannot get "%s" parameter', parameter); - return undefined; - } -}; - - -/** -* Performs Digest authentication given a SIP request and the challenge -* received in a response to that request. -* Returns true if auth was successfully generated, false otherwise. -*/ -DigestAuthentication.prototype.authenticate = function(request, challenge) { - var ha2, hex; - - this.algorithm = challenge.algorithm; - this.realm = challenge.realm; - this.nonce = challenge.nonce; - this.opaque = challenge.opaque; - this.stale = challenge.stale; - - if (this.algorithm) { - if (this.algorithm !== 'MD5') { - debugerror('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'); - return false; - } - } else { - this.algorithm = 'MD5'; - } - - if (!this.nonce) { - debugerror('authenticate() | challenge without Digest nonce, authentication aborted'); - return false; - } - - if (!this.realm) { - debugerror('authenticate() | challenge without Digest realm, authentication aborted'); - return false; - } - - // If no plain SIP password is provided. - if (!this.credentials.password) { - // If ha1 is not provided we cannot authenticate. - if (!this.credentials.ha1) { - debugerror('authenticate() | no plain SIP password nor ha1 provided, authentication aborted'); - return false; - } - - // If the realm does not match the stored realm we cannot authenticate. - if (this.credentials.realm !== this.realm) { - debugerror('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]', this.credentials.realm, this.realm); - return false; - } - } - - // 'qop' can contain a list of values (Array). Let's choose just one. - if (challenge.qop) { - if (challenge.qop.indexOf('auth') > -1) { - this.qop = 'auth'; - } else if (challenge.qop.indexOf('auth-int') > -1) { - this.qop = 'auth-int'; - } else { - // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. - debugerror('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'); - return false; - } - } else { - this.qop = null; - } - - // Fill other attributes. - - this.method = request.method; - this.uri = request.ruri; - this.cnonce = Utils.createRandomToken(12); - this.nc += 1; - hex = Number(this.nc).toString(16); - this.ncHex = '00000000'.substr(0, 8-hex.length) + hex; - - // nc-value = 8LHEX. Max value = 'FFFFFFFF'. - if (this.nc === 4294967296) { - this.nc = 1; - this.ncHex = '00000001'; - } - - // Calculate the Digest "response" value. - - // If we have plain SIP password then regenerate ha1. - if (this.credentials.password) { - // HA1 = MD5(A1) = MD5(username:realm:password) - this.ha1 = Utils.calculateMD5(this.credentials.username + ':' + this.realm + ':' + this.credentials.password); - // - // Otherwise reuse the stored ha1. - } else { - this.ha1 = this.credentials.ha1; - } - - if (this.qop === 'auth') { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = Utils.calculateMD5(this.method + ':' + this.uri); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth:' + ha2); - - } else if (this.qop === 'auth-int') { - // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) - ha2 = Utils.calculateMD5(this.method + ':' + this.uri + ':' + Utils.calculateMD5(this.body ? this.body : '')); - // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) - this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth-int:' + ha2); - - } else if (this.qop === null) { - // HA2 = MD5(A2) = MD5(method:digestURI) - ha2 = Utils.calculateMD5(this.method + ':' + this.uri); - // response = MD5(HA1:nonce:HA2) - this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + ha2); - } - - debug('authenticate() | response generated'); - - return true; -}; - - -/** -* Return the Proxy-Authorization or WWW-Authorization header value. -*/ -DigestAuthentication.prototype.toString = function() { - var auth_params = []; - - if (!this.response) { - throw new Error('response field does not exist, cannot generate Authorization header'); - } - - auth_params.push('algorithm=' + this.algorithm); - auth_params.push('username="' + this.credentials.username + '"'); - auth_params.push('realm="' + this.realm + '"'); - auth_params.push('nonce="' + this.nonce + '"'); - auth_params.push('uri="' + this.uri + '"'); - auth_params.push('response="' + this.response + '"'); - if (this.opaque) { - auth_params.push('opaque="' + this.opaque + '"'); - } - if (this.qop) { - auth_params.push('qop=' + this.qop); - auth_params.push('cnonce="' + this.cnonce + '"'); - auth_params.push('nc=' + this.ncHex); - } - - return 'Digest ' + auth_params.join(', '); -}; - -},{"./Utils":59,"debug":11}],39:[function(require,module,exports){ -/** - * @namespace Exceptions - * @memberOf JsSIP - */ -var Exceptions = { - /** - * Exception thrown when a valid parameter is given to the JsSIP.UA constructor. - * @class ConfigurationError - * @memberOf JsSIP.Exceptions - */ - ConfigurationError: (function(){ - var exception = function(parameter, value) { - this.code = 1; - this.name = 'CONFIGURATION_ERROR'; - this.parameter = parameter; - this.value = value; - this.message = (!this.value)? 'Missing parameter: '+ this.parameter : 'Invalid value '+ JSON.stringify(this.value) +' for parameter "'+ this.parameter +'"'; - }; - exception.prototype = new Error(); - return exception; - }()), - - InvalidStateError: (function(){ - var exception = function(status) { - this.code = 2; - this.name = 'INVALID_STATE_ERROR'; - this.status = status; - this.message = 'Invalid status: '+ status; - }; - exception.prototype = new Error(); - return exception; - }()), - - NotSupportedError: (function(){ - var exception = function(message) { - this.code = 3; - this.name = 'NOT_SUPPORTED_ERROR'; - this.message = message; - }; - exception.prototype = new Error(); - return exception; - }()), - - NotReadyError: (function(){ - var exception = function(message) { - this.code = 4; - this.name = 'NOT_READY_ERROR'; - this.message = message; - }; - exception.prototype = new Error(); - return exception; - }()) -}; - - -module.exports = Exceptions; - -},{}],40:[function(require,module,exports){ -module.exports = (function(){ - /* - * Generated by PEG.js 0.7.0. - * - * http://pegjs.majda.cz/ - */ - function quote(s) { - /* - * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a - * string literal except for the closing quote character, backslash, - * carriage return, line separator, paragraph separator, and line feed. - * Any character may appear in the form of an escape sequence. - * - * For portability, we also escape escape all control and non-ASCII - * characters. Note that "\0" and "\v" escape sequences are not used - * because JSHint does not like the first and IE the second. - */ - return '"' + s - .replace(/\\/g, '\\\\') // backslash - .replace(/"/g, '\\"') // closing quote character - .replace(/\x08/g, '\\b') // backspace - .replace(/\t/g, '\\t') // horizontal tab - .replace(/\n/g, '\\n') // line feed - .replace(/\f/g, '\\f') // form feed - .replace(/\r/g, '\\r') // carriage return - .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape) - + '"'; - } - var result = { - /* - * Parses the input with a generated parser. If the parsing is successfull, - * returns a value explicitly or implicitly specified by the grammar from - * which the parser was generated (see |PEG.buildParser|). If the parsing is - * unsuccessful, throws |PEG.parser.SyntaxError| describing the error. - */ - parse: function(input, startRule) { - var parseFunctions = { - "CRLF": parse_CRLF, - "DIGIT": parse_DIGIT, - "ALPHA": parse_ALPHA, - "HEXDIG": parse_HEXDIG, - "WSP": parse_WSP, - "OCTET": parse_OCTET, - "DQUOTE": parse_DQUOTE, - "SP": parse_SP, - "HTAB": parse_HTAB, - "alphanum": parse_alphanum, - "reserved": parse_reserved, - "unreserved": parse_unreserved, - "mark": parse_mark, - "escaped": parse_escaped, - "LWS": parse_LWS, - "SWS": parse_SWS, - "HCOLON": parse_HCOLON, - "TEXT_UTF8_TRIM": parse_TEXT_UTF8_TRIM, - "TEXT_UTF8char": parse_TEXT_UTF8char, - "UTF8_NONASCII": parse_UTF8_NONASCII, - "UTF8_CONT": parse_UTF8_CONT, - "LHEX": parse_LHEX, - "token": parse_token, - "token_nodot": parse_token_nodot, - "separators": parse_separators, - "word": parse_word, - "STAR": parse_STAR, - "SLASH": parse_SLASH, - "EQUAL": parse_EQUAL, - "LPAREN": parse_LPAREN, - "RPAREN": parse_RPAREN, - "RAQUOT": parse_RAQUOT, - "LAQUOT": parse_LAQUOT, - "COMMA": parse_COMMA, - "SEMI": parse_SEMI, - "COLON": parse_COLON, - "LDQUOT": parse_LDQUOT, - "RDQUOT": parse_RDQUOT, - "comment": parse_comment, - "ctext": parse_ctext, - "quoted_string": parse_quoted_string, - "quoted_string_clean": parse_quoted_string_clean, - "qdtext": parse_qdtext, - "quoted_pair": parse_quoted_pair, - "SIP_URI_noparams": parse_SIP_URI_noparams, - "SIP_URI": parse_SIP_URI, - "uri_scheme": parse_uri_scheme, - "uri_scheme_sips": parse_uri_scheme_sips, - "uri_scheme_sip": parse_uri_scheme_sip, - "userinfo": parse_userinfo, - "user": parse_user, - "user_unreserved": parse_user_unreserved, - "password": parse_password, - "hostport": parse_hostport, - "host": parse_host, - "hostname": parse_hostname, - "domainlabel": parse_domainlabel, - "toplabel": parse_toplabel, - "IPv6reference": parse_IPv6reference, - "IPv6address": parse_IPv6address, - "h16": parse_h16, - "ls32": parse_ls32, - "IPv4address": parse_IPv4address, - "dec_octet": parse_dec_octet, - "port": parse_port, - "uri_parameters": parse_uri_parameters, - "uri_parameter": parse_uri_parameter, - "transport_param": parse_transport_param, - "user_param": parse_user_param, - "method_param": parse_method_param, - "ttl_param": parse_ttl_param, - "maddr_param": parse_maddr_param, - "lr_param": parse_lr_param, - "other_param": parse_other_param, - "pname": parse_pname, - "pvalue": parse_pvalue, - "paramchar": parse_paramchar, - "param_unreserved": parse_param_unreserved, - "headers": parse_headers, - "header": parse_header, - "hname": parse_hname, - "hvalue": parse_hvalue, - "hnv_unreserved": parse_hnv_unreserved, - "Request_Response": parse_Request_Response, - "Request_Line": parse_Request_Line, - "Request_URI": parse_Request_URI, - "absoluteURI": parse_absoluteURI, - "hier_part": parse_hier_part, - "net_path": parse_net_path, - "abs_path": parse_abs_path, - "opaque_part": parse_opaque_part, - "uric": parse_uric, - "uric_no_slash": parse_uric_no_slash, - "path_segments": parse_path_segments, - "segment": parse_segment, - "param": parse_param, - "pchar": parse_pchar, - "scheme": parse_scheme, - "authority": parse_authority, - "srvr": parse_srvr, - "reg_name": parse_reg_name, - "query": parse_query, - "SIP_Version": parse_SIP_Version, - "INVITEm": parse_INVITEm, - "ACKm": parse_ACKm, - "OPTIONSm": parse_OPTIONSm, - "BYEm": parse_BYEm, - "CANCELm": parse_CANCELm, - "REGISTERm": parse_REGISTERm, - "SUBSCRIBEm": parse_SUBSCRIBEm, - "NOTIFYm": parse_NOTIFYm, - "REFERm": parse_REFERm, - "Method": parse_Method, - "Status_Line": parse_Status_Line, - "Status_Code": parse_Status_Code, - "extension_code": parse_extension_code, - "Reason_Phrase": parse_Reason_Phrase, - "Allow_Events": parse_Allow_Events, - "Call_ID": parse_Call_ID, - "Contact": parse_Contact, - "contact_param": parse_contact_param, - "name_addr": parse_name_addr, - "display_name": parse_display_name, - "contact_params": parse_contact_params, - "c_p_q": parse_c_p_q, - "c_p_expires": parse_c_p_expires, - "delta_seconds": parse_delta_seconds, - "qvalue": parse_qvalue, - "generic_param": parse_generic_param, - "gen_value": parse_gen_value, - "Content_Disposition": parse_Content_Disposition, - "disp_type": parse_disp_type, - "disp_param": parse_disp_param, - "handling_param": parse_handling_param, - "Content_Encoding": parse_Content_Encoding, - "Content_Length": parse_Content_Length, - "Content_Type": parse_Content_Type, - "media_type": parse_media_type, - "m_type": parse_m_type, - "discrete_type": parse_discrete_type, - "composite_type": parse_composite_type, - "extension_token": parse_extension_token, - "x_token": parse_x_token, - "m_subtype": parse_m_subtype, - "m_parameter": parse_m_parameter, - "m_value": parse_m_value, - "CSeq": parse_CSeq, - "CSeq_value": parse_CSeq_value, - "Expires": parse_Expires, - "Event": parse_Event, - "event_type": parse_event_type, - "From": parse_From, - "from_param": parse_from_param, - "tag_param": parse_tag_param, - "Max_Forwards": parse_Max_Forwards, - "Min_Expires": parse_Min_Expires, - "Name_Addr_Header": parse_Name_Addr_Header, - "Proxy_Authenticate": parse_Proxy_Authenticate, - "challenge": parse_challenge, - "other_challenge": parse_other_challenge, - "auth_param": parse_auth_param, - "digest_cln": parse_digest_cln, - "realm": parse_realm, - "realm_value": parse_realm_value, - "domain": parse_domain, - "URI": parse_URI, - "nonce": parse_nonce, - "nonce_value": parse_nonce_value, - "opaque": parse_opaque, - "stale": parse_stale, - "algorithm": parse_algorithm, - "qop_options": parse_qop_options, - "qop_value": parse_qop_value, - "Proxy_Require": parse_Proxy_Require, - "Record_Route": parse_Record_Route, - "rec_route": parse_rec_route, - "Reason": parse_Reason, - "reason_param": parse_reason_param, - "reason_cause": parse_reason_cause, - "Require": parse_Require, - "Route": parse_Route, - "route_param": parse_route_param, - "Subscription_State": parse_Subscription_State, - "substate_value": parse_substate_value, - "subexp_params": parse_subexp_params, - "event_reason_value": parse_event_reason_value, - "Subject": parse_Subject, - "Supported": parse_Supported, - "To": parse_To, - "to_param": parse_to_param, - "Via": parse_Via, - "via_param": parse_via_param, - "via_params": parse_via_params, - "via_ttl": parse_via_ttl, - "via_maddr": parse_via_maddr, - "via_received": parse_via_received, - "via_branch": parse_via_branch, - "response_port": parse_response_port, - "sent_protocol": parse_sent_protocol, - "protocol_name": parse_protocol_name, - "transport": parse_transport, - "sent_by": parse_sent_by, - "via_host": parse_via_host, - "via_port": parse_via_port, - "ttl": parse_ttl, - "WWW_Authenticate": parse_WWW_Authenticate, - "Session_Expires": parse_Session_Expires, - "s_e_expires": parse_s_e_expires, - "s_e_params": parse_s_e_params, - "s_e_refresher": parse_s_e_refresher, - "extension_header": parse_extension_header, - "header_value": parse_header_value, - "message_body": parse_message_body, - "uuid_URI": parse_uuid_URI, - "uuid": parse_uuid, - "hex4": parse_hex4, - "hex8": parse_hex8, - "hex12": parse_hex12, - "Refer_To": parse_Refer_To, - "Replaces": parse_Replaces, - "call_id": parse_call_id, - "replaces_param": parse_replaces_param, - "to_tag": parse_to_tag, - "from_tag": parse_from_tag, - "early_flag": parse_early_flag - }; - if (startRule !== undefined) { - if (parseFunctions[startRule] === undefined) { - throw new Error("Invalid rule name: " + quote(startRule) + "."); - } - } else { - startRule = "CRLF"; - } - var pos = 0; - var reportFailures = 0; - var rightmostFailuresPos = 0; - var rightmostFailuresExpected = []; - function padLeft(input, padding, length) { - var result = input; - var padLength = length - input.length; - for (var i = 0; i < padLength; i++) { - result = padding + result; - } - return result; - } - function escape(ch) { - var charCode = ch.charCodeAt(0); - var escapeChar; - var length; - if (charCode <= 0xFF) { - escapeChar = 'x'; - length = 2; - } else { - escapeChar = 'u'; - length = 4; - } - return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length); - } - function matchFailed(failure) { - if (pos < rightmostFailuresPos) { - return; - } - if (pos > rightmostFailuresPos) { - rightmostFailuresPos = pos; - rightmostFailuresExpected = []; - } - rightmostFailuresExpected.push(failure); - } - function parse_CRLF() { - var result0; - if (input.substr(pos, 2) === "\r\n") { - result0 = "\r\n"; - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"\\r\\n\""); - } - } - return result0; - } - function parse_DIGIT() { - var result0; - if (/^[0-9]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[0-9]"); - } - } - return result0; - } - function parse_ALPHA() { - var result0; - if (/^[a-zA-Z]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[a-zA-Z]"); - } - } - return result0; - } - function parse_HEXDIG() { - var result0; - if (/^[0-9a-fA-F]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[0-9a-fA-F]"); - } - } - return result0; - } - function parse_WSP() { - var result0; - result0 = parse_SP(); - if (result0 === null) { - result0 = parse_HTAB(); - } - return result0; - } - function parse_OCTET() { - var result0; - if (/^[\0-\xFF]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[\\0-\\xFF]"); - } - } - return result0; - } - function parse_DQUOTE() { - var result0; - if (/^["]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[\"]"); - } - } - return result0; - } - function parse_SP() { - var result0; - if (input.charCodeAt(pos) === 32) { - result0 = " "; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\" \""); - } - } - return result0; - } - function parse_HTAB() { - var result0; - if (input.charCodeAt(pos) === 9) { - result0 = "\t"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"\\t\""); - } - } - return result0; - } - function parse_alphanum() { - var result0; - if (/^[a-zA-Z0-9]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[a-zA-Z0-9]"); - } - } - return result0; - } - function parse_reserved() { - var result0; - if (input.charCodeAt(pos) === 59) { - result0 = ";"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 47) { - result0 = "/"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 63) { - result0 = "?"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"?\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 58) { - result0 = ":"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 64) { - result0 = "@"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"@\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 38) { - result0 = "&"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 61) { - result0 = "="; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 43) { - result0 = "+"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 36) { - result0 = "$"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"$\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 44) { - result0 = ","; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - } - } - } - } - } - } - } - } - } - return result0; - } - function parse_unreserved() { - var result0; - result0 = parse_alphanum(); - if (result0 === null) { - result0 = parse_mark(); - } - return result0; - } - function parse_mark() { - var result0; - if (input.charCodeAt(pos) === 45) { - result0 = "-"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 95) { - result0 = "_"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 46) { - result0 = "."; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 33) { - result0 = "!"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"!\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 126) { - result0 = "~"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"~\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 42) { - result0 = "*"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"*\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 39) { - result0 = "'"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"'\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 40) { - result0 = "("; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"(\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 41) { - result0 = ")"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\")\""); - } - } - } - } - } - } - } - } - } - } - return result0; - } - function parse_escaped() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 37) { - result0 = "%"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"%\""); - } - } - if (result0 !== null) { - result1 = parse_HEXDIG(); - if (result1 !== null) { - result2 = parse_HEXDIG(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, escaped) {return escaped.join(''); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_LWS() { - var result0, result1, result2; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - pos2 = pos; - result0 = []; - result1 = parse_WSP(); - while (result1 !== null) { - result0.push(result1); - result1 = parse_WSP(); - } - if (result0 !== null) { - result1 = parse_CRLF(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos2; - } - } else { - result0 = null; - pos = pos2; - } - result0 = result0 !== null ? result0 : ""; - if (result0 !== null) { - result2 = parse_WSP(); - if (result2 !== null) { - result1 = []; - while (result2 !== null) { - result1.push(result2); - result2 = parse_WSP(); - } - } else { - result1 = null; - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return " "; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_SWS() { - var result0; - result0 = parse_LWS(); - result0 = result0 !== null ? result0 : ""; - return result0; - } - function parse_HCOLON() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = []; - result1 = parse_SP(); - if (result1 === null) { - result1 = parse_HTAB(); - } - while (result1 !== null) { - result0.push(result1); - result1 = parse_SP(); - if (result1 === null) { - result1 = parse_HTAB(); - } - } - if (result0 !== null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_SWS(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return ':'; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_TEXT_UTF8_TRIM() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result1 = parse_TEXT_UTF8char(); - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_TEXT_UTF8char(); - } - } else { - result0 = null; - } - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = []; - result3 = parse_LWS(); - while (result3 !== null) { - result2.push(result3); - result3 = parse_LWS(); - } - if (result2 !== null) { - result3 = parse_TEXT_UTF8char(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = []; - result3 = parse_LWS(); - while (result3 !== null) { - result2.push(result3); - result3 = parse_LWS(); - } - if (result2 !== null) { - result3 = parse_TEXT_UTF8char(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - return input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_TEXT_UTF8char() { - var result0; - if (/^[!-~]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[!-~]"); - } - } - if (result0 === null) { - result0 = parse_UTF8_NONASCII(); - } - return result0; - } - function parse_UTF8_NONASCII() { - var result0; - if (/^[\x80-\uFFFF]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[\\x80-\\uFFFF]"); - } - } - return result0; - } - function parse_UTF8_CONT() { - var result0; - if (/^[\x80-\xBF]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[\\x80-\\xBF]"); - } - } - return result0; - } - function parse_LHEX() { - var result0; - result0 = parse_DIGIT(); - if (result0 === null) { - if (/^[a-f]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[a-f]"); - } - } - } - return result0; - } - function parse_token() { - var result0, result1; - var pos0; - pos0 = pos; - result1 = parse_alphanum(); - if (result1 === null) { - if (input.charCodeAt(pos) === 45) { - result1 = "-"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 46) { - result1 = "."; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 33) { - result1 = "!"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"!\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 37) { - result1 = "%"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"%\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 42) { - result1 = "*"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"*\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 95) { - result1 = "_"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 96) { - result1 = "`"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"`\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 39) { - result1 = "'"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"'\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 126) { - result1 = "~"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"~\""); - } - } - } - } - } - } - } - } - } - } - } - } - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_alphanum(); - if (result1 === null) { - if (input.charCodeAt(pos) === 45) { - result1 = "-"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 46) { - result1 = "."; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 33) { - result1 = "!"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"!\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 37) { - result1 = "%"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"%\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 42) { - result1 = "*"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"*\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 95) { - result1 = "_"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 96) { - result1 = "`"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"`\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 39) { - result1 = "'"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"'\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 126) { - result1 = "~"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"~\""); - } - } - } - } - } - } - } - } - } - } - } - } - } - } else { - result0 = null; - } - if (result0 !== null) { - result0 = (function(offset) { - return input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_token_nodot() { - var result0, result1; - var pos0; - pos0 = pos; - result1 = parse_alphanum(); - if (result1 === null) { - if (input.charCodeAt(pos) === 45) { - result1 = "-"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 33) { - result1 = "!"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"!\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 37) { - result1 = "%"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"%\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 42) { - result1 = "*"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"*\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 95) { - result1 = "_"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 96) { - result1 = "`"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"`\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 39) { - result1 = "'"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"'\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 126) { - result1 = "~"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"~\""); - } - } - } - } - } - } - } - } - } - } - } - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_alphanum(); - if (result1 === null) { - if (input.charCodeAt(pos) === 45) { - result1 = "-"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 33) { - result1 = "!"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"!\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 37) { - result1 = "%"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"%\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 42) { - result1 = "*"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"*\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 95) { - result1 = "_"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 96) { - result1 = "`"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"`\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 39) { - result1 = "'"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"'\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 126) { - result1 = "~"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"~\""); - } - } - } - } - } - } - } - } - } - } - } - } - } else { - result0 = null; - } - if (result0 !== null) { - result0 = (function(offset) { - return input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_separators() { - var result0; - if (input.charCodeAt(pos) === 40) { - result0 = "("; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"(\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 41) { - result0 = ")"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\")\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 60) { - result0 = "<"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"<\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 62) { - result0 = ">"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\">\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 64) { - result0 = "@"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"@\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 44) { - result0 = ","; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 59) { - result0 = ";"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 58) { - result0 = ":"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 92) { - result0 = "\\"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"\\\\\""); - } - } - if (result0 === null) { - result0 = parse_DQUOTE(); - if (result0 === null) { - if (input.charCodeAt(pos) === 47) { - result0 = "/"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 91) { - result0 = "["; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"[\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 93) { - result0 = "]"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"]\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 63) { - result0 = "?"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"?\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 61) { - result0 = "="; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 123) { - result0 = "{"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"{\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 125) { - result0 = "}"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"}\""); - } - } - if (result0 === null) { - result0 = parse_SP(); - if (result0 === null) { - result0 = parse_HTAB(); - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - return result0; - } - function parse_word() { - var result0, result1; - var pos0; - pos0 = pos; - result1 = parse_alphanum(); - if (result1 === null) { - if (input.charCodeAt(pos) === 45) { - result1 = "-"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 46) { - result1 = "."; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 33) { - result1 = "!"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"!\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 37) { - result1 = "%"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"%\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 42) { - result1 = "*"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"*\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 95) { - result1 = "_"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 96) { - result1 = "`"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"`\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 39) { - result1 = "'"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"'\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 126) { - result1 = "~"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"~\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 40) { - result1 = "("; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"(\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 41) { - result1 = ")"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\")\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 60) { - result1 = "<"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"<\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 62) { - result1 = ">"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\">\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 92) { - result1 = "\\"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"\\\\\""); - } - } - if (result1 === null) { - result1 = parse_DQUOTE(); - if (result1 === null) { - if (input.charCodeAt(pos) === 47) { - result1 = "/"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 91) { - result1 = "["; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"[\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 93) { - result1 = "]"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"]\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 63) { - result1 = "?"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"?\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 123) { - result1 = "{"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"{\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 125) { - result1 = "}"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"}\""); - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_alphanum(); - if (result1 === null) { - if (input.charCodeAt(pos) === 45) { - result1 = "-"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 46) { - result1 = "."; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 33) { - result1 = "!"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"!\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 37) { - result1 = "%"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"%\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 42) { - result1 = "*"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"*\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 95) { - result1 = "_"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 96) { - result1 = "`"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"`\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 39) { - result1 = "'"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"'\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 126) { - result1 = "~"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"~\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 40) { - result1 = "("; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"(\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 41) { - result1 = ")"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\")\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 60) { - result1 = "<"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"<\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 62) { - result1 = ">"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\">\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 92) { - result1 = "\\"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"\\\\\""); - } - } - if (result1 === null) { - result1 = parse_DQUOTE(); - if (result1 === null) { - if (input.charCodeAt(pos) === 47) { - result1 = "/"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 91) { - result1 = "["; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"[\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 93) { - result1 = "]"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"]\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 63) { - result1 = "?"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"?\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 123) { - result1 = "{"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"{\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 125) { - result1 = "}"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"}\""); - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } else { - result0 = null; - } - if (result0 !== null) { - result0 = (function(offset) { - return input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_STAR() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 42) { - result1 = "*"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"*\""); - } - } - if (result1 !== null) { - result2 = parse_SWS(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return "*"; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_SLASH() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 47) { - result1 = "/"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result1 !== null) { - result2 = parse_SWS(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return "/"; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_EQUAL() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 61) { - result1 = "="; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result1 !== null) { - result2 = parse_SWS(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return "="; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_LPAREN() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 40) { - result1 = "("; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"(\""); - } - } - if (result1 !== null) { - result2 = parse_SWS(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return "("; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_RPAREN() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 41) { - result1 = ")"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\")\""); - } - } - if (result1 !== null) { - result2 = parse_SWS(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return ")"; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_RAQUOT() { - var result0, result1; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 62) { - result0 = ">"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\">\""); - } - } - if (result0 !== null) { - result1 = parse_SWS(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return ">"; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_LAQUOT() { - var result0, result1; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 60) { - result1 = "<"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"<\""); - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return "<"; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_COMMA() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 44) { - result1 = ","; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - if (result1 !== null) { - result2 = parse_SWS(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return ","; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_SEMI() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 59) { - result1 = ";"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result1 !== null) { - result2 = parse_SWS(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return ";"; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_COLON() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_SWS(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return ":"; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_LDQUOT() { - var result0, result1; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - result1 = parse_DQUOTE(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return "\""; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_RDQUOT() { - var result0, result1; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_DQUOTE(); - if (result0 !== null) { - result1 = parse_SWS(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) {return "\""; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_comment() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_LPAREN(); - if (result0 !== null) { - result1 = []; - result2 = parse_ctext(); - if (result2 === null) { - result2 = parse_quoted_pair(); - if (result2 === null) { - result2 = parse_comment(); - } - } - while (result2 !== null) { - result1.push(result2); - result2 = parse_ctext(); - if (result2 === null) { - result2 = parse_quoted_pair(); - if (result2 === null) { - result2 = parse_comment(); - } - } - } - if (result1 !== null) { - result2 = parse_RPAREN(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_ctext() { - var result0; - if (/^[!-']/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[!-']"); - } - } - if (result0 === null) { - if (/^[*-[]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[*-[]"); - } - } - if (result0 === null) { - if (/^[\]-~]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[\\]-~]"); - } - } - if (result0 === null) { - result0 = parse_UTF8_NONASCII(); - if (result0 === null) { - result0 = parse_LWS(); - } - } - } - } - return result0; - } - function parse_quoted_string() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - result1 = parse_DQUOTE(); - if (result1 !== null) { - result2 = []; - result3 = parse_qdtext(); - if (result3 === null) { - result3 = parse_quoted_pair(); - } - while (result3 !== null) { - result2.push(result3); - result3 = parse_qdtext(); - if (result3 === null) { - result3 = parse_quoted_pair(); - } - } - if (result2 !== null) { - result3 = parse_DQUOTE(); - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - return input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_quoted_string_clean() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_SWS(); - if (result0 !== null) { - result1 = parse_DQUOTE(); - if (result1 !== null) { - result2 = []; - result3 = parse_qdtext(); - if (result3 === null) { - result3 = parse_quoted_pair(); - } - while (result3 !== null) { - result2.push(result3); - result3 = parse_qdtext(); - if (result3 === null) { - result3 = parse_quoted_pair(); - } - } - if (result2 !== null) { - result3 = parse_DQUOTE(); - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - return input.substring(pos-1, offset+1); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_qdtext() { - var result0; - result0 = parse_LWS(); - if (result0 === null) { - if (input.charCodeAt(pos) === 33) { - result0 = "!"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"!\""); - } - } - if (result0 === null) { - if (/^[#-[]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[#-[]"); - } - } - if (result0 === null) { - if (/^[\]-~]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[\\]-~]"); - } - } - if (result0 === null) { - result0 = parse_UTF8_NONASCII(); - } - } - } - } - return result0; - } - function parse_quoted_pair() { - var result0, result1; - var pos0; - pos0 = pos; - if (input.charCodeAt(pos) === 92) { - result0 = "\\"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"\\\\\""); - } - } - if (result0 !== null) { - if (/^[\0-\t]/.test(input.charAt(pos))) { - result1 = input.charAt(pos); - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("[\\0-\\t]"); - } - } - if (result1 === null) { - if (/^[\x0B-\f]/.test(input.charAt(pos))) { - result1 = input.charAt(pos); - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("[\\x0B-\\f]"); - } - } - if (result1 === null) { - if (/^[\x0E-]/.test(input.charAt(pos))) { - result1 = input.charAt(pos); - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("[\\x0E-]"); - } - } - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_SIP_URI_noparams() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_uri_scheme(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_userinfo(); - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - result3 = parse_hostport(); - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - try { - data.uri = new URI(data.scheme, data.user, data.host, data.port); - delete data.scheme; - delete data.user; - delete data.host; - delete data.host_type; - delete data.port; - } catch(e) { - data = -1; - }})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_SIP_URI() { - var result0, result1, result2, result3, result4, result5; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_uri_scheme(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_userinfo(); - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - result3 = parse_hostport(); - if (result3 !== null) { - result4 = parse_uri_parameters(); - if (result4 !== null) { - result5 = parse_headers(); - result5 = result5 !== null ? result5 : ""; - if (result5 !== null) { - result0 = [result0, result1, result2, result3, result4, result5]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - var header; - try { - data.uri = new URI(data.scheme, data.user, data.host, data.port, data.uri_params, data.uri_headers); - delete data.scheme; - delete data.user; - delete data.host; - delete data.host_type; - delete data.port; - delete data.uri_params; - if (startRule === 'SIP_URI') { data = data.uri;} - } catch(e) { - data = -1; - }})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_uri_scheme() { - var result0; - result0 = parse_uri_scheme_sips(); - if (result0 === null) { - result0 = parse_uri_scheme_sip(); - } - return result0; - } - function parse_uri_scheme_sips() { - var result0; - var pos0; - pos0 = pos; - if (input.substr(pos, 4).toLowerCase() === "sips") { - result0 = input.substr(pos, 4); - pos += 4; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"sips\""); - } - } - if (result0 !== null) { - result0 = (function(offset, scheme) { - data.scheme = scheme.toLowerCase(); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_uri_scheme_sip() { - var result0; - var pos0; - pos0 = pos; - if (input.substr(pos, 3).toLowerCase() === "sip") { - result0 = input.substr(pos, 3); - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"sip\""); - } - } - if (result0 !== null) { - result0 = (function(offset, scheme) { - data.scheme = scheme.toLowerCase(); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_userinfo() { - var result0, result1, result2; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_user(); - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_password(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - if (input.charCodeAt(pos) === 64) { - result2 = "@"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"@\""); - } - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - data.user = decodeURIComponent(input.substring(pos-1, offset));})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_user() { - var result0, result1; - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - if (result1 === null) { - result1 = parse_user_unreserved(); - } - } - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - if (result1 === null) { - result1 = parse_user_unreserved(); - } - } - } - } else { - result0 = null; - } - return result0; - } - function parse_user_unreserved() { - var result0; - if (input.charCodeAt(pos) === 38) { - result0 = "&"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 61) { - result0 = "="; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 43) { - result0 = "+"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 36) { - result0 = "$"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"$\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 44) { - result0 = ","; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 59) { - result0 = ";"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 63) { - result0 = "?"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"?\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 47) { - result0 = "/"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - } - } - } - } - } - } - } - return result0; - } - function parse_password() { - var result0, result1; - var pos0; - pos0 = pos; - result0 = []; - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - if (result1 === null) { - if (input.charCodeAt(pos) === 38) { - result1 = "&"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 61) { - result1 = "="; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 36) { - result1 = "$"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"$\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 44) { - result1 = ","; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - } - } - } - } - } - } - while (result1 !== null) { - result0.push(result1); - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - if (result1 === null) { - if (input.charCodeAt(pos) === 38) { - result1 = "&"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 61) { - result1 = "="; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 36) { - result1 = "$"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"$\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 44) { - result1 = ","; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - } - } - } - } - } - } - } - if (result0 !== null) { - result0 = (function(offset) { - data.password = input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_hostport() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - result0 = parse_host(); - if (result0 !== null) { - pos1 = pos; - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_port(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos1; - } - } else { - result1 = null; - pos = pos1; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_host() { - var result0; - var pos0; - pos0 = pos; - result0 = parse_hostname(); - if (result0 === null) { - result0 = parse_IPv4address(); - if (result0 === null) { - result0 = parse_IPv6reference(); - } - } - if (result0 !== null) { - result0 = (function(offset) { - data.host = input.substring(pos, offset).toLowerCase(); - return data.host; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_hostname() { - var result0, result1, result2; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = []; - pos2 = pos; - result1 = parse_domainlabel(); - if (result1 !== null) { - if (input.charCodeAt(pos) === 46) { - result2 = "."; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - while (result1 !== null) { - result0.push(result1); - pos2 = pos; - result1 = parse_domainlabel(); - if (result1 !== null) { - if (input.charCodeAt(pos) === 46) { - result2 = "."; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - } - if (result0 !== null) { - result1 = parse_toplabel(); - if (result1 !== null) { - if (input.charCodeAt(pos) === 46) { - result2 = "."; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - data.host_type = 'domain'; - return input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_domainlabel() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_alphanum(); - if (result0 !== null) { - result1 = []; - result2 = parse_alphanum(); - if (result2 === null) { - if (input.charCodeAt(pos) === 45) { - result2 = "-"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result2 === null) { - if (input.charCodeAt(pos) === 95) { - result2 = "_"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - } - } - while (result2 !== null) { - result1.push(result2); - result2 = parse_alphanum(); - if (result2 === null) { - if (input.charCodeAt(pos) === 45) { - result2 = "-"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result2 === null) { - if (input.charCodeAt(pos) === 95) { - result2 = "_"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - } - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_toplabel() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_ALPHA(); - if (result0 !== null) { - result1 = []; - result2 = parse_alphanum(); - if (result2 === null) { - if (input.charCodeAt(pos) === 45) { - result2 = "-"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result2 === null) { - if (input.charCodeAt(pos) === 95) { - result2 = "_"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - } - } - while (result2 !== null) { - result1.push(result2); - result2 = parse_alphanum(); - if (result2 === null) { - if (input.charCodeAt(pos) === 45) { - result2 = "-"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result2 === null) { - if (input.charCodeAt(pos) === 95) { - result2 = "_"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"_\""); - } - } - } - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_IPv6reference() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 91) { - result0 = "["; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"[\""); - } - } - if (result0 !== null) { - result1 = parse_IPv6address(); - if (result1 !== null) { - if (input.charCodeAt(pos) === 93) { - result2 = "]"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"]\""); - } - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - data.host_type = 'IPv6'; - return input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_IPv6address() { - var result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_h16(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_h16(); - if (result2 !== null) { - if (input.charCodeAt(pos) === 58) { - result3 = ":"; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result3 !== null) { - result4 = parse_h16(); - if (result4 !== null) { - if (input.charCodeAt(pos) === 58) { - result5 = ":"; - pos++; - } else { - result5 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result5 !== null) { - result6 = parse_h16(); - if (result6 !== null) { - if (input.charCodeAt(pos) === 58) { - result7 = ":"; - pos++; - } else { - result7 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result7 !== null) { - result8 = parse_h16(); - if (result8 !== null) { - if (input.charCodeAt(pos) === 58) { - result9 = ":"; - pos++; - } else { - result9 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result9 !== null) { - result10 = parse_h16(); - if (result10 !== null) { - if (input.charCodeAt(pos) === 58) { - result11 = ":"; - pos++; - } else { - result11 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result11 !== null) { - result12 = parse_ls32(); - if (result12 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - if (input.substr(pos, 2) === "::") { - result0 = "::"; - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result0 !== null) { - result1 = parse_h16(); - if (result1 !== null) { - if (input.charCodeAt(pos) === 58) { - result2 = ":"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result2 !== null) { - result3 = parse_h16(); - if (result3 !== null) { - if (input.charCodeAt(pos) === 58) { - result4 = ":"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result4 !== null) { - result5 = parse_h16(); - if (result5 !== null) { - if (input.charCodeAt(pos) === 58) { - result6 = ":"; - pos++; - } else { - result6 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result6 !== null) { - result7 = parse_h16(); - if (result7 !== null) { - if (input.charCodeAt(pos) === 58) { - result8 = ":"; - pos++; - } else { - result8 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result8 !== null) { - result9 = parse_h16(); - if (result9 !== null) { - if (input.charCodeAt(pos) === 58) { - result10 = ":"; - pos++; - } else { - result10 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result10 !== null) { - result11 = parse_ls32(); - if (result11 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - if (input.substr(pos, 2) === "::") { - result0 = "::"; - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result0 !== null) { - result1 = parse_h16(); - if (result1 !== null) { - if (input.charCodeAt(pos) === 58) { - result2 = ":"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result2 !== null) { - result3 = parse_h16(); - if (result3 !== null) { - if (input.charCodeAt(pos) === 58) { - result4 = ":"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result4 !== null) { - result5 = parse_h16(); - if (result5 !== null) { - if (input.charCodeAt(pos) === 58) { - result6 = ":"; - pos++; - } else { - result6 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result6 !== null) { - result7 = parse_h16(); - if (result7 !== null) { - if (input.charCodeAt(pos) === 58) { - result8 = ":"; - pos++; - } else { - result8 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result8 !== null) { - result9 = parse_ls32(); - if (result9 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - if (input.substr(pos, 2) === "::") { - result0 = "::"; - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result0 !== null) { - result1 = parse_h16(); - if (result1 !== null) { - if (input.charCodeAt(pos) === 58) { - result2 = ":"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result2 !== null) { - result3 = parse_h16(); - if (result3 !== null) { - if (input.charCodeAt(pos) === 58) { - result4 = ":"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result4 !== null) { - result5 = parse_h16(); - if (result5 !== null) { - if (input.charCodeAt(pos) === 58) { - result6 = ":"; - pos++; - } else { - result6 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result6 !== null) { - result7 = parse_ls32(); - if (result7 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - if (input.substr(pos, 2) === "::") { - result0 = "::"; - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result0 !== null) { - result1 = parse_h16(); - if (result1 !== null) { - if (input.charCodeAt(pos) === 58) { - result2 = ":"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result2 !== null) { - result3 = parse_h16(); - if (result3 !== null) { - if (input.charCodeAt(pos) === 58) { - result4 = ":"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result4 !== null) { - result5 = parse_ls32(); - if (result5 !== null) { - result0 = [result0, result1, result2, result3, result4, result5]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - if (input.substr(pos, 2) === "::") { - result0 = "::"; - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result0 !== null) { - result1 = parse_h16(); - if (result1 !== null) { - if (input.charCodeAt(pos) === 58) { - result2 = ":"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result2 !== null) { - result3 = parse_ls32(); - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - if (input.substr(pos, 2) === "::") { - result0 = "::"; - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result0 !== null) { - result1 = parse_ls32(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - if (input.substr(pos, 2) === "::") { - result0 = "::"; - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result0 !== null) { - result1 = parse_h16(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - result0 = parse_h16(); - if (result0 !== null) { - if (input.substr(pos, 2) === "::") { - result1 = "::"; - pos += 2; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result1 !== null) { - result2 = parse_h16(); - if (result2 !== null) { - if (input.charCodeAt(pos) === 58) { - result3 = ":"; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result3 !== null) { - result4 = parse_h16(); - if (result4 !== null) { - if (input.charCodeAt(pos) === 58) { - result5 = ":"; - pos++; - } else { - result5 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result5 !== null) { - result6 = parse_h16(); - if (result6 !== null) { - if (input.charCodeAt(pos) === 58) { - result7 = ":"; - pos++; - } else { - result7 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result7 !== null) { - result8 = parse_h16(); - if (result8 !== null) { - if (input.charCodeAt(pos) === 58) { - result9 = ":"; - pos++; - } else { - result9 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result9 !== null) { - result10 = parse_ls32(); - if (result10 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - result0 = parse_h16(); - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_h16(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - if (input.substr(pos, 2) === "::") { - result2 = "::"; - pos += 2; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result2 !== null) { - result3 = parse_h16(); - if (result3 !== null) { - if (input.charCodeAt(pos) === 58) { - result4 = ":"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result4 !== null) { - result5 = parse_h16(); - if (result5 !== null) { - if (input.charCodeAt(pos) === 58) { - result6 = ":"; - pos++; - } else { - result6 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result6 !== null) { - result7 = parse_h16(); - if (result7 !== null) { - if (input.charCodeAt(pos) === 58) { - result8 = ":"; - pos++; - } else { - result8 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result8 !== null) { - result9 = parse_ls32(); - if (result9 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - result0 = parse_h16(); - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_h16(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result2 = ":"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result2 !== null) { - result3 = parse_h16(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - if (input.substr(pos, 2) === "::") { - result3 = "::"; - pos += 2; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result3 !== null) { - result4 = parse_h16(); - if (result4 !== null) { - if (input.charCodeAt(pos) === 58) { - result5 = ":"; - pos++; - } else { - result5 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result5 !== null) { - result6 = parse_h16(); - if (result6 !== null) { - if (input.charCodeAt(pos) === 58) { - result7 = ":"; - pos++; - } else { - result7 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result7 !== null) { - result8 = parse_ls32(); - if (result8 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - result0 = parse_h16(); - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_h16(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result2 = ":"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result2 !== null) { - result3 = parse_h16(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result3 = ":"; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result3 !== null) { - result4 = parse_h16(); - if (result4 !== null) { - result3 = [result3, result4]; - } else { - result3 = null; - pos = pos2; - } - } else { - result3 = null; - pos = pos2; - } - result3 = result3 !== null ? result3 : ""; - if (result3 !== null) { - if (input.substr(pos, 2) === "::") { - result4 = "::"; - pos += 2; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result4 !== null) { - result5 = parse_h16(); - if (result5 !== null) { - if (input.charCodeAt(pos) === 58) { - result6 = ":"; - pos++; - } else { - result6 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result6 !== null) { - result7 = parse_ls32(); - if (result7 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - result0 = parse_h16(); - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_h16(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result2 = ":"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result2 !== null) { - result3 = parse_h16(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result3 = ":"; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result3 !== null) { - result4 = parse_h16(); - if (result4 !== null) { - result3 = [result3, result4]; - } else { - result3 = null; - pos = pos2; - } - } else { - result3 = null; - pos = pos2; - } - result3 = result3 !== null ? result3 : ""; - if (result3 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result4 = ":"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result4 !== null) { - result5 = parse_h16(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos2; - } - } else { - result4 = null; - pos = pos2; - } - result4 = result4 !== null ? result4 : ""; - if (result4 !== null) { - if (input.substr(pos, 2) === "::") { - result5 = "::"; - pos += 2; - } else { - result5 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result5 !== null) { - result6 = parse_ls32(); - if (result6 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - result0 = parse_h16(); - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_h16(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result2 = ":"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result2 !== null) { - result3 = parse_h16(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result3 = ":"; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result3 !== null) { - result4 = parse_h16(); - if (result4 !== null) { - result3 = [result3, result4]; - } else { - result3 = null; - pos = pos2; - } - } else { - result3 = null; - pos = pos2; - } - result3 = result3 !== null ? result3 : ""; - if (result3 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result4 = ":"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result4 !== null) { - result5 = parse_h16(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos2; - } - } else { - result4 = null; - pos = pos2; - } - result4 = result4 !== null ? result4 : ""; - if (result4 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result5 = ":"; - pos++; - } else { - result5 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result5 !== null) { - result6 = parse_h16(); - if (result6 !== null) { - result5 = [result5, result6]; - } else { - result5 = null; - pos = pos2; - } - } else { - result5 = null; - pos = pos2; - } - result5 = result5 !== null ? result5 : ""; - if (result5 !== null) { - if (input.substr(pos, 2) === "::") { - result6 = "::"; - pos += 2; - } else { - result6 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result6 !== null) { - result7 = parse_h16(); - if (result7 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - pos1 = pos; - result0 = parse_h16(); - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_h16(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result2 = ":"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result2 !== null) { - result3 = parse_h16(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result3 = ":"; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result3 !== null) { - result4 = parse_h16(); - if (result4 !== null) { - result3 = [result3, result4]; - } else { - result3 = null; - pos = pos2; - } - } else { - result3 = null; - pos = pos2; - } - result3 = result3 !== null ? result3 : ""; - if (result3 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result4 = ":"; - pos++; - } else { - result4 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result4 !== null) { - result5 = parse_h16(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos2; - } - } else { - result4 = null; - pos = pos2; - } - result4 = result4 !== null ? result4 : ""; - if (result4 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result5 = ":"; - pos++; - } else { - result5 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result5 !== null) { - result6 = parse_h16(); - if (result6 !== null) { - result5 = [result5, result6]; - } else { - result5 = null; - pos = pos2; - } - } else { - result5 = null; - pos = pos2; - } - result5 = result5 !== null ? result5 : ""; - if (result5 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 58) { - result6 = ":"; - pos++; - } else { - result6 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result6 !== null) { - result7 = parse_h16(); - if (result7 !== null) { - result6 = [result6, result7]; - } else { - result6 = null; - pos = pos2; - } - } else { - result6 = null; - pos = pos2; - } - result6 = result6 !== null ? result6 : ""; - if (result6 !== null) { - if (input.substr(pos, 2) === "::") { - result7 = "::"; - pos += 2; - } else { - result7 = null; - if (reportFailures === 0) { - matchFailed("\"::\""); - } - } - if (result7 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } - } - } - } - } - } - } - } - } - } - } - } - } - } - if (result0 !== null) { - result0 = (function(offset) { - data.host_type = 'IPv6'; - return input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_h16() { - var result0, result1, result2, result3; - var pos0; - pos0 = pos; - result0 = parse_HEXDIG(); - if (result0 !== null) { - result1 = parse_HEXDIG(); - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result2 = parse_HEXDIG(); - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - result3 = parse_HEXDIG(); - result3 = result3 !== null ? result3 : ""; - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_ls32() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_h16(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_h16(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - if (result0 === null) { - result0 = parse_IPv4address(); - } - return result0; - } - function parse_IPv4address() { - var result0, result1, result2, result3, result4, result5, result6; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_dec_octet(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 46) { - result1 = "."; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result1 !== null) { - result2 = parse_dec_octet(); - if (result2 !== null) { - if (input.charCodeAt(pos) === 46) { - result3 = "."; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result3 !== null) { - result4 = parse_dec_octet(); - if (result4 !== null) { - if (input.charCodeAt(pos) === 46) { - result5 = "."; - pos++; - } else { - result5 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result5 !== null) { - result6 = parse_dec_octet(); - if (result6 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - data.host_type = 'IPv4'; - return input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_dec_octet() { - var result0, result1, result2; - var pos0; - pos0 = pos; - if (input.substr(pos, 2) === "25") { - result0 = "25"; - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"25\""); - } - } - if (result0 !== null) { - if (/^[0-5]/.test(input.charAt(pos))) { - result1 = input.charAt(pos); - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("[0-5]"); - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - if (result0 === null) { - pos0 = pos; - if (input.charCodeAt(pos) === 50) { - result0 = "2"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"2\""); - } - } - if (result0 !== null) { - if (/^[0-4]/.test(input.charAt(pos))) { - result1 = input.charAt(pos); - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("[0-4]"); - } - } - if (result1 !== null) { - result2 = parse_DIGIT(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - if (result0 === null) { - pos0 = pos; - if (input.charCodeAt(pos) === 49) { - result0 = "1"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"1\""); - } - } - if (result0 !== null) { - result1 = parse_DIGIT(); - if (result1 !== null) { - result2 = parse_DIGIT(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - if (result0 === null) { - pos0 = pos; - if (/^[1-9]/.test(input.charAt(pos))) { - result0 = input.charAt(pos); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("[1-9]"); - } - } - if (result0 !== null) { - result1 = parse_DIGIT(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - if (result0 === null) { - result0 = parse_DIGIT(); - } - } - } - } - return result0; - } - function parse_port() { - var result0, result1, result2, result3, result4; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_DIGIT(); - result0 = result0 !== null ? result0 : ""; - if (result0 !== null) { - result1 = parse_DIGIT(); - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result2 = parse_DIGIT(); - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - result3 = parse_DIGIT(); - result3 = result3 !== null ? result3 : ""; - if (result3 !== null) { - result4 = parse_DIGIT(); - result4 = result4 !== null ? result4 : ""; - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, port) { - port = parseInt(port.join('')); - data.port = port; - return port; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_uri_parameters() { - var result0, result1, result2; - var pos0; - result0 = []; - pos0 = pos; - if (input.charCodeAt(pos) === 59) { - result1 = ";"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result1 !== null) { - result2 = parse_uri_parameter(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos0; - } - } else { - result1 = null; - pos = pos0; - } - while (result1 !== null) { - result0.push(result1); - pos0 = pos; - if (input.charCodeAt(pos) === 59) { - result1 = ";"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result1 !== null) { - result2 = parse_uri_parameter(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos0; - } - } else { - result1 = null; - pos = pos0; - } - } - return result0; - } - function parse_uri_parameter() { - var result0; - result0 = parse_transport_param(); - if (result0 === null) { - result0 = parse_user_param(); - if (result0 === null) { - result0 = parse_method_param(); - if (result0 === null) { - result0 = parse_ttl_param(); - if (result0 === null) { - result0 = parse_maddr_param(); - if (result0 === null) { - result0 = parse_lr_param(); - if (result0 === null) { - result0 = parse_other_param(); - } - } - } - } - } - } - return result0; - } - function parse_transport_param() { - var result0, result1; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 10).toLowerCase() === "transport=") { - result0 = input.substr(pos, 10); - pos += 10; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"transport=\""); - } - } - if (result0 !== null) { - if (input.substr(pos, 3).toLowerCase() === "udp") { - result1 = input.substr(pos, 3); - pos += 3; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"udp\""); - } - } - if (result1 === null) { - if (input.substr(pos, 3).toLowerCase() === "tcp") { - result1 = input.substr(pos, 3); - pos += 3; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"tcp\""); - } - } - if (result1 === null) { - if (input.substr(pos, 4).toLowerCase() === "sctp") { - result1 = input.substr(pos, 4); - pos += 4; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"sctp\""); - } - } - if (result1 === null) { - if (input.substr(pos, 3).toLowerCase() === "tls") { - result1 = input.substr(pos, 3); - pos += 3; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"tls\""); - } - } - if (result1 === null) { - result1 = parse_token(); - } - } - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, transport) { - if(!data.uri_params) data.uri_params={}; - data.uri_params['transport'] = transport.toLowerCase(); })(pos0, result0[1]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_user_param() { - var result0, result1; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 5).toLowerCase() === "user=") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"user=\""); - } - } - if (result0 !== null) { - if (input.substr(pos, 5).toLowerCase() === "phone") { - result1 = input.substr(pos, 5); - pos += 5; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"phone\""); - } - } - if (result1 === null) { - if (input.substr(pos, 2).toLowerCase() === "ip") { - result1 = input.substr(pos, 2); - pos += 2; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"ip\""); - } - } - if (result1 === null) { - result1 = parse_token(); - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, user) { - if(!data.uri_params) data.uri_params={}; - data.uri_params['user'] = user.toLowerCase(); })(pos0, result0[1]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_method_param() { - var result0, result1; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 7).toLowerCase() === "method=") { - result0 = input.substr(pos, 7); - pos += 7; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"method=\""); - } - } - if (result0 !== null) { - result1 = parse_Method(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, method) { - if(!data.uri_params) data.uri_params={}; - data.uri_params['method'] = method; })(pos0, result0[1]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_ttl_param() { - var result0, result1; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 4).toLowerCase() === "ttl=") { - result0 = input.substr(pos, 4); - pos += 4; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"ttl=\""); - } - } - if (result0 !== null) { - result1 = parse_ttl(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, ttl) { - if(!data.params) data.params={}; - data.params['ttl'] = ttl; })(pos0, result0[1]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_maddr_param() { - var result0, result1; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 6).toLowerCase() === "maddr=") { - result0 = input.substr(pos, 6); - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"maddr=\""); - } - } - if (result0 !== null) { - result1 = parse_host(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, maddr) { - if(!data.uri_params) data.uri_params={}; - data.uri_params['maddr'] = maddr; })(pos0, result0[1]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_lr_param() { - var result0, result1, result2; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 2).toLowerCase() === "lr") { - result0 = input.substr(pos, 2); - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"lr\""); - } - } - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 61) { - result1 = "="; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result1 !== null) { - result2 = parse_token(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - if(!data.uri_params) data.uri_params={}; - data.uri_params['lr'] = undefined; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_other_param() { - var result0, result1, result2; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_pname(); - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 61) { - result1 = "="; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result1 !== null) { - result2 = parse_pvalue(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, param, value) { - if(!data.uri_params) data.uri_params = {}; - if (typeof value === 'undefined'){ - value = undefined; - } - else { - value = value[1]; - } - data.uri_params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_pname() { - var result0, result1; - var pos0; - pos0 = pos; - result1 = parse_paramchar(); - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_paramchar(); - } - } else { - result0 = null; - } - if (result0 !== null) { - result0 = (function(offset, pname) {return pname.join(''); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_pvalue() { - var result0, result1; - var pos0; - pos0 = pos; - result1 = parse_paramchar(); - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_paramchar(); - } - } else { - result0 = null; - } - if (result0 !== null) { - result0 = (function(offset, pvalue) {return pvalue.join(''); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_paramchar() { - var result0; - result0 = parse_param_unreserved(); - if (result0 === null) { - result0 = parse_unreserved(); - if (result0 === null) { - result0 = parse_escaped(); - } - } - return result0; - } - function parse_param_unreserved() { - var result0; - if (input.charCodeAt(pos) === 91) { - result0 = "["; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"[\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 93) { - result0 = "]"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"]\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 47) { - result0 = "/"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 58) { - result0 = ":"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 38) { - result0 = "&"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 43) { - result0 = "+"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 36) { - result0 = "$"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"$\""); - } - } - } - } - } - } - } - } - return result0; - } - function parse_headers() { - var result0, result1, result2, result3, result4; - var pos0, pos1; - pos0 = pos; - if (input.charCodeAt(pos) === 63) { - result0 = "?"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"?\""); - } - } - if (result0 !== null) { - result1 = parse_header(); - if (result1 !== null) { - result2 = []; - pos1 = pos; - if (input.charCodeAt(pos) === 38) { - result3 = "&"; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result3 !== null) { - result4 = parse_header(); - if (result4 !== null) { - result3 = [result3, result4]; - } else { - result3 = null; - pos = pos1; - } - } else { - result3 = null; - pos = pos1; - } - while (result3 !== null) { - result2.push(result3); - pos1 = pos; - if (input.charCodeAt(pos) === 38) { - result3 = "&"; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result3 !== null) { - result4 = parse_header(); - if (result4 !== null) { - result3 = [result3, result4]; - } else { - result3 = null; - pos = pos1; - } - } else { - result3 = null; - pos = pos1; - } - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_header() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_hname(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 61) { - result1 = "="; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result1 !== null) { - result2 = parse_hvalue(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, hname, hvalue) { - hname = hname.join('').toLowerCase(); - hvalue = hvalue.join(''); - if(!data.uri_headers) data.uri_headers = {}; - if (!data.uri_headers[hname]) { - data.uri_headers[hname] = [hvalue]; - } else { - data.uri_headers[hname].push(hvalue); - }})(pos0, result0[0], result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_hname() { - var result0, result1; - result1 = parse_hnv_unreserved(); - if (result1 === null) { - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - } - } - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_hnv_unreserved(); - if (result1 === null) { - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - } - } - } - } else { - result0 = null; - } - return result0; - } - function parse_hvalue() { - var result0, result1; - result0 = []; - result1 = parse_hnv_unreserved(); - if (result1 === null) { - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - } - } - while (result1 !== null) { - result0.push(result1); - result1 = parse_hnv_unreserved(); - if (result1 === null) { - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - } - } - } - return result0; - } - function parse_hnv_unreserved() { - var result0; - if (input.charCodeAt(pos) === 91) { - result0 = "["; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"[\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 93) { - result0 = "]"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"]\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 47) { - result0 = "/"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 63) { - result0 = "?"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"?\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 58) { - result0 = ":"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 43) { - result0 = "+"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 36) { - result0 = "$"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"$\""); - } - } - } - } - } - } - } - } - return result0; - } - function parse_Request_Response() { - var result0; - result0 = parse_Status_Line(); - if (result0 === null) { - result0 = parse_Request_Line(); - } - return result0; - } - function parse_Request_Line() { - var result0, result1, result2, result3, result4; - var pos0; - pos0 = pos; - result0 = parse_Method(); - if (result0 !== null) { - result1 = parse_SP(); - if (result1 !== null) { - result2 = parse_Request_URI(); - if (result2 !== null) { - result3 = parse_SP(); - if (result3 !== null) { - result4 = parse_SIP_Version(); - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_Request_URI() { - var result0; - result0 = parse_SIP_URI(); - if (result0 === null) { - result0 = parse_absoluteURI(); - } - return result0; - } - function parse_absoluteURI() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_scheme(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 !== null) { - result2 = parse_hier_part(); - if (result2 === null) { - result2 = parse_opaque_part(); - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_hier_part() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - result0 = parse_net_path(); - if (result0 === null) { - result0 = parse_abs_path(); - } - if (result0 !== null) { - pos1 = pos; - if (input.charCodeAt(pos) === 63) { - result1 = "?"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"?\""); - } - } - if (result1 !== null) { - result2 = parse_query(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos1; - } - } else { - result1 = null; - pos = pos1; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_net_path() { - var result0, result1, result2; - var pos0; - pos0 = pos; - if (input.substr(pos, 2) === "//") { - result0 = "//"; - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"//\""); - } - } - if (result0 !== null) { - result1 = parse_authority(); - if (result1 !== null) { - result2 = parse_abs_path(); - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_abs_path() { - var result0, result1; - var pos0; - pos0 = pos; - if (input.charCodeAt(pos) === 47) { - result0 = "/"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result0 !== null) { - result1 = parse_path_segments(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_opaque_part() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_uric_no_slash(); - if (result0 !== null) { - result1 = []; - result2 = parse_uric(); - while (result2 !== null) { - result1.push(result2); - result2 = parse_uric(); - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_uric() { - var result0; - result0 = parse_reserved(); - if (result0 === null) { - result0 = parse_unreserved(); - if (result0 === null) { - result0 = parse_escaped(); - } - } - return result0; - } - function parse_uric_no_slash() { - var result0; - result0 = parse_unreserved(); - if (result0 === null) { - result0 = parse_escaped(); - if (result0 === null) { - if (input.charCodeAt(pos) === 59) { - result0 = ";"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 63) { - result0 = "?"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"?\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 58) { - result0 = ":"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 64) { - result0 = "@"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"@\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 38) { - result0 = "&"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 61) { - result0 = "="; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 43) { - result0 = "+"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 36) { - result0 = "$"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"$\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 44) { - result0 = ","; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - } - } - } - } - } - } - } - } - } - } - return result0; - } - function parse_path_segments() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_segment(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - if (input.charCodeAt(pos) === 47) { - result2 = "/"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result2 !== null) { - result3 = parse_segment(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - if (input.charCodeAt(pos) === 47) { - result2 = "/"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result2 !== null) { - result3 = parse_segment(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_segment() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = []; - result1 = parse_pchar(); - while (result1 !== null) { - result0.push(result1); - result1 = parse_pchar(); - } - if (result0 !== null) { - result1 = []; - pos1 = pos; - if (input.charCodeAt(pos) === 59) { - result2 = ";"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result2 !== null) { - result3 = parse_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - if (input.charCodeAt(pos) === 59) { - result2 = ";"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result2 !== null) { - result3 = parse_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_param() { - var result0, result1; - result0 = []; - result1 = parse_pchar(); - while (result1 !== null) { - result0.push(result1); - result1 = parse_pchar(); - } - return result0; - } - function parse_pchar() { - var result0; - result0 = parse_unreserved(); - if (result0 === null) { - result0 = parse_escaped(); - if (result0 === null) { - if (input.charCodeAt(pos) === 58) { - result0 = ":"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 64) { - result0 = "@"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"@\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 38) { - result0 = "&"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 61) { - result0 = "="; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 43) { - result0 = "+"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 36) { - result0 = "$"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"$\""); - } - } - if (result0 === null) { - if (input.charCodeAt(pos) === 44) { - result0 = ","; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - } - } - } - } - } - } - } - } - return result0; - } - function parse_scheme() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_ALPHA(); - if (result0 !== null) { - result1 = []; - result2 = parse_ALPHA(); - if (result2 === null) { - result2 = parse_DIGIT(); - if (result2 === null) { - if (input.charCodeAt(pos) === 43) { - result2 = "+"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result2 === null) { - if (input.charCodeAt(pos) === 45) { - result2 = "-"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result2 === null) { - if (input.charCodeAt(pos) === 46) { - result2 = "."; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - } - } - } - } - while (result2 !== null) { - result1.push(result2); - result2 = parse_ALPHA(); - if (result2 === null) { - result2 = parse_DIGIT(); - if (result2 === null) { - if (input.charCodeAt(pos) === 43) { - result2 = "+"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - if (result2 === null) { - if (input.charCodeAt(pos) === 45) { - result2 = "-"; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result2 === null) { - if (input.charCodeAt(pos) === 46) { - result2 = "."; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - } - } - } - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - data.scheme= input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_authority() { - var result0; - result0 = parse_srvr(); - if (result0 === null) { - result0 = parse_reg_name(); - } - return result0; - } - function parse_srvr() { - var result0, result1; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_userinfo(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 64) { - result1 = "@"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"@\""); - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - result0 = result0 !== null ? result0 : ""; - if (result0 !== null) { - result1 = parse_hostport(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - result0 = result0 !== null ? result0 : ""; - return result0; - } - function parse_reg_name() { - var result0, result1; - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - if (result1 === null) { - if (input.charCodeAt(pos) === 36) { - result1 = "$"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"$\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 44) { - result1 = ","; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 59) { - result1 = ";"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 64) { - result1 = "@"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"@\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 38) { - result1 = "&"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 61) { - result1 = "="; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - } - } - } - } - } - } - } - } - } - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - if (result1 === null) { - if (input.charCodeAt(pos) === 36) { - result1 = "$"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"$\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 44) { - result1 = ","; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 59) { - result1 = ";"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\";\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 58) { - result1 = ":"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\":\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 64) { - result1 = "@"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"@\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 38) { - result1 = "&"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"&\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 61) { - result1 = "="; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"=\""); - } - } - if (result1 === null) { - if (input.charCodeAt(pos) === 43) { - result1 = "+"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"+\""); - } - } - } - } - } - } - } - } - } - } - } - } - } else { - result0 = null; - } - return result0; - } - function parse_query() { - var result0, result1; - result0 = []; - result1 = parse_uric(); - while (result1 !== null) { - result0.push(result1); - result1 = parse_uric(); - } - return result0; - } - function parse_SIP_Version() { - var result0, result1, result2, result3, result4, result5; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 3).toLowerCase() === "sip") { - result0 = input.substr(pos, 3); - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"SIP\""); - } - } - if (result0 !== null) { - if (input.charCodeAt(pos) === 47) { - result1 = "/"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"/\""); - } - } - if (result1 !== null) { - result3 = parse_DIGIT(); - if (result3 !== null) { - result2 = []; - while (result3 !== null) { - result2.push(result3); - result3 = parse_DIGIT(); - } - } else { - result2 = null; - } - if (result2 !== null) { - if (input.charCodeAt(pos) === 46) { - result3 = "."; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result3 !== null) { - result5 = parse_DIGIT(); - if (result5 !== null) { - result4 = []; - while (result5 !== null) { - result4.push(result5); - result5 = parse_DIGIT(); - } - } else { - result4 = null; - } - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - data.sip_version = input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_INVITEm() { - var result0; - if (input.substr(pos, 6) === "INVITE") { - result0 = "INVITE"; - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"INVITE\""); - } - } - return result0; - } - function parse_ACKm() { - var result0; - if (input.substr(pos, 3) === "ACK") { - result0 = "ACK"; - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"ACK\""); - } - } - return result0; - } - function parse_OPTIONSm() { - var result0; - if (input.substr(pos, 7) === "OPTIONS") { - result0 = "OPTIONS"; - pos += 7; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"OPTIONS\""); - } - } - return result0; - } - function parse_BYEm() { - var result0; - if (input.substr(pos, 3) === "BYE") { - result0 = "BYE"; - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"BYE\""); - } - } - return result0; - } - function parse_CANCELm() { - var result0; - if (input.substr(pos, 6) === "CANCEL") { - result0 = "CANCEL"; - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"CANCEL\""); - } - } - return result0; - } - function parse_REGISTERm() { - var result0; - if (input.substr(pos, 8) === "REGISTER") { - result0 = "REGISTER"; - pos += 8; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"REGISTER\""); - } - } - return result0; - } - function parse_SUBSCRIBEm() { - var result0; - if (input.substr(pos, 9) === "SUBSCRIBE") { - result0 = "SUBSCRIBE"; - pos += 9; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"SUBSCRIBE\""); - } - } - return result0; - } - function parse_NOTIFYm() { - var result0; - if (input.substr(pos, 6) === "NOTIFY") { - result0 = "NOTIFY"; - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"NOTIFY\""); - } - } - return result0; - } - function parse_REFERm() { - var result0; - if (input.substr(pos, 5) === "REFER") { - result0 = "REFER"; - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"REFER\""); - } - } - return result0; - } - function parse_Method() { - var result0; - var pos0; - pos0 = pos; - result0 = parse_INVITEm(); - if (result0 === null) { - result0 = parse_ACKm(); - if (result0 === null) { - result0 = parse_OPTIONSm(); - if (result0 === null) { - result0 = parse_BYEm(); - if (result0 === null) { - result0 = parse_CANCELm(); - if (result0 === null) { - result0 = parse_REGISTERm(); - if (result0 === null) { - result0 = parse_SUBSCRIBEm(); - if (result0 === null) { - result0 = parse_NOTIFYm(); - if (result0 === null) { - result0 = parse_REFERm(); - if (result0 === null) { - result0 = parse_token(); - } - } - } - } - } - } - } - } - } - if (result0 !== null) { - result0 = (function(offset) { - data.method = input.substring(pos, offset); - return data.method; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Status_Line() { - var result0, result1, result2, result3, result4; - var pos0; - pos0 = pos; - result0 = parse_SIP_Version(); - if (result0 !== null) { - result1 = parse_SP(); - if (result1 !== null) { - result2 = parse_Status_Code(); - if (result2 !== null) { - result3 = parse_SP(); - if (result3 !== null) { - result4 = parse_Reason_Phrase(); - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_Status_Code() { - var result0; - var pos0; - pos0 = pos; - result0 = parse_extension_code(); - if (result0 !== null) { - result0 = (function(offset, status_code) { - data.status_code = parseInt(status_code.join('')); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_extension_code() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_DIGIT(); - if (result0 !== null) { - result1 = parse_DIGIT(); - if (result1 !== null) { - result2 = parse_DIGIT(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_Reason_Phrase() { - var result0, result1; - var pos0; - pos0 = pos; - result0 = []; - result1 = parse_reserved(); - if (result1 === null) { - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - if (result1 === null) { - result1 = parse_UTF8_NONASCII(); - if (result1 === null) { - result1 = parse_UTF8_CONT(); - if (result1 === null) { - result1 = parse_SP(); - if (result1 === null) { - result1 = parse_HTAB(); - } - } - } - } - } - } - while (result1 !== null) { - result0.push(result1); - result1 = parse_reserved(); - if (result1 === null) { - result1 = parse_unreserved(); - if (result1 === null) { - result1 = parse_escaped(); - if (result1 === null) { - result1 = parse_UTF8_NONASCII(); - if (result1 === null) { - result1 = parse_UTF8_CONT(); - if (result1 === null) { - result1 = parse_SP(); - if (result1 === null) { - result1 = parse_HTAB(); - } - } - } - } - } - } - } - if (result0 !== null) { - result0 = (function(offset) { - data.reason_phrase = input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Allow_Events() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_event_type(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_event_type(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_event_type(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_Call_ID() { - var result0, result1, result2; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_word(); - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 64) { - result1 = "@"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"@\""); - } - } - if (result1 !== null) { - result2 = parse_word(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - data = input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Contact() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - result0 = parse_STAR(); - if (result0 === null) { - pos1 = pos; - result0 = parse_contact_param(); - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_contact_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_contact_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } - if (result0 !== null) { - result0 = (function(offset) { - var idx, length; - length = data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (data.multi_header[idx].parsed === null) { - data = null; - break; - } - } - if (data !== null) { - data = data.multi_header; - } else { - data = -1; - }})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_contact_param() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_SIP_URI_noparams(); - if (result0 === null) { - result0 = parse_name_addr(); - } - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_contact_params(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_contact_params(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - var header; - if(!data.multi_header) data.multi_header = []; - try { - header = new NameAddrHeader(data.uri, data.display_name, data.params); - delete data.uri; - delete data.display_name; - delete data.params; - } catch(e) { - header = null; - } - data.multi_header.push( { 'possition': pos, - 'offset': offset, - 'parsed': header - });})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_name_addr() { - var result0, result1, result2, result3; - var pos0; - pos0 = pos; - result0 = parse_display_name(); - result0 = result0 !== null ? result0 : ""; - if (result0 !== null) { - result1 = parse_LAQUOT(); - if (result1 !== null) { - result2 = parse_SIP_URI(); - if (result2 !== null) { - result3 = parse_RAQUOT(); - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_display_name() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_token(); - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_LWS(); - if (result2 !== null) { - result3 = parse_token(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_LWS(); - if (result2 !== null) { - result3 = parse_token(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 === null) { - result0 = parse_quoted_string(); - } - if (result0 !== null) { - result0 = (function(offset, display_name) { - display_name = input.substring(pos, offset).trim(); - if (display_name[0] === '\"') { - display_name = display_name.substring(1, display_name.length-1); - } - data.display_name = display_name; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_contact_params() { - var result0; - result0 = parse_c_p_q(); - if (result0 === null) { - result0 = parse_c_p_expires(); - if (result0 === null) { - result0 = parse_generic_param(); - } - } - return result0; - } - function parse_c_p_q() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 1).toLowerCase() === "q") { - result0 = input.substr(pos, 1); - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"q\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_qvalue(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, q) { - if(!data.params) data.params = {}; - data.params['q'] = q; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_c_p_expires() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 7).toLowerCase() === "expires") { - result0 = input.substr(pos, 7); - pos += 7; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"expires\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_delta_seconds(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, expires) { - if(!data.params) data.params = {}; - data.params['expires'] = expires; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_delta_seconds() { - var result0, result1; - var pos0; - pos0 = pos; - result1 = parse_DIGIT(); - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_DIGIT(); - } - } else { - result0 = null; - } - if (result0 !== null) { - result0 = (function(offset, delta_seconds) { - return parseInt(delta_seconds.join('')); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_qvalue() { - var result0, result1, result2, result3, result4; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - if (input.charCodeAt(pos) === 48) { - result0 = "0"; - pos++; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"0\""); - } - } - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 46) { - result1 = "."; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result1 !== null) { - result2 = parse_DIGIT(); - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - result3 = parse_DIGIT(); - result3 = result3 !== null ? result3 : ""; - if (result3 !== null) { - result4 = parse_DIGIT(); - result4 = result4 !== null ? result4 : ""; - if (result4 !== null) { - result1 = [result1, result2, result3, result4]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - return parseFloat(input.substring(pos, offset)); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_generic_param() { - var result0, result1, result2; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_token(); - if (result0 !== null) { - pos2 = pos; - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_gen_value(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, param, value) { - if(!data.params) data.params = {}; - if (typeof value === 'undefined'){ - value = undefined; - } - else { - value = value[1]; - } - data.params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_gen_value() { - var result0; - result0 = parse_token(); - if (result0 === null) { - result0 = parse_host(); - if (result0 === null) { - result0 = parse_quoted_string(); - } - } - return result0; - } - function parse_Content_Disposition() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_disp_type(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_disp_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_disp_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_disp_type() { - var result0; - if (input.substr(pos, 6).toLowerCase() === "render") { - result0 = input.substr(pos, 6); - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"render\""); - } - } - if (result0 === null) { - if (input.substr(pos, 7).toLowerCase() === "session") { - result0 = input.substr(pos, 7); - pos += 7; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"session\""); - } - } - if (result0 === null) { - if (input.substr(pos, 4).toLowerCase() === "icon") { - result0 = input.substr(pos, 4); - pos += 4; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"icon\""); - } - } - if (result0 === null) { - if (input.substr(pos, 5).toLowerCase() === "alert") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"alert\""); - } - } - if (result0 === null) { - result0 = parse_token(); - } - } - } - } - return result0; - } - function parse_disp_param() { - var result0; - result0 = parse_handling_param(); - if (result0 === null) { - result0 = parse_generic_param(); - } - return result0; - } - function parse_handling_param() { - var result0, result1, result2; - var pos0; - pos0 = pos; - if (input.substr(pos, 8).toLowerCase() === "handling") { - result0 = input.substr(pos, 8); - pos += 8; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"handling\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - if (input.substr(pos, 8).toLowerCase() === "optional") { - result2 = input.substr(pos, 8); - pos += 8; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"optional\""); - } - } - if (result2 === null) { - if (input.substr(pos, 8).toLowerCase() === "required") { - result2 = input.substr(pos, 8); - pos += 8; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"required\""); - } - } - if (result2 === null) { - result2 = parse_token(); - } - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_Content_Encoding() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_token(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_token(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_token(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_Content_Length() { - var result0, result1; - var pos0; - pos0 = pos; - result1 = parse_DIGIT(); - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_DIGIT(); - } - } else { - result0 = null; - } - if (result0 !== null) { - result0 = (function(offset, length) { - data = parseInt(length.join('')); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Content_Type() { - var result0; - var pos0; - pos0 = pos; - result0 = parse_media_type(); - if (result0 !== null) { - result0 = (function(offset) { - data = input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_media_type() { - var result0, result1, result2, result3, result4, result5; - var pos0, pos1; - pos0 = pos; - result0 = parse_m_type(); - if (result0 !== null) { - result1 = parse_SLASH(); - if (result1 !== null) { - result2 = parse_m_subtype(); - if (result2 !== null) { - result3 = []; - pos1 = pos; - result4 = parse_SEMI(); - if (result4 !== null) { - result5 = parse_m_parameter(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos1; - } - } else { - result4 = null; - pos = pos1; - } - while (result4 !== null) { - result3.push(result4); - pos1 = pos; - result4 = parse_SEMI(); - if (result4 !== null) { - result5 = parse_m_parameter(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos1; - } - } else { - result4 = null; - pos = pos1; - } - } - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_m_type() { - var result0; - result0 = parse_discrete_type(); - if (result0 === null) { - result0 = parse_composite_type(); - } - return result0; - } - function parse_discrete_type() { - var result0; - if (input.substr(pos, 4).toLowerCase() === "text") { - result0 = input.substr(pos, 4); - pos += 4; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"text\""); - } - } - if (result0 === null) { - if (input.substr(pos, 5).toLowerCase() === "image") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"image\""); - } - } - if (result0 === null) { - if (input.substr(pos, 5).toLowerCase() === "audio") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"audio\""); - } - } - if (result0 === null) { - if (input.substr(pos, 5).toLowerCase() === "video") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"video\""); - } - } - if (result0 === null) { - if (input.substr(pos, 11).toLowerCase() === "application") { - result0 = input.substr(pos, 11); - pos += 11; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"application\""); - } - } - if (result0 === null) { - result0 = parse_extension_token(); - } - } - } - } - } - return result0; - } - function parse_composite_type() { - var result0; - if (input.substr(pos, 7).toLowerCase() === "message") { - result0 = input.substr(pos, 7); - pos += 7; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"message\""); - } - } - if (result0 === null) { - if (input.substr(pos, 9).toLowerCase() === "multipart") { - result0 = input.substr(pos, 9); - pos += 9; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"multipart\""); - } - } - if (result0 === null) { - result0 = parse_extension_token(); - } - } - return result0; - } - function parse_extension_token() { - var result0; - result0 = parse_token(); - if (result0 === null) { - result0 = parse_x_token(); - } - return result0; - } - function parse_x_token() { - var result0, result1; - var pos0; - pos0 = pos; - if (input.substr(pos, 2).toLowerCase() === "x-") { - result0 = input.substr(pos, 2); - pos += 2; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"x-\""); - } - } - if (result0 !== null) { - result1 = parse_token(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_m_subtype() { - var result0; - result0 = parse_extension_token(); - if (result0 === null) { - result0 = parse_token(); - } - return result0; - } - function parse_m_parameter() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_token(); - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_m_value(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_m_value() { - var result0; - result0 = parse_token(); - if (result0 === null) { - result0 = parse_quoted_string(); - } - return result0; - } - function parse_CSeq() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_CSeq_value(); - if (result0 !== null) { - result1 = parse_LWS(); - if (result1 !== null) { - result2 = parse_Method(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_CSeq_value() { - var result0, result1; - var pos0; - pos0 = pos; - result1 = parse_DIGIT(); - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_DIGIT(); - } - } else { - result0 = null; - } - if (result0 !== null) { - result0 = (function(offset, cseq_value) { - data.value=parseInt(cseq_value.join('')); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Expires() { - var result0; - var pos0; - pos0 = pos; - result0 = parse_delta_seconds(); - if (result0 !== null) { - result0 = (function(offset, expires) {data = expires; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Event() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_event_type(); - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_generic_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_generic_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, event_type) { - data.event = event_type.join('').toLowerCase(); })(pos0, result0[0]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_event_type() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_token_nodot(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - if (input.charCodeAt(pos) === 46) { - result2 = "."; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result2 !== null) { - result3 = parse_token_nodot(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - if (input.charCodeAt(pos) === 46) { - result2 = "."; - pos++; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\".\""); - } - } - if (result2 !== null) { - result3 = parse_token_nodot(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_From() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_SIP_URI_noparams(); - if (result0 === null) { - result0 = parse_name_addr(); - } - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_from_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_from_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - var tag = data.tag; - try { - data = new NameAddrHeader(data.uri, data.display_name, data.params); - if (tag) {data.setParam('tag',tag)} - } catch(e) { - data = -1; - }})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_from_param() { - var result0; - result0 = parse_tag_param(); - if (result0 === null) { - result0 = parse_generic_param(); - } - return result0; - } - function parse_tag_param() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 3).toLowerCase() === "tag") { - result0 = input.substr(pos, 3); - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"tag\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_token(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, tag) {data.tag = tag; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Max_Forwards() { - var result0, result1; - var pos0; - pos0 = pos; - result1 = parse_DIGIT(); - if (result1 !== null) { - result0 = []; - while (result1 !== null) { - result0.push(result1); - result1 = parse_DIGIT(); - } - } else { - result0 = null; - } - if (result0 !== null) { - result0 = (function(offset, forwards) { - data = parseInt(forwards.join('')); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Min_Expires() { - var result0; - var pos0; - pos0 = pos; - result0 = parse_delta_seconds(); - if (result0 !== null) { - result0 = (function(offset, min_expires) {data = min_expires; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Name_Addr_Header() { - var result0, result1, result2, result3, result4, result5, result6; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = []; - result1 = parse_display_name(); - while (result1 !== null) { - result0.push(result1); - result1 = parse_display_name(); - } - if (result0 !== null) { - result1 = parse_LAQUOT(); - if (result1 !== null) { - result2 = parse_SIP_URI(); - if (result2 !== null) { - result3 = parse_RAQUOT(); - if (result3 !== null) { - result4 = []; - pos2 = pos; - result5 = parse_SEMI(); - if (result5 !== null) { - result6 = parse_generic_param(); - if (result6 !== null) { - result5 = [result5, result6]; - } else { - result5 = null; - pos = pos2; - } - } else { - result5 = null; - pos = pos2; - } - while (result5 !== null) { - result4.push(result5); - pos2 = pos; - result5 = parse_SEMI(); - if (result5 !== null) { - result6 = parse_generic_param(); - if (result6 !== null) { - result5 = [result5, result6]; - } else { - result5 = null; - pos = pos2; - } - } else { - result5 = null; - pos = pos2; - } - } - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - try { - data = new NameAddrHeader(data.uri, data.display_name, data.params); - } catch(e) { - data = -1; - }})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Proxy_Authenticate() { - var result0; - result0 = parse_challenge(); - return result0; - } - function parse_challenge() { - var result0, result1, result2, result3, result4, result5; - var pos0, pos1; - pos0 = pos; - if (input.substr(pos, 6).toLowerCase() === "digest") { - result0 = input.substr(pos, 6); - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"Digest\""); - } - } - if (result0 !== null) { - result1 = parse_LWS(); - if (result1 !== null) { - result2 = parse_digest_cln(); - if (result2 !== null) { - result3 = []; - pos1 = pos; - result4 = parse_COMMA(); - if (result4 !== null) { - result5 = parse_digest_cln(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos1; - } - } else { - result4 = null; - pos = pos1; - } - while (result4 !== null) { - result3.push(result4); - pos1 = pos; - result4 = parse_COMMA(); - if (result4 !== null) { - result5 = parse_digest_cln(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos1; - } - } else { - result4 = null; - pos = pos1; - } - } - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - if (result0 === null) { - result0 = parse_other_challenge(); - } - return result0; - } - function parse_other_challenge() { - var result0, result1, result2, result3, result4, result5; - var pos0, pos1; - pos0 = pos; - result0 = parse_token(); - if (result0 !== null) { - result1 = parse_LWS(); - if (result1 !== null) { - result2 = parse_auth_param(); - if (result2 !== null) { - result3 = []; - pos1 = pos; - result4 = parse_COMMA(); - if (result4 !== null) { - result5 = parse_auth_param(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos1; - } - } else { - result4 = null; - pos = pos1; - } - while (result4 !== null) { - result3.push(result4); - pos1 = pos; - result4 = parse_COMMA(); - if (result4 !== null) { - result5 = parse_auth_param(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos1; - } - } else { - result4 = null; - pos = pos1; - } - } - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_auth_param() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_token(); - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_token(); - if (result2 === null) { - result2 = parse_quoted_string(); - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_digest_cln() { - var result0; - result0 = parse_realm(); - if (result0 === null) { - result0 = parse_domain(); - if (result0 === null) { - result0 = parse_nonce(); - if (result0 === null) { - result0 = parse_opaque(); - if (result0 === null) { - result0 = parse_stale(); - if (result0 === null) { - result0 = parse_algorithm(); - if (result0 === null) { - result0 = parse_qop_options(); - if (result0 === null) { - result0 = parse_auth_param(); - } - } - } - } - } - } - } - return result0; - } - function parse_realm() { - var result0, result1, result2; - var pos0; - pos0 = pos; - if (input.substr(pos, 5).toLowerCase() === "realm") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"realm\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_realm_value(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_realm_value() { - var result0; - var pos0; - pos0 = pos; - result0 = parse_quoted_string_clean(); - if (result0 !== null) { - result0 = (function(offset, realm) { data.realm = realm; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_domain() { - var result0, result1, result2, result3, result4, result5, result6; - var pos0, pos1; - pos0 = pos; - if (input.substr(pos, 6).toLowerCase() === "domain") { - result0 = input.substr(pos, 6); - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"domain\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_LDQUOT(); - if (result2 !== null) { - result3 = parse_URI(); - if (result3 !== null) { - result4 = []; - pos1 = pos; - result6 = parse_SP(); - if (result6 !== null) { - result5 = []; - while (result6 !== null) { - result5.push(result6); - result6 = parse_SP(); - } - } else { - result5 = null; - } - if (result5 !== null) { - result6 = parse_URI(); - if (result6 !== null) { - result5 = [result5, result6]; - } else { - result5 = null; - pos = pos1; - } - } else { - result5 = null; - pos = pos1; - } - while (result5 !== null) { - result4.push(result5); - pos1 = pos; - result6 = parse_SP(); - if (result6 !== null) { - result5 = []; - while (result6 !== null) { - result5.push(result6); - result6 = parse_SP(); - } - } else { - result5 = null; - } - if (result5 !== null) { - result6 = parse_URI(); - if (result6 !== null) { - result5 = [result5, result6]; - } else { - result5 = null; - pos = pos1; - } - } else { - result5 = null; - pos = pos1; - } - } - if (result4 !== null) { - result5 = parse_RDQUOT(); - if (result5 !== null) { - result0 = [result0, result1, result2, result3, result4, result5]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_URI() { - var result0; - result0 = parse_absoluteURI(); - if (result0 === null) { - result0 = parse_abs_path(); - } - return result0; - } - function parse_nonce() { - var result0, result1, result2; - var pos0; - pos0 = pos; - if (input.substr(pos, 5).toLowerCase() === "nonce") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"nonce\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_nonce_value(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_nonce_value() { - var result0; - var pos0; - pos0 = pos; - result0 = parse_quoted_string_clean(); - if (result0 !== null) { - result0 = (function(offset, nonce) { data.nonce=nonce; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_opaque() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 6).toLowerCase() === "opaque") { - result0 = input.substr(pos, 6); - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"opaque\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_quoted_string_clean(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, opaque) { data.opaque=opaque; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_stale() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - if (input.substr(pos, 5).toLowerCase() === "stale") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"stale\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - pos1 = pos; - if (input.substr(pos, 4).toLowerCase() === "true") { - result2 = input.substr(pos, 4); - pos += 4; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"true\""); - } - } - if (result2 !== null) { - result2 = (function(offset) { data.stale=true; })(pos1); - } - if (result2 === null) { - pos = pos1; - } - if (result2 === null) { - pos1 = pos; - if (input.substr(pos, 5).toLowerCase() === "false") { - result2 = input.substr(pos, 5); - pos += 5; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"false\""); - } - } - if (result2 !== null) { - result2 = (function(offset) { data.stale=false; })(pos1); - } - if (result2 === null) { - pos = pos1; - } - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_algorithm() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 9).toLowerCase() === "algorithm") { - result0 = input.substr(pos, 9); - pos += 9; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"algorithm\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - if (input.substr(pos, 3).toLowerCase() === "md5") { - result2 = input.substr(pos, 3); - pos += 3; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"MD5\""); - } - } - if (result2 === null) { - if (input.substr(pos, 8).toLowerCase() === "md5-sess") { - result2 = input.substr(pos, 8); - pos += 8; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"MD5-sess\""); - } - } - if (result2 === null) { - result2 = parse_token(); - } - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, algorithm) { - data.algorithm=algorithm.toUpperCase(); })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_qop_options() { - var result0, result1, result2, result3, result4, result5, result6; - var pos0, pos1, pos2; - pos0 = pos; - if (input.substr(pos, 3).toLowerCase() === "qop") { - result0 = input.substr(pos, 3); - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"qop\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_LDQUOT(); - if (result2 !== null) { - pos1 = pos; - result3 = parse_qop_value(); - if (result3 !== null) { - result4 = []; - pos2 = pos; - if (input.charCodeAt(pos) === 44) { - result5 = ","; - pos++; - } else { - result5 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - if (result5 !== null) { - result6 = parse_qop_value(); - if (result6 !== null) { - result5 = [result5, result6]; - } else { - result5 = null; - pos = pos2; - } - } else { - result5 = null; - pos = pos2; - } - while (result5 !== null) { - result4.push(result5); - pos2 = pos; - if (input.charCodeAt(pos) === 44) { - result5 = ","; - pos++; - } else { - result5 = null; - if (reportFailures === 0) { - matchFailed("\",\""); - } - } - if (result5 !== null) { - result6 = parse_qop_value(); - if (result6 !== null) { - result5 = [result5, result6]; - } else { - result5 = null; - pos = pos2; - } - } else { - result5 = null; - pos = pos2; - } - } - if (result4 !== null) { - result3 = [result3, result4]; - } else { - result3 = null; - pos = pos1; - } - } else { - result3 = null; - pos = pos1; - } - if (result3 !== null) { - result4 = parse_RDQUOT(); - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_qop_value() { - var result0; - var pos0; - pos0 = pos; - if (input.substr(pos, 8).toLowerCase() === "auth-int") { - result0 = input.substr(pos, 8); - pos += 8; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"auth-int\""); - } - } - if (result0 === null) { - if (input.substr(pos, 4).toLowerCase() === "auth") { - result0 = input.substr(pos, 4); - pos += 4; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"auth\""); - } - } - if (result0 === null) { - result0 = parse_token(); - } - } - if (result0 !== null) { - result0 = (function(offset, qop_value) { - data.qop || (data.qop=[]); - data.qop.push(qop_value.toLowerCase()); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Proxy_Require() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_token(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_token(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_token(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_Record_Route() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_rec_route(); - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_rec_route(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_rec_route(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - var idx, length; - length = data.multi_header.length; - for (idx = 0; idx < length; idx++) { - if (data.multi_header[idx].parsed === null) { - data = null; - break; - } - } - if (data !== null) { - data = data.multi_header; - } else { - data = -1; - }})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_rec_route() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_name_addr(); - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_generic_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_generic_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - var header; - if(!data.multi_header) data.multi_header = []; - try { - header = new NameAddrHeader(data.uri, data.display_name, data.params); - delete data.uri; - delete data.display_name; - delete data.params; - } catch(e) { - header = null; - } - data.multi_header.push( { 'possition': pos, - 'offset': offset, - 'parsed': header - });})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Reason() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 3).toLowerCase() === "sip") { - result0 = input.substr(pos, 3); - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"SIP\""); - } - } - if (result0 === null) { - result0 = parse_token(); - } - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_reason_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_reason_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, protocol) { - data.protocol = protocol.toLowerCase(); - if (!data.params) data.params = {}; - if (data.params.text && data.params.text[0] === '"') { - var text = data.params.text; - data.text = text.substring(1, text.length-1); - delete data.params.text; - } - })(pos0, result0[0]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_reason_param() { - var result0; - result0 = parse_reason_cause(); - if (result0 === null) { - result0 = parse_generic_param(); - } - return result0; - } - function parse_reason_cause() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 5).toLowerCase() === "cause") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"cause\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result3 = parse_DIGIT(); - if (result3 !== null) { - result2 = []; - while (result3 !== null) { - result2.push(result3); - result3 = parse_DIGIT(); - } - } else { - result2 = null; - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, cause) { - data.cause = parseInt(cause.join('')); - })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Require() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_token(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_token(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_token(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_Route() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_route_param(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_route_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_route_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_route_param() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_name_addr(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_generic_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_generic_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_Subscription_State() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_substate_value(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_subexp_params(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_subexp_params(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_substate_value() { - var result0; - var pos0; - pos0 = pos; - if (input.substr(pos, 6).toLowerCase() === "active") { - result0 = input.substr(pos, 6); - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"active\""); - } - } - if (result0 === null) { - if (input.substr(pos, 7).toLowerCase() === "pending") { - result0 = input.substr(pos, 7); - pos += 7; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"pending\""); - } - } - if (result0 === null) { - if (input.substr(pos, 10).toLowerCase() === "terminated") { - result0 = input.substr(pos, 10); - pos += 10; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"terminated\""); - } - } - if (result0 === null) { - result0 = parse_token(); - } - } - } - if (result0 !== null) { - result0 = (function(offset) { - data.state = input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_subexp_params() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 6).toLowerCase() === "reason") { - result0 = input.substr(pos, 6); - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"reason\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_event_reason_value(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, reason) { - if (typeof reason !== 'undefined') data.reason = reason; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - if (result0 === null) { - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 7).toLowerCase() === "expires") { - result0 = input.substr(pos, 7); - pos += 7; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"expires\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_delta_seconds(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, expires) { - if (typeof expires !== 'undefined') data.expires = expires; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - if (result0 === null) { - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 11).toLowerCase() === "retry_after") { - result0 = input.substr(pos, 11); - pos += 11; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"retry_after\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_delta_seconds(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, retry_after) { - if (typeof retry_after !== 'undefined') data.retry_after = retry_after; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - if (result0 === null) { - result0 = parse_generic_param(); - } - } - } - return result0; - } - function parse_event_reason_value() { - var result0; - if (input.substr(pos, 11).toLowerCase() === "deactivated") { - result0 = input.substr(pos, 11); - pos += 11; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"deactivated\""); - } - } - if (result0 === null) { - if (input.substr(pos, 9).toLowerCase() === "probation") { - result0 = input.substr(pos, 9); - pos += 9; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"probation\""); - } - } - if (result0 === null) { - if (input.substr(pos, 8).toLowerCase() === "rejected") { - result0 = input.substr(pos, 8); - pos += 8; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"rejected\""); - } - } - if (result0 === null) { - if (input.substr(pos, 7).toLowerCase() === "timeout") { - result0 = input.substr(pos, 7); - pos += 7; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"timeout\""); - } - } - if (result0 === null) { - if (input.substr(pos, 6).toLowerCase() === "giveup") { - result0 = input.substr(pos, 6); - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"giveup\""); - } - } - if (result0 === null) { - if (input.substr(pos, 10).toLowerCase() === "noresource") { - result0 = input.substr(pos, 10); - pos += 10; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"noresource\""); - } - } - if (result0 === null) { - if (input.substr(pos, 9).toLowerCase() === "invariant") { - result0 = input.substr(pos, 9); - pos += 9; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"invariant\""); - } - } - if (result0 === null) { - result0 = parse_token(); - } - } - } - } - } - } - } - return result0; - } - function parse_Subject() { - var result0; - result0 = parse_TEXT_UTF8_TRIM(); - result0 = result0 !== null ? result0 : ""; - return result0; - } - function parse_Supported() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_token(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_token(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_token(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - result0 = result0 !== null ? result0 : ""; - return result0; - } - function parse_To() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_SIP_URI_noparams(); - if (result0 === null) { - result0 = parse_name_addr(); - } - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_to_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_to_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - var tag = data.tag; - try { - data = new NameAddrHeader(data.uri, data.display_name, data.params); - if (tag) {data.setParam('tag',tag)} - } catch(e) { - data = -1; - }})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_to_param() { - var result0; - result0 = parse_tag_param(); - if (result0 === null) { - result0 = parse_generic_param(); - } - return result0; - } - function parse_Via() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_via_param(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_via_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_COMMA(); - if (result2 !== null) { - result3 = parse_via_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_via_param() { - var result0, result1, result2, result3, result4, result5; - var pos0, pos1; - pos0 = pos; - result0 = parse_sent_protocol(); - if (result0 !== null) { - result1 = parse_LWS(); - if (result1 !== null) { - result2 = parse_sent_by(); - if (result2 !== null) { - result3 = []; - pos1 = pos; - result4 = parse_SEMI(); - if (result4 !== null) { - result5 = parse_via_params(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos1; - } - } else { - result4 = null; - pos = pos1; - } - while (result4 !== null) { - result3.push(result4); - pos1 = pos; - result4 = parse_SEMI(); - if (result4 !== null) { - result5 = parse_via_params(); - if (result5 !== null) { - result4 = [result4, result5]; - } else { - result4 = null; - pos = pos1; - } - } else { - result4 = null; - pos = pos1; - } - } - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_via_params() { - var result0; - result0 = parse_via_ttl(); - if (result0 === null) { - result0 = parse_via_maddr(); - if (result0 === null) { - result0 = parse_via_received(); - if (result0 === null) { - result0 = parse_via_branch(); - if (result0 === null) { - result0 = parse_response_port(); - if (result0 === null) { - result0 = parse_generic_param(); - } - } - } - } - } - return result0; - } - function parse_via_ttl() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 3).toLowerCase() === "ttl") { - result0 = input.substr(pos, 3); - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"ttl\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_ttl(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, via_ttl_value) { - data.ttl = via_ttl_value; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_via_maddr() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 5).toLowerCase() === "maddr") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"maddr\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_host(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, via_maddr) { - data.maddr = via_maddr; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_via_received() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 8).toLowerCase() === "received") { - result0 = input.substr(pos, 8); - pos += 8; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"received\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_IPv4address(); - if (result2 === null) { - result2 = parse_IPv6address(); - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, via_received) { - data.received = via_received; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_via_branch() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 6).toLowerCase() === "branch") { - result0 = input.substr(pos, 6); - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"branch\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_token(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, via_branch) { - data.branch = via_branch; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_response_port() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 5).toLowerCase() === "rport") { - result0 = input.substr(pos, 5); - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"rport\""); - } - } - if (result0 !== null) { - pos2 = pos; - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = []; - result3 = parse_DIGIT(); - while (result3 !== null) { - result2.push(result3); - result3 = parse_DIGIT(); - } - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - if(typeof response_port !== 'undefined') - data.rport = response_port.join(''); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_sent_protocol() { - var result0, result1, result2, result3, result4; - var pos0; - pos0 = pos; - result0 = parse_protocol_name(); - if (result0 !== null) { - result1 = parse_SLASH(); - if (result1 !== null) { - result2 = parse_token(); - if (result2 !== null) { - result3 = parse_SLASH(); - if (result3 !== null) { - result4 = parse_transport(); - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_protocol_name() { - var result0; - var pos0; - pos0 = pos; - if (input.substr(pos, 3).toLowerCase() === "sip") { - result0 = input.substr(pos, 3); - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"SIP\""); - } - } - if (result0 === null) { - result0 = parse_token(); - } - if (result0 !== null) { - result0 = (function(offset, via_protocol) { - data.protocol = via_protocol; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_transport() { - var result0; - var pos0; - pos0 = pos; - if (input.substr(pos, 3).toLowerCase() === "udp") { - result0 = input.substr(pos, 3); - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"UDP\""); - } - } - if (result0 === null) { - if (input.substr(pos, 3).toLowerCase() === "tcp") { - result0 = input.substr(pos, 3); - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"TCP\""); - } - } - if (result0 === null) { - if (input.substr(pos, 3).toLowerCase() === "tls") { - result0 = input.substr(pos, 3); - pos += 3; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"TLS\""); - } - } - if (result0 === null) { - if (input.substr(pos, 4).toLowerCase() === "sctp") { - result0 = input.substr(pos, 4); - pos += 4; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"SCTP\""); - } - } - if (result0 === null) { - result0 = parse_token(); - } - } - } - } - if (result0 !== null) { - result0 = (function(offset, via_transport) { - data.transport = via_transport; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_sent_by() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - result0 = parse_via_host(); - if (result0 !== null) { - pos1 = pos; - result1 = parse_COLON(); - if (result1 !== null) { - result2 = parse_via_port(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos1; - } - } else { - result1 = null; - pos = pos1; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_via_host() { - var result0; - var pos0; - pos0 = pos; - result0 = parse_IPv4address(); - if (result0 === null) { - result0 = parse_IPv6reference(); - if (result0 === null) { - result0 = parse_hostname(); - } - } - if (result0 !== null) { - result0 = (function(offset) { - data.host = input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_via_port() { - var result0, result1, result2, result3, result4; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_DIGIT(); - result0 = result0 !== null ? result0 : ""; - if (result0 !== null) { - result1 = parse_DIGIT(); - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result2 = parse_DIGIT(); - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - result3 = parse_DIGIT(); - result3 = result3 !== null ? result3 : ""; - if (result3 !== null) { - result4 = parse_DIGIT(); - result4 = result4 !== null ? result4 : ""; - if (result4 !== null) { - result0 = [result0, result1, result2, result3, result4]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, via_sent_by_port) { - data.port = parseInt(via_sent_by_port.join('')); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_ttl() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_DIGIT(); - if (result0 !== null) { - result1 = parse_DIGIT(); - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result2 = parse_DIGIT(); - result2 = result2 !== null ? result2 : ""; - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, ttl) { - return parseInt(ttl.join('')); })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_WWW_Authenticate() { - var result0; - result0 = parse_challenge(); - return result0; - } - function parse_Session_Expires() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_s_e_expires(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_s_e_params(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_s_e_params(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_s_e_expires() { - var result0; - var pos0; - pos0 = pos; - result0 = parse_delta_seconds(); - if (result0 !== null) { - result0 = (function(offset, expires) { data.expires = expires; })(pos0, result0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_s_e_params() { - var result0; - result0 = parse_s_e_refresher(); - if (result0 === null) { - result0 = parse_generic_param(); - } - return result0; - } - function parse_s_e_refresher() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 9).toLowerCase() === "refresher") { - result0 = input.substr(pos, 9); - pos += 9; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"refresher\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - if (input.substr(pos, 3).toLowerCase() === "uac") { - result2 = input.substr(pos, 3); - pos += 3; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"uac\""); - } - } - if (result2 === null) { - if (input.substr(pos, 3).toLowerCase() === "uas") { - result2 = input.substr(pos, 3); - pos += 3; - } else { - result2 = null; - if (reportFailures === 0) { - matchFailed("\"uas\""); - } - } - } - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, s_e_refresher_value) { data.refresher = s_e_refresher_value.toLowerCase(); })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_extension_header() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_token(); - if (result0 !== null) { - result1 = parse_HCOLON(); - if (result1 !== null) { - result2 = parse_header_value(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_header_value() { - var result0, result1; - result0 = []; - result1 = parse_TEXT_UTF8char(); - if (result1 === null) { - result1 = parse_UTF8_CONT(); - if (result1 === null) { - result1 = parse_LWS(); - } - } - while (result1 !== null) { - result0.push(result1); - result1 = parse_TEXT_UTF8char(); - if (result1 === null) { - result1 = parse_UTF8_CONT(); - if (result1 === null) { - result1 = parse_LWS(); - } - } - } - return result0; - } - function parse_message_body() { - var result0, result1; - result0 = []; - result1 = parse_OCTET(); - while (result1 !== null) { - result0.push(result1); - result1 = parse_OCTET(); - } - return result0; - } - function parse_uuid_URI() { - var result0, result1; - var pos0; - pos0 = pos; - if (input.substr(pos, 5) === "uuid:") { - result0 = "uuid:"; - pos += 5; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"uuid:\""); - } - } - if (result0 !== null) { - result1 = parse_uuid(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_uuid() { - var result0, result1, result2, result3, result4, result5, result6, result7, result8; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - result0 = parse_hex8(); - if (result0 !== null) { - if (input.charCodeAt(pos) === 45) { - result1 = "-"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result1 !== null) { - result2 = parse_hex4(); - if (result2 !== null) { - if (input.charCodeAt(pos) === 45) { - result3 = "-"; - pos++; - } else { - result3 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result3 !== null) { - result4 = parse_hex4(); - if (result4 !== null) { - if (input.charCodeAt(pos) === 45) { - result5 = "-"; - pos++; - } else { - result5 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result5 !== null) { - result6 = parse_hex4(); - if (result6 !== null) { - if (input.charCodeAt(pos) === 45) { - result7 = "-"; - pos++; - } else { - result7 = null; - if (reportFailures === 0) { - matchFailed("\"-\""); - } - } - if (result7 !== null) { - result8 = parse_hex12(); - if (result8 !== null) { - result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, uuid) { - data = input.substring(pos+5, offset); })(pos0, result0[0]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_hex4() { - var result0, result1, result2, result3; - var pos0; - pos0 = pos; - result0 = parse_HEXDIG(); - if (result0 !== null) { - result1 = parse_HEXDIG(); - if (result1 !== null) { - result2 = parse_HEXDIG(); - if (result2 !== null) { - result3 = parse_HEXDIG(); - if (result3 !== null) { - result0 = [result0, result1, result2, result3]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_hex8() { - var result0, result1; - var pos0; - pos0 = pos; - result0 = parse_hex4(); - if (result0 !== null) { - result1 = parse_hex4(); - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_hex12() { - var result0, result1, result2; - var pos0; - pos0 = pos; - result0 = parse_hex4(); - if (result0 !== null) { - result1 = parse_hex4(); - if (result1 !== null) { - result2 = parse_hex4(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_Refer_To() { - var result0, result1, result2, result3; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_SIP_URI_noparams(); - if (result0 === null) { - result0 = parse_name_addr(); - } - if (result0 !== null) { - result1 = []; - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_generic_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - while (result2 !== null) { - result1.push(result2); - pos2 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_generic_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos2; - } - } else { - result2 = null; - pos = pos2; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - try { - data = new NameAddrHeader(data.uri, data.display_name, data.params); - } catch(e) { - data = -1; - }})(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_Replaces() { - var result0, result1, result2, result3; - var pos0, pos1; - pos0 = pos; - result0 = parse_call_id(); - if (result0 !== null) { - result1 = []; - pos1 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_replaces_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - while (result2 !== null) { - result1.push(result2); - pos1 = pos; - result2 = parse_SEMI(); - if (result2 !== null) { - result3 = parse_replaces_param(); - if (result3 !== null) { - result2 = [result2, result3]; - } else { - result2 = null; - pos = pos1; - } - } else { - result2 = null; - pos = pos1; - } - } - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos0; - } - } else { - result0 = null; - pos = pos0; - } - return result0; - } - function parse_call_id() { - var result0, result1, result2; - var pos0, pos1, pos2; - pos0 = pos; - pos1 = pos; - result0 = parse_word(); - if (result0 !== null) { - pos2 = pos; - if (input.charCodeAt(pos) === 64) { - result1 = "@"; - pos++; - } else { - result1 = null; - if (reportFailures === 0) { - matchFailed("\"@\""); - } - } - if (result1 !== null) { - result2 = parse_word(); - if (result2 !== null) { - result1 = [result1, result2]; - } else { - result1 = null; - pos = pos2; - } - } else { - result1 = null; - pos = pos2; - } - result1 = result1 !== null ? result1 : ""; - if (result1 !== null) { - result0 = [result0, result1]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset) { - data.call_id = input.substring(pos, offset); })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_replaces_param() { - var result0; - result0 = parse_to_tag(); - if (result0 === null) { - result0 = parse_from_tag(); - if (result0 === null) { - result0 = parse_early_flag(); - if (result0 === null) { - result0 = parse_generic_param(); - } - } - } - return result0; - } - function parse_to_tag() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 6) === "to-tag") { - result0 = "to-tag"; - pos += 6; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"to-tag\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_token(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, to_tag) { - data.to_tag = to_tag; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_from_tag() { - var result0, result1, result2; - var pos0, pos1; - pos0 = pos; - pos1 = pos; - if (input.substr(pos, 8) === "from-tag") { - result0 = "from-tag"; - pos += 8; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"from-tag\""); - } - } - if (result0 !== null) { - result1 = parse_EQUAL(); - if (result1 !== null) { - result2 = parse_token(); - if (result2 !== null) { - result0 = [result0, result1, result2]; - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - } else { - result0 = null; - pos = pos1; - } - if (result0 !== null) { - result0 = (function(offset, from_tag) { - data.from_tag = from_tag; })(pos0, result0[2]); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function parse_early_flag() { - var result0; - var pos0; - pos0 = pos; - if (input.substr(pos, 10) === "early-only") { - result0 = "early-only"; - pos += 10; - } else { - result0 = null; - if (reportFailures === 0) { - matchFailed("\"early-only\""); - } - } - if (result0 !== null) { - result0 = (function(offset) { - data.early_only = true; })(pos0); - } - if (result0 === null) { - pos = pos0; - } - return result0; - } - function cleanupExpected(expected) { - expected.sort(); - var lastExpected = null; - var cleanExpected = []; - for (var i = 0; i < expected.length; i++) { - if (expected[i] !== lastExpected) { - cleanExpected.push(expected[i]); - lastExpected = expected[i]; - } - } - return cleanExpected; - } - function computeErrorPosition() { - /* - * The first idea was to use |String.split| to break the input up to the - * error position along newlines and derive the line and column from - * there. However IE's |split| implementation is so broken that it was - * enough to prevent it. - */ - var line = 1; - var column = 1; - var seenCR = false; - for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) { - var ch = input.charAt(i); - if (ch === "\n") { - if (!seenCR) { line++; } - column = 1; - seenCR = false; - } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { - line++; - column = 1; - seenCR = true; - } else { - column++; - seenCR = false; - } - } - return { line: line, column: column }; - } - var URI = require('./URI'); - var NameAddrHeader = require('./NameAddrHeader'); - var data = {}; - var result = parseFunctions[startRule](); - /* - * The parser is now in one of the following three states: - * - * 1. The parser successfully parsed the whole input. - * - * - |result !== null| - * - |pos === input.length| - * - |rightmostFailuresExpected| may or may not contain something - * - * 2. The parser successfully parsed only a part of the input. - * - * - |result !== null| - * - |pos < input.length| - * - |rightmostFailuresExpected| may or may not contain something - * - * 3. The parser did not successfully parse any part of the input. - * - * - |result === null| - * - |pos === 0| - * - |rightmostFailuresExpected| contains at least one failure - * - * All code following this comment (including called functions) must - * handle these states. - */ - if (result === null || pos !== input.length) { - var offset = Math.max(pos, rightmostFailuresPos); - var found = offset < input.length ? input.charAt(offset) : null; - var errorPosition = computeErrorPosition(); - new this.SyntaxError( - cleanupExpected(rightmostFailuresExpected), - found, - offset, - errorPosition.line, - errorPosition.column - ); - return -1; - } - return data; - }, - /* Returns the parser source code. */ - toSource: function() { return this._source; } - }; - /* Thrown when a parser encounters a syntax error. */ - result.SyntaxError = function(expected, found, offset, line, column) { - function buildMessage(expected, found) { - var expectedHumanized, foundHumanized; - switch (expected.length) { - case 0: - expectedHumanized = "end of input"; - break; - case 1: - expectedHumanized = expected[0]; - break; - default: - expectedHumanized = expected.slice(0, expected.length - 1).join(", ") - + " or " - + expected[expected.length - 1]; - } - foundHumanized = found ? quote(found) : "end of input"; - return "Expected " + expectedHumanized + " but " + foundHumanized + " found."; - } - this.name = "SyntaxError"; - this.expected = expected; - this.found = found; - this.message = buildMessage(expected, found); - this.offset = offset; - this.line = line; - this.column = column; - }; - result.SyntaxError.prototype = Error.prototype; - return result; -})(); -},{"./NameAddrHeader":43,"./URI":58}],41:[function(require,module,exports){ -/** - * Dependencies. - */ -var debug = require('debug')('PlivoSIP'); -var adapter = require('webrtc-adapter'); -var pkg = require('../package.json'); - -debug('version %s', pkg.version); - -var C = require('./Constants'); -var Exceptions = require('./Exceptions'); -var Utils = require('./Utils'); -var UA = require('./UA'); -var URI = require('./URI'); -var NameAddrHeader = require('./NameAddrHeader'); -var Grammar = require('./Grammar'); -var WebSocketInterface = require('./WebSocketInterface'); - - -/** - * Expose the JsSIP module. - */ -var JsSIP = module.exports = { - C: C, - Exceptions: Exceptions, - Utils: Utils, - UA: UA, - URI: URI, - NameAddrHeader: NameAddrHeader, - WebSocketInterface: WebSocketInterface, - Grammar: Grammar, - // Expose the debug module. - debug: require('debug'), - // Expose the adapter module. - adapter: adapter -}; - - -Object.defineProperties(JsSIP, { - name: { - get: function() { return pkg.title; } - }, - - version: { - get: function() { return pkg.version; } - } -}); - -},{"../package.json":34,"./Constants":35,"./Exceptions":39,"./Grammar":40,"./NameAddrHeader":43,"./UA":57,"./URI":58,"./Utils":59,"./WebSocketInterface":60,"debug":11,"webrtc-adapter":24}],42:[function(require,module,exports){ -module.exports = Message; - - -/** - * Dependencies. - */ -var util = require('util'); -var events = require('events'); -var JsSIP_C = require('./Constants'); -var SIPMessage = require('./SIPMessage'); -var Utils = require('./Utils'); -var RequestSender = require('./RequestSender'); -var Transactions = require('./Transactions'); -var Exceptions = require('./Exceptions'); - - -function Message(ua) { - this.ua = ua; - - // Custom message empty object for high level use - this.data = {}; - - events.EventEmitter.call(this); -} - -util.inherits(Message, events.EventEmitter); - - -Message.prototype.send = function(target, body, options) { - var request_sender, event, contentType, eventHandlers, extraHeaders, - originalTarget = target; - - if (target === undefined || body === undefined) { - throw new TypeError('Not enough arguments'); - } - - // Check target validity - target = this.ua.normalizeTarget(target); - if (!target) { - throw new TypeError('Invalid target: '+ originalTarget); - } - - // Get call options - options = options || {}; - extraHeaders = options.extraHeaders && options.extraHeaders.slice() || []; - eventHandlers = options.eventHandlers || {}; - contentType = options.contentType || 'text/plain'; - - this.content_type = contentType; - - // Set event handlers - for (event in eventHandlers) { - this.on(event, eventHandlers[event]); - } - - this.closed = false; - this.ua.applicants[this] = this; - - extraHeaders.push('Content-Type: '+ contentType); - - this.request = new SIPMessage.OutgoingRequest(JsSIP_C.MESSAGE, target, this.ua, null, extraHeaders); - - if(body) { - this.request.body = body; - this.content = body; - } else { - this.content = null; - } - - request_sender = new RequestSender(this, this.ua); - - this.newMessage('local', this.request); - - request_sender.send(); -}; - -Message.prototype.receiveResponse = function(response) { - var cause; - - if(this.closed) { - return; - } - switch(true) { - case /^1[0-9]{2}$/.test(response.status_code): - // Ignore provisional responses. - break; - - case /^2[0-9]{2}$/.test(response.status_code): - delete this.ua.applicants[this]; - this.emit('succeeded', { - originator: 'remote', - response: response - }); - break; - - default: - delete this.ua.applicants[this]; - cause = Utils.sipErrorCause(response.status_code); - this.emit('failed', { - originator: 'remote', - response: response, - cause: cause - }); - break; - } -}; - - -Message.prototype.onRequestTimeout = function() { - if(this.closed) { - return; - } - this.emit('failed', { - originator: 'system', - cause: JsSIP_C.causes.REQUEST_TIMEOUT - }); -}; - -Message.prototype.onTransportError = function() { - if(this.closed) { - return; - } - this.emit('failed', { - originator: 'system', - cause: JsSIP_C.causes.CONNECTION_ERROR - }); -}; - -Message.prototype.close = function() { - this.closed = true; - delete this.ua.applicants[this]; -}; - -Message.prototype.init_incoming = function(request) { - var transaction; - - this.request = request; - this.content_type = request.getHeader('Content-Type'); - - if (request.body) { - this.content = request.body; - } else { - this.content = null; - } - - this.newMessage('remote', request); - - transaction = this.ua.transactions.nist[request.via_branch]; - - if (transaction && (transaction.state === Transactions.C.STATUS_TRYING || transaction.state === Transactions.C.STATUS_PROCEEDING)) { - request.reply(200); - } -}; - -/** - * Accept the incoming Message - * Only valid for incoming Messages - */ -Message.prototype.accept = function(options) { - options = options || {}; - - var - extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], - body = options.body; - - if (this.direction !== 'incoming') { - throw new Exceptions.NotSupportedError('"accept" not supported for outgoing Message'); - } - - this.request.reply(200, null, extraHeaders, body); -}; - -/** - * Reject the incoming Message - * Only valid for incoming Messages - */ -Message.prototype.reject = function(options) { - options = options || {}; - - var - status_code = options.status_code || 480, - reason_phrase = options.reason_phrase, - extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], - body = options.body; - - if (this.direction !== 'incoming') { - throw new Exceptions.NotSupportedError('"reject" not supported for outgoing Message'); - } - - if (status_code < 300 || status_code >= 700) { - throw new TypeError('Invalid status_code: '+ status_code); - } - - this.request.reply(status_code, reason_phrase, extraHeaders, body); -}; - -/** - * Internal Callbacks - */ - -Message.prototype.newMessage = function(originator, request) { - if (originator === 'remote') { - this.direction = 'incoming'; - this.local_identity = request.to; - this.remote_identity = request.from; - } else if (originator === 'local'){ - this.direction = 'outgoing'; - this.local_identity = request.from; - this.remote_identity = request.to; - } - - this.ua.newMessage({ - originator: originator, - message: this, - request: request - }); -}; - -},{"./Constants":35,"./Exceptions":39,"./RequestSender":51,"./SIPMessage":52,"./Transactions":55,"./Utils":59,"events":13,"util":23}],43:[function(require,module,exports){ -module.exports = NameAddrHeader; - - -/** - * Dependencies. - */ -var URI = require('./URI'); -var Grammar = require('./Grammar'); - - -function NameAddrHeader(uri, display_name, parameters) { - var param; - - // Checks - if(!uri || !(uri instanceof URI)) { - throw new TypeError('missing or invalid "uri" parameter'); - } - - // Initialize parameters - this.uri = uri; - this.parameters = {}; - - for (param in parameters) { - this.setParam(param, parameters[param]); - } - - Object.defineProperties(this, { - display_name: { - get: function() { return display_name; }, - set: function(value) { - display_name = (value === 0) ? '0' : value; - } - } - }); -} - -NameAddrHeader.prototype = { - setParam: function(key, value) { - if (key) { - this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString(); - } - }, - - getParam: function(key) { - if(key) { - return this.parameters[key.toLowerCase()]; - } - }, - - hasParam: function(key) { - if(key) { - return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false; - } - }, - - deleteParam: function(parameter) { - var value; - parameter = parameter.toLowerCase(); - if (this.parameters.hasOwnProperty(parameter)) { - value = this.parameters[parameter]; - delete this.parameters[parameter]; - return value; - } - }, - - clearParams: function() { - this.parameters = {}; - }, - - clone: function() { - return new NameAddrHeader( - this.uri.clone(), - this.display_name, - JSON.parse(JSON.stringify(this.parameters))); - }, - - toString: function() { - var body, parameter; - - body = (this.display_name || this.display_name === 0) ? '"' + this.display_name + '" ' : ''; - body += '<' + this.uri.toString() + '>'; - - for (parameter in this.parameters) { - body += ';' + parameter; - - if (this.parameters[parameter] !== null) { - body += '='+ this.parameters[parameter]; - } - } - - return body; - } -}; - - -/** - * Parse the given string and returns a NameAddrHeader instance or undefined if - * it is an invalid NameAddrHeader. - */ -NameAddrHeader.parse = function(name_addr_header) { - name_addr_header = Grammar.parse(name_addr_header,'Name_Addr_Header'); - - if (name_addr_header !== -1) { - return name_addr_header; - } else { - return undefined; - } -}; - -},{"./Grammar":40,"./URI":58}],44:[function(require,module,exports){ -var Parser = {}; - -module.exports = Parser; - - -/** - * Dependencies. - */ -var debugerror = require('debug')('PlivoSIP:ERROR:Parser'); -debugerror.log = console.warn.bind(console); -var Grammar = require('./Grammar'); -var SIPMessage = require('./SIPMessage'); - - -/** - * Extract and parse every header of a SIP message. - */ -function getHeader(data, headerStart) { - var - // 'start' position of the header. - start = headerStart, - // 'end' position of the header. - end = 0, - // 'partial end' position of the header. - partialEnd = 0; - - //End of message. - if (data.substring(start, start + 2).match(/(^\r\n)/)) { - return -2; - } - - while(end === 0) { - // Partial End of Header. - partialEnd = data.indexOf('\r\n', start); - - // 'indexOf' returns -1 if the value to be found never occurs. - if (partialEnd === -1) { - return partialEnd; - } - - if(!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/)) { - // Not the end of the message. Continue from the next position. - start = partialEnd + 2; - } else { - end = partialEnd; - } - } - - return end; -} - -function parseHeader(message, data, headerStart, headerEnd) { - var header, idx, length, parsed, - hcolonIndex = data.indexOf(':', headerStart), - headerName = data.substring(headerStart, hcolonIndex).trim(), - headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); - - // If header-field is well-known, parse it. - switch(headerName.toLowerCase()) { - case 'via': - case 'v': - message.addHeader('via', headerValue); - if(message.getHeaders('via').length === 1) { - parsed = message.parseHeader('Via'); - if(parsed) { - message.via = parsed; - message.via_branch = parsed.branch; - } - } else { - parsed = 0; - } - break; - case 'from': - case 'f': - message.setHeader('from', headerValue); - parsed = message.parseHeader('from'); - if(parsed) { - message.from = parsed; - message.from_tag = parsed.getParam('tag'); - } - break; - case 'to': - case 't': - message.setHeader('to', headerValue); - parsed = message.parseHeader('to'); - if(parsed) { - message.to = parsed; - message.to_tag = parsed.getParam('tag'); - } - break; - case 'record-route': - parsed = Grammar.parse(headerValue, 'Record_Route'); - - if (parsed === -1) { - parsed = undefined; - } else { - length = parsed.length; - for (idx = 0; idx < length; idx++) { - header = parsed[idx]; - message.addHeader('record-route', headerValue.substring(header.possition, header.offset)); - message.headers['Record-Route'][message.getHeaders('record-route').length - 1].parsed = header.parsed; - } - } - break; - case 'call-id': - case 'i': - message.setHeader('call-id', headerValue); - parsed = message.parseHeader('call-id'); - if(parsed) { - message.call_id = headerValue; - } - break; - case 'contact': - case 'm': - parsed = Grammar.parse(headerValue, 'Contact'); - - if (parsed === -1) { - parsed = undefined; - } else { - length = parsed.length; - for (idx = 0; idx < length; idx++) { - header = parsed[idx]; - message.addHeader('contact', headerValue.substring(header.possition, header.offset)); - message.headers.Contact[message.getHeaders('contact').length - 1].parsed = header.parsed; - } - } - break; - case 'content-length': - case 'l': - message.setHeader('content-length', headerValue); - parsed = message.parseHeader('content-length'); - break; - case 'content-type': - case 'c': - message.setHeader('content-type', headerValue); - parsed = message.parseHeader('content-type'); - break; - case 'cseq': - message.setHeader('cseq', headerValue); - parsed = message.parseHeader('cseq'); - if(parsed) { - message.cseq = parsed.value; - } - if(message instanceof SIPMessage.IncomingResponse) { - message.method = parsed.method; - } - break; - case 'max-forwards': - message.setHeader('max-forwards', headerValue); - parsed = message.parseHeader('max-forwards'); - break; - case 'www-authenticate': - message.setHeader('www-authenticate', headerValue); - parsed = message.parseHeader('www-authenticate'); - break; - case 'proxy-authenticate': - message.setHeader('proxy-authenticate', headerValue); - parsed = message.parseHeader('proxy-authenticate'); - break; - case 'session-expires': - case 'x': - message.setHeader('session-expires', headerValue); - parsed = message.parseHeader('session-expires'); - if (parsed) { - message.session_expires = parsed.expires; - message.session_expires_refresher = parsed.refresher; - } - break; - case 'refer-to': - case 'r': - message.setHeader('refer-to', headerValue); - parsed = message.parseHeader('refer-to'); - if(parsed) { - message.refer_to = parsed; - } - break; - case 'replaces': - message.setHeader('replaces', headerValue); - parsed = message.parseHeader('replaces'); - if(parsed) { - message.replaces = parsed; - } - break; - case 'event': - case 'o': - message.setHeader('event', headerValue); - parsed = message.parseHeader('event'); - if(parsed) { - message.event = parsed; - } - break; - default: - // Do not parse this header. - message.setHeader(headerName, headerValue); - parsed = 0; - } - - if (parsed === undefined) { - return { - error: 'error parsing header "'+ headerName +'"' - }; - } else { - return true; - } -} - - -/** - * Parse SIP Message - */ -Parser.parseMessage = function(data, ua) { - var message, firstLine, contentLength, bodyStart, parsed, - headerStart = 0, - headerEnd = data.indexOf('\r\n'); - - if(headerEnd === -1) { - debugerror('parseMessage() | no CRLF found, not a SIP message'); - return; - } - - // Parse first line. Check if it is a Request or a Reply. - firstLine = data.substring(0, headerEnd); - parsed = Grammar.parse(firstLine, 'Request_Response'); - - if(parsed === -1) { - debugerror('parseMessage() | error parsing first line of SIP message: "' + firstLine + '"'); - return; - } else if(!parsed.status_code) { - message = new SIPMessage.IncomingRequest(ua); - message.method = parsed.method; - message.ruri = parsed.uri; - } else { - message = new SIPMessage.IncomingResponse(); - message.status_code = parsed.status_code; - message.reason_phrase = parsed.reason_phrase; - } - - message.data = data; - headerStart = headerEnd + 2; - - /* Loop over every line in data. Detect the end of each header and parse - * it or simply add to the headers collection. - */ - while(true) { - headerEnd = getHeader(data, headerStart); - - // The SIP message has normally finished. - if(headerEnd === -2) { - bodyStart = headerStart + 2; - break; - } - // data.indexOf returned -1 due to a malformed message. - else if(headerEnd === -1) { - debugerror('parseMessage() | malformed message'); - return; - } - - parsed = parseHeader(message, data, headerStart, headerEnd); - - if(parsed !== true) { - debugerror('parseMessage() |', parsed.error); - return; - } - - headerStart = headerEnd + 2; - } - - /* RFC3261 18.3. - * If there are additional bytes in the transport packet - * beyond the end of the body, they MUST be discarded. - */ - if(message.hasHeader('content-length')) { - contentLength = message.getHeader('content-length'); - message.body = data.substr(bodyStart, contentLength); - } else { - message.body = data.substring(bodyStart); - } - - return message; -}; - -},{"./Grammar":40,"./SIPMessage":52,"debug":11}],45:[function(require,module,exports){ -/* globals RTCPeerConnection: false, RTCSessionDescription: false */ - -module.exports = RTCSession; - - -var C = { - // RTCSession states - STATUS_NULL: 0, - STATUS_INVITE_SENT: 1, - STATUS_1XX_RECEIVED: 2, - STATUS_INVITE_RECEIVED: 3, - STATUS_WAITING_FOR_ANSWER: 4, - STATUS_ANSWERED: 5, - STATUS_WAITING_FOR_ACK: 6, - STATUS_CANCELED: 7, - STATUS_TERMINATED: 8, - STATUS_CONFIRMED: 9 -}; - -/** - * Expose C object. - */ -RTCSession.C = C; - - -/** - * Dependencies. - */ -var util = require('util'); -var events = require('events'); -var debug = require('debug')('PlivoSIP:RTCSession'); -var debugerror = require('debug')('PlivoSIP:ERROR:RTCSession'); -debugerror.log = console.warn.bind(console); -var sdp_transform = require('sdp-transform'); -var JsSIP_C = require('./Constants'); -var Exceptions = require('./Exceptions'); -var Transactions = require('./Transactions'); -var Utils = require('./Utils'); -var Timers = require('./Timers'); -var SIPMessage = require('./SIPMessage'); -var Dialog = require('./Dialog'); -var RequestSender = require('./RequestSender'); -var RTCSession_Request = require('./RTCSession/Request'); -var RTCSession_DTMF = require('./RTCSession/DTMF'); -var RTCSession_ReferNotifier = require('./RTCSession/ReferNotifier'); -var RTCSession_ReferSubscriber = require('./RTCSession/ReferSubscriber'); - - -/** - * Local variables. - */ -var holdMediaTypes = ['audio', 'video']; - - -function RTCSession(ua) { - debug('new'); - - this.ua = ua; - this.status = C.STATUS_NULL; - this.dialog = null; - this.earlyDialogs = {}; - this.connection = null; // The RTCPeerConnection instance (public attribute). - - // RTCSession confirmation flag - this.is_confirmed = false; - - // is late SDP being negotiated - this.late_sdp = false; - - // Default rtcOfferConstraints and rtcAnswerConstrainsts (passed in connect() or answer()). - this.rtcOfferConstraints = null; - this.rtcAnswerConstraints = null; - - // Local MediaStream. - this.localMediaStream = null; - this.localMediaStreamLocallyGenerated = false; - - // Flag to indicate PeerConnection ready for new actions. - this.rtcReady = true; - - // SIP Timers - this.timers = { - ackTimer: null, - expiresTimer: null, - invite2xxTimer: null, - userNoAnswerTimer: null - }; - - // Session info - this.direction = null; - this.local_identity = null; - this.remote_identity = null; - this.start_time = null; - this.end_time = null; - this.tones = null; - - // Mute/Hold state - this.audioMuted = false; - this.videoMuted = false; - this.localHold = false; - this.remoteHold = false; - - // Session Timers (RFC 4028) - this.sessionTimers = { - enabled: this.ua.configuration.session_timers, - defaultExpires: JsSIP_C.SESSION_EXPIRES, - currentExpires: null, - running: false, - refresher: false, - timer: null // A setTimeout. - }; - - // Map of ReferSubscriber instances indexed by the REFER's CSeq number - this.referSubscribers = {}; - - // Custom session empty object for high level use - this.data = {}; - - // Expose session failed/ended causes as a property of the RTCSession instance - this.causes = JsSIP_C.causes; - - events.EventEmitter.call(this); -} - -util.inherits(RTCSession, events.EventEmitter); - - -/** - * User API - */ - - -RTCSession.prototype.isInProgress = function() { - switch(this.status) { - case C.STATUS_NULL: - case C.STATUS_INVITE_SENT: - case C.STATUS_1XX_RECEIVED: - case C.STATUS_INVITE_RECEIVED: - case C.STATUS_WAITING_FOR_ANSWER: - return true; - default: - return false; - } -}; - - -RTCSession.prototype.isEstablished = function() { - switch(this.status) { - case C.STATUS_ANSWERED: - case C.STATUS_WAITING_FOR_ACK: - case C.STATUS_CONFIRMED: - return true; - default: - return false; - } -}; - - -RTCSession.prototype.isEnded = function() { - switch(this.status) { - case C.STATUS_CANCELED: - case C.STATUS_TERMINATED: - return true; - default: - return false; - } -}; - - -RTCSession.prototype.isMuted = function() { - return { - audio: this.audioMuted, - video: this.videoMuted - }; -}; - - -RTCSession.prototype.isOnHold = function() { - return { - local: this.localHold, - remote: this.remoteHold - }; -}; - - -/** - * Check if RTCSession is ready for an outgoing re-INVITE or UPDATE with SDP. - */ - RTCSession.prototype.isReadyToReOffer = function() { - if (! this.rtcReady) { - debug('isReadyToReOffer() | internal WebRTC status not ready'); - return false; - } - - // No established yet. - if (! this.dialog) { - debug('isReadyToReOffer() | session not established yet'); - return false; - } - - // Another INVITE transaction is in progress - if (this.dialog.uac_pending_reply === true || this.dialog.uas_pending_reply === true) { - debug('isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress'); - return false; - } - - return true; -}; - - - -RTCSession.prototype.connect = function(target, options, initCallback) { - debug('connect()'); - - options = options || {}; - - var event, requestParams, - originalTarget = target, - eventHandlers = options.eventHandlers || {}, - extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], - mediaConstraints = options.mediaConstraints || {audio: true, video: true}, - mediaStream = options.mediaStream || null, - pcConfig = options.pcConfig || {iceServers:[]}, - rtcConstraints = options.rtcConstraints || null, - rtcOfferConstraints = options.rtcOfferConstraints || null; - - this.rtcOfferConstraints = rtcOfferConstraints; - this.rtcAnswerConstraints = options.rtcAnswerConstraints || null; - - // Session Timers. - if (this.sessionTimers.enabled) { - if (Utils.isDecimal(options.sessionTimersExpires)) { - if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) { - this.sessionTimers.defaultExpires = options.sessionTimersExpires; - } - else { - this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES; - } - } - } - - this.data = options.data || this.data; - - if (target === undefined) { - throw new TypeError('Not enough arguments'); - } - - // Check WebRTC support. - if (!window.RTCPeerConnection) { - throw new Exceptions.NotSupportedError('WebRTC not supported'); - } - - // Check target validity - target = this.ua.normalizeTarget(target); - if (!target) { - throw new TypeError('Invalid target: '+ originalTarget); - } - - // Check Session Status - if (this.status !== C.STATUS_NULL) { - throw new Exceptions.InvalidStateError(this.status); - } - - // Set event handlers - for (event in eventHandlers) { - this.on(event, eventHandlers[event]); - } - - // Session parameter initialization - this.from_tag = Utils.newTag(); - - // Set anonymous property - this.anonymous = options.anonymous || false; - - // OutgoingSession specific parameters - this.isCanceled = false; - - requestParams = {from_tag: this.from_tag}; - - this.contact = this.ua.contact.toString({ - anonymous: this.anonymous, - outbound: true - }); - - if (this.anonymous) { - requestParams.from_display_name = 'Anonymous'; - requestParams.from_uri = 'sip:anonymous@anonymous.invalid'; - - extraHeaders.push('P-Preferred-Identity: '+ this.ua.configuration.uri.toString()); - extraHeaders.push('Privacy: id'); - } - - extraHeaders.push('Contact: '+ this.contact); - extraHeaders.push('Content-Type: application/sdp'); - if (this.sessionTimers.enabled) { - extraHeaders.push('Session-Expires: ' + this.sessionTimers.defaultExpires); - } - - this.request = new SIPMessage.OutgoingRequest(JsSIP_C.INVITE, target, this.ua, requestParams, extraHeaders); - - this.id = this.request.call_id + this.from_tag; - - // Create a new RTCPeerConnection instance. - createRTCConnection.call(this, pcConfig, rtcConstraints); - - // Save the session into the ua sessions collection. - this.ua.sessions[this.id] = this; - - // Set internal properties - this.direction = 'outgoing'; - this.local_identity = this.request.from; - this.remote_identity = this.request.to; - - // User explicitly provided a newRTCSession callback for this session - if (initCallback) { - initCallback(this); - } else { - newRTCSession.call(this, 'local', this.request); - } - - sendInitialRequest.call(this, mediaConstraints, rtcOfferConstraints, mediaStream); -}; - - -RTCSession.prototype.init_incoming = function(request, initCallback) { - debug('init_incoming()'); - - var expires, - self = this, - contentType = request.getHeader('Content-Type'); - - // Check body and content type - if (request.body && (contentType !== 'application/sdp')) { - request.reply(415); - return; - } - - // Session parameter initialization - this.status = C.STATUS_INVITE_RECEIVED; - this.from_tag = request.from_tag; - this.id = request.call_id + this.from_tag; - this.request = request; - this.contact = this.ua.contact.toString(); - - // Save the session into the ua sessions collection. - this.ua.sessions[this.id] = this; - - // Get the Expires header value if exists - if (request.hasHeader('expires')) { - expires = request.getHeader('expires') * 1000; - } - - /* Set the to_tag before - * replying a response code that will create a dialog. - */ - request.to_tag = Utils.newTag(); - - // An error on dialog creation will fire 'failed' event - if (! createDialog.call(this, request, 'UAS', true)) { - request.reply(500, 'Missing Contact header field'); - return; - } - - if (request.body) { - this.late_sdp = false; - } - else { - this.late_sdp = true; - } - - this.status = C.STATUS_WAITING_FOR_ANSWER; - - // Set userNoAnswerTimer - this.timers.userNoAnswerTimer = setTimeout(function() { - request.reply(408); - failed.call(self, 'local',null, JsSIP_C.causes.NO_ANSWER); - }, this.ua.configuration.no_answer_timeout - ); - - /* Set expiresTimer - * RFC3261 13.3.1 - */ - if (expires) { - this.timers.expiresTimer = setTimeout(function() { - if(self.status === C.STATUS_WAITING_FOR_ANSWER) { - request.reply(487); - failed.call(self, 'system', null, JsSIP_C.causes.EXPIRES); - } - }, expires - ); - } - - // Set internal properties - this.direction = 'incoming'; - this.local_identity = request.to; - this.remote_identity = request.from; - - // A init callback was specifically defined - if (initCallback) { - initCallback(this); - - // Fire 'newRTCSession' event. - } else { - newRTCSession.call(this, 'remote', request); - } - - // The user may have rejected the call in the 'newRTCSession' event. - if (this.status === C.STATUS_TERMINATED) { - return; - } - - // Reply 180. - request.reply(180, null, ['Contact: ' + self.contact]); - - // Fire 'progress' event. - // TODO: Document that 'response' field in 'progress' event is null for - // incoming calls. - progress.call(self, 'local', null); -}; - - -/** - * Answer the call. - */ -RTCSession.prototype.answer = function(options) { - debug('answer()'); - - options = options || {}; - - var idx, length, sdp, tracks, - peerHasAudioLine = false, - peerHasVideoLine = false, - peerOffersFullAudio = false, - peerOffersFullVideo = false, - self = this, - request = this.request, - extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], - mediaConstraints = options.mediaConstraints || {}, - mediaStream = options.mediaStream || null, - pcConfig = options.pcConfig || {iceServers:[]}, - rtcConstraints = options.rtcConstraints || null, - rtcAnswerConstraints = options.rtcAnswerConstraints || null; - - this.rtcAnswerConstraints = rtcAnswerConstraints; - this.rtcOfferConstraints = options.rtcOfferConstraints || null; - - // Session Timers. - if (this.sessionTimers.enabled) { - if (Utils.isDecimal(options.sessionTimersExpires)) { - if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) { - this.sessionTimers.defaultExpires = options.sessionTimersExpires; - } - else { - this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES; - } - } - } - - this.data = options.data || this.data; - - // Check Session Direction and Status - if (this.direction !== 'incoming') { - throw new Exceptions.NotSupportedError('"answer" not supported for outgoing RTCSession'); - } else if (this.status !== C.STATUS_WAITING_FOR_ANSWER) { - throw new Exceptions.InvalidStateError(this.status); - } - - this.status = C.STATUS_ANSWERED; - - // An error on dialog creation will fire 'failed' event - if (! createDialog.call(this, request, 'UAS')) { - request.reply(500, 'Error creating dialog'); - return; - } - - clearTimeout(this.timers.userNoAnswerTimer); - - extraHeaders.unshift('Contact: ' + self.contact); - - // Determine incoming media from incoming SDP offer (if any). - sdp = request.parseSDP(); - - // Make sure sdp.media is an array, not the case if there is only one media - if (! Array.isArray(sdp.media)) { - sdp.media = [sdp.media]; - } - - // Go through all medias in SDP to find offered capabilities to answer with - idx = sdp.media.length; - while(idx--) { - var m = sdp.media[idx]; - if (m.type === 'audio') { - peerHasAudioLine = true; - if (!m.direction || m.direction === 'sendrecv') { - peerOffersFullAudio = true; - } - } - if (m.type === 'video') { - peerHasVideoLine = true; - if (!m.direction || m.direction === 'sendrecv') { - peerOffersFullVideo = true; - } - } - } - - // Remove audio from mediaStream if suggested by mediaConstraints - if (mediaStream && mediaConstraints.audio === false) { - tracks = mediaStream.getAudioTracks(); - length = tracks.length; - for (idx=0; idx= 700)) { - throw new TypeError('Invalid status_code: '+ status_code); - } else if (status_code) { - reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; - cancel_reason = 'SIP ;cause=' + status_code + ' ;text="' + reason_phrase + '"'; - } - - // Check Session Status - if (this.status === C.STATUS_NULL) { - this.isCanceled = true; - this.cancelReason = cancel_reason; - } else if (this.status === C.STATUS_INVITE_SENT) { - this.isCanceled = true; - this.cancelReason = cancel_reason; - } else if(this.status === C.STATUS_1XX_RECEIVED) { - this.request.cancel(cancel_reason); - } - - this.status = C.STATUS_CANCELED; - - failed.call(this, 'local', null, JsSIP_C.causes.CANCELED); - break; - - // - UAS - - case C.STATUS_WAITING_FOR_ANSWER: - case C.STATUS_ANSWERED: - debug('rejecting session'); - - status_code = status_code || 480; - - if (status_code < 300 || status_code >= 700) { - throw new TypeError('Invalid status_code: '+ status_code); - } - - this.request.reply(status_code, reason_phrase, extraHeaders, body); - failed.call(this, 'local', null, JsSIP_C.causes.REJECTED); - break; - - case C.STATUS_WAITING_FOR_ACK: - case C.STATUS_CONFIRMED: - debug('terminating session'); - - reason_phrase = options.reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; - - if (status_code && (status_code < 200 || status_code >= 700)) { - throw new TypeError('Invalid status_code: '+ status_code); - } else if (status_code) { - extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"'); - } - - /* RFC 3261 section 15 (Terminating a session): - * - * "...the callee's UA MUST NOT send a BYE on a confirmed dialog - * until it has received an ACK for its 2xx response or until the server - * transaction times out." - */ - if (this.status === C.STATUS_WAITING_FOR_ACK && - this.direction === 'incoming' && - this.request.server_transaction.state !== Transactions.C.STATUS_TERMINATED) { - - // Save the dialog for later restoration - dialog = this.dialog; - - // Send the BYE as soon as the ACK is received... - this.receiveRequest = function(request) { - if(request.method === JsSIP_C.ACK) { - sendRequest.call(this, JsSIP_C.BYE, { - extraHeaders: extraHeaders, - body: body - }); - dialog.terminate(); - } - }; - - // .., or when the INVITE transaction times out - this.request.server_transaction.on('stateChanged', function(){ - if (this.state === Transactions.C.STATUS_TERMINATED) { - sendRequest.call(self, JsSIP_C.BYE, { - extraHeaders: extraHeaders, - body: body - }); - dialog.terminate(); - } - }); - - ended.call(this, 'local', null, cause); - - // Restore the dialog into 'this' in order to be able to send the in-dialog BYE :-) - this.dialog = dialog; - - // Restore the dialog into 'ua' so the ACK can reach 'this' session - this.ua.dialogs[dialog.id.toString()] = dialog; - - } else { - sendRequest.call(this, JsSIP_C.BYE, { - extraHeaders: extraHeaders, - body: body - }); - - ended.call(this, 'local', null, cause); - } - } -}; - - -RTCSession.prototype.close = function() { - debug('close()'); - - var idx; - - if (this.status === C.STATUS_TERMINATED) { - return; - } - - // Terminate RTC. - if (this.connection) { - try { - this.connection.close(); - } catch(error) { - debugerror('close() | error closing the RTCPeerConnection: %o', error); - } - } - - // Close local MediaStream if it was not given by the user. - if (this.localMediaStream && this.localMediaStreamLocallyGenerated) { - debug('close() | closing local MediaStream'); - - Utils.closeMediaStream(this.localMediaStream); - } - - // Terminate signaling. - - // Clear SIP timers - for(idx in this.timers) { - clearTimeout(this.timers[idx]); - } - - // Clear Session Timers. - clearTimeout(this.sessionTimers.timer); - - // Terminate confirmed dialog - if (this.dialog) { - this.dialog.terminate(); - delete this.dialog; - } - - // Terminate early dialogs - for(idx in this.earlyDialogs) { - this.earlyDialogs[idx].terminate(); - delete this.earlyDialogs[idx]; - } - - this.status = C.STATUS_TERMINATED; - - delete this.ua.sessions[this.id]; -}; - - -RTCSession.prototype.sendDTMF = function(tones, options) { - debug('sendDTMF() | tones: %s', tones); - - var duration, interToneGap, - position = 0, - self = this; - - options = options || {}; - duration = options.duration || null; - interToneGap = options.interToneGap || null; - - if (tones === undefined) { - throw new TypeError('Not enough arguments'); - } - - // Check Session Status - if (this.status !== C.STATUS_CONFIRMED && this.status !== C.STATUS_WAITING_FOR_ACK) { - throw new Exceptions.InvalidStateError(this.status); - } - - // Convert to string - if(typeof tones === 'number') { - tones = tones.toString(); - } - - // Check tones - if (!tones || typeof tones !== 'string' || !tones.match(/^[0-9A-D#*,]+$/i)) { - throw new TypeError('Invalid tones: '+ tones); - } - - // Check duration - if (duration && !Utils.isDecimal(duration)) { - throw new TypeError('Invalid tone duration: '+ duration); - } else if (!duration) { - duration = RTCSession_DTMF.C.DEFAULT_DURATION; - } else if (duration < RTCSession_DTMF.C.MIN_DURATION) { - debug('"duration" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_DURATION+ ' milliseconds'); - duration = RTCSession_DTMF.C.MIN_DURATION; - } else if (duration > RTCSession_DTMF.C.MAX_DURATION) { - debug('"duration" value is greater than the maximum allowed, setting it to '+ RTCSession_DTMF.C.MAX_DURATION +' milliseconds'); - duration = RTCSession_DTMF.C.MAX_DURATION; - } else { - duration = Math.abs(duration); - } - options.duration = duration; - - // Check interToneGap - if (interToneGap && !Utils.isDecimal(interToneGap)) { - throw new TypeError('Invalid interToneGap: '+ interToneGap); - } else if (!interToneGap) { - interToneGap = RTCSession_DTMF.C.DEFAULT_INTER_TONE_GAP; - } else if (interToneGap < RTCSession_DTMF.C.MIN_INTER_TONE_GAP) { - debug('"interToneGap" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_INTER_TONE_GAP +' milliseconds'); - interToneGap = RTCSession_DTMF.C.MIN_INTER_TONE_GAP; - } else { - interToneGap = Math.abs(interToneGap); - } - - if (this.tones) { - // Tones are already queued, just add to the queue - this.tones += tones; - return; - } - - this.tones = tones; - - // Send the first tone - _sendDTMF(); - - function _sendDTMF() { - var tone, timeout; - - if (self.status === C.STATUS_TERMINATED || !self.tones || position >= self.tones.length) { - // Stop sending DTMF - self.tones = null; - return; - } - - tone = self.tones[position]; - position += 1; - - if (tone === ',') { - timeout = 2000; - } else { - var dtmf = new RTCSession_DTMF(self); - options.eventHandlers = { - failed: function() { self.tones = null; } - }; - dtmf.send(tone, options); - timeout = duration + interToneGap; - } - - // Set timeout for the next tone - setTimeout(_sendDTMF, timeout); - } -}; - - -/** - * Mute - */ -RTCSession.prototype.mute = function(options) { - debug('mute()'); - - options = options || {audio:true, video:false}; - - var - audioMuted = false, - videoMuted = false; - - if (this.audioMuted === false && options.audio) { - audioMuted = true; - this.audioMuted = true; - toogleMuteAudio.call(this, true); - } - - if (this.videoMuted === false && options.video) { - videoMuted = true; - this.videoMuted = true; - toogleMuteVideo.call(this, true); - } - - if (audioMuted === true || videoMuted === true) { - onmute.call(this, { - audio: audioMuted, - video: videoMuted - }); - } -}; - - -/** - * Unmute - */ -RTCSession.prototype.unmute = function(options) { - debug('unmute()'); - - options = options || {audio:true, video:true}; - - var - audioUnMuted = false, - videoUnMuted = false; - - if (this.audioMuted === true && options.audio) { - audioUnMuted = true; - this.audioMuted = false; - - if (this.localHold === false) { - toogleMuteAudio.call(this, false); - } - } - - if (this.videoMuted === true && options.video) { - videoUnMuted = true; - this.videoMuted = false; - - if (this.localHold === false) { - toogleMuteVideo.call(this, false); - } - } - - if (audioUnMuted === true || videoUnMuted === true) { - onunmute.call(this, { - audio: audioUnMuted, - video: videoUnMuted - }); - } -}; - - -/** - * Hold - */ -RTCSession.prototype.hold = function(options, done) { - debug('hold()'); - - options = options || {}; - - var self = this, - eventHandlers; - - if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { - return false; - } - - if (this.localHold === true) { - return false; - } - - if (! this.isReadyToReOffer()) { - return false; - } - - this.localHold = true; - onhold.call(this, 'local'); - - eventHandlers = { - succeeded: function() { - if (done) { done(); } - }, - failed: function() { - self.terminate({ - cause: JsSIP_C.causes.WEBRTC_ERROR, - status_code: 500, - reason_phrase: 'Hold Failed' - }); - } - }; - - if (options.useUpdate) { - sendUpdate.call(this, { - sdpOffer: true, - eventHandlers: eventHandlers, - extraHeaders: options.extraHeaders - }); - } else { - sendReinvite.call(this, { - eventHandlers: eventHandlers, - extraHeaders: options.extraHeaders - }); - } - - return true; -}; - - -RTCSession.prototype.unhold = function(options, done) { - debug('unhold()'); - - options = options || {}; - - var self = this, - eventHandlers; - - if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { - return false; - } - - if (this.localHold === false) { - return false; - } - - if (! this.isReadyToReOffer()) { - return false; - } - - this.localHold = false; - onunhold.call(this, 'local'); - - eventHandlers = { - succeeded: function() { - if (done) { done(); } - }, - failed: function() { - self.terminate({ - cause: JsSIP_C.causes.WEBRTC_ERROR, - status_code: 500, - reason_phrase: 'Unhold Failed' - }); - } - }; - - if (options.useUpdate) { - sendUpdate.call(this, { - sdpOffer: true, - eventHandlers: eventHandlers, - extraHeaders: options.extraHeaders - }); - } else { - sendReinvite.call(this, { - eventHandlers: eventHandlers, - extraHeaders: options.extraHeaders - }); - } - - return true; -}; - - -RTCSession.prototype.renegotiate = function(options, done) { - debug('renegotiate()'); - - options = options || {}; - - var self = this, - eventHandlers, - rtcOfferConstraints = options.rtcOfferConstraints || null; - - if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { - return false; - } - - if (! this.isReadyToReOffer()) { - return false; - } - - eventHandlers = { - succeeded: function() { - if (done) { done(); } - }, - failed: function() { - self.terminate({ - cause: JsSIP_C.causes.WEBRTC_ERROR, - status_code: 500, - reason_phrase: 'Media Renegotiation Failed' - }); - } - }; - - setLocalMediaStatus.call(this); - - if (options.useUpdate) { - sendUpdate.call(this, { - sdpOffer: true, - eventHandlers: eventHandlers, - rtcOfferConstraints: rtcOfferConstraints, - extraHeaders: options.extraHeaders - }); - } else { - sendReinvite.call(this, { - eventHandlers: eventHandlers, - rtcOfferConstraints: rtcOfferConstraints, - extraHeaders: options.extraHeaders - }); - } - - return true; -}; - -/** - * Refer - */ -RTCSession.prototype.refer = function(target, options) { - debug('refer()'); - - var self = this, - originalTarget = target, - referSubscriber, - id; - - if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { - return false; - } - - // Check target validity - target = this.ua.normalizeTarget(target); - if (!target) { - throw new TypeError('Invalid target: '+ originalTarget); - } - - referSubscriber = new RTCSession_ReferSubscriber(this); - referSubscriber.sendRefer(target, options); - - // Store in the map - id = referSubscriber.outgoingRequest.cseq; - this.referSubscribers[id] = referSubscriber; - - // Listen for ending events so we can remove it from the map - referSubscriber.on('requestFailed', function() { - delete self.referSubscribers[id]; - }); - referSubscriber.on('accepted', function() { - delete self.referSubscribers[id]; - }); - referSubscriber.on('failed', function() { - delete self.referSubscribers[id]; - }); - - return referSubscriber; -}; - -/** - * In dialog Request Reception - */ -RTCSession.prototype.receiveRequest = function(request) { - debug('receiveRequest()'); - - var contentType, - self = this; - - if(request.method === JsSIP_C.CANCEL) { - /* RFC3261 15 States that a UAS may have accepted an invitation while a CANCEL - * was in progress and that the UAC MAY continue with the session established by - * any 2xx response, or MAY terminate with BYE. JsSIP does continue with the - * established session. So the CANCEL is processed only if the session is not yet - * established. - */ - - /* - * Terminate the whole session in case the user didn't accept (or yet send the answer) - * nor reject the request opening the session. - */ - if(this.status === C.STATUS_WAITING_FOR_ANSWER || this.status === C.STATUS_ANSWERED) { - this.status = C.STATUS_CANCELED; - this.request.reply(487); - failed.call(this, 'remote', request, JsSIP_C.causes.CANCELED); - } - } else { - // Requests arriving here are in-dialog requests. - switch(request.method) { - case JsSIP_C.ACK: - if (this.status !== C.STATUS_WAITING_FOR_ACK) { - return; - } - - // Update signaling status. - this.status = C.STATUS_CONFIRMED; - - clearTimeout(this.timers.ackTimer); - clearTimeout(this.timers.invite2xxTimer); - - if (this.late_sdp) { - if (!request.body) { - this.terminate({ - cause: JsSIP_C.causes.MISSING_SDP, - status_code: 400 - }); - break; - } - - var e = {originator:'remote', type:'answer', sdp:request.body}; - var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); - - this.emit('sdp', e); - - this.connection.setRemoteDescription(answer) - .then(function() { - if (!self.is_confirmed) { - confirmed.call(self, 'remote', request); - } - }) - .catch(function(error) { - self.terminate({ - cause: JsSIP_C.causes.BAD_MEDIA_DESCRIPTION, - status_code: 488 - }); - - self.emit('peerconnection:setremotedescriptionfailed', error); - }); - } - else { - if (!this.is_confirmed) { - confirmed.call(this, 'remote', request); - } - } - - break; - case JsSIP_C.BYE: - if(this.status === C.STATUS_CONFIRMED) { - request.reply(200); - ended.call(this, 'remote', request, JsSIP_C.causes.BYE); - } - else if (this.status === C.STATUS_INVITE_RECEIVED) { - request.reply(200); - this.request.reply(487, 'BYE Received'); - ended.call(this, 'remote', request, JsSIP_C.causes.BYE); - } - else { - request.reply(403, 'Wrong Status'); - } - break; - case JsSIP_C.INVITE: - if(this.status === C.STATUS_CONFIRMED) { - if (request.hasHeader('replaces')) { - receiveReplaces.call(this, request); - } else { - receiveReinvite.call(this, request); - } - } - else { - request.reply(403, 'Wrong Status'); - } - break; - case JsSIP_C.INFO: - if(this.status === C.STATUS_CONFIRMED || this.status === C.STATUS_WAITING_FOR_ACK || this.status === C.STATUS_INVITE_RECEIVED) { - contentType = request.getHeader('content-type'); - if (contentType && (contentType.match(/^application\/dtmf-relay/i))) { - new RTCSession_DTMF(this).init_incoming(request); - } - else { - request.reply(415); - } - } - else { - request.reply(403, 'Wrong Status'); - } - break; - case JsSIP_C.UPDATE: - if(this.status === C.STATUS_CONFIRMED) { - receiveUpdate.call(this, request); - } - else { - request.reply(403, 'Wrong Status'); - } - break; - case JsSIP_C.REFER: - if(this.status === C.STATUS_CONFIRMED) { - receiveRefer.call(this, request); - } - else { - request.reply(403, 'Wrong Status'); - } - break; - case JsSIP_C.NOTIFY: - if(this.status === C.STATUS_CONFIRMED) { - receiveNotify.call(this, request); - } - else { - request.reply(403, 'Wrong Status'); - } - break; - default: - request.reply(501); - } - } -}; - - -/** - * Session Callbacks - */ - -RTCSession.prototype.onTransportError = function() { - debugerror('onTransportError()'); - - if(this.status !== C.STATUS_TERMINATED) { - this.terminate({ - status_code: 500, - reason_phrase: JsSIP_C.causes.CONNECTION_ERROR, - cause: JsSIP_C.causes.CONNECTION_ERROR - }); - } -}; - - -RTCSession.prototype.onRequestTimeout = function() { - debug('onRequestTimeout'); - - if(this.status !== C.STATUS_TERMINATED) { - this.terminate({ - status_code: 408, - reason_phrase: JsSIP_C.causes.REQUEST_TIMEOUT, - cause: JsSIP_C.causes.REQUEST_TIMEOUT - }); - } -}; - - -RTCSession.prototype.onDialogError = function() { - debugerror('onDialogError()'); - - if(this.status !== C.STATUS_TERMINATED) { - this.terminate({ - status_code: 500, - reason_phrase: JsSIP_C.causes.DIALOG_ERROR, - cause: JsSIP_C.causes.DIALOG_ERROR - }); - } -}; - - -// Called from DTMF handler. -RTCSession.prototype.newDTMF = function(data) { - debug('newDTMF()'); - - this.emit('newDTMF', data); -}; - - -RTCSession.prototype.resetLocalMedia = function() { - debug('resetLocalMedia()'); - - // Reset all but remoteHold. - this.localHold = false; - this.audioMuted = false; - this.videoMuted = false; - - setLocalMediaStatus.call(this); -}; - - -/** - * Private API. - */ - - -/** - * RFC3261 13.3.1.4 - * Response retransmissions cannot be accomplished by transaction layer - * since it is destroyed when receiving the first 2xx answer - */ -function setInvite2xxTimer(request, body) { - var - self = this, - timeout = Timers.T1; - - this.timers.invite2xxTimer = setTimeout(function invite2xxRetransmission() { - if (self.status !== C.STATUS_WAITING_FOR_ACK) { - return; - } - - request.reply(200, null, ['Contact: '+ self.contact], body); - - if (timeout < Timers.T2) { - timeout = timeout * 2; - if (timeout > Timers.T2) { - timeout = Timers.T2; - } - } - self.timers.invite2xxTimer = setTimeout( - invite2xxRetransmission, timeout - ); - }, timeout); -} - - -/** - * RFC3261 14.2 - * If a UAS generates a 2xx response and never receives an ACK, - * it SHOULD generate a BYE to terminate the dialog. - */ -function setACKTimer() { - var self = this; - - this.timers.ackTimer = setTimeout(function() { - if(self.status === C.STATUS_WAITING_FOR_ACK) { - debug('no ACK received, terminating the session'); - clearTimeout(self.timers.invite2xxTimer); - sendRequest.call(self, JsSIP_C.BYE); - ended.call(self, 'remote', null, JsSIP_C.causes.NO_ACK); - } - }, Timers.TIMER_H); -} - - -function createRTCConnection(pcConfig, rtcConstraints) { - var self = this; - - this.connection = new RTCPeerConnection(pcConfig, rtcConstraints); - - this.connection.addEventListener('iceconnectionstatechange', function() { - var state = self.connection.iceConnectionState; - - // TODO: Do more with different states. - // Plivo patch for disable RTP timeout - if (state === 'failed' && !this.disableRtpTimeOut) { - self.terminate({ - cause: JsSIP_C.causes.RTP_TIMEOUT, - status_code: 200, - reason_phrase: JsSIP_C.causes.RTP_TIMEOUT - }); - } - }); -} - -function createLocalDescription(type, onSuccess, onFailure, constraints) { - debug('createLocalDescription()'); - - var self = this; - var connection = this.connection; - - this.rtcReady = false; - - if (type === 'offer') { - connection.createOffer(constraints) - .then(createSucceeded) - .catch(function(error) { - self.rtcReady = true; - if (onFailure) { onFailure(error); } - - self.emit('peerconnection:createofferfailed', error); - }); - } - else if (type === 'answer') { - connection.createAnswer(constraints) - .then(createSucceeded) - .catch(function(error) { - self.rtcReady = true; - if (onFailure) { onFailure(error); } - - self.emit('peerconnection:createanswerfailed', error); - }); - } - else { - throw new Error('createLocalDescription() | type must be "offer" or "answer", but "' +type+ '" was given'); - } - - // createAnswer or createOffer succeeded - function createSucceeded(desc) { - var listener; - /* - Plivo patch for gatherTimeout - */ - var srflxReceived=false; - - connection.addEventListener('icecandidate', listener = function(event) { - var candidate = event.candidate; - // Look for external ip with srflx string - if(candidate && candidate.candidate.search('srflx') != -1){ - srflxReceived=true; - } - if (!candidate || srflxReceived) { - connection.removeEventListener('icecandidate', listener); - self.rtcReady = true; - - if (onSuccess) { - var e = {originator:'local', type:type, sdp:connection.localDescription.sdp}; - - self.emit('sdp', e); - onSuccess(e.sdp); - debug('iceGathering completed'); - } - onSuccess = null; - } - }); - - connection.setLocalDescription(desc) - .then(function() { - if (connection.iceGatheringState != 'complete') { - setTimeout(function() { - if (connection.iceGatheringState === 'complete') { - debug('iceGathering already completed'); - return; - } - self.rtcReady = true; - if (onSuccess) { - var e = { - originator: 'local', - type: type, - sdp: connection.localDescription.sdp - }; - self.emit('sdp', e); - onSuccess(e.sdp); - onSuccess = null; - debug('iceGathering taking more than 2sec '+connection.iceGatheringState); - iceTimeOut.call(self, 2000); - } - }, 2000); - } - debug('iceGatheringState after setLocalDescription success: ' + connection.iceGatheringState); - }) - .catch(function(error) { - self.rtcReady = true; - if (onFailure) { onFailure(error); } - - self.emit('peerconnection:setlocaldescriptionfailed', error); - }); - } -} - - -/** - * Dialog Management - */ -function createDialog(message, type, early) { - var dialog, early_dialog, - local_tag = (type === 'UAS') ? message.to_tag : message.from_tag, - remote_tag = (type === 'UAS') ? message.from_tag : message.to_tag, - id = message.call_id + local_tag + remote_tag; - - early_dialog = this.earlyDialogs[id]; - - // Early Dialog - if (early) { - if (early_dialog) { - return true; - } else { - early_dialog = new Dialog(this, message, type, Dialog.C.STATUS_EARLY); - - // Dialog has been successfully created. - if(early_dialog.error) { - debug(early_dialog.error); - failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR); - return false; - } else { - this.earlyDialogs[id] = early_dialog; - return true; - } - } - } - - // Confirmed Dialog - else { - this.from_tag = message.from_tag; - this.to_tag = message.to_tag; - - // In case the dialog is in _early_ state, update it - if (early_dialog) { - early_dialog.update(message, type); - this.dialog = early_dialog; - delete this.earlyDialogs[id]; - return true; - } - - // Otherwise, create a _confirmed_ dialog - dialog = new Dialog(this, message, type); - - if(dialog.error) { - debug(dialog.error); - failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR); - return false; - } else { - this.dialog = dialog; - return true; - } - } -} - -/** - * In dialog INVITE Reception - */ - -function receiveReinvite(request) { - debug('receiveReinvite()'); - - var - sdp, idx, direction, m, - self = this, - contentType = request.getHeader('Content-Type'), - hold = false, - rejected = false, - data = { - request: request, - callback: undefined, - reject: reject.bind(this) - }; - - function reject(options) { - options = options || {}; - rejected = true; - - var - status_code = options.status_code || 403, - reason_phrase = options.reason_phrase || '', - extraHeaders = options.extraHeaders && options.extraHeaders.slice() || []; - - if (this.status !== C.STATUS_CONFIRMED) { - return false; - } - - if (status_code < 300 || status_code >= 700) { - throw new TypeError('Invalid status_code: '+ status_code); - } - - request.reply(status_code, reason_phrase, extraHeaders); - } - - // Emit 'reinvite'. - this.emit('reinvite', data); - - if (rejected) { - return; - } - - if (request.body) { - this.late_sdp = false; - if (contentType !== 'application/sdp') { - debug('invalid Content-Type'); - request.reply(415); - return; - } - - sdp = request.parseSDP(); - - for (idx=0; idx < sdp.media.length; idx++) { - m = sdp.media[idx]; - - if (holdMediaTypes.indexOf(m.type) === -1) { - continue; - } - - direction = m.direction || sdp.direction || 'sendrecv'; - - if (direction === 'sendonly' || direction === 'inactive') { - hold = true; - } - // If at least one of the streams is active don't emit 'hold'. - else { - hold = false; - break; - } - } - - var e = {originator:'remote', type:'offer', sdp:request.body}; - var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp}); - - this.emit('sdp', e); - - this.connection.setRemoteDescription(offer) - .then(doAnswer) - .catch(function(error) { - request.reply(488); - - self.emit('peerconnection:setremotedescriptionfailed', error); - }); - } - else { - this.late_sdp = true; - doAnswer(); - } - - function doAnswer() { - createSdp( - // onSuccess - function(sdp) { - var extraHeaders = ['Contact: ' + self.contact]; - - handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); - - if (self.late_sdp) { - sdp = mangleOffer.call(self, sdp); - } - - request.reply(200, null, extraHeaders, sdp, - function() { - self.status = C.STATUS_WAITING_FOR_ACK; - setInvite2xxTimer.call(self, request, sdp); - setACKTimer.call(self); - } - ); - - // If callback is given execute it. - if (typeof data.callback === 'function') { - data.callback(); - } - }, - // onFailure - function() { - request.reply(500); - } - ); - } - - function createSdp(onSuccess, onFailure) { - if (! self.late_sdp) { - if (self.remoteHold === true && hold === false) { - self.remoteHold = false; - onunhold.call(self, 'remote'); - } else if (self.remoteHold === false && hold === true) { - self.remoteHold = true; - onhold.call(self, 'remote'); - } - - createLocalDescription.call(self, 'answer', onSuccess, onFailure, self.rtcAnswerConstraints); - } else { - createLocalDescription.call(self, 'offer', onSuccess, onFailure, self.rtcOfferConstraints); - } - } -} - -/** - * In dialog UPDATE Reception - */ -function receiveUpdate(request) { - debug('receiveUpdate()'); - - var - sdp, idx, direction, m, - self = this, - contentType = request.getHeader('Content-Type'), - rejected = false, - hold = false, - data = { - request: request, - callback: undefined, - reject: reject.bind(this) - }; - - function reject(options) { - options = options || {}; - rejected = true; - - var - status_code = options.status_code || 403, - reason_phrase = options.reason_phrase || '', - extraHeaders = options.extraHeaders && options.extraHeaders.slice() || []; - - if (this.status !== C.STATUS_CONFIRMED) { - return false; - } - - if (status_code < 300 || status_code >= 700) { - throw new TypeError('Invalid status_code: '+ status_code); - } - - request.reply(status_code, reason_phrase, extraHeaders); - } - - // Emit 'update'. - this.emit('update', data); - - if (rejected) { - return; - } - - if (! request.body) { - var extraHeaders = []; - handleSessionTimersInIncomingRequest.call(this, request, extraHeaders); - request.reply(200, null, extraHeaders); - return; - } - - if (contentType !== 'application/sdp') { - debug('invalid Content-Type'); - request.reply(415); - return; - } - - sdp = request.parseSDP(); - - for (idx=0; idx < sdp.media.length; idx++) { - m = sdp.media[idx]; - - if (holdMediaTypes.indexOf(m.type) === -1) { - continue; - } - - direction = m.direction || sdp.direction || 'sendrecv'; - - if (direction === 'sendonly' || direction === 'inactive') { - hold = true; - } - // If at least one of the streams is active don't emit 'hold'. - else { - hold = false; - break; - } - } - - var e = {originator:'remote', type:'offer', sdp:request.body}; - var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp}); - - this.emit('sdp', e); - - this.connection.setRemoteDescription(offer) - .then(function() { - if (self.remoteHold === true && hold === false) { - self.remoteHold = false; - onunhold.call(self, 'remote'); - } else if (self.remoteHold === false && hold === true) { - self.remoteHold = true; - onhold.call(self, 'remote'); - } - - createLocalDescription.call(self, 'answer', - // success - function(sdp) { - var extraHeaders = ['Contact: ' + self.contact]; - - handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); - request.reply(200, null, extraHeaders, sdp); - - // If callback is given execute it. - if (typeof data.callback === 'function') { - data.callback(); - } - }, - // failure - function() { - request.reply(500); - } - ); - }) - .catch(function(error) { - request.reply(488); - - self.emit('peerconnection:setremotedescriptionfailed', error); - }); -} - -/** - * In dialog Refer Reception - */ -function receiveRefer(request) { - debug('receiveRefer()'); - - var notifier, - self = this; - - function accept(initCallback, options) { - var session, replaces; - - options = options || {}; - initCallback = (typeof initCallback === 'function')? initCallback : null; - - if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { - return false; - } - - session = new RTCSession(this.ua); - - session.on('progress', function(e) { - notifier.notify(e.response.status_code, e.response.reason_phrase); - }); - - session.on('accepted', function(e) { - notifier.notify(e.response.status_code, e.response.reason_phrase); - }); - - session.on('failed', function(e) { - if (e.message) { - notifier.notify(e.message.status_code, e.message.reason_phrase); - } else { - notifier.notify(487, e.cause); - } - }); - - // Consider the Replaces header present in the Refer-To URI - if (request.refer_to.uri.hasHeader('replaces')) { - replaces = decodeURIComponent(request.refer_to.uri.getHeader('replaces')); - options.extraHeaders = options.extraHeaders || []; - options.extraHeaders.push('Replaces: '+ replaces); - } - - session.connect(request.refer_to.uri.toAor(), options, initCallback); - } - - function reject() { - notifier.notify(603); - } - - if (typeof request.refer_to === undefined) { - debug('no Refer-To header field present in REFER'); - request.reply(400); - return; - } - - if (request.refer_to.uri.scheme !== JsSIP_C.SIP) { - debug('Refer-To header field points to a non-SIP URI scheme'); - request.reply(416); - return; - } - - // reply before the transaction timer expires - request.reply(202); - - notifier = new RTCSession_ReferNotifier(this, request.cseq); - - // Emit 'refer'. - this.emit('refer', { - request: request, - accept: function(initCallback, options) { accept.call(self, initCallback, options); }, - reject: function() { reject.call(self); } - }); -} - -/** - * In dialog Notify Reception - */ -function receiveNotify(request) { - debug('receiveNotify()'); - - if (typeof request.event === undefined) { - request.reply(400); - } - - switch (request.event.event) { - case 'refer': { - var id = request.event.params.id; - var referSubscriber = this.referSubscribers[id]; - - if (!referSubscriber) { - request.reply(481, 'Subscription does not exist'); - return; - } - - referSubscriber.receiveNotify(request); - request.reply(200); - - break; - } - - default: { - request.reply(489); - } - } -} - -/** - * INVITE with Replaces Reception - */ -function receiveReplaces(request) { - debug('receiveReplaces()'); - - var self = this; - - function accept(initCallback) { - var session; - - if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { - return false; - } - - session = new RTCSession(this.ua); - - // terminate the current session when the new one is confirmed - session.on('confirmed', function() { - self.terminate(); - }); - - session.init_incoming(request, initCallback); - } - - function reject() { - debug('Replaced INVITE rejected by the user'); - request.reply(486); - } - - // Emit 'replace'. - this.emit('replaces', { - request: request, - accept: function(initCallback) { accept.call(self, initCallback); }, - reject: function() { reject.call(self); } - }); -} - -/** - * Initial Request Sender - */ -function sendInitialRequest(mediaConstraints, rtcOfferConstraints, mediaStream) { - var self = this; - var request_sender = new RequestSender(self, this.ua); - - this.receiveResponse = function(response) { - receiveInviteResponse.call(self, response); - }; - - // If a local MediaStream is given use it. - if (mediaStream) { - // Wait a bit so the app can set events such as 'peerconnection' and 'connecting'. - setTimeout(function() { - userMediaSucceeded(mediaStream); - }); - // If at least audio or video is requested prompt getUserMedia. - } else if (mediaConstraints.audio || mediaConstraints.video) { - this.localMediaStreamLocallyGenerated = true; - navigator.mediaDevices.getUserMedia(mediaConstraints) - .then(userMediaSucceeded) - .catch(function(error) - { - userMediaFailed(error); - - self.emit('getusermediafailed', error); - }); - // Otherwise don't prompt getUserMedia. - } else { - userMediaSucceeded(null); - } - - // User media succeeded - function userMediaSucceeded(stream) { - if (self.status === C.STATUS_TERMINATED) { return; } - - self.localMediaStream = stream; - if (stream) { - self.connection.addStream(stream); - } - - // Notify the app with the RTCPeerConnection so it can do stuff on it - // before generating the offer. - self.emit('peerconnection', { - peerconnection: self.connection - }); - - connecting.call(self, self.request); - createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, rtcOfferConstraints); - } - - // User media failed - function userMediaFailed() { - if (self.status === C.STATUS_TERMINATED) { return; } - - failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS); - } - - function rtcSucceeded(desc) { - if (self.isCanceled || self.status === C.STATUS_TERMINATED) { return; } - - self.request.body = desc; - self.status = C.STATUS_INVITE_SENT; - - // Emit 'sending' so the app can mangle the body before the request - // is sent. - self.emit('sending', { - request: self.request - }); - - request_sender.send(); - } - - function rtcFailed() { - if (self.status === C.STATUS_TERMINATED) { return; } - - failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR); - } -} - -/** - * Reception of Response for Initial INVITE - */ -function receiveInviteResponse(response) { - debug('receiveInviteResponse()'); - - var cause, dialog, e, - self = this; - - // Handle 2XX retransmissions and responses from forked requests - if (this.dialog && (response.status_code >=200 && response.status_code <=299)) { - - /* - * If it is a retransmission from the endpoint that established - * the dialog, send an ACK - */ - if (this.dialog.id.call_id === response.call_id && - this.dialog.id.local_tag === response.from_tag && - this.dialog.id.remote_tag === response.to_tag) { - sendRequest.call(this, JsSIP_C.ACK); - return; - } - - // If not, send an ACK and terminate - else { - dialog = new Dialog(this, response, 'UAC'); - - if (dialog.error !== undefined) { - debug(dialog.error); - return; - } - - dialog.sendRequest({ - owner: {status: C.STATUS_TERMINATED}, - onRequestTimeout: function(){}, - onTransportError: function(){}, - onDialogError: function(){}, - receiveResponse: function(){} - }, JsSIP_C.ACK); - - dialog.sendRequest({ - owner: {status: C.STATUS_TERMINATED}, - onRequestTimeout: function(){}, - onTransportError: function(){}, - onDialogError: function(){}, - receiveResponse: function(){} - }, JsSIP_C.BYE); - return; - } - - } - - // Proceed to cancellation if the user requested. - if(this.isCanceled) { - // Remove the flag. We are done. - this.isCanceled = false; - - if(response.status_code >= 100 && response.status_code < 200) { - this.request.cancel(this.cancelReason); - } else if(response.status_code >= 200 && response.status_code < 299) { - acceptAndTerminate.call(this, response); - } - return; - } - - if(this.status !== C.STATUS_INVITE_SENT && this.status !== C.STATUS_1XX_RECEIVED) { - return; - } - - switch(true) { - case /^100$/.test(response.status_code): - this.status = C.STATUS_1XX_RECEIVED; - break; - - case /^1[0-9]{2}$/.test(response.status_code): - // Do nothing with 1xx responses without To tag. - if (!response.to_tag) { - debug('1xx response received without to tag'); - break; - } - - // Create Early Dialog if 1XX comes with contact - if (response.hasHeader('contact')) { - // An error on dialog creation will fire 'failed' event - if(! createDialog.call(this, response, 'UAC', true)) { - break; - } - } - - this.status = C.STATUS_1XX_RECEIVED; - progress.call(this, 'remote', response); - - if (!response.body) { - break; - } - - e = {originator:'remote', type:'pranswer', sdp:response.body}; - this.emit('sdp', e); - - var pranswer = new RTCSessionDescription({type:'pranswer', sdp:e.sdp}); - - this.connection.setRemoteDescription(pranswer) - .catch(function(error) { - self.emit('peerconnection:setremotedescriptionfailed', error); - }); - break; - - case /^2[0-9]{2}$/.test(response.status_code): - this.status = C.STATUS_CONFIRMED; - - if(!response.body) { - acceptAndTerminate.call(this, response, 400, JsSIP_C.causes.MISSING_SDP); - failed.call(this, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); - break; - } - - // An error on dialog creation will fire 'failed' event - if (! createDialog.call(this, response, 'UAC')) { - break; - } - - e = {originator:'remote', type:'answer', sdp:response.body}; - this.emit('sdp', e); - - var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); - - this.connection.setRemoteDescription(answer) - .then(function() { - // Handle Session Timers. - handleSessionTimersInIncomingResponse.call(self, response); - - accepted.call(self, 'remote', response); - sendRequest.call(self, JsSIP_C.ACK); - confirmed.call(self, 'local', null); - }) - .catch(function(error) { - acceptAndTerminate.call(self, response, 488, 'Not Acceptable Here'); - failed.call(self, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); - - self.emit('peerconnection:setremotedescriptionfailed', error); - }); - break; - - default: - cause = Utils.sipErrorCause(response.status_code); - failed.call(this, 'remote', response, cause); - } -} - -/** - * Send Re-INVITE - */ -function sendReinvite(options) { - debug('sendReinvite()'); - - options = options || {}; - - var - self = this, - extraHeaders = options.extraHeaders || [], - eventHandlers = options.eventHandlers || {}, - rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null, - succeeded = false; - - extraHeaders.push('Contact: ' + this.contact); - extraHeaders.push('Content-Type: application/sdp'); - - // Session Timers. - if (this.sessionTimers.running) { - extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas')); - } - - createLocalDescription.call(this, 'offer', - // success - function(sdp) { - sdp = mangleOffer.call(self, sdp); - - var request = new RTCSession_Request(self, JsSIP_C.INVITE); - - request.send({ - extraHeaders: extraHeaders, - body: sdp, - eventHandlers: { - onSuccessResponse: function(response) { - onSucceeded(response); - succeeded = true; - }, - onErrorResponse: function(response) { - onFailed(response); - }, - onTransportError: function() { - self.onTransportError(); // Do nothing because session ends. - }, - onRequestTimeout: function() { - self.onRequestTimeout(); // Do nothing because session ends. - }, - onDialogError: function() { - self.onDialogError(); // Do nothing because session ends. - } - } - }); - }, - // failure - function() { - onFailed(); - }, - // RTC constraints. - rtcOfferConstraints - ); - - function onSucceeded(response) { - if (self.status === C.STATUS_TERMINATED) { - return; - } - - sendRequest.call(self, JsSIP_C.ACK); - - // If it is a 2XX retransmission exit now. - if (succeeded) { return; } - - // Handle Session Timers. - handleSessionTimersInIncomingResponse.call(self, response); - - // Must have SDP answer. - if(! response.body) { - onFailed(); - return; - } else if (response.getHeader('Content-Type') !== 'application/sdp') { - onFailed(); - return; - } - - var e = {originator:'remote', type:'answer', sdp:response.body}; - var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); - - self.emit('sdp', e); - - self.connection.setRemoteDescription(answer) - .then(function() { - if (eventHandlers.succeeded) { - eventHandlers.succeeded(response); - } - }) - .catch(function(error) { - onFailed(); - - self.emit('peerconnection:setremotedescriptionfailed', error); - }); - } - - function onFailed(response) { - if (eventHandlers.failed) { - eventHandlers.failed(response); - } - } -} - -/** - * Send UPDATE - */ -function sendUpdate(options) { - debug('sendUpdate()'); - - options = options || {}; - - var - self = this, - extraHeaders = options.extraHeaders || [], - eventHandlers = options.eventHandlers || {}, - rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null, - sdpOffer = options.sdpOffer || false, - succeeded = false; - - extraHeaders.push('Contact: ' + this.contact); - - // Session Timers. - if (this.sessionTimers.running) { - extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas')); - } - - if (sdpOffer) { - extraHeaders.push('Content-Type: application/sdp'); - - createLocalDescription.call(this, 'offer', - // success - function(sdp) { - sdp = mangleOffer.call(self, sdp); - - var request = new RTCSession_Request(self, JsSIP_C.UPDATE); - - request.send({ - extraHeaders: extraHeaders, - body: sdp, - eventHandlers: { - onSuccessResponse: function(response) { - onSucceeded(response); - succeeded = true; - }, - onErrorResponse: function(response) { - onFailed(response); - }, - onTransportError: function() { - self.onTransportError(); // Do nothing because session ends. - }, - onRequestTimeout: function() { - self.onRequestTimeout(); // Do nothing because session ends. - }, - onDialogError: function() { - self.onDialogError(); // Do nothing because session ends. - } - } - }); - }, - // failure - function() { - onFailed(); - }, - // RTC constraints. - rtcOfferConstraints - ); - } - - // No SDP. - else { - var request = new RTCSession_Request(self, JsSIP_C.UPDATE); - - request.send({ - extraHeaders: extraHeaders, - eventHandlers: { - onSuccessResponse: function(response) { - onSucceeded(response); - }, - onErrorResponse: function(response) { - onFailed(response); - }, - onTransportError: function() { - self.onTransportError(); // Do nothing because session ends. - }, - onRequestTimeout: function() { - self.onRequestTimeout(); // Do nothing because session ends. - }, - onDialogError: function() { - self.onDialogError(); // Do nothing because session ends. - } - } - }); - } - - function onSucceeded(response) { - if (self.status === C.STATUS_TERMINATED) { - return; - } - - // If it is a 2XX retransmission exit now. - if (succeeded) { return; } - - // Handle Session Timers. - handleSessionTimersInIncomingResponse.call(self, response); - - // Must have SDP answer. - if (sdpOffer) { - if(! response.body) { - onFailed(); - return; - } else if (response.getHeader('Content-Type') !== 'application/sdp') { - onFailed(); - return; - } - - var e = {originator:'remote', type:'answer', sdp:response.body}; - var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); - - self.emit('sdp', e); - - self.connection.setRemoteDescription(answer) - .then(function() { - if (eventHandlers.succeeded) { - eventHandlers.succeeded(response); - } - }) - .catch(function(error) { - onFailed(); - - self.emit('peerconnection:setremotedescriptionfailed', error); - }); - } - // No SDP answer. - else { - if (eventHandlers.succeeded) { - eventHandlers.succeeded(response); - } - } - } - - function onFailed(response) { - if (eventHandlers.failed) { eventHandlers.failed(response); } - } -} - -function acceptAndTerminate(response, status_code, reason_phrase) { - debug('acceptAndTerminate()'); - - var extraHeaders = []; - - if (status_code) { - reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; - extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"'); - } - - // An error on dialog creation will fire 'failed' event - if (this.dialog || createDialog.call(this, response, 'UAC')) { - sendRequest.call(this, JsSIP_C.ACK); - sendRequest.call(this, JsSIP_C.BYE, { - extraHeaders: extraHeaders - }); - } - - // Update session status. - this.status = C.STATUS_TERMINATED; -} - -/** - * Send a generic in-dialog Request - */ -function sendRequest(method, options) { - debug('sendRequest()'); - - var request = new RTCSession_Request(this, method); - request.send(options); -} - -/** - * Correctly set the SDP direction attributes if the call is on local hold - */ -function mangleOffer(sdp) { - var idx, length, m; - - if (! this.localHold && ! this.remoteHold) { - return sdp; - } - - sdp = sdp_transform.parse(sdp); - - // Local hold. - if (this.localHold && ! this.remoteHold) { - debug('mangleOffer() | me on hold, mangling offer'); - length = sdp.media.length; - for (idx=0; idx= JsSIP_C.MIN_SESSION_EXPIRES) { - this.sessionTimers.currentExpires = request.session_expires; - session_expires_refresher = request.session_expires_refresher || 'uas'; - } - else { - this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires; - session_expires_refresher = 'uas'; - } - - responseExtraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + session_expires_refresher); - - this.sessionTimers.refresher = (session_expires_refresher === 'uas'); - runSessionTimer.call(this); -} - -/** - * Handle SessionTimers for an incoming response to INVITE or UPDATE. - * @param {IncomingResponse} response - */ -function handleSessionTimersInIncomingResponse(response) { - if (! this.sessionTimers.enabled) { return; } - - var session_expires_refresher; - - if (response.session_expires && response.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) { - this.sessionTimers.currentExpires = response.session_expires; - session_expires_refresher = response.session_expires_refresher || 'uac'; - } - else { - this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires; - session_expires_refresher = 'uac'; - } - - this.sessionTimers.refresher = (session_expires_refresher === 'uac'); - runSessionTimer.call(this); -} - -function runSessionTimer() { - var self = this; - var expires = this.sessionTimers.currentExpires; - - this.sessionTimers.running = true; - - clearTimeout(this.sessionTimers.timer); - - // I'm the refresher. - if (this.sessionTimers.refresher) { - this.sessionTimers.timer = setTimeout(function() { - if (self.status === C.STATUS_TERMINATED) { return; } - - debug('runSessionTimer() | sending session refresh request'); - - sendUpdate.call(self, { - eventHandlers: { - succeeded: function(response) { - handleSessionTimersInIncomingResponse.call(self, response); - } - } - }); - }, expires * 500); // Half the given interval (as the RFC states). - } - - // I'm not the refresher. - else { - this.sessionTimers.timer = setTimeout(function() { - if (self.status === C.STATUS_TERMINATED) { return; } - - debugerror('runSessionTimer() | timer expired, terminating the session'); - - self.terminate({ - cause: JsSIP_C.causes.REQUEST_TIMEOUT, - status_code: 408, - reason_phrase: 'Session Timer Expired' - }); - }, expires * 1100); - } -} - -function toogleMuteAudio(mute) { - var streamIdx, trackIdx, streamsLength, tracksLength, tracks, - localStreams = this.connection.getLocalStreams(); - - streamsLength = localStreams.length; - for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) { - tracks = localStreams[streamIdx].getAudioTracks(); - tracksLength = tracks.length; - for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) { - tracks[trackIdx].enabled = !mute; - } - } -} - -function toogleMuteVideo(mute) { - var streamIdx, trackIdx, streamsLength, tracksLength, tracks, - localStreams = this.connection.getLocalStreams(); - - streamsLength = localStreams.length; - for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) { - tracks = localStreams[streamIdx].getVideoTracks(); - tracksLength = tracks.length; - for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) { - tracks[trackIdx].enabled = !mute; - } - } -} - -function newRTCSession(originator, request) { - debug('newRTCSession'); - - this.ua.newRTCSession({ - originator: originator, - session: this, - request: request - }); -} - -function connecting(request) { - debug('session connecting'); - - this.emit('connecting', { - request: request - }); -} - -function progress(originator, response) { - debug('session progress'); - - this.emit('progress', { - originator: originator, - response: response || null - }); -} - -function accepted(originator, message) { - debug('session accepted'); - - this.start_time = new Date(); - - this.emit('accepted', { - originator: originator, - response: message || null - }); -} - -function confirmed(originator, ack) { - debug('session confirmed'); - - this.is_confirmed = true; - - this.emit('confirmed', { - originator: originator, - ack: ack || null - }); -} - -function ended(originator, message, cause) { - debug('session ended'); - - this.end_time = new Date(); - - this.close(); - this.emit('ended', { - originator: originator, - message: message || null, - cause: cause - }); -} - -function failed(originator, message, cause) { - debug('session failed'); - - this.close(); - this.emit('failed', { - originator: originator, - message: message || null, - cause: cause - }); -} - -function onhold(originator) { - debug('session onhold'); - - setLocalMediaStatus.call(this); - - this.emit('hold', { - originator: originator - }); -} - -function onunhold(originator) { - debug('session onunhold'); - - setLocalMediaStatus.call(this); - - this.emit('unhold', { - originator: originator - }); -} - -function onmute(options) { - debug('session onmute'); - - setLocalMediaStatus.call(this); - - this.emit('muted', { - audio: options.audio, - video: options.video - }); -} - -function onunmute(options) { - debug('session onunmute'); - - setLocalMediaStatus.call(this); - - this.emit('unmuted', { - audio: options.audio, - video: options.video - }); -} - -// Plivo patch to trigger iceTimeOut -function iceTimeOut(time){ - debug('iceTimeOut() after '+ time); - this.emit('icetimeout',time); -} -},{"./Constants":35,"./Dialog":36,"./Exceptions":39,"./RTCSession/DTMF":46,"./RTCSession/ReferNotifier":47,"./RTCSession/ReferSubscriber":48,"./RTCSession/Request":49,"./RequestSender":51,"./SIPMessage":52,"./Timers":54,"./Transactions":55,"./Utils":59,"debug":11,"events":13,"sdp-transform":17,"util":23}],46:[function(require,module,exports){ -module.exports = DTMF; - - -var C = { - MIN_DURATION: 70, - MAX_DURATION: 6000, - DEFAULT_DURATION: 100, - MIN_INTER_TONE_GAP: 50, - DEFAULT_INTER_TONE_GAP: 500 -}; - -/** - * Expose C object. - */ -DTMF.C = C; - - -/** - * Dependencies. - */ -var debug = require('debug')('PlivoSIP:RTCSession:DTMF'); -var debugerror = require('debug')('PlivoSIP:ERROR:RTCSession:DTMF'); -debugerror.log = console.warn.bind(console); -var JsSIP_C = require('../Constants'); -var Exceptions = require('../Exceptions'); -var RTCSession = require('../RTCSession'); - - -function DTMF(session) { - this.owner = session; - this.direction = null; - this.tone = null; - this.duration = null; -} - - -DTMF.prototype.send = function(tone, options) { - var extraHeaders, body; - - if (tone === undefined) { - throw new TypeError('Not enough arguments'); - } - - this.direction = 'outgoing'; - - // Check RTCSession Status - if (this.owner.status !== RTCSession.C.STATUS_CONFIRMED && - this.owner.status !== RTCSession.C.STATUS_WAITING_FOR_ACK) { - throw new Exceptions.InvalidStateError(this.owner.status); - } - - // Get DTMF options - options = options || {}; - extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; - this.eventHandlers = options.eventHandlers || {}; - - // Check tone type - if (typeof tone === 'string' ) { - tone = tone.toUpperCase(); - } else if (typeof tone === 'number') { - tone = tone.toString(); - } else { - throw new TypeError('Invalid tone: '+ tone); - } - - // Check tone value - if (!tone.match(/^[0-9A-D#*]$/)) { - throw new TypeError('Invalid tone: '+ tone); - } else { - this.tone = tone; - } - - // Duration is checked/corrected in RTCSession - this.duration = options.duration; - - extraHeaders.push('Content-Type: application/dtmf-relay'); - - body = 'Signal=' + this.tone + '\r\n'; - body += 'Duration=' + this.duration; - - this.owner.newDTMF({ - originator: 'local', - dtmf: this, - request: this.request - }); - - this.owner.dialog.sendRequest(this, JsSIP_C.INFO, { - extraHeaders: extraHeaders, - body: body - }); -}; - -DTMF.prototype.receiveResponse = function(response) { - switch(true) { - case /^1[0-9]{2}$/.test(response.status_code): - // Ignore provisional responses. - break; - - case /^2[0-9]{2}$/.test(response.status_code): - debug('onSuccessResponse'); - if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); } - break; - - default: - if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); } - break; - } -}; - -DTMF.prototype.onRequestTimeout = function() { - debugerror('onRequestTimeout'); - if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); } -}; - -DTMF.prototype.onTransportError = function() { - debugerror('onTransportError'); - if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); } -}; - -DTMF.prototype.onDialogError = function() { - debugerror('onDialogError'); - if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); } -}; - -DTMF.prototype.init_incoming = function(request) { - var body, - reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/, - reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; - - this.direction = 'incoming'; - this.request = request; - - request.reply(200); - - if (request.body) { - body = request.body.split('\n'); - if (body.length >= 1) { - if (reg_tone.test(body[0])) { - this.tone = body[0].replace(reg_tone,'$2'); - } - } - if (body.length >=2) { - if (reg_duration.test(body[1])) { - this.duration = parseInt(body[1].replace(reg_duration,'$2'), 10); - } - } - } - - if (!this.duration) { - this.duration = C.DEFAULT_DURATION; - } - - if (!this.tone) { - debug('invalid INFO DTMF received, discarded'); - } else { - this.owner.newDTMF({ - originator: 'remote', - dtmf: this, - request: request - }); - } -}; - -},{"../Constants":35,"../Exceptions":39,"../RTCSession":45,"debug":11}],47:[function(require,module,exports){ -module.exports = ReferNotifier; - - -var C = { - event_type: 'refer', - body_type: 'message/sipfrag;version=2.0', - expires: 300 -}; - -/** - * Dependencies. - */ -var debug = require('debug')('PlivoSIP:RTCSession:ReferNotifier'); -var JsSIP_C = require('../Constants'); -var RTCSession_Request = require('./Request'); - - -function ReferNotifier(session, id, expires) { - this.session = session; - this.id = id; - this.expires = expires || C.expires; - this.active = true; - - // The creation of a Notifier results in an immediate NOTIFY - this.notify(100); -} - -ReferNotifier.prototype.notify = function(code, reason) { - debug('notify()'); - - var state, - self = this; - - if (this.active === false) { - return; - } - - reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; - - if (code >= 200) { - state = 'terminated;reason=noresource'; - } else { - state = 'active;expires='+ this.expires; - } - - // put this in a try/catch block - var request = new RTCSession_Request(this.session, JsSIP_C.NOTIFY); - request.send({ - extraHeaders: [ - 'Event: '+ C.event_type +';id='+ self.id, - 'Subscription-State: '+ state, - 'Content-Type: '+ C.body_type - ], - body: 'SIP/2.0 ' + code + ' ' + reason, - eventHandlers: { - // if a negative response is received, subscription is canceled - onErrorResponse: function() { self.active = false; } - } - }); -}; - -},{"../Constants":35,"./Request":49,"debug":11}],48:[function(require,module,exports){ -module.exports = ReferSubscriber; - - -var C = { - expires: 120 -}; - -/** - * Dependencies. - */ -var util = require('util'); -var events = require('events'); -var debug = require('debug')('PlivoSIP:RTCSession:ReferSubscriber'); -var JsSIP_C = require('../Constants'); -var Grammar = require('../Grammar'); -var RTCSession_Request = require('./Request'); - - -function ReferSubscriber(session) { - this.session = session; - this.timer = null; - // Instance of REFER OutgoingRequest - this.outgoingRequest = null; - - events.EventEmitter.call(this); -} - -util.inherits(ReferSubscriber, events.EventEmitter); - -ReferSubscriber.prototype.sendRefer = function(target, options) { - debug('sendRefer()'); - - var extraHeaders, eventHandlers, referTo, - replaces = null, - self = this; - - // Get REFER options - options = options || {}; - extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; - eventHandlers = options.eventHandlers || {}; - - // Set event handlers - for (var event in eventHandlers) { - this.on(event, eventHandlers[event]); - } - - // Replaces URI header field - if (options.replaces) { - replaces = options.replaces.request.call_id; - replaces += ';to-tag='+ options.replaces.to_tag; - replaces += ';from-tag='+ options.replaces.from_tag; - - replaces = encodeURIComponent(replaces); - } - - // Refer-To header field - referTo = 'Refer-To: <'+ target + (replaces?'?Replaces='+ replaces:'') +'>'; - - extraHeaders.push(referTo); - - var request = new RTCSession_Request(this.session, JsSIP_C.REFER); - - this.timer = setTimeout(function() { - removeSubscriber.call(self); - }, C.expires * 1000); - - request.send({ - extraHeaders: extraHeaders, - eventHandlers: { - onSuccessResponse: function(response) { - self.emit('requestSucceeded', { - response: response - }); - }, - onErrorResponse: function(response) { - self.emit('requestFailed', { - response: response, - cause: JsSIP_C.causes.REJECTED - }); - }, - onTransportError: function() { - removeSubscriber.call(self); - self.emit('requestFailed', { - response: null, - cause: JsSIP_C.causes.CONNECTION_ERROR - }); - }, - onRequestTimeout: function() { - removeSubscriber.call(self); - self.emit('requestFailed', { - response: null, - cause: JsSIP_C.causes.REQUEST_TIMEOUT - }); - }, - onDialogError: function() { - removeSubscriber.call(self); - self.emit('requestFailed', { - response: null, - cause: JsSIP_C.causes.DIALOG_ERROR - }); - } - } - }); - - this.outgoingRequest = request.outgoingRequest; -}; - -ReferSubscriber.prototype.receiveNotify = function(request) { - debug('receiveNotify()'); - - var status_line; - - if (!request.body) { - return; - } - - status_line = Grammar.parse(request.body, 'Status_Line'); - - if(status_line === -1) { - debug('receiveNotify() | error parsing NOTIFY body: "' + request.body + '"'); - return; - } - - switch(true) { - case /^100$/.test(status_line.status_code): - this.emit('trying', { - request: request, - status_line: status_line - }); - break; - - case /^1[0-9]{2}$/.test(status_line.status_code): - this.emit('progress', { - request: request, - status_line: status_line - }); - break; - - case /^2[0-9]{2}$/.test(status_line.status_code): - removeSubscriber.call(this); - this.emit('accepted', { - request: request, - status_line: status_line - }); - break; - - default: - removeSubscriber.call(this); - this.emit('failed', { - request: request, - status_line: status_line - }); - break; - } -}; - -// remove refer subscriber from the session -function removeSubscriber() { - console.log('removeSubscriber()'); - clearTimeout(this.timer); - this.session.referSubscriber = null; -} - -},{"../Constants":35,"../Grammar":40,"./Request":49,"debug":11,"events":13,"util":23}],49:[function(require,module,exports){ -module.exports = Request; - -/** - * Dependencies. - */ -var debug = require('debug')('PlivoSIP:RTCSession:Request'); -var debugerror = require('debug')('PlivoSIP:ERROR:RTCSession:Request'); -debugerror.log = console.warn.bind(console); -var JsSIP_C = require('../Constants'); -var Exceptions = require('../Exceptions'); -var RTCSession = require('../RTCSession'); - - -function Request(session, method) { - debug('new | %s', method); - - this.session = session; - this.method = method; - // Instance of OutgoingRequest - this.outgoingRequest = null; - - // Check RTCSession Status - if (this.session.status !== RTCSession.C.STATUS_1XX_RECEIVED && - this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ANSWER && - this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ACK && - this.session.status !== RTCSession.C.STATUS_CONFIRMED && - this.session.status !== RTCSession.C.STATUS_TERMINATED) { - throw new Exceptions.InvalidStateError(this.session.status); - } - - /* - * Allow sending BYE in TERMINATED status since the RTCSession - * could had been terminated before the ACK had arrived. - * RFC3261 Section 15, Paragraph 2 - */ - else if (this.session.status === RTCSession.C.STATUS_TERMINATED && method !== JsSIP_C.BYE) { - throw new Exceptions.InvalidStateError(this.session.status); - } -} - -Request.prototype.send = function(options) { - options = options || {}; - - var - extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], - body = options.body || null; - - this.eventHandlers = options.eventHandlers || {}; - - this.outgoingRequest = this.session.dialog.sendRequest(this, this.method, { - extraHeaders: extraHeaders, - body: body - }); -}; - -Request.prototype.receiveResponse = function(response) { - switch(true) { - case /^1[0-9]{2}$/.test(response.status_code): - debug('onProgressResponse'); - if (this.eventHandlers.onProgressResponse) { this.eventHandlers.onProgressResponse(response); } - break; - - case /^2[0-9]{2}$/.test(response.status_code): - debug('onSuccessResponse'); - if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); } - break; - - default: - debug('onErrorResponse'); - if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); } - break; - } -}; - -Request.prototype.onRequestTimeout = function() { - debugerror('onRequestTimeout'); - if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); } -}; - -Request.prototype.onTransportError = function() { - debugerror('onTransportError'); - if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); } -}; - -Request.prototype.onDialogError = function() { - debugerror('onDialogError'); - if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); } -}; - -},{"../Constants":35,"../Exceptions":39,"../RTCSession":45,"debug":11}],50:[function(require,module,exports){ -module.exports = Registrator; - - -/** - * Dependecies - */ -var debug = require('debug')('PlivoSIP:Registrator'); -var Utils = require('./Utils'); -var JsSIP_C = require('./Constants'); -var SIPMessage = require('./SIPMessage'); -var RequestSender = require('./RequestSender'); - - -function Registrator(ua, transport) { - var reg_id=1; //Force reg_id to 1. - - this.ua = ua; - this.transport = transport; - - this.registrar = ua.configuration.registrar_server; - this.expires = ua.configuration.register_expires; - - // Call-ID and CSeq values RFC3261 10.2 - this.call_id = Utils.createRandomToken(22); - this.cseq = 0; - - // this.to_uri - this.to_uri = ua.configuration.uri; - - this.registrationTimer = null; - - // Set status - this.registered = false; - - // Contact header - this.contact = this.ua.contact.toString(); - - // sip.ice media feature tag (RFC 5768) - this.contact += ';+sip.ice'; - - // Custom headers for REGISTER and un-REGISTER. - this.extraHeaders = []; - - // Custom Contact header params for REGISTER and un-REGISTER. - this.extraContactParams = ''; - - if(reg_id) { - this.contact += ';reg-id='+ reg_id; - this.contact += ';+sip.instance=""'; - } -} - - -Registrator.prototype = { - setExtraHeaders: function(extraHeaders) { - if (! Array.isArray(extraHeaders)) { - extraHeaders = []; - } - - this.extraHeaders = extraHeaders.slice(); - }, - - setExtraContactParams: function(extraContactParams) { - if (! (extraContactParams instanceof Object)) { - extraContactParams = {}; - } - - // Reset it. - this.extraContactParams = ''; - - for(var param_key in extraContactParams) { - var param_value = extraContactParams[param_key]; - this.extraContactParams += (';' + param_key); - if (param_value) { - this.extraContactParams += ('=' + param_value); - } - } - }, - - register: function() { - var request_sender, cause, extraHeaders, - self = this; - - extraHeaders = this.extraHeaders.slice(); - extraHeaders.push('Contact: ' + this.contact + ';expires=' + this.expires + this.extraContactParams); - extraHeaders.push('Expires: '+ this.expires); - - this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { - 'to_uri': this.to_uri, - 'call_id': this.call_id, - 'cseq': (this.cseq += 1) - }, extraHeaders); - - request_sender = new RequestSender(this, this.ua); - - this.receiveResponse = function(response) { - var contact, expires, - contacts = response.getHeaders('contact').length; - - // Discard responses to older REGISTER/un-REGISTER requests. - if(response.cseq !== this.cseq) { - return; - } - - // Clear registration timer - if (this.registrationTimer !== null) { - clearTimeout(this.registrationTimer); - this.registrationTimer = null; - } - - switch(true) { - case /^1[0-9]{2}$/.test(response.status_code): - // Ignore provisional responses. - break; - case /^2[0-9]{2}$/.test(response.status_code): - if(response.hasHeader('expires')) { - expires = response.getHeader('expires'); - } - - // Search the Contact pointing to us and update the expires value accordingly. - if (!contacts) { - debug('no Contact header in response to REGISTER, response ignored'); - break; - } - - while(contacts--) { - contact = response.parseHeader('contact', contacts); - if(contact.uri.user === this.ua.contact.uri.user) { - expires = contact.getParam('expires'); - break; - } else { - contact = null; - } - } - - if (!contact) { - debug('no Contact header pointing to us, response ignored'); - break; - } - - if(!expires) { - expires = this.expires; - } - - // Re-Register before the expiration interval has elapsed. - // For that, decrease the expires value. ie: 3 seconds - this.registrationTimer = setTimeout(function() { - self.registrationTimer = null; - self.register(); - }, (expires * 1000) - 3000); - - //Save gruu values - if (contact.hasParam('temp-gruu')) { - this.ua.contact.temp_gruu = contact.getParam('temp-gruu').replace(/"/g,''); - } - if (contact.hasParam('pub-gruu')) { - this.ua.contact.pub_gruu = contact.getParam('pub-gruu').replace(/"/g,''); - } - - if (! this.registered) { - this.registered = true; - this.ua.registered({ - response: response - }); - } - break; - // Interval too brief RFC3261 10.2.8 - case /^423$/.test(response.status_code): - if(response.hasHeader('min-expires')) { - // Increase our registration interval to the suggested minimum - this.expires = response.getHeader('min-expires'); - // Attempt the registration again immediately - this.register(); - } else { //This response MUST contain a Min-Expires header field - debug('423 response received for REGISTER without Min-Expires'); - this.registrationFailure(response, JsSIP_C.causes.SIP_FAILURE_CODE); - } - break; - default: - cause = Utils.sipErrorCause(response.status_code); - this.registrationFailure(response, cause); - } - }; - - this.onRequestTimeout = function() { - this.registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT); - }; - - this.onTransportError = function() { - this.registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR); - }; - - request_sender.send(); - }, - - unregister: function(options) { - var extraHeaders; - - if(!this.registered) { - debug('already unregistered'); - return; - } - - options = options || {}; - - this.registered = false; - - // Clear the registration timer. - if (this.registrationTimer !== null) { - clearTimeout(this.registrationTimer); - this.registrationTimer = null; - } - - extraHeaders = this.extraHeaders.slice(); - - if(options.all) { - extraHeaders.push('Contact: *' + this.extraContactParams); - extraHeaders.push('Expires: 0'); - - this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { - 'to_uri': this.to_uri, - 'call_id': this.call_id, - 'cseq': (this.cseq += 1) - }, extraHeaders); - } else { - extraHeaders.push('Contact: '+ this.contact + ';expires=0' + this.extraContactParams); - extraHeaders.push('Expires: 0'); - - this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { - 'to_uri': this.to_uri, - 'call_id': this.call_id, - 'cseq': (this.cseq += 1) - }, extraHeaders); - } - - var request_sender = new RequestSender(this, this.ua); - - this.receiveResponse = function(response) { - var cause; - - switch(true) { - case /^1[0-9]{2}$/.test(response.status_code): - // Ignore provisional responses. - break; - case /^2[0-9]{2}$/.test(response.status_code): - this.unregistered(response); - break; - default: - cause = Utils.sipErrorCause(response.status_code); - this.unregistered(response, cause); - } - }; - - this.onRequestTimeout = function() { - this.unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT); - }; - - this.onTransportError = function() { - this.unregistered(null, JsSIP_C.causes.CONNECTION_ERROR); - }; - - request_sender.send(); - }, - - registrationFailure: function(response, cause) { - this.ua.registrationFailed({ - response: response || null, - cause: cause - }); - - if (this.registered) { - this.registered = false; - this.ua.unregistered({ - response: response || null, - cause: cause - }); - } - }, - - unregistered: function(response, cause) { - this.registered = false; - this.ua.unregistered({ - response: response || null, - cause: cause || null - }); - }, - - onTransportClosed: function() { - if (this.registrationTimer !== null) { - clearTimeout(this.registrationTimer); - this.registrationTimer = null; - } - - if(this.registered) { - this.registered = false; - this.ua.unregistered({}); - } - }, - - close: function() { - if (this.registered) { - this.unregister(); - } - } -}; - - -},{"./Constants":35,"./RequestSender":51,"./SIPMessage":52,"./Utils":59,"debug":11}],51:[function(require,module,exports){ -module.exports = RequestSender; - - -/** - * Dependencies. - */ -var debug = require('debug')('PlivoSIP:RequestSender'); -var JsSIP_C = require('./Constants'); -var UA = require('./UA'); -var DigestAuthentication = require('./DigestAuthentication'); -var Transactions = require('./Transactions'); - - -function RequestSender(applicant, ua) { - this.ua = ua; - this.applicant = applicant; - this.method = applicant.request.method; - this.request = applicant.request; - this.auth = null; - this.challenged = false; - this.staled = false; - - // If ua is in closing process or even closed just allow sending Bye and ACK - if (ua.status === UA.C.STATUS_USER_CLOSED && (this.method !== JsSIP_C.BYE || this.method !== JsSIP_C.ACK)) { - this.onTransportError(); - } -} - - -/** -* Create the client transaction and send the message. -*/ -RequestSender.prototype = { - send: function() { - switch(this.method) { - case 'INVITE': - this.clientTransaction = new Transactions.InviteClientTransaction(this, this.request, this.ua.transport); - break; - case 'ACK': - this.clientTransaction = new Transactions.AckClientTransaction(this, this.request, this.ua.transport); - break; - default: - this.clientTransaction = new Transactions.NonInviteClientTransaction(this, this.request, this.ua.transport); - } - - this.clientTransaction.send(); - }, - - /** - * Callback fired when receiving a request timeout error from the client transaction. - * To be re-defined by the applicant. - */ - onRequestTimeout: function() { - this.applicant.onRequestTimeout(); - }, - - /** - * Callback fired when receiving a transport error from the client transaction. - * To be re-defined by the applicant. - */ - onTransportError: function() { - this.applicant.onTransportError(); - }, - - /** - * Called from client transaction when receiving a correct response to the request. - * Authenticate request if needed or pass the response back to the applicant. - */ - receiveResponse: function(response) { - var - cseq, challenge, authorization_header_name, - status_code = response.status_code; - - /* - * Authentication - * Authenticate once. _challenged_ flag used to avoid infinite authentications. - */ - if ((status_code === 401 || status_code === 407) && - (this.ua.configuration.password !== null || this.ua.configuration.ha1 !== null)) { - - // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. - if (response.status_code === 401) { - challenge = response.parseHeader('www-authenticate'); - authorization_header_name = 'authorization'; - } else { - challenge = response.parseHeader('proxy-authenticate'); - authorization_header_name = 'proxy-authorization'; - } - - // Verify it seems a valid challenge. - if (!challenge) { - debug(response.status_code + ' with wrong or missing challenge, cannot authenticate'); - this.applicant.receiveResponse(response); - return; - } - - if (!this.challenged || (!this.staled && challenge.stale === true)) { - if (!this.auth) { - this.auth = new DigestAuthentication({ - username : this.ua.configuration.authorization_user, - password : this.ua.configuration.password, - realm : this.ua.configuration.realm, - ha1 : this.ua.configuration.ha1 - }); - } - - // Verify that the challenge is really valid. - if (!this.auth.authenticate(this.request, challenge)) { - this.applicant.receiveResponse(response); - return; - } - this.challenged = true; - - // Update ha1 and realm in the UA. - this.ua.set('realm', this.auth.get('realm')); - this.ua.set('ha1', this.auth.get('ha1')); - - if (challenge.stale) { - this.staled = true; - } - - if (response.method === JsSIP_C.REGISTER) { - cseq = this.applicant.cseq += 1; - } else if (this.request.dialog) { - cseq = this.request.dialog.local_seqnum += 1; - } else { - cseq = this.request.cseq + 1; - } - - this.request = this.applicant.request = this.request.clone(); - - this.request.cseq = cseq; - this.request.setHeader('cseq', cseq +' '+ this.method); - - this.request.setHeader(authorization_header_name, this.auth.toString()); - this.send(); - } else { - this.applicant.receiveResponse(response); - } - } else { - this.applicant.receiveResponse(response); - } - } -}; - -},{"./Constants":35,"./DigestAuthentication":38,"./Transactions":55,"./UA":57,"debug":11}],52:[function(require,module,exports){ -module.exports = { - OutgoingRequest: OutgoingRequest, - IncomingRequest: IncomingRequest, - IncomingResponse: IncomingResponse -}; - - -/** - * Dependencies. - */ -var debug = require('debug')('PlivoSIP:SIPMessage'); -var sdp_transform = require('sdp-transform'); -var JsSIP_C = require('./Constants'); -var Utils = require('./Utils'); -var NameAddrHeader = require('./NameAddrHeader'); -var Grammar = require('./Grammar'); - - -/** - * -param {String} method request method - * -param {String} ruri request uri - * -param {UA} ua - * -param {Object} params parameters that will have priority over ua.configuration parameters: - *
- * - cseq, call_id, from_tag, from_uri, from_display_name, to_uri, to_tag, route_set - * -param {Object} [headers] extra headers - * -param {String} [body] - */ -function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) { - var - to, - from, - call_id, - cseq; - - params = params || {}; - - // Mandatory parameters check - if(!method || !ruri || !ua) { - return null; - } - - this.ua = ua; - this.headers = {}; - this.method = method; - this.ruri = ruri; - this.body = body; - this.extraHeaders = extraHeaders && extraHeaders.slice() || []; - - // Fill the Common SIP Request Headers - - // Route - if (params.route_set) { - this.setHeader('route', params.route_set); - } else if (ua.configuration.use_preloaded_route) { - this.setHeader('route', '<' + ua.transport.sip_uri + ';lr>'); - } - - // Via - // Empty Via header. Will be filled by the client transaction. - this.setHeader('via', ''); - - // Max-Forwards - this.setHeader('max-forwards', JsSIP_C.MAX_FORWARDS); - - // To - to = (params.to_display_name || params.to_display_name === 0) ? '"' + params.to_display_name + '" ' : ''; - to += '<' + (params.to_uri || ruri) + '>'; - to += params.to_tag ? ';tag=' + params.to_tag : ''; - this.to = new NameAddrHeader.parse(to); - this.setHeader('to', to); - - // From - if (params.from_display_name || params.from_display_name === 0) { - from = '"' + params.from_display_name + '" '; - } else if (ua.configuration.display_name) { - from = '"' + ua.configuration.display_name + '" '; - } else { - from = ''; - } - from += '<' + (params.from_uri || ua.configuration.uri) + '>;tag='; - from += params.from_tag || Utils.newTag(); - this.from = new NameAddrHeader.parse(from); - this.setHeader('from', from); - - // Call-ID - call_id = params.call_id || (ua.configuration.plivosip_id + Utils.createRandomToken(15)); - this.call_id = call_id; - this.setHeader('call-id', call_id); - - // CSeq - cseq = params.cseq || Math.floor(Math.random() * 10000); - this.cseq = cseq; - this.setHeader('cseq', cseq + ' ' + method); -} - -OutgoingRequest.prototype = { - /** - * Replace the the given header by the given value. - * -param {String} name header name - * -param {String | Array} value header value - */ - setHeader: function(name, value) { - var regexp, idx; - - // Remove the header from extraHeaders if present. - regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); - for (idx=0; idx= this.headers[name].length) { - debug('not so many "' + name + '" headers present'); - return; - } - - header = this.headers[name][idx]; - value = header.raw; - - if(header.parsed) { - return header.parsed; - } - - //substitute '-' by '_' for grammar rule matching. - parsed = Grammar.parse(value, name.replace(/-/g, '_')); - - if(parsed === -1) { - this.headers[name].splice(idx, 1); //delete from headers - debug('error parsing "' + name + '" header field with value "' + value + '"'); - return; - } else { - header.parsed = parsed; - return parsed; - } - }, - - /** - * Message Header attribute selector. Alias of parseHeader. - * -param {String} name header name - * -param {Number} [idx=0] header index - * -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error. - * - * -example - * message.s('via',3).port - */ - s: function(name, idx) { - return this.parseHeader(name, idx); - }, - - /** - * Replace the value of the given header by the value. - * -param {String} name header name - * -param {String} value header value - */ - setHeader: function(name, value) { - var header = { raw: value }; - this.headers[Utils.headerize(name)] = [header]; - }, - - /** - * Parse the current body as a SDP and store the resulting object - * into this.sdp. - * -param {Boolean} force: Parse even if this.sdp already exists. - * - * Returns this.sdp. - */ - parseSDP: function(force) { - if (!force && this.sdp) { - return this.sdp; - } else { - this.sdp = sdp_transform.parse(this.body || ''); - return this.sdp; - } - }, - - toString: function() { - return this.data; - } -}; - - -function IncomingRequest(ua) { - this.ua = ua; - this.headers = {}; - this.ruri = null; - this.transport = null; - this.server_transaction = null; -} - -IncomingRequest.prototype = new IncomingMessage(); - -/** -* Stateful reply. -* -param {Number} code status code -* -param {String} reason reason phrase -* -param {Object} headers extra headers -* -param {String} body body -* -param {Function} [onSuccess] onSuccess callback -* -param {Function} [onFailure] onFailure callback -*/ -IncomingRequest.prototype.reply = function(code, reason, extraHeaders, body, onSuccess, onFailure) { - var rr, vias, length, idx, response, - supported = [], - to = this.getHeader('To'), - r = 0, - v = 0; - - code = code || null; - reason = reason || null; - - // Validate code and reason values - if (!code || (code < 100 || code > 699)) { - throw new TypeError('Invalid status_code: '+ code); - } else if (reason && typeof reason !== 'string' && !(reason instanceof String)) { - throw new TypeError('Invalid reason_phrase: '+ reason); - } - - reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; - extraHeaders = extraHeaders && extraHeaders.slice() || []; - - response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n'; - - if(this.method === JsSIP_C.INVITE && code > 100 && code <= 200) { - rr = this.getHeaders('record-route'); - length = rr.length; - - for(r; r < length; r++) { - response += 'Record-Route: ' + rr[r] + '\r\n'; - } - } - - vias = this.getHeaders('via'); - length = vias.length; - - for(v; v < length; v++) { - response += 'Via: ' + vias[v] + '\r\n'; - } - - if(!this.to_tag && code > 100) { - to += ';tag=' + Utils.newTag(); - } else if(this.to_tag && !this.s('to').hasParam('tag')) { - to += ';tag=' + this.to_tag; - } - - response += 'To: ' + to + '\r\n'; - response += 'From: ' + this.getHeader('From') + '\r\n'; - response += 'Call-ID: ' + this.call_id + '\r\n'; - response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n'; - - length = extraHeaders.length; - for (idx = 0; idx < length; idx++) { - response += extraHeaders[idx].trim() +'\r\n'; - } - - // Supported - switch (this.method) { - case JsSIP_C.INVITE: - if (this.ua.configuration.session_timers) { - supported.push('timer'); - } - if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) { - supported.push('gruu'); - } - supported.push('ice','replaces'); - break; - case JsSIP_C.UPDATE: - if (this.ua.configuration.session_timers) { - supported.push('timer'); - } - if (body) { - supported.push('ice'); - } - supported.push('replaces'); - } - - supported.push('outbound'); - - // Allow and Accept - if (this.method === JsSIP_C.OPTIONS) { - response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; - response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n'; - } else if (code === 405) { - response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; - } else if (code === 415 ) { - response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n'; - } - - response += 'Supported: ' + supported +'\r\n'; - - if(body) { - length = Utils.str_utf8_length(body); - response += 'Content-Type: application/sdp\r\n'; - response += 'Content-Length: ' + length + '\r\n\r\n'; - response += body; - } else { - response += 'Content-Length: ' + 0 + '\r\n\r\n'; - } - - this.server_transaction.receiveResponse(code, response, onSuccess, onFailure); -}; - -/** -* Stateless reply. -* -param {Number} code status code -* -param {String} reason reason phrase -*/ -IncomingRequest.prototype.reply_sl = function(code, reason) { - var to, response, - v = 0, - vias = this.getHeaders('via'), - length = vias.length; - - code = code || null; - reason = reason || null; - - // Validate code and reason values - if (!code || (code < 100 || code > 699)) { - throw new TypeError('Invalid status_code: '+ code); - } else if (reason && typeof reason !== 'string' && !(reason instanceof String)) { - throw new TypeError('Invalid reason_phrase: '+ reason); - } - - reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; - - response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n'; - - for(v; v < length; v++) { - response += 'Via: ' + vias[v] + '\r\n'; - } - - to = this.getHeader('To'); - - if(!this.to_tag && code > 100) { - to += ';tag=' + Utils.newTag(); - } else if(this.to_tag && !this.s('to').hasParam('tag')) { - to += ';tag=' + this.to_tag; - } - - response += 'To: ' + to + '\r\n'; - response += 'From: ' + this.getHeader('From') + '\r\n'; - response += 'Call-ID: ' + this.call_id + '\r\n'; - response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n'; - response += 'Content-Length: ' + 0 + '\r\n\r\n'; - - this.transport.send(response); -}; - - -function IncomingResponse() { - this.headers = {}; - this.status_code = null; - this.reason_phrase = null; -} - -IncomingResponse.prototype = new IncomingMessage(); - -},{"./Constants":35,"./Grammar":40,"./NameAddrHeader":43,"./Utils":59,"debug":11,"sdp-transform":17}],53:[function(require,module,exports){ -module.exports = Socket; - -/** - * Interface documentation: http://jssip.net/documentation/$last_version/api/socket/ - * - * interface Socket { - * attribute String via_transport - * attribute String url - * attribute String sip_uri - * - * method connect(); - * method disconnect(); - * method send(data); - * - * attribute EventHandler onconnect - * attribute EventHandler ondisconnect - * attribute EventHandler ondata - * } - * - */ - - -/** - * Dependencies. - */ -var Utils = require('./Utils'); -var Grammar = require('./Grammar'); -var debugerror = require('debug')('PlivoSIP:ERROR:Socket'); -debugerror.log = console.warn.bind(console); - -function Socket() {} - -Socket.isSocket = function(socket) { - // Ignore if an array is given - if (Array.isArray(socket)) { - return false; - } - - if (typeof socket === 'undefined') { - debugerror('undefined JsSIP.Socket instance'); - return false; - } - - // Check Properties - try { - if (!Utils.isString(socket.url)) { - debugerror('missing or invalid JsSIP.Socket url property'); - throw new Error(); - } - - if (!Utils.isString(socket.via_transport)) { - debugerror('missing or invalid JsSIP.Socket via_transport property'); - throw new Error(); - } - - if (Grammar.parse(socket.sip_uri, 'SIP_URI') === -1) { - debugerror('missing or invalid JsSIP.Socket sip_uri property'); - throw new Error(); - } - } catch(e) { - return false; - } - - // Check Methods - try { - ['connect', 'disconnect', 'send'].forEach(function(method) { - if (!Utils.isFunction(socket[method])) { - debugerror('missing or invalid JsSIP.Socket method: ' + method); - throw new Error(); - } - }); - } catch(e) { - return false; - } - - return true; -}; - -},{"./Grammar":40,"./Utils":59,"debug":11}],54:[function(require,module,exports){ -var T1 = 500, - T2 = 4000, - T4 = 5000; - - -var Timers = { - T1: T1, - T2: T2, - T4: T4, - TIMER_B: 64 * T1, - TIMER_D: 0 * T1, - TIMER_F: 64 * T1, - TIMER_H: 64 * T1, - TIMER_I: 0 * T1, - TIMER_J: 0 * T1, - TIMER_K: 0 * T4, - TIMER_L: 64 * T1, - TIMER_M: 64 * T1, - PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 -}; - - -module.exports = Timers; - -},{}],55:[function(require,module,exports){ -module.exports = { - C: null, - NonInviteClientTransaction: NonInviteClientTransaction, - InviteClientTransaction: InviteClientTransaction, - AckClientTransaction: AckClientTransaction, - NonInviteServerTransaction: NonInviteServerTransaction, - InviteServerTransaction: InviteServerTransaction, - checkTransaction: checkTransaction -}; - - -var C = { - // Transaction states - STATUS_TRYING: 1, - STATUS_PROCEEDING: 2, - STATUS_CALLING: 3, - STATUS_ACCEPTED: 4, - STATUS_COMPLETED: 5, - STATUS_TERMINATED: 6, - STATUS_CONFIRMED: 7, - - // Transaction types - NON_INVITE_CLIENT: 'nict', - NON_INVITE_SERVER: 'nist', - INVITE_CLIENT: 'ict', - INVITE_SERVER: 'ist' -}; - -/** - * Expose C object. - */ -module.exports.C = C; - - -/** - * Dependencies. - */ -var util = require('util'); -var events = require('events'); -var debugnict = require('debug')('PlivoSIP:NonInviteClientTransaction'); -var debugict = require('debug')('PlivoSIP:InviteClientTransaction'); -var debugact = require('debug')('PlivoSIP:AckClientTransaction'); -var debugnist = require('debug')('PlivoSIP:NonInviteServerTransaction'); -var debugist = require('debug')('PlivoSIP:InviteServerTransaction'); -var JsSIP_C = require('./Constants'); -var Timers = require('./Timers'); - - -function NonInviteClientTransaction(request_sender, request, transport) { - var via; - - this.type = C.NON_INVITE_CLIENT; - this.transport = transport; - this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); - this.request_sender = request_sender; - this.request = request; - - via = 'SIP/2.0/' + transport.via_transport; - via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; - - this.request.setHeader('via', via); - - this.request_sender.ua.newTransaction(this); - - events.EventEmitter.call(this); -} - -util.inherits(NonInviteClientTransaction, events.EventEmitter); - -NonInviteClientTransaction.prototype.stateChanged = function(state) { - this.state = state; - this.emit('stateChanged'); -}; - -NonInviteClientTransaction.prototype.send = function() { - var tr = this; - - this.stateChanged(C.STATUS_TRYING); - this.F = setTimeout(function() {tr.timer_F();}, Timers.TIMER_F); - - if(!this.transport.send(this.request)) { - this.onTransportError(); - } -}; - -NonInviteClientTransaction.prototype.onTransportError = function() { - debugnict('transport error occurred, deleting transaction ' + this.id); - clearTimeout(this.F); - clearTimeout(this.K); - this.stateChanged(C.STATUS_TERMINATED); - this.request_sender.ua.destroyTransaction(this); - this.request_sender.onTransportError(); -}; - -NonInviteClientTransaction.prototype.timer_F = function() { - debugnict('Timer F expired for transaction ' + this.id); - this.stateChanged(C.STATUS_TERMINATED); - this.request_sender.ua.destroyTransaction(this); - this.request_sender.onRequestTimeout(); -}; - -NonInviteClientTransaction.prototype.timer_K = function() { - this.stateChanged(C.STATUS_TERMINATED); - this.request_sender.ua.destroyTransaction(this); -}; - -NonInviteClientTransaction.prototype.receiveResponse = function(response) { - var - tr = this, - status_code = response.status_code; - - if(status_code < 200) { - switch(this.state) { - case C.STATUS_TRYING: - case C.STATUS_PROCEEDING: - this.stateChanged(C.STATUS_PROCEEDING); - this.request_sender.receiveResponse(response); - break; - } - } else { - switch(this.state) { - case C.STATUS_TRYING: - case C.STATUS_PROCEEDING: - this.stateChanged(C.STATUS_COMPLETED); - clearTimeout(this.F); - - if(status_code === 408) { - this.request_sender.onRequestTimeout(); - } else { - this.request_sender.receiveResponse(response); - } - - this.K = setTimeout(function() {tr.timer_K();}, Timers.TIMER_K); - break; - case C.STATUS_COMPLETED: - break; - } - } -}; - - -function InviteClientTransaction(request_sender, request, transport) { - var via, - tr = this; - - this.type = C.INVITE_CLIENT; - this.transport = transport; - this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); - this.request_sender = request_sender; - this.request = request; - - via = 'SIP/2.0/' + transport.via_transport; - via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; - - this.request.setHeader('via', via); - - this.request_sender.ua.newTransaction(this); - - // TODO: Adding here the cancel() method is a hack that must be fixed. - // Add the cancel property to the request. - //Will be called from the request instance, not the transaction itself. - this.request.cancel = function(reason) { - tr.cancel_request(tr, reason); - }; - - events.EventEmitter.call(this); -} - -util.inherits(InviteClientTransaction, events.EventEmitter); - -InviteClientTransaction.prototype.stateChanged = function(state) { - this.state = state; - this.emit('stateChanged'); -}; - -InviteClientTransaction.prototype.send = function() { - var tr = this; - this.stateChanged(C.STATUS_CALLING); - this.B = setTimeout(function() { - tr.timer_B(); - }, Timers.TIMER_B); - - if(!this.transport.send(this.request)) { - this.onTransportError(); - } -}; - -InviteClientTransaction.prototype.onTransportError = function() { - clearTimeout(this.B); - clearTimeout(this.D); - clearTimeout(this.M); - - if (this.state !== C.STATUS_ACCEPTED) { - debugict('transport error occurred, deleting transaction ' + this.id); - this.request_sender.onTransportError(); - } - - this.stateChanged(C.STATUS_TERMINATED); - this.request_sender.ua.destroyTransaction(this); -}; - -// RFC 6026 7.2 -InviteClientTransaction.prototype.timer_M = function() { - debugict('Timer M expired for transaction ' + this.id); - - if(this.state === C.STATUS_ACCEPTED) { - clearTimeout(this.B); - this.stateChanged(C.STATUS_TERMINATED); - this.request_sender.ua.destroyTransaction(this); - } -}; - -// RFC 3261 17.1.1 -InviteClientTransaction.prototype.timer_B = function() { - debugict('Timer B expired for transaction ' + this.id); - if(this.state === C.STATUS_CALLING) { - this.stateChanged(C.STATUS_TERMINATED); - this.request_sender.ua.destroyTransaction(this); - this.request_sender.onRequestTimeout(); - } -}; - -InviteClientTransaction.prototype.timer_D = function() { - debugict('Timer D expired for transaction ' + this.id); - clearTimeout(this.B); - this.stateChanged(C.STATUS_TERMINATED); - this.request_sender.ua.destroyTransaction(this); -}; - -InviteClientTransaction.prototype.sendACK = function(response) { - var tr = this; - - this.ack = 'ACK ' + this.request.ruri + ' SIP/2.0\r\n'; - this.ack += 'Via: ' + this.request.headers.Via.toString() + '\r\n'; - - if(this.request.headers.Route) { - this.ack += 'Route: ' + this.request.headers.Route.toString() + '\r\n'; - } - - this.ack += 'To: ' + response.getHeader('to') + '\r\n'; - this.ack += 'From: ' + this.request.headers.From.toString() + '\r\n'; - this.ack += 'Call-ID: ' + this.request.headers['Call-ID'].toString() + '\r\n'; - this.ack += 'CSeq: ' + this.request.headers.CSeq.toString().split(' ')[0]; - this.ack += ' ACK\r\n'; - this.ack += 'Content-Length: 0\r\n\r\n'; - - this.D = setTimeout(function() {tr.timer_D();}, Timers.TIMER_D); - - this.transport.send(this.ack); -}; - -InviteClientTransaction.prototype.cancel_request = function(tr, reason) { - var request = tr.request; - - this.cancel = JsSIP_C.CANCEL + ' ' + request.ruri + ' SIP/2.0\r\n'; - this.cancel += 'Via: ' + request.headers.Via.toString() + '\r\n'; - - if(this.request.headers.Route) { - this.cancel += 'Route: ' + request.headers.Route.toString() + '\r\n'; - } - - this.cancel += 'To: ' + request.headers.To.toString() + '\r\n'; - this.cancel += 'From: ' + request.headers.From.toString() + '\r\n'; - this.cancel += 'Call-ID: ' + request.headers['Call-ID'].toString() + '\r\n'; - this.cancel += 'CSeq: ' + request.headers.CSeq.toString().split(' ')[0] + - ' CANCEL\r\n'; - - if(reason) { - this.cancel += 'Reason: ' + reason + '\r\n'; - } - - this.cancel += 'Content-Length: 0\r\n\r\n'; - - // Send only if a provisional response (>100) has been received. - if(this.state === C.STATUS_PROCEEDING) { - this.transport.send(this.cancel); - } -}; - -InviteClientTransaction.prototype.receiveResponse = function(response) { - var - tr = this, - status_code = response.status_code; - - if(status_code >= 100 && status_code <= 199) { - switch(this.state) { - case C.STATUS_CALLING: - this.stateChanged(C.STATUS_PROCEEDING); - this.request_sender.receiveResponse(response); - break; - case C.STATUS_PROCEEDING: - this.request_sender.receiveResponse(response); - break; - } - } else if(status_code >= 200 && status_code <= 299) { - switch(this.state) { - case C.STATUS_CALLING: - case C.STATUS_PROCEEDING: - this.stateChanged(C.STATUS_ACCEPTED); - this.M = setTimeout(function() { - tr.timer_M(); - }, Timers.TIMER_M); - this.request_sender.receiveResponse(response); - break; - case C.STATUS_ACCEPTED: - this.request_sender.receiveResponse(response); - break; - } - } else if(status_code >= 300 && status_code <= 699) { - switch(this.state) { - case C.STATUS_CALLING: - case C.STATUS_PROCEEDING: - this.stateChanged(C.STATUS_COMPLETED); - this.sendACK(response); - this.request_sender.receiveResponse(response); - break; - case C.STATUS_COMPLETED: - this.sendACK(response); - break; - } - } -}; - - -function AckClientTransaction(request_sender, request, transport) { - var via; - - this.transport = transport; - this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); - this.request_sender = request_sender; - this.request = request; - - via = 'SIP/2.0/' + transport.via_transport; - via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; - - this.request.setHeader('via', via); - - events.EventEmitter.call(this); -} - -util.inherits(AckClientTransaction, events.EventEmitter); - -AckClientTransaction.prototype.send = function() { - if(!this.transport.send(this.request)) { - this.onTransportError(); - } -}; - -AckClientTransaction.prototype.onTransportError = function() { - debugact('transport error occurred for transaction ' + this.id); - this.request_sender.onTransportError(); -}; - - -function NonInviteServerTransaction(request, ua) { - this.type = C.NON_INVITE_SERVER; - this.id = request.via_branch; - this.request = request; - this.transport = request.transport; - this.ua = ua; - this.last_response = ''; - request.server_transaction = this; - - this.state = C.STATUS_TRYING; - - ua.newTransaction(this); - - events.EventEmitter.call(this); -} - -util.inherits(NonInviteServerTransaction, events.EventEmitter); - -NonInviteServerTransaction.prototype.stateChanged = function(state) { - this.state = state; - this.emit('stateChanged'); -}; - -NonInviteServerTransaction.prototype.timer_J = function() { - debugnist('Timer J expired for transaction ' + this.id); - this.stateChanged(C.STATUS_TERMINATED); - this.ua.destroyTransaction(this); -}; - -NonInviteServerTransaction.prototype.onTransportError = function() { - if (!this.transportError) { - this.transportError = true; - - debugnist('transport error occurred, deleting transaction ' + this.id); - - clearTimeout(this.J); - this.stateChanged(C.STATUS_TERMINATED); - this.ua.destroyTransaction(this); - } -}; - -NonInviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) { - var tr = this; - - if(status_code === 100) { - /* RFC 4320 4.1 - * 'A SIP element MUST NOT - * send any provisional response with a - * Status-Code other than 100 to a non-INVITE request.' - */ - switch(this.state) { - case C.STATUS_TRYING: - this.stateChanged(C.STATUS_PROCEEDING); - if(!this.transport.send(response)) { - this.onTransportError(); - } - break; - case C.STATUS_PROCEEDING: - this.last_response = response; - if(!this.transport.send(response)) { - this.onTransportError(); - if (onFailure) { - onFailure(); - } - } else if (onSuccess) { - onSuccess(); - } - break; - } - } else if(status_code >= 200 && status_code <= 699) { - switch(this.state) { - case C.STATUS_TRYING: - case C.STATUS_PROCEEDING: - this.stateChanged(C.STATUS_COMPLETED); - this.last_response = response; - this.J = setTimeout(function() { - tr.timer_J(); - }, Timers.TIMER_J); - if(!this.transport.send(response)) { - this.onTransportError(); - if (onFailure) { - onFailure(); - } - } else if (onSuccess) { - onSuccess(); - } - break; - case C.STATUS_COMPLETED: - break; - } - } -}; - - -function InviteServerTransaction(request, ua) { - this.type = C.INVITE_SERVER; - this.id = request.via_branch; - this.request = request; - this.transport = request.transport; - this.ua = ua; - this.last_response = ''; - request.server_transaction = this; - - this.state = C.STATUS_PROCEEDING; - - ua.newTransaction(this); - - this.resendProvisionalTimer = null; - - request.reply(100); - - events.EventEmitter.call(this); -} - -util.inherits(InviteServerTransaction, events.EventEmitter); - -InviteServerTransaction.prototype.stateChanged = function(state) { - this.state = state; - this.emit('stateChanged'); -}; - -InviteServerTransaction.prototype.timer_H = function() { - debugist('Timer H expired for transaction ' + this.id); - - if(this.state === C.STATUS_COMPLETED) { - debugist('ACK not received, dialog will be terminated'); - } - - this.stateChanged(C.STATUS_TERMINATED); - this.ua.destroyTransaction(this); -}; - -InviteServerTransaction.prototype.timer_I = function() { - this.stateChanged(C.STATUS_TERMINATED); -}; - -// RFC 6026 7.1 -InviteServerTransaction.prototype.timer_L = function() { - debugist('Timer L expired for transaction ' + this.id); - - if(this.state === C.STATUS_ACCEPTED) { - this.stateChanged(C.STATUS_TERMINATED); - this.ua.destroyTransaction(this); - } -}; - -InviteServerTransaction.prototype.onTransportError = function() { - if (!this.transportError) { - this.transportError = true; - - debugist('transport error occurred, deleting transaction ' + this.id); - - if (this.resendProvisionalTimer !== null) { - clearInterval(this.resendProvisionalTimer); - this.resendProvisionalTimer = null; - } - - clearTimeout(this.L); - clearTimeout(this.H); - clearTimeout(this.I); - - this.stateChanged(C.STATUS_TERMINATED); - this.ua.destroyTransaction(this); - } -}; - -InviteServerTransaction.prototype.resend_provisional = function() { - if(!this.transport.send(this.last_response)) { - this.onTransportError(); - } -}; - -// INVITE Server Transaction RFC 3261 17.2.1 -InviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) { - var tr = this; - - if(status_code >= 100 && status_code <= 199) { - switch(this.state) { - case C.STATUS_PROCEEDING: - if(!this.transport.send(response)) { - this.onTransportError(); - } - this.last_response = response; - break; - } - } - - if(status_code > 100 && status_code <= 199 && this.state === C.STATUS_PROCEEDING) { - // Trigger the resendProvisionalTimer only for the first non 100 provisional response. - if(this.resendProvisionalTimer === null) { - this.resendProvisionalTimer = setInterval(function() { - tr.resend_provisional();}, Timers.PROVISIONAL_RESPONSE_INTERVAL); - } - } else if(status_code >= 200 && status_code <= 299) { - switch(this.state) { - case C.STATUS_PROCEEDING: - this.stateChanged(C.STATUS_ACCEPTED); - this.last_response = response; - this.L = setTimeout(function() { - tr.timer_L(); - }, Timers.TIMER_L); - - if (this.resendProvisionalTimer !== null) { - clearInterval(this.resendProvisionalTimer); - this.resendProvisionalTimer = null; - } - /* falls through */ - case C.STATUS_ACCEPTED: - // Note that this point will be reached for proceeding tr.state also. - if(!this.transport.send(response)) { - this.onTransportError(); - if (onFailure) { - onFailure(); - } - } else if (onSuccess) { - onSuccess(); - } - break; - } - } else if(status_code >= 300 && status_code <= 699) { - switch(this.state) { - case C.STATUS_PROCEEDING: - if (this.resendProvisionalTimer !== null) { - clearInterval(this.resendProvisionalTimer); - this.resendProvisionalTimer = null; - } - - if(!this.transport.send(response)) { - this.onTransportError(); - if (onFailure) { - onFailure(); - } - } else { - this.stateChanged(C.STATUS_COMPLETED); - this.H = setTimeout(function() { - tr.timer_H(); - }, Timers.TIMER_H); - if (onSuccess) { - onSuccess(); - } - } - break; - } - } -}; - -/** - * INVITE: - * _true_ if retransmission - * _false_ new request - * - * ACK: - * _true_ ACK to non2xx response - * _false_ ACK must be passed to TU (accepted state) - * ACK to 2xx response - * - * CANCEL: - * _true_ no matching invite transaction - * _false_ matching invite transaction and no final response sent - * - * OTHER: - * _true_ retransmission - * _false_ new request - */ -function checkTransaction(ua, request) { - var tr; - - switch(request.method) { - case JsSIP_C.INVITE: - tr = ua.transactions.ist[request.via_branch]; - if(tr) { - switch(tr.state) { - case C.STATUS_PROCEEDING: - tr.transport.send(tr.last_response); - break; - - // RFC 6026 7.1 Invite retransmission - //received while in C.STATUS_ACCEPTED state. Absorb it. - case C.STATUS_ACCEPTED: - break; - } - return true; - } - break; - case JsSIP_C.ACK: - tr = ua.transactions.ist[request.via_branch]; - - // RFC 6026 7.1 - if(tr) { - if(tr.state === C.STATUS_ACCEPTED) { - return false; - } else if(tr.state === C.STATUS_COMPLETED) { - tr.state = C.STATUS_CONFIRMED; - tr.I = setTimeout(function() {tr.timer_I();}, Timers.TIMER_I); - return true; - } - } - // ACK to 2XX Response. - else { - return false; - } - break; - case JsSIP_C.CANCEL: - tr = ua.transactions.ist[request.via_branch]; - if(tr) { - request.reply_sl(200); - if(tr.state === C.STATUS_PROCEEDING) { - return false; - } else { - return true; - } - } else { - request.reply_sl(481); - return true; - } - break; - default: - - // Non-INVITE Server Transaction RFC 3261 17.2.2 - tr = ua.transactions.nist[request.via_branch]; - if(tr) { - switch(tr.state) { - case C.STATUS_TRYING: - break; - case C.STATUS_PROCEEDING: - case C.STATUS_COMPLETED: - tr.transport.send(tr.last_response); - break; - } - return true; - } - break; - } -} - -},{"./Constants":35,"./Timers":54,"debug":11,"events":13,"util":23}],56:[function(require,module,exports){ -module.exports = Transport; - -/** - * Dependencies. - */ -var Socket = require('./Socket'); -var debug = require('debug')('PlivoSIP:Transport'); -var debugerror = require('debug')('PlivoSIP:ERROR:Transport'); - -/** - * Constants - */ -var C = { - // Transport status - STATUS_CONNECTED: 0, - STATUS_CONNECTING: 1, - STATUS_DISCONNECTED: 2, - - // Socket status - SOCKET_STATUS_READY: 0, - SOCKET_STATUS_ERROR: 1, - - // Recovery options - recovery_options: { - min_interval: 2, // minimum interval in seconds between recover attempts - max_interval: 30 // maximum interval in seconds between recover attempts - } -}; - -/* - * Manages one or multiple JsSIP.Socket instances. - * Is reponsible for transport recovery logic among all socket instances. - * - * @socket JsSIP::Socket instance - */ - -function Transport(sockets, recovery_options) { - debug('new()'); - - this.status = C.STATUS_DISCONNECTED; - - // current socket - this.socket = null; - - // socket collection - this.sockets = []; - - this.recovery_options = recovery_options || C.recovery_options; - this.recover_attempts = 0; - this.recovery_timer = null; - - this.close_requested = false; - - if (typeof sockets === 'undefined') { - throw new TypeError('Invalid argument.' + - ' undefined \'sockets\' argument'); - } - - if (!(sockets instanceof Array)) { - sockets = [ sockets ]; - } - - sockets.forEach(function(socket) { - if (!Socket.isSocket(socket.socket)) { - throw new TypeError('Invalid argument.' + - ' invalid \'JsSIP.Socket\' instance'); - } - - if (socket.weight && !Number(socket.weight)) { - throw new TypeError('Invalid argument.' + - ' \'weight\' attribute is not a number'); - } - - this.sockets.push({ - socket: socket.socket, - weight: socket.weight || 0, - status: C.SOCKET_STATUS_READY - }); - }, this); - - // read only properties - Object.defineProperties(this, { - via_transport: { get: function() { return this.socket.via_transport; } }, - url: { get: function() { return this.socket.url; } }, - sip_uri: { get: function() { return this.socket.sip_uri; } } - }); - - // get the socket with higher weight - getSocket.call(this); -} - -/** - * Instance Methods - */ - -Transport.prototype.connect = function() { - debug('connect()'); - - if (this.isConnected()) { - debug('Transport is already connected'); - return; - } else if (this.isConnecting()) { - debug('Transport is connecting'); - return; - } - - this.close_requested = false; - this.status = C.STATUS_CONNECTING; - this.onconnecting({ socket:this.socket, attempts:this.recover_attempts }); - - if (!this.close_requested) { - // bind socket event callbacks - this.socket.onconnect = onConnect.bind(this); - this.socket.ondisconnect = onDisconnect.bind(this); - this.socket.ondata = onData.bind(this); - - this.socket.connect(); - } - - return; -}; - -Transport.prototype.disconnect = function() { - debug('close()'); - - this.close_requested = true; - this.recover_attempts = 0; - this.status = C.STATUS_DISCONNECTED; - - // clear recovery_timer - if (this.recovery_timer !== null) { - clearTimeout(this.recovery_timer); - this.recovery_timer = null; - } - - // unbind socket event callbacks - this.socket.onconnect = function() {}; - this.socket.ondisconnect = function() {}; - this.socket.ondata = function() {}; - - this.socket.disconnect(); - this.ondisconnect(); -}; - -Transport.prototype.send = function(data) { - debug('send()'); - - if (!this.isConnected()) { - debugerror('unable to send message, transport is not connected'); - return false; - } - - var message = data.toString(); - - debug('sending message:\n\n' + message + '\n'); - return this.socket.send(message); -}; - -Transport.prototype.isConnected = function() { - return this.status === C.STATUS_CONNECTED; -}; - -Transport.prototype.isConnecting = function() { - return this.status === C.STATUS_CONNECTING; -}; - -/** - * Socket Event Handlers - */ - -function onConnect() { - this.recover_attempts = 0; - this.status = C.STATUS_CONNECTED; - - // clear recovery_timer - if (this.recovery_timer !== null) { - clearTimeout(this.recovery_timer); - this.recovery_timer = null; - } - - this.onconnect( {socket:this} ); -} - -function onDisconnect(error, code, reason) { - this.status = C.STATUS_DISCONNECTED; - this.ondisconnect({ socket:this.socket, error:error, code:code, reason:reason }); - - if (this.close_requested) { - return; - } - - // update socket status - if (error) { - this.socket.status = C.SOCKET_STATUS_ERROR; - } - - reconnect.call(this, error); -} - -function onData(data) { - // CRLF Keep Alive response from server. Ignore it. - if(data === '\r\n') { - debug('received message with CRLF Keep Alive response'); - return; - } - - // binary message. - else if (typeof data !== 'string') { - try { - data = String.fromCharCode.apply(null, new Uint8Array(data)); - } catch(evt) { - debug('received binary message failed to be converted into string,' + - ' message discarded'); - return; - } - - debug('received binary message:\n\n' + data + '\n'); - } - - // text message. - else { - debug('received text message:\n\n' + data + '\n'); - } - - this.ondata({ transport:this, message:data }); -} - -function reconnect() { - var k, - self = this; - - this.recover_attempts+=1; - - k = Math.floor((Math.random() * Math.pow(2,this.recover_attempts)) +1); - - if (k < this.recovery_options.min_interval) { - k = this.recovery_options.min_interval; - } - - else if (k > this.recovery_options.max_interval) { - k = this.recovery_options.max_interval; - } - - debug('reconnection attempt: '+ this.recover_attempts + - '. next connection attempt in '+ k +' seconds'); - - this.recovery_timer = setTimeout(function() { - if (!self.close_requested && !(self.isConnected() || self.isConnecting())) { - // get the next available socket with higher weight - getSocket.call(self); - - // connect the socket - self.connect(); - } - }, k * 1000); -} - -/** - * get the next available socket with higher weight - */ -function getSocket() { - - var candidates = []; - - this.sockets.forEach(function(socket) { - if (socket.status === C.SOCKET_STATUS_ERROR) { - return; // continue the array iteration - } else if (candidates.length === 0) { - candidates.push(socket); - } else if (socket.weight > candidates[0].weight) { - candidates = [socket]; - } else if (socket.weight === candidates[0].weight) { - candidates.push(socket); - } - }); - - if (candidates.length === 0) { - // all sockets have failed. reset sockets status - this.sockets.forEach(function(socket) { - socket.status = C.SOCKET_STATUS_READY; - }); - - // get next available socket - getSocket.call(this); - return; - } - - var idx = Math.floor((Math.random()* candidates.length)); - this.socket = candidates[idx].socket; -} - -},{"./Socket":53,"debug":11}],57:[function(require,module,exports){ -module.exports = UA; - - -var C = { - // UA status codes - STATUS_INIT : 0, - STATUS_READY: 1, - STATUS_USER_CLOSED: 2, - STATUS_NOT_READY: 3, - - // UA error codes - CONFIGURATION_ERROR: 1, - NETWORK_ERROR: 2 -}; - -/** - * Expose C object. - */ -UA.C = C; - - -/** - * Dependencies. - */ -var util = require('util'); -var events = require('events'); -var debug = require('debug')('PlivoSIP:UA'); -var debugerror = require('debug')('PlivoSIP:ERROR:UA'); -debugerror.log = console.warn.bind(console); -var JsSIP_C = require('./Constants'); -var Registrator = require('./Registrator'); -var RTCSession = require('./RTCSession'); -var Message = require('./Message'); -var Transactions = require('./Transactions'); -var Transport = require('./Transport'); -var Socket = require('./Socket'); -var Utils = require('./Utils'); -var Exceptions = require('./Exceptions'); -var URI = require('./URI'); -var Grammar = require('./Grammar'); -var Parser = require('./Parser'); -var SIPMessage = require('./SIPMessage'); -var sanityCheck = require('./sanityCheck'); - - - -/** - * The User-Agent class. - * @class JsSIP.UA - * @param {Object} configuration Configuration parameters. - * @throws {JsSIP.Exceptions.ConfigurationError} If a configuration parameter is invalid. - * @throws {TypeError} If no configuration is given. - */ -function UA(configuration) { - - - this.cache = { - credentials: {} - }; - - this.configuration = {}; - this.dynConfiguration = {}; - this.dialogs = {}; - - //User actions outside any session/dialog (MESSAGE) - this.applicants = {}; - - this.sessions = {}; - this.transport = null; - this.contact = null; - this.status = C.STATUS_INIT; - this.error = null; - this.transactions = { - nist: {}, - nict: {}, - ist: {}, - ict: {} - }; - - // Custom UA empty object for high level use - this.data = {}; - - this.closeTimer = null; - - Object.defineProperties(this, { - transactionsCount: { - get: function() { - var type, - transactions = ['nist','nict','ist','ict'], - count = 0; - - for (type in transactions) { - count += Object.keys(this.transactions[transactions[type]]).length; - } - - return count; - } - }, - - nictTransactionsCount: { - get: function() { - return Object.keys(this.transactions.nict).length; - } - }, - - nistTransactionsCount: { - get: function() { - return Object.keys(this.transactions.nist).length; - } - }, - - ictTransactionsCount: { - get: function() { - return Object.keys(this.transactions.ict).length; - } - }, - - istTransactionsCount: { - get: function() { - return Object.keys(this.transactions.ist).length; - } - } - }); - - /** - * Load configuration - */ - - if(configuration === undefined) { - throw new TypeError('Not enough arguments'); - } - - try { - this.loadConfig(configuration); - } catch(e) { - this.status = C.STATUS_NOT_READY; - this.error = C.CONFIGURATION_ERROR; - throw e; - } - - // Initialize registrator - this._registrator = new Registrator(this); - - events.EventEmitter.call(this); -} - -util.inherits(UA, events.EventEmitter); - - -//================= -// High Level API -//================= - -/** - * Connect to the server if status = STATUS_INIT. - * Resume UA after being closed. - */ -UA.prototype.start = function() { - debug('start()'); - - if (this.status === C.STATUS_INIT) { - this.transport.connect(); - } else if(this.status === C.STATUS_USER_CLOSED) { - debug('restarting UA'); - - // disconnect - if (this.closeTimer !== null) { - clearTimeout(this.closeTimer); - this.closeTimer = null; - this.transport.disconnect(); - } - - // reconnect - this.status = C.STATUS_INIT; - this.transport.connect(); - } else if (this.status === C.STATUS_READY) { - debug('UA is in READY status, not restarted'); - } else { - debug('ERROR: connection is down, Auto-Recovery system is trying to reconnect'); - } - - // Set dynamic configuration. - this.dynConfiguration.register = this.configuration.register; -}; - -/** - * Register. - */ -UA.prototype.register = function() { - debug('register()'); - - this.dynConfiguration.register = true; - this._registrator.register(); -}; - -/** - * Unregister. - */ -UA.prototype.unregister = function(options) { - debug('unregister()'); - - this.dynConfiguration.register = false; - this._registrator.unregister(options); -}; - -/** - * Get the Registrator instance. - */ -UA.prototype.registrator = function() { - return this._registrator; -}; - -/** - * Registration state. - */ -UA.prototype.isRegistered = function() { - if(this._registrator.registered) { - return true; - } else { - return false; - } -}; - -/** - * Connection state. - */ -UA.prototype.isConnected = function() { - return this.transport.isConnected(); -}; - -/** - * Make an outgoing call. - * - * -param {String} target - * -param {Object} views - * -param {Object} [options] - * - * -throws {TypeError} - * - */ -UA.prototype.call = function(target, options) { - debug('call()'); - - var session; - - session = new RTCSession(this); - session.connect(target, options); - return session; -}; - -/** - * Send a message. - * - * -param {String} target - * -param {String} body - * -param {Object} [options] - * - * -throws {TypeError} - * - */ -UA.prototype.sendMessage = function(target, body, options) { - debug('sendMessage()'); - - var message; - - message = new Message(this); - message.send(target, body, options); - return message; -}; - -/** - * Terminate ongoing sessions. - */ -UA.prototype.terminateSessions = function(options) { - debug('terminateSessions()'); - - for(var idx in this.sessions) { - if (!this.sessions[idx].isEnded()) { - this.sessions[idx].terminate(options); - } - } -}; - -/** - * Gracefully close. - * - */ -UA.prototype.stop = function() { - debug('stop()'); - - var session; - var applicant; - var num_sessions; - var ua = this; - - // Remove dynamic settings. - this.dynConfiguration = {}; - - if(this.status === C.STATUS_USER_CLOSED) { - debug('UA already closed'); - return; - } - - // Close registrator - this._registrator.close(); - - // If there are session wait a bit so CANCEL/BYE can be sent and their responses received. - num_sessions = Object.keys(this.sessions).length; - - // Run _terminate_ on every Session - for(session in this.sessions) { - debug('closing session ' + session); - try { this.sessions[session].terminate(); } catch(error) {} - } - - // Run _close_ on every applicant - for(applicant in this.applicants) { - try { this.applicants[applicant].close(); } catch(error) {} - } - - this.status = C.STATUS_USER_CLOSED; - - if (this.nistTransactionsCount === 0 && - this.nictTransactionsCount === 0 && - this.ictTransactionsCount === 0 && - this.istTransactionsCount === 0 && - num_sessions === 0) { - ua.transport.disconnect(); - } - else { - this.closeTimer = setTimeout(function() { - ua.closeTimer = null; - ua.transport.disconnect(); - }, 2000); - } -}; - -/** - * Normalice a string into a valid SIP request URI - * -param {String} target - * -returns {JsSIP.URI|undefined} - */ -UA.prototype.normalizeTarget = function(target) { - return Utils.normalizeTarget(target, this.configuration.hostport_params); -}; - -/** - * Allow retrieving configuration and autogenerated fields in runtime. - */ -UA.prototype.get = function(parameter) { - switch(parameter) { - case 'realm': - return this.configuration.realm; - - case 'ha1': - return this.configuration.ha1; - - default: - debugerror('get() | cannot get "%s" parameter in runtime', parameter); - return undefined; - } - - return true; -}; - -/** - * Allow configuration changes in runtime. - * Returns true if the parameter could be set. - */ -UA.prototype.set = function(parameter, value) { - switch(parameter) { - case 'password': { - this.configuration.password = String(value); - break; - } - - case 'realm': { - this.configuration.realm = String(value); - break; - } - - case 'ha1': { - this.configuration.ha1 = String(value); - // Delete the plain SIP password. - this.configuration.password = null; - break; - } - - case 'display_name': { - if (Grammar.parse('"' + value + '"', 'display_name') === -1) { - debugerror('set() | wrong "display_name"'); - return false; - } - this.configuration.display_name = value; - break; - } - - default: - debugerror('set() | cannot set "%s" parameter in runtime', parameter); - return false; - } - - return true; -}; - - -//=============================== -// Private (For internal use) -//=============================== - -// UA.prototype.saveCredentials = function(credentials) { -// this.cache.credentials[credentials.realm] = this.cache.credentials[credentials.realm] || {}; -// this.cache.credentials[credentials.realm][credentials.uri] = credentials; -// }; - -// UA.prototype.getCredentials = function(request) { -// var realm, credentials; - -// realm = request.ruri.host; - -// if (this.cache.credentials[realm] && this.cache.credentials[realm][request.ruri]) { -// credentials = this.cache.credentials[realm][request.ruri]; -// credentials.method = request.method; -// } - -// return credentials; -// }; - - -//========================== -// Event Handlers -//========================== - -/** - * new Transaction - */ -UA.prototype.newTransaction = function(transaction) { - this.transactions[transaction.type][transaction.id] = transaction; - this.emit('newTransaction', { - transaction: transaction - }); -}; - - -/** - * Transaction destroyed. - */ -UA.prototype.destroyTransaction = function(transaction) { - delete this.transactions[transaction.type][transaction.id]; - this.emit('transactionDestroyed', { - transaction: transaction - }); -}; - - -/** - * new Message - */ -UA.prototype.newMessage = function(data) { - this.emit('newMessage', data); -}; - -/** - * new RTCSession - */ -UA.prototype.newRTCSession = function(data) { - this.emit('newRTCSession', data); -}; - -/** - * Registered - */ -UA.prototype.registered = function(data) { - this.emit('registered', data); -}; - - -/** - * Unregistered - */ -UA.prototype.unregistered = function(data) { - this.emit('unregistered', data); -}; - - -/** - * Registration Failed - */ -UA.prototype.registrationFailed = function(data) { - this.emit('registrationFailed', data); -}; - - -//========================= -// receiveRequest -//========================= - -/** - * Request reception - */ -UA.prototype.receiveRequest = function(request) { - var dialog, session, message, replaces, - method = request.method; - - // Check that request URI points to us - if(request.ruri.user !== this.configuration.uri.user && request.ruri.user !== this.contact.uri.user) { - debug('Request-URI does not point to us'); - if (request.method !== JsSIP_C.ACK) { - request.reply_sl(404); - } - return; - } - - // Check request URI scheme - if(request.ruri.scheme === JsSIP_C.SIPS) { - request.reply_sl(416); - return; - } - - // Check transaction - if(Transactions.checkTransaction(this, request)) { - return; - } - - // Create the server transaction - if(method === JsSIP_C.INVITE) { - new Transactions.InviteServerTransaction(request, this); - } else if(method !== JsSIP_C.ACK && method !== JsSIP_C.CANCEL) { - new Transactions.NonInviteServerTransaction(request, this); - } - - /* RFC3261 12.2.2 - * Requests that do not change in any way the state of a dialog may be - * received within a dialog (for example, an OPTIONS request). - * They are processed as if they had been received outside the dialog. - */ - if(method === JsSIP_C.OPTIONS) { - request.reply(200); - } else if (method === JsSIP_C.MESSAGE) { - if (this.listeners('newMessage').length === 0) { - request.reply(405); - return; - } - message = new Message(this); - message.init_incoming(request); - } else if (method === JsSIP_C.INVITE) { - // Initial INVITE - if(!request.to_tag && this.listeners('newRTCSession').length === 0) { - request.reply(405); - return; - } - } - - // Initial Request - if(!request.to_tag) { - switch(method) { - case JsSIP_C.INVITE: - if (window.RTCPeerConnection) { // TODO - if (request.hasHeader('replaces')) { - replaces = request.replaces; - dialog = this.findDialog(replaces.call_id, replaces.from_tag, replaces.to_tag); - if (dialog) { - session = dialog.owner; - if (!session.isEnded()) { - session.receiveRequest(request); - } else { - request.reply(603); - } - } else { - request.reply(481); - } - } else { - session = new RTCSession(this); - session.init_incoming(request); - } - } else { - debugerror('INVITE received but WebRTC is not supported'); - request.reply(488); - } - break; - case JsSIP_C.BYE: - // Out of dialog BYE received - request.reply(481); - break; - case JsSIP_C.CANCEL: - session = this.findSession(request); - if (session) { - session.receiveRequest(request); - } else { - debug('received CANCEL request for a non existent session'); - } - break; - case JsSIP_C.ACK: - /* Absorb it. - * ACK request without a corresponding Invite Transaction - * and without To tag. - */ - break; - default: - request.reply(405); - break; - } - } - // In-dialog request - else { - dialog = this.findDialog(request.call_id, request.from_tag, request.to_tag); - - if(dialog) { - dialog.receiveRequest(request); - } else if (method === JsSIP_C.NOTIFY) { - session = this.findSession(request); - if(session) { - session.receiveRequest(request); - } else { - debug('received NOTIFY request for a non existent subscription'); - request.reply(481, 'Subscription does not exist'); - } - } - /* RFC3261 12.2.2 - * Request with to tag, but no matching dialog found. - * Exception: ACK for an Invite request for which a dialog has not - * been created. - */ - else { - if(method !== JsSIP_C.ACK) { - request.reply(481); - } - } - } -}; - -//================= -// Utils -//================= - -/** - * Get the session to which the request belongs to, if any. - */ -UA.prototype.findSession = function(request) { - var - sessionIDa = request.call_id + request.from_tag, - sessionA = this.sessions[sessionIDa], - sessionIDb = request.call_id + request.to_tag, - sessionB = this.sessions[sessionIDb]; - - if(sessionA) { - return sessionA; - } else if(sessionB) { - return sessionB; - } else { - return null; - } -}; - -/** - * Get the dialog to which the request belongs to, if any. - */ -UA.prototype.findDialog = function(call_id, from_tag, to_tag) { - var - id = call_id + from_tag + to_tag, - dialog = this.dialogs[id]; - - if(dialog) { - return dialog; - } else { - id = call_id + to_tag + from_tag; - dialog = this.dialogs[id]; - if(dialog) { - return dialog; - } else { - return null; - } - } -}; - -UA.prototype.loadConfig = function(configuration) { - // Settings and default values - var parameter, value, checked_value, hostport_params, registrar_server, - settings = { - /* Host address - * Value to be set in Via sent_by and host part of Contact FQDN - */ - via_host: Utils.createRandomToken(12) + '.invalid', - - // SIP Contact URI - contact_uri: null, - - // SIP authentication password - password: null, - - // SIP authentication realm - realm: null, - - // SIP authentication HA1 hash - ha1: null, - - // Registration parameters - register_expires: 600, - register: true, - registrar_server: null, - - use_preloaded_route: false, - - // Session parameters - no_answer_timeout: 60, - session_timers: true, - }; - - // Pre-Configuration - - // Check Mandatory parameters - for(parameter in UA.configuration_check.mandatory) { - if(!configuration.hasOwnProperty(parameter)) { - throw new Exceptions.ConfigurationError(parameter); - } else { - value = configuration[parameter]; - checked_value = UA.configuration_check.mandatory[parameter].call(this, value); - if (checked_value !== undefined) { - settings[parameter] = checked_value; - } else { - throw new Exceptions.ConfigurationError(parameter, value); - } - } - } - - // Check Optional parameters - for(parameter in UA.configuration_check.optional) { - if(configuration.hasOwnProperty(parameter)) { - value = configuration[parameter]; - - /* If the parameter value is null, empty string, undefined, empty array - * or it's a number with NaN value, then apply its default value. - */ - if (Utils.isEmpty(value)) { - continue; - } - - checked_value = UA.configuration_check.optional[parameter].call(this, value, configuration); - if (checked_value !== undefined) { - settings[parameter] = checked_value; - } else { - throw new Exceptions.ConfigurationError(parameter, value); - } - } - } - - // Post Configuration Process - - // Allow passing 0 number as display_name. - if (settings.display_name === 0) { - settings.display_name = '0'; - } - - // Instance-id for GRUU. - if (!settings.instance_id) { - settings.instance_id = Utils.newUUID(); - } - - // plivosip_id instance parameter. Static random tag of length 5. - settings.plivosip_id = Utils.createRandomToken(5); - - // String containing settings.uri without scheme and user. - hostport_params = settings.uri.clone(); - hostport_params.user = null; - settings.hostport_params = hostport_params.toString().replace(/^sip:/i, ''); - - // Transport - var sockets = []; - - if (settings.sockets && Array.isArray(settings.sockets)) { - sockets = sockets.concat(settings.sockets); - } - - if (sockets.length === 0) { - throw new Exceptions.ConfigurationError('sockets'); - } - - try { - this.transport = new Transport(sockets, { /* recovery options */ - max_interval: settings.connection_recovery_max_interval, - min_interval: settings.connection_recovery_min_interval - }); - - // Transport event callbacks - this.transport.onconnecting = onTransportConnecting.bind(this); - this.transport.onconnect = onTransportConnect.bind(this); - this.transport.ondisconnect = onTransportDisconnect.bind(this); - this.transport.ondata = onTransportData.bind(this); - - // transport options not needed here anymore - delete settings.connection_recovery_max_interval; - delete settings.connection_recovery_min_interval; - delete settings.sockets; - } catch (e) { - debugerror(e); - throw new Exceptions.ConfigurationError('sockets', sockets); - } - - // Check whether authorization_user is explicitly defined. - // Take 'settings.uri.user' value if not. - if (!settings.authorization_user) { - settings.authorization_user = settings.uri.user; - } - - // If no 'registrar_server' is set use the 'uri' value without user portion and - // without URI params/headers. - if (!settings.registrar_server) { - registrar_server = settings.uri.clone(); - registrar_server.user = null; - registrar_server.clearParams(); - registrar_server.clearHeaders(); - settings.registrar_server = registrar_server; - } - - // User no_answer_timeout. - settings.no_answer_timeout = settings.no_answer_timeout * 1000; - - // Via Host - if (settings.contact_uri) { - settings.via_host = settings.contact_uri.host; - } - - // Contact URI - else { - settings.contact_uri = new URI('sip', Utils.createRandomToken(8), settings.via_host, null, {transport: 'ws'}); - } - - this.contact = { - pub_gruu: null, - temp_gruu: null, - uri: settings.contact_uri, - toString: function(options) { - options = options || {}; - - var - anonymous = options.anonymous || null, - outbound = options.outbound || null, - contact = '<'; - - if (anonymous) { - contact += this.temp_gruu || 'sip:anonymous@anonymous.invalid;transport=ws'; - } else { - contact += this.pub_gruu || this.uri.toString(); - } - - if (outbound && (anonymous ? !this.temp_gruu : !this.pub_gruu)) { - contact += ';ob'; - } - - contact += '>'; - - return contact; - } - }; - - // Fill the value of the configuration_skeleton - for(parameter in settings) { - UA.configuration_skeleton[parameter].value = settings[parameter]; - } - - Object.defineProperties(this.configuration, UA.configuration_skeleton); - - // Clean UA.configuration_skeleton - for(parameter in settings) { - UA.configuration_skeleton[parameter].value = ''; - } - - - for(parameter in settings) { - switch(parameter) { - case 'uri': - case 'registrar_server': - debug('- ' + parameter + ': ' + settings[parameter]); - break; - case 'password': - case 'ha1': - debug('- ' + parameter + ': ' + 'NOT SHOWN'); - break; - default: - debug('- ' + parameter + ': ' + JSON.stringify(settings[parameter])); - } - } - - return; -}; - -/** - * Configuration Object skeleton. - */ -UA.configuration_skeleton = (function() { - var - idx, parameter, writable, - skeleton = {}, - parameters = [ - // Internal parameters - 'plivosip_id', - 'hostport_params', - - // Mandatory user configurable parameters - 'uri', - - // Optional user configurable parameters - 'authorization_user', - 'contact_uri', - 'display_name', - 'instance_id', - 'no_answer_timeout', // 30 seconds - 'session_timers', // true - 'password', - 'realm', - 'ha1', - 'register_expires', // 600 seconds - 'registrar_server', - 'sockets', - 'use_preloaded_route', - - // Post-configuration generated parameters - 'via_core_value', - 'via_host' - ]; - - var writable_parameters = [ - 'password', 'realm', 'ha1', 'display_name' - ]; - - for(idx in parameters) { - parameter = parameters[idx]; - - if (writable_parameters.indexOf(parameter) !== -1) { - writable = true; - } else { - writable = false; - } - - skeleton[parameter] = { - value: '', - writable: writable, - configurable: false - }; - } - - skeleton.register = { - value: '', - writable: true, - configurable: false - }; - - return skeleton; -}()); - -/** - * Configuration checker. - */ -UA.configuration_check = { - mandatory: { - - uri: function(uri) { - var parsed; - - if (!/^sip:/i.test(uri)) { - uri = JsSIP_C.SIP + ':' + uri; - } - parsed = URI.parse(uri); - - if(!parsed) { - return; - } else if(!parsed.user) { - return; - } else { - return parsed; - } - } - }, - - optional: { - - authorization_user: function(authorization_user) { - if(Grammar.parse('"'+ authorization_user +'"', 'quoted_string') === -1) { - return; - } else { - return authorization_user; - } - }, - - connection_recovery_max_interval: function(connection_recovery_max_interval) { - var value; - if(Utils.isDecimal(connection_recovery_max_interval)) { - value = Number(connection_recovery_max_interval); - if(value > 0) { - return value; - } - } - }, - - connection_recovery_min_interval: function(connection_recovery_min_interval) { - var value; - if(Utils.isDecimal(connection_recovery_min_interval)) { - value = Number(connection_recovery_min_interval); - if(value > 0) { - return value; - } - } - }, - - contact_uri: function(contact_uri) { - if (typeof contact_uri === 'string') { - var uri = Grammar.parse(contact_uri,'SIP_URI'); - if (uri !== -1) { - return uri; - } - } - }, - - display_name: function(display_name) { - if (Grammar.parse('"' + display_name + '"', 'display_name') === -1) { - return; - } else { - return display_name; - } - }, - - instance_id: function(instance_id) { - if ((/^uuid:/i.test(instance_id))) { - instance_id = instance_id.substr(5); - } - - if(Grammar.parse(instance_id, 'uuid') === -1) { - return; - } else { - return instance_id; - } - }, - - no_answer_timeout: function(no_answer_timeout) { - var value; - if (Utils.isDecimal(no_answer_timeout)) { - value = Number(no_answer_timeout); - if (value > 0) { - return value; - } - } - }, - - session_timers: function(session_timers) { - if (typeof session_timers === 'boolean') { - return session_timers; - } - }, - - password: function(password) { - return String(password); - }, - - realm: function(realm) { - return String(realm); - }, - - ha1: function(ha1) { - return String(ha1); - }, - - register: function(register) { - if (typeof register === 'boolean') { - return register; - } - }, - - register_expires: function(register_expires) { - var value; - if (Utils.isDecimal(register_expires)) { - value = Number(register_expires); - if (value > 0) { - return value; - } - } - }, - - registrar_server: function(registrar_server) { - var parsed; - - if (!/^sip:/i.test(registrar_server)) { - registrar_server = JsSIP_C.SIP + ':' + registrar_server; - } - parsed = URI.parse(registrar_server); - - if(!parsed) { - return; - } else if(parsed.user) { - return; - } else { - return parsed; - } - }, - - sockets: function(sockets) { - var idx, length; - - /* Allow defining sockets parameter as: - * Socket: socket - * Array of Socket: [socket1, socket2] - * Array of Objects: [{socket: socket1, weight:1}, {socket: Socket2, weight:0}] - * Array of Objects and Socket: [{socket: socket1}, socket2] - */ - if (Socket.isSocket(sockets)) { - sockets = [{socket: sockets}]; - } else if (Array.isArray(sockets) && sockets.length) { - length = sockets.length; - for (idx = 0; idx < length; idx++) { - if (Socket.isSocket(sockets[idx])) { - sockets[idx] = {socket: sockets[idx]}; - } - } - } else { - return; - } - - return sockets; - }, - - use_preloaded_route: function(use_preloaded_route) { - if (typeof use_preloaded_route === 'boolean') { - return use_preloaded_route; - } - } - } -}; - -/** - * Transport event handlers - */ - -// Transport connecting event -function onTransportConnecting(data) { - this.emit('connecting', data); -} - -// Transport connected event. -function onTransportConnect(data) { - if(this.status === C.STATUS_USER_CLOSED) { - return; - } - - this.status = C.STATUS_READY; - this.error = null; - - this.emit('connected', data); - - if(this.dynConfiguration.register) { - this._registrator.register(); - } -} - -// Transport disconnected event. -function onTransportDisconnect(data) { - // Run _onTransportError_ callback on every client transaction using _transport_ - var type, idx, length, - client_transactions = ['nict', 'ict', 'nist', 'ist']; - - length = client_transactions.length; - for (type = 0; type < length; type++) { - for(idx in this.transactions[client_transactions[type]]) { - this.transactions[client_transactions[type]][idx].onTransportError(); - } - } - - this.emit('disconnected', data); - - // Call registrator _onTransportClosed_ - this._registrator.onTransportClosed(); - - if (this.status !== C.STATUS_USER_CLOSED) { - this.status = C.STATUS_NOT_READY; - this.error = C.NETWORK_ERROR; - } -} - -// Transport data event -function onTransportData(data) { - var transaction, - transport = data.transport, - message = data.message; - - message = Parser.parseMessage(message, this); - - if (! message) { - return; - } - - if (this.status === UA.C.STATUS_USER_CLOSED && - message instanceof SIPMessage.IncomingRequest) { - return; - } - - // Do some sanity check - if(! sanityCheck(message, this, transport)) { - return; - } - - if(message instanceof SIPMessage.IncomingRequest) { - message.transport = transport; - this.receiveRequest(message); - } else if(message instanceof SIPMessage.IncomingResponse) { - /* Unike stated in 18.1.2, if a response does not match - * any transaction, it is discarded here and no passed to the core - * in order to be discarded there. - */ - switch(message.method) { - case JsSIP_C.INVITE: - transaction = this.transactions.ict[message.via_branch]; - if(transaction) { - transaction.receiveResponse(message); - } - break; - case JsSIP_C.ACK: - // Just in case ;-) - break; - default: - transaction = this.transactions.nict[message.via_branch]; - if(transaction) { - transaction.receiveResponse(message); - } - break; - } - } -} - -},{"./Constants":35,"./Exceptions":39,"./Grammar":40,"./Message":42,"./Parser":44,"./RTCSession":45,"./Registrator":50,"./SIPMessage":52,"./Socket":53,"./Transactions":55,"./Transport":56,"./URI":58,"./Utils":59,"./sanityCheck":61,"debug":11,"events":13,"util":23}],58:[function(require,module,exports){ -module.exports = URI; - - -/** - * Dependencies. - */ -var JsSIP_C = require('./Constants'); -var Utils = require('./Utils'); -var Grammar = require('./Grammar'); - - -/** - * -param {String} [scheme] - * -param {String} [user] - * -param {String} host - * -param {String} [port] - * -param {Object} [parameters] - * -param {Object} [headers] - * - */ -function URI(scheme, user, host, port, parameters, headers) { - var param, header; - - // Checks - if(!host) { - throw new TypeError('missing or invalid "host" parameter'); - } - - // Initialize parameters - scheme = scheme || JsSIP_C.SIP; - this.parameters = {}; - this.headers = {}; - - for (param in parameters) { - this.setParam(param, parameters[param]); - } - - for (header in headers) { - this.setHeader(header, headers[header]); - } - - Object.defineProperties(this, { - scheme: { - get: function(){ return scheme; }, - set: function(value){ - scheme = value.toLowerCase(); - } - }, - - user: { - get: function(){ return user; }, - set: function(value){ - user = value; - } - }, - - host: { - get: function(){ return host; }, - set: function(value){ - host = value.toLowerCase(); - } - }, - - port: { - get: function(){ return port; }, - set: function(value){ - port = value === 0 ? value : (parseInt(value,10) || null); - } - } - }); -} - - -URI.prototype = { - setParam: function(key, value) { - if(key) { - this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString(); - } - }, - - getParam: function(key) { - if(key) { - return this.parameters[key.toLowerCase()]; - } - }, - - hasParam: function(key) { - if(key) { - return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false; - } - }, - - deleteParam: function(parameter) { - var value; - parameter = parameter.toLowerCase(); - if (this.parameters.hasOwnProperty(parameter)) { - value = this.parameters[parameter]; - delete this.parameters[parameter]; - return value; - } - }, - - clearParams: function() { - this.parameters = {}; - }, - - setHeader: function(name, value) { - this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value]; - }, - - getHeader: function(name) { - if(name) { - return this.headers[Utils.headerize(name)]; - } - }, - - hasHeader: function(name) { - if(name) { - return (this.headers.hasOwnProperty(Utils.headerize(name)) && true) || false; - } - }, - - deleteHeader: function(header) { - var value; - header = Utils.headerize(header); - if(this.headers.hasOwnProperty(header)) { - value = this.headers[header]; - delete this.headers[header]; - return value; - } - }, - - clearHeaders: function() { - this.headers = {}; - }, - - clone: function() { - return new URI( - this.scheme, - this.user, - this.host, - this.port, - JSON.parse(JSON.stringify(this.parameters)), - JSON.parse(JSON.stringify(this.headers))); - }, - - toString: function(){ - var header, parameter, idx, uri, - headers = []; - - uri = this.scheme + ':'; - if (this.user) { - uri += Utils.escapeUser(this.user) + '@'; - } - uri += this.host; - if (this.port || this.port === 0) { - uri += ':' + this.port; - } - - for (parameter in this.parameters) { - uri += ';' + parameter; - - if (this.parameters[parameter] !== null) { - uri += '='+ this.parameters[parameter]; - } - } - - for(header in this.headers) { - for(idx = 0; idx < this.headers[header].length; idx++) { - headers.push(header + '=' + this.headers[header][idx]); - } - } - - if (headers.length > 0) { - uri += '?' + headers.join('&'); - } - - return uri; - }, - - toAor: function(show_port){ - var aor; - - aor = this.scheme + ':'; - if (this.user) { - aor += Utils.escapeUser(this.user) + '@'; - } - aor += this.host; - if (show_port && (this.port || this.port === 0)) { - aor += ':' + this.port; - } - - return aor; - } -}; - - -/** - * Parse the given string and returns a JsSIP.URI instance or undefined if - * it is an invalid URI. - */ -URI.parse = function(uri) { - uri = Grammar.parse(uri,'SIP_URI'); - - if (uri !== -1) { - return uri; - } else { - return undefined; - } -}; - -},{"./Constants":35,"./Grammar":40,"./Utils":59}],59:[function(require,module,exports){ -var Utils = {}; - -module.exports = Utils; - - -/** - * Dependencies. - */ -var JsSIP_C = require('./Constants'); -var URI = require('./URI'); -var Grammar = require('./Grammar'); - - -Utils.str_utf8_length = function(string) { - return unescape(encodeURIComponent(string)).length; -}; - -Utils.isFunction = function(fn) { - if (fn !== undefined) { - return (Object.prototype.toString.call(fn) === '[object Function]')? true : false; - } else { - return false; - } -}; - -Utils.isString = function(str) { - if (str !== undefined) { - return (Object.prototype.toString.call(str) === '[object String]')? true : false; - } else { - return false; - } -}; - -Utils.isDecimal = function(num) { - return !isNaN(num) && (parseFloat(num) === parseInt(num,10)); -}; - -Utils.isEmpty = function(value) { - if (value === null || value === '' || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof(value) === 'number' && isNaN(value))) { - return true; - } -}; - -Utils.hasMethods = function(obj /*, method list as strings */){ - var i = 1, methodName; - while((methodName = arguments[i++])){ - if(this.isFunction(obj[methodName])) { - return false; - } - } - return true; -}; - -Utils.createRandomToken = function(size, base) { - var i, r, - token = ''; - - base = base || 32; - - for( i=0; i < size; i++ ) { - r = Math.random() * base|0; - token += r.toString(base); - } - return token; -}; - -Utils.newTag = function() { - return Utils.createRandomToken(10); -}; - -// http://stackoverflow.com/users/109538/broofa -Utils.newUUID = function() { - var UUID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); - return v.toString(16); - }); - - return UUID; -}; - -Utils.hostType = function(host) { - if (!host) { - return; - } else { - host = Grammar.parse(host,'host'); - if (host !== -1) { - return host.host_type; - } - } -}; - -/** -* Normalize SIP URI. -* NOTE: It does not allow a SIP URI without username. -* Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. -* Detects the domain part (if given) and properly hex-escapes the user portion. -* If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. -*/ -Utils.normalizeTarget = function(target, domain) { - var uri, target_array, target_user, target_domain; - - // If no target is given then raise an error. - if (!target) { - return; - // If a URI instance is given then return it. - } else if (target instanceof URI) { - return target; - - // If a string is given split it by '@': - // - Last fragment is the desired domain. - // - Otherwise append the given domain argument. - } else if (typeof target === 'string') { - target_array = target.split('@'); - - switch(target_array.length) { - case 1: - if (!domain) { - return; - } - target_user = target; - target_domain = domain; - break; - case 2: - target_user = target_array[0]; - target_domain = target_array[1]; - break; - default: - target_user = target_array.slice(0, target_array.length-1).join('@'); - target_domain = target_array[target_array.length-1]; - } - - // Remove the URI scheme (if present). - target_user = target_user.replace(/^(sips?|tel):/i, ''); - - // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. - if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(target_user)) { - target_user = target_user.replace(/[\-\.\(\)]/g, ''); - } - - // Build the complete SIP URI. - target = JsSIP_C.SIP + ':' + Utils.escapeUser(target_user) + '@' + target_domain; - - // Finally parse the resulting URI. - if ((uri = URI.parse(target))) { - return uri; - } else { - return; - } - } else { - return; - } -}; - -/** -* Hex-escape a SIP URI user. -*/ -Utils.escapeUser = function(user) { - // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). - return encodeURIComponent(decodeURIComponent(user)).replace(/%3A/ig, ':').replace(/%2B/ig, '+').replace(/%3F/ig, '?').replace(/%2F/ig, '/'); -}; - -Utils.headerize = function(string) { - var exceptions = { - 'Call-Id': 'Call-ID', - 'Cseq': 'CSeq', - 'Www-Authenticate': 'WWW-Authenticate' - }, - name = string.toLowerCase().replace(/_/g,'-').split('-'), - hname = '', - parts = name.length, part; - - for (part = 0; part < parts; part++) { - if (part !== 0) { - hname +='-'; - } - hname += name[part].charAt(0).toUpperCase()+name[part].substring(1); - } - if (exceptions[hname]) { - hname = exceptions[hname]; - } - return hname; -}; - -Utils.sipErrorCause = function(status_code) { - var cause; - - for (cause in JsSIP_C.SIP_ERROR_CAUSES) { - if (JsSIP_C.SIP_ERROR_CAUSES[cause].indexOf(status_code) !== -1) { - return JsSIP_C.causes[cause]; - } - } - - return JsSIP_C.causes.SIP_FAILURE_CODE; -}; - -/** -* Generate a random Test-Net IP (http://tools.ietf.org/html/rfc5735) -*/ -Utils.getRandomTestNetIP = function() { - function getOctet(from,to) { - return Math.floor(Math.random()*(to-from+1)+from); - } - return '192.0.2.' + getOctet(1, 254); -}; - -// MD5 (Message-Digest Algorithm) http://www.webtoolkit.info -Utils.calculateMD5 = function(string) { - function rotateLeft(lValue, iShiftBits) { - return (lValue<>>(32-iShiftBits)); - } - - function addUnsigned(lX,lY) { - var lX4,lY4,lX8,lY8,lResult; - lX8 = (lX & 0x80000000); - lY8 = (lY & 0x80000000); - lX4 = (lX & 0x40000000); - lY4 = (lY & 0x40000000); - lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF); - if (lX4 & lY4) { - return (lResult ^ 0x80000000 ^ lX8 ^ lY8); - } - if (lX4 | lY4) { - if (lResult & 0x40000000) { - return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); - } else { - return (lResult ^ 0x40000000 ^ lX8 ^ lY8); - } - } else { - return (lResult ^ lX8 ^ lY8); - } - } - - function doF(x,y,z) { - return (x & y) | ((~x) & z); - } - - function doG(x,y,z) { - return (x & z) | (y & (~z)); - } - - function doH(x,y,z) { - return (x ^ y ^ z); - } - - function doI(x,y,z) { - return (y ^ (x | (~z))); - } - - function doFF(a,b,c,d,x,s,ac) { - a = addUnsigned(a, addUnsigned(addUnsigned(doF(b, c, d), x), ac)); - return addUnsigned(rotateLeft(a, s), b); - } - - function doGG(a,b,c,d,x,s,ac) { - a = addUnsigned(a, addUnsigned(addUnsigned(doG(b, c, d), x), ac)); - return addUnsigned(rotateLeft(a, s), b); - } - - function doHH(a,b,c,d,x,s,ac) { - a = addUnsigned(a, addUnsigned(addUnsigned(doH(b, c, d), x), ac)); - return addUnsigned(rotateLeft(a, s), b); - } - - function doII(a,b,c,d,x,s,ac) { - a = addUnsigned(a, addUnsigned(addUnsigned(doI(b, c, d), x), ac)); - return addUnsigned(rotateLeft(a, s), b); - } - - function convertToWordArray(string) { - var lWordCount; - var lMessageLength = string.length; - var lNumberOfWords_temp1=lMessageLength + 8; - var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64; - var lNumberOfWords = (lNumberOfWords_temp2+1)*16; - var lWordArray = new Array(lNumberOfWords-1); - var lBytePosition = 0; - var lByteCount = 0; - while ( lByteCount < lMessageLength ) { - lWordCount = (lByteCount-(lByteCount % 4))/4; - lBytePosition = (lByteCount % 4)*8; - lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<>>29; - return lWordArray; - } - - function wordToHex(lValue) { - var wordToHexValue='',wordToHexValue_temp='',lByte,lCount; - for (lCount = 0;lCount<=3;lCount++) { - lByte = (lValue>>>(lCount*8)) & 255; - wordToHexValue_temp = '0' + lByte.toString(16); - wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2); - } - return wordToHexValue; - } - - function utf8Encode(string) { - string = string.replace(/\r\n/g, '\n'); - var utftext = ''; - - for (var n = 0; n < string.length; n++) { - var c = string.charCodeAt(n); - - if (c < 128) { - utftext += String.fromCharCode(c); - } - else if((c > 127) && (c < 2048)) { - utftext += String.fromCharCode((c >> 6) | 192); - utftext += String.fromCharCode((c & 63) | 128); - } - else { - utftext += String.fromCharCode((c >> 12) | 224); - utftext += String.fromCharCode(((c >> 6) & 63) | 128); - utftext += String.fromCharCode((c & 63) | 128); - } - } - return utftext; - } - - var x=[]; - var k,AA,BB,CC,DD,a,b,c,d; - var S11=7, S12=12, S13=17, S14=22; - var S21=5, S22=9 , S23=14, S24=20; - var S31=4, S32=11, S33=16, S34=23; - var S41=6, S42=10, S43=15, S44=21; - - string = utf8Encode(string); - - x = convertToWordArray(string); - - a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; - - for (k=0;k 1) { - debug('more than one Via header field present in the response, dropping the response'); - return false; - } -} - -function rfc3261_18_3_response() { - var - len = Utils.str_utf8_length(message.body), - contentLength = message.getHeader('content-length'); - - if(len < contentLength) { - debug('message body length is lower than the value in Content-Length header field, dropping the response'); - return false; - } -} - -// Sanity Check functions for requests and responses -function minimumHeaders() { - var - mandatoryHeaders = ['from', 'to', 'call_id', 'cseq', 'via'], - idx = mandatoryHeaders.length; - - while(idx--) { - if(!message.hasHeader(mandatoryHeaders[idx])) { - debug('missing mandatory header field : ' + mandatoryHeaders[idx] + ', dropping the response'); - return false; - } - } -} - -// Reply -function reply(status_code) { - var to, - response = 'SIP/2.0 ' + status_code + ' ' + JsSIP_C.REASON_PHRASE[status_code] + '\r\n', - vias = message.getHeaders('via'), - length = vias.length, - idx = 0; - - for(idx; idx < length; idx++) { - response += 'Via: ' + vias[idx] + '\r\n'; - } - - to = message.getHeader('To'); - - if(!message.to_tag) { - to += ';tag=' + Utils.newTag(); - } - - response += 'To: ' + to + '\r\n'; - response += 'From: ' + message.getHeader('From') + '\r\n'; - response += 'Call-ID: ' + message.call_id + '\r\n'; - response += 'CSeq: ' + message.cseq + ' ' + message.method + '\r\n'; - response += '\r\n'; - - transport.send(response); -} - -},{"./Constants":35,"./SIPMessage":52,"./Utils":59,"debug":11}]},{},[1]); -return bundle(id)})(); \ No newline at end of file diff --git a/webApp-plivo/public/js/plivowebsdk.min.js b/webApp-plivo/public/js/plivowebsdk.min.js new file mode 100644 index 0000000..12c5359 --- /dev/null +++ b/webApp-plivo/public/js/plivowebsdk.min.js @@ -0,0 +1,13737 @@ +/* Name: JsSIP Maintainer: José Luis Millán Copyright (c) 2012-2016 José Luis Millán License: The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ +/*Copyright (c) 2013-2016, callstats.io All rights reserved.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/ +var Plivo=function(){var e=1,t=function n(e,t,r){function i(s,a){if(!t[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var c=t[s]={exports:{}};e[s][0].call(c.exports,function(t){var n=e[s][1][t];return i(n?n:t)},c,c.exports,n,e,t,r)}return t[s].exports}for(var o="function"==typeof require&&require,s=0;s1e3){var t={state:"disconnected",eventCode:e.code,eventReason:e.reason};s.emit("onConnectionChange",t)}c=!1}),this.phone.on("registered",function(){if(s.userName=e,s.isLoggedIn===!1&&(s.isLoggedIn=!0,s.emit("onLogin"),Plivo.log.debug("logged in"),s.options.enableTracking&&!s.callStats)){s.options.appId?null:s.options.appId="380077084",window.csioChromeLegacyGetStats=!0,s.callStats=new callstats;var t={disableBeforeUnloadHandler:!1,applicationVersion:"2.0.19"},n=function(e,t){Plivo.log.debug("Stats Initializing Status: err= "+e+" msg= "+t)},r=function(e){var t=e.streams;u.call(s,g,t),window._PlivoDevLogging&&console.log(t)};if("chrome"!=i.adapter.browserDetails.browser&&(r=null),s.callStats){var o=s.options.appSecret||S(s);s.callStats.initialize(s.options.appId,o,e,n,r,t)}Plivo.log.debug("enableTracking initialized")}}),this.phone.on("unregistered",function(){Plivo.log.debug("Plivo client logged out"),s.isLoggedIn=!1,s.ringToneView.paused?null:f.stopAudio(a.RINGTONE_ELEMENT_ID),s.ringBackToneView.paused?null:f.stopAudio(a.RINGBACK_ELEMENT_ID),s.userName=null,s.emit("onLogout")}),this.phone.on("registrationFailed",function(e){s.isLoggedIn=!1,Plivo.log.debug("Login failed : ",e.cause),s.userName=null,s.emit("onLoginFailed",e.cause)}),this.phone.on("newRTCSession",function(e){if(Plivo.log.debug("new rtc session"),s.callSession&&"closed"==s.callSession.connection.signalingState&&(Plivo.log.warn("Previous call doesn't end properly"),s.callSession=null),s.callSession){Plivo.log.debug("Already on call, sending busy signal.");var t={status_code:486,reason_phrase:"Busy Here"};return void e.session.terminate(t)}if(s.callSession=e.session,"remote"===e.originator){s.callDirection="incoming",Plivo.log.info("<----- INCOMING ----->"),s.connStage=[],s.connStage.push("I-invite@"+y()),s.callUUID=e.request.getHeader("X-Calluuid")||null;var n=e.request.getHeader("From");s.caller=n.match(/:(.*)@/i)[1];try{e.request.body=l(s.options.codecs,e.request.body)}catch(r){Plivo.log.debug("checkCodecPreference err - ",r)}s.callSession.on("progress",function(e){Plivo.log.debug("Incoming call progress"),s.connStage.push("progress-180@"+y());var t=s.callSession.remote_identity.uri.toString();s.ringToneFlag!==!1&&(Plivo.log.debug("ringtone enabled : ",s.ringToneFlag),f.playAudio(a.RINGTONE_ELEMENT_ID)),s.emit("onIncomingCall",t.substring(4,t.indexOf("@"))+"@"+a.DOMAIN,c),Plivo.log.debug("Incoming Call Extra Headers : ",c)}),s.callSession.on("sdp",function(e){Plivo.log.debug("Incoming call SDP processing done")}),s.callSession.on("accepted",function(e){Plivo.log.info("Incoming call accepted"),_(s);var t=s.callSession.connection||null;t.oniceconnectionstatechange=function(e){var n=t.iceConnectionState;if(Plivo.log.debug("oniceconnectionstatechange:: "+n),s.connStage.push("iceConnectionState-"+n+"@"+y()),T.call(s,n),s.callStats&&s.callUUID&&t&&("failed"==n||"disconnected"==n)){var r=new DOMError(n,n);s.callStats.reportError(t,s.callUUID,s.callStats.webRTCFunctions.iceConnectionFailure,r)}}}),s.callSession.on("confirmed",function(e){Plivo.log.debug("Incoming call confirmed - "+s.callUUID),s.connStage.push("confirmed@"+y()),s.options.disableRtpTimeOut&&(s.callSession.connection.disableRtpTimeOut=!0);var t=this.connection.getRemoteStreams()[0];t||Plivo.log.error("Incoming call remoteStream does not exists"),s.remoteView.srcObject=t;var n=function(e){Plivo.log.debug("Stats new fabric message: "+e)};s.callStats&&this.connection&&s.callStats.addNewFabric(this.connection,s.caller,s.callStats.fabricUsage.audio,s.callUUID,n),s.ringToneView.paused?null:f.stopAudio(a.RINGTONE_ELEMENT_ID),s.ringBackToneView.paused?null:f.stopAudio(a.RINGBACK_ELEMENT_ID),s.emit("onCallAnswered"),Plivo.log.debug("Plivo Event: Post-Answer detecting OWA"),setTimeout(v,3e3,this.connection,s)}),s.callSession.on("icetimeout",function(e){Plivo.log.debug("iceGathering timed out"),g(s,"network","warning","ice_timeout",e,!0,"Possible NAT/Firewall issue")}),s.callSession.on("failed",function(e){if(Plivo.log.error("Call failed: "+e.cause),s.connStage.push("failed@"+y()),s.ringToneView.paused?null:f.stopAudio(a.RINGTONE_ELEMENT_ID),e.cause==i.C.causes.CANCELED&&"incoming"==s.callDirection?s.emit("onIncomingCallCanceled"):s.emit("onCallFailed",e.cause),s.callStats&&s.callUUID&&this.connection&&!e.cause.match("edia")){var t,n;e.message&&(t=e.cause,n=t,e.message.status_code&&(n=String(e.message.status_code)));var r=new DOMError(t,n);Plivo.log.debug(r),s.callStats.reportError(this.connection,s.callUUID,s.callStats.webRTCFunctions.signalingError,r)}k(s)}),s.callSession.on("ended",function(e){Plivo.log.debug("Incoming call ended - "+s.callUUID),Plivo.log.info("Incoming call ended"),s.connStage.push("ended@"+y()),s.callStats&&s.callStats.sendFabricEvent(this.connection,s.callStats.fabricEvent.fabricTerminated,s.callUUID),s.emit("onCallTerminated",{originator:e.originator,reason:e.cause}),k(s)}),s.callSession.on("getusermediafailed",function(e){Plivo.log.error("getusermediafailed: "+e),s.userName&&s.callStats&&(e.message="getusermediafailed",s.callStats.reportError(null,s.userName,s.callStats.webRTCFunctions.getUserMedia,e))}),s.callSession.on("peerconnection:createofferfailed",function(e){Plivo.log.error("peerconnection:createofferfailed: ",e),s.userName&&s.callStats&&(e.message="peerconnection:createofferfailed",s.callStats.reportError(null,s.userName,s.callStats.webRTCFunctions.createOffer,e))}),s.callSession.on("peerconnection:createanswerfailed",function(e){Plivo.log.error("peerconnection:createanswerfailed: ",e),s.userName&&s.callStats&&(e.message="peerconnection:createanswerfailed",s.callStats.reportError(null,s.userName,s.callStats.webRTCFunctions.createAnswer,e))}),s.callSession.on("peerconnection:setlocaldescriptionfailed",function(e){Plivo.log.error("peerconnection:setlocaldescriptionfailed: ",e),s.userName&&s.callStats&&(e.message="peerconnection:setlocaldescriptionfailed",s.callStats.reportError(null,s.userName,s.callStats.webRTCFunctions.setLocalDescription,e))}),s.callSession.on("peerconnection:setremotedescriptionfailed",function(e){Plivo.log.error("peerconnection:setremotedescriptionfailed: ",e),e.message&&"pranswer not yet implemented"==!e.message&&s.userName&&s.callStats&&s.callStats.reportError(null,s.userName,s.callStats.webRTCFunctions.setRemoteDescription,e)});var o=e.request,u=o.headers,c=h.receiveExtraHeader(o,u);Plivo.log.debug("callSession - "+s.callUUID)}else s.callDirection="outgoing",Plivo.log.debug("new RTCSession outgoing"),s.emit("onCalling")}),this.phone.start(),!0},r.prototype.logout=function(){return Plivo.log.debug("logout() triggered!"),this.callSession&&(Plivo.log.debug("Terminating an active call"),this.callSession.terminate()),this.connStage.push("logout()@"+y()),this.phone&&this.phone.stop(),this.emit("onLogout"),!0},r.prototype.call=function(e,t){function n(e){return i.emit("onCallFailed",e),!0}function r(){return i.owaLastDetect.isOneWay=!1,m(i,t,e)}var i=this;return Plivo.log.info("<----- OUTGOING ----->"),i.connStage=[],Plivo.log.info("Outgoing call initialized to : "+e),this.isLoggedIn?(i.connStage.push("call()@"+y()),void(i.options.preDetectOwa&&"chrome"==i.browserDetails.browser&&(new Date-i.owaLastDetect.time>i.owaDetectTime||i.owaLastDetect.isOneWay)?C(function(e,t){return i.owaLastDetect.time=new Date,t?(Plivo.log.error("Error in detecting microphone status ",t),i.emit("onMediaPermission",{status:"failure",error:t.name}),n("media - "+t.name),!1):(Plivo.log.debug("getUserMedia precheck ",e),0==Number(e.bytesSent)&&0==Number(e.audioInputLevel)?(g(i,"audio","warning","no_microphone_access",0,!0,"chrome lost access to microphone - restart browser"),i.owaLastDetect.isOneWay=!0,n("no_microphone_access"),!1):(0==Number(e.audioInputLevel)&&g(i,"audio","warning","no_microphone_access",0,!0,"microphone is muted"),void r()))}):r())):(Plivo.log.warn("Must be logged in before make a call"),!1)},r.prototype.answer=function(){function e(e){return n.reject(),!0}function t(){if(n.owaLastDetect.isOneWay=!1,r.pcConfig={iceServers:[{urls:a.STUN_SERVERS}]},n.permOnClick){var e=n.options.audioConstraints||!0;r.mediaConstraints={audio:e,video:!1}}else!!window.localStream||Plivo.log.warn("no localStream attached for this call");r.mediaStream=window.localStream||null,r.rtcConstraints=n.options.dscp?{optional:[{googDscp:!0}]}:null,r.sessionTimersExpires=a.SESSION_TIMERS_EXPIRES;try{n.callSession&&n.callSession.answer(r)}catch(t){Plivo.log.error("error in answering : ",t),n.emit("onIncomingCallCanceled",t)}return n.ringToneView.paused?null:f.stopAudio(a.RINGTONE_ELEMENT_ID),!0}Plivo.log.debug("answer - "+this.callUUID);var n=this,r={};return this.callSession?(n.connStage.push("answer()@"+y()),n.options.preDetectOwa&&"chrome"==n.browserDetails.browser&&(new Date-n.owaLastDetect.time>n.owaDetectTime||n.owaLastDetect.isOneWay)?C(function(r,i){return n.owaLastDetect.time=new Date,i?(Plivo.log.error("Error in detecting microphone status ",i),n.emit("onMediaPermission",{status:"failure",error:i.name}),e("media - "+i.name),!1):(Plivo.log.debug("getUserMedia precheck ",n.str(r)),0==Number(r.bytesSent)&&0==Number(r.audioInputLevel)?(g(n,"audio","warning","no_microphone_access",0,!0,"chrome lost access to microphone - restart browser"),n.owaLastDetect.isOneWay=!0,e("no_microphone_access"),!1):(0==Number(r.audioInputLevel)&&g(n,"audio","warning","no_microphone_access",0,!0,"microphone is muted"),void t()))}):t(),!0):(Plivo.log.error("Incoming call answer() failed : no incoming call"),!1)},r.prototype.hangup=function(){if(Plivo.log.debug("hangup - "+this.callUUID),!this.callSession)return Plivo.log.warn("No call session exists to hangup"),!1;"outgoing"==this.callSession.direction||E(this.callSession)||Plivo.log.warn("use of hangup() on unanswered call is deprecated. use reject() instead");try{Plivo.log.info("hangup initialized"),Plivo.AppError({name:"hangup",message:"hangup initialized",method:"hangup()"}),this.callSession.terminate(),this.ringBackToneView.paused?null:f.stopAudio(a.RINGBACK_ELEMENT_ID)}catch(e){Plivo.log.error("Could not hangup reason : ",e),Plivo.AppError({name:e.name,message:e.message,method:"hangup()"})}return!0},r.prototype.reject=function(){if(Plivo.log.debug("reject - "+this.callUUID),!this.callSession)return Plivo.log.warn("No call session exists to reject()"),!1;if(E(this.callSession))return Plivo.log.warn("call already answerd, please use hangup() method"),!1;if(this.callSession){var e={status_code:486,reason_phrase:"Busy Here"};Plivo.log.info("rejecting call"),Plivo.AppError({name:"reject",message:"reject initialized",method:"reject()"});try{this.callSession.terminate(e)}catch(t){Plivo.log.error("error in rejecting call : ",t),Plivo.AppError({name:t.name,message:t.message,method:"reject()"})}return this.ringToneView.paused?null:f.stopAudio(a.RINGTONE_ELEMENT_ID),!0}},r.prototype.sendDtmf=function(e){if(Plivo.log.debug("sendDtmf - "+this.callUUID),"undefined"==typeof e||null==e)return Plivo.log.warn("DTMF digit can not be null");if("undefined"==typeof a.DTMF_TONE_FLAG[e])return Plivo.log.warn(e+" is not a valid DTMF digit");if(this.callSession)try{return Plivo.log.debug("sending dtmf digit "+e),this.callSession.sendDTMF(e),"*"===e?f.playAudio("dtmfstar"):"#"===e?f.playAudio("dtmfpound"):f.playAudio("dtmf"+e)}catch(t){Plivo.log.error("Call has not been confirmed cannot send DTMF"),Plivo.AppError({name:t.name,message:t.message,method:"sendDtmf()"})}else Plivo.log.warn("No call session exists to sendDtmf")},r.prototype.mute=function(){if(!this.callSession)return Plivo.log.warn("No call session exists to mute"),!1;Plivo.log.debug("mute called");try{this.callSession.mute(),this.callStats&&this.callStats.sendFabricEvent(this.callSession.connection,this.callStats.fabricEvent.audioMute,this.callUUID)}catch(e){Plivo.log.error("error in mute :",e),Plivo.AppError({name:e.name,message:e.message,method:"mute()"})}return!0},r.prototype.unmute=function(){if(!this.callSession)return Plivo.log.warn("No call session exists to unmute"),!1;Plivo.log.debug("unmute called");try{this.callSession.unmute(),this.callStats&&this.callStats.sendFabricEvent(this.callSession.connection,this.callStats.fabricEvent.audioUnmute,this.callUUID)}catch(e){Plivo.log.error("error in unmute : ",e),Plivo.AppError({name:e.name,message:e.message,method:"unmute()"})}return!0},r.prototype.setRingTone=function(e){return e===!1||null===e?this.ringToneFlag=!1:"string"==typeof e?(this.ringToneFlag="user",Plivo.log.debug("setRingTone() url : "+e),this.ringToneView.src=e):this.ringToneFlag=!0,!0},r.prototype.setRingToneBack=function(e){return e===!1||null===e?this.ringToneBackFlag=!1:"string"==typeof e?(this.ringToneBackFlag="user",Plivo.log.debug("setRingToneBack() url : "+e),this.ringBackToneView.src=e):this.ringToneBackFlag=!0,!0},r.prototype.setConnectTone=function(e){return e?this.connectToneFlag=!0:this.connectToneFlag=!1,!0},r.prototype.setDtmfTone=function(e,t){if(t===!1||null===t)a.DTMF_TONE_FLAG[e]=!1;else if("string"==typeof t){Plivo.log.debug("set dtmf tone"),a.DTMF_TONE_FLAG[e]="user";var n="dtmf"+e,r=document.getElementById(n);r.src=t}else a.DTMF_TONE_FLAG[e]=!0;return!0},r.prototype.getCallUUID=function(){return this.callUUID},r.prototype.getLastCallUUID=function(){return this.lastCallUUID},r.prototype.setDebug=function(e){e&&["INFO","DEBUG","WARN","ERROR","ALL","OFF"].indexOf(e)!=-1&&Plivo.log.setLevel(e)},r.prototype.getPeerConnection=function(){return this.callSession&&E(this.callSession)?{status:"success",pc:this.callSession.connection}:{status:"called in wrong state",pc:null}},r.prototype.version="2.0.19",r.prototype.webRTC=function(){return!!window.RTCPeerConnection},r.prototype.supportedBrowsers=function(){return"Chrome, Firefox"},r.prototype.sendQualityFeedback=function(e,t,n){var t=Number(t);if(!this.callStats)return void Plivo.log.warn("Stats integration not configured, ignoring feedback");if(!this.userName)return void Plivo.log.error("sendQualityFeedback() userName is null, isLoggedIn : "+this.isLoggedIn);if(!e)return void Plivo.log.error("sendQualityFeedback() callUUID is mandatory");if(n&&n.toString().length>200)return void Plivo.log.error("sendQualityFeedback() comment max length is 200 character");if(n||Plivo.log.error("sendQualityFeedback() comment is mandatory"),t>0&&t<=5){var r={userID:this.userName,overall:t,comment:n},i=function(e){Plivo.log.debug("Stats sendFeedback status: "+e)};Plivo.log.debug("Feedback sent for callUUID : "+e),this.callStats.sendUserFeedback(e,r,i)}else Plivo.log.error("sendQualityFeedback() score: "+t+" , score should be from 1-5 range")};var v=function(e,t){if(e&&"closed"!=e.signalingState&&"chrome"==i.adapter.browserDetails.browser){var n=e;n.getStats(function(e){e.result().forEach(function(e){var n=e;n.stat("bytesSent")&&Plivo.log.debug("Bytes sent by WebSDK client: "+n.stat("bytesSent")+" audioInputLevel: "+n.stat("audioInputLevel")),t.storage.audioCodec=n.stat("googCodecName"),"ssrc"===n.type&&"audio"===n.stat("mediaType")&&0===parseInt(n.stat("bytesSent"),10)&&0===n.stat("audioInputLevel")&&(Plivo.log.debug("One way audio detected"),g(t,"audio","warning","no_microphone_access",0,!0,"no access to your microphone"))})},n.getLocalStreams()[0].getAudioTracks()[0],function(e){console.log(e)})}},g=function(e,t,n,r,i,o,s){var a={group:t,level:n,type:r,value:i,active:o,desc:s||""};e.emit("mediaMetrics",a)},m=function(e,t,n){var r,i={};if(n&&(n=String(n)),"undefined"==typeof n||null===n||n.length<=0)return Plivo.log.warn("Destination address cant be null and its length must be > 0"),!1;if(e.callSession)return Plivo.log.warn("Can't make another call while in call"),!1;t=t||{};var o=[];for(var s in t){var u=t[s];h.checkExtraHeaderKey(s)&&h.checkExtraHeaderVal(u)?(o.push(s+": "+u),Plivo.log.debug("valid hdr = "+s+" -> "+u)):Plivo.log.debug("invalid hdr = "+s+" -> "+u)}e.options.clientRegion&&o.push("X-ClientRegion: "+e.options.clientRegion),r="sip:"!=n.substring(0,4)?"sip:"+n:n,i.sessionTimersExpires=a.SESSION_TIMERS_EXPIRES,i.pcConfig={iceServers:[{urls:a.STUN_SERVERS}]};var c=e.options.audioConstraints||!0;i.mediaConstraints={audio:c,video:!1},i.rtcConstraints=e.options.dscp?{optional:[{googDscp:!0}]}:null,i.extraHeaders=o,i.mediaStream=window.localStream||null,i.eventHandlers={sending:function(t){Plivo.log.debug("Outgoing call sending"),e.connStage.push("O-invite@"+y());var n=this.connection||null;e.connectToneFlag!==!1&&f.playAudio(a.CONNECT_TONE_ELEMENT_ID),n.ontrack=function(t){Plivo.log.debug("Outgoing call received addStream"),e.connStage.push("addStream-success@"+y()),t.streams[0]?(setTimeout(function(){e.remoteView.srcObject=t.streams[0]},100),e.ringToneBackFlag&&!E(e.callSession)?setTimeout(function(){E(e.callSession)||e.remoteView.pause()},100):e.ringToneBackFlag||E(e.callSession)||Plivo.log.debug("playAudio - MediaServer")):(Plivo.log.error("Outgoing call addStream failure"),e.connStage.push("addStream-failure@"+y()))},n.oniceconnectionstatechange=function(){var t=n.iceConnectionState;if(Plivo.log.debug("oniceconnectionstatechange:: "+t),e.connStage.push("iceConnectionState-"+t+"@"+y()),T.call(e,t),e.callStats&&e.callUUID&&n&&("failed"==t||"disconnected"==t)){Plivo.log.debug("iceState :: "+t);var r=new DOMError(t,t);e.callStats.reportError(n,e.callUUID,e.callStats.webRTCFunctions.iceConnectionFailure,r)}}},sdp:function(t){try{t.sdp=l(e.options.codecs,t.sdp)}catch(n){Plivo.log.debug("checkCodecPreference err - ",n)}},progress:function(t){if(e.callSession=this,e.callUUID=t.response.getHeader("X-Calluuid"),e.emit("onCallRemoteRinging"),e.callStats&&this.connection){var n=function(e){Plivo.log.debug("Stats new fabric message: "+e)},r=this.request.headers.To.toString().match(/:(.*)@/i)[1];e.callStats.addNewFabric(this.connection,r,e.callStats.fabricUsage.audio,e.callUUID,n)}if(e.connStage.push("progress-"+t.response.status_code+"@"+y()),Plivo.log.debug("Outgoing call progress",t.response.status_code),Plivo.log.debug("ringback tone enabled : "+e.ringToneBackFlag),e.connectToneView.paused?null:f.stopAudio(a.CONNECT_TONE_ELEMENT_ID),e.ringToneBackFlag&&f.playAudio(a.RINGBACK_ELEMENT_ID),183==t.response.status_code&&t.response.body&&(Plivo.log.debug("callSession - "+e.callUUID),!e.ringToneBackFlag))return void(e.ringBackToneView.paused?null:f.stopAudio(a.RINGBACK_ELEMENT_ID))},accepted:function(t){var n=t.response.getHeader("To").match(/:(.*)@/i)[1];e.callUUID=t.response.getHeader("X-Calluuid"),Plivo.log.info("Outgoing call accepted");var r=function(e){Plivo.log.debug("Stats new fabric message: "+e)};_(e),e.callStats&&this.connection&&e.callStats.addNewFabric(this.connection,n,e.callStats.fabricUsage.audio,e.callUUID,r)},confirmed:function(t){Plivo.log.debug("Outgoing call confirmed - "+e.callUUID),e.connStage.push("confirmed@"+y()),e.remoteView.paused&&e.remoteView.play(),e.options.disableRtpTimeOut&&(e.callSession.connection.disableRtpTimeOut=!0),e.ringToneView.paused?null:f.stopAudio(a.RINGTONE_ELEMENT_ID),e.ringBackToneView.paused?null:f.stopAudio(a.RINGBACK_ELEMENT_ID),e.connectToneView.paused?null:f.stopAudio(a.CONNECT_TONE_ELEMENT_ID),e.emit("onCallAnswered"),setTimeout(v,3e3,this.connection,e)},icetimeout:function(t){Plivo.log.debug("iceGathering timed out"),g(e,"network","warning","ice_timeout",t,!0,"Possible NAT/Firewall issue")},failed:function(t){if(Plivo.log.error("Outgoing call failed: "+t.cause),e.connStage.push("failed@"+y()),e.ringBackToneView.paused?null:f.stopAudio(a.RINGBACK_ELEMENT_ID),e.connectToneView.paused?null:f.stopAudio(a.CONNECT_TONE_ELEMENT_ID),t.message&&(e.callUUID=t.message.getHeader("X-CallUUID")||null),e.callStats&&e.callUUID&&!t.cause.match("edia")){var n=t.cause,r=n;t.message&&t.message.status_code&&(r=String(t.message.status_code));var i=new DOMError(n,r);Plivo.log.debug(i),e.callStats.reportError(null,e.callUUID,e.callStats.webRTCFunctions.signalingError,i)}e.emit("onCallFailed",t.cause),k(e)},ended:function(t){Plivo.log.debug("Outgoing call ended - "+e.callUUID),Plivo.log.info("Outgoing call ended"),e.connStage.push("ended@"+y()),e.callStats&&e.callStats.sendFabricEvent(this.connection,e.callStats.fabricEvent.fabricTerminated,e.callUUID),e.emit("onCallTerminated",{originator:t.originator,reason:t.cause}),Plivo.AppError({name:"onCallTerminated",originator:t.originator,reason:t.cause}),k(e)},getusermediafailed:function(t){Plivo.log.error("getusermediafailed: "+t),e.userName&&e.callStats&&(t.message="getusermediafailed",e.callStats.reportError(null,e.userName,e.callStats.webRTCFunctions.getUserMedia,t))},"peerconnection:createofferfailed":function(t){Plivo.log.error("peerconnection:createofferfailed: ",t),e.userName&&e.callStats&&(t.message="peerconnection:createofferfailed",e.callStats.reportError(null,e.userName,e.callStats.webRTCFunctions.createOffer,t))},"peerconnection:createanswerfailed":function(t){Plivo.log.error("peerconnection:createanswerfailed: ",t),e.userName&&e.callStats&&(t.message="peerconnection:createanswerfailed",e.callStats.reportError(null,e.userName,e.callStats.webRTCFunctions.createAnswer,t))},"peerconnection:setlocaldescriptionfailed":function(t){Plivo.log.error("peerconnection:setlocaldescriptionfailed: ",t),e.userName&&e.callStats&&(t.message="peerconnection:setlocaldescriptionfailed",e.callStats.reportError(null,e.userName,e.callStats.webRTCFunctions.setLocalDescription,t))},"peerconnection:setremotedescriptionfailed":function(t){t.message&&!/pranswer/.test(t.message)&&(Plivo.log.error("peerconnection:setremotedescriptionfailed: ",t),e.userName&&e.callStats&&(t.message="peerconnection:setremotedescriptionfailed",e.callStats.reportError(null,e.userName,e.callStats.webRTCFunctions.setRemoteDescription,t)))}};try{e.phone.call(r,i),Plivo.log.debug("Outgoing call options : ",JSON.stringify(i.mediaConstraints))}catch(d){return Plivo.log.error("Failed to execute plivo.onCalling event handler",d),Plivo.AppError({name:d.name,message:d.message,method:"call()"}),!1}return!0},y=function(){var e=new Date,t=e.toISOString().substring(0,10)+" "+e.toString().split(" ")[4]+"."+e.getMilliseconds();return t},b=function(e){var t=e.storage;return t.local_audio=[],t.remote_audio=[],t.mosLocalMeasures=[],t.mosRemoteMeasures=[],t.jitterLocalMeasures=[],t.jitterRemoteMeasures=[],t.packetLossRemoteMeasures=[],t.packetLossLocalMeasures=[],t.rtt=[],t.audioCodec=null,t.warning={audioLocalMeasures:!1,audioRemoteMeasures:!1,mosLocalMeasures:!1,mosRemoteMeasures:!1,jitterLocalMeasures:!1,jitterRemoteMeasures:!1,packetLossRemoteMeasures:!1,packetLossLocalMeasures:!1,rtt:!1,ice_connection:!1},t.startAnalysis=!1,setTimeout(function(){t.startAnalysis=!0,Plivo.log.debug("Stats startAnalysis started")},5e3),!0},_=function(e){return e.storage={},b(e)},S=function(e){return function(t,n){Plivo.log.info("Stats token req...");var r={eventHandlers:{succeeded:function(e){Plivo.log.info("Stats token success!");var t=JSON.parse(e.response.getHeader("x-token"));return t&&"0"!==t?n(null,t.token):(Plivo.log.error("Stats token failed with 0"),n("token failed 0"))},failed:function(e){return e.response&&e.response.status_code?(Plivo.log.error("Stats token failed!",e.response.status_code),n(e.response.status_code)):(Plivo.log.error("Stats token failed!"),n("failed"))}},extraHeaders:["X-appID: "+e.options.appId,"X-userID: "+e.userName]};e.phone.sendMessage("admin","-- Plivo web client --",r)}},T=function(e){["disconnected","failed"].indexOf(e)!=-1&&(g(this,"network","warning","ice_connection",e,!0,"network drop"),this.storage&&(this.storage.warning.ice_connection=!0)),"connected"==e&&this.storage&&this.storage.warning.ice_connection===!0&&(g(this,"network","warning","ice_connection",e,!1),this.storage.warning.ice_connection=!1)},C=function(e){function t(e,t){t.candidate&&e.addIceCandidate(t.candidate).then()["catch"](n)}function n(t){e&&e(null,t)}function r(e){e.addStream(a),e.createOffer().then(function(t){e.setLocalDescription(t).then(function(){i(u,t)})["catch"](n)})["catch"](n)}function i(e,t){e.setRemoteDescription(t).then(function(){"offer"==t.type&&e.createAnswer().then(function(t){e.setLocalDescription(t).then(function(){})["catch"](n),i(l,t)})["catch"](n)})["catch"](n)}function o(){a&&a.getTracks().forEach(function(e){e.stop(),a.removeTrack(e),a=null}),"stable"==l.signalingState&&l.close(),"stable"==u.signalingState&&u.close()}function s(){function t(){l.getLocalStreams()[0]&&l.getStats(function(n){n.result().forEach(function(n){var i=n;if("ssrc"===i.type&&"audio"===i.stat("mediaType")){var s={bytesSent:i.stat("bytesSent"),audioInputLevel:i.stat("audioInputLevel")};Number(s.audioInputLevel)<=0&&2!=r?(r++,setTimeout(t,1e3),Plivo.log.debug("getUM precheck re-attempt: "+r)):(e&&e(s,null),setTimeout(o,3e3))}})},l.getLocalStreams()[0].getAudioTracks()[0],n)}Plivo.log.debug("getUM precheck icestate : "+l.iceConnectionState);var r=0;t()}var a,l,u,c=null;l=new RTCPeerConnection(c),u=new RTCPeerConnection(c),navigator.mediaDevices.getUserMedia({audio:!0,video:!1}).then(function(e){a=e,r(l)})["catch"](n),l.onicecandidate=function(e){t(u,e)},u.onicecandidate=function(e){t(l,e)},setTimeout(s,500)},w=function(e){for(var t,n=[],r=0;e.length>r;r++){var i=e[r].split("@");if(0==r)t=i[1],n.push(i[0]+" = "+i[1]+"#");else{var o=new Date(i[1])-new Date(t);o>1e3?(o/=1e3,o=String(o)+"s#"):o=String(o)+"ms#",n.push(i[0]+" = "+i[1]+" +"+o)}}return n=JSON.stringify(n),n=n.replace(/[[",\]]/g,""),n=n.replace(/#/g,"\n")},E=function(e){return e?e.is_confirmed:(Plivo.log.debug("session not available"),!1)},k=function(e){if(e.remoteView.pause(),Plivo.AppError(w(e.connStage),"log"),e.callSession=null,delete e.storage,e.lastCallUUID=e.callUUID,e.callUUID=null,e.callDirection=null,window.localStream&&("chrome"==i.adapter.browserDetails.browser||e.permOnClick))try{window.localStream.getTracks().forEach(function(e){ +e.stop(),window.localStream.removeTrack(e)}),window.localStream=null}catch(t){Plivo.log.debug("error on stop track in localStream : "+t.message)}};t.exports=r},{"../sipLib/JsSIP":41,"./media/audioDevice":3,"./media/document":4,"./util/callAnalytics":5,"./util/codecPreference":6,"./util/constants":7,"./util/headers":8,"./util/logger":9,"./util/validateOptions":10,events:11,util:23}],3:[function(e,t,n){var r=e("../util/constants"),i=function(e){return new Promise(function(t,n){navigator.mediaDevices.enumerateDevices().then(function(n){var r=[];n.filter(function(t){"input"==e?"audioinput"==t.kind&&r.push(t):"output"==e?"audiooutput"==t.kind&&r.push(t):/video/i.test(t.kind)||r.push(t)}),t(r)})["catch"](function(e){n(e)})})},o=function(e){return new Promise(function(t,n){navigator.mediaDevices.getUserMedia?navigator.mediaDevices.getUserMedia({audio:!0,video:!1}).then(function(n){"returnStream"==e?t(n):(n.getTracks().forEach(function(e){e.stop()}),t("success"))})["catch"](function(e){Plivo.log.error("failed to get user media :: "+e.name),n(e.name)}):n("no getUserMedia support")})},s=function(){return{set:function(e){if("string"==typeof e&&"optional"in Plivo.audioConstraints)return Plivo.audioConstraints.optional.push({sourceId:e}),!0},get:function(){if(Plivo.audioConstraints.optional){var e=Plivo.audioConstraints.optional.filter(function(e){return e.sourceId});return e.length>0?e[0].sourceId:""}return""},reset:function(){return Plivo.audioConstraints.optional&&(Plivo.audioConstraints.optional=Plivo.audioConstraints.optional.filter(function(e){return!e.sourceId})),!0}}}(),a=function(){return{set:function(e){var t=document.querySelectorAll('[data-devicetype="speakerDevice"]');return t.forEach(function(t){t.setSinkId&&t.setSinkId(e)}),!0},get:function(){var e=document.querySelector('[data-devicetype="speakerDevice"]');if(e.sinkId)return e.sinkId},reset:function(){var e=document.querySelectorAll('[data-devicetype="speakerDevice"]');return e.forEach(function(e){e.setSinkId&&e.setSinkId("")}),!0},media:function(e){var t={dtmf:"dtmfstar",ringback:r.RINGBACK_ELEMENT_ID};return e&&e in t?document.getElementById(t[e]):document.getElementById(r.RINGBACK_ELEMENT_ID)}}}(),l=function(){return{set:function(e){var t=document.getElementById(r.RINGTONE_ELEMENT_ID);return t.setSinkId&&t.setSinkId(e),!0},get:function(){var e=document.getElementById(r.RINGTONE_ELEMENT_ID);if(e.sinkId)return e.sinkId},reset:function(){var e=document.getElementById(r.RINGTONE_ELEMENT_ID);return e.setSinkId&&e.setSinkId(""),!0},media:function(){return document.getElementById(r.RINGTONE_ELEMENT_ID)}}}(),u=function(e){var t=this;return new Promise(function(n,r){i().then(function(r){var i=[];r.forEach(function(e){if(e.label){var t=JSON.stringify(e);i.push(t)}else i=null}),e?(t.audioDevDic=i,n(!0)):n(i)})["catch"](function(e){Plivo.log.error("Error availableDevices() ",e),r(e)})})},c=function(){var e,t,n=this;u().then(function(r){n.audioDevDic&&r&&(r.forEach(function(t){n.audioDevDic.indexOf(t)==-1&&(e=JSON.parse(t),/default/i.test(e.deviceId)||n.emit("audioDeviceChange",{change:"added",device:e}))}),n.audioDevDic.forEach(function(e){r.indexOf(e)==-1&&(t=JSON.parse(e),/default/i.test(t.deviceId)||n.emit("audioDeviceChange",{change:"removed",device:t}))})),n.audioDevDic||n.emit("audioDeviceChange",{change:"",device:""}),r&&(n.audioDevDic=r)})["catch"](function(e){Plivo.log.error("Error checkAudioDevChange() ",e)})};t.exports.inputDevices=s,t.exports.outputDevices=a,t.exports.ringtoneDevices=l,t.exports.revealAudioDevices=o,t.exports.availableDevices=i,t.exports.audioDevDictionary=u,t.exports.checkAudioDevChange=c},{"../util/constants":7}],4:[function(e,t,n){"use strict";var r=e("../util/constants"),i=function(e,t){var n=document.createElement("audio");n.id=r.REMOTE_VIEW_ID,n.hidden=!0,n.autoplay=!0,n.width=0,n.height=0,n.setAttribute("data-devicetype","speakerDevice"),document.body.appendChild(n);var i=document.createElement("audio");i.id=r.CONNECT_TONE_ELEMENT_ID,i.loop="loop",i.src=r.CONNECT_TONE_URL,i.setAttribute("data-devicetype","speakerDevice"),document.body.appendChild(i);var s=document.createElement("audio");s.id=r.RINGBACK_ELEMENT_ID,s.loop="loop",s.src=r.RINGTONE_URL,s.setAttribute("data-devicetype","speakerDevice"),document.body.appendChild(s);var a=document.createElement("audio");a.id=r.RINGTONE_ELEMENT_ID,a.loop="loop",a.src=r.RINGTONE_URL,a.setAttribute("data-devicetype","ringtoneDevice"),document.body.appendChild(a);for(var l="mp3",u="https://cdn.plivo.com/sdk/browser/audio/dtmf-",c=function(e,t,n){var r="dtmf"+t,i=e+t+"."+n,o=document.createElement("audio");o.id=r,o.src=i,o.setAttribute("data-devicetype","speakerDevice"),document.body.appendChild(o)},d=0;d<=9;d++)c(u,d,l);c(u,"star",l),c(u,"pound",l),e.permOnClick?(window.localStream=null,t({status:"success",stream:!1})):o(e.audioConstraints,function(e){t(e)})},o=function(e,t){navigator.mediaDevices.getUserMedia?navigator.mediaDevices.getUserMedia({audio:e,video:!1}).then(function(e){window.localStream=e,Plivo.log.debug("getUserMedia success"),t({status:"success",stream:!0})})["catch"](function(e){Plivo.log.error("failed to get user media :: "+e.name),t({status:"failure",error:e.name})}):(Plivo.log.error("getUserMedia not available"),t({status:"failure",error:"getUserMedia not supported"}))},s=function(e){try{document.getElementById(e).play(),Plivo.log.debug("playAudio - "+e)}catch(t){Plivo.log.debug("failed to play audio for elementId "+e+" Cause: "+t)}},a=function(e){try{document.getElementById(e).pause(),Plivo.log.debug("stopAudio - "+e)}catch(t){Plivo.log.debug("failed to stop audio for elementId "+e+" Cause: "+t)}},l=function(){var e=document.createElement("div");e.id="plivo_mask",document.body.insertBefore(e,document.body.firstChild),e.style.position="fixed",e.style.top="0",e.style.left="0",e.style.width="100%",e.style.height="100%",e.style.background="#000",e.style.opacity="0.8",e.style.filter="alpha(opacity=80)",e.style.zindex="50"};t.exports.setup=i,t.exports.getLocalMedia=o,t.exports.playAudio=s,t.exports.stopAudio=a,t.exports.maskPage=l},{"../util/constants":7}],5:[function(e,t,n){var r=function(e,t){function n(t,n){var r=a.storage[t];if(2==r.length){r.push(Number(n));var i={},o=null;r.forEach(function(e){i[e]=i[e]+1||1});for(var s in i)i[s]>=2&&(o=Number(s));"number"==typeof o?(a.storage.warning[t]=!0,o>1?Plivo.log.debug("Same audioLevel detected for "+t+" : ",a.str(r)):Plivo.log.debug("Audio mute detected for "+t+" : ",a.str(r)),e(a,"audio","warning","no_audio_received",o,!0,t)):a.storage.warning[t]?(a.storage.warning[t]=!1,e(a,"audio","warning","no_audio_received",0,!1,t)):null}else r.push(Number(n));3==r.length&&r.splice(0,2)}function r(t,n){var n=Number(n),r=a.storage[t];if(2==r.length){r.push(n);var i=r.filter(function(e,t){return e>400});if(i.length>=2){var o=i.reduce(function(e,t){return e+t}),s=(o/i.length).toFixed(2);a.storage.warning[t]=!0,Plivo.log.debug(t+" : getting high rtt : ",a.str(i)),e(a,"network","warning","high_rtt",s,!0,"high latency")}else a.storage.warning[t]?(a.storage.warning[t]=!1,e(a,"network","warning","high_rtt",0,!1)):null}else r.push(n);3==r.length&&r.splice(0,2)}function i(t,n){var n=Number(n),r=a.storage[t];if(2==r.length){r.push(n);var i=r.filter(function(e,t){return e>30});if(i.length>=2){var o=i.reduce(function(e,t){return e+t}),s=o/i.length;a.storage.warning[t]=!0,Plivo.log.debug(t+" : getting high jitter rate : ",a.str(i)),e(a,"network","warning","high_jitter",s,!0,t)}else a.storage.warning[t]?(a.storage.warning[t]=!1,e(a,"network","warning","high_jitter",0,!1,t)):null}else r.push(n);3==r.length&&r.splice(0,2)}function o(t,n){var r=a.storage[t];if(2==r.length){r.push(n);var i=r.filter(function(e,t){return"opus"==a.storage.audioCodec?"bad"==e:"excellent"!=e});i.length>=2?(a.storage.warning[t]=!0,Plivo.log.debug(t+" : getting low mos : ",a.str(r)),e(a,"network","warning","low_mos",i[0],!0,t)):a.storage.warning[t]?(a.storage.warning[t]=!1,e(a,"network","warning","low_mos",0,!1,t)):null}else r.push(n);3==r.length&&r.splice(0,2)}function s(t,n){var n=Number(n),r=a.storage[t];if(2==r.length){r.push(n);var i=r.filter(function(e,t){return"opus"==a.storage.audioCodec?e>=.1:e>=.02});if(i.length>=2){var o=i.reduce(function(e,t){return e+t}),s=o/i.length;s=s.toFixed(3),a.storage.warning[t]=!0,Plivo.log.debug(t+" : ploss score value is high :",a.str(i)),e(a,"network","warning","high_packetloss",s,!0,t)}else a.storage.warning[t]?(a.storage.warning[t]=!1,e(a,"network","warning","high_packetloss",0,!1,t)):null}else r.push(n);3==r.length&&r.splice(0,2)}var a=this;if(a.storage&&a.storage.startAnalysis)for(var l in t)if("audioInputLevel"in t[l]){var u=t[l],c=u.fractionLoss?u.fractionLoss.toFixed(2):0,d=(u.bitrate?u.bitrate.toFixed(2):0,u.quality||null),f=u.rtt||0,h=u.jitter||0,p=u.audioInputLevel||0;n("local_audio",p),r("rtt",f),i("jitterLocalMeasures",h),s("packetLossLocalMeasures",c)}else if("audioOutputLevel"in t[l]){var u=t[l],c=u.fractionLoss?u.fractionLoss.toFixed(2):0,d=(u.bitrate?u.bitrate.toFixed(2):0,u.quality||null),h=u.jitter||0,v=u.audioOutputLevel||0;n("remote_audio",v),i("jitterRemoteMeasures",h),o("mosRemoteMeasures",d),s("packetLossRemoteMeasures",c)}};t.exports=r},{}],6:[function(e,t,n){var r=function(e,t){function n(e,t){var n=new RegExp("a=rtpmap:.* "+e+"(.*)","ig");return!!t.match(n)&&t.match(n)[0].split(" ")[0].match(/\d+/)}function r(e,t){var r;return e.forEach(function(e){var i=n(e,t);r=new RegExp("\na=rtpmap:.*"+e+"/.*","ig"),t=t.replace(r,""),r=new RegExp("\na=fmtp:"+i+" (.*)","ig"),t=t.replace(r,""),r=new RegExp("\na=rtcp-fb:"+i+" (.*)","ig"),t=t.replace(r,"")}),t}if(e.length>0){var i=["OPUS","G722","PCMA","PCMU","ISAC","CN"],o=e,s="";o.forEach(function(e){var r=i.indexOf(e);r>-1&&i.splice(r,1);var o=n(e,t);o&&(s+=o+" ")}),s=s.slice(0,-1),t=t.replace(t.match(/m=audio .*[a-z] (.*)/i)[1],s),t=r(i,t)}return t};t.exports=r},{}],7:[function(e,t,n){"use strict";t.exports.DEFAULT_LOG_LEVEL="INFO",t.exports.DOMAIN="phone.plivo.com",t.exports.WS_SERVERS="wss://phone.plivo.com:5063",t.exports.REGISTER_EXPIRES_SECONDS=120,t.exports.SESSION_TIMERS_EXPIRES=300,t.exports.WS_RECOVERY_MAX_INTERVAL=20,t.exports.WS_RECOVERY_MIN_INTERVAL=2,t.exports.DEFAULT_CODECS=["OPUS","PCMU"],t.exports.STUN_SERVERS=["stun:stun.l.google.com:19302","stun:stun1.l.google.com:19302"],t.exports.LIB_NAME="plivojs",t.exports.DEBUG_MODES=["INFO","DEBUG","WARN","ERROR","ALL","ALL-PLAIN","OFF"],t.exports.REGION=["usa_west","usa_east","australia","europe","asia","south_america"],t.exports.RINGTONE_URL="https://cdn.plivo.com/sdk/browser/audio/us-ring.mp3",t.exports.CONNECT_TONE_URL="https://cdn.plivo.com/sdk/browser/audio/connect-tone.mp3",t.exports.SELF_VIEW_ID="plivo_webrtc_selfview",t.exports.REMOTE_VIEW_ID="plivo_webrtc_remoteview",t.exports.RINGBACK_ELEMENT_ID="plivo_ringbacktone",t.exports.RINGTONE_ELEMENT_ID="plivo_ringtone",t.exports.CONNECT_TONE_ELEMENT_ID="plivo_connect_tone",t.exports.DTMF_TONE_FLAG={0:!0,1:!0,2:!0,3:!0,4:!0,5:!0,6:!0,7:!0,8:!0,9:!0,"#":!0,"*":!0},t.exports.DEFAULT_COMMENTS=["bad-audio","call-dropped","wrong-callerid","post-dial-delay","dtmf-not-captured","audio-latency","unsolicited-call","one-way-audio","no-audio","never-connected"];var r={};"undefined"!=typeof navigator&&navigator.mozGetUserMedia?r={offerToReceiveAudio:!0}:r.mandatory={OfferToReceiveAudio:!0},t.exports.DEFAULT_OFFER_OPTIONS=r},{}],8:[function(e,t,n){"use strict";var r=function(e){if("X-Ph-"!=e.substr(0,5)&&"X-PH-"!=e.substr(0,5))return!1;var t=/^([a-z0-9A-Z]){1,19}$/;return t.test(e.substr(5))!==!1},i=function(e){var t=/^([a-z0-9A-Z_\-\+\(\)%]){1,120}$/;return t.test(e)!==!1},o=function(e,t){var n={};for(var o in t){var s=e.getHeader(o);r(o)&&i(s)&&(n[o]=s)}return n};t.exports.checkExtraHeaderKey=r,t.exports.checkExtraHeaderVal=i,t.exports.receiveExtraHeader=o},{}],9:[function(e,t,n){var r=function(e){e?e:e={};var t=["INFO","DEBUG","WARN","ERROR","ALL","OFF"],n=e.logMethod||"INFO",r=e.enableDate||!1,i=e.loggingName||"",o="undefined"!=typeof chrome&&chrome.storage?chrome.storage.local:window.localStorage,s=function(){function e(){if(r){var e=new Date,n=e.toISOString().substring(0,10)+" "+e.toString().split(" ")[4]+"."+e.getMilliseconds();console.log("["+n+"] ["+t+"] "+i+" :: ",s,a)}else console.log("["+t+"] "+i+" :: ",s,a)}var t=arguments[0].toUpperCase(),o=arguments[1],s=o[0]||"",a=o[1]||"";if("DEBUG"==n||"ALL"==n)e();else{if(n!=t)return;e()}};return{info:function(){s("info",arguments)},debug:function(){s("debug",arguments)},warn:function(){s("warn",arguments)},error:function(){s("error",arguments)},setLevel:function(e){return e=e.toUpperCase(),t.indexOf(e)!=-1?(n=e,["DEBUG","ALL"].indexOf(e)==-1&&(o.debug=""),"logLevel is now : "+n):"only : "+t.toString()+" are allowed in run time!"},level:function(){return n}}};t.exports=r},{}],10:[function(e,t,n){var r=function(e,t){if("[object Array]"==Object.prototype.toString.call(e)){var n=!0;return e.forEach(function(e){t.indexOf(e)==-1&&(n=!1,Plivo.log.warn("Ignoring invalid codec - ",e),Plivo.log.debug("Allowed list: ",t))}),!!n}return Plivo.log.error("Please send codecs in Array. Eg:",t),!1},i=function(e,t){return"boolean"==typeof t||(Plivo.log.error(e+" has to be boolean. "+t+" is not accepted"),!1)},o=function(e,t){return t.indexOf(e)!=-1||(Plivo.log.error("debug method "+e+" is not allowed"),Plivo.log.debug("Allowed list for debug: ",t),!1)},s=function(e,t){return t.indexOf(e)!=-1||(Plivo.log.error("region name "+e+" is not allowed"),Plivo.log.debug("Allowed list for regions: ",t),!1)};t.exports={codecs:r,isBoolean:i,debug:o,region:s}},{}],11:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function o(e){return"number"==typeof e}function s(e){return"object"==typeof e&&null!==e}function a(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!o(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,o,l,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||s(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}if(n=this._events[e],a(n))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:for(r=arguments.length,o=new Array(r-1),l=1;l0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())}return this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var n,r,o,a;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],o=n.length,r=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(s(n)){for(a=o;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){r=a;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],i(n))this.removeListener(e,n);else for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.listenerCount=function(e,t){var n;return n=e._events&&e._events[t]?i(e._events[t])?1:e._events[t].length:0}},{}],12:[function(e,t,n){(function(r){function i(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type)||("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function o(e){var t=window._PlivoUseColorLog;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+n.humanize(this.diff),t){var r="color: "+this.color;e.splice(1,0,r,"color: inherit");var i=0,o=0;e[0].replace(/%[a-zA-Z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))}),e.splice(o,0,r)}}function s(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?n.storage.removeItem("debug"):n.storage.debug=e}catch(t){}}function l(){var e;try{e=n.storage.debug}catch(t){}return!e&&"undefined"!=typeof r&&"env"in r&&(e=r.env.DEBUG),e}function u(){try{return window.localStorage}catch(e){}}n=t.exports=e("./debug"),n.log=s,n.formatArgs=o,n.save=a,n.load=l,n.useColors=i,n.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}},n.enable(l())}).call(this,e("_process"))},{"./debug":13,_process:16}],13:[function(e,t,n){function r(e){var t,r=0;for(t in e)r=(r<<5)-r+e.charCodeAt(t),r|=0;return n.colors[Math.abs(r)%n.colors.length]}function i(e){function t(){if(t.enabled){var e=t,r=+new Date,i=r-(u||r);e.diff=i,e.prev=u,e.curr=r,u=r;for(var o=new Array(arguments.length),s=0;s100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*d;case"days":case"day":case"d":return n*c;case"hours":case"hour":case"hrs":case"hr":case"h":return n*u;case"minutes":case"minute":case"mins":case"min":case"m":return n*l;case"seconds":case"second":case"secs":case"sec":case"s":return n*a;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function i(e){return e>=c?Math.round(e/c)+"d":e>=u?Math.round(e/u)+"h":e>=l?Math.round(e/l)+"m":e>=a?Math.round(e/a)+"s":e+"ms"}function o(e){return s(e,c,"day")||s(e,u,"hour")||s(e,l,"minute")||s(e,a,"second")||e+" ms"}function s(e,t,n){if(!(e0)return r(e);if("number"===n&&isNaN(e)===!1)return t["long"]?o(e):i(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],16:[function(e,t,n){function r(){if(!a){a=!0;for(var e,t=s.length;t;){e=s,s=[];for(var n=-1;++n1&&(e[n[0]]=void 0),e};n.parseParams=function(e){return e.split(/\;\s?/).reduce(l,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(e){return e.split(" ").map(Number)},n.parseRemoteCandidates=function(e){for(var t=[],n=e.split(" ").map(r),i=0;i=r)return e;var i=n[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},s=function(e,t,n){var r=t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format,i=[e+"="+r];if(t.names)for(var s=0;s0?"m="+e:e).trim()+"\r\n"})},r.matchPrefix=function(e,t){return r.splitLines(e).filter(function(e){return 0===e.indexOf(t)})},r.parseCandidate=function(e){var t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");for(var n={foundation:t[0],component:t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],port:parseInt(t[5],10),type:t[7]},r=8;r0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},r.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},r.parseFmtp=function(e){for(var t,n={},r=e.substr(e.indexOf(" ")+1).split(";"),i=0;i-1?(n.attribute=e.substr(t+1,r-t-1),n.value=e.substr(r+1)):n.attribute=e.substr(t+1),n},r.getMid=function(e){var t=r.matchPrefix(e,"a=mid:")[0];if(t)return t.substr(6)},r.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},r.getDtlsParameters=function(e,t){var n=r.matchPrefix(e+t,"a=fingerprint:");return{role:"auto",fingerprints:n.map(r.parseFingerprint)}},r.writeDtlsParameters=function(e,t){var n="a=setup:"+t+"\r\n";return e.fingerprints.forEach(function(e){n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),n},r.getIceParameters=function(e,t){var n=r.splitLines(e);n=n.concat(r.splitLines(t));var i={usernameFragment:n.filter(function(e){return 0===e.indexOf("a=ice-ufrag:")})[0].substr(12),password:n.filter(function(e){return 0===e.indexOf("a=ice-pwd:")})[0].substr(10)};return i},r.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},r.parseRtpParameters=function(e){for(var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=r.splitLines(e),i=n[0].split(" "),o=3;o0?"9":"0",n+=" UDP/TLS/RTP/SAVPF ",n+=t.codecs.map(function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType}).join(" ")+"\r\n",n+="c=IN IP4 0.0.0.0\r\n",n+="a=rtcp:9 IN IP4 0.0.0.0\r\n",t.codecs.forEach(function(e){n+=r.writeRtpMap(e),n+=r.writeFmtp(e),n+=r.writeRtcpFb(e)});var i=0;return t.codecs.forEach(function(e){e.maxptime>i&&(i=e.maxptime)}),i>0&&(n+="a=maxptime:"+i+"\r\n"),n+="a=rtcp-mux\r\n",t.headerExtensions.forEach(function(e){n+=r.writeExtmap(e)}),n},r.parseRtpEncodingParameters=function(e){var t,n=[],i=r.parseRtpParameters(e),o=i.fecMechanisms.indexOf("RED")!==-1,s=i.fecMechanisms.indexOf("ULPFEC")!==-1,a=r.matchPrefix(e,"a=ssrc:").map(function(e){return r.parseSsrcMedia(e)}).filter(function(e){return"cname"===e.attribute}),l=a.length>0&&a[0].ssrc,u=r.matchPrefix(e,"a=ssrc-group:FID").map(function(e){var t=e.split(" ");return t.shift(),t.map(function(e){return parseInt(e,10)})});u.length>0&&u[0].length>1&&u[0][0]===l&&(t=u[0][1]),i.codecs.forEach(function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var r={ssrc:l,codecPayloadType:parseInt(e.parameters.apt,10),rtx:{ssrc:t}};n.push(r),o&&(r=JSON.parse(JSON.stringify(r)),r.fec={ssrc:t,mechanism:s?"red+ulpfec":"red"},n.push(r))}}),0===n.length&&l&&n.push({ssrc:l});var c=r.matchPrefix(e,"b=");return c.length&&(0===c[0].indexOf("b=TIAS:")?c=parseInt(c[0].substr(7),10):0===c[0].indexOf("b=AS:")&&(c=parseInt(c[0].substr(5),10)),n.forEach(function(e){e.maxBitrate=c})),n},r.parseRtcpParameters=function(e){var t={},n=r.matchPrefix(e,"a=ssrc:").map(function(e){return r.parseSsrcMedia(e)}).filter(function(e){return"cname"===e.attribute})[0];n&&(t.cname=n.value,t.ssrc=n.ssrc);var i=r.matchPrefix(e,"a=rtcp-rsize");t.reducedSize=i.length>0,t.compound=0===i.length;var o=r.matchPrefix(e,"a=rtcp-mux");return t.mux=o.length>0,t},r.parseMsid=function(e){var t,n=r.matchPrefix(e,"a=msid:");if(1===n.length)return t=n[0].substr(7).split(" "),{stream:t[0],track:t[1]};var i=r.matchPrefix(e,"a=ssrc:").map(function(e){return r.parseSsrcMedia(e)}).filter(function(e){return"msid"===e.attribute});return i.length>0?(t=i[0].value.split(" "),{stream:t[0],track:t[1]}):void 0},r.writeSessionBoilerplate=function(){return"v=0\r\no=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},r.writeMediaSection=function(e,t,n,i){var o=r.writeRtpDescription(e.kind,t);if(o+=r.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=r.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===n?"actpass":"active"),o+="a=mid:"+e.mid+"\r\n",o+=e.direction?"a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?"a=sendrecv\r\n":e.rtpSender?"a=sendonly\r\n":e.rtpReceiver?"a=recvonly\r\n":"a=inactive\r\n",e.rtpSender){var s="msid:"+i.id+" "+e.rtpSender.track.id+"\r\n";o+="a="+s,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+s,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+s,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+r.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+r.localCName+"\r\n"),o},r.getDirection=function(e,t){for(var n=r.splitLines(e),i=0;i=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),v(t)?r.showHidden=t:t&&n._extend(r,t),S(r.showHidden)&&(r.showHidden=!1),S(r.depth)&&(r.depth=2),S(r.colors)&&(r.colors=!1),S(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),l(r,e,r.depth)}function o(e,t){var n=i.styles[t];return n?"\x1b["+i.colors[n][0]+"m"+e+"\x1b["+i.colors[n][1]+"m":e}function s(e,t){return e}function a(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function l(e,t,r){if(e.customInspect&&t&&k(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return b(i)||(i=l(e,i,r)),i}var o=u(e,t);if(o)return o;var s=Object.keys(t),v=a(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),E(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return c(t);if(0===s.length){if(k(t)){var g=t.name?": "+t.name:"";return e.stylize("[Function"+g+"]","special")}if(T(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(w(t))return e.stylize(Date.prototype.toString.call(t),"date");if(E(t))return c(t)}var m="",y=!1,_=["{","}"];if(p(t)&&(y=!0,_=["[","]"]),k(t)){var S=t.name?": "+t.name:"";m=" [Function"+S+"]"}if(T(t)&&(m=" "+RegExp.prototype.toString.call(t)),w(t)&&(m=" "+Date.prototype.toUTCString.call(t)),E(t)&&(m=" "+c(t)),0===s.length&&(!y||0==t.length))return _[0]+m+_[1];if(r<0)return T(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var C;return C=y?d(e,t,r,v,s):s.map(function(n){return f(e,t,r,v,n,y)}),e.seen.pop(),h(C,m,_)}function u(e,t){if(S(t))return e.stylize("undefined","undefined");if(b(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return y(t)?e.stylize(""+t,"number"):v(t)?e.stylize(""+t,"boolean"):g(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,n,r,i){for(var o=[],s=0,a=t.length;s-1&&(a=o?a.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+a.split("\n").map(function(e){return" "+e}).join("\n"))):a=e.stylize("[Circular]","special")),S(s)){if(o&&i.match(/^\d+$/))return a;s=JSON.stringify(""+i),s.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function h(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function p(e){return Array.isArray(e)}function v(e){return"boolean"==typeof e}function g(e){return null===e}function m(e){return null==e}function y(e){return"number"==typeof e}function b(e){return"string"==typeof e}function _(e){return"symbol"==typeof e}function S(e){return void 0===e}function T(e){return C(e)&&"[object RegExp]"===I(e)}function C(e){return"object"==typeof e&&null!==e}function w(e){return C(e)&&"[object Date]"===I(e)}function E(e){return C(e)&&("[object Error]"===I(e)||e instanceof Error)}function k(e){return"function"==typeof e}function R(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function I(e){return Object.prototype.toString.call(e)}function P(e){return e<10?"0"+e.toString(10):e.toString(10)}function A(){var e=new Date,t=[P(e.getHours()),P(e.getMinutes()),P(e.getSeconds())].join(":");return[e.getDate(),N[e.getMonth()],t].join(" ")}function O(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var M=/%[sdj%]/g;n.format=function(e){if(!b(e)){for(var t=[],n=0;n=o)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(t){return"[Circular]"}default:return e}}),a=r[n];n0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof arguments[0]))return t.apply(this,[]);var s=function(e){var t={},n=e.result();return n.forEach(function(e){var n={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach(function(t){n[t]=e.stat(t)}),t[n.id]=n}),t},a=function(e){return new Map(Object.keys(e).map(function(t){return[t,e[t]]}))};if(arguments.length>=2){var l=function(e){o[1](a(s(e)))};return t.apply(this,[l,arguments[0]])}return new Promise(function(e,n){t.apply(i,[function(t){e(a(s(t)))},n])}).then(n,r)},i.version<51&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(e){var t=RTCPeerConnection.prototype[e];RTCPeerConnection.prototype[e]=function(){var e=arguments,n=this,r=new Promise(function(r,i){t.apply(n,[e[0],r,i])});return e.length<2?r:r.then(function(){e[1].apply(null,[])},function(t){e.length>=3&&e[2].apply(null,[t])})}}),i.version<52&&["createOffer","createAnswer"].forEach(function(e){var t=RTCPeerConnection.prototype[e];RTCPeerConnection.prototype[e]=function(){var e=this;if(arguments.length<1||1===arguments.length&&"object"==typeof arguments[0]){var n=1===arguments.length?arguments[0]:void 0;return new Promise(function(r,i){t.apply(e,[r,i,n])})}return t.apply(this,arguments)}}),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(e){var t=RTCPeerConnection.prototype[e];RTCPeerConnection.prototype[e]=function(){return arguments[0]=new("addIceCandidate"===e?RTCIceCandidate:RTCSessionDescription)(arguments[0]),t.apply(this,arguments)}});var n=RTCPeerConnection.prototype.addIceCandidate;RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())}}};t.exports={shimMediaStream:o.shimMediaStream,shimOnTrack:o.shimOnTrack,shimGetSendersWithDtmf:o.shimGetSendersWithDtmf,shimSourceObject:o.shimSourceObject,shimPeerConnection:o.shimPeerConnection,shimGetUserMedia:e("./getusermedia")}},{"../utils.js":33,"./getusermedia":26}],26:[function(e,t,n){"use strict";var r=e("../utils.js").log,i=e("../utils.js").browserDetails;t.exports=function(){var e=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;var t={};return Object.keys(e).forEach(function(n){if("require"!==n&&"advanced"!==n&&"mediaSource"!==n){var r="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==r.exact&&"number"==typeof r.exact&&(r.min=r.max=r.exact);var i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==r.ideal){t.optional=t.optional||[];var o={};"number"==typeof r.ideal?(o[i("min",n)]=r.ideal,t.optional.push(o),o={},o[i("max",n)]=r.ideal,t.optional.push(o)):(o[i("",n)]=r.ideal,t.optional.push(o))}void 0!==r.exact&&"number"!=typeof r.exact?(t.mandatory=t.mandatory||{},t.mandatory[i("",n)]=r.exact):["min","max"].forEach(function(e){void 0!==r[e]&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])})}}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},t=function(t,n){if(t=JSON.parse(JSON.stringify(t)),t&&t.audio&&(t.audio=e(t.audio)),t&&"object"==typeof t.video){var o=t.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});var s=i.version<61;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!navigator.mediaDevices.getSupportedConstraints||!navigator.mediaDevices.getSupportedConstraints().facingMode||s)){delete t.video.facingMode;var a;if("environment"===o.exact||"environment"===o.ideal?a=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(a=["front"]),a)return navigator.mediaDevices.enumerateDevices().then(function(i){i=i.filter(function(e){return"videoinput"===e.kind});var s=i.find(function(e){return a.some(function(t){return e.label.toLowerCase().indexOf(t)!==-1})});return!s&&i.length&&a.indexOf("back")!==-1&&(s=i[i.length-1]),s&&(t.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),t.video=e(t.video),r("chrome: "+JSON.stringify(t)),n(t)})}t.video=e(t.video)}return r("chrome: "+JSON.stringify(t)),n(t)},n=function(e){return{name:{ConstraintNotSatisfiedError:"OverconstrainedError",PermissionDeniedError:"NotAllowedError",TrackStartError:"NotReadableError"}[e.name]||e.name,message:e.message,constraint:e.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}},o=function(e,r,i){t(e,function(e){navigator.webkitGetUserMedia(e,r,function(e){i(n(e))})})};navigator.getUserMedia=o;var s=function(e){return new Promise(function(t,n){navigator.getUserMedia(e,t,n)})};if(navigator.mediaDevices||(navigator.mediaDevices={getUserMedia:s,enumerateDevices:function(){return new Promise(function(e){var t={audio:"audioinput",video:"videoinput"};return MediaStreamTrack.getSources(function(n){e(n.map(function(e){return{label:e.label,kind:t[e.kind],deviceId:e.id,groupId:""}}))})})},getSupportedConstraints:function(){return{deviceId:!0,echoCancellation:!0,facingMode:!0,frameRate:!0,height:!0,width:!0}}}),navigator.mediaDevices.getUserMedia){var a=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(e){return t(e,function(e){return a(e).then(function(t){if(e.audio&&!t.getAudioTracks().length||e.video&&!t.getVideoTracks().length)throw t.getTracks().forEach(function(e){e.stop()}),new DOMException("","NotFoundError");return t},function(e){return Promise.reject(n(e))})})}}else navigator.mediaDevices.getUserMedia=function(e){return s(e)};"undefined"==typeof navigator.mediaDevices.addEventListener&&(navigator.mediaDevices.addEventListener=function(){r("Dummy mediaDevices.addEventListener called.")}),"undefined"==typeof navigator.mediaDevices.removeEventListener&&(navigator.mediaDevices.removeEventListener=function(){r("Dummy mediaDevices.removeEventListener called.")})}},{"../utils.js":33}],27:[function(e,t,n){"use strict";var r=e("../utils").browserDetails,i=e("./rtcpeerconnection_shim");t.exports={shimGetUserMedia:e("./getusermedia"),shimPeerConnection:function(){if(window.RTCIceGatherer&&(window.RTCIceCandidate||(window.RTCIceCandidate=function(e){return e}),window.RTCSessionDescription||(window.RTCSessionDescription=function(e){return e}),r.version<15025)){var e=Object.getOwnPropertyDescriptor(MediaStreamTrack.prototype,"enabled");Object.defineProperty(MediaStreamTrack.prototype,"enabled",{set:function(t){e.set.call(this,t);var n=new Event("enabled");n.enabled=t,this.dispatchEvent(n)}})}window.RTCPeerConnection=i(r.version)},shimReplaceTrack:function(){!window.RTCRtpSender||"replaceTrack"in RTCRtpSender.prototype||(RTCRtpSender.prototype.replaceTrack=RTCRtpSender.prototype.setTrack)}}},{"../utils":33,"./getusermedia":28,"./rtcpeerconnection_shim":29}],28:[function(e,t,n){"use strict";t.exports=function(){var e=function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString:function(){return this.name}}},t=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(n){return t(n)["catch"](function(t){return Promise.reject(e(t))})}}},{}],29:[function(e,t,n){"use strict";function r(e){var t=e.filter(function(e){return"audio"===e.kind}),n=e.filter(function(e){return"video"===e.kind});for(e=[];t.length||n.length;)t.length&&e.push(t.shift()),n.length&&e.push(n.shift());return e}function i(e,t){var n=!1;return e=JSON.parse(JSON.stringify(e)),e.filter(function(e){if(e&&(e.urls||e.url)){var r=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var i="string"==typeof r;return i&&(r=[r]),r=r.filter(function(e){var r=0===e.indexOf("turn:")&&e.indexOf("transport=udp")!==-1&&e.indexOf("turn:[")===-1&&!n;return r?(n=!0,!0):0===e.indexOf("stun:")&&t>=14393}),delete e.url,e.urls=i?r[0]:r,!!r.length}return!1})}function o(e,t){var n={codecs:[],headerExtensions:[],fecMechanisms:[]},r=function(e,t){e=parseInt(e,10);for(var n=0;n0,n={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,wantReceive:!0};if(this.usingBundle&&t)n.iceTransport=this.transceivers[0].iceTransport,n.dtlsTransport=this.transceivers[0].dtlsTransport;else{var r=this._createIceAndDtlsTransports();n.iceTransport=r.iceTransport,n.dtlsTransport=r.dtlsTransport}return this.transceivers.push(n),n},t.prototype.addTrack=function(e,t){for(var n,r=0;r=15025)this.localStreams.push(t),t.getTracks().forEach(function(e){n.addTrack(e,t)});else{var r=t.clone();t.getTracks().forEach(function(e,t){var n=r.getTracks()[t];e.addEventListener("enabled",function(e){n.enabled=e.enabled})}),r.getTracks().forEach(function(e){n.addTrack(e,r)}),this.localStreams.push(r)}this._maybeFireNegotiationNeeded()},t.prototype.removeStream=function(e){var t=this.localStreams.indexOf(e);t>-1&&(this.localStreams.splice(t,1),this._maybeFireNegotiationNeeded())},t.prototype.getSenders=function(){return this.transceivers.filter(function(e){return!!e.rtpSender}).map(function(e){return e.rtpSender})},t.prototype.getReceivers=function(){return this.transceivers.filter(function(e){return!!e.rtpReceiver}).map(function(e){return e.rtpReceiver})},t.prototype._createIceGatherer=function(e,t){var n=this,r=new RTCIceGatherer(n.iceOptions);return r.onlocalcandidate=function(i){var o=new Event("icecandidate");o.candidate={sdpMid:e,sdpMLineIndex:t};var s=i.candidate,l=!s||0===Object.keys(s).length;l?void 0===r.state&&(r.state="completed"):(s.component=1,o.candidate.candidate=a.writeCandidate(s));var u=a.splitSections(n.localDescription.sdp);l?u[o.candidate.sdpMLineIndex+1]+="a=end-of-candidates\r\n":u[o.candidate.sdpMLineIndex+1]+="a="+o.candidate.candidate+"\r\n",n.localDescription.sdp=u.join("");var c=n._pendingOffer?n._pendingOffer:n.transceivers,d=c.every(function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state});switch(n.iceGatheringState){case"new":l||n._localIceCandidatesBuffer.push(o),l&&d&&n._localIceCandidatesBuffer.push(new Event("icecandidate"));break;case"gathering":n._emitBufferedCandidates(),l||(n.dispatchEvent(o),null!==n.onicecandidate&&n.onicecandidate(o)),d&&(n.dispatchEvent(new Event("icecandidate")),null!==n.onicecandidate&&n.onicecandidate(new Event("icecandidate")),n.iceGatheringState="complete",n._emitGatheringStateChange());break;case"complete":}},r},t.prototype._createIceAndDtlsTransports=function(){var e=this,t=new RTCIceTransport(null);t.onicestatechange=function(){e._updateConnectionState()};var n=new RTCDtlsTransport(t);return n.ondtlsstatechange=function(){e._updateConnectionState()},n.onerror=function(){Object.defineProperty(n,"state",{value:"failed",writable:!0}),e._updateConnectionState()},{iceTransport:t,dtlsTransport:n}},t.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var n=this.transceivers[e].iceTransport;n&&(delete n.onicestatechange,delete this.transceivers[e].iceTransport);var r=this.transceivers[e].dtlsTransport;r&&(delete r.ondtlssttatechange,delete r.onerror,delete this.transceivers[e].dtlsTransport)},t.prototype._transceive=function(t,n,r){var i=o(t.localCapabilities,t.remoteCapabilities);n&&t.rtpSender&&(i.encodings=t.sendEncodingParameters,i.rtcp={cname:a.localCName,compound:t.rtcpParameters.compound},t.recvEncodingParameters.length&&(i.rtcp.ssrc=t.recvEncodingParameters[0].ssrc),t.rtpSender.send(i)),r&&t.rtpReceiver&&("video"===t.kind&&t.recvEncodingParameters&&e<15019&&t.recvEncodingParameters.forEach(function(e){delete e.rtx}),i.encodings=t.recvEncodingParameters,i.rtcp={cname:t.rtcpParameters.cname,compound:t.rtcpParameters.compound},t.sendEncodingParameters.length&&(i.rtcp.ssrc=t.sendEncodingParameters[0].ssrc),t.rtpReceiver.receive(i))},t.prototype.setLocalDescription=function(e){var t=this;if(!s("setLocalDescription",e.type,this.signalingState)){var n=new Error("Can not set local "+e.type+" in state "+this.signalingState);return n.name="InvalidStateError",arguments.length>2&&"function"==typeof arguments[2]&&window.setTimeout(arguments[2],0,n),Promise.reject(n)}var r,i;if("offer"===e.type)this._pendingOffer&&(r=a.splitSections(e.sdp),i=r.shift(),r.forEach(function(e,n){var r=a.parseRtpParameters(e);t._pendingOffer[n].localCapabilities=r}),this.transceivers=this._pendingOffer,delete this._pendingOffer);else if("answer"===e.type){r=a.splitSections(t.remoteDescription.sdp),i=r.shift();var l=a.matchPrefix(i,"a=ice-lite").length>0;r.forEach(function(e,n){var r=t.transceivers[n],s=r.iceGatherer,u=r.iceTransport,c=r.dtlsTransport,d=r.localCapabilities,f=r.remoteCapabilities,h=a.isRejected(e);if(!h&&!r.isDatachannel){var p=a.getIceParameters(e,i),v=a.getDtlsParameters(e,i);l&&(v.role="server"),t.usingBundle&&0!==n||(u.start(s,p,l?"controlling":"controlled"),c.start(v));var g=o(d,f);t._transceive(r,g.codecs.length>0,!1)}})}switch(this.localDescription={type:e.type,sdp:e.sdp},e.type){case"offer":this._updateSignalingState("have-local-offer");break;case"answer":this._updateSignalingState("stable");break;default:throw new TypeError('unsupported type "'+e.type+'"')}var u=arguments.length>1&&"function"==typeof arguments[1];if(u){var c=arguments[1];window.setTimeout(function(){c(),"new"===t.iceGatheringState&&(t.iceGatheringState="gathering",t._emitGatheringStateChange()),t._emitBufferedCandidates()},0)}var d=Promise.resolve();return d.then(function(){u||("new"===t.iceGatheringState&&(t.iceGatheringState="gathering",t._emitGatheringStateChange()),window.setTimeout(t._emitBufferedCandidates.bind(t),500))}),d},t.prototype.setRemoteDescription=function(t){var n=this;if(!s("setRemoteDescription",t.type,this.signalingState)){var r=new Error("Can not set remote "+t.type+" in state "+this.signalingState);return r.name="InvalidStateError",arguments.length>2&&"function"==typeof arguments[2]&&window.setTimeout(arguments[2],0,r),Promise.reject(r)}var i={},o=[],l=a.splitSections(t.sdp),u=l.shift(),c=a.matchPrefix(u,"a=ice-lite").length>0,d=a.matchPrefix(u,"a=group:BUNDLE ").length>0;this.usingBundle=d;var f=a.matchPrefix(u,"a=ice-options:")[0];switch(f?this.canTrickleIceCandidates=f.substr(14).split(" ").indexOf("trickle")>=0:this.canTrickleIceCandidates=!1,l.forEach(function(r,s){var l=a.splitLines(r),f=a.getKind(r),h=a.isRejected(r),p=l[0].substr(2).split(" ")[2],v=a.getDirection(r,u),g=a.parseMsid(r),m=a.getMid(r)||a.generateIdentifier();if("application"===f&&"DTLS/SCTP"===p)return void(n.transceivers[s]={mid:m,isDatachannel:!0});var y,b,_,S,T,C,w,E,k,R,I,P=a.parseRtpParameters(r);h||(R=a.getIceParameters(r,u),I=a.getDtlsParameters(r,u),I.role="client"),w=a.parseRtpEncodingParameters(r);var A=a.parseRtcpParameters(r),O=a.matchPrefix(r,"a=end-of-candidates",u).length>0,M=a.matchPrefix(r,"a=candidate:").map(function(e){return a.parseCandidate(e)}).filter(function(e){return"1"===e.component||1===e.component});"offer"!==t.type||h?"answer"!==t.type||h||(d&&s>0&&(n._disposeIceAndDtlsTransports(s),n.transceivers[s].iceGatherer=n.transceivers[0].iceGatherer,n.transceivers[s].iceTransport=n.transceivers[0].iceTransport,n.transceivers[s].dtlsTransport=n.transceivers[0].dtlsTransport,n.transceivers[s].rtpSender&&n.transceivers[s].rtpSender.setTransport(n.transceivers[0].dtlsTransport),n.transceivers[s].rtpReceiver&&n.transceivers[s].rtpReceiver.setTransport(n.transceivers[0].dtlsTransport)),y=n.transceivers[s],b=y.iceGatherer,_=y.iceTransport,S=y.dtlsTransport,T=y.rtpReceiver,C=y.sendEncodingParameters,E=y.localCapabilities,n.transceivers[s].recvEncodingParameters=w,n.transceivers[s].remoteCapabilities=P,n.transceivers[s].rtcpParameters=A,(c||O)&&M.length&&_.setRemoteCandidates(M),d&&0!==s||(_.start(b,R,"controlling"),S.start(I)),n._transceive(y,"sendrecv"===v||"recvonly"===v,"sendrecv"===v||"sendonly"===v),!T||"sendrecv"!==v&&"sendonly"!==v?delete y.rtpReceiver:(k=T.track,g?(i[g.stream]||(i[g.stream]=new MediaStream),i[g.stream].addTrack(k),o.push([k,T,i[g.stream]])):(i["default"]||(i["default"]=new MediaStream),i["default"].addTrack(k),o.push([k,T,i["default"]])))):(y=n.transceivers[s]||n._createTransceiver(f),y.mid=m,y.iceGatherer||(y.iceGatherer=d&&s>0?n.transceivers[0].iceGatherer:n._createIceGatherer(m,s)),!O||d&&0!==s||y.iceTransport.setRemoteCandidates(M),E=RTCRtpReceiver.getCapabilities(f),e<15019&&(E.codecs=E.codecs.filter(function(e){return"rtx"!==e.name})),C=[{ssrc:1001*(2*s+2)}],"sendrecv"!==v&&"sendonly"!==v||(T=new RTCRtpReceiver(y.dtlsTransport,f),k=T.track,g?(i[g.stream]||(i[g.stream]=new MediaStream,Object.defineProperty(i[g.stream],"id",{get:function(){return g.stream}})),Object.defineProperty(k,"id",{get:function(){return g.track}}),i[g.stream].addTrack(k),o.push([k,T,i[g.stream]])):(i["default"]||(i["default"]=new MediaStream),i["default"].addTrack(k),o.push([k,T,i["default"]]))),y.localCapabilities=E,y.remoteCapabilities=P,y.rtpReceiver=T,y.rtcpParameters=A,y.sendEncodingParameters=C,y.recvEncodingParameters=w,n._transceive(n.transceivers[s],!1,"sendrecv"===v||"sendonly"===v))}),this.remoteDescription={type:t.type,sdp:t.sdp},t.type){case"offer":this._updateSignalingState("have-remote-offer");break;case"answer":this._updateSignalingState("stable");break;default:throw new TypeError('unsupported type "'+t.type+'"')}return Object.keys(i).forEach(function(e){var t=i[e];if(t.getTracks().length){n.remoteStreams.push(t);var r=new Event("addstream");r.stream=t,n.dispatchEvent(r),null!==n.onaddstream&&window.setTimeout(function(){n.onaddstream(r)},0),o.forEach(function(e){var r=e[0],i=e[1];if(t.id===e[2].id){var o=new Event("track");o.track=r,o.receiver=i,o.streams=[t],n.dispatchEvent(o),null!==n.ontrack&&window.setTimeout(function(){n.ontrack(o)},0)}})}}),window.setTimeout(function(){n&&n.transceivers&&n.transceivers.forEach(function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))})},4e3),arguments.length>1&&"function"==typeof arguments[1]&&window.setTimeout(arguments[1],0),Promise.resolve()},t.prototype.close=function(){this.transceivers.forEach(function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()}),this._updateSignalingState("closed")},t.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this.dispatchEvent(t),null!==this.onsignalingstatechange&&this.onsignalingstatechange(t)},t.prototype._maybeFireNegotiationNeeded=function(){var e=this;"stable"===this.signalingState&&this.needNegotiation!==!0&&(this.needNegotiation=!0,window.setTimeout(function(){if(e.needNegotiation!==!1){e.needNegotiation=!1;var t=new Event("negotiationneeded");e.dispatchEvent(t),null!==e.onnegotiationneeded&&e.onnegotiationneeded(t)}},0))},t.prototype._updateConnectionState=function(){var e,t=this,n={"new":0,closed:0,connecting:0,checking:0,connected:0,completed:0,failed:0};if(this.transceivers.forEach(function(e){n[e.iceTransport.state]++,n[e.dtlsTransport.state]++}),n.connected+=n.completed,e="new",n.failed>0?e="failed":n.connecting>0||n.checking>0?e="connecting":n.disconnected>0?e="disconnected":n["new"]>0?e="new":(n.connected>0||n.completed>0)&&(e="connected"),e!==t.iceConnectionState){t.iceConnectionState=e;var r=new Event("iceconnectionstatechange");this.dispatchEvent(r),null!==this.oniceconnectionstatechange&&this.oniceconnectionstatechange(r)}},t.prototype.createOffer=function(){var t=this;if(this._pendingOffer)throw new Error("createOffer called while there is a pending offer.");var n;1===arguments.length&&"function"!=typeof arguments[0]?n=arguments[0]:3===arguments.length&&(n=arguments[2]);var i=this.transceivers.filter(function(e){return"audio"===e.kind}).length,o=this.transceivers.filter(function(e){return"video"===e.kind}).length;if(n){if(n.mandatory||n.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==n.offerToReceiveAudio&&(i=n.offerToReceiveAudio===!0?1:n.offerToReceiveAudio===!1?0:n.offerToReceiveAudio),void 0!==n.offerToReceiveVideo&&(o=n.offerToReceiveVideo===!0?1:n.offerToReceiveVideo===!1?0:n.offerToReceiveVideo)}for(this.transceivers.forEach(function(e){"audio"===e.kind?(i--,i<0&&(e.wantReceive=!1)):"video"===e.kind&&(o--,o<0&&(e.wantReceive=!1))});i>0||o>0;)i>0&&(this._createTransceiver("audio"),i--),o>0&&(this._createTransceiver("video"),o--);var s=r(this.transceivers),l=a.writeSessionBoilerplate();s.forEach(function(n,r){var i=n.track,o=n.kind,l=a.generateIdentifier();n.mid=l,n.iceGatherer||(n.iceGatherer=t.usingBundle&&r>0?s[0].iceGatherer:t._createIceGatherer(l,r));var u=RTCRtpSender.getCapabilities(o);e<15019&&(u.codecs=u.codecs.filter(function(e){return"rtx"!==e.name})),u.codecs.forEach(function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1")});var c=[{ssrc:1001*(2*r+1)}];i&&e>=15019&&"video"===o&&(c[0].rtx={ssrc:1001*(2*r+1)+1}),n.wantReceive&&(n.rtpReceiver=new RTCRtpReceiver(n.dtlsTransport,o)),n.localCapabilities=u,n.sendEncodingParameters=c}),"max-compat"!==this._config.bundlePolicy&&(l+="a=group:BUNDLE "+s.map(function(e){return e.mid}).join(" ")+"\r\n"),l+="a=ice-options:trickle\r\n",s.forEach(function(e,t){l+=a.writeMediaSection(e,e.localCapabilities,"offer",e.stream),l+="a=rtcp-rsize\r\n"}),this._pendingOffer=s;var u=new RTCSessionDescription({type:"offer",sdp:l});return arguments.length&&"function"==typeof arguments[0]&&window.setTimeout(arguments[0],0,u),Promise.resolve(u)},t.prototype.createAnswer=function(){var t=a.writeSessionBoilerplate();this.usingBundle&&(t+="a=group:BUNDLE "+this.transceivers.map(function(e){return e.mid}).join(" ")+"\r\n"),this.transceivers.forEach(function(n,r){if(n.isDatachannel)return void(t+="m=application 0 DTLS/SCTP 5000\r\nc=IN IP4 0.0.0.0\r\na=mid:"+n.mid+"\r\n");if(n.stream){var i;"audio"===n.kind?i=n.stream.getAudioTracks()[0]:"video"===n.kind&&(i=n.stream.getVideoTracks()[0]),i&&e>=15019&&"video"===n.kind&&(n.sendEncodingParameters[0].rtx={ssrc:1001*(2*r+2)+1})}var s=o(n.localCapabilities,n.remoteCapabilities),l=s.codecs.filter(function(e){return"rtx"===e.name.toLowerCase()}).length;!l&&n.sendEncodingParameters[0].rtx&&delete n.sendEncodingParameters[0].rtx,t+=a.writeMediaSection(n,s,"answer",n.stream),n.rtcpParameters&&n.rtcpParameters.reducedSize&&(t+="a=rtcp-rsize\r\n")});var n=new RTCSessionDescription({type:"answer",sdp:t});return arguments.length&&"function"==typeof arguments[0]&&window.setTimeout(arguments[0],0,n),Promise.resolve(n)},t.prototype.addIceCandidate=function(e){if(e){var t=e.sdpMLineIndex;if(e.sdpMid)for(var n=0;n0?a.parseCandidate(e.candidate):{};if("tcp"===i.protocol&&(0===i.port||9===i.port))return Promise.resolve();if(i.component&&"1"!==i.component&&1!==i.component)return Promise.resolve();r.iceTransport.addRemoteCandidate(i);var o=a.splitSections(this.remoteDescription.sdp);o[t+1]+=(i.type?e.candidate.trim():"a=end-of-candidates")+"\r\n",this.remoteDescription.sdp=o.join("")}}else for(var s=0;s1&&"function"==typeof arguments[1]&&window.setTimeout(arguments[1],0),Promise.resolve()},t.prototype.getStats=function(){var e=[];this.transceivers.forEach(function(t){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(n){t[n]&&e.push(t[n].getStats())})});var t=arguments.length>1&&"function"==typeof arguments[1]&&arguments[1],n=function(e){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};return new Promise(function(r){var i=new Map;Promise.all(e).then(function(e){e.forEach(function(e){Object.keys(e).forEach(function(t){e[t].type=n(e[t]),i.set(t,e[t])})}),t&&window.setTimeout(t,0,i),r(i)})})},t}},{sdp:21}],30:[function(e,t,n){"use strict";var r=e("../utils").browserDetails,i={shimOnTrack:function(){"object"!=typeof window||!window.RTCPeerConnection||"ontrack"in window.RTCPeerConnection.prototype||Object.defineProperty(window.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(e){this._ontrack&&(this.removeEventListener("track",this._ontrack),this.removeEventListener("addstream",this._ontrackpoly)),this.addEventListener("track",this._ontrack=e),this.addEventListener("addstream",this._ontrackpoly=function(e){e.stream.getTracks().forEach(function(t){var n=new Event("track");n.track=t,n.receiver={track:t},n.streams=[e.stream],this.dispatchEvent(n)}.bind(this))}.bind(this))}})},shimSourceObject:function(){"object"==typeof window&&(!window.HTMLMediaElement||"srcObject"in window.HTMLMediaElement.prototype||Object.defineProperty(window.HTMLMediaElement.prototype,"srcObject",{get:function(){return this.mozSrcObject},set:function(e){this.mozSrcObject=e}}))},shimPeerConnection:function(){if("object"==typeof window&&(window.RTCPeerConnection||window.mozRTCPeerConnection)){window.RTCPeerConnection||(window.RTCPeerConnection=function(e,t){if(r.version<38&&e&&e.iceServers){for(var n=[],i=0;i=0)){this._streams.push(t);var n=new Event("addstream");n.stream=e.streams[0],this.dispatchEvent(n)}}.bind(this))}})},shimCallbacksAPI:function(){if("object"==typeof window&&window.RTCPeerConnection){var e=RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,r=e.setLocalDescription,i=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(e,n){var r=arguments.length>=2?arguments[2]:arguments[0],i=t.apply(this,[r]);return n?(i.then(e,n),Promise.resolve()):i},e.createAnswer=function(e,t){var r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i};var s=function(e,t,n){var i=r.apply(this,[e]);return n?(i.then(t,n),Promise.resolve()):i};e.setLocalDescription=s,s=function(e,t,n){var r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},e.setRemoteDescription=s,s=function(e,t,n){var r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},e.addIceCandidate=s}},shimGetUserMedia:function(){navigator.getUserMedia||(navigator.webkitGetUserMedia?navigator.getUserMedia=navigator.webkitGetUserMedia.bind(navigator):navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&(navigator.getUserMedia=function(e,t,n){navigator.mediaDevices.getUserMedia(e).then(t,n)}.bind(navigator)))}};t.exports={shimCallbacksAPI:r.shimCallbacksAPI,shimAddStream:r.shimAddStream,shimOnAddStream:r.shimOnAddStream,shimGetUserMedia:r.shimGetUserMedia}},{}],33:[function(e,t,n){"use strict";var r=!0,i={disableLog:function(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(r=e,e?"adapter.js logging disabled":"adapter.js logging enabled")},log:function(){if("object"==typeof window){if(r)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},extractVersion:function(e,t,n){var r=e.match(t);return r&&r.length>=n&&parseInt(r[n],10)},detectBrowser:function(){var e={};if(e.browser=null,e.version=null,"undefined"==typeof window||!window.navigator)return e.browser="Not a browser.",e;if(navigator.mozGetUserMedia)e.browser="firefox",e.version=this.extractVersion(navigator.userAgent,/Firefox\/(\d+)\./,1);else if(navigator.webkitGetUserMedia)if(window.webkitRTCPeerConnection)e.browser="chrome",e.version=this.extractVersion(navigator.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!navigator.userAgent.match(/Version\/(\d+).(\d+)/))return e.browser="Unsupported webkit-based browser with GUM support but no WebRTC support.",e;e.browser="safari",e.version=this.extractVersion(navigator.userAgent,/AppleWebKit\/(\d+)\./,1)}else if(navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/))e.browser="edge",e.version=this.extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!navigator.mediaDevices||!navigator.userAgent.match(/AppleWebKit\/(\d+)\./))return e.browser="Not a supported browser.",e;e.browser="safari",e.version=this.extractVersion(navigator.userAgent,/AppleWebKit\/(\d+)\./,1)}return e},shimCreateObjectURL:function(){return}};t.exports={log:i.log,disableLog:i.disableLog,browserDetails:i.detectBrowser(),extractVersion:i.extractVersion,shimCreateObjectURL:i.shimCreateObjectURL,detectBrowser:i.detectBrowser.bind(i)}},{}],34:[function(e,t,n){t.exports={name:"plivowebsdk",title:"plivowebsdk",version:"2.0.19",description:"Plivo WebRTC sdk for use in chrome/firefox ",main:"./lib/index.js",directories:{example:"example"},scripts:{build:"node_modules/gulp/bin/gulp.js build"},repository:{type:"git",url:"git+https://github.com/gigster-eng/PlivoWebSDK.git"},author:"",license:"ISC",bugs:{url:"https://github.com/gigster-eng/PlivoWebSDK/issues"},homepage:"https://github.com/gigster-eng/PlivoWebSDK#readme",dependencies:{debug:"^2.6.3","sdp-transform":"^2.3.0",uuid:"^2.0.3","webrtc-adapter":"^3.2.0"},devDependencies:{browserify:"^9.0.3",cheerio:"^0.22.0",del:"^2.0.2",disc:"^1.3.2",eslint:"^2.12.0",gulp:"^3.9.0","gulp-copy":"0.0.2","gulp-express":"^0.3.5","gulp-footer":"^1.0.5","gulp-header":"^2.0.5","gulp-insert":"^0.5.0","gulp-istanbul":"^0.10.3","gulp-newer":"^1.0.0","gulp-rename":"^1.2.2","gulp-replace":"^0.5.4","gulp-uglify":"^1.4.2","gulp-util":"^3.0.7",jsdoc:"https://github.com/jsdoc3/jsdoc.git#e2fd9e75de9617aadfc3120331f020b2d66cff86",jshint:"^2.6.3","jshint-stylish":"^1.0.0",mkdirp:"^0.5.1",opener:"^1.4.2",promptly:"^0.2.0","release-tool":"^0.2.2","run-sequence":"^1.2.2",sinon:"^1.15.3","stream-from-promise":"^0.1.0",through2:"^2.0.0","vinyl-source-stream":"^1.1.0"}}},{}],35:[function(e,t,n){var r=e("../package.json"),i={USER_AGENT:r.title+" "+r.version,SIP:"sip",SIPS:"sips",causes:{CONNECTION_ERROR:"Connection Error",REQUEST_TIMEOUT:"Request Timeout",SIP_FAILURE_CODE:"SIP Failure Code",INTERNAL_ERROR:"Internal Error",BUSY:"Busy",REJECTED:"Rejected",REDIRECTED:"Redirected",UNAVAILABLE:"Unavailable",NOT_FOUND:"Not Found",ADDRESS_INCOMPLETE:"Address Incomplete",INCOMPATIBLE_SDP:"Incompatible SDP",MISSING_SDP:"Missing SDP",AUTHENTICATION_ERROR:"Authentication Error",BYE:"Terminated",WEBRTC_ERROR:"WebRTC Error",CANCELED:"Canceled",NO_ANSWER:"No Answer",EXPIRES:"Expires",NO_ACK:"No ACK",DIALOG_ERROR:"Dialog Error",USER_DENIED_MEDIA_ACCESS:"User Denied Media Access",BAD_MEDIA_DESCRIPTION:"Bad Media Description",RTP_TIMEOUT:"RTP Timeout"},SIP_ERROR_CAUSES:{REDIRECTED:[300,301,302,305,380],BUSY:[486,600],REJECTED:[403,603],NOT_FOUND:[404,604],UNAVAILABLE:[480,410,408,430],ADDRESS_INCOMPLETE:[484,424],INCOMPATIBLE_SDP:[488,606],AUTHENTICATION_ERROR:[401,407]},ACK:"ACK",BYE:"BYE",CANCEL:"CANCEL",INFO:"INFO",INVITE:"INVITE",MESSAGE:"MESSAGE",NOTIFY:"NOTIFY",OPTIONS:"OPTIONS",REGISTER:"REGISTER",REFER:"REFER",UPDATE:"UPDATE",SUBSCRIBE:"SUBSCRIBE",REASON_PHRASE:{100:"Trying",180:"Ringing",181:"Call Is Being Forwarded",182:"Queued",183:"Session Progress",199:"Early Dialog Terminated",200:"OK",202:"Accepted",204:"No Notification",300:"Multiple Choices",301:"Moved Permanently",302:"Moved Temporarily",305:"Use Proxy",380:"Alternative Service",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",410:"Gone",412:"Conditional Request Failed",413:"Request Entity Too Large",414:"Request-URI Too Long",415:"Unsupported Media Type",416:"Unsupported URI Scheme",417:"Unknown Resource-Priority",420:"Bad Extension",421:"Extension Required",422:"Session Interval Too Small",423:"Interval Too Brief",424:"Bad Location Information",428:"Use Identity Header",429:"Provide Referrer Identity",430:"Flow Failed",433:"Anonymity Disallowed",436:"Bad Identity-Info",437:"Unsupported Certificate",438:"Invalid Identity Header",439:"First Hop Lacks Outbound Support",440:"Max-Breadth Exceeded",469:"Bad Info Package",470:"Consent Needed",478:"Unresolvable Destination",480:"Temporarily Unavailable",481:"Call/Transaction Does Not Exist",482:"Loop Detected",483:"Too Many Hops",484:"Address Incomplete",485:"Ambiguous",486:"Busy Here",487:"Request Terminated",488:"Not Acceptable Here",489:"Bad Event",491:"Request Pending",493:"Undecipherable",494:"Security Agreement Required",500:"JsSIP Internal Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Server Time-out",505:"Version Not Supported",513:"Message Too Large",580:"Precondition Failure",600:"Busy Everywhere",603:"Decline",604:"Does Not Exist Anywhere",606:"Not Acceptable"},ALLOWED_METHODS:"INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO",ACCEPTED_BODY_TYPES:"application/sdp, application/dtmf-relay",MAX_FORWARDS:69,SESSION_EXPIRES:90,MIN_SESSION_EXPIRES:60};t.exports=i},{"../package.json":34}],36:[function(e,t,n){function r(e,t,n,r){var a;return this.uac_pending_reply=!1,this.uas_pending_reply=!1,t.hasHeader("contact")?(r=t instanceof s.IncomingResponse?t.status_code<200?i.STATUS_EARLY:i.STATUS_CONFIRMED:r||i.STATUS_CONFIRMED,a=t.parseHeader("contact"),"UAS"===n?(this.id={call_id:t.call_id,local_tag:t.to_tag,remote_tag:t.from_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this.state=r,this.remote_seqnum=t.cseq,this.local_uri=t.parseHeader("to").uri,this.remote_uri=t.parseHeader("from").uri,this.remote_target=a.uri,this.route_set=t.getHeaders("record-route")):"UAC"===n&&(this.id={call_id:t.call_id,local_tag:t.from_tag,remote_tag:t.to_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag; +}},this.state=r,this.local_seqnum=t.cseq,this.local_uri=t.parseHeader("from").uri,this.remote_uri=t.parseHeader("to").uri,this.remote_target=a.uri,this.route_set=t.getHeaders("record-route").reverse()),this.owner=e,e.ua.dialogs[this.id.toString()]=this,void o("new "+n+" dialog created with status "+(this.state===i.STATUS_EARLY?"EARLY":"CONFIRMED"))):{error:"unable to create a Dialog without Contact header field"}}t.exports=r;var i={STATUS_EARLY:1,STATUS_CONFIRMED:2};r.C=i;var o=e("debug")("PlivoSIP:Dialog"),s=e("./SIPMessage"),a=e("./Constants"),l=e("./Transactions"),u=e("./Dialog/RequestSender");r.prototype={update:function(e,t){this.state=i.STATUS_CONFIRMED,o("dialog "+this.id.toString()+" changed to CONFIRMED state"),"UAC"===t&&(this.route_set=e.getHeaders("record-route").reverse())},terminate:function(){o("dialog "+this.id.toString()+" deleted"),delete this.owner.ua.dialogs[this.id.toString()]},createRequest:function(e,t,n){var r,i;return t=t&&t.slice()||[],this.local_seqnum||(this.local_seqnum=Math.floor(1e4*Math.random())),r=e===a.CANCEL||e===a.ACK?this.local_seqnum:this.local_seqnum+=1,i=new s.OutgoingRequest(e,this.remote_target,this.owner.ua,{cseq:r,call_id:this.id.call_id,from_uri:this.local_uri,from_tag:this.id.local_tag,to_uri:this.remote_uri,to_tag:this.id.remote_tag,route_set:this.route_set},t,n),i.dialog=this,i},checkInDialogRequest:function(e){var t=this;if(this.remote_seqnum){if(e.cseqthis.remote_seqnum&&(this.remote_seqnum=e.cseq)}else this.remote_seqnum=e.cseq;if(e.method===a.INVITE||e.method===a.UPDATE&&e.body){if(this.uac_pending_reply===!0)e.reply(491);else{if(this.uas_pending_reply===!0){var n=(10*Math.random()|0)+1;return e.reply(500,null,["Retry-After:"+n]),!1}this.uas_pending_reply=!0,e.server_transaction.on("stateChanged",function r(){this.state!==l.C.STATUS_ACCEPTED&&this.state!==l.C.STATUS_COMPLETED&&this.state!==l.C.STATUS_TERMINATED||(e.server_transaction.removeListener("stateChanged",r),t.uas_pending_reply=!1)})}e.hasHeader("contact")&&e.server_transaction.on("stateChanged",function(){this.state===l.C.STATUS_ACCEPTED&&(t.remote_target=e.parseHeader("contact").uri)})}else e.method===a.NOTIFY&&e.hasHeader("contact")&&e.server_transaction.on("stateChanged",function(){this.state===l.C.STATUS_COMPLETED&&(t.remote_target=e.parseHeader("contact").uri)});return!0},sendRequest:function(e,t,n){n=n||{};var r=n.extraHeaders&&n.extraHeaders.slice()||[],i=n.body||null,o=this.createRequest(t,r,i),s=new u(this,e,o);return s.send(),o},receiveRequest:function(e){this.checkInDialogRequest(e)&&this.owner.receiveRequest(e)}}},{"./Constants":35,"./Dialog/RequestSender":37,"./SIPMessage":52,"./Transactions":55,debug:12}],37:[function(e,t,n){function r(e,t,n){this.dialog=e,this.applicant=t,this.request=n,this.reattempt=!1,this.reattemptTimer=null}t.exports=r;var i=e("../Constants"),o=e("../Transactions"),s=e("../RTCSession"),a=e("../RequestSender");r.prototype={send:function(){var e=this,t=new a(this,this.dialog.owner.ua);t.send(),(this.request.method===i.INVITE||this.request.method===i.UPDATE&&this.request.body)&&t.clientTransaction.state!==o.C.STATUS_TERMINATED&&(this.dialog.uac_pending_reply=!0,t.clientTransaction.on("stateChanged",function n(){this.state!==o.C.STATUS_ACCEPTED&&this.state!==o.C.STATUS_COMPLETED&&this.state!==o.C.STATUS_TERMINATED||(t.clientTransaction.removeListener("stateChanged",n),e.dialog.uac_pending_reply=!1)}))},onRequestTimeout:function(){this.applicant.onRequestTimeout()},onTransportError:function(){this.applicant.onTransportError()},receiveResponse:function(e){var t=this;408===e.status_code||481===e.status_code?this.applicant.onDialogError(e):e.method===i.INVITE&&491===e.status_code?this.reattempt?this.applicant.receiveResponse(e):(this.request.cseq.value=this.dialog.local_seqnum+=1,this.reattemptTimer=setTimeout(function(){t.applicant.owner.status!==s.C.STATUS_TERMINATED&&(t.reattempt=!0,t.request_sender.send())},1e3)):this.applicant.receiveResponse(e)}}},{"../Constants":35,"../RTCSession":45,"../RequestSender":51,"../Transactions":55}],38:[function(e,t,n){function r(e){this.credentials=e,this.cnonce=null,this.nc=0,this.ncHex="00000000",this.algorithm=null,this.realm=null,this.nonce=null,this.opaque=null,this.stale=null,this.qop=null,this.method=null,this.uri=null,this.ha1=null,this.response=null}t.exports=r;var i=e("debug")("PlivoSIP:DigestAuthentication"),o=e("debug")("PlivoSIP:ERROR:DigestAuthentication");o.log=console.warn.bind(console);var s=e("./Utils");r.prototype.get=function(e){switch(e){case"realm":return this.realm;case"ha1":return this.ha1;default:return void o('get() | cannot get "%s" parameter',e)}},r.prototype.authenticate=function(e,t){var n,r;if(this.algorithm=t.algorithm,this.realm=t.realm,this.nonce=t.nonce,this.opaque=t.opaque,this.stale=t.stale,this.algorithm){if("MD5"!==this.algorithm)return o('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this.algorithm="MD5";if(!this.nonce)return o("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this.realm)return o("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this.credentials.password){if(!this.credentials.ha1)return o("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this.credentials.realm!==this.realm)return o('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this.credentials.realm,this.realm),!1}if(t.qop)if(t.qop.indexOf("auth")>-1)this.qop="auth";else{if(!(t.qop.indexOf("auth-int")>-1))return o('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;this.qop="auth-int"}else this.qop=null;return this.method=e.method,this.uri=e.ruri,this.cnonce=s.createRandomToken(12),this.nc+=1,r=Number(this.nc).toString(16),this.ncHex="00000000".substr(0,8-r.length)+r,4294967296===this.nc&&(this.nc=1,this.ncHex="00000001"),this.credentials.password?this.ha1=s.calculateMD5(this.credentials.username+":"+this.realm+":"+this.credentials.password):this.ha1=this.credentials.ha1,"auth"===this.qop?(n=s.calculateMD5(this.method+":"+this.uri),this.response=s.calculateMD5(this.ha1+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth:"+n)):"auth-int"===this.qop?(n=s.calculateMD5(this.method+":"+this.uri+":"+s.calculateMD5(this.body?this.body:"")),this.response=s.calculateMD5(this.ha1+":"+this.nonce+":"+this.ncHex+":"+this.cnonce+":auth-int:"+n)):null===this.qop&&(n=s.calculateMD5(this.method+":"+this.uri),this.response=s.calculateMD5(this.ha1+":"+this.nonce+":"+n)),i("authenticate() | response generated"),!0},r.prototype.toString=function(){var e=[];if(!this.response)throw new Error("response field does not exist, cannot generate Authorization header");return e.push("algorithm="+this.algorithm),e.push('username="'+this.credentials.username+'"'),e.push('realm="'+this.realm+'"'),e.push('nonce="'+this.nonce+'"'),e.push('uri="'+this.uri+'"'),e.push('response="'+this.response+'"'),this.opaque&&e.push('opaque="'+this.opaque+'"'),this.qop&&(e.push("qop="+this.qop),e.push('cnonce="'+this.cnonce+'"'),e.push("nc="+this.ncHex)),"Digest "+e.join(", ")}},{"./Utils":59,debug:12}],39:[function(e,t,n){var r={ConfigurationError:function(){var e=function(e,t){this.code=1,this.name="CONFIGURATION_ERROR",this.parameter=e,this.value=t,this.message=this.value?"Invalid value "+JSON.stringify(this.value)+' for parameter "'+this.parameter+'"':"Missing parameter: "+this.parameter};return e.prototype=new Error,e}(),InvalidStateError:function(){var e=function(e){this.code=2,this.name="INVALID_STATE_ERROR",this.status=e,this.message="Invalid status: "+e};return e.prototype=new Error,e}(),NotSupportedError:function(){var e=function(e){this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=e};return e.prototype=new Error,e}(),NotReadyError:function(){var e=function(e){this.code=4,this.name="NOT_READY_ERROR",this.message=e};return e.prototype=new Error,e}()};t.exports=r},{}],40:[function(e,t,n){t.exports=function(){function t(e){return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g,escape)+'"'}var n={parse:function(n,r){function i(e){yr<_r||(yr>_r&&(_r=yr,Sr=[]),Sr.push(e))}function o(){var e;return"\r\n"===n.substr(yr,2)?(e="\r\n",yr+=2):(e=null,0===br&&i('"\\r\\n"')),e}function s(){var e;return/^[0-9]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[0-9]")),e}function a(){var e;return/^[a-zA-Z]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[a-zA-Z]")),e}function l(){var e;return/^[0-9a-fA-F]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[0-9a-fA-F]")),e}function u(){var e;return e=f(),null===e&&(e=h()),e}function c(){var e;return/^[\0-\xFF]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[\\0-\\xFF]")),e}function d(){var e;return/^["]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i('["]')),e}function f(){var e;return 32===n.charCodeAt(yr)?(e=" ",yr++):(e=null,0===br&&i('" "')),e}function h(){var e;return 9===n.charCodeAt(yr)?(e="\t",yr++):(e=null,0===br&&i('"\\t"')),e}function p(){var e;return/^[a-zA-Z0-9]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[a-zA-Z0-9]")),e}function v(){var e;return 59===n.charCodeAt(yr)?(e=";",yr++):(e=null,0===br&&i('";"')),null===e&&(47===n.charCodeAt(yr)?(e="/",yr++):(e=null,0===br&&i('"/"')),null===e&&(63===n.charCodeAt(yr)?(e="?",yr++):(e=null,0===br&&i('"?"')),null===e&&(58===n.charCodeAt(yr)?(e=":",yr++):(e=null,0===br&&i('":"')),null===e&&(64===n.charCodeAt(yr)?(e="@",yr++):(e=null,0===br&&i('"@"')),null===e&&(38===n.charCodeAt(yr)?(e="&",yr++):(e=null,0===br&&i('"&"')),null===e&&(61===n.charCodeAt(yr)?(e="=",yr++):(e=null,0===br&&i('"="')),null===e&&(43===n.charCodeAt(yr)?(e="+",yr++):(e=null,0===br&&i('"+"')),null===e&&(36===n.charCodeAt(yr)?(e="$",yr++):(e=null,0===br&&i('"$"')),null===e&&(44===n.charCodeAt(yr)?(e=",",yr++):(e=null,0===br&&i('","'))))))))))),e}function g(){var e;return e=p(),null===e&&(e=m()),e}function m(){var e;return 45===n.charCodeAt(yr)?(e="-",yr++):(e=null,0===br&&i('"-"')),null===e&&(95===n.charCodeAt(yr)?(e="_",yr++):(e=null,0===br&&i('"_"')),null===e&&(46===n.charCodeAt(yr)?(e=".",yr++):(e=null,0===br&&i('"."')),null===e&&(33===n.charCodeAt(yr)?(e="!",yr++):(e=null,0===br&&i('"!"')),null===e&&(126===n.charCodeAt(yr)?(e="~",yr++):(e=null,0===br&&i('"~"')),null===e&&(42===n.charCodeAt(yr)?(e="*",yr++):(e=null,0===br&&i('"*"')),null===e&&(39===n.charCodeAt(yr)?(e="'",yr++):(e=null,0===br&&i('"\'"')),null===e&&(40===n.charCodeAt(yr)?(e="(",yr++):(e=null,0===br&&i('"("')),null===e&&(41===n.charCodeAt(yr)?(e=")",yr++):(e=null,0===br&&i('")"')))))))))),e}function y(){var e,t,r,o,s;return o=yr,s=yr,37===n.charCodeAt(yr)?(e="%",yr++):(e=null,0===br&&i('"%"')),null!==e?(t=l(),null!==t?(r=l(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e,t){return t.join("")}(o,e)),null===e&&(yr=o),e}function b(){var e,t,n,r,i,s;for(r=yr,i=yr,s=yr,e=[],t=u();null!==t;)e.push(t),t=u();if(null!==e?(t=o(),null!==t?e=[e,t]:(e=null,yr=s)):(e=null,yr=s),e=null!==e?e:"",null!==e){if(n=u(),null!==n)for(t=[];null!==n;)t.push(n),n=u();else t=null;null!==t?e=[e,t]:(e=null,yr=i)}else e=null,yr=i;return null!==e&&(e=function(e){return" "}(r)),null===e&&(yr=r),e}function _(){var e;return e=b(),e=null!==e?e:""}function S(){var e,t,r,o,s;for(o=yr,s=yr,e=[],t=f(),null===t&&(t=h());null!==t;)e.push(t),t=f(),null===t&&(t=h());return null!==e?(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=_(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return":"}(o)),null===e&&(yr=o),e}function T(){var e,t,r,i,o,s,a;if(o=yr,s=yr,t=C(),null!==t)for(e=[];null!==t;)e.push(t),t=C();else e=null;if(null!==e){for(t=[],a=yr,r=[],i=b();null!==i;)r.push(i),i=b();for(null!==r?(i=C(),null!==i?r=[r,i]:(r=null,yr=a)):(r=null,yr=a);null!==r;){for(t.push(r),a=yr,r=[],i=b();null!==i;)r.push(i),i=b();null!==r?(i=C(),null!==i?r=[r,i]:(r=null,yr=a)):(r=null,yr=a)}null!==t?e=[e,t]:(e=null,yr=s)}else e=null,yr=s;return null!==e&&(e=function(e){return n.substring(yr,e)}(o)),null===e&&(yr=o),e}function C(){var e;return/^[!-~]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[!-~]")),null===e&&(e=w()),e}function w(){var e;return/^[\x80-\uFFFF]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[\\x80-\\uFFFF]")),e}function E(){var e;return/^[\x80-\xBF]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[\\x80-\\xBF]")),e}function k(){var e;return e=s(),null===e&&(/^[a-f]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[a-f]"))),e}function R(){var e,t,r;if(r=yr,t=p(),null===t&&(45===n.charCodeAt(yr)?(t="-",yr++):(t=null,0===br&&i('"-"')),null===t&&(46===n.charCodeAt(yr)?(t=".",yr++):(t=null,0===br&&i('"."')),null===t&&(33===n.charCodeAt(yr)?(t="!",yr++):(t=null,0===br&&i('"!"')),null===t&&(37===n.charCodeAt(yr)?(t="%",yr++):(t=null,0===br&&i('"%"')),null===t&&(42===n.charCodeAt(yr)?(t="*",yr++):(t=null,0===br&&i('"*"')),null===t&&(95===n.charCodeAt(yr)?(t="_",yr++):(t=null,0===br&&i('"_"')),null===t&&(43===n.charCodeAt(yr)?(t="+",yr++):(t=null,0===br&&i('"+"')),null===t&&(96===n.charCodeAt(yr)?(t="`",yr++):(t=null,0===br&&i('"`"')),null===t&&(39===n.charCodeAt(yr)?(t="'",yr++):(t=null,0===br&&i('"\'"')),null===t&&(126===n.charCodeAt(yr)?(t="~",yr++):(t=null,0===br&&i('"~"')))))))))))),null!==t)for(e=[];null!==t;)e.push(t),t=p(),null===t&&(45===n.charCodeAt(yr)?(t="-",yr++):(t=null,0===br&&i('"-"')),null===t&&(46===n.charCodeAt(yr)?(t=".",yr++):(t=null,0===br&&i('"."')),null===t&&(33===n.charCodeAt(yr)?(t="!",yr++):(t=null,0===br&&i('"!"')),null===t&&(37===n.charCodeAt(yr)?(t="%",yr++):(t=null,0===br&&i('"%"')),null===t&&(42===n.charCodeAt(yr)?(t="*",yr++):(t=null,0===br&&i('"*"')),null===t&&(95===n.charCodeAt(yr)?(t="_",yr++):(t=null,0===br&&i('"_"')),null===t&&(43===n.charCodeAt(yr)?(t="+",yr++):(t=null,0===br&&i('"+"')),null===t&&(96===n.charCodeAt(yr)?(t="`",yr++):(t=null,0===br&&i('"`"')),null===t&&(39===n.charCodeAt(yr)?(t="'",yr++):(t=null,0===br&&i('"\'"')),null===t&&(126===n.charCodeAt(yr)?(t="~",yr++):(t=null,0===br&&i('"~"'))))))))))));else e=null;return null!==e&&(e=function(e){return n.substring(yr,e)}(r)),null===e&&(yr=r),e}function I(){var e,t,r;if(r=yr,t=p(),null===t&&(45===n.charCodeAt(yr)?(t="-",yr++):(t=null,0===br&&i('"-"')),null===t&&(33===n.charCodeAt(yr)?(t="!",yr++):(t=null,0===br&&i('"!"')),null===t&&(37===n.charCodeAt(yr)?(t="%",yr++):(t=null,0===br&&i('"%"')),null===t&&(42===n.charCodeAt(yr)?(t="*",yr++):(t=null,0===br&&i('"*"')),null===t&&(95===n.charCodeAt(yr)?(t="_",yr++):(t=null,0===br&&i('"_"')),null===t&&(43===n.charCodeAt(yr)?(t="+",yr++):(t=null,0===br&&i('"+"')),null===t&&(96===n.charCodeAt(yr)?(t="`",yr++):(t=null,0===br&&i('"`"')),null===t&&(39===n.charCodeAt(yr)?(t="'",yr++):(t=null,0===br&&i('"\'"')),null===t&&(126===n.charCodeAt(yr)?(t="~",yr++):(t=null,0===br&&i('"~"'))))))))))),null!==t)for(e=[];null!==t;)e.push(t),t=p(),null===t&&(45===n.charCodeAt(yr)?(t="-",yr++):(t=null,0===br&&i('"-"')),null===t&&(33===n.charCodeAt(yr)?(t="!",yr++):(t=null,0===br&&i('"!"')),null===t&&(37===n.charCodeAt(yr)?(t="%",yr++):(t=null,0===br&&i('"%"')),null===t&&(42===n.charCodeAt(yr)?(t="*",yr++):(t=null,0===br&&i('"*"')),null===t&&(95===n.charCodeAt(yr)?(t="_",yr++):(t=null,0===br&&i('"_"')),null===t&&(43===n.charCodeAt(yr)?(t="+",yr++):(t=null,0===br&&i('"+"')),null===t&&(96===n.charCodeAt(yr)?(t="`",yr++):(t=null,0===br&&i('"`"')),null===t&&(39===n.charCodeAt(yr)?(t="'",yr++):(t=null,0===br&&i('"\'"')),null===t&&(126===n.charCodeAt(yr)?(t="~",yr++):(t=null,0===br&&i('"~"')))))))))));else e=null;return null!==e&&(e=function(e){return n.substring(yr,e)}(r)),null===e&&(yr=r),e}function P(){var e;return 40===n.charCodeAt(yr)?(e="(",yr++):(e=null,0===br&&i('"("')),null===e&&(41===n.charCodeAt(yr)?(e=")",yr++):(e=null,0===br&&i('")"')),null===e&&(60===n.charCodeAt(yr)?(e="<",yr++):(e=null,0===br&&i('"<"')),null===e&&(62===n.charCodeAt(yr)?(e=">",yr++):(e=null,0===br&&i('">"')),null===e&&(64===n.charCodeAt(yr)?(e="@",yr++):(e=null,0===br&&i('"@"')),null===e&&(44===n.charCodeAt(yr)?(e=",",yr++):(e=null,0===br&&i('","')),null===e&&(59===n.charCodeAt(yr)?(e=";",yr++):(e=null,0===br&&i('";"')),null===e&&(58===n.charCodeAt(yr)?(e=":",yr++):(e=null,0===br&&i('":"')),null===e&&(92===n.charCodeAt(yr)?(e="\\",yr++):(e=null,0===br&&i('"\\\\"')),null===e&&(e=d(),null===e&&(47===n.charCodeAt(yr)?(e="/",yr++):(e=null,0===br&&i('"/"')),null===e&&(91===n.charCodeAt(yr)?(e="[",yr++):(e=null,0===br&&i('"["')),null===e&&(93===n.charCodeAt(yr)?(e="]",yr++):(e=null,0===br&&i('"]"')),null===e&&(63===n.charCodeAt(yr)?(e="?",yr++):(e=null,0===br&&i('"?"')),null===e&&(61===n.charCodeAt(yr)?(e="=",yr++):(e=null,0===br&&i('"="')),null===e&&(123===n.charCodeAt(yr)?(e="{",yr++):(e=null,0===br&&i('"{"')),null===e&&(125===n.charCodeAt(yr)?(e="}",yr++):(e=null,0===br&&i('"}"')),null===e&&(e=f(),null===e&&(e=h())))))))))))))))))),e}function A(){var e,t,r;if(r=yr,t=p(),null===t&&(45===n.charCodeAt(yr)?(t="-",yr++):(t=null,0===br&&i('"-"')),null===t&&(46===n.charCodeAt(yr)?(t=".",yr++):(t=null,0===br&&i('"."')),null===t&&(33===n.charCodeAt(yr)?(t="!",yr++):(t=null,0===br&&i('"!"')),null===t&&(37===n.charCodeAt(yr)?(t="%",yr++):(t=null,0===br&&i('"%"')),null===t&&(42===n.charCodeAt(yr)?(t="*",yr++):(t=null,0===br&&i('"*"')),null===t&&(95===n.charCodeAt(yr)?(t="_",yr++):(t=null,0===br&&i('"_"')),null===t&&(43===n.charCodeAt(yr)?(t="+",yr++):(t=null,0===br&&i('"+"')),null===t&&(96===n.charCodeAt(yr)?(t="`",yr++):(t=null,0===br&&i('"`"')),null===t&&(39===n.charCodeAt(yr)?(t="'",yr++):(t=null,0===br&&i('"\'"')),null===t&&(126===n.charCodeAt(yr)?(t="~",yr++):(t=null,0===br&&i('"~"')),null===t&&(40===n.charCodeAt(yr)?(t="(",yr++):(t=null,0===br&&i('"("')),null===t&&(41===n.charCodeAt(yr)?(t=")",yr++):(t=null,0===br&&i('")"')),null===t&&(60===n.charCodeAt(yr)?(t="<",yr++):(t=null,0===br&&i('"<"')),null===t&&(62===n.charCodeAt(yr)?(t=">",yr++):(t=null,0===br&&i('">"')),null===t&&(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null===t&&(92===n.charCodeAt(yr)?(t="\\",yr++):(t=null,0===br&&i('"\\\\"')),null===t&&(t=d(),null===t&&(47===n.charCodeAt(yr)?(t="/",yr++):(t=null,0===br&&i('"/"')),null===t&&(91===n.charCodeAt(yr)?(t="[",yr++):(t=null,0===br&&i('"["')),null===t&&(93===n.charCodeAt(yr)?(t="]",yr++):(t=null,0===br&&i('"]"')),null===t&&(63===n.charCodeAt(yr)?(t="?",yr++):(t=null,0===br&&i('"?"')),null===t&&(123===n.charCodeAt(yr)?(t="{",yr++):(t=null,0===br&&i('"{"')),null===t&&(125===n.charCodeAt(yr)?(t="}",yr++):(t=null,0===br&&i('"}"'))))))))))))))))))))))))),null!==t)for(e=[];null!==t;)e.push(t),t=p(),null===t&&(45===n.charCodeAt(yr)?(t="-",yr++):(t=null,0===br&&i('"-"')),null===t&&(46===n.charCodeAt(yr)?(t=".",yr++):(t=null,0===br&&i('"."')),null===t&&(33===n.charCodeAt(yr)?(t="!",yr++):(t=null,0===br&&i('"!"')),null===t&&(37===n.charCodeAt(yr)?(t="%",yr++):(t=null,0===br&&i('"%"')),null===t&&(42===n.charCodeAt(yr)?(t="*",yr++):(t=null,0===br&&i('"*"')),null===t&&(95===n.charCodeAt(yr)?(t="_",yr++):(t=null,0===br&&i('"_"')),null===t&&(43===n.charCodeAt(yr)?(t="+",yr++):(t=null,0===br&&i('"+"')),null===t&&(96===n.charCodeAt(yr)?(t="`",yr++):(t=null,0===br&&i('"`"')),null===t&&(39===n.charCodeAt(yr)?(t="'",yr++):(t=null,0===br&&i('"\'"')),null===t&&(126===n.charCodeAt(yr)?(t="~",yr++):(t=null,0===br&&i('"~"')),null===t&&(40===n.charCodeAt(yr)?(t="(",yr++):(t=null,0===br&&i('"("')),null===t&&(41===n.charCodeAt(yr)?(t=")",yr++):(t=null,0===br&&i('")"')),null===t&&(60===n.charCodeAt(yr)?(t="<",yr++):(t=null,0===br&&i('"<"')),null===t&&(62===n.charCodeAt(yr)?(t=">",yr++):(t=null,0===br&&i('">"')),null===t&&(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null===t&&(92===n.charCodeAt(yr)?(t="\\",yr++):(t=null,0===br&&i('"\\\\"')),null===t&&(t=d(),null===t&&(47===n.charCodeAt(yr)?(t="/",yr++):(t=null,0===br&&i('"/"')),null===t&&(91===n.charCodeAt(yr)?(t="[",yr++):(t=null,0===br&&i('"["')),null===t&&(93===n.charCodeAt(yr)?(t="]",yr++):(t=null,0===br&&i('"]"')),null===t&&(63===n.charCodeAt(yr)?(t="?",yr++):(t=null,0===br&&i('"?"')),null===t&&(123===n.charCodeAt(yr)?(t="{",yr++):(t=null,0===br&&i('"{"')),null===t&&(125===n.charCodeAt(yr)?(t="}",yr++):(t=null,0===br&&i('"}"')))))))))))))))))))))))));else e=null;return null!==e&&(e=function(e){return n.substring(yr,e)}(r)),null===e&&(yr=r),e}function O(){var e,t,r,o,s;return o=yr,s=yr,e=_(),null!==e?(42===n.charCodeAt(yr)?(t="*",yr++):(t=null,0===br&&i('"*"')),null!==t?(r=_(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return"*"}(o)),null===e&&(yr=o),e}function M(){var e,t,r,o,s;return o=yr,s=yr,e=_(),null!==e?(47===n.charCodeAt(yr)?(t="/",yr++):(t=null,0===br&&i('"/"')),null!==t?(r=_(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return"/"}(o)),null===e&&(yr=o),e}function D(){var e,t,r,o,s;return o=yr,s=yr,e=_(),null!==e?(61===n.charCodeAt(yr)?(t="=",yr++):(t=null,0===br&&i('"="')),null!==t?(r=_(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return"="}(o)),null===e&&(yr=o),e}function x(){var e,t,r,o,s;return o=yr,s=yr,e=_(),null!==e?(40===n.charCodeAt(yr)?(t="(",yr++):(t=null,0===br&&i('"("')),null!==t?(r=_(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return"("}(o)),null===e&&(yr=o),e}function N(){var e,t,r,o,s;return o=yr,s=yr,e=_(),null!==e?(41===n.charCodeAt(yr)?(t=")",yr++):(t=null,0===br&&i('")"')),null!==t?(r=_(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return")"}(o)),null===e&&(yr=o),e}function F(){var e,t,r,o;return r=yr,o=yr,62===n.charCodeAt(yr)?(e=">",yr++):(e=null,0===br&&i('">"')),null!==e?(t=_(),null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),null!==e&&(e=function(e){return">"}(r)),null===e&&(yr=r),e}function U(){var e,t,r,o;return r=yr,o=yr,e=_(),null!==e?(60===n.charCodeAt(yr)?(t="<",yr++):(t=null,0===br&&i('"<"')),null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),null!==e&&(e=function(e){return"<"}(r)),null===e&&(yr=r),e}function j(){var e,t,r,o,s;return o=yr,s=yr,e=_(),null!==e?(44===n.charCodeAt(yr)?(t=",",yr++):(t=null,0===br&&i('","')),null!==t?(r=_(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return","}(o)),null===e&&(yr=o),e}function L(){var e,t,r,o,s;return o=yr,s=yr,e=_(),null!==e?(59===n.charCodeAt(yr)?(t=";",yr++):(t=null,0===br&&i('";"')),null!==t?(r=_(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return";"}(o)),null===e&&(yr=o),e}function H(){var e,t,r,o,s;return o=yr,s=yr,e=_(),null!==e?(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=_(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return":"}(o)),null===e&&(yr=o),e}function B(){var e,t,n,r;return n=yr,r=yr,e=_(),null!==e?(t=d(),null!==t?e=[e,t]:(e=null,yr=r)):(e=null,yr=r),null!==e&&(e=function(e){return'"'}(n)),null===e&&(yr=n),e}function q(){var e,t,n,r;return n=yr,r=yr,e=d(),null!==e?(t=_(),null!==t?e=[e,t]:(e=null,yr=r)):(e=null,yr=r),null!==e&&(e=function(e){return'"'}(n)),null===e&&(yr=n),e}function G(){var e,t,n,r;if(r=yr,e=x(),null!==e){for(t=[],n=W(),null===n&&(n=J(),null===n&&(n=G()));null!==n;)t.push(n),n=W(),null===n&&(n=J(),null===n&&(n=G()));null!==t?(n=N(),null!==n?e=[e,t,n]:(e=null,yr=r)):(e=null,yr=r)}else e=null,yr=r;return e}function W(){var e;return/^[!-']/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[!-']")),null===e&&(/^[*-[]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[*-[]")),null===e&&(/^[\]-~]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[\\]-~]")),null===e&&(e=w(),null===e&&(e=b())))),e}function V(){var e,t,r,i,o,s;if(o=yr,s=yr,e=_(),null!==e)if(t=d(),null!==t){for(r=[],i=K(),null===i&&(i=J());null!==i;)r.push(i),i=K(),null===i&&(i=J());null!==r?(i=d(),null!==i?e=[e,t,r,i]:(e=null,yr=s)):(e=null,yr=s)}else e=null,yr=s;else e=null,yr=s;return null!==e&&(e=function(e){return n.substring(yr,e)}(o)),null===e&&(yr=o),e}function z(){var e,t,r,i,o,s;if(o=yr,s=yr,e=_(),null!==e)if(t=d(),null!==t){for(r=[],i=K(),null===i&&(i=J());null!==i;)r.push(i),i=K(),null===i&&(i=J());null!==r?(i=d(),null!==i?e=[e,t,r,i]:(e=null,yr=s)):(e=null,yr=s)}else e=null,yr=s;else e=null,yr=s;return null!==e&&(e=function(e){return n.substring(yr-1,e+1)}(o)),null===e&&(yr=o),e}function K(){var e;return e=b(),null===e&&(33===n.charCodeAt(yr)?(e="!",yr++):(e=null,0===br&&i('"!"')),null===e&&(/^[#-[]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[#-[]")),null===e&&(/^[\]-~]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[\\]-~]")),null===e&&(e=w())))),e}function J(){var e,t,r;return r=yr,92===n.charCodeAt(yr)?(e="\\",yr++):(e=null,0===br&&i('"\\\\"')),null!==e?(/^[\0-\t]/.test(n.charAt(yr))?(t=n.charAt(yr),yr++):(t=null,0===br&&i("[\\0-\\t]")),null===t&&(/^[\x0B-\f]/.test(n.charAt(yr))?(t=n.charAt(yr),yr++):(t=null,0===br&&i("[\\x0B-\\f]")),null===t&&(/^[\x0E-\x7f]/.test(n.charAt(yr))?(t=n.charAt(yr),yr++):(t=null,0===br&&i("[\\x0E-\x7f]")))),null!==t?e=[e,t]:(e=null,yr=r)):(e=null,yr=r),e}function Q(){var e,t,r,o,s,a;return s=yr,a=yr,e=$(),null!==e?(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=ee(),r=null!==r?r:"",null!==r?(o=ie(),null!==o?e=[e,t,r,o]:(e=null,yr=a)):(e=null,yr=a)):(e=null,yr=a)):(e=null,yr=a),null!==e&&(e=function(e){try{wr.uri=new Tr(wr.scheme,wr.user,wr.host,wr.port),delete wr.scheme,delete wr.user,delete wr.host,delete wr.host_type,delete wr.port}catch(t){wr=-1}}(s)),null===e&&(yr=s),e}function X(){var e,t,o,s,a,l,u,c;return u=yr,c=yr,e=$(),null!==e?(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(o=ee(),o=null!==o?o:"",null!==o?(s=ie(),null!==s?(a=ge(),null!==a?(l=Pe(),l=null!==l?l:"",null!==l?e=[e,t,o,s,a,l]:(e=null,yr=c)):(e=null,yr=c)):(e=null,yr=c)):(e=null,yr=c)):(e=null,yr=c)):(e=null,yr=c),null!==e&&(e=function(e){try{wr.uri=new Tr(wr.scheme,wr.user,wr.host,wr.port,wr.uri_params,wr.uri_headers),delete wr.scheme,delete wr.user,delete wr.host,delete wr.host_type,delete wr.port,delete wr.uri_params,"SIP_URI"===r&&(wr=wr.uri)}catch(t){wr=-1}}(u)),null===e&&(yr=u),e}function $(){var e;return e=Y(),null===e&&(e=Z()),e}function Y(){var e,t;return t=yr,"sips"===n.substr(yr,4).toLowerCase()?(e=n.substr(yr,4),yr+=4):(e=null,0===br&&i('"sips"')),null!==e&&(e=function(e,t){wr.scheme=t.toLowerCase()}(t,e)),null===e&&(yr=t),e}function Z(){var e,t;return t=yr,"sip"===n.substr(yr,3).toLowerCase()?(e=n.substr(yr,3),yr+=3):(e=null,0===br&&i('"sip"')),null!==e&&(e=function(e,t){wr.scheme=t.toLowerCase()}(t,e)),null===e&&(yr=t),e}function ee(){var e,t,r,o,s,a;return o=yr,s=yr,e=te(),null!==e?(a=yr,58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=re(),null!==r?t=[t,r]:(t=null,yr=a)):(t=null,yr=a),t=null!==t?t:"",null!==t?(64===n.charCodeAt(yr)?(r="@",yr++):(r=null,0===br&&i('"@"')),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){wr.user=decodeURIComponent(n.substring(yr-1,e))}(o)),null===e&&(yr=o),e}function te(){var e,t;if(t=g(),null===t&&(t=y(),null===t&&(t=ne())),null!==t)for(e=[];null!==t;)e.push(t),t=g(),null===t&&(t=y(),null===t&&(t=ne()));else e=null;return e}function ne(){var e;return 38===n.charCodeAt(yr)?(e="&",yr++):(e=null,0===br&&i('"&"')),null===e&&(61===n.charCodeAt(yr)?(e="=",yr++):(e=null,0===br&&i('"="')),null===e&&(43===n.charCodeAt(yr)?(e="+",yr++):(e=null,0===br&&i('"+"')),null===e&&(36===n.charCodeAt(yr)?(e="$",yr++):(e=null,0===br&&i('"$"')),null===e&&(44===n.charCodeAt(yr)?(e=",",yr++):(e=null,0===br&&i('","')),null===e&&(59===n.charCodeAt(yr)?(e=";",yr++):(e=null,0===br&&i('";"')),null===e&&(63===n.charCodeAt(yr)?(e="?",yr++):(e=null,0===br&&i('"?"')),null===e&&(47===n.charCodeAt(yr)?(e="/",yr++):(e=null,0===br&&i('"/"'))))))))),e}function re(){var e,t,r;for(r=yr,e=[],t=g(),null===t&&(t=y(),null===t&&(38===n.charCodeAt(yr)?(t="&",yr++):(t=null,0===br&&i('"&"')),null===t&&(61===n.charCodeAt(yr)?(t="=",yr++):(t=null,0===br&&i('"="')),null===t&&(43===n.charCodeAt(yr)?(t="+",yr++):(t=null,0===br&&i('"+"')),null===t&&(36===n.charCodeAt(yr)?(t="$",yr++):(t=null,0===br&&i('"$"')),null===t&&(44===n.charCodeAt(yr)?(t=",",yr++):(t=null,0===br&&i('","'))))))));null!==t;)e.push(t),t=g(),null===t&&(t=y(),null===t&&(38===n.charCodeAt(yr)?(t="&",yr++):(t=null,0===br&&i('"&"')),null===t&&(61===n.charCodeAt(yr)?(t="=",yr++):(t=null,0===br&&i('"="')),null===t&&(43===n.charCodeAt(yr)?(t="+",yr++):(t=null,0===br&&i('"+"')),null===t&&(36===n.charCodeAt(yr)?(t="$",yr++):(t=null,0===br&&i('"$"')),null===t&&(44===n.charCodeAt(yr)?(t=",",yr++):(t=null,0===br&&i('","'))))))));return null!==e&&(e=function(e){wr.password=n.substring(yr,e)}(r)),null===e&&(yr=r),e}function ie(){var e,t,r,o,s;return o=yr,e=oe(),null!==e?(s=yr,58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=ve(),null!==r?t=[t,r]:(t=null,yr=s)):(t=null,yr=s),t=null!==t?t:"",null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),e}function oe(){var e,t;return t=yr,e=se(),null===e&&(e=he(),null===e&&(e=ue())),null!==e&&(e=function(e){return wr.host=n.substring(yr,e).toLowerCase(),wr.host}(t)),null===e&&(yr=t),e}function se(){var e,t,r,o,s,a;for(o=yr,s=yr,e=[],a=yr,t=ae(),null!==t?(46===n.charCodeAt(yr)?(r=".",yr++):(r=null,0===br&&i('"."')),null!==r?t=[t,r]:(t=null,yr=a)):(t=null,yr=a);null!==t;)e.push(t),a=yr,t=ae(),null!==t?(46===n.charCodeAt(yr)?(r=".",yr++):(r=null,0===br&&i('"."')),null!==r?t=[t,r]:(t=null,yr=a)):(t=null,yr=a);return null!==e?(t=le(),null!==t?(46===n.charCodeAt(yr)?(r=".",yr++):(r=null,0===br&&i('"."')),r=null!==r?r:"",null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return wr.host_type="domain",n.substring(yr,e)}(o)),null===e&&(yr=o),e}function ae(){var e,t,r,o;if(o=yr,e=p(),null!==e){for(t=[],r=p(),null===r&&(45===n.charCodeAt(yr)?(r="-",yr++):(r=null,0===br&&i('"-"')),null===r&&(95===n.charCodeAt(yr)?(r="_",yr++):(r=null,0===br&&i('"_"'))));null!==r;)t.push(r),r=p(),null===r&&(45===n.charCodeAt(yr)?(r="-",yr++):(r=null,0===br&&i('"-"')),null===r&&(95===n.charCodeAt(yr)?(r="_",yr++):(r=null,0===br&&i('"_"'))));null!==t?e=[e,t]:(e=null,yr=o)}else e=null,yr=o;return e}function le(){var e,t,r,o;if(o=yr,e=a(),null!==e){for(t=[],r=p(),null===r&&(45===n.charCodeAt(yr)?(r="-",yr++):(r=null,0===br&&i('"-"')),null===r&&(95===n.charCodeAt(yr)?(r="_",yr++):(r=null,0===br&&i('"_"'))));null!==r;)t.push(r),r=p(),null===r&&(45===n.charCodeAt(yr)?(r="-",yr++):(r=null,0===br&&i('"-"')),null===r&&(95===n.charCodeAt(yr)?(r="_",yr++):(r=null,0===br&&i('"_"'))));null!==t?e=[e,t]:(e=null,yr=o)}else e=null,yr=o;return e}function ue(){var e,t,r,o,s;return o=yr,s=yr,91===n.charCodeAt(yr)?(e="[",yr++):(e=null,0===br&&i('"["')),null!==e?(t=ce(),null!==t?(93===n.charCodeAt(yr)?(r="]",yr++):(r=null,0===br&&i('"]"')),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){return wr.host_type="IPv6",n.substring(yr,e)}(o)),null===e&&(yr=o),e}function ce(){var e,t,r,o,s,a,l,u,c,d,f,h,p,v,g,m;return v=yr,g=yr,e=de(),null!==e?(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=de(),null!==r?(58===n.charCodeAt(yr)?(o=":",yr++):(o=null,0===br&&i('":"')),null!==o?(s=de(),null!==s?(58===n.charCodeAt(yr)?(a=":",yr++):(a=null,0===br&&i('":"')),null!==a?(l=de(),null!==l?(58===n.charCodeAt(yr)?(u=":",yr++):(u=null,0===br&&i('":"')),null!==u?(c=de(),null!==c?(58===n.charCodeAt(yr)?(d=":", +yr++):(d=null,0===br&&i('":"')),null!==d?(f=de(),null!==f?(58===n.charCodeAt(yr)?(h=":",yr++):(h=null,0===br&&i('":"')),null!==h?(p=fe(),null!==p?e=[e,t,r,o,s,a,l,u,c,d,f,h,p]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,"::"===n.substr(yr,2)?(e="::",yr+=2):(e=null,0===br&&i('"::"')),null!==e?(t=de(),null!==t?(58===n.charCodeAt(yr)?(r=":",yr++):(r=null,0===br&&i('":"')),null!==r?(o=de(),null!==o?(58===n.charCodeAt(yr)?(s=":",yr++):(s=null,0===br&&i('":"')),null!==s?(a=de(),null!==a?(58===n.charCodeAt(yr)?(l=":",yr++):(l=null,0===br&&i('":"')),null!==l?(u=de(),null!==u?(58===n.charCodeAt(yr)?(c=":",yr++):(c=null,0===br&&i('":"')),null!==c?(d=de(),null!==d?(58===n.charCodeAt(yr)?(f=":",yr++):(f=null,0===br&&i('":"')),null!==f?(h=fe(),null!==h?e=[e,t,r,o,s,a,l,u,c,d,f,h]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,"::"===n.substr(yr,2)?(e="::",yr+=2):(e=null,0===br&&i('"::"')),null!==e?(t=de(),null!==t?(58===n.charCodeAt(yr)?(r=":",yr++):(r=null,0===br&&i('":"')),null!==r?(o=de(),null!==o?(58===n.charCodeAt(yr)?(s=":",yr++):(s=null,0===br&&i('":"')),null!==s?(a=de(),null!==a?(58===n.charCodeAt(yr)?(l=":",yr++):(l=null,0===br&&i('":"')),null!==l?(u=de(),null!==u?(58===n.charCodeAt(yr)?(c=":",yr++):(c=null,0===br&&i('":"')),null!==c?(d=fe(),null!==d?e=[e,t,r,o,s,a,l,u,c,d]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,"::"===n.substr(yr,2)?(e="::",yr+=2):(e=null,0===br&&i('"::"')),null!==e?(t=de(),null!==t?(58===n.charCodeAt(yr)?(r=":",yr++):(r=null,0===br&&i('":"')),null!==r?(o=de(),null!==o?(58===n.charCodeAt(yr)?(s=":",yr++):(s=null,0===br&&i('":"')),null!==s?(a=de(),null!==a?(58===n.charCodeAt(yr)?(l=":",yr++):(l=null,0===br&&i('":"')),null!==l?(u=fe(),null!==u?e=[e,t,r,o,s,a,l,u]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,"::"===n.substr(yr,2)?(e="::",yr+=2):(e=null,0===br&&i('"::"')),null!==e?(t=de(),null!==t?(58===n.charCodeAt(yr)?(r=":",yr++):(r=null,0===br&&i('":"')),null!==r?(o=de(),null!==o?(58===n.charCodeAt(yr)?(s=":",yr++):(s=null,0===br&&i('":"')),null!==s?(a=fe(),null!==a?e=[e,t,r,o,s,a]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,"::"===n.substr(yr,2)?(e="::",yr+=2):(e=null,0===br&&i('"::"')),null!==e?(t=de(),null!==t?(58===n.charCodeAt(yr)?(r=":",yr++):(r=null,0===br&&i('":"')),null!==r?(o=fe(),null!==o?e=[e,t,r,o]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,"::"===n.substr(yr,2)?(e="::",yr+=2):(e=null,0===br&&i('"::"')),null!==e?(t=fe(),null!==t?e=[e,t]:(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,"::"===n.substr(yr,2)?(e="::",yr+=2):(e=null,0===br&&i('"::"')),null!==e?(t=de(),null!==t?e=[e,t]:(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,e=de(),null!==e?("::"===n.substr(yr,2)?(t="::",yr+=2):(t=null,0===br&&i('"::"')),null!==t?(r=de(),null!==r?(58===n.charCodeAt(yr)?(o=":",yr++):(o=null,0===br&&i('":"')),null!==o?(s=de(),null!==s?(58===n.charCodeAt(yr)?(a=":",yr++):(a=null,0===br&&i('":"')),null!==a?(l=de(),null!==l?(58===n.charCodeAt(yr)?(u=":",yr++):(u=null,0===br&&i('":"')),null!==u?(c=de(),null!==c?(58===n.charCodeAt(yr)?(d=":",yr++):(d=null,0===br&&i('":"')),null!==d?(f=fe(),null!==f?e=[e,t,r,o,s,a,l,u,c,d,f]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,e=de(),null!==e?(m=yr,58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=de(),null!==r?t=[t,r]:(t=null,yr=m)):(t=null,yr=m),t=null!==t?t:"",null!==t?("::"===n.substr(yr,2)?(r="::",yr+=2):(r=null,0===br&&i('"::"')),null!==r?(o=de(),null!==o?(58===n.charCodeAt(yr)?(s=":",yr++):(s=null,0===br&&i('":"')),null!==s?(a=de(),null!==a?(58===n.charCodeAt(yr)?(l=":",yr++):(l=null,0===br&&i('":"')),null!==l?(u=de(),null!==u?(58===n.charCodeAt(yr)?(c=":",yr++):(c=null,0===br&&i('":"')),null!==c?(d=fe(),null!==d?e=[e,t,r,o,s,a,l,u,c,d]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,e=de(),null!==e?(m=yr,58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=de(),null!==r?t=[t,r]:(t=null,yr=m)):(t=null,yr=m),t=null!==t?t:"",null!==t?(m=yr,58===n.charCodeAt(yr)?(r=":",yr++):(r=null,0===br&&i('":"')),null!==r?(o=de(),null!==o?r=[r,o]:(r=null,yr=m)):(r=null,yr=m),r=null!==r?r:"",null!==r?("::"===n.substr(yr,2)?(o="::",yr+=2):(o=null,0===br&&i('"::"')),null!==o?(s=de(),null!==s?(58===n.charCodeAt(yr)?(a=":",yr++):(a=null,0===br&&i('":"')),null!==a?(l=de(),null!==l?(58===n.charCodeAt(yr)?(u=":",yr++):(u=null,0===br&&i('":"')),null!==u?(c=fe(),null!==c?e=[e,t,r,o,s,a,l,u,c]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,e=de(),null!==e?(m=yr,58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=de(),null!==r?t=[t,r]:(t=null,yr=m)):(t=null,yr=m),t=null!==t?t:"",null!==t?(m=yr,58===n.charCodeAt(yr)?(r=":",yr++):(r=null,0===br&&i('":"')),null!==r?(o=de(),null!==o?r=[r,o]:(r=null,yr=m)):(r=null,yr=m),r=null!==r?r:"",null!==r?(m=yr,58===n.charCodeAt(yr)?(o=":",yr++):(o=null,0===br&&i('":"')),null!==o?(s=de(),null!==s?o=[o,s]:(o=null,yr=m)):(o=null,yr=m),o=null!==o?o:"",null!==o?("::"===n.substr(yr,2)?(s="::",yr+=2):(s=null,0===br&&i('"::"')),null!==s?(a=de(),null!==a?(58===n.charCodeAt(yr)?(l=":",yr++):(l=null,0===br&&i('":"')),null!==l?(u=fe(),null!==u?e=[e,t,r,o,s,a,l,u]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,e=de(),null!==e?(m=yr,58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=de(),null!==r?t=[t,r]:(t=null,yr=m)):(t=null,yr=m),t=null!==t?t:"",null!==t?(m=yr,58===n.charCodeAt(yr)?(r=":",yr++):(r=null,0===br&&i('":"')),null!==r?(o=de(),null!==o?r=[r,o]:(r=null,yr=m)):(r=null,yr=m),r=null!==r?r:"",null!==r?(m=yr,58===n.charCodeAt(yr)?(o=":",yr++):(o=null,0===br&&i('":"')),null!==o?(s=de(),null!==s?o=[o,s]:(o=null,yr=m)):(o=null,yr=m),o=null!==o?o:"",null!==o?(m=yr,58===n.charCodeAt(yr)?(s=":",yr++):(s=null,0===br&&i('":"')),null!==s?(a=de(),null!==a?s=[s,a]:(s=null,yr=m)):(s=null,yr=m),s=null!==s?s:"",null!==s?("::"===n.substr(yr,2)?(a="::",yr+=2):(a=null,0===br&&i('"::"')),null!==a?(l=fe(),null!==l?e=[e,t,r,o,s,a,l]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,e=de(),null!==e?(m=yr,58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=de(),null!==r?t=[t,r]:(t=null,yr=m)):(t=null,yr=m),t=null!==t?t:"",null!==t?(m=yr,58===n.charCodeAt(yr)?(r=":",yr++):(r=null,0===br&&i('":"')),null!==r?(o=de(),null!==o?r=[r,o]:(r=null,yr=m)):(r=null,yr=m),r=null!==r?r:"",null!==r?(m=yr,58===n.charCodeAt(yr)?(o=":",yr++):(o=null,0===br&&i('":"')),null!==o?(s=de(),null!==s?o=[o,s]:(o=null,yr=m)):(o=null,yr=m),o=null!==o?o:"",null!==o?(m=yr,58===n.charCodeAt(yr)?(s=":",yr++):(s=null,0===br&&i('":"')),null!==s?(a=de(),null!==a?s=[s,a]:(s=null,yr=m)):(s=null,yr=m),s=null!==s?s:"",null!==s?(m=yr,58===n.charCodeAt(yr)?(a=":",yr++):(a=null,0===br&&i('":"')),null!==a?(l=de(),null!==l?a=[a,l]:(a=null,yr=m)):(a=null,yr=m),a=null!==a?a:"",null!==a?("::"===n.substr(yr,2)?(l="::",yr+=2):(l=null,0===br&&i('"::"')),null!==l?(u=de(),null!==u?e=[e,t,r,o,s,a,l,u]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g),null===e&&(g=yr,e=de(),null!==e?(m=yr,58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=de(),null!==r?t=[t,r]:(t=null,yr=m)):(t=null,yr=m),t=null!==t?t:"",null!==t?(m=yr,58===n.charCodeAt(yr)?(r=":",yr++):(r=null,0===br&&i('":"')),null!==r?(o=de(),null!==o?r=[r,o]:(r=null,yr=m)):(r=null,yr=m),r=null!==r?r:"",null!==r?(m=yr,58===n.charCodeAt(yr)?(o=":",yr++):(o=null,0===br&&i('":"')),null!==o?(s=de(),null!==s?o=[o,s]:(o=null,yr=m)):(o=null,yr=m),o=null!==o?o:"",null!==o?(m=yr,58===n.charCodeAt(yr)?(s=":",yr++):(s=null,0===br&&i('":"')),null!==s?(a=de(),null!==a?s=[s,a]:(s=null,yr=m)):(s=null,yr=m),s=null!==s?s:"",null!==s?(m=yr,58===n.charCodeAt(yr)?(a=":",yr++):(a=null,0===br&&i('":"')),null!==a?(l=de(),null!==l?a=[a,l]:(a=null,yr=m)):(a=null,yr=m),a=null!==a?a:"",null!==a?(m=yr,58===n.charCodeAt(yr)?(l=":",yr++):(l=null,0===br&&i('":"')),null!==l?(u=de(),null!==u?l=[l,u]:(l=null,yr=m)):(l=null,yr=m),l=null!==l?l:"",null!==l?("::"===n.substr(yr,2)?(u="::",yr+=2):(u=null,0===br&&i('"::"')),null!==u?e=[e,t,r,o,s,a,l,u]:(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g)):(e=null,yr=g))))))))))))))),null!==e&&(e=function(e){return wr.host_type="IPv6",n.substring(yr,e)}(v)),null===e&&(yr=v),e}function de(){var e,t,n,r,i;return i=yr,e=l(),null!==e?(t=l(),t=null!==t?t:"",null!==t?(n=l(),n=null!==n?n:"",null!==n?(r=l(),r=null!==r?r:"",null!==r?e=[e,t,n,r]:(e=null,yr=i)):(e=null,yr=i)):(e=null,yr=i)):(e=null,yr=i),e}function fe(){var e,t,r,o;return o=yr,e=de(),null!==e?(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=de(),null!==r?e=[e,t,r]:(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o),null===e&&(e=he()),e}function he(){var e,t,r,o,s,a,l,u,c;return u=yr,c=yr,e=pe(),null!==e?(46===n.charCodeAt(yr)?(t=".",yr++):(t=null,0===br&&i('"."')),null!==t?(r=pe(),null!==r?(46===n.charCodeAt(yr)?(o=".",yr++):(o=null,0===br&&i('"."')),null!==o?(s=pe(),null!==s?(46===n.charCodeAt(yr)?(a=".",yr++):(a=null,0===br&&i('"."')),null!==a?(l=pe(),null!==l?e=[e,t,r,o,s,a,l]:(e=null,yr=c)):(e=null,yr=c)):(e=null,yr=c)):(e=null,yr=c)):(e=null,yr=c)):(e=null,yr=c)):(e=null,yr=c),null!==e&&(e=function(e){return wr.host_type="IPv4",n.substring(yr,e)}(u)),null===e&&(yr=u),e}function pe(){var e,t,r,o;return o=yr,"25"===n.substr(yr,2)?(e="25",yr+=2):(e=null,0===br&&i('"25"')),null!==e?(/^[0-5]/.test(n.charAt(yr))?(t=n.charAt(yr),yr++):(t=null,0===br&&i("[0-5]")),null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),null===e&&(o=yr,50===n.charCodeAt(yr)?(e="2",yr++):(e=null,0===br&&i('"2"')),null!==e?(/^[0-4]/.test(n.charAt(yr))?(t=n.charAt(yr),yr++):(t=null,0===br&&i("[0-4]")),null!==t?(r=s(),null!==r?e=[e,t,r]:(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o),null===e&&(o=yr,49===n.charCodeAt(yr)?(e="1",yr++):(e=null,0===br&&i('"1"')),null!==e?(t=s(),null!==t?(r=s(),null!==r?e=[e,t,r]:(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o),null===e&&(o=yr,/^[1-9]/.test(n.charAt(yr))?(e=n.charAt(yr),yr++):(e=null,0===br&&i("[1-9]")),null!==e?(t=s(),null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),null===e&&(e=s())))),e}function ve(){var e,t,n,r,i,o,a;return o=yr,a=yr,e=s(),e=null!==e?e:"",null!==e?(t=s(),t=null!==t?t:"",null!==t?(n=s(),n=null!==n?n:"",null!==n?(r=s(),r=null!==r?r:"",null!==r?(i=s(),i=null!==i?i:"",null!==i?e=[e,t,n,r,i]:(e=null,yr=a)):(e=null,yr=a)):(e=null,yr=a)):(e=null,yr=a)):(e=null,yr=a),null!==e&&(e=function(e,t){return t=parseInt(t.join("")),wr.port=t,t}(o,e)),null===e&&(yr=o),e}function ge(){var e,t,r,o;for(e=[],o=yr,59===n.charCodeAt(yr)?(t=";",yr++):(t=null,0===br&&i('";"')),null!==t?(r=me(),null!==r?t=[t,r]:(t=null,yr=o)):(t=null,yr=o);null!==t;)e.push(t),o=yr,59===n.charCodeAt(yr)?(t=";",yr++):(t=null,0===br&&i('";"')),null!==t?(r=me(),null!==r?t=[t,r]:(t=null,yr=o)):(t=null,yr=o);return e}function me(){var e;return e=ye(),null===e&&(e=be(),null===e&&(e=_e(),null===e&&(e=Se(),null===e&&(e=Te(),null===e&&(e=Ce(),null===e&&(e=we())))))),e}function ye(){var e,t,r,o;return r=yr,o=yr,"transport="===n.substr(yr,10).toLowerCase()?(e=n.substr(yr,10),yr+=10):(e=null,0===br&&i('"transport="')),null!==e?("udp"===n.substr(yr,3).toLowerCase()?(t=n.substr(yr,3),yr+=3):(t=null,0===br&&i('"udp"')),null===t&&("tcp"===n.substr(yr,3).toLowerCase()?(t=n.substr(yr,3),yr+=3):(t=null,0===br&&i('"tcp"')),null===t&&("sctp"===n.substr(yr,4).toLowerCase()?(t=n.substr(yr,4),yr+=4):(t=null,0===br&&i('"sctp"')),null===t&&("tls"===n.substr(yr,3).toLowerCase()?(t=n.substr(yr,3),yr+=3):(t=null,0===br&&i('"tls"')),null===t&&(t=R())))),null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),null!==e&&(e=function(e,t){wr.uri_params||(wr.uri_params={}),wr.uri_params.transport=t.toLowerCase()}(r,e[1])),null===e&&(yr=r),e}function be(){var e,t,r,o;return r=yr,o=yr,"user="===n.substr(yr,5).toLowerCase()?(e=n.substr(yr,5),yr+=5):(e=null,0===br&&i('"user="')),null!==e?("phone"===n.substr(yr,5).toLowerCase()?(t=n.substr(yr,5),yr+=5):(t=null,0===br&&i('"phone"')),null===t&&("ip"===n.substr(yr,2).toLowerCase()?(t=n.substr(yr,2),yr+=2):(t=null,0===br&&i('"ip"')),null===t&&(t=R())),null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),null!==e&&(e=function(e,t){wr.uri_params||(wr.uri_params={}),wr.uri_params.user=t.toLowerCase()}(r,e[1])),null===e&&(yr=r),e}function _e(){var e,t,r,o;return r=yr,o=yr,"method="===n.substr(yr,7).toLowerCase()?(e=n.substr(yr,7),yr+=7):(e=null,0===br&&i('"method="')),null!==e?(t=ut(),null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),null!==e&&(e=function(e,t){wr.uri_params||(wr.uri_params={}),wr.uri_params.method=t}(r,e[1])),null===e&&(yr=r),e}function Se(){var e,t,r,o;return r=yr,o=yr,"ttl="===n.substr(yr,4).toLowerCase()?(e=n.substr(yr,4),yr+=4):(e=null,0===br&&i('"ttl="')),null!==e?(t=Jn(),null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),null!==e&&(e=function(e,t){wr.params||(wr.params={}),wr.params.ttl=t}(r,e[1])),null===e&&(yr=r),e}function Te(){var e,t,r,o;return r=yr,o=yr,"maddr="===n.substr(yr,6).toLowerCase()?(e=n.substr(yr,6),yr+=6):(e=null,0===br&&i('"maddr="')),null!==e?(t=oe(),null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),null!==e&&(e=function(e,t){wr.uri_params||(wr.uri_params={}),wr.uri_params.maddr=t}(r,e[1])),null===e&&(yr=r),e}function Ce(){var e,t,r,o,s,a;return o=yr,s=yr,"lr"===n.substr(yr,2).toLowerCase()?(e=n.substr(yr,2),yr+=2):(e=null,0===br&&i('"lr"')),null!==e?(a=yr,61===n.charCodeAt(yr)?(t="=",yr++):(t=null,0===br&&i('"="')),null!==t?(r=R(),null!==r?t=[t,r]:(t=null,yr=a)):(t=null,yr=a),t=null!==t?t:"",null!==t?e=[e,t]:(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){wr.uri_params||(wr.uri_params={}),wr.uri_params.lr=void 0}(o)),null===e&&(yr=o),e}function we(){var e,t,r,o,s,a;return o=yr,s=yr,e=Ee(),null!==e?(a=yr,61===n.charCodeAt(yr)?(t="=",yr++):(t=null,0===br&&i('"="')),null!==t?(r=ke(),null!==r?t=[t,r]:(t=null,yr=a)):(t=null,yr=a),t=null!==t?t:"",null!==t?e=[e,t]:(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e,t,n){wr.uri_params||(wr.uri_params={}),n="undefined"==typeof n?void 0:n[1],wr.uri_params[t.toLowerCase()]=n}(o,e[0],e[1])),null===e&&(yr=o),e}function Ee(){var e,t,n;if(n=yr,t=Re(),null!==t)for(e=[];null!==t;)e.push(t),t=Re();else e=null;return null!==e&&(e=function(e,t){return t.join("")}(n,e)),null===e&&(yr=n),e}function ke(){var e,t,n;if(n=yr,t=Re(),null!==t)for(e=[];null!==t;)e.push(t),t=Re();else e=null;return null!==e&&(e=function(e,t){return t.join("")}(n,e)),null===e&&(yr=n),e}function Re(){var e;return e=Ie(),null===e&&(e=g(),null===e&&(e=y())),e}function Ie(){var e;return 91===n.charCodeAt(yr)?(e="[",yr++):(e=null,0===br&&i('"["')),null===e&&(93===n.charCodeAt(yr)?(e="]",yr++):(e=null,0===br&&i('"]"')),null===e&&(47===n.charCodeAt(yr)?(e="/",yr++):(e=null,0===br&&i('"/"')),null===e&&(58===n.charCodeAt(yr)?(e=":",yr++):(e=null,0===br&&i('":"')),null===e&&(38===n.charCodeAt(yr)?(e="&",yr++):(e=null,0===br&&i('"&"')),null===e&&(43===n.charCodeAt(yr)?(e="+",yr++):(e=null,0===br&&i('"+"')),null===e&&(36===n.charCodeAt(yr)?(e="$",yr++):(e=null,0===br&&i('"$"')))))))),e}function Pe(){var e,t,r,o,s,a,l;if(a=yr,63===n.charCodeAt(yr)?(e="?",yr++):(e=null,0===br&&i('"?"')),null!==e)if(t=Ae(),null!==t){for(r=[],l=yr,38===n.charCodeAt(yr)?(o="&",yr++):(o=null,0===br&&i('"&"')),null!==o?(s=Ae(),null!==s?o=[o,s]:(o=null,yr=l)):(o=null,yr=l);null!==o;)r.push(o),l=yr,38===n.charCodeAt(yr)?(o="&",yr++):(o=null,0===br&&i('"&"')),null!==o?(s=Ae(),null!==s?o=[o,s]:(o=null,yr=l)):(o=null,yr=l);null!==r?e=[e,t,r]:(e=null,yr=a)}else e=null,yr=a;else e=null,yr=a;return e}function Ae(){var e,t,r,o,s;return o=yr,s=yr,e=Oe(),null!==e?(61===n.charCodeAt(yr)?(t="=",yr++):(t=null,0===br&&i('"="')),null!==t?(r=Me(),null!==r?e=[e,t,r]:(e=null,yr=s)):(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e,t,n){t=t.join("").toLowerCase(),n=n.join(""),wr.uri_headers||(wr.uri_headers={}),wr.uri_headers[t]?wr.uri_headers[t].push(n):wr.uri_headers[t]=[n]}(o,e[0],e[2])),null===e&&(yr=o),e}function Oe(){var e,t;if(t=De(),null===t&&(t=g(),null===t&&(t=y())),null!==t)for(e=[];null!==t;)e.push(t),t=De(),null===t&&(t=g(),null===t&&(t=y()));else e=null;return e}function Me(){var e,t;for(e=[],t=De(),null===t&&(t=g(),null===t&&(t=y()));null!==t;)e.push(t),t=De(),null===t&&(t=g(),null===t&&(t=y()));return e}function De(){var e;return 91===n.charCodeAt(yr)?(e="[",yr++):(e=null,0===br&&i('"["')),null===e&&(93===n.charCodeAt(yr)?(e="]",yr++):(e=null,0===br&&i('"]"')),null===e&&(47===n.charCodeAt(yr)?(e="/",yr++):(e=null,0===br&&i('"/"')),null===e&&(63===n.charCodeAt(yr)?(e="?",yr++):(e=null,0===br&&i('"?"')),null===e&&(58===n.charCodeAt(yr)?(e=":",yr++):(e=null,0===br&&i('":"')),null===e&&(43===n.charCodeAt(yr)?(e="+",yr++):(e=null,0===br&&i('"+"')),null===e&&(36===n.charCodeAt(yr)?(e="$",yr++):(e=null,0===br&&i('"$"')))))))),e}function xe(){var e;return e=ct(),null===e&&(e=Ne()),e}function Ne(){var e,t,n,r,i,o;return o=yr,e=ut(),null!==e?(t=f(),null!==t?(n=Fe(),null!==n?(r=f(),null!==r?(i=Ze(),null!==i?e=[e,t,n,r,i]:(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o),e}function Fe(){var e;return e=X(),null===e&&(e=Ue()),e}function Ue(){var e,t,r,o;return o=yr,e=Je(),null!==e?(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null!==t?(r=je(),null===r&&(r=Be()),null!==r?e=[e,t,r]:(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o),e}function je(){var e,t,r,o,s;return o=yr,e=Le(),null===e&&(e=He()),null!==e?(s=yr,63===n.charCodeAt(yr)?(t="?",yr++):(t=null,0===br&&i('"?"')),null!==t?(r=Ye(),null!==r?t=[t,r]:(t=null,yr=s)):(t=null,yr=s),t=null!==t?t:"",null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),e}function Le(){var e,t,r,o;return o=yr,"//"===n.substr(yr,2)?(e="//",yr+=2):(e=null,0===br&&i('"//"')),null!==e?(t=Qe(),null!==t?(r=He(),r=null!==r?r:"",null!==r?e=[e,t,r]:(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o),e}function He(){var e,t,r;return r=yr,47===n.charCodeAt(yr)?(e="/",yr++):(e=null,0===br&&i('"/"')),null!==e?(t=We(),null!==t?e=[e,t]:(e=null,yr=r)):(e=null,yr=r),e}function Be(){var e,t,n,r;if(r=yr,e=Ge(),null!==e){for(t=[],n=qe();null!==n;)t.push(n),n=qe();null!==t?e=[e,t]:(e=null,yr=r)}else e=null,yr=r;return e}function qe(){var e;return e=v(),null===e&&(e=g(),null===e&&(e=y())),e}function Ge(){var e;return e=g(),null===e&&(e=y(),null===e&&(59===n.charCodeAt(yr)?(e=";",yr++):(e=null,0===br&&i('";"')),null===e&&(63===n.charCodeAt(yr)?(e="?",yr++):(e=null,0===br&&i('"?"')),null===e&&(58===n.charCodeAt(yr)?(e=":",yr++):(e=null,0===br&&i('":"')),null===e&&(64===n.charCodeAt(yr)?(e="@",yr++):(e=null,0===br&&i('"@"')),null===e&&(38===n.charCodeAt(yr)?(e="&",yr++):(e=null,0===br&&i('"&"')),null===e&&(61===n.charCodeAt(yr)?(e="=",yr++):(e=null,0===br&&i('"="')),null===e&&(43===n.charCodeAt(yr)?(e="+",yr++):(e=null,0===br&&i('"+"')),null===e&&(36===n.charCodeAt(yr)?(e="$",yr++):(e=null,0===br&&i('"$"')),null===e&&(44===n.charCodeAt(yr)?(e=",",yr++):(e=null,0===br&&i('","')))))))))))),e}function We(){var e,t,r,o,s,a;if(s=yr,e=Ve(),null!==e){for(t=[],a=yr,47===n.charCodeAt(yr)?(r="/",yr++):(r=null,0===br&&i('"/"')),null!==r?(o=Ve(),null!==o?r=[r,o]:(r=null,yr=a)):(r=null,yr=a);null!==r;)t.push(r),a=yr,47===n.charCodeAt(yr)?(r="/",yr++):(r=null,0===br&&i('"/"')),null!==r?(o=Ve(),null!==o?r=[r,o]:(r=null,yr=a)):(r=null,yr=a);null!==t?e=[e,t]:(e=null,yr=s)}else e=null,yr=s;return e}function Ve(){var e,t,r,o,s,a;for(s=yr,e=[],t=Ke();null!==t;)e.push(t),t=Ke();if(null!==e){for(t=[],a=yr,59===n.charCodeAt(yr)?(r=";",yr++):(r=null,0===br&&i('";"')),null!==r?(o=ze(),null!==o?r=[r,o]:(r=null,yr=a)):(r=null,yr=a);null!==r;)t.push(r),a=yr,59===n.charCodeAt(yr)?(r=";",yr++):(r=null,0===br&&i('";"')),null!==r?(o=ze(),null!==o?r=[r,o]:(r=null,yr=a)):(r=null,yr=a);null!==t?e=[e,t]:(e=null,yr=s)}else e=null,yr=s;return e}function ze(){var e,t;for(e=[],t=Ke();null!==t;)e.push(t),t=Ke();return e}function Ke(){var e;return e=g(),null===e&&(e=y(),null===e&&(58===n.charCodeAt(yr)?(e=":",yr++):(e=null,0===br&&i('":"')),null===e&&(64===n.charCodeAt(yr)?(e="@",yr++):(e=null,0===br&&i('"@"')),null===e&&(38===n.charCodeAt(yr)?(e="&",yr++):(e=null,0===br&&i('"&"')),null===e&&(61===n.charCodeAt(yr)?(e="=",yr++):(e=null,0===br&&i('"="')),null===e&&(43===n.charCodeAt(yr)?(e="+",yr++):(e=null,0===br&&i('"+"')),null===e&&(36===n.charCodeAt(yr)?(e="$",yr++):(e=null,0===br&&i('"$"')),null===e&&(44===n.charCodeAt(yr)?(e=",",yr++):(e=null,0===br&&i('","')))))))))),e}function Je(){var e,t,r,o,l;if(o=yr,l=yr,e=a(),null!==e){for(t=[],r=a(),null===r&&(r=s(),null===r&&(43===n.charCodeAt(yr)?(r="+",yr++):(r=null,0===br&&i('"+"')),null===r&&(45===n.charCodeAt(yr)?(r="-",yr++):(r=null,0===br&&i('"-"')),null===r&&(46===n.charCodeAt(yr)?(r=".",yr++):(r=null,0===br&&i('"."'))))));null!==r;)t.push(r),r=a(),null===r&&(r=s(),null===r&&(43===n.charCodeAt(yr)?(r="+",yr++):(r=null,0===br&&i('"+"')),null===r&&(45===n.charCodeAt(yr)?(r="-",yr++):(r=null,0===br&&i('"-"')),null===r&&(46===n.charCodeAt(yr)?(r=".",yr++):(r=null,0===br&&i('"."'))))));null!==t?e=[e,t]:(e=null,yr=l)}else e=null,yr=l;return null!==e&&(e=function(e){wr.scheme=n.substring(yr,e)}(o)),null===e&&(yr=o),e}function Qe(){var e;return e=Xe(),null===e&&(e=$e()),e}function Xe(){var e,t,r,o;return r=yr,o=yr,e=ee(),null!==e?(64===n.charCodeAt(yr)?(t="@",yr++):(t=null,0===br&&i('"@"')),null!==t?e=[e,t]:(e=null,yr=o)):(e=null,yr=o),e=null!==e?e:"",null!==e?(t=ie(),null!==t?e=[e,t]:(e=null,yr=r)):(e=null,yr=r),e=null!==e?e:""}function $e(){var e,t;if(t=g(),null===t&&(t=y(),null===t&&(36===n.charCodeAt(yr)?(t="$",yr++):(t=null,0===br&&i('"$"')),null===t&&(44===n.charCodeAt(yr)?(t=",",yr++):(t=null,0===br&&i('","')),null===t&&(59===n.charCodeAt(yr)?(t=";",yr++):(t=null,0===br&&i('";"')),null===t&&(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null===t&&(64===n.charCodeAt(yr)?(t="@",yr++):(t=null,0===br&&i('"@"')),null===t&&(38===n.charCodeAt(yr)?(t="&",yr++):(t=null,0===br&&i('"&"')),null===t&&(61===n.charCodeAt(yr)?(t="=",yr++):(t=null,0===br&&i('"="')),null===t&&(43===n.charCodeAt(yr)?(t="+",yr++):(t=null,0===br&&i('"+"'))))))))))),null!==t)for(e=[];null!==t;)e.push(t),t=g(),null===t&&(t=y(),null===t&&(36===n.charCodeAt(yr)?(t="$",yr++):(t=null,0===br&&i('"$"')),null===t&&(44===n.charCodeAt(yr)?(t=",",yr++):(t=null,0===br&&i('","')),null===t&&(59===n.charCodeAt(yr)?(t=";",yr++):(t=null,0===br&&i('";"')),null===t&&(58===n.charCodeAt(yr)?(t=":",yr++):(t=null,0===br&&i('":"')),null===t&&(64===n.charCodeAt(yr)?(t="@",yr++):(t=null,0===br&&i('"@"')),null===t&&(38===n.charCodeAt(yr)?(t="&",yr++):(t=null,0===br&&i('"&"')),null===t&&(61===n.charCodeAt(yr)?(t="=",yr++):(t=null,0===br&&i('"="')),null===t&&(43===n.charCodeAt(yr)?(t="+",yr++):(t=null,0===br&&i('"+"')))))))))));else e=null;return e}function Ye(){var e,t;for(e=[],t=qe();null!==t;)e.push(t),t=qe();return e}function Ze(){var e,t,r,o,a,l,u,c;if(u=yr,c=yr,"sip"===n.substr(yr,3).toLowerCase()?(e=n.substr(yr,3),yr+=3):(e=null,0===br&&i('"SIP"')),null!==e)if(47===n.charCodeAt(yr)?(t="/",yr++):(t=null,0===br&&i('"/"')),null!==t){if(o=s(),null!==o)for(r=[];null!==o;)r.push(o),o=s();else r=null;if(null!==r)if(46===n.charCodeAt(yr)?(o=".",yr++):(o=null,0===br&&i('"."')),null!==o){if(l=s(),null!==l)for(a=[];null!==l;)a.push(l),l=s();else a=null;null!==a?e=[e,t,r,o,a]:(e=null,yr=c)}else e=null,yr=c;else e=null,yr=c}else e=null,yr=c;else e=null,yr=c;return null!==e&&(e=function(e){wr.sip_version=n.substring(yr,e)}(u)),null===e&&(yr=u),e}function et(){var e;return"INVITE"===n.substr(yr,6)?(e="INVITE",yr+=6):(e=null,0===br&&i('"INVITE"')),e}function tt(){var e;return"ACK"===n.substr(yr,3)?(e="ACK",yr+=3):(e=null,0===br&&i('"ACK"')),e}function nt(){var e;return"OPTIONS"===n.substr(yr,7)?(e="OPTIONS",yr+=7):(e=null,0===br&&i('"OPTIONS"')),e}function rt(){var e;return"BYE"===n.substr(yr,3)?(e="BYE",yr+=3):(e=null,0===br&&i('"BYE"')),e}function it(){var e;return"CANCEL"===n.substr(yr,6)?(e="CANCEL",yr+=6):(e=null,0===br&&i('"CANCEL"')),e}function ot(){var e;return"REGISTER"===n.substr(yr,8)?(e="REGISTER",yr+=8):(e=null,0===br&&i('"REGISTER"')),e}function st(){var e;return"SUBSCRIBE"===n.substr(yr,9)?(e="SUBSCRIBE",yr+=9):(e=null,0===br&&i('"SUBSCRIBE"')),e}function at(){var e;return"NOTIFY"===n.substr(yr,6)?(e="NOTIFY",yr+=6):(e=null,0===br&&i('"NOTIFY"')),e}function lt(){var e;return"REFER"===n.substr(yr,5)?(e="REFER",yr+=5):(e=null,0===br&&i('"REFER"')),e}function ut(){var e,t;return t=yr,e=et(),null===e&&(e=tt(),null===e&&(e=nt(),null===e&&(e=rt(),null===e&&(e=it(),null===e&&(e=ot(),null===e&&(e=st(),null===e&&(e=at(),null===e&&(e=lt(),null===e&&(e=R()))))))))),null!==e&&(e=function(e){return wr.method=n.substring(yr,e),wr.method}(t)),null===e&&(yr=t),e}function ct(){var e,t,n,r,i,o;return o=yr,e=Ze(),null!==e?(t=f(),null!==t?(n=dt(),null!==n?(r=f(),null!==r?(i=ht(),null!==i?e=[e,t,n,r,i]:(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o)):(e=null,yr=o),e}function dt(){var e,t;return t=yr,e=ft(),null!==e&&(e=function(e,t){wr.status_code=parseInt(t.join(""))}(t,e)),null===e&&(yr=t),e}function ft(){var e,t,n,r;return r=yr,e=s(),null!==e?(t=s(),null!==t?(n=s(),null!==n?e=[e,t,n]:(e=null,yr=r)):(e=null,yr=r)):(e=null,yr=r),e}function ht(){var e,t,r;for(r=yr,e=[],t=v(),null===t&&(t=g(),null===t&&(t=y(),null===t&&(t=w(),null===t&&(t=E(),null===t&&(t=f(),null===t&&(t=h()))))));null!==t;)e.push(t),t=v(),null===t&&(t=g(),null===t&&(t=y(),null===t&&(t=w(),null===t&&(t=E(),null===t&&(t=f(),null===t&&(t=h()))))));return null!==e&&(e=function(e){wr.reason_phrase=n.substring(yr,e)}(r)),null===e&&(yr=r),e}function pt(){var e,t,n,r,i,o;if(i=yr,e=Kt(),null!==e){for(t=[],o=yr,n=j(),null!==n?(r=Kt(),null!==r?n=[n,r]:(n=null,yr=o)):(n=null,yr=o);null!==n;)t.push(n),o=yr,n=j(),null!==n?(r=Kt(),null!==r?n=[n,r]:(n=null,yr=o)):(n=null,yr=o);null!==t?e=[e,t]:(e=null,yr=i)}else e=null,yr=i;return e}function vt(){var e,t,r,o,s,a;return o=yr,s=yr,e=A(),null!==e?(a=yr,64===n.charCodeAt(yr)?(t="@",yr++):(t=null,0===br&&i('"@"')),null!==t?(r=A(),null!==r?t=[t,r]:(t=null,yr=a)):(t=null,yr=a),t=null!==t?t:"",null!==t?e=[e,t]:(e=null,yr=s)):(e=null,yr=s),null!==e&&(e=function(e){wr=n.substring(yr,e)}(o)),null===e&&(yr=o),e}function gt(){var e,t,n,r,i,o,s;if(i=yr,e=O(),null===e)if(o=yr,e=mt(),null!==e){for(t=[],s=yr,n=j(),null!==n?(r=mt(),null!==r?n=[n,r]:(n=null,yr=s)):(n=null,yr=s);null!==n;)t.push(n),s=yr,n=j(),null!==n?(r=mt(),null!==r?n=[n,r]:(n=null,yr=s)):(n=null,yr=s);null!==t?e=[e,t]:(e=null,yr=o)}else e=null,yr=o;return null!==e&&(e=function(e){var t,n;for(n=wr.multi_header.length,t=0;t=700)throw new TypeError("Invalid status_code: "+t);this.request.reply(t,n,r,i)},r.prototype.newMessage=function(e,t){"remote"===e?(this.direction="incoming",this.local_identity=t.to,this.remote_identity=t.from):"local"===e&&(this.direction="outgoing",this.local_identity=t.from,this.remote_identity=t.to),this.ua.newMessage({originator:e,message:this,request:t})}},{"./Constants":35,"./Exceptions":39,"./RequestSender":51,"./SIPMessage":52,"./Transactions":55,"./Utils":59,events:11,util:23}],43:[function(e,t,n){function r(e,t,n){var r;if(!(e&&e instanceof i))throw new TypeError('missing or invalid "uri" parameter');this.uri=e,this.parameters={};for(r in n)this.setParam(r,n[r]);Object.defineProperties(this,{display_name:{get:function(){return t},set:function(e){t=0===e?"0":e}}})}t.exports=r;var i=e("./URI"),o=e("./Grammar");r.prototype={setParam:function(e,t){e&&(this.parameters[e.toLowerCase()]="undefined"==typeof t||null===t?null:t.toString())},getParam:function(e){if(e)return this.parameters[e.toLowerCase()]},hasParam:function(e){if(e)return this.parameters.hasOwnProperty(e.toLowerCase())&&!0||!1},deleteParam:function(e){var t;if(e=e.toLowerCase(),this.parameters.hasOwnProperty(e))return t=this.parameters[e],delete this.parameters[e],t},clearParams:function(){this.parameters={}},clone:function(){return new r(this.uri.clone(),this.display_name,JSON.parse(JSON.stringify(this.parameters)))},toString:function(){var e,t;e=this.display_name||0===this.display_name?'"'+this.display_name+'" ':"",e+="<"+this.uri.toString()+">";for(t in this.parameters)e+=";"+t,null!==this.parameters[t]&&(e+="="+this.parameters[t]);return e}},r.parse=function(e){return e=o.parse(e,"Name_Addr_Header"),e!==-1?e:void 0}},{"./Grammar":40,"./URI":58}],44:[function(e,t,n){function r(e,t){var n=t,r=0,i=0;if(e.substring(n,n+2).match(/(^\r\n)/))return-2;for(;0===r;){if(i=e.indexOf("\r\n",n),i===-1)return i;!e.substring(i+2,i+4).match(/(^\r\n)/)&&e.charAt(i+2).match(/(^\s+)/)?n=i+2:r=i}return r}function i(e,t,n,r){var i,o,s,u,c=t.indexOf(":",n),d=t.substring(n,c).trim(),f=t.substring(c+1,r).trim();switch(d.toLowerCase()){case"via":case"v":e.addHeader("via",f),1===e.getHeaders("via").length?(u=e.parseHeader("Via"),u&&(e.via=u,e.via_branch=u.branch)):u=0;break;case"from":case"f":e.setHeader("from",f),u=e.parseHeader("from"),u&&(e.from=u,e.from_tag=u.getParam("tag"));break;case"to":case"t":e.setHeader("to",f),u=e.parseHeader("to"),u&&(e.to=u,e.to_tag=u.getParam("tag"));break;case"record-route":if(u=a.parse(f,"Record_Route"),u===-1)u=void 0;else for(s=u.length,o=0;oQ.T2&&(r=Q.T2)),n.timers.invite2xxTimer=setTimeout(i,r))},r)}function o(){var e=this;this.timers.ackTimer=setTimeout(function(){e.status===L.STATUS_WAITING_FOR_ACK&&(q("no ACK received, terminating the session"),clearTimeout(e.timers.invite2xxTimer),b.call(e,V.BYE),M.call(e,"remote",null,V.causes.NO_ACK))},Q.TIMER_H)}function s(e,t){var n=this;this.connection=new RTCPeerConnection(e,t),this.connection.addEventListener("iceconnectionstatechange",function(){var e=n.connection.iceConnectionState;"failed"!==e||this.disableRtpTimeOut||n.terminate({cause:V.causes.RTP_TIMEOUT,status_code:200,reason_phrase:V.causes.RTP_TIMEOUT})})}function a(e,t,n,r){function i(r){var i,a=!1;s.addEventListener("icecandidate",i=function(n){var r=n.candidate;if(r&&r.candidate.search("srflx")!=-1&&(a=!0),!r||a){if(s.removeEventListener("icecandidate",i),o.rtcReady=!0,t){var l={originator:"local",type:e,sdp:s.localDescription.sdp};o.emit("sdp",l),t(l.sdp),q("iceGathering completed")}t=null}}),s.setLocalDescription(r).then(function(){"complete"!=s.iceGatheringState&&setTimeout(function(){if("complete"===s.iceGatheringState)return void q("iceGathering already completed");if(o.rtcReady=!0,t){var n={originator:"local",type:e,sdp:s.localDescription.sdp};o.emit("sdp",n),t(n.sdp),t=null,q("iceGathering taking more than 2sec "+s.iceGatheringState),j.call(o,2e3)}},2e3),q("iceGatheringState after setLocalDescription success: "+s.iceGatheringState)})["catch"](function(e){o.rtcReady=!0,n&&n(e),o.emit("peerconnection:setlocaldescriptionfailed",e)})}q("createLocalDescription()");var o=this,s=this.connection;if(this.rtcReady=!1,"offer"===e)s.createOffer(r).then(i)["catch"](function(e){o.rtcReady=!0,n&&n(e),o.emit("peerconnection:createofferfailed",e)});else{if("answer"!==e)throw new Error('createLocalDescription() | type must be "offer" or "answer", but "'+e+'" was given');s.createAnswer(r).then(i)["catch"](function(e){o.rtcReady=!0,n&&n(e),o.emit("peerconnection:createanswerfailed",e)})}}function l(e,t,n){var r,i,o="UAS"===t?e.to_tag:e.from_tag,s="UAS"===t?e.from_tag:e.to_tag,a=e.call_id+o+s;return i=this.earlyDialogs[a],n?!!i||(i=new $(this,e,t,$.C.STATUS_EARLY),i.error?(q(i.error),D.call(this,"remote",e,V.causes.INTERNAL_ERROR),!1):(this.earlyDialogs[a]=i,!0)):(this.from_tag=e.from_tag,this.to_tag=e.to_tag,i?(i.update(e,t),this.dialog=i,delete this.earlyDialogs[a],!0):(r=new $(this,e,t),r.error?(q(r.error),D.call(this,"remote",e,V.causes.INTERNAL_ERROR),!1):(this.dialog=r,!0)))}function u(e){function t(t){t=t||{},p=!0;var n=t.status_code||403,r=t.reason_phrase||"",i=t.extraHeaders&&t.extraHeaders.slice()||[];if(this.status!==L.STATUS_CONFIRMED)return!1;if(n<300||n>=700)throw new TypeError("Invalid status_code: "+n);e.reply(n,r,i)}function n(){r(function(t){var n=["Contact: "+d.contact];T.call(d,e,n),d.late_sdp&&(t=_.call(d,t)),e.reply(200,null,n,t,function(){d.status=L.STATUS_WAITING_FOR_ACK,i.call(d,e,t),o.call(d)}),"function"==typeof v.callback&&v.callback()},function(){e.reply(500)})}function r(e,t){d.late_sdp?a.call(d,"offer",e,t,d.rtcOfferConstraints):(d.remoteHold===!0&&h===!1?(d.remoteHold=!1,N.call(d,"remote")):d.remoteHold===!1&&h===!0&&(d.remoteHold=!0,x.call(d,"remote")),a.call(d,"answer",e,t,d.rtcAnswerConstraints))}q("receiveReinvite()");var s,l,u,c,d=this,f=e.getHeader("Content-Type"),h=!1,p=!1,v={request:e,callback:void 0,reject:t.bind(this)};if(this.emit("reinvite",v),!p)if(e.body){if(this.late_sdp=!1,"application/sdp"!==f)return q("invalid Content-Type"),void e.reply(415);for(s=e.parseSDP(),l=0;l=700)throw new TypeError("Invalid status_code: "+n);e.reply(n,r,i)}q("receiveUpdate()");var n,r,i,o,s=this,l=e.getHeader("Content-Type"),u=!1,c=!1,d={request:e,callback:void 0,reject:t.bind(this)};if(this.emit("update",d),!u){if(!e.body){var f=[];return T.call(this,e,f),void e.reply(200,null,f)}if("application/sdp"!==l)return q("invalid Content-Type"),void e.reply(415);for(n=e.parseSDP(),r=0;r=200&&e.status_code<=299)return this.dialog.id.call_id===e.call_id&&this.dialog.id.local_tag===e.from_tag&&this.dialog.id.remote_tag===e.to_tag?void b.call(this,V.ACK):(n=new $(this,e,"UAC"),void 0!==n.error?void q(n.error):(n.sendRequest({owner:{status:L.STATUS_TERMINATED},onRequestTimeout:function(){},onTransportError:function(){},onDialogError:function(){},receiveResponse:function(){}},V.ACK),void n.sendRequest({owner:{status:L.STATUS_TERMINATED},onRequestTimeout:function(){},onTransportError:function(){},onDialogError:function(){},receiveResponse:function(){}},V.BYE)));if(this.isCanceled)return this.isCanceled=!1,void(e.status_code>=100&&e.status_code<200?this.request.cancel(this.cancelReason):e.status_code>=200&&e.status_code<299&&y.call(this,e));if(this.status===L.STATUS_INVITE_SENT||this.status===L.STATUS_1XX_RECEIVED)switch(!0){case/^100$/.test(e.status_code):this.status=L.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(e.status_code):if(!e.to_tag){q("1xx response received without to tag");break}if(e.hasHeader("contact")&&!l.call(this,e,"UAC",!0))break;if(this.status=L.STATUS_1XX_RECEIVED,P.call(this,"remote",e),!e.body)break;r={originator:"remote",type:"pranswer",sdp:e.body},this.emit("sdp",r);var o=new RTCSessionDescription({type:"pranswer",sdp:r.sdp});this.connection.setRemoteDescription(o)["catch"](function(e){i.emit("peerconnection:setremotedescriptionfailed",e)});break;case/^2[0-9]{2}$/.test(e.status_code):if(this.status=L.STATUS_CONFIRMED,!e.body){y.call(this,e,400,V.causes.MISSING_SDP),D.call(this,"remote",e,V.causes.BAD_MEDIA_DESCRIPTION);break}if(!l.call(this,e,"UAC"))break;r={originator:"remote",type:"answer",sdp:e.body},this.emit("sdp",r);var s=new RTCSessionDescription({type:"answer",sdp:r.sdp});this.connection.setRemoteDescription(s).then(function(){C.call(i,e),A.call(i,"remote",e),b.call(i,V.ACK),O.call(i,"local",null)})["catch"](function(t){y.call(i,e,488,"Not Acceptable Here"),D.call(i,"remote",e,V.causes.BAD_MEDIA_DESCRIPTION),i.emit("peerconnection:setremotedescriptionfailed",t)});break;default:t=J.sipErrorCause(e.status_code),D.call(this,"remote",e,t)}}function g(e){function t(e){if(r.status!==L.STATUS_TERMINATED&&(b.call(r,V.ACK),!l)){if(C.call(r,e),!e.body)return void n();if("application/sdp"!==e.getHeader("Content-Type"))return void n();var t={originator:"remote",type:"answer",sdp:e.body},i=new RTCSessionDescription({type:"answer",sdp:t.sdp});r.emit("sdp",t),r.connection.setRemoteDescription(i).then(function(){o.succeeded&&o.succeeded(e)})["catch"](function(e){n(),r.emit("peerconnection:setremotedescriptionfailed",e)})}}function n(e){o.failed&&o.failed(e)}q("sendReinvite()"),e=e||{};var r=this,i=e.extraHeaders||[],o=e.eventHandlers||{},s=e.rtcOfferConstraints||this.rtcOfferConstraints||null,l=!1;i.push("Contact: "+this.contact),i.push("Content-Type: application/sdp"),this.sessionTimers.running&&i.push("Session-Expires: "+this.sessionTimers.currentExpires+";refresher="+(this.sessionTimers.refresher?"uac":"uas")),a.call(this,"offer",function(e){e=_.call(r,e);var o=new Z(r,V.INVITE);o.send({extraHeaders:i,body:e,eventHandlers:{onSuccessResponse:function(e){t(e),l=!0},onErrorResponse:function(e){n(e)},onTransportError:function(){r.onTransportError()},onRequestTimeout:function(){r.onRequestTimeout()},onDialogError:function(){r.onDialogError()}}})},function(){n()},s)}function m(e){function t(e){if(r.status!==L.STATUS_TERMINATED&&!u)if(C.call(r,e),l){if(!e.body)return void n();if("application/sdp"!==e.getHeader("Content-Type"))return void n();var t={originator:"remote",type:"answer",sdp:e.body},i=new RTCSessionDescription({type:"answer",sdp:t.sdp});r.emit("sdp",t),r.connection.setRemoteDescription(i).then(function(){o.succeeded&&o.succeeded(e)})["catch"](function(e){n(),r.emit("peerconnection:setremotedescriptionfailed",e)})}else o.succeeded&&o.succeeded(e)}function n(e){o.failed&&o.failed(e)}q("sendUpdate()"),e=e||{};var r=this,i=e.extraHeaders||[],o=e.eventHandlers||{},s=e.rtcOfferConstraints||this.rtcOfferConstraints||null,l=e.sdpOffer||!1,u=!1;if(i.push("Contact: "+this.contact),this.sessionTimers.running&&i.push("Session-Expires: "+this.sessionTimers.currentExpires+";refresher="+(this.sessionTimers.refresher?"uac":"uas")),l)i.push("Content-Type: application/sdp"),a.call(this,"offer",function(e){e=_.call(r,e);var o=new Z(r,V.UPDATE);o.send({extraHeaders:i,body:e,eventHandlers:{onSuccessResponse:function(e){t(e),u=!0},onErrorResponse:function(e){n(e)},onTransportError:function(){r.onTransportError()},onRequestTimeout:function(){r.onRequestTimeout()},onDialogError:function(){r.onDialogError()}}})},function(){n()},s);else{var c=new Z(r,V.UPDATE);c.send({extraHeaders:i,eventHandlers:{onSuccessResponse:function(e){t(e)},onErrorResponse:function(e){n(e)},onTransportError:function(){r.onTransportError()},onRequestTimeout:function(){r.onRequestTimeout()},onDialogError:function(){r.onDialogError()}}})}}function y(e,t,n){q("acceptAndTerminate()");var r=[];t&&(n=n||V.REASON_PHRASE[t]||"",r.push("Reason: SIP ;cause="+t+'; text="'+n+'"')),(this.dialog||l.call(this,e,"UAC"))&&(b.call(this,V.ACK),b.call(this,V.BYE,{extraHeaders:r})),this.status=L.STATUS_TERMINATED}function b(e,t){q("sendRequest()");var n=new Z(this,e);n.send(t)}function _(e){var t,n,r;if(!this.localHold&&!this.remoteHold)return e;if(e=W.parse(e),this.localHold&&!this.remoteHold)for(q("mangleOffer() | me on hold, mangling offer"),n=e.media.length,t=0;t=V.MIN_SESSION_EXPIRES?(this.sessionTimers.currentExpires=e.session_expires,n=e.session_expires_refresher||"uas"):(this.sessionTimers.currentExpires=this.sessionTimers.defaultExpires,n="uas"),t.push("Session-Expires: "+this.sessionTimers.currentExpires+";refresher="+n),this.sessionTimers.refresher="uas"===n,w.call(this)}}function C(e){if(this.sessionTimers.enabled){var t;e.session_expires&&e.session_expires>=V.MIN_SESSION_EXPIRES?(this.sessionTimers.currentExpires=e.session_expires,t=e.session_expires_refresher||"uac"):(this.sessionTimers.currentExpires=this.sessionTimers.defaultExpires,t="uac"),this.sessionTimers.refresher="uac"===t,w.call(this)}}function w(){var e=this,t=this.sessionTimers.currentExpires;this.sessionTimers.running=!0,clearTimeout(this.sessionTimers.timer),this.sessionTimers.refresher?this.sessionTimers.timer=setTimeout(function(){e.status!==L.STATUS_TERMINATED&&(q("runSessionTimer() | sending session refresh request"),m.call(e,{eventHandlers:{succeeded:function(t){C.call(e,t)}}}))},500*t):this.sessionTimers.timer=setTimeout(function(){e.status!==L.STATUS_TERMINATED&&(G("runSessionTimer() | timer expired, terminating the session"),e.terminate({cause:V.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},1100*t)}function E(e){var t,n,r,i,o,s=this.connection.getLocalStreams();for(r=s.length,t=0;t=V.MIN_SESSION_EXPIRES?this.sessionTimers.defaultExpires=t.sessionTimersExpires:this.sessionTimers.defaultExpires=V.SESSION_EXPIRES),this.data=t.data||this.data,void 0===e)throw new TypeError("Not enough arguments");if(!window.RTCPeerConnection)throw new z.NotSupportedError("WebRTC not supported");if(e=this.ua.normalizeTarget(e),!e)throw new TypeError("Invalid target: "+o);if(this.status!==L.STATUS_NULL)throw new z.InvalidStateError(this.status);for(r in a)this.on(r,a[r]);this.from_tag=J.newTag(),this.anonymous=t.anonymous||!1,this.isCanceled=!1,i={from_tag:this.from_tag},this.contact=this.ua.contact.toString({anonymous:this.anonymous,outbound:!0}),this.anonymous&&(i.from_display_name="Anonymous",i.from_uri="sip:anonymous@anonymous.invalid",l.push("P-Preferred-Identity: "+this.ua.configuration.uri.toString()),l.push("Privacy: id")),l.push("Contact: "+this.contact),l.push("Content-Type: application/sdp"),this.sessionTimers.enabled&&l.push("Session-Expires: "+this.sessionTimers.defaultExpires),this.request=new X.OutgoingRequest(V.INVITE,e,this.ua,i,l),this.id=this.request.call_id+this.from_tag,s.call(this,d,f),this.ua.sessions[this.id]=this,this.direction="outgoing",this.local_identity=this.request.from,this.remote_identity=this.request.to,n?n(this):R.call(this,"local",this.request),p.call(this,u,h,c)},r.prototype.init_incoming=function(e,t){q("init_incoming()");var n,r=this,i=e.getHeader("Content-Type");return e.body&&"application/sdp"!==i?void e.reply(415):(this.status=L.STATUS_INVITE_RECEIVED,this.from_tag=e.from_tag,this.id=e.call_id+this.from_tag,this.request=e,this.contact=this.ua.contact.toString(),this.ua.sessions[this.id]=this,e.hasHeader("expires")&&(n=1e3*e.getHeader("expires")),e.to_tag=J.newTag(),l.call(this,e,"UAS",!0)?(e.body?this.late_sdp=!1:this.late_sdp=!0,this.status=L.STATUS_WAITING_FOR_ANSWER,this.timers.userNoAnswerTimer=setTimeout(function(){e.reply(408),D.call(r,"local",null,V.causes.NO_ANSWER)},this.ua.configuration.no_answer_timeout),n&&(this.timers.expiresTimer=setTimeout(function(){r.status===L.STATUS_WAITING_FOR_ANSWER&&(e.reply(487),D.call(r,"system",null,V.causes.EXPIRES))},n)),this.direction="incoming",this.local_identity=e.to,this.remote_identity=e.from,t?t(this):R.call(this,"remote",e),void(this.status!==L.STATUS_TERMINATED&&(e.reply(180,null,["Contact: "+r.contact]),P.call(r,"local",null)))):void e.reply(500,"Missing Contact header field"))},r.prototype.answer=function(e){function t(e){if(b.status!==L.STATUS_TERMINATED)if(b.localMediaStream=e,e&&b.connection.addStream(e),b.request.body||b.emit("peerconnection",{peerconnection:b.connection}),b.late_sdp)r();else{var t={originator:"remote",type:"offer",sdp:_.body},n=new RTCSessionDescription({type:"offer",sdp:t.sdp});b.emit("sdp",t),b.connection.setRemoteDescription(n).then(r)["catch"](function(e){_.reply(488),D.call(b,"system",null,V.causes.WEBRTC_ERROR),b.emit("peerconnection:setremotedescriptionfailed",e)})}}function n(){b.status!==L.STATUS_TERMINATED&&(_.reply(480),D.call(b,"local",null,V.causes.USER_DENIED_MEDIA_ACCESS))}function r(){I.call(b,_),b.late_sdp?a.call(b,"offer",u,c,b.rtcOfferConstraints):a.call(b,"answer",u,c,R)}function u(e){function t(){b.status=L.STATUS_WAITING_FOR_ACK,i.call(b,_,e),o.call(b),A.call(b,"local")}function n(){D.call(b,"system",null,V.causes.CONNECTION_ERROR)}b.status!==L.STATUS_TERMINATED&&(T.call(b,_,S),_.reply(200,null,S,e,t,n))}function c(){b.status!==L.STATUS_TERMINATED&&(_.reply(500),D.call(b,"system",null,V.causes.WEBRTC_ERROR))}q("answer()"),e=e||{};var d,f,h,p,v=!1,g=!1,m=!1,y=!1,b=this,_=this.request,S=e.extraHeaders&&e.extraHeaders.slice()||[],C=e.mediaConstraints||{},w=e.mediaStream||null,E=e.pcConfig||{iceServers:[]},k=e.rtcConstraints||null,R=e.rtcAnswerConstraints||null;if(this.rtcAnswerConstraints=R,this.rtcOfferConstraints=e.rtcOfferConstraints||null,this.sessionTimers.enabled&&J.isDecimal(e.sessionTimersExpires)&&(e.sessionTimersExpires>=V.MIN_SESSION_EXPIRES?this.sessionTimers.defaultExpires=e.sessionTimersExpires:this.sessionTimers.defaultExpires=V.SESSION_EXPIRES),this.data=e.data||this.data,"incoming"!==this.direction)throw new z.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this.status!==L.STATUS_WAITING_FOR_ANSWER)throw new z.InvalidStateError(this.status);if(this.status=L.STATUS_ANSWERED,!l.call(this,_,"UAS"))return void _.reply(500,"Error creating dialog");for(clearTimeout(this.timers.userNoAnswerTimer),S.unshift("Contact: "+b.contact),h=_.parseSDP(),Array.isArray(h.media)||(h.media=[h.media]),d=h.media.length;d--;){var P=h.media[d];"audio"===P.type&&(v=!0,P.direction&&"sendrecv"!==P.direction||(m=!0)),"video"===P.type&&(g=!0,P.direction&&"sendrecv"!==P.direction||(y=!0))}if(w&&C.audio===!1)for(p=w.getAudioTracks(),f=p.length,d=0;d=700))throw new TypeError("Invalid status_code: "+i);i&&(o=o||V.REASON_PHRASE[i]||"", +t="SIP ;cause="+i+' ;text="'+o+'"'),this.status===L.STATUS_NULL?(this.isCanceled=!0,this.cancelReason=t):this.status===L.STATUS_INVITE_SENT?(this.isCanceled=!0,this.cancelReason=t):this.status===L.STATUS_1XX_RECEIVED&&this.request.cancel(t),this.status=L.STATUS_CANCELED,D.call(this,"local",null,V.causes.CANCELED);break;case L.STATUS_WAITING_FOR_ANSWER:case L.STATUS_ANSWERED:if(q("rejecting session"),i=i||480,i<300||i>=700)throw new TypeError("Invalid status_code: "+i);this.request.reply(i,o,s,a),D.call(this,"local",null,V.causes.REJECTED);break;case L.STATUS_WAITING_FOR_ACK:case L.STATUS_CONFIRMED:if(q("terminating session"),o=e.reason_phrase||V.REASON_PHRASE[i]||"",i&&(i<200||i>=700))throw new TypeError("Invalid status_code: "+i);i&&s.push("Reason: SIP ;cause="+i+'; text="'+o+'"'),this.status===L.STATUS_WAITING_FOR_ACK&&"incoming"===this.direction&&this.request.server_transaction.state!==K.C.STATUS_TERMINATED?(n=this.dialog,this.receiveRequest=function(e){e.method===V.ACK&&(b.call(this,V.BYE,{extraHeaders:s,body:a}),n.terminate())},this.request.server_transaction.on("stateChanged",function(){this.state===K.C.STATUS_TERMINATED&&(b.call(l,V.BYE,{extraHeaders:s,body:a}),n.terminate())}),M.call(this,"local",null,r),this.dialog=n,this.ua.dialogs[n.id.toString()]=n):(b.call(this,V.BYE,{extraHeaders:s,body:a}),M.call(this,"local",null,r))}},r.prototype.close=function(){q("close()");var e;if(this.status!==L.STATUS_TERMINATED){if(this.connection)try{this.connection.close()}catch(t){G("close() | error closing the RTCPeerConnection: %o",t)}this.localMediaStream&&this.localMediaStreamLocallyGenerated&&(q("close() | closing local MediaStream"),J.closeMediaStream(this.localMediaStream));for(e in this.timers)clearTimeout(this.timers[e]);clearTimeout(this.sessionTimers.timer),this.dialog&&(this.dialog.terminate(),delete this.dialog);for(e in this.earlyDialogs)this.earlyDialogs[e].terminate(),delete this.earlyDialogs[e];this.status=L.STATUS_TERMINATED,delete this.ua.sessions[this.id]}},r.prototype.sendDTMF=function(e,t){function n(){var e,a;if(s.status===L.STATUS_TERMINATED||!s.tones||o>=s.tones.length)return void(s.tones=null);if(e=s.tones[o],o+=1,","===e)a=2e3;else{var l=new ee(s);t.eventHandlers={failed:function(){s.tones=null}},l.send(e,t),a=r+i}setTimeout(n,a)}q("sendDTMF() | tones: %s",e);var r,i,o=0,s=this;if(t=t||{},r=t.duration||null,i=t.interToneGap||null,void 0===e)throw new TypeError("Not enough arguments");if(this.status!==L.STATUS_CONFIRMED&&this.status!==L.STATUS_WAITING_FOR_ACK)throw new z.InvalidStateError(this.status);if("number"==typeof e&&(e=e.toString()),!e||"string"!=typeof e||!e.match(/^[0-9A-D#*,]+$/i))throw new TypeError("Invalid tones: "+e);if(r&&!J.isDecimal(r))throw new TypeError("Invalid tone duration: "+r);if(r?ree.C.MAX_DURATION?(q('"duration" value is greater than the maximum allowed, setting it to '+ee.C.MAX_DURATION+" milliseconds"),r=ee.C.MAX_DURATION):r=Math.abs(r):r=ee.C.DEFAULT_DURATION,t.duration=r,i&&!J.isDecimal(i))throw new TypeError("Invalid interToneGap: "+i);return i?i=1&&n.test(t[0])&&(this.tone=t[0].replace(n,"$2")),t.length>=2&&r.test(t[1])&&(this.duration=parseInt(t[1].replace(r,"$2"),10))),this.duration||(this.duration=i.DEFAULT_DURATION),this.tone?this.owner.newDTMF({originator:"remote",dtmf:this,request:e}):o("invalid INFO DTMF received, discarded")}},{"../Constants":35,"../Exceptions":39,"../RTCSession":45,debug:12}],47:[function(e,t,n){function r(e,t,n){this.session=e,this.id=t,this.expires=n||i.expires,this.active=!0,this.notify(100)}t.exports=r;var i={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300},o=e("debug")("PlivoSIP:RTCSession:ReferNotifier"),s=e("../Constants"),a=e("./Request");r.prototype.notify=function(e,t){o("notify()");var n,r=this;if(this.active!==!1){t=t||s.REASON_PHRASE[e]||"",n=e>=200?"terminated;reason=noresource":"active;expires="+this.expires;var l=new a(this.session,s.NOTIFY);l.send({extraHeaders:["Event: "+i.event_type+";id="+r.id,"Subscription-State: "+n,"Content-Type: "+i.body_type],body:"SIP/2.0 "+e+" "+t,eventHandlers:{onErrorResponse:function(){r.active=!1}}})}}},{"../Constants":35,"./Request":49,debug:12}],48:[function(e,t,n){function r(e){this.session=e,this.timer=null,this.outgoingRequest=null,a.EventEmitter.call(this)}function i(){console.log("removeSubscriber()"),clearTimeout(this.timer),this.session.referSubscriber=null}t.exports=r;var o={expires:120},s=e("util"),a=e("events"),l=e("debug")("PlivoSIP:RTCSession:ReferSubscriber"),u=e("../Constants"),c=e("../Grammar"),d=e("./Request");s.inherits(r,a.EventEmitter),r.prototype.sendRefer=function(e,t){l("sendRefer()");var n,r,s,a=null,c=this;t=t||{},n=t.extraHeaders?t.extraHeaders.slice():[],r=t.eventHandlers||{};for(var f in r)this.on(f,r[f]);t.replaces&&(a=t.replaces.request.call_id,a+=";to-tag="+t.replaces.to_tag,a+=";from-tag="+t.replaces.from_tag,a=encodeURIComponent(a)),s="Refer-To: <"+e+(a?"?Replaces="+a:"")+">",n.push(s);var h=new d(this.session,u.REFER);this.timer=setTimeout(function(){i.call(c)},1e3*o.expires),h.send({extraHeaders:n,eventHandlers:{onSuccessResponse:function(e){c.emit("requestSucceeded",{response:e})},onErrorResponse:function(e){c.emit("requestFailed",{response:e,cause:u.causes.REJECTED})},onTransportError:function(){i.call(c),c.emit("requestFailed",{response:null,cause:u.causes.CONNECTION_ERROR})},onRequestTimeout:function(){i.call(c),c.emit("requestFailed",{response:null,cause:u.causes.REQUEST_TIMEOUT})},onDialogError:function(){i.call(c),c.emit("requestFailed",{response:null,cause:u.causes.DIALOG_ERROR})}}}),this.outgoingRequest=h.outgoingRequest},r.prototype.receiveNotify=function(e){l("receiveNotify()");var t;if(e.body){if(t=c.parse(e.body,"Status_Line"),t===-1)return void l('receiveNotify() | error parsing NOTIFY body: "'+e.body+'"');switch(!0){case/^100$/.test(t.status_code):this.emit("trying",{request:e,status_line:t});break;case/^1[0-9]{2}$/.test(t.status_code):this.emit("progress",{request:e,status_line:t});break;case/^2[0-9]{2}$/.test(t.status_code):i.call(this),this.emit("accepted",{request:e,status_line:t});break;default:i.call(this),this.emit("failed",{request:e,status_line:t})}}}},{"../Constants":35,"../Grammar":40,"./Request":49,debug:12,events:11,util:23}],49:[function(e,t,n){function r(e,t){if(i("new | %s",t),this.session=e,this.method=t,this.outgoingRequest=null,this.session.status!==l.C.STATUS_1XX_RECEIVED&&this.session.status!==l.C.STATUS_WAITING_FOR_ANSWER&&this.session.status!==l.C.STATUS_WAITING_FOR_ACK&&this.session.status!==l.C.STATUS_CONFIRMED&&this.session.status!==l.C.STATUS_TERMINATED)throw new a.InvalidStateError(this.session.status);if(this.session.status===l.C.STATUS_TERMINATED&&t!==s.BYE)throw new a.InvalidStateError(this.session.status)}t.exports=r;var i=e("debug")("PlivoSIP:RTCSession:Request"),o=e("debug")("PlivoSIP:ERROR:RTCSession:Request");o.log=console.warn.bind(console);var s=e("../Constants"),a=e("../Exceptions"),l=e("../RTCSession");r.prototype.send=function(e){e=e||{};var t=e.extraHeaders&&e.extraHeaders.slice()||[],n=e.body||null;this.eventHandlers=e.eventHandlers||{},this.outgoingRequest=this.session.dialog.sendRequest(this,this.method,{extraHeaders:t,body:n})},r.prototype.receiveResponse=function(e){switch(!0){case/^1[0-9]{2}$/.test(e.status_code):i("onProgressResponse"),this.eventHandlers.onProgressResponse&&this.eventHandlers.onProgressResponse(e);break;case/^2[0-9]{2}$/.test(e.status_code):i("onSuccessResponse"),this.eventHandlers.onSuccessResponse&&this.eventHandlers.onSuccessResponse(e);break;default:i("onErrorResponse"),this.eventHandlers.onErrorResponse&&this.eventHandlers.onErrorResponse(e)}},r.prototype.onRequestTimeout=function(){o("onRequestTimeout"),this.eventHandlers.onRequestTimeout&&this.eventHandlers.onRequestTimeout()},r.prototype.onTransportError=function(){o("onTransportError"),this.eventHandlers.onTransportError&&this.eventHandlers.onTransportError()},r.prototype.onDialogError=function(){o("onDialogError"),this.eventHandlers.onDialogError&&this.eventHandlers.onDialogError()}},{"../Constants":35,"../Exceptions":39,"../RTCSession":45,debug:12}],50:[function(e,t,n){function r(e,t){var n=1;this.ua=e,this.transport=t,this.registrar=e.configuration.registrar_server,this.expires=e.configuration.register_expires,this.call_id=o.createRandomToken(22),this.cseq=0,this.to_uri=e.configuration.uri,this.registrationTimer=null,this.registered=!1,this.contact=this.ua.contact.toString(),this.contact+=";+sip.ice",this.extraHeaders=[],this.extraContactParams="",n&&(this.contact+=";reg-id="+n,this.contact+=';+sip.instance=""')}t.exports=r;var i=e("debug")("PlivoSIP:Registrator"),o=e("./Utils"),s=e("./Constants"),a=e("./SIPMessage"),l=e("./RequestSender");r.prototype={setExtraHeaders:function(e){Array.isArray(e)||(e=[]),this.extraHeaders=e.slice()},setExtraContactParams:function(e){e instanceof Object||(e={}),this.extraContactParams="";for(var t in e){var n=e[t];this.extraContactParams+=";"+t,n&&(this.extraContactParams+="="+n)}},register:function(){var e,t,n,r=this;n=this.extraHeaders.slice(),n.push("Contact: "+this.contact+";expires="+this.expires+this.extraContactParams),n.push("Expires: "+this.expires),this.request=new a.OutgoingRequest(s.REGISTER,this.registrar,this.ua,{to_uri:this.to_uri,call_id:this.call_id,cseq:this.cseq+=1},n),e=new l(this,this.ua),this.receiveResponse=function(e){var n,a,l=e.getHeaders("contact").length;if(e.cseq===this.cseq)switch(null!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=null),!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):if(e.hasHeader("expires")&&(a=e.getHeader("expires")),!l){i("no Contact header in response to REGISTER, response ignored");break}for(;l--;){if(n=e.parseHeader("contact",l),n.uri.user===this.ua.contact.uri.user){a=n.getParam("expires");break}n=null}if(!n){i("no Contact header pointing to us, response ignored");break}a||(a=this.expires),this.registrationTimer=setTimeout(function(){r.registrationTimer=null,r.register()},1e3*a-3e3),n.hasParam("temp-gruu")&&(this.ua.contact.temp_gruu=n.getParam("temp-gruu").replace(/"/g,"")),n.hasParam("pub-gruu")&&(this.ua.contact.pub_gruu=n.getParam("pub-gruu").replace(/"/g,"")),this.registered||(this.registered=!0,this.ua.registered({response:e}));break;case/^423$/.test(e.status_code):e.hasHeader("min-expires")?(this.expires=e.getHeader("min-expires"),this.register()):(i("423 response received for REGISTER without Min-Expires"),this.registrationFailure(e,s.causes.SIP_FAILURE_CODE));break;default:t=o.sipErrorCause(e.status_code),this.registrationFailure(e,t)}},this.onRequestTimeout=function(){this.registrationFailure(null,s.causes.REQUEST_TIMEOUT)},this.onTransportError=function(){this.registrationFailure(null,s.causes.CONNECTION_ERROR)},e.send()},unregister:function(e){var t;if(!this.registered)return void i("already unregistered");e=e||{},this.registered=!1,null!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=null),t=this.extraHeaders.slice(),e.all?(t.push("Contact: *"+this.extraContactParams),t.push("Expires: 0"),this.request=new a.OutgoingRequest(s.REGISTER,this.registrar,this.ua,{to_uri:this.to_uri,call_id:this.call_id,cseq:this.cseq+=1},t)):(t.push("Contact: "+this.contact+";expires=0"+this.extraContactParams),t.push("Expires: 0"),this.request=new a.OutgoingRequest(s.REGISTER,this.registrar,this.ua,{to_uri:this.to_uri,call_id:this.call_id,cseq:this.cseq+=1},t));var n=new l(this,this.ua);this.receiveResponse=function(e){var t;switch(!0){case/^1[0-9]{2}$/.test(e.status_code):break;case/^2[0-9]{2}$/.test(e.status_code):this.unregistered(e);break;default:t=o.sipErrorCause(e.status_code),this.unregistered(e,t)}},this.onRequestTimeout=function(){this.unregistered(null,s.causes.REQUEST_TIMEOUT)},this.onTransportError=function(){this.unregistered(null,s.causes.CONNECTION_ERROR)},n.send()},registrationFailure:function(e,t){this.ua.registrationFailed({response:e||null,cause:t}),this.registered&&(this.registered=!1,this.ua.unregistered({response:e||null,cause:t}))},unregistered:function(e,t){this.registered=!1,this.ua.unregistered({response:e||null,cause:t||null})},onTransportClosed:function(){null!==this.registrationTimer&&(clearTimeout(this.registrationTimer),this.registrationTimer=null),this.registered&&(this.registered=!1,this.ua.unregistered({}))},close:function(){this.registered&&this.unregister()}}},{"./Constants":35,"./RequestSender":51,"./SIPMessage":52,"./Utils":59,debug:12}],51:[function(e,t,n){function r(e,t){this.ua=t,this.applicant=e,this.method=e.request.method,this.request=e.request,this.auth=null,this.challenged=!1,this.staled=!1,t.status!==s.C.STATUS_USER_CLOSED||this.method===o.BYE&&this.method===o.ACK||this.onTransportError()}t.exports=r;var i=e("debug")("PlivoSIP:RequestSender"),o=e("./Constants"),s=e("./UA"),a=e("./DigestAuthentication"),l=e("./Transactions");r.prototype={send:function(){switch(this.method){case"INVITE":this.clientTransaction=new l.InviteClientTransaction(this,this.request,this.ua.transport);break;case"ACK":this.clientTransaction=new l.AckClientTransaction(this,this.request,this.ua.transport);break;default:this.clientTransaction=new l.NonInviteClientTransaction(this,this.request,this.ua.transport)}this.clientTransaction.send()},onRequestTimeout:function(){this.applicant.onRequestTimeout()},onTransportError:function(){this.applicant.onTransportError()},receiveResponse:function(e){var t,n,r,s=e.status_code;if(401!==s&&407!==s||null===this.ua.configuration.password&&null===this.ua.configuration.ha1)this.applicant.receiveResponse(e);else{if(401===e.status_code?(n=e.parseHeader("www-authenticate"),r="authorization"):(n=e.parseHeader("proxy-authenticate"),r="proxy-authorization"),!n)return i(e.status_code+" with wrong or missing challenge, cannot authenticate"),void this.applicant.receiveResponse(e);if(!this.challenged||!this.staled&&n.stale===!0){if(this.auth||(this.auth=new a({username:this.ua.configuration.authorization_user,password:this.ua.configuration.password,realm:this.ua.configuration.realm,ha1:this.ua.configuration.ha1})),!this.auth.authenticate(this.request,n))return void this.applicant.receiveResponse(e);this.challenged=!0,this.ua.set("realm",this.auth.get("realm")),this.ua.set("ha1",this.auth.get("ha1")),n.stale&&(this.staled=!0),t=e.method===o.REGISTER?this.applicant.cseq+=1:this.request.dialog?this.request.dialog.local_seqnum+=1:this.request.cseq+1,this.request=this.applicant.request=this.request.clone(),this.request.cseq=t,this.request.setHeader("cseq",t+" "+this.method),this.request.setHeader(r,this.auth.toString()),this.send()}else this.applicant.receiveResponse(e)}}}},{"./Constants":35,"./DigestAuthentication":38,"./Transactions":55,"./UA":57,debug:12}],52:[function(e,t,n){function r(e,t,n,r,i,o){var s,a,l,f;return r=r||{},e&&t&&n?(this.ua=n,this.headers={},this.method=e,this.ruri=t,this.body=o,this.extraHeaders=i&&i.slice()||[],r.route_set?this.setHeader("route",r.route_set):n.configuration.use_preloaded_route&&this.setHeader("route","<"+n.transport.sip_uri+";lr>"),this.setHeader("via",""),this.setHeader("max-forwards",u.MAX_FORWARDS),s=r.to_display_name||0===r.to_display_name?'"'+r.to_display_name+'" ':"",s+="<"+(r.to_uri||t)+">",s+=r.to_tag?";tag="+r.to_tag:"",this.to=new d.parse(s),this.setHeader("to",s),a=r.from_display_name||0===r.from_display_name?'"'+r.from_display_name+'" ':n.configuration.display_name?'"'+n.configuration.display_name+'" ':"",a+="<"+(r.from_uri||n.configuration.uri)+">;tag=",a+=r.from_tag||c.newTag(),this.from=new d.parse(a),this.setHeader("from",a),l=r.call_id||n.configuration.plivosip_id+c.createRandomToken(15),this.call_id=l,this.setHeader("call-id",l),f=r.cseq||Math.floor(1e4*Math.random()),this.cseq=f,void this.setHeader("cseq",f+" "+e)):null}function i(){this.data=null,this.headers=null,this.method=null,this.via=null,this.via_branch=null,this.call_id=null,this.cseq=null,this.from=null,this.from_tag=null,this.to=null,this.to_tag=null,this.body=null,this.sdp=null}function o(e){this.ua=e,this.headers={},this.ruri=null,this.transport=null,this.server_transaction=null}function s(){this.headers={},this.status_code=null,this.reason_phrase=null}t.exports={OutgoingRequest:r,IncomingRequest:o,IncomingResponse:s};var a=e("debug")("PlivoSIP:SIPMessage"),l=e("sdp-transform"),u=e("./Constants"),c=e("./Utils"),d=e("./NameAddrHeader"),f=e("./Grammar");r.prototype={setHeader:function(e,t){var n,r;for(n=new RegExp("^\\s*"+e+"\\s*:","i"),r=0;r=this.headers[e].length?void a('not so many "'+e+'" headers present'):(n=this.headers[e][t],r=n.raw,n.parsed?n.parsed:(i=f.parse(r,e.replace(/-/g,"_")),i===-1?(this.headers[e].splice(t,1),void a('error parsing "'+e+'" header field with value "'+r+'"')):(n.parsed=i,i))):void a('header "'+e+'" not present')},s:function(e,t){return this.parseHeader(e,t)},setHeader:function(e,t){var n={raw:t};this.headers[c.headerize(e)]=[n]},parseSDP:function(e){return!e&&this.sdp?this.sdp:(this.sdp=l.parse(this.body||""),this.sdp)},toString:function(){return this.data}},o.prototype=new i,o.prototype.reply=function(e,t,n,r,i,o){var s,a,l,d,f,h=[],p=this.getHeader("To"),v=0,g=0;if(e=e||null,t=t||null,!e||e<100||e>699)throw new TypeError("Invalid status_code: "+e);if(t&&"string"!=typeof t&&!(t instanceof String))throw new TypeError("Invalid reason_phrase: "+t);if(t=t||u.REASON_PHRASE[e]||"",n=n&&n.slice()||[],f="SIP/2.0 "+e+" "+t+"\r\n",this.method===u.INVITE&&e>100&&e<=200)for(s=this.getHeaders("record-route"),l=s.length,v;v100?p+=";tag="+c.newTag():this.to_tag&&!this.s("to").hasParam("tag")&&(p+=";tag="+this.to_tag),f+="To: "+p+"\r\n",f+="From: "+this.getHeader("From")+"\r\n",f+="Call-ID: "+this.call_id+"\r\n",f+="CSeq: "+this.cseq+" "+this.method+"\r\n",l=n.length,d=0;d699)throw new TypeError("Invalid status_code: "+e);if(t&&"string"!=typeof t&&!(t instanceof String))throw new TypeError("Invalid reason_phrase: "+t);for(t=t||u.REASON_PHRASE[e]||"",r="SIP/2.0 "+e+" "+t+"\r\n",i;i100?n+=";tag="+c.newTag():this.to_tag&&!this.s("to").hasParam("tag")&&(n+=";tag="+this.to_tag),r+="To: "+n+"\r\n",r+="From: "+this.getHeader("From")+"\r\n",r+="Call-ID: "+this.call_id+"\r\n",r+="CSeq: "+this.cseq+" "+this.method+"\r\n",r+="Content-Length: 0\r\n\r\n",this.transport.send(r)},s.prototype=new i},{"./Constants":35,"./Grammar":40,"./NameAddrHeader":43,"./Utils":59,debug:12,"sdp-transform":18}],53:[function(e,t,n){function r(){}t.exports=r;var i=e("./Utils"),o=e("./Grammar"),s=e("debug")("PlivoSIP:ERROR:Socket");s.log=console.warn.bind(console),r.isSocket=function(e){if(Array.isArray(e))return!1;if("undefined"==typeof e)return s("undefined JsSIP.Socket instance"),!1;try{if(!i.isString(e.url))throw s("missing or invalid JsSIP.Socket url property"),new Error;if(!i.isString(e.via_transport))throw s("missing or invalid JsSIP.Socket via_transport property"),new Error;if(o.parse(e.sip_uri,"SIP_URI")===-1)throw s("missing or invalid JsSIP.Socket sip_uri property"),new Error}catch(t){return!1}try{["connect","disconnect","send"].forEach(function(t){if(!i.isFunction(e[t]))throw s("missing or invalid JsSIP.Socket method: "+t),new Error})}catch(t){return!1}return!0}},{"./Grammar":40,"./Utils":59,debug:12}],54:[function(e,t,n){var r=500,i=4e3,o=5e3,s={T1:r,T2:i,T4:o,TIMER_B:64*r,TIMER_D:0*r,TIMER_F:64*r,TIMER_H:64*r,TIMER_I:0*r,TIMER_J:0*r,TIMER_K:0*o,TIMER_L:64*r,TIMER_M:64*r,PROVISIONAL_RESPONSE_INTERVAL:6e4};t.exports=s},{}],55:[function(e,t,n){function r(e,t,n){var r;this.type=u.NON_INVITE_CLIENT,this.transport=n,this.id="z9hG4bK"+Math.floor(1e7*Math.random()),this.request_sender=e,this.request=t,r="SIP/2.0/"+n.via_transport,r+=" "+e.ua.configuration.via_host+";branch="+this.id,this.request.setHeader("via",r),this.request_sender.ua.newTransaction(this),d.EventEmitter.call(this)}function i(e,t,n){var r,i=this; +this.type=u.INVITE_CLIENT,this.transport=n,this.id="z9hG4bK"+Math.floor(1e7*Math.random()),this.request_sender=e,this.request=t,r="SIP/2.0/"+n.via_transport,r+=" "+e.ua.configuration.via_host+";branch="+this.id,this.request.setHeader("via",r),this.request_sender.ua.newTransaction(this),this.request.cancel=function(e){i.cancel_request(i,e)},d.EventEmitter.call(this)}function o(e,t,n){var r;this.transport=n,this.id="z9hG4bK"+Math.floor(1e7*Math.random()),this.request_sender=e,this.request=t,r="SIP/2.0/"+n.via_transport,r+=" "+e.ua.configuration.via_host+";branch="+this.id,this.request.setHeader("via",r),d.EventEmitter.call(this)}function s(e,t){this.type=u.NON_INVITE_SERVER,this.id=e.via_branch,this.request=e,this.transport=e.transport,this.ua=t,this.last_response="",e.server_transaction=this,this.state=u.STATUS_TRYING,t.newTransaction(this),d.EventEmitter.call(this)}function a(e,t){this.type=u.INVITE_SERVER,this.id=e.via_branch,this.request=e,this.transport=e.transport,this.ua=t,this.last_response="",e.server_transaction=this,this.state=u.STATUS_PROCEEDING,t.newTransaction(this),this.resendProvisionalTimer=null,e.reply(100),d.EventEmitter.call(this)}function l(e,t){var n;switch(t.method){case m.INVITE:if(n=e.transactions.ist[t.via_branch]){switch(n.state){case u.STATUS_PROCEEDING:n.transport.send(n.last_response);break;case u.STATUS_ACCEPTED:}return!0}break;case m.ACK:if(n=e.transactions.ist[t.via_branch],!n)return!1;if(n.state===u.STATUS_ACCEPTED)return!1;if(n.state===u.STATUS_COMPLETED)return n.state=u.STATUS_CONFIRMED,n.I=setTimeout(function(){n.timer_I()},y.TIMER_I),!0;break;case m.CANCEL:return n=e.transactions.ist[t.via_branch],n?(t.reply_sl(200),n.state!==u.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(n=e.transactions.nist[t.via_branch]){switch(n.state){case u.STATUS_TRYING:break;case u.STATUS_PROCEEDING:case u.STATUS_COMPLETED:n.transport.send(n.last_response)}return!0}}}t.exports={C:null,NonInviteClientTransaction:r,InviteClientTransaction:i,AckClientTransaction:o,NonInviteServerTransaction:s,InviteServerTransaction:a,checkTransaction:l};var u={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"};t.exports.C=u;var c=e("util"),d=e("events"),f=e("debug")("PlivoSIP:NonInviteClientTransaction"),h=e("debug")("PlivoSIP:InviteClientTransaction"),p=e("debug")("PlivoSIP:AckClientTransaction"),v=e("debug")("PlivoSIP:NonInviteServerTransaction"),g=e("debug")("PlivoSIP:InviteServerTransaction"),m=e("./Constants"),y=e("./Timers");c.inherits(r,d.EventEmitter),r.prototype.stateChanged=function(e){this.state=e,this.emit("stateChanged")},r.prototype.send=function(){var e=this;this.stateChanged(u.STATUS_TRYING),this.F=setTimeout(function(){e.timer_F()},y.TIMER_F),this.transport.send(this.request)||this.onTransportError()},r.prototype.onTransportError=function(){f("transport error occurred, deleting transaction "+this.id),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(u.STATUS_TERMINATED),this.request_sender.ua.destroyTransaction(this),this.request_sender.onTransportError()},r.prototype.timer_F=function(){f("Timer F expired for transaction "+this.id),this.stateChanged(u.STATUS_TERMINATED),this.request_sender.ua.destroyTransaction(this),this.request_sender.onRequestTimeout()},r.prototype.timer_K=function(){this.stateChanged(u.STATUS_TERMINATED),this.request_sender.ua.destroyTransaction(this)},r.prototype.receiveResponse=function(e){var t=this,n=e.status_code;if(n<200)switch(this.state){case u.STATUS_TRYING:case u.STATUS_PROCEEDING:this.stateChanged(u.STATUS_PROCEEDING),this.request_sender.receiveResponse(e)}else switch(this.state){case u.STATUS_TRYING:case u.STATUS_PROCEEDING:this.stateChanged(u.STATUS_COMPLETED),clearTimeout(this.F),408===n?this.request_sender.onRequestTimeout():this.request_sender.receiveResponse(e),this.K=setTimeout(function(){t.timer_K()},y.TIMER_K);break;case u.STATUS_COMPLETED:}},c.inherits(i,d.EventEmitter),i.prototype.stateChanged=function(e){this.state=e,this.emit("stateChanged")},i.prototype.send=function(){var e=this;this.stateChanged(u.STATUS_CALLING),this.B=setTimeout(function(){e.timer_B()},y.TIMER_B),this.transport.send(this.request)||this.onTransportError()},i.prototype.onTransportError=function(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==u.STATUS_ACCEPTED&&(h("transport error occurred, deleting transaction "+this.id),this.request_sender.onTransportError()),this.stateChanged(u.STATUS_TERMINATED),this.request_sender.ua.destroyTransaction(this)},i.prototype.timer_M=function(){h("Timer M expired for transaction "+this.id),this.state===u.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(u.STATUS_TERMINATED),this.request_sender.ua.destroyTransaction(this))},i.prototype.timer_B=function(){h("Timer B expired for transaction "+this.id),this.state===u.STATUS_CALLING&&(this.stateChanged(u.STATUS_TERMINATED),this.request_sender.ua.destroyTransaction(this),this.request_sender.onRequestTimeout())},i.prototype.timer_D=function(){h("Timer D expired for transaction "+this.id),clearTimeout(this.B),this.stateChanged(u.STATUS_TERMINATED),this.request_sender.ua.destroyTransaction(this)},i.prototype.sendACK=function(e){var t=this;this.ack="ACK "+this.request.ruri+" SIP/2.0\r\n",this.ack+="Via: "+this.request.headers.Via.toString()+"\r\n",this.request.headers.Route&&(this.ack+="Route: "+this.request.headers.Route.toString()+"\r\n"),this.ack+="To: "+e.getHeader("to")+"\r\n",this.ack+="From: "+this.request.headers.From.toString()+"\r\n",this.ack+="Call-ID: "+this.request.headers["Call-ID"].toString()+"\r\n",this.ack+="CSeq: "+this.request.headers.CSeq.toString().split(" ")[0],this.ack+=" ACK\r\n",this.ack+="Content-Length: 0\r\n\r\n",this.D=setTimeout(function(){t.timer_D()},y.TIMER_D),this.transport.send(this.ack)},i.prototype.cancel_request=function(e,t){var n=e.request;this.cancel=m.CANCEL+" "+n.ruri+" SIP/2.0\r\n",this.cancel+="Via: "+n.headers.Via.toString()+"\r\n",this.request.headers.Route&&(this.cancel+="Route: "+n.headers.Route.toString()+"\r\n"),this.cancel+="To: "+n.headers.To.toString()+"\r\n",this.cancel+="From: "+n.headers.From.toString()+"\r\n",this.cancel+="Call-ID: "+n.headers["Call-ID"].toString()+"\r\n",this.cancel+="CSeq: "+n.headers.CSeq.toString().split(" ")[0]+" CANCEL\r\n",t&&(this.cancel+="Reason: "+t+"\r\n"),this.cancel+="Content-Length: 0\r\n\r\n",this.state===u.STATUS_PROCEEDING&&this.transport.send(this.cancel)},i.prototype.receiveResponse=function(e){var t=this,n=e.status_code;if(n>=100&&n<=199)switch(this.state){case u.STATUS_CALLING:this.stateChanged(u.STATUS_PROCEEDING),this.request_sender.receiveResponse(e);break;case u.STATUS_PROCEEDING:this.request_sender.receiveResponse(e)}else if(n>=200&&n<=299)switch(this.state){case u.STATUS_CALLING:case u.STATUS_PROCEEDING:this.stateChanged(u.STATUS_ACCEPTED),this.M=setTimeout(function(){t.timer_M()},y.TIMER_M),this.request_sender.receiveResponse(e);break;case u.STATUS_ACCEPTED:this.request_sender.receiveResponse(e)}else if(n>=300&&n<=699)switch(this.state){case u.STATUS_CALLING:case u.STATUS_PROCEEDING:this.stateChanged(u.STATUS_COMPLETED),this.sendACK(e),this.request_sender.receiveResponse(e);break;case u.STATUS_COMPLETED:this.sendACK(e)}},c.inherits(o,d.EventEmitter),o.prototype.send=function(){this.transport.send(this.request)||this.onTransportError()},o.prototype.onTransportError=function(){p("transport error occurred for transaction "+this.id),this.request_sender.onTransportError()},c.inherits(s,d.EventEmitter),s.prototype.stateChanged=function(e){this.state=e,this.emit("stateChanged")},s.prototype.timer_J=function(){v("Timer J expired for transaction "+this.id),this.stateChanged(u.STATUS_TERMINATED),this.ua.destroyTransaction(this)},s.prototype.onTransportError=function(){this.transportError||(this.transportError=!0,v("transport error occurred, deleting transaction "+this.id),clearTimeout(this.J),this.stateChanged(u.STATUS_TERMINATED),this.ua.destroyTransaction(this))},s.prototype.receiveResponse=function(e,t,n,r){var i=this;if(100===e)switch(this.state){case u.STATUS_TRYING:this.stateChanged(u.STATUS_PROCEEDING),this.transport.send(t)||this.onTransportError();break;case u.STATUS_PROCEEDING:this.last_response=t,this.transport.send(t)?n&&n():(this.onTransportError(),r&&r())}else if(e>=200&&e<=699)switch(this.state){case u.STATUS_TRYING:case u.STATUS_PROCEEDING:this.stateChanged(u.STATUS_COMPLETED),this.last_response=t,this.J=setTimeout(function(){i.timer_J()},y.TIMER_J),this.transport.send(t)?n&&n():(this.onTransportError(),r&&r());break;case u.STATUS_COMPLETED:}},c.inherits(a,d.EventEmitter),a.prototype.stateChanged=function(e){this.state=e,this.emit("stateChanged")},a.prototype.timer_H=function(){g("Timer H expired for transaction "+this.id),this.state===u.STATUS_COMPLETED&&g("ACK not received, dialog will be terminated"),this.stateChanged(u.STATUS_TERMINATED),this.ua.destroyTransaction(this)},a.prototype.timer_I=function(){this.stateChanged(u.STATUS_TERMINATED)},a.prototype.timer_L=function(){g("Timer L expired for transaction "+this.id),this.state===u.STATUS_ACCEPTED&&(this.stateChanged(u.STATUS_TERMINATED),this.ua.destroyTransaction(this))},a.prototype.onTransportError=function(){this.transportError||(this.transportError=!0,g("transport error occurred, deleting transaction "+this.id),null!==this.resendProvisionalTimer&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(u.STATUS_TERMINATED),this.ua.destroyTransaction(this))},a.prototype.resend_provisional=function(){this.transport.send(this.last_response)||this.onTransportError()},a.prototype.receiveResponse=function(e,t,n,r){var i=this;if(e>=100&&e<=199)switch(this.state){case u.STATUS_PROCEEDING:this.transport.send(t)||this.onTransportError(),this.last_response=t}if(e>100&&e<=199&&this.state===u.STATUS_PROCEEDING)null===this.resendProvisionalTimer&&(this.resendProvisionalTimer=setInterval(function(){i.resend_provisional()},y.PROVISIONAL_RESPONSE_INTERVAL));else if(e>=200&&e<=299)switch(this.state){case u.STATUS_PROCEEDING:this.stateChanged(u.STATUS_ACCEPTED),this.last_response=t,this.L=setTimeout(function(){i.timer_L()},y.TIMER_L),null!==this.resendProvisionalTimer&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case u.STATUS_ACCEPTED:this.transport.send(t)?n&&n():(this.onTransportError(),r&&r())}else if(e>=300&&e<=699)switch(this.state){case u.STATUS_PROCEEDING:null!==this.resendProvisionalTimer&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(t)?(this.stateChanged(u.STATUS_COMPLETED),this.H=setTimeout(function(){i.timer_H()},y.TIMER_H),n&&n()):(this.onTransportError(),r&&r())}}},{"./Constants":35,"./Timers":54,debug:12,events:11,util:23}],56:[function(e,t,n){function r(e,t){if(c("new()"),this.status=f.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=t||f.recovery_options,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1,"undefined"==typeof e)throw new TypeError("Invalid argument. undefined 'sockets' argument");e instanceof Array||(e=[e]),e.forEach(function(e){if(!u.isSocket(e.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(e.weight&&!Number(e.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:e.socket,weight:e.weight||0,status:f.SOCKET_STATUS_READY})},this),Object.defineProperties(this,{via_transport:{get:function(){return this.socket.via_transport}},url:{get:function(){return this.socket.url}},sip_uri:{get:function(){return this.socket.sip_uri}}}),l.call(this)}function i(){this.recover_attempts=0,this.status=f.STATUS_CONNECTED,null!==this.recovery_timer&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}function o(e,t,n){this.status=f.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:e,code:t,reason:n}),this.close_requested||(e&&(this.socket.status=f.SOCKET_STATUS_ERROR),a.call(this,e))}function s(e){if("\r\n"===e)return void c("received message with CRLF Keep Alive response");if("string"!=typeof e){try{e=String.fromCharCode.apply(null,new Uint8Array(e))}catch(t){return void c("received binary message failed to be converted into string, message discarded")}c("received binary message:\n\n"+e+"\n")}else c("received text message:\n\n"+e+"\n");this.ondata({transport:this,message:e})}function a(){var e,t=this;this.recover_attempts+=1,e=Math.floor(Math.random()*Math.pow(2,this.recover_attempts)+1),ethis.recovery_options.max_interval&&(e=this.recovery_options.max_interval),c("reconnection attempt: "+this.recover_attempts+". next connection attempt in "+e+" seconds"),this.recovery_timer=setTimeout(function(){t.close_requested||t.isConnected()||t.isConnecting()||(l.call(t),t.connect())},1e3*e)}function l(){var e=[];if(this.sockets.forEach(function(t){t.status!==f.SOCKET_STATUS_ERROR&&(0===e.length?e.push(t):t.weight>e[0].weight?e=[t]:t.weight===e[0].weight&&e.push(t))}),0===e.length)return this.sockets.forEach(function(e){e.status=f.SOCKET_STATUS_READY}),void l.call(this);var t=Math.floor(Math.random()*e.length);this.socket=e[t].socket}t.exports=r;var u=e("./Socket"),c=e("debug")("PlivoSIP:Transport"),d=e("debug")("PlivoSIP:ERROR:Transport"),f={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:2,max_interval:30}};r.prototype.connect=function(){return c("connect()"),this.isConnected()?void c("Transport is already connected"):this.isConnecting()?void c("Transport is connecting"):(this.close_requested=!1,this.status=f.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),void(this.close_requested||(this.socket.onconnect=i.bind(this),this.socket.ondisconnect=o.bind(this),this.socket.ondata=s.bind(this),this.socket.connect())))},r.prototype.disconnect=function(){c("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=f.STATUS_DISCONNECTED,null!==this.recovery_timer&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=function(){},this.socket.ondisconnect=function(){},this.socket.ondata=function(){},this.socket.disconnect(),this.ondisconnect()},r.prototype.send=function(e){if(c("send()"),!this.isConnected())return d("unable to send message, transport is not connected"),!1;var t=e.toString();return c("sending message:\n\n"+t+"\n"),this.socket.send(t)},r.prototype.isConnected=function(){return this.status===f.STATUS_CONNECTED},r.prototype.isConnecting=function(){return this.status===f.STATUS_CONNECTING}},{"./Socket":53,debug:12}],57:[function(e,t,n){function r(e){if(this.cache={credentials:{}},this.configuration={},this.dynConfiguration={},this.dialogs={},this.applicants={},this.sessions={},this.transport=null,this.contact=null,this.status=l.STATUS_INIT,this.error=null,this.transactions={nist:{},nict:{},ist:{},ict:{}},this.data={},this.closeTimer=null,Object.defineProperties(this,{transactionsCount:{get:function(){var e,t=["nist","nict","ist","ict"],n=0;for(e in t)n+=Object.keys(this.transactions[t[e]]).length;return n}},nictTransactionsCount:{get:function(){return Object.keys(this.transactions.nict).length}},nistTransactionsCount:{get:function(){return Object.keys(this.transactions.nist).length}},ictTransactionsCount:{get:function(){return Object.keys(this.transactions.ict).length}},istTransactionsCount:{get:function(){return Object.keys(this.transactions.ist).length}}}),void 0===e)throw new TypeError("Not enough arguments");try{this.loadConfig(e)}catch(t){throw this.status=l.STATUS_NOT_READY,this.error=l.CONFIGURATION_ERROR,t}this._registrator=new p(this),c.EventEmitter.call(this)}function i(e){this.emit("connecting",e)}function o(e){this.status!==l.STATUS_USER_CLOSED&&(this.status=l.STATUS_READY,this.error=null,this.emit("connected",e),this.dynConfiguration.register&&this._registrator.register())}function s(e){var t,n,r,i=["nict","ict","nist","ist"];for(r=i.length,t=0;t"}};for(t in h)r.configuration_skeleton[t].value=h[t];Object.defineProperties(this.configuration,r.configuration_skeleton);for(t in h)r.configuration_skeleton[t].value="";for(t in h)switch(t){case"uri":case"registrar_server":d("- "+t+": "+h[t]);break;case"password":case"ha1":d("- "+t+": NOT SHOWN");break;default:d("- "+t+": "+JSON.stringify(h[t]))}},r.configuration_skeleton=function(){var e,t,n,r={},i=["plivosip_id","hostport_params","uri","authorization_user","contact_uri","display_name","instance_id","no_answer_timeout","session_timers","password","realm","ha1","register_expires","registrar_server","sockets","use_preloaded_route","via_core_value","via_host"],o=["password","realm","ha1","display_name"];for(e in i)t=i[e],n=o.indexOf(t)!==-1,r[t]={value:"",writable:n,configurable:!1};return r.register={value:"",writable:!0,configurable:!1},r}(),r.configuration_check={mandatory:{uri:function(e){var t;return/^sip:/i.test(e)||(e=h.SIP+":"+e),t=T.parse(e),t&&t.user?t:void 0}},optional:{authorization_user:function(e){return C.parse('"'+e+'"',"quoted_string")===-1?void 0:e},connection_recovery_max_interval:function(e){var t;if(_.isDecimal(e)&&(t=Number(e),t>0))return t},connection_recovery_min_interval:function(e){var t;if(_.isDecimal(e)&&(t=Number(e),t>0))return t},contact_uri:function(e){if("string"==typeof e){var t=C.parse(e,"SIP_URI");if(t!==-1)return t}},display_name:function(e){return C.parse('"'+e+'"',"display_name")===-1?void 0:e},instance_id:function(e){return/^uuid:/i.test(e)&&(e=e.substr(5)),C.parse(e,"uuid")===-1?void 0:e},no_answer_timeout:function(e){var t;if(_.isDecimal(e)&&(t=Number(e),t>0))return t},session_timers:function(e){if("boolean"==typeof e)return e},password:function(e){return String(e)},realm:function(e){return String(e)},ha1:function(e){return String(e)},register:function(e){if("boolean"==typeof e)return e},register_expires:function(e){var t;if(_.isDecimal(e)&&(t=Number(e),t>0))return t},registrar_server:function(e){var t;return/^sip:/i.test(e)||(e=h.SIP+":"+e),t=T.parse(e),t?t.user?void 0:t:void 0},sockets:function(e){var t,n;if(b.isSocket(e))e=[{socket:e}];else{if(!Array.isArray(e)||!e.length)return;for(n=e.length,t=0;t0&&(r+="?"+i.join("&")),r},toAor:function(e){var t;return t=this.scheme+":",this.user&&(t+=o.escapeUser(this.user)+"@"),t+=this.host,e&&(this.port||0===this.port)&&(t+=":"+this.port),t}},r.parse=function(e){return e=s.parse(e,"SIP_URI"),e!==-1?e:void 0}},{"./Constants":35,"./Grammar":40,"./Utils":59}],59:[function(e,t,n){var r={};t.exports=r;var i=e("./Constants"),o=e("./URI"),s=e("./Grammar");r.str_utf8_length=function(e){return unescape(encodeURIComponent(e)).length},r.isFunction=function(e){return void 0!==e&&"[object Function]"===Object.prototype.toString.call(e)},r.isString=function(e){return void 0!==e&&"[object String]"===Object.prototype.toString.call(e)},r.isDecimal=function(e){return!isNaN(e)&&parseFloat(e)===parseInt(e,10)},r.isEmpty=function(e){if(null===e||""===e||void 0===e||Array.isArray(e)&&0===e.length||"number"==typeof e&&isNaN(e))return!0},r.hasMethods=function(e){for(var t,n=1;t=arguments[n++];)if(this.isFunction(e[t]))return!1;return!0},r.createRandomToken=function(e,t){var n,r,i="";for(t=t||32,n=0;n>>32-t}function n(e,t){var n,r,i,o,s;return i=2147483648&e,o=2147483648&t,n=1073741824&e,r=1073741824&t,s=(1073741823&e)+(1073741823&t),n&r?2147483648^s^i^o:n|r?1073741824&s?3221225472^s^i^o:1073741824^s^i^o:s^i^o; +}function r(e,t,n){return e&t|~e&n}function i(e,t,n){return e&n|t&~n}function o(e,t,n){return e^t^n}function s(e,t,n){return t^(e|~n)}function a(e,i,o,s,a,l,u){return e=n(e,n(n(r(i,o,s),a),u)),n(t(e,l),i)}function l(e,r,o,s,a,l,u){return e=n(e,n(n(i(r,o,s),a),u)),n(t(e,l),r)}function u(e,r,i,s,a,l,u){return e=n(e,n(n(o(r,i,s),a),u)),n(t(e,l),r)}function c(e,r,i,o,a,l,u){return e=n(e,n(n(s(r,i,o),a),u)),n(t(e,l),r)}function d(e){for(var t,n=e.length,r=n+8,i=(r-r%64)/64,o=16*(i+1),s=new Array(o-1),a=0,l=0;l>>29,s}function f(e){var t,n,r="",i="";for(n=0;n<=3;n++)t=e>>>8*n&255,i="0"+t.toString(16),r+=i.substr(i.length-2,2);return r}function h(e){e=e.replace(/\r\n/g,"\n");for(var t="",n=0;n127&&r<2048?(t+=String.fromCharCode(r>>6|192),t+=String.fromCharCode(63&r|128)):(t+=String.fromCharCode(r>>12|224),t+=String.fromCharCode(r>>6&63|128),t+=String.fromCharCode(63&r|128))}return t}var p,v,g,m,y,b,_,S,T,C=[],w=7,E=12,k=17,R=22,I=5,P=9,A=14,O=20,M=4,D=11,x=16,N=23,F=6,U=10,j=15,L=21;for(e=h(e),C=d(e),b=1732584193,_=4023233417,S=2562383102,T=271733878,p=0;p1)return v("more than one Via header field present in the response, dropping the response"),!1}function u(){var e=y.str_utf8_length(f.body),t=f.getHeader("content-length");if(e0;){var t=e.shift();if("function"==typeof t){var n=e.shift(),r=e.shift();t.call(n,r)}else t._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},t.exports=r,t.exports.firstLineError=a},{"./queue":26,"./schedule":29,"./util":36}],3:[function(e,t,n){"use strict";t.exports=function(e,t,n,r){var i=!1,o=function(e,t){this._reject(t)},s=function(e,t){t.promiseRejectionQueued=!0,t.bindingPromise._then(o,o,null,this,e)},a=function(e,t){0==(50397184&this._bitField)&&this._resolveCallback(t.target)},l=function(e,t){t.promiseRejectionQueued||this._reject(e)};e.prototype.bind=function(o){i||(i=!0,e.prototype._propagateFrom=r.propagateFromFunction(),e.prototype._boundValue=r.boundValueFunction());var u=n(o),c=new e(t);c._propagateFrom(this,1);var d=this._target();if(c._setBoundTo(u),u instanceof e){var f={promiseRejectionQueued:!1,promise:c,target:d,bindingPromise:u};d._then(t,s,void 0,c,f),u._then(a,l,void 0,c,f),c._setOnCancel(u)}else c._resolveCallback(d);return c},e.prototype._setBoundTo=function(e){void 0!==e?(this._bitField=2097152|this._bitField,this._boundTo=e):this._bitField=-2097153&this._bitField},e.prototype._isBound=function(){return 2097152==(2097152&this._bitField)},e.bind=function(t,n){return e.resolve(n).bind(t)}}},{}],4:[function(e,t,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(e){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=e("./promise")();o.noConflict=r,t.exports=o},{"./promise":22}],5:[function(e,t,n){"use strict";var r=Object.create;if(r){var i=r(null),o=r(null);i[" size"]=o[" size"]=0}t.exports=function(t){function n(e,n){var r;if(null!=e&&(r=e[n]),"function"!=typeof r){var i="Object "+a.classString(e)+" has no method '"+a.toString(n)+"'";throw new t.TypeError(i)}return r}function r(e){return n(e,this.pop()).apply(e,this)}function i(e){return e[this]}function o(e){var t=+this;return t<0&&(t=Math.max(0,t+e.length)),e[t]}var s,a=e("./util"),l=a.canEvaluate;a.isIdentifier,t.prototype.call=function(e){var t=[].slice.call(arguments,1);return t.push(e),this._then(r,void 0,void 0,t,void 0)},t.prototype.get=function(e){var t,n="number"==typeof e;if(n)t=o;else if(l){var r=s(e);t=null!==r?r:i}else t=i;return this._then(t,void 0,void 0,e,void 0)}}},{"./util":36}],6:[function(e,t,n){"use strict";t.exports=function(t,n,r,i){var o=e("./util"),s=o.tryCatch,a=o.errorObj,l=t._async;t.prototype["break"]=t.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var e=this,t=e;e._isCancellable();){if(!e._cancelBy(t)){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}var n=e._cancellationParent;if(null==n||!n._isCancellable()){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}e._isFollowing()&&e._followee().cancel(),e._setWillBeCancelled(),t=e,e=n}},t.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},t.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},t.prototype._cancelBy=function(e){return e===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},t.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},t.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),l.invoke(this._cancelPromises,this,void 0))},t.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},t.prototype._unsetOnCancel=function(){this._onCancelField=void 0},t.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},t.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},t.prototype._doInvokeOnCancel=function(e,t){if(o.isArray(e))for(var n=0;n=0)return o[e]}var i=!1,o=[];return e.prototype._promiseCreated=function(){},e.prototype._pushContext=function(){},e.prototype._popContext=function(){return null},e._peekContext=e.prototype._peekContext=function(){},t.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},t.prototype._popContext=function(){if(void 0!==this._trace){var e=o.pop(),t=e._promiseCreated;return e._promiseCreated=null,t}return null},t.CapturedTrace=null,t.create=n,t.deactivateLongStackTraces=function(){},t.activateLongStackTraces=function(){var n=e.prototype._pushContext,o=e.prototype._popContext,s=e._peekContext,a=e.prototype._peekContext,l=e.prototype._promiseCreated;t.deactivateLongStackTraces=function(){e.prototype._pushContext=n,e.prototype._popContext=o,e._peekContext=s,e.prototype._peekContext=a,e.prototype._promiseCreated=l,i=!1},i=!0,e.prototype._pushContext=t.prototype._pushContext,e.prototype._popContext=t.prototype._popContext,e._peekContext=e.prototype._peekContext=r,e.prototype._promiseCreated=function(){var e=this._peekContext();e&&null==e._promiseCreated&&(e._promiseCreated=this)}},t}},{}],9:[function(t,n,r){"use strict";n.exports=function(n,r){function i(e,t){return{promise:t}}function o(){return!1}function s(e,t,n){var r=this;try{e(t,n,function(e){if("function"!=typeof e)throw new TypeError("onCancel must be a function, got: "+L.toString(e));r._attachCancellationCallback(e)})}catch(e){return e}}function a(e){if(!this._isCancellable())return this;var t=this._onCancel();void 0!==t?L.isArray(t)?t.push(e):this._setOnCancel([t,e]):this._setOnCancel(e)}function l(){return this._onCancelField}function u(e){this._onCancelField=e}function c(){this._cancellationParent=void 0,this._onCancelField=void 0}function d(e,t){if(0!=(1&t)){this._cancellationParent=e;var n=e._branchesRemainingToCancel;void 0===n&&(n=0),e._branchesRemainingToCancel=n+1}0!=(2&t)&&e._isBound()&&this._setBoundTo(e._boundTo)}function f(e,t){0!=(2&t)&&e._isBound()&&this._setBoundTo(e._boundTo)}function h(){var e=this._boundTo;return void 0!==e&&e instanceof n?e.isFulfilled()?e.value():void 0:e}function p(){this._trace=new M(this._peekContext())}function v(e,t){if(H(e)){var n=this._trace;if(void 0!==n&&t&&(n=n._parent),void 0!==n)n.attachExtraTrace(e);else if(!e.__stackCleaned__){var r=w(e);L.notEnumerableProp(e,"stack",r.message+"\n"+r.stack.join("\n")),L.notEnumerableProp(e,"__stackCleaned__",!0)}}}function g(e,t,n,r,i){if(void 0===e&&null!==t&&X){if(void 0!==i&&i._returnedNonUndefined())return;if(0==(65535&r._bitField))return;n&&(n+=" ");var o="",s="";if(t._trace){for(var a=t._trace.stack.split("\n"),l=T(a),u=l.length-1;u>=0;--u){var c=l[u];if(!q.test(c)){var d=c.match(G);d&&(o="at "+d[1]+":"+d[2]+":"+d[3]+" ");break}}if(l.length>0)for(var f=l[0],u=0;u0&&(s="\n"+a[u-1]);break}}var h="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;r._warn(h,!0,t)}}function m(e,t){var n=e+" is deprecated and will be removed in a future version.";return t&&(n+=" Use "+t+" instead."),y(n)}function y(e,t,r){if(se.warnings){var i,o=new j(e);if(t)r._attachExtraTrace(o);else if(se.longStackTraces&&(i=n._peekContext()))i.attachExtraTrace(o);else{var s=w(o);o.stack=s.message+"\n"+s.stack.join("\n")}te("warning",o)||E(o,"",!0)}}function b(e,t){for(var n=0;n=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var l=r[a];if(t[i]!==l)break;t.pop(),i--}t=r}}function T(e){for(var t=[],n=0;n0&&"SyntaxError"!=e.name&&(t=t.slice(n)),t}function w(e){var t=e.stack,n=e.toString();return t="string"==typeof t&&t.length>0?C(e):[" (No stack trace)"],{message:n,stack:"SyntaxError"==e.name?t:T(t)}}function E(e,t,n){if("undefined"!=typeof console){var r;if(L.isObject(e)){var i=e.stack;r=t+V(i,e)}else r=t+String(e);"function"==typeof N?N(r,n):"function"!=typeof console.log&&"object"!=typeof console.log||console.log(r)}}function k(e,t,n,r){var i=!1;try{"function"==typeof t&&(i=!0,"rejectionHandled"===e?t(r):t(n,r))}catch(e){U.throwLater(e)}"unhandledRejection"===e?te(e,n,r)||i||E(n,"Unhandled rejection "):te(e,r)}function R(e){var t;if("function"==typeof e)t="[function "+(e.name||"anonymous")+"]";else{if(t=e&&"function"==typeof e.toString?e.toString():L.toString(e),/\[object [a-zA-Z0-9$_]+\]/.test(t))try{t=JSON.stringify(e)}catch(e){}0===t.length&&(t="(empty array)")}return"(<"+I(t)+">, no stack trace)"}function I(e){return e.length<41?e:e.substr(0,38)+"..."}function P(){return"function"==typeof oe}function A(e){var t=e.match(ie);if(t)return{fileName:t[1],line:parseInt(t[2],10)}}function O(e,t){if(P()){for(var n,r,i=e.stack.split("\n"),o=t.stack.split("\n"),s=-1,a=-1,l=0;l=a||(re=function(e){if(B.test(e))return!0;var t=A(e);return!!(t&&t.fileName===n&&s<=t.line&&t.line<=a)})}}function M(e){this._parent=e,this._promisesCreated=0;var t=this._length=1+(void 0===e?0:e._length);oe(this,M),t>32&&this.uncycle()}var D,x,N,F=n._getDomain,U=n._async,j=t("./errors").Warning,L=t("./util"),H=L.canAttachTrace,B=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,q=/\((?:timers\.js):\d+:\d+\)/,G=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,W=null,V=null,z=!1,K=!(0==L.env("BLUEBIRD_DEBUG")),J=!(0==L.env("BLUEBIRD_WARNINGS")||!K&&!L.env("BLUEBIRD_WARNINGS")),Q=!(0==L.env("BLUEBIRD_LONG_STACK_TRACES")||!K&&!L.env("BLUEBIRD_LONG_STACK_TRACES")),X=0!=L.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(J||!!L.env("BLUEBIRD_W_FORGOTTEN_RETURN"));n.prototype.suppressUnhandledRejections=function(){var e=this._target();e._bitField=-1048577&e._bitField|524288},n.prototype._ensurePossibleRejectionHandled=function(){if(0==(524288&this._bitField)){this._setRejectionIsUnhandled();var e=this;setTimeout(function(){e._notifyUnhandledRejection()},1)}},n.prototype._notifyUnhandledRejectionIsHandled=function(){k("rejectionHandled",D,void 0,this)},n.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},n.prototype._returnedNonUndefined=function(){return 0!=(268435456&this._bitField)},n.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var e=this._settledValue();this._setUnhandledRejectionIsNotified(),k("unhandledRejection",x,e,this)}},n.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},n.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},n.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},n.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},n.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},n.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},n.prototype._warn=function(e,t,n){return y(e,t,n||this)},n.onPossiblyUnhandledRejection=function(e){var t=F();x="function"==typeof e?null===t?e:L.domainBind(t,e):void 0},n.onUnhandledRejectionHandled=function(e){var t=F();D="function"==typeof e?null===t?e:L.domainBind(t,e):void 0};var $=function(){};n.longStackTraces=function(){if(U.haveItemsQueued()&&!se.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!se.longStackTraces&&P()){var e=n.prototype._captureStackTrace,t=n.prototype._attachExtraTrace;se.longStackTraces=!0,$=function(){if(U.haveItemsQueued()&&!se.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");n.prototype._captureStackTrace=e,n.prototype._attachExtraTrace=t,r.deactivateLongStackTraces(),U.enableTrampoline(),se.longStackTraces=!1},n.prototype._captureStackTrace=p,n.prototype._attachExtraTrace=v,r.activateLongStackTraces(),U.disableTrampolineIfNecessary()}},n.hasLongStackTraces=function(){return se.longStackTraces&&P()};var Y=function(){try{if("function"==typeof CustomEvent){var e=new CustomEvent("CustomEvent");return L.global.dispatchEvent(e),function(e,t){var n=new CustomEvent(e.toLowerCase(),{detail:t,cancelable:!0});return!L.global.dispatchEvent(n)}}if("function"==typeof Event){var e=new Event("CustomEvent");return L.global.dispatchEvent(e),function(e,t){var n=new Event(e.toLowerCase(),{cancelable:!0});return n.detail=t,!L.global.dispatchEvent(n)}}var e=document.createEvent("CustomEvent");return e.initCustomEvent("testingtheevent",!1,!0,{}),L.global.dispatchEvent(e),function(e,t){var n=document.createEvent("CustomEvent");return n.initCustomEvent(e.toLowerCase(),!1,!0,t),!L.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Z=function(){return L.isNode?function(){return e.emit.apply(e,arguments)}:L.global?function(e){var t="on"+e.toLowerCase(),n=L.global[t];return!!n&&(n.apply(L.global,[].slice.call(arguments,1)),!0)}:function(){return!1}}(),ee={promiseCreated:i,promiseFulfilled:i,promiseRejected:i,promiseResolved:i,promiseCancelled:i,promiseChained:function(e,t,n){return{promise:t,child:n}},warning:function(e,t){return{warning:t}},unhandledRejection:function(e,t,n){return{reason:t,promise:n}},rejectionHandled:i},te=function(e){var t=!1;try{t=Z.apply(null,arguments)}catch(e){U.throwLater(e),t=!0}var n=!1;try{n=Y(e,ee[e].apply(null,arguments))}catch(e){U.throwLater(e),n=!0}return n||t};n.config=function(e){if(e=Object(e),"longStackTraces"in e&&(e.longStackTraces?n.longStackTraces():!e.longStackTraces&&n.hasLongStackTraces()&&$()),"warnings"in e){var t=e.warnings;se.warnings=!!t,X=se.warnings,L.isObject(t)&&"wForgottenReturn"in t&&(X=!!t.wForgottenReturn)}if("cancellation"in e&&e.cancellation&&!se.cancellation){if(U.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");n.prototype._clearCancellationData=c,n.prototype._propagateFrom=d,n.prototype._onCancel=l,n.prototype._setOnCancel=u,n.prototype._attachCancellationCallback=a,n.prototype._execute=s,ne=d,se.cancellation=!0}return"monitoring"in e&&(e.monitoring&&!se.monitoring?(se.monitoring=!0,n.prototype._fireEvent=te):!e.monitoring&&se.monitoring&&(se.monitoring=!1,n.prototype._fireEvent=o)),n},n.prototype._fireEvent=o,n.prototype._execute=function(e,t,n){try{e(t,n)}catch(e){return e}},n.prototype._onCancel=function(){},n.prototype._setOnCancel=function(e){},n.prototype._attachCancellationCallback=function(e){},n.prototype._captureStackTrace=function(){},n.prototype._attachExtraTrace=function(){},n.prototype._clearCancellationData=function(){},n.prototype._propagateFrom=function(e,t){};var ne=f,re=function(){return!1},ie=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;L.inherits(M,Error),r.CapturedTrace=M,M.prototype.uncycle=function(){var e=this._length;if(!(e<2)){for(var t=[],n={},r=0,i=this;void 0!==i;++r)t.push(i),i=i._parent;e=this._length=r;for(var r=e-1;r>=0;--r){var o=t[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;r0&&(t[a-1]._parent=void 0,t[a-1]._length=1),t[r]._parent=void 0,t[r]._length=1;var l=r>0?t[r-1]:this;a=0;--c)t[c]._length=u,u++;return}}}},M.prototype.attachExtraTrace=function(e){if(!e.__stackCleaned__){this.uncycle();for(var t=w(e),n=t.message,r=[t.stack],i=this;void 0!==i;)r.push(T(i.stack.split("\n"))),i=i._parent;S(r),_(r),L.notEnumerableProp(e,"stack",b(n,r)),L.notEnumerableProp(e,"__stackCleaned__",!0)}};var oe=function(){var e=/^\s*at\s*/,t=function(e,t){return"string"==typeof e?e:void 0!==t.name&&void 0!==t.message?t.toString():R(t)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,W=e,V=t;var n=Error.captureStackTrace;return re=function(e){return B.test(e)},function(e,t){Error.stackTraceLimit+=6,n(e,t),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return W=/@/,V=t,z=!0,function(e){e.stack=(new Error).stack};var i;try{throw new Error}catch(e){i="stack"in e}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(V=function(e,t){return"string"==typeof e?e:"object"!=typeof t&&"function"!=typeof t||void 0===t.name||void 0===t.message?R(t):t.toString()},null):(W=e,V=t,function(e){Error.stackTraceLimit+=6;try{throw new Error}catch(t){e.stack=t.stack}Error.stackTraceLimit-=6})}();"undefined"!=typeof console&&void 0!==console.warn&&(N=function(e){console.warn(e)},L.isNode&&e.stderr.isTTY?N=function(e,t){var n=t?"\x1b[33m":"\x1b[31m";console.warn(n+e+"\x1b[0m\n")}:L.isNode||"string"!=typeof(new Error).stack||(N=function(e,t){console.warn("%c"+e,t?"color: darkorange":"color: red")}));var se={warnings:J,longStackTraces:!1,cancellation:!1,monitoring:!1};return Q&&n.longStackTraces(),{longStackTraces:function(){return se.longStackTraces},warnings:function(){return se.warnings},cancellation:function(){return se.cancellation},monitoring:function(){return se.monitoring},propagateFromFunction:function(){return ne},boundValueFunction:function(){return h},checkForgottenReturns:g,setBounds:O,warn:y,deprecated:m,CapturedTrace:M,fireDomEvent:Y,fireGlobalEvent:Z}}},{"./errors":12,"./util":36}],10:[function(e,t,n){"use strict";t.exports=function(e){function t(){return this.value}function n(){throw this.reason}e.prototype["return"]=e.prototype.thenReturn=function(n){return n instanceof e&&n.suppressUnhandledRejections(),this._then(t,void 0,void 0,{value:n},void 0)},e.prototype["throw"]=e.prototype.thenThrow=function(e){return this._then(n,void 0,void 0,{reason:e},void 0)},e.prototype.catchThrow=function(e){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:e},void 0);var t=arguments[1],r=function(){throw t};return this.caught(e,r)},e.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof e&&n.suppressUnhandledRejections(),this._then(void 0,t,void 0,{value:n},void 0);var r=arguments[1];r instanceof e&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(e,t,n){"use strict";t.exports=function(e,t){function n(){return o(this)}function r(e,n){return i(e,n,t,t)}var i=e.reduce,o=e.all; +e.prototype.each=function(e){return i(this,e,t,0)._then(n,void 0,void 0,this,void 0)},e.prototype.mapSeries=function(e){return i(this,e,t,t)},e.each=function(e,r){return i(e,r,t,0)._then(n,void 0,void 0,e,void 0)},e.mapSeries=r}},{}],12:[function(e,t,n){"use strict";function r(e,t){function n(r){return this instanceof n?(d(this,"message","string"==typeof r?r:t),d(this,"name",e),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this),void 0):new n(r)}return c(n,Error),n}function i(e){return this instanceof i?(d(this,"name","OperationalError"),d(this,"message",e),this.cause=e,this.isOperational=!0,e instanceof Error?(d(this,"message",e.message),d(this,"stack",e.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),void 0):new i(e)}var o,s,a=e("./es5"),l=a.freeze,u=e("./util"),c=u.inherits,d=u.notEnumerableProp,f=r("Warning","warning"),h=r("CancellationError","cancellation error"),p=r("TimeoutError","timeout error"),v=r("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(e){o=r("TypeError","type error"),s=r("RangeError","range error")}for(var g="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),m=0;m1?e.cancelPromise._reject(t):e.cancelPromise._cancel(),e.cancelPromise=null,!0)}function a(){return u.call(this,this.promise._target()._settledValue())}function l(e){if(!s(this,e))return f.e=e,f}function u(e){var i=this.promise,u=this.handler;if(!this.called){this.called=!0;var c=this.isFinallyHandler()?u.call(i._boundValue()):u.call(i._boundValue(),e);if(c===r)return c;if(void 0!==c){i._setReturnedNonUndefined();var h=n(c,i);if(h instanceof t){if(null!=this.cancelPromise){if(h._isCancelled()){var p=new d("late cancellation observer");return i._attachExtraTrace(p),f.e=p,f}h.isPending()&&h._attachCancellationCallback(new o(this))}return h._then(a,l,void 0,this,void 0)}}}return i.isRejected()?(s(this),f.e=e,f):(s(this),e)}var c=e("./util"),d=t.CancellationError,f=c.errorObj,h=e("./catch_filter")(r);return i.prototype.isFinallyHandler=function(){return 0===this.type},o.prototype._resultCancelled=function(){s(this.finallyHandler)},t.prototype._passThrough=function(e,t,n,r){return"function"!=typeof e?this.then():this._then(n,r,void 0,new i(this,t,e),void 0)},t.prototype.lastly=t.prototype["finally"]=function(e){return this._passThrough(e,0,u,u)},t.prototype.tap=function(e){return this._passThrough(e,1,u)},t.prototype.tapCatch=function(e){var n=arguments.length;if(1===n)return this._passThrough(e,1,void 0,u);var r,i=new Array(n-1),o=0;for(r=0;r0&&"function"==typeof arguments[t]){e=arguments[t];var r}var i=[].slice.call(arguments);e&&i.pop();var r=new n(i).promise();return void 0!==e?r.spread(e):r}}},{"./util":36}],18:[function(e,t,n){"use strict";t.exports=function(t,n,r,i,o,s){function a(e,t,n,r){this.constructor$(e),this._promise._captureStackTrace();var i=u();this._callback=null===i?t:c.domainBind(i,t),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],h.invoke(this._asyncInit,this,void 0)}function l(e,n,i,o){if("function"!=typeof n)return r("expecting a function but got "+c.classString(n));var s=0;if(void 0!==i){if("object"!=typeof i||null===i)return t.reject(new TypeError("options argument must be an object but it is "+c.classString(i)));if("number"!=typeof i.concurrency)return t.reject(new TypeError("'concurrency' must be a number but it is "+c.classString(i.concurrency)));s=i.concurrency}return s="number"==typeof s&&isFinite(s)&&s>=1?s:0,new a(e,n,s,o).promise()}var u=t._getDomain,c=e("./util"),d=c.tryCatch,f=c.errorObj,h=t._async;c.inherits(a,n),a.prototype._asyncInit=function(){this._init$(void 0,-2)},a.prototype._init=function(){},a.prototype._promiseFulfilled=function(e,n){var r=this._values,o=this.length(),a=this._preservedValues,l=this._limit;if(n<0){if(n=-1*n-1,r[n]=e,l>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(l>=1&&this._inFlight>=l)return r[n]=e,this._queue.push(n),!1;null!==a&&(a[n]=e);var u=this._promise,c=this._callback,h=u._boundValue();u._pushContext();var p=d(c).call(h,e,n,o),v=u._popContext();if(s.checkForgottenReturns(p,v,null!==a?"Promise.filter":"Promise.map",u),p===f)return this._reject(p.e),!0;var g=i(p,this._promise);if(g instanceof t){g=g._target();var m=g._bitField;if(0==(50397184&m))return l>=1&&this._inFlight++,r[n]=g,g._proxy(this,-1*(n+1)),!1;if(0==(33554432&m))return 0!=(16777216&m)?(this._reject(g._reason()),!0):(this._cancel(),!0);p=g._value()}r[n]=p}return++this._totalResolved>=o&&(null!==a?this._filter(r,a):this._resolve(r),!0)},a.prototype._drainQueue=function(){for(var e=this._queue,t=this._limit,n=this._values;e.length>0&&this._inFlight1){o.deprecated("calling Promise.try with more than 1 argument");var u=arguments[1],c=arguments[2];l=s.isArray(u)?a(e).apply(c,u):a(e).call(c,u)}else l=a(e)();var d=r._popContext();return o.checkForgottenReturns(l,d,"Promise.try",r),r._resolveFromSyncValue(l),r},t.prototype._resolveFromSyncValue=function(e){e===s.errorObj?this._rejectCallback(e.e,!1):this._resolveCallback(e,!0)}}},{"./util":36}],20:[function(e,t,n){"use strict";function r(e){return e instanceof Error&&c.getPrototypeOf(e)===Error.prototype}function i(e){var t;if(r(e)){t=new u(e),t.name=e.name,t.message=e.message,t.stack=e.stack;for(var n=c.keys(e),i=0;i1){var n,r=new Array(t-1),i=0;for(n=0;n0&&"function"!=typeof e&&"function"!=typeof t){var n=".then() only accepts functions but was passed: "+p.classString(e);arguments.length>1&&(n+=", "+p.classString(t)),this._warn(n)}return this._then(e,t,void 0,void 0,void 0)},o.prototype.done=function(e,t){this._then(e,t,void 0,void 0,void 0)._setIsFinal()},o.prototype.spread=function(e){return"function"!=typeof e?f("expecting a function but got "+p.classString(e)):this.all()._then(e,void 0,void 0,T,void 0)},o.prototype.toJSON=function(){var e={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(e.fulfillmentValue=this.value(),e.isFulfilled=!0):this.isRejected()&&(e.rejectionReason=this.reason(),e.isRejected=!0),e},o.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new E(this).promise()},o.prototype.error=function(e){return this.caught(p.originatesFromRejection,e)},o.getNewLibraryCopy=n.exports,o.is=function(e){return e instanceof o},o.fromNode=o.fromCallback=function(e){var t=new o(S);t._captureStackTrace();var n=arguments.length>1&&!!Object(arguments[1]).multiArgs,r=D(e)(O(t,n));return r===M&&t._rejectCallback(r.e,!0),t._isFateSealed()||t._setAsyncGuaranteed(),t},o.all=function(e){return new E(e).promise()},o.cast=function(e){var t=w(e);return t instanceof o||(t=new o(S),t._captureStackTrace(),t._setFulfilled(),t._rejectionHandler0=e),t},o.resolve=o.fulfilled=o.cast,o.reject=o.rejected=function(e){var t=new o(S);return t._captureStackTrace(),t._rejectCallback(e,!0),t},o.setScheduler=function(e){if("function"!=typeof e)throw new b("expecting a function but got "+p.classString(e));return m.setScheduler(e)},o.prototype._then=function(e,t,n,r,i){var s=void 0!==i,a=s?i:new o(S),l=this._target(),c=l._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===r&&0!=(2097152&this._bitField)&&(r=0!=(50397184&c)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var d=u();if(0!=(50397184&c)){var f,h,v=l._settlePromiseCtx;0!=(33554432&c)?(h=l._rejectionHandler0,f=e):0!=(16777216&c)?(h=l._fulfillmentHandler0,f=t,l._unsetRejectionIsUnhandled()):(v=l._settlePromiseLateCancellationObserver,h=new _("late cancellation observer"),l._attachExtraTrace(h),f=t),m.invoke(v,l,{handler:null===d?f:"function"==typeof f&&p.domainBind(d,f),promise:a,receiver:r,value:h})}else l._addCallbacks(e,t,a,r,d);return a},o.prototype._length=function(){return 65535&this._bitField},o.prototype._isFateSealed=function(){return 0!=(117506048&this._bitField)},o.prototype._isFollowing=function(){return 67108864==(67108864&this._bitField)},o.prototype._setLength=function(e){this._bitField=-65536&this._bitField|65535&e},o.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},o.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},o.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},o.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},o.prototype._isFinal=function(){return(4194304&this._bitField)>0},o.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},o.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},o.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},o.prototype._setAsyncGuaranteed=function(){m.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},o.prototype._receiverAt=function(e){var t=0===e?this._receiver0:this[4*e-4+3];if(t!==h)return void 0===t&&this._isBound()?this._boundValue():t},o.prototype._promiseAt=function(e){return this[4*e-4+2]},o.prototype._fulfillmentHandlerAt=function(e){return this[4*e-4+0]},o.prototype._rejectionHandlerAt=function(e){return this[4*e-4+1]},o.prototype._boundValue=function(){},o.prototype._migrateCallback0=function(e){var t=(e._bitField,e._fulfillmentHandler0),n=e._rejectionHandler0,r=e._promise0,i=e._receiverAt(0);void 0===i&&(i=h),this._addCallbacks(t,n,r,i,null)},o.prototype._migrateCallbackAt=function(e,t){var n=e._fulfillmentHandlerAt(t),r=e._rejectionHandlerAt(t),i=e._promiseAt(t),o=e._receiverAt(t);void 0===o&&(o=h),this._addCallbacks(n,r,i,o,null)},o.prototype._addCallbacks=function(e,t,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof e&&(this._fulfillmentHandler0=null===i?e:p.domainBind(i,e)),"function"==typeof t&&(this._rejectionHandler0=null===i?t:p.domainBind(i,t));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof e&&(this[s+0]=null===i?e:p.domainBind(i,e)),"function"==typeof t&&(this[s+1]=null===i?t:p.domainBind(i,t))}return this._setLength(o+1),o},o.prototype._proxy=function(e,t){this._addCallbacks(void 0,void 0,t,e,null)},o.prototype._resolveCallback=function(e,t){if(0==(117506048&this._bitField)){if(e===this)return this._rejectCallback(c(),!1);var n=w(e,this);if(!(n instanceof o))return this._fulfill(e);t&&this._propagateFrom(n,2);var r=n._target();if(r===this)return void this._reject(c());var i=r._bitField;if(0==(50397184&i)){var s=this._length();s>0&&r._migrateCallback0(this);for(var a=1;a>>16)){if(e===this){var n=c();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=e,(65535&t)>0&&(0!=(134217728&t)?this._settlePromises():m.settlePromises(this))}},o.prototype._reject=function(e){var t=this._bitField;if(!((117506048&t)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=e,this._isFinal())return m.fatalError(e,p.isNode);(65535&t)>0?m.settlePromises(this):this._ensurePossibleRejectionHandled()}},o.prototype._fulfillPromises=function(e,t){for(var n=1;n0){if(0!=(16842752&e)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,e),this._rejectPromises(t,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,e),this._fulfillPromises(t,r)}this._setLength(0)}this._clearCancellationData()},o.prototype._settledValue=function(){var e=this._bitField;return 0!=(33554432&e)?this._rejectionHandler0:0!=(16777216&e)?this._fulfillmentHandler0:void 0},o.defer=o.pending=function(){return I.deprecated("Promise.defer","new Promise"),{promise:new o(S),resolve:s,reject:a}},p.notEnumerableProp(o,"_makeSelfResolutionError",c),t("./method")(o,S,w,f,I),t("./bind")(o,S,w,I),t("./cancel")(o,E,f,I),t("./direct_resolve")(o),t("./synchronous_inspection")(o),t("./join")(o,E,w,S,m,u),o.Promise=o,o.version="3.5.1",t("./map.js")(o,E,f,w,S,I),t("./call_get.js")(o),t("./using.js")(o,f,w,R,S,I),t("./timers.js")(o,S,I),t("./generators.js")(o,f,S,w,r,I),t("./nodeify.js")(o),t("./promisify.js")(o,S),t("./props.js")(o,E,w,f),t("./race.js")(o,S,w,f),t("./reduce.js")(o,E,f,w,S,I),t("./settle.js")(o,E,I),t("./some.js")(o,E,f),t("./filter.js")(o,S),t("./each.js")(o,S),t("./any.js")(o),p.toFastProperties(o),p.toFastProperties(o.prototype),l({a:1}),l({b:2}),l({c:3}),l(1),l(function(){}),l(void 0),l(!1),l(new o(S)),I.setBounds(g.firstLineError,p.lastLineError),o}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(e,t,n){"use strict";t.exports=function(t,n,r,i,o){function s(e){switch(e){case-2:return[];case-3:return{};case-6:return new Map}}function a(e){var r=this._promise=new t(n);e instanceof t&&r._propagateFrom(e,3),r._setOnCancel(this),this._values=e,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var l=e("./util");return l.isArray,l.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function u(e,n){var o=r(this._values,this._promise);if(o instanceof t){o=o._target();var a=o._bitField;if(this._values=o,0==(50397184&a))return this._promise._setAsyncGuaranteed(),o._then(u,this._reject,void 0,this,n);if(0==(33554432&a))return 0!=(16777216&a)?this._reject(o._reason()):this._cancel();o=o._value()}if(null===(o=l.asArray(o))){var c=i("expecting an array or an iterable object but got "+l.classString(o)).reason();return void this._promise._rejectCallback(c,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(s(n))):void this._iterate(o)},a.prototype._iterate=function(e){var n=this.getActualLength(e.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;a=this._length&&(this._resolve(this._values),!0)},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(e){return this._totalResolved++,this._reject(e),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var e=this._values;if(this._cancel(),e instanceof t)e.cancel();else for(var n=0;n=this._length){var n;if(this._isMap)n=f(this._values);else{n={};for(var r=this.length(),i=0,o=this.length();i>1},t.prototype.props=function(){return s(this)},t.props=function(e){return s(e)}}},{"./es5":13,"./util":36}],26:[function(e,t,n){"use strict";function r(e,t,n,r,i){for(var o=0;o=this._length&&(this._resolve(this._values),!0)},i.prototype._promiseFulfilled=function(e,t){var n=new o;return n._bitField=33554432,n._settledValueField=e,this._promiseResolved(t,n)},i.prototype._promiseRejected=function(e,t){var n=new o;return n._bitField=16777216,n._settledValueField=e,this._promiseResolved(t,n)},t.settle=function(e){return r.deprecated(".settle()",".reflect()"),new i(e).promise()},t.prototype.settle=function(){return t.settle(this)}}},{"./util":36}],31:[function(e,t,n){"use strict";t.exports=function(t,n,r){function i(e){this.constructor$(e),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(e,t){if((0|t)!==t||t<0)return r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new i(e),o=n.promise();return n.setHowMany(t),n.init(),o}var s=e("./util"),a=e("./errors").RangeError,l=e("./errors").AggregateError,u=s.isArray,c={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var e=u(this._values);!this._isResolved()&&e&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(e){this._howMany=e},i.prototype._promiseFulfilled=function(e){return this._addFulfilled(e),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},i.prototype._promiseRejected=function(e){return this._addRejected(e),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof t||null==this._values?this._cancel():(this._addRejected(c),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var e=new l,t=this.length();t0?this._reject(e):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(e){this._values.push(e)},i.prototype._addFulfilled=function(e){this._values[this._totalResolved++]=e},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(e){var t="Input array must contain at least "+this._howMany+" items but contains only "+e+" items";return new a(t)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},t.some=function(e,t){return o(e,t)},t.prototype.some=function(e){return o(this,e)},t._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(e,t,n){"use strict";t.exports=function(e){function t(e){void 0!==e?(e=e._target(),this._bitField=e._bitField,this._settledValueField=e._isFateSealed()?e._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}t.prototype._settledValue=function(){return this._settledValueField};var n=t.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=t.prototype.error=t.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=t.prototype.isFulfilled=function(){return 0!=(33554432&this._bitField)},o=t.prototype.isRejected=function(){return 0!=(16777216&this._bitField)},s=t.prototype.isPending=function(){return 0==(50397184&this._bitField)},a=t.prototype.isResolved=function(){return 0!=(50331648&this._bitField)};t.prototype.isCancelled=function(){return 0!=(8454144&this._bitField)},e.prototype.__isCancelled=function(){return 65536==(65536&this._bitField)},e.prototype._isCancelled=function(){return this._target().__isCancelled()},e.prototype.isCancelled=function(){return 0!=(8454144&this._target()._bitField)},e.prototype.isPending=function(){return s.call(this._target())},e.prototype.isRejected=function(){return o.call(this._target())},e.prototype.isFulfilled=function(){return i.call(this._target())},e.prototype.isResolved=function(){return a.call(this._target())},e.prototype.value=function(){return n.call(this._target())},e.prototype.reason=function(){var e=this._target();return e._unsetRejectionIsUnhandled(),r.call(e)},e.prototype._value=function(){return this._settledValue()},e.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},e.PromiseInspection=t}},{}],33:[function(e,t,n){"use strict";t.exports=function(t,n){function r(e,r){if(c(e)){if(e instanceof t)return e;var i=o(e);if(i===u){r&&r._pushContext();var l=t.reject(i.e);return r&&r._popContext(),l}if("function"==typeof i){if(s(e)){var l=new t(n);return e._then(l._fulfill,l._reject,void 0,l,null),l}return a(e,i,r)}}return e}function i(e){return e.then}function o(e){try{return i(e)}catch(e){return u.e=e,u}}function s(e){try{return d.call(e,"_promise0")}catch(e){return!1}}function a(e,r,i){function o(e){a&&(a._resolveCallback(e),a=null)}function s(e){a&&(a._rejectCallback(e,d,!0),a=null)}var a=new t(n),c=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var d=!0,f=l.tryCatch(r).call(e,o,s);return d=!1,a&&f===u&&(a._rejectCallback(f.e,!0,!0),a=null),c}var l=e("./util"),u=l.errorObj,c=l.isObject,d={}.hasOwnProperty;return r}},{"./util":36}],34:[function(e,t,n){"use strict";t.exports=function(t,n,r){function i(e){this.handle=e}function o(e){return clearTimeout(this.handle),e}function s(e){throw clearTimeout(this.handle),e}var a=e("./util"),l=t.TimeoutError;i.prototype._resultCancelled=function(){clearTimeout(this.handle)};var u=function(e){return c(+this).thenReturn(e)},c=t.delay=function(e,o){var s,a;return void 0!==o?(s=t.resolve(o)._then(u,null,null,e,void 0),r.cancellation()&&o instanceof t&&s._setOnCancel(o)):(s=new t(n),a=setTimeout(function(){s._fulfill()},+e),r.cancellation()&&s._setOnCancel(new i(a)),s._captureStackTrace()),s._setAsyncGuaranteed(),s};t.prototype.delay=function(e){return c(e,this)};var d=function(e,t,n){var r;r="string"!=typeof t?t instanceof Error?t:new l("operation timed out"):new l(t),a.markAsOriginatingFromRejection(r),e._attachExtraTrace(r),e._reject(r),null!=n&&n.cancel()};t.prototype.timeout=function(e,t){e=+e;var n,a,l=new i(setTimeout(function(){n.isPending()&&d(n,t,a)},e));return r.cancellation()?(a=this.then(),n=a._then(o,s,void 0,l,void 0),n._setOnCancel(l)):n=this._then(o,s,void 0,l,void 0),n}}},{"./util":36}],35:[function(e,t,n){"use strict";t.exports=function(t,n,r,i,o,s){function a(e){setTimeout(function(){throw e},0)}function l(e){var t=r(e);return t!==e&&"function"==typeof e._isDisposable&&"function"==typeof e._getDisposer&&e._isDisposable()&&t._setDisposable(e._getDisposer()),t}function u(e,n){function i(){if(s>=u)return c._fulfill();var e=l(o[s++]);if(e instanceof t&&e._isDisposable()){try{e=r(e._getDisposer().tryDispose(n),o.promise)}catch(o){return a(o)}if(e instanceof t)return e._then(i,a,null,null,null)}i()}var s=0,u=e.length,c=new t(o);return i(),c}function c(e,t,n){this._data=e,this._promise=t,this._context=n}function d(e,t,n){this.constructor$(e,t,n)}function f(e){return c.isDisposer(e)?(this.resources[this.index]._setDisposable(e),e.promise()):e}function h(e){this.length=e,this.promise=null,this[e-1]=null}var p=e("./util"),v=e("./errors").TypeError,g=e("./util").inherits,m=p.errorObj,y=p.tryCatch,b={};c.prototype.data=function(){return this._data},c.prototype.promise=function(){return this._promise},c.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():b},c.prototype.tryDispose=function(e){var t=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=t!==b?this.doDispose(t,e):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},c.isDisposer=function(e){return null!=e&&"function"==typeof e.resource&&"function"==typeof e.tryDispose},g(d,c),d.prototype.doDispose=function(e,t){return this.data().call(e,e,t)},h.prototype._resultCancelled=function(){for(var e=this.length,n=0;n0},t.prototype._getDisposer=function(){return this._disposer},t.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},t.prototype.disposer=function(e){if("function"==typeof e)return new d(e,this,i());throw new v}}},{"./errors":12,"./util":36}],36:[function(e,t,n){"use strict";function i(){try{var e=R;return R=null,e.apply(this,arguments)}catch(e){return A.e=e,A}}function o(e){return R=e,i}function s(e){return null==e||!0===e||!1===e||"string"==typeof e||"number"==typeof e}function a(e){return"function"==typeof e||"object"==typeof e&&null!==e}function l(e){return s(e)?new Error(m(e)):e}function u(e,t){var n,r=e.length,i=new Array(r+1);for(n=0;n1,r=t.length>0&&!(1===t.length&&"constructor"===t[0]),i=x.test(e+"")&&I.names(e).length>0;if(n||r||i)return!0}return!1}catch(e){return!1}}function p(e){function t(){}t.prototype=e;for(var n=8;n--;)new t;return e}function v(e){return N.test(e)}function g(e,t,n){for(var r=new Array(e),i=0;i10||e[0]>0}(),B.isNode&&B.toFastProperties(q);try{throw new Error}catch(q){B.lastLineError=q}t.exports=B},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:15}],2:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.PreCallTest=void 0;var i=function(){function e(e,t){for(var n=0;n0)this.callback&&this.callback(null,"Not started: call in progress");else if(e){this.turnTestCounter=0,this.resultsHandler=new l.ResultsHandler;var n={type:"browser",os:this.browserInfo.os,osVersion:this.browserInfo.osVersion,buildName:this.browserInfo.browserName,buildVersion:this.browserInfo.browserVersion};this.resultsHandler.add("endpointInfo",n),this.onlineCheck.start(),this.active=!0,this._start()}else this.callback&&this.callback(null,"Not started: no ICE servers given");else this.callback&&this.callback(null,"Not started: disabled for IE")}},{key:"_start",value:function(){var e=this;this.active&&this.turnConnection.connect(this.iceServers).then(function(){e.active?e.startTurnTests().then(function(){e.stop()},function(t){e.stop()}):e.stop()},function(e){var t=e.continueFlag;if(r.resultsHandler.failure(e),!t){r.turnConnection.disconnect(),r.active=!1;var n="";try{n=e.stack}catch(r){n=e.toString()}return n&&""!==n||(n=e.toString()),void r.callback(null,n)}r.resultsHandler.getFailureNumber()>=10?r.stop():(r.turnConnection.disconnect(),setTimeout(function(){r._start()},0))})}},{key:"stop",value:function(){var e=this;if(this.browserInfo.browserName!==c.Constants.browserName.msie&&this.active){this.active=!1,this.activeTurnTest&&this.activeTurnTest.forceStop();var t=this.onlineCheck.stop();this.resultsHandler&&this.resultsHandler.add("onlineStatus",t),this.turnConnection.getIceResults().then(function(t){e.resultsHandler&&e.resultsHandler.add("ice",t),e.turnConnection.disconnect(),e.sendResults()},function(t){e.resultsHandler&&e.resultsHandler.failure(t),e.turnConnection.disconnect(),e.sendResults()})}}},{key:"sendResults",value:function(){this.resultsHandler||this.callback&&this.callback(null,"No results present");var e=this.resultsHandler.getResults();this.callback&&this.callback(e,null),this.resultsHandler=null}},{key:"callStarts",value:function(){this.callsInProgress+=1,this.stop()}},{key:"callFinished",value:function(){this.callsInProgress-=1}},{key:"getId",value:function(){return this.resultsHandler?this.resultsHandler.getId():null}},{key:"crashDisconnect",value:function(){try{this.turnConnection.disconnect()}catch(e){}}},{key:"startTurnTests",value:function(){var e=this;if(this.turnTestCounter>=this.turnTests.length)return new d(function(e,t){e()});var t=this.turnTests[this.turnTestCounter],n=null;switch(t){case f.RTT:n=new s.RttTest(this.turnConnection);break;case f.THROUGHPUT:n=new a.ThroughputTest(this.turnConnection,this.rtt);break;default:return new d(function(e,n){n(new Error("Unknown test: "+t))})}return this.activeTurnTest=n,this.active?n.start().then(function(){return e.handleTestResults(t,n.getResults()),e.turnTestCounter+=1,e.activeTurnTest=null,e.startTurnTests()},function(r){return e.handleTestResults(t,n.getResults(),r),e.turnTestCounter+=1,e.activeTurnTest=null,e.startTurnTests()}):new d(function(e,t){t(new Error("Test trying to start while testing is not active"))})}},{key:"handleTestResults",value:function(e,t){null==(arguments.length>2&&void 0!==arguments[2]?arguments[2]:null)&&e==f.RTT&&(this.rtt=t.median),this.resultsHandler&&this.resultsHandler.add(e,t)}}]),e}();n.PreCallTest=h},{"./tests/rttTest":3,"./tests/throughputTest":4,"./turnConnection":6,"./utility/onlineCheck":8,"./utility/resultsHandler":10,"./utility/stats/detectbrowser":11,bluebird:1}],3:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(n,"__esModule",{value:!0}),n.RttTest=void 0;var s=function(){function e(e,t){for(var n=0;n=this.intervalLength){var r=n-this.intervalStart,i=this.averageThroughput(this.intervalBytes,r),o=null;try{o=n-JSON.parse(this.lastMessage).timestamp}catch(e){}this.intervals.push({startTimestamp:this.intervalStart,endTimestamp:n,bytesReceived:this.intervalBytes,average:i,rtt:o}),this.intervalStart=n,this.intervalBytes=0}this.results.startTimestamp&&n-this.results.startTimestamp>this.duration/2&&(this.secondHalfStart||(this.secondHalfStart=n),this.secondHalfBytes+=e.length)}}},{key:"handleError",value:function(e){this.stop(),this.failed(e)}},{key:"averageThroughput",value:function(e,t){return e/(t/1e3)*8/1024}},{key:"bufferListener",value:function(){this.sendChannel.removeEventListener("bufferedamountlow",this.bufferListener.bind(this)),this.fillBuffer()}},{key:"fillBuffer",value:function(){for(0==this.sendChannel.bufferedAmount&&(this.bufferEmpty+=1);this.isActive();){if(this.sendChannel.bufferedAmount>this.bufferFullThreshold)return void(this.usePolling?setTimeout(this.fillBuffer.bind(this),250):this.sendChannel.addEventListener("bufferedamountlow",this.bufferListener.bind(this)));var e=this.messageMaker.make(this.sentBytes);this.sentBytes+=e.length,this.send(e)}this.sendChannel.removeEventListener("bufferedamountlow",this.bufferListener.bind(this))}},{key:"startSend",value:function(){this.isActive()&&(this.bufferFullThreshold=1e3*this.chunkSize,this.sendChannel=this.connection.sendChannel,this.usePolling=!0,"number"==typeof this.sendChannel.bufferedAmountLowThreshold&&(this.usePolling=!1,this.sendChannel.bufferedAmountLowThreshold=this.bufferFullThreshold/10),setTimeout(this.fillBuffer.bind(this),0))}},{key:"fillResults",value:function(){this.results.endTimestamp=u.getCurrent(),this.results.maxDuration=this.duration,this.results.forceStopped=this.forceStopped,this.results.bufferEmpty=this.bufferEmpty,this.results.intervals=this.intervals,this.results.bytesPrepared=this.sentBytes,this.results.bytesReceived=this.receivedBytes;var e=0,t=0;this.secondHalfStart&&(e=this.results.endTimestamp-this.secondHalfStart,t=this.averageThroughput(this.secondHalfBytes,e));var n=this.results.endTimestamp-this.results.startTimestamp,r=this.averageThroughput(this.receivedBytes,n);r>t&&(t=r),this.results.average=t;var i=null;try{i=JSON.parse(this.lastMessage)}catch(e){return}if(i){var o=i.sentBytes+this.lastMessage.length;this.results.bytesSent=o,this.results.fractionLostBytes=1-this.receivedBytes/o}else this.results.bytesSent=-1,this.results.fractionLostBytes=-1}},{key:"stop",value:function(){this.isActive()&&(clearTimeout(this.sendTimer),this.sendTimer=null,a(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"stop",this).call(this),this.fillResults())}}]),t}();n.ThroughputTest=f},{"../utility/messageMaker":7,"../utility/timestamps":14,"./turnTest":5}],5:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:1200;r(this,e),this.message={timestamp:"",sentBytes:1e4,padding:""};var n=i(t-a.getCurrent().toString().length-JSON.stringify(this.message).length);this.message.padding=n}return o(e,[{key:"make",value:function(e){return this.message.timestamp=a.getCurrent(),this.message.sentBytes=e,JSON.stringify(this.message)}}]),e}();n.MessageMaker=l,n.randomAsciiString=i},{"../utility/timestamps":14}],8:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.OnlineCheck=void 0;var i=function(){function e(e,t){for(var n=0;n>24;if("rtp"===this.protocol&&n>=0&&n<=2)switch(n){case 0:t="TLS";break;case 1:t="TCP";break;case 2:t="UDP"}return t}},{key:"getString",value:function(){return this.iceCandidateStr}},{key:"getType",value:function(){return this.type}},{key:"isHost",value:function(){return"host"===this.type.toLowerCase()}},{key:"isServerReflexive",value:function(){return"srflx"===this.type.toLowerCase()}},{key:"isPeerReflexive",value:function(){return"prflx"===this.type.toLowerCase()}},{key:"isRelay",value:function(){return"relay"===this.type.toLowerCase()||"relayed"===this.type.toLowerCase()}},{key:"getTypeTransport",value:function(){return this.typeTransport}},{key:"isTypeTransportUdp",value:function(){return"UDP"===this.typeTransport}},{key:"isTypeTransportTcp",value:function(){return"TCP"===this.typeTransport}},{key:"isTypeTransportTls",value:function(){return"TLS"===this.typeTransport}},{key:"getTransport",value:function(){return this.transport}},{key:"isUdp",value:function(){return"udp"===this.transport.toLowerCase()}},{key:"isTcp",value:function(){return"tcp"===this.transport.toLowerCase()}},{key:"getProtocol",value:function(){return this.protocol}},{key:"isRtp",value:function(){return"rtp"===this.protocol}},{key:"isRtcp",value:function(){return"rtcp"===this.protocol}},{key:"isIpv6",value:function(){return this.ipv6}},{key:"getIpAddress",value:function(){return this.ipAddress}},{key:"getPort",value:function(){return this.port}}]),e}();n.ParsedIceCandidate=o},{}],10:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.ResultsHandler=void 0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o=function(){function e(e,t){for(var n=0;n>24;l.mozLocalTransport=this.formatRelayType(u)}l.mozLocalTransport=l.mozLocalTransport.toLowerCase()}t.push(l)}else a.remoteCandidate&&n.push(a.remoteCandidate)}if(i)for(var c=0;c1)for(var n=1;n2&&void 0!==arguments[2]?arguments[2]:"")}function a(){var e=null,t=m.Registry.getEndpoint().getBrowserName();return"Firefox"===t?e=mozRTCPeerConnection:"Chrome"===t||"Opera"===t?e=webkitRTCPeerConnection:"Safari"===t?b.log("Browser type Safari"):"Edge"===t&&(e=window.RTCPeerConnection),e}function l(e){if(null===e)return!1;var t=m.Registry.getEndpoint().getCodeBase();if(t===f.codeBaseType.firefox)return"undefined"!=typeof mozRTCPeerConnection&&e instanceof mozRTCPeerConnection||"undefined"!=typeof RTCPeerConnection&&e instanceof RTCPeerConnection;if(t===f.codeBaseType.edge||"function"==typeof e)return!0;var n=a();return null!==n&&e instanceof n||void 0!==e.createOffer}var u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},c=function(){function e(e,t){for(var n=0;n ("+r+") ["+t.toString()+"]"),null!==t.getLeft()&&e(t.getLeft(),n+1,"Left"),null!==t.getRight()&&e(t.getRight(),n+1,"Right")}}(this.root,0,"Root"))}}]),e}();n.BinaryTree=u},{"../utility/csiologger":87,"./binarytreenode.js":23}],23:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n1&&void 0!==arguments[1]&&arguments[1];return this.length()>1e6?void s.error("Maximum cached items reached, dropping."):void(t?this.priority.push(e):this.queue.push(e))}},{key:"pop",value:function(){return this.priority.length>0?this.priority.shift():this.queue.shift()}},{key:"peak",value:function(){return this.priority.length>0?this.priority[0]:this.queue.length>0?this.queue[0]:null}},{key:"length",value:function(){return this.queue.length+this.priority.length}},{key:"updateConferenceId",value:function(e){for(var t=0;t0&&void 0!==arguments[0]?arguments[0]:"Unknown";r(this,e),this.name=t,this.ports=new Map}return i(e,[{key:"bindPort",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this;return this.ports.has(e)?void a.warn("Port ("+e+") for "+this.name+" already exists."):void this.ports.set(e,new o.Port(t,n))}},{key:"declarePort",value:function(e){return this.ports.has(e)?void a.warn("Port ("+e+") for "+this.name+" already exists."):void this.ports.set(e,null)}},{key:"getPort",value:function(e){return this.ports.get(e)}},{key:"isConnected",value:function(e){return!!this.ports.has(e)&&null!==this.ports.get(e)}},{key:"connect",value:function(e,t){return this.ports.has(e)?void this.ports.set(e,t):void a.warn("Port ("+e+") for "+this.name+" does not exists.")}},{key:"transmit",value:function(e){var t=this.ports.get(e);if(void 0===t)return void a.warn("Port ("+e+") for "+this.name+" does not exists.");if(null===t)return void a.warn("Port ("+e+") for "+this.name+" is not connected.");for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i1?n-1:0),i=1;i1&&void 0!==arguments[1]?arguments[1]:null;r(this,e),this.target=t,this.object=n}return i(e,[{key:"transmit",value:function(e){this.target.apply(this.object,e)}},{key:"request",value:function(e){return this.target.apply(this.object,e)}}]),e}();n.Port=o},{}],27:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.SlidingWindow=void 0;var i=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:0;return this.items.length<=e?null:this.items[this.items.length-e-1].getValue()}},{key:"attach",value:function(e){this.plugins.push(e)}},{key:"addPreProcess",value:function(e){this.preProcesses.push(e)}},{key:"addPostProcess",value:function(e){this.postProcesses.push(e)}},{key:"detach",value:function(e){this.plugins=this.plugins.filter(function(t){return t!==e})}}]),e}();n.SlidingWindow=l},{"../utility/timestamps":98,"./switem":28}],28:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.SWItem=void 0;var i=function(){function e(e,t){for(var n=0;n>>0,r=arguments[1],i=void 0,o=0;o0&&f.Registry.getEventMessageBuilder().make(_.precalltestEvents.associate,r,e,{ids:u})}},{key:"onSendFabricEvent",value:function(e,t,n,r){p.warn("FSM onSendFabricEvent");var i={};r&&(i=r),t===_.fabricEvent.activeDeviceList&&(i={mediaDeviceList:g.normalizeMediaDeviceList(r.deviceList)}),f.Registry.getEventMessageBuilder().make(t,n,e,i);var o=f.Registry.getConferenceManager().get(n);if(o){var s=o.getPeerConnectionManager().getPcHandler(e);t!==_.fabricEvent.fabricTerminated&&t!==_.internalFabricEvent.fabricSetupFailed||(s.stopUserAliveHandler(),s.setPcState(_.fabricState.terminated),s.stopStatsPolling()),t===_.fabricEvent.fabricHold&&(s.setPcState(_.fabricState.hold),s.stopStatsPolling()),t===_.fabricEvent.fabricResume&&(s.setPcState(_.fabricState.established),s.startStatsPolling())}}},{key:"onReportError",value:function(e,t,n,r,i,o){p.warn("FSM onReportError");var s={failureDelay:0,reason:this.callFailureClassifier(n),"function":n,magicKey:f.Registry.getEndpoint().getMagicKey(),endpoint:f.Registry.getEndpoint().serialize(),level:"debug"};if(r){var a=this.formatDomError(r);s.message=a.message,s.messageType=a.messageType,s.name=r.name,s.stack=r.stack}if(e){var l=f.Registry.getConferenceManager().get(t),u=void 0;if(l&&(u=l.getPeerConnectionManager().getPcHandler(e)),!u)return void p.error("onReportError: No handler found for given PeerConnection!");if(s.failureDelay=y.getCurrent()-u.getStartTime(),s.fabricState=u.getPcState(),s.iceConnectionState=u.getIceConnectionState(),(i||o||e&&"closed"!==e.signalingState)&&f.Registry.getCredentials().getCollectSDP()&&n===_.fabricEvent.fabricSetupFailed){var c={};c.localSDP=this.pickSDP(e,i,"localDescription"),c.remoteSDP=this.pickSDP(e,o,"remoteDescription"),f.Registry.getEventMessageBuilder().make(_.callstatsChannels.sdpSubmission,t,e,c)}}n===_.webRTCFunctions.applicationLog||n===_.webRTCFunctions.applicationError?f.Registry.getEventMessageBuilder().make(_.fabricEvent.applicationErrorLog,t,e,s):f.Registry.getEventMessageBuilder().make(_.fabricEvent.fabricSetupFailed,t,e,s)}},{key:"onAssociateMstWithUserID",value:function(e,t,n,r,i,o){var s=f.Registry.getConferenceManager().get(n);if(s){var a=s.getPeerConnectionManager().getPcHandler(e);"string"!=typeof r&&(r+=""),a.updateSSRCInfo(r,t,i,o)}}},{key:"onAttachWifiStatsHandler",value:function(e){f.Registry.getWifiStatsExecutor().setGetWifiStatsMethod(e)}},{key:"onSetProxyConfig",value:function(e){e.collectorURL&&T.setBaseUrl(e.collectorURL),e.authServiceURL&&T.setAuthServiceUrl(e.authServiceURL),e.csioInternalAPIURL&&T.setQmodelThresholdsAPIUrl(e.csioInternalAPIURL),e.wsURL&&T.setWsUrl(e.wsURL),e.restEventUrl&&T.setRestEventUrl(e.restEventURL),e.restStatsUrl&&T.setRestStatsUrl(e.restStatsURL),this.setup()}},{key:"onSendUserFeedback",value:function(e,t,n){var r={feedback:{overallRating:t.overall}};t.video&&(r.feedback.videoQualityRating=t.video),t.audio&&(r.feedback.audioQualityRating=t.audio),t.comment&&(r.feedback.comments=t.comment),f.Registry.getEventMessageBuilder().make(_.callstatsChannels.userFeedback,e,null,r)}},{key:"onOn",value:function(e,t){f.Registry.getCallbacks().set(e,t)}},{key:"onSetIdentifiers",value:function(e,t){if(e.conferenceID&&(f.Registry.getConferenceManager().updateConferenceId(e.conferenceID),f.Registry.getTransmissionManager().updateConferenceId(e.conferenceID),f.Registry.getTransmissionManager().trySend()),e.remoteUserID&&t){var n=f.Registry.getConferenceManager().getConferenceForPc(t);if(!n)return void p.log("onSetIdentifiers conference not found");var r=n.getPeerConnectionManager().getPcHandler(t);if(!r)return void p.log("pcHandler not found");r.updateRemoteId(e.remoteUserID),f.Registry.getTransmissionManager().trySend()}}},{key:"onMakePrecallTest",value:function(){var e=this,t=this.authenticator.getIceServers();e.precalltest.start(t,e.precalltestCallback.bind(e))}},{key:"callFailureClassifier",value:function(e){var t=void 0;return _.webRTCFunctions.hasOwnProperty(e)?e===_.webRTCFunctions.createOffer||e===_.webRTCFunctions.createAnswer||e===_.webRTCFunctions.setRemoteDescription?t=_.callFailureReasons.negotiationFailure:e===_.webRTCFunctions.setLocalDescription?t=_.callFailureReasons.sdpError:e===_.webRTCFunctions.addIceCandidate?t=_.callFailureReasons.sdpError:e===_.webRTCFunctions.getUserMedia?t=_.callFailureReasons.mediaConfigError:e===_.webRTCFunctions.iceConnectionFailure?t=_.callFailureReasons.iceFailure:e===_.webRTCFunctions.signalingError?t=_.callFailureReasons.signalingError:(e===_.webRTCFunctions.applicationLog||_.webRTCFunctions.applicationError)&&(t=_.callFailureReasons.applicationLog):t=_.callFailureReasons.invalidWebRTCFunctionName,t}},{key:"formatDomError",value:function(e){var t={},n={};e&&(window.DOMException&&e instanceof window.DOMException?(n.message=e.message,n.name=e.name,t.messageType="domError"):"object"===(void 0===e?"undefined":u(e))?(e.message&&(n.message=e.message),e.name&&(n.name=e.name),e.constraintName&&(n.name=e.constraintName),e.stack&&(n.stack=e.stack),t.messageType="json"):(n=e,t.messageType="text"));var r=this.truncateLog(n);return"object"===(void 0===r?"undefined":u(r))?t.message=JSON.stringify(r):t.message=r,t}},{key:"pickSDP",value:function(e,t,n){return t||(e&&e[n]?e[n].sdp:"")}},{key:"truncateString",value:function(e){return e.length>2e4&&(p.log("Log exceeds 20kb, It will be truncated"),e=e.substring(0,2e4)),e}},{key:"truncateLog",value:function(e){return e?("string"==typeof e?e=this.truncateString(e):"object"===(void 0===e?"undefined":u(e))&&e.message&&(e.message=this.truncateString(e.message)),e):e}}]),t}(d.StateMachine);n.MainFSM=D},{"../config/constants":32,"../config/settings":33,"../statspipeline/statsadapter":68,"../statspipeline/statsassembler":69,"../statspipeline/statsmonitor":71,"../statspipeline/statsparser":72,"../statspipeline/statstransmitter":73,"../utility/csiologger":87,"../utility/registry":94,"../utility/timestamps":98,"../utility/utils":100,"./statemachine":36,"./utility":37}],35:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n1?t-1:0),r=1;r",this.iceConnectionState);var e={changedState:a.fabricStateChangeType.iceConnectionState,prevState:this.oldIceConnectionState,newState:this.iceConnectionState};this.sendFabricStateChange(e)}},{key:"handleIceGatheringState",value:function(){if(this.iceGatheringState!==this.pc.iceGatheringState){"complete"===this.pc.iceGatheringState&&(this.iceGatheringDelay=c.getCurrent()-this.startTime),this.oldIceGatheringState=this.iceGatheringState,this.iceGatheringState=this.pc.iceGatheringState,p.warn("CALLBACK: ICE gathering state change",this.oldIceGatheringState,"->",this.iceGatheringState);var e={changedState:a.fabricStateChangeType.iceGatheringState,prevState:this.oldIceGatheringState,newState:this.iceGatheringState};this.sendFabricStateChange(e)}}},{key:"handleIceChecking",value:function(){if("disconnected"===this.oldIceConnectionState&&this.pcState===a.fabricState.checkingDisrupted){var e={prevIceConnectionState:this.oldIceConnectionState,currIceConnectionState:this.iceConnectionState,disruptionDelay:c.getCurrent()-this.disruptedTS};this.emb.make(a.internalFabricEvent.iceConnectionDisruptionEnd,this.conferenceId,this.pc,e)}}},{key:"handleIceConnectedOrCompleted",value:function(e){var t=c.getCurrent();this.pcState===a.fabricState.disrupted&&(e.prevIceCandidatePair=this.prevActiveIceCandidatePair,e.currIceCandidatePair=this.activeIceCandidatePair,e.disruptionDelay=t-this.disruptedTS,this.emb.make(a.internalFabricEvent.iceDisruptionEnd,this.conferenceId,this.pc,e)),this.iceConnectivityDelay=t-this.startTime,this.established=!0,this.pcState=a.fabricState.established,this.sendfabricSetup(),this.startStatsPolling()}},{key:"sendfabricSetup",value:function(){if(this.fabricSetupSent)return void p.log("fabricSetup has been sent already");var e={delay:c.getCurrent()-this.startTime,iceGatheringDelay:this.iceGatheringDelay,iceConnectivityDelay:this.iceConnectivityDelay,localIceCandidates:this.localIceCandidates,remoteIceCandidates:this.remoteIceCandidates,iceCandidatePairs:this.iceCandidatePairs};this.fabricSetupSent=!0;var t=void 0;this.conferenceId&&(t=l.Registry.getConferenceManager().get(this.conferenceId).getPeerConnectionManager().getPcHandler(this.pc),e.remoteEndpointType=t.getRemoteEndpointType(),e.fabricTransmissionDirection=t.getFabricTransmissionDirection()),this.pcState=a.fabricState.established,this.emb.make(a.internalFabricEvent.fabricSetup,this.conferenceId,this.pc,e)}},{key:"isFabricSetupSent",value:function(){return this.fabricSetupSent}},{key:"startStatsPolling",value:function(){this.getStatsHandler.startStatsPolling()}},{key:"stopStatsPolling",value:function(){this.getStatsHandler.stopStatsPolling()}},{key:"handleIceFailed",value:function(e){e.currIceCandidatePair=this.activeIceCandidatePair,e.failureDelay=c.getCurrent()-this.startTime,e.delay=c.getCurrent()-this.startTime,this.pcState=a.fabricState.failed,"checking"===this.oldIceConnectionState?this.sendIceFailed(e):"completed"===this.oldIceConnectionState||"connected"===this.oldIceConnectionState?this.emb.make(a.internalFabricEvent.fabricDropped,this.conferenceId,this.pc,e):"disconnected"===this.oldIceConnectionState&&this.established?this.emb.make(a.internalFabricEvent.fabricDropped,this.conferenceId,this.pc,e):"disconnected"===this.oldIceConnectionState&&this.sendIceFailed(e)}},{key:"getActiveIceCandidatePair",value:function(){var e=null,t=this.iceCandidatePairs;if(t&&t.length>0){var n=t.filter(function(e){return"true"===e.selected||"true"===e.googActiveConnection||!0===e.selected||!0===e.googActiveConnection});n.length>0&&(e=n[0])}return e}},{key:"sendIceFailed",value:function(e){e.localIceCandidates=this.localIceCandidates,e.remoteIceCandidates=this.remoteIceCandidates,e.iceCandidatePairs=this.iceCandidatePairs,p.log("sending icefailed ",e),this.emb.make(a.internalFabricEvent.iceFailed,this.conferenceId,this.pc,e)}},{key:"sendFabricTransportSwitch",value:function(e){var t=this,n={};n.prevIceCandidatePair=t.activeIceCandidatePair,n.relayType=e,n.currIceConnectionState=t.iceConnectionState,n.prevIceConnectionState=t.oldIceConnectionState,n.switchDelay=null,t.getStatsHandler.getIceCandidates().then(function(e){t.localIceCandidates=e.localIceCandidates,t.remoteIceCandidates=e.remoteIceCandidates,t.iceCandidatePairs=e.iceCandidatePairs,t.activeIceCandidatePair=t.getActiveIceCandidatePair(),n.currIceCandidatePair=t.activeIceCandidatePair,n.localIceCandidates=t.localIceCandidates,n.remoteIceCandidates=t.remoteIceCandidates,p.log("sending fabric transport switch ",n),"completed"!==n.currIceConnectionState&&"connected"!==n.currIceConnectionState||"completed"!==n.prevIceConnectionState&&"connected"!==n.prevIceConnectionState||t.emb.make(a.internalFabricEvent.fabricTransportSwitch,t.conferenceId,t.pc,n)})}},{key:"handleIceDisconnected",value:function(e){var t=c.getCurrent();this.startTime=t,e.prevIceConnectionStateTs=this.iceConnectionStateTS,e.currIceCandidatePair=this.activeIceCandidatePair,"connected"===this.oldIceConnectionState||"completed"===this.oldIceConnectionState?(this.pcState=a.fabricState.disrupted,this.disruptedTS=t,this.emb.make(a.internalFabricEvent.iceDisruptionStart,this.conferenceId,this.pc,e),this.callback&&this.callback(f.csError.appConnectivityError,"Connectivity check for PC object to "+this.remoteId+" failed.")):"checking"===this.oldIceConnectionState&&(this.pcState=a.fabricState.checkingDisrupted,this.disruptedTS=t,this.emb.make(a.internalFabricEvent.iceConnectionDisruptionStart,this.conferenceId,this.pc,e),this.callback&&this.callback(f.csError.appConnectivityError,"Connectivity check for PC object to "+this.remoteId+" failed."))}},{key:"handleIceClosed",value:function(e){"new"===this.oldIceConnectionState||"checking"===this.oldIceConnectionState?(e.failureDelay=c.getCurrent()-this.startTime,e.localIceCandidates=this.localIceCandidates,e.remoteIceCandidates=this.remoteIceCandidates,e.iceCandidatePairs=this.iceCandidatePairs,this.emb.make(a.internalFabricEvent.iceAborted,this.conferenceId,this.pc,e)):(e.currIceCandidatePair=this.activeIceCandidatePair,this.emb.make(a.internalFabricEvent.iceTerminated,this.conferenceId,this.pc,e),this.stopStatsPolling())}},{key:"handleIceRestart",value:function(e){e.prevIceCandidatePair=this.prevActiveIceCandidatePair,"new"!==this.oldIceConnectionState&&(p.log("iceRestarted sending"),this.established=!1,this.emb.make(a.internalFabricEvent.iceRestarted,this.conferenceId,this.pc,e))}},{key:"pcSignalingStateChangeCallback",value:function(e){var t=this;if(e){var n=this.signalingState;this.signalingState=this.pc.signalingState,p.warn("CALLBACK: signaling state change",n,"->",this.signalingState);var r={changedState:a.fabricStateChangeType.signalingState,prevState:n,newState:this.signalingState};this.sendFabricStateChange(r),"have-remote-offer"!==this.signalingState&&"stable"!==this.signalingState||(this.precalltest.callStarts(),this.genericevent.sendEvent(a.logEvents.log,{msg:"precalltest told to stop "})),"closed"===this.signalingState&&(this.emb.make(a.fabricEvent.fabricTerminated,this.conferenceId,this.pc),this.userAlive.stop(),this.precalltest.callFinished(),this.stopStatsPolling(),this.genericevent.sendEvent(a.logEvents.log,{msg:"precalltest finished "})),"have-local-offer"!==this.signalingState&&"have-local-pranswer"!==this.signalingState&&"stable"!==this.signalingState||(p.log(this.signalingState,".. requesting sender config."),l.Registry.getConfigServiceWrapper().initiateSenderConfig(this.pc).then(function(){var e=l.Registry.getConfigServiceWrapper().getSenderConfig();p.log("Sender config:",e);var n=a.callstatsChannels.senderConfiguration;l.Registry.getEventMessageBuilder().make(n,t.conferenceId,t.pc,e)})["catch"](function(e){p.warn(e)}))}}},{key:"pcNegotiationNeededCallback",value:function(e){e&&(this.negotiationNeeded++,this.startTime=c.getCurrent(),p.warn("CALLBACK: negotiation needed",this.negotiationNeeded))}}]),e}();n.PcCallbackHandler=v},{"../config/callstatserrors":31,"../config/constants":32,"../utility/csiologger":87,"../utility/registry":94,"../utility/timestamps":98}],40:[function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.PeerConnectionHandler=void 0;var o=function(){function e(e,t){for(var n=0;n0)return void this.handleErrorActions(r["urn:x-callstats:auth:errorActions"]);if(200===t.status){if("bearer"!==r.token_type)return R.error(this.name+": successful, but token type was not bearer. Scheduling retry."),void this.sendNextRequest();this.setupToken(r.access_token),r.iceServers&&(this.iceServers=r.iceServers);var i=parseInt(1e3*parseInt(r.expires_in)*.9);return this.setupReauthTimer(i),this.renew=!1,this.initCallback&&this.initCallback(g.csError.success,y.csCallBackMessages.authSuccessful),this.elapsed=n,void this.completeProcess()}R.error("Authentication failed, but no error actions were defined in response."),this.sendNextRequest()}},{key:"request",value:function(){var e=this;this.clearReauthTimer();var t=new Promise(function(t,n){e.tempResolve=t,e.tempReject=n});return this.tokenGenerator(this.renew,function(t,n){if(null!==t)return e.initCallback&&e.initCallback(g.csError.tokenGenerationError,t.toString()),e.rejectCb(new Error(e.name+": tokenGenerationError")),R.error("tokenGenerationError ",t),null;var r=e.url+"authenticate",i={client_id:e.credentials.userId+"@"+e.credentials.getAppId(),code:n,grant_type:"authorization_code"},o={"Content-Type":"application/x-www-form-urlencoded"};(0,C.sendPostRequest)(r,o,I,i).then(function(t){e.tempResolve(t)},function(t){e.tempReject(t)})}),t}},{key:"tokenGeneratorCreator",value:function(e,t){var n=this;return function(r,i){var o=null,s={alg:"HS256"};if(!r&&null!==o)return i(null,o);var a=n.credentials,l={userID:a.getUserId(),appID:a.getAppId()};t&&(l.keyId=t),n.jwt.sign(s,l,e).then(function(e){o=e,i(null,e)})["catch"](function(e){i(e)})}}},{key:"createTokenGenerator",value:function(e){var t=this;return new Promise(function(n,r){var i=null;e.indexOf(":")>-1&&(i=p.strtohex(e.split(":")[0]),e=e.split(":")[1]),t.jwt.importKey(e).then(function(r){e=null;var o=t.tokenGeneratorCreator(r,i);n(o)})["catch"](function(e){R.error(t.name+": could not import key ("+e+")"),r(e)})})}}]),t}(w.XMLHttpService);n.Authenticator=P},{"../browserapi/localstorage":19,"../config/callstatserrors":31,"../config/constants":32,"../config/settings":33,"../utility/base64":84,"../utility/csiologger":87,"../utility/json":92,"../utility/registry":94,"./jwt/jwt":51,"./jwt/jwttoken":52,"./xmlhttp":57,"./xmlhttpservice":58}],44:[function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.GenericEventHandler=void 0;var o=function(){function e(e,t){for(var n=0;n6e4?(this.offsetResults=[],v.Registry.getGenericEventHandler().sendEvent(m.logEvents.log,{msg:"clockSync restarting"})):this.addOffset(e,r,n),this.offsetResults.length>=5?(this.calculateOffset(),this.endTime=h.getCurrent(),this.completeProcess()):this.sendRequest()}},{key:"isCompleted",value:function(){return this.completed}},{key:"addOffset",value:function(e,t,n){var r=e.now+t,i=r-n;this.offsetResults.push(i),v.Registry.getGenericEventHandler().sendEvent(m.logEvents.log,{msg:"clockSync Info: serverTime "+r+" responseRecvTs: "+n})}},{key:"calculateOffset",value:function(){var e=this.offsetResults.reduce(function(e,t){return e+t});this.currentOffset=e/this.offsetResults.length,this.currentOffset=isNaN(this.currentOffset)?0:this.currentOffset,v.Registry.getGenericEventHandler().sendEvent(m.logEvents.log,{msg:"clockSync Done, offset is: "+this.currentOffset+"results length"+this.offsetResults.length}),this.offsetResults=[],this.completed=!0}}]),t}(p.XMLHttpService);n.ClockSync=b},{"../config/constants":32,"../config/settings":33,"../utility/registry":94,"../utility/timestamps":98,"./xmlhttp":57,"./xmlhttpservice":58}],46:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n1)return h.warn("Multiple PCs found, skipping"),null;if(!e.getSenders||"function"!=typeof e.getSenders)return h.warn("Get senders error"),t;for(var r=e.getSenders(),i=void 0,s=0;s=0;h--)c[h]=s.charCodeAt(h);var p=r.subtlecrypto.sign(d,n,c);"ie"===r.cryptotype?(p.onerror=o,p.oncomplete=function(e){s=r.buildToken(e.target.result,s),i(s)}):p.then(function(e){s=r.buildToken(e,s),i(s)})["catch"](function(e){o(e)})})}},{key:"buildToken",value:function(e,t){for(var n="",r=new Uint8Array(e),i=r.byteLength,o=0;o0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return function(n,r){if(!n||!n.xhr)return void v.log("Response for request is null");var i=n.xhr.response,o=JSON.parse(i);o.conferenceId=r,"success"===o.status?e&&e(o):t?t(o):(f.Registry.getGenericEventHandler().sendEvent(u.logEvents.restResponseError,{msg:"response failure "+o.msg+":"+o.status}),v.error("Response error:",o.msg,i))}}function s(e){var t=o();return new Map([[u.fabricEvent.fabricTerminated,new m(d.restEventUrl,"/events/fabric/terminated",t)],[u.fabricEvent.audioMute,new m(d.restEventUrl,"/events/media/actions",t)],[u.fabricEvent.audioUnmute,new m(d.restEventUrl,"/events/media/actions",t)],[u.fabricEvent.videoPause,new m(d.restEventUrl,"/events/media/actions",t)],[u.fabricEvent.videoResume,new m(d.restEventUrl,"/events/media/actions",t)],[u.fabricEvent.screenShareStart,new m(d.restEventUrl,"/events/media/actions",t)],[u.fabricEvent.screenShareStop,new m(d.restEventUrl,"/events/media/actions",t)],[u.fabricEvent.activeDeviceList,new m(d.restEventUrl,"/events/devices/list",t)],[u.fabricEvent.applicationErrorLog,new m(d.restEventUrl,"/events/app/logs",t)],[u.fabricEvent.dominantSpeaker,new m(d.restEventUrl,"/events/dominantspeaker",t)],[u.fabricEvent.fabricHold,new m(d.restEventUrl,"/events/fabric/actions",t)],[u.fabricEvent.fabricResume,new m(d.restEventUrl,"/events/fabric/actions",t)],[u.internalFabricEvent.fabricSetup,new m(d.restEventUrl,"/events/fabric/setup",t)],[u.fabricEvent.fabricSetupFailed,new m(d.restEventUrl,"/events/fabric/setupfailed",t)],[u.internalFabricEvent.userJoined,new m(d.restEventUrl,"",o(function(e){if("success"!==e.status)return void f.Registry.getGenericEventHandler().sendEvent(u.logEvents.restResponseError,{msg:"userJoined response failure"+e.msg+":"+e.status});var t=decodeURIComponent(e.conferenceId),n=f.Registry.getConferenceManager().get(t);n&&(v.log("UcId =",e.ucID,t),n.setUcId(e.ucID),f.Registry.getTransmissionManager().trySend())}))],[u.internalFabricEvent.userLeft,new m(d.restEventUrl,"/events/user/left",t)],[u.internalFabricEvent.userAlive,new m(d.restEventUrl,"/events/user/alive",t)],[u.internalFabricEvent.fabricTransportSwitch,new m(d.restEventUrl,"/events/fabric/transportchange",t)],[u.internalFabricEvent.mediaPlaybackStart,new m(d.restEventUrl,"/events/media/pipeline",t)],[u.internalFabricEvent.mediaPlaybackSuspended,new m(d.restEventUrl,"/events/media/pipeline",t)],[u.internalFabricEvent.mediaPlaybackStalled,new m(d.restEventUrl,"/events/media/pipeline",t)],[u.internalFabricEvent.ssrcMap,new m(d.restEventUrl,"/events/ssrcmap",t)],[u.internalFabricEvent.connectedDeviceList,new m(d.restEventUrl,"/events/devices/list",t)],[u.internalFabricEvent.sdpSubmission,new m(d.restEventUrl,"/events/sdp",t)],[u.internalFabricEvent.iceDisruptionStart,new m(d.restEventUrl,"/events/ice/status",t)],[u.internalFabricEvent.iceDisruptionEnd,new m(d.restEventUrl,"/events/ice/status",t)],[u.internalFabricEvent.iceConnectionDisruptionStart,new m(d.restEventUrl,"/events/ice/status",t)],[u.internalFabricEvent.iceConnectionDisruptionEnd,new m(d.restEventUrl,"/events/ice/status",t)],[u.internalFabricEvent.iceAborted,new m(d.restEventUrl,"/events/ice/status",t)],[u.internalFabricEvent.iceTerminated,new m(d.restEventUrl,"/events/ice/status",t)],[u.internalFabricEvent.iceFailed,new m(d.restEventUrl,"/events/ice/status",t)],[u.internalFabricEvent.iceRestarted,new m(d.restEventUrl,"/events/ice/status",t)],[u.internalFabricEvent.fabricDropped,new m(d.restEventUrl,"/events/fabric/status",t)],[u.callstatsChannels.processedStats,new m(d.restStatsUrl,"/stats",t)],[u.internalFabricEvent.fabricStateChange,new m(d.restEventUrl,"/events/fabric/statechange",t)],[u.callstatsChannels.userFeedback,new m(d.restEventUrl,"/events/feedback",t)],[u.precalltestEvents.results,new m(d.restEventUrl,"/events/precall",t)],[u.precalltestEvents.associate,new m(d.restEventUrl,"/events/precall",t)],[u.internalFabricEvent.userDetails,new m(d.restEventUrl,"/events/userdetails",t)]]); +}Object.defineProperty(n,"__esModule",{value:!0}),n.RestRelays=void 0;var a=function(){function e(e,t){for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:null;i(this,e),this.baseUrl=t,this.urlAppendix=n,this.responseHandler=r}return a(e,[{key:"getRequestUrl",value:function(e,t,n){return this.makeRequestUrl(e,t,n),this.requestUrl.toString()}},{key:"makeRequestUrl",value:function(e,t,n){e===u.precalltestEvents.results?this.requestUrl=new h.Url(this.baseUrl,f.Registry.getCredentials().getAppId(),this.urlAppendix):(e===u.internalFabricEvent.userJoined&&n&&(n=""),this.requestUrl=new h.Url(this.baseUrl,f.Registry.getCredentials().getAppId()+"/conferences/"+t,n,this.urlAppendix))}},{key:"handleResponse",value:function(e,t){this.responseHandler(e,t)}}]),e}();n.RestRelays=g},{"../config/constants":32,"../config/settings":33,"../utility/csiologger":87,"../utility/registry":94,"../utility/url":99}],55:[function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.TransmissionManager=void 0;var o=function(){function e(e,t){for(var n=0;n0&&this.startTimer()):void this.setupConnection()}},{key:"setupConnection",value:function(){this.connectionManager.setup().then(function(){h.log("Connected to connectionManager")})["catch"](function(e){return h.log("Could not connect to connectionManager",e)})}},{key:"sendMessage",value:function(){var e=void 0,t=void 0;if(0===this.getCacheLength())return!1;for(var n in this.cache)if(this.cache.hasOwnProperty(n)&&(t=n,(e=this.cache[t].peak())&&e.canBeSent()))break;return!(!e||!e.canBeSent()||(h.log("sending message type :",e.toJson().action,e.toJson()),e=this.cache[t].pop(),this.lastTS=a.getCurrent(),this.connectionManager.send(e.toJson()),0))}},{key:"startTimer",value:function(){var e=this;this.timerStarted||0!=this.getCacheLength()&&(this.timerStarted=!0,setTimeout(function(){e.timerStarted=!1,e.trySend()},200))}},{key:"timeToSend",value:function(){return a.getCurrent()>=this.lastTS+200}},{key:"getCacheLength",value:function(){var e=0;for(var t in this.cache)this.cache.hasOwnProperty(t)&&(e+=this.cache[t].length());return e}},{key:"updateConferenceId",value:function(e){var t=d.tmpConferenceId;this.cache[t]&&this.cache[t].updateConferenceId(e)}}]),e}();n.TransmissionManager=p},{"../collections/cache":24,"../config/constants":32,"../utility/csiologger":87,"../utility/registry":94,"../utility/timestamps":98}],56:[function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(n,"__esModule",{value:!0}),n.WsCollectorConnection=void 0;var a=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:"XMLHttpService",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:l,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u;r(this,e),this.name=t,this.minRetryTimeout=n,this.sigmoid=new o.Sigmoid(i-n,15,.5),this.reset()}return i(e,[{key:"reset",value:function(){this.inProgress=!1,this.completed=!1,this.resolveCb&&this.rejectCb(new Error(this.name+": resetting")),this.resolveCb=null,this.rejectCb=null}},{key:"initiate",value:function(){var e=this;if(this.inProgress)return new Promise(function(t,n){n(new Error(e.name+": in progress"))});var t=new Promise(function(t,n){e.resolveCb=t,e.rejectCb=n});return this.inProgress=!0,this.sendRequest(),t}},{key:"isCompleted",value:function(){return this.completed}},{key:"handleSendError",value:function(e){a.log(this.name+": send next request ("+e+")"),this.sendNextRequest()}},{key:"handleResponseProxy",value:function(e){this.handleResponse(e),this.resetTimeout()}},{key:"handleResponse",value:function(e){a.error(this.name+": handleResponse() not implemented"),this.completeProcess()}},{key:"completeProcess",value:function(){this.inProgress=!1,this.completed=!0,this.resolveCb.apply(this,arguments)}},{key:"request",value:function(){return a.error(this.name+": request() not implemented!"),new Promise(function(e,t){e()})}},{key:"sendRequest",value:function(){if(this.inProgress){var e=this.request();e&&e.then(this.handleResponseProxy.bind(this),this.handleSendError.bind(this))}}},{key:"sendNextRequest",value:function(){setTimeout(this.sendRequest.bind(this),this.getTimeout())}},{key:"resetTimeout",value:function(){this.sigmoid.reset()}},{key:"getTimeout",value:function(){return this.minRetryTimeout+this.sigmoid.getActual()}}]),e}();n.XMLHttpService=c},{"../utility/csiologger":87,"../utility/sigmoid":96}],59:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.Measurement=void 0;var i=function(){function e(e,t){for(var n=0;n0&&l>0?new o.Resolution(u,l,s):null,_}}]),i(e,[{key:"getPcHash",value:function(){return this.pcHash}},{key:"getSSRC",value:function(){return this.ssrc}},{key:"getStreamType",value:function(){return this.streamType}},{key:"getMediaType",value:function(){return this.mediaType}},{key:"getResolution",value:function(){return this.resolution?this.resolution.toString():null}},{key:"getFrameRateReceived",value:function(){return this.frameRateReceived}},{key:"getFrameHeight",value:function(){return this.frameHeight}},{key:"getFrameWidth",value:function(){return this.frameWidth}},{key:"getDroppedFramesNum",value:function(){return this.droppedFramesNum}},{key:"getJitter",value:function(){return this.jitter}},{key:"getRTT",value:function(){return this.rtt}},{key:"getLostPackets",value:function(){return this.lostPackets}},{key:"getDiscardedPackets",value:function(){return this.discardedPackets}},{key:"getReceivedPackets",value:function(){return this.receivedPackets}},{key:"getSentPackets",value:function(){return this.sentPackets}},{key:"getSentBytes",value:function(){return this.sentBytes}},{key:"getReceivedBytes",value:function(){return this.receivedBytes}},{key:"setFractionLost",value:function(e){this.fractionLost=void 0===e?null:e}},{key:"getFractionLost",value:function(){return this.fractionLost}},{key:"extractTrack",value:function(){var e=this.track;return this.track=null,e}},{key:"toString",value:function(){return"pcHash: "+this.pcHash+", ssrc: "+this.ssrc+", streamType: "+this.streamType+", mediaType: "+this.mediaType+", frameRateReceived: "+this.frameRateReceived+", frameHeight: "+this.frameHeight+", frameWidth: "+this.frameWidth+", droppedFramesNum: "+this.droppedFramesNum+", rtt: "+this.rtt+", jitter: "+this.jitter+", lostPackets: "+this.lostPackets+", receivedPackets: "+this.receivedPackets+", sentPackets: "+this.sentPackets+", discardedPackets: "+this.discardedPackets+", sentBytes: "+this.sentBytes+", receivedBytes: "+this.receivedBytes}}]),e}();n.Measurement=l},{"./resolution":67,"./validator":82}],60:[function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.CPULimitationObserver=void 0;var o=function(){function e(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:"0";r(this,e),this.mediaType=t,this.ssrc=n}return i(e,[{key:"getContent",value:function(){var e=this;return{mediaType:e.mediaType,ssrc:e.ssrc}}}]),e}();n.OneWayMediaDisruption=o},{}],66:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n0||parseInt(a.transportStats.bytesSent,10)>0)&&(n.transportStats.push(a.transportStats),"true"!==a.transportStats.googActiveConnection&&!0!==a.transportStats.googActiveConnection||(n.activeConnectionIndex=a.transportStats.length)):"true"!==a.transportStats.selected&&!0!==a.transportStats.selected||(n.transportStats.push(a.transportStats),n.activeConnectionIndex=a.transportStats.length):a.bwe?n.bwe=a.bwe:a.trackStats?n.trackStats.push(a.trackStats):a.codec?n.codec.push(a.codec):a.localCandidate?r[a.localCandidate.id]=a.localCandidate:a.remoteCandidate&&(i[a.remoteCandidate.id]=a.remoteCandidate)}if(n.tracks){var l=d.Registry.getConferenceManager().getConferenceForPcHash(t),c=void 0;l&&(c=l.getPeerConnectionManager().getPcHandlerByHash(t)),n.tracks.forEach(function(e){var t=c.getSSRCInfo(e.data.ssrc);void 0!==t&&t.localStartTime||c&&(c.updateSDP(n.tracks),t=c.getSSRCInfo(e.data.ssrc)),t&&(e.cname=t.cname,e.msid=t.msid,e.associatedVideoTag=t.associatedVideoTag,e.usageLabel=t.usageLabel)})}return n.transportStats&&this.codeBase===u.codeBaseType.firefox&&(n.transportStats=this.getAddressInfoFromCandidates(n.transportStats,r,i)),n}},{key:"getParsedStats",value:function(e){var t={};if(e.timestamp instanceof Date&&(t.timestamp=e.timestamp.getTime().toString()),e.type&&(t.type=e.type),e.names){for(var n=e.names(),r=0;r0)return n[0]}}},{key:"formatRelayType",value:function(e){var t="None";switch(e){case 0:t="TURN/TLS";break;case 1:t="TURN/TCP";break;case 2:t="TURN/UDP"}return t}},{key:"getRelayType",value:function(e,t){var n=this,r=void 0,i=function(t){if(t.typePreference){var i=t.typePreference>>24;return"rtp"===t.protocol&&t.address===e&&(i>=0&&i<=2&&(r=n.formatTypePreference(i)),!0)}return!1};return t.getIceCandidates().some(i),r}},{key:"getTransportInfo",value:function(e,t){for(var n={},r=!1,i=0;i2&&void 0!==arguments[2]?arguments[2]:null;r(this,t);var s=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n,o));return s.sum=0,s.counter=0,s}return o(t,e),s(t,[{key:"add",value:function(e){this.filter(e)&&(this.sum+=this.extract(e),++this.counter,this.calculate())}},{key:"remove",value:function(e){this.filter(e)&&(this.sum-=this.extract(e),--this.counter,this.calculate())}},{key:"calculate",value:function(){var e=0;return this.counter<1?void this.notify(e):(e=this.sum/this.counter,void this.notify(e))}}]),t}(a.SWPlugin);n.SWAvg=l},{"./swplugin":78}],76:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(n,"__esModule",{value:!0}),n.SWBTreePercentile=void 0;var s=function(){function e(e,t){var n=[],r=!0,i=!1,o=void 0;try{for(var s,a=e[Symbol.iterator]();!(r=(s=a.next()).done)&&(n.push(s.value),!t||n.length!==t);r=!0);}catch(e){i=!0,o=e}finally{try{!r&&a["return"]&&a["return"]()}finally{if(i)throw o}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),a=function(){function e(e,t){for(var n=0;n4&&void 0!==arguments[4]?arguments[4]:null,l=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,c=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null;r(this,t);var d=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,o,s,l));if(992&&void 0!==arguments[2]?arguments[2]:null;r(this,t);var s=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,null,null,o));return s.addFunc=e,s.remFunc=n,s}return o(t,e),s(t,[{key:"add",value:function(e){this.filter(e)&&this.addFunc&&this.addFunc(e)}},{key:"remove",value:function(e){this.filter(e)&&this.remFunc&&this.remFunc(e)}},{key:"toString",value:function(){return"SWFuncPlugin"}}]),t}(a.SWPlugin);n.SWFunctor=l},{"./swplugin":78}],78:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.SWPlugin=void 0;var i=function(){function e(e,t){for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:null;r(this,e),this.extractorFnc=t,this.notifierFnc=n,this.filterFunc=i}return i(e,[{key:"notify",value:function(e){return this.notifierFnc?void this.notifierFnc(e):void s.warn("Failed notification for "+this.toString())}},{key:"extract",value:function(e){return this.extractorFnc?this.extractorFnc(e):(s.warn(this.toString()+" tried to extract without extractorFnc"),null)}},{key:"filter",value:function(e){return!this.filterFunc||this.filterFunc(e)}},{key:"add",value:function(e){s.log("Abstract method is called width value: "+e)}},{key:"remove",value:function(e){s.log("Abstract method is called with value: "+e)}},{key:"toString",value:function(){return"SWPlugin"}}]),e}();n.SWPlugin=a},{"../../utility/csiologger":87}],79:[function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){return t.green<=e?b.avQualityRatings.excellent:t.red1&&void 0!==arguments[1]?arguments[1]:1,n={processFnc:e,weight:t};this.evaluators.push(n)}},{key:"getQuality",value:function(e){for(var t=0,n=[],r=0,i=0;i1&&void 0!==arguments[1]?arguments[1]:1;this.qualityHelper.addEvaluator(e,t)}},{key:"getQuality",value:function(e){return this.qualityHelper.getQuality(e)}},{key:"addPreProcess",value:function(e){u(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"addPreProcess",this).call(this,e)}},{key:"addPostProcess",value:function(e){u(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"addPostProcess",this).call(this,e)}}]),t}(f.SlidingWindow);n.TrackMonitor=C},{"../collections/slidingwindow":27,"../config/constants":32,"../statspipeline/swplugins/swavg":75,"../statspipeline/swplugins/swbtreepercentile":76,"../statspipeline/swplugins/swfunctor":77,"../utility/csiologger":87,"../utility/registry":94,"../utility/timestamps":98}],80:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.TracksMonitor=void 0;var i=function(){function e(e,t){for(var n=0;n3&&void 0!==arguments[3]?arguments[3]:{};if("string"!=typeof e||null===r||"object"!==(void 0===r?"undefined":o(r)))return f.error("failed typeof checks:",e,void 0===e?"undefined":o(e),void 0===r?"undefined":o(r),r),c.Registry.getGenericEventHandler().sendEvent(u.logEvents.error,{msg:"failed typeof checks:"+e+":"+(void 0===r?"undefined":o(r))}),!1;if(null===t&&e!==u.precalltestEvents.results)return f.error("failed conferenceId checks:",e,t),c.Registry.getGenericEventHandler().sendEvent(u.logEvents.error,{msg:"failed conferenceId checks:"+e}),!1;if(!n&&e!==u.callstatsChannels.userFeedback&&e!==u.fabricEvent.applicationErrorLog&&e!==u.fabricEvent.fabricSetupFailed&&e!==u.precalltestEvents.results)return f.error("peerconnection cannot be null",e),c.Registry.getGenericEventHandler().sendEvent(u.logEvents.error,{msg:"peerconnection cannot be null"+e}),!1;if(!a.EventMessage.checkCustomEntries(e,r))return f.error("failed checks:",e,r),c.Registry.getGenericEventHandler().sendEvent(u.logEvents.error,{msg:"failed customEntries checks:"+e}),!1;var i=void 0;if(t){var s=c.Registry.getConferenceManager().get(t);s&&n&&(i=s.getPeerConnectionManager().getPcHandler(n))}var l=new a.EventMessage(e,t,r,i);return this.transmissionmanager.send(l),!0}}]),e}();n.EventMessageBuilder=h},{"../config/constants":32,"./csiologger":87,"./eventmessage":89,"./registry":94}],91:[function(e,t,n){"use strict";function r(e,t){var n={name:"SHA-256"};if(window.crypto){var r=window.crypto.subtle||window.crypto.webkitSubtle;if(!r)return void i(e,t);r.digest(n,o(e)).then(function(e){t(s(e))})["catch"](function(){i(e,t)})}else if(window.msCrypto){if(!window.msCrypto.subtle)return void i(e,t);var a=window.msCrypto.subtle.digest(n,o(e));a.oncomplete=function(e){e.target&&t(s(e.target.result))},a.onerror=function(){i(e,t)}}else i(e,t)}function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=0;if(!e)return n;for(var r=0,i=e.length;r127&&r<2048?(t[t.length]=r>>6|192,t[t.length]=63&r|128):(t[t.length]=r>>12|224,t[t.length]=r>>6&63|128,t[t.length]=63&r|128)}return new Uint8Array(t).buffer}function s(e){for(var t=new DataView(e),n="",r=void 0,i=0;i-1){for(var n=!1,r={fileName:e.filename,line:e.lineno,col:e.colno,jsVersion:a.version,eventType:"error",message:e.message,pageURL:window.location.href},i=o.Registry.getConferenceManager().getConferenceIds(),s=0;s0&&void 0!==arguments[0]?arguments[0]:1;return this.actualStep+=e,this.max/(1+Math.exp(-1*this.stepness*(this.actualStep-this.midpoint)))}}]),e}();n.Sigmoid=o},{}],97:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0}),n.TimeoutProcess=void 0;var i=function(){function e(e,t){for(var n=0;n1?n-1:0),o=1;o 0; ) { + var b = a.shift(); + if ("function" == typeof b) { + var c = a.shift(), d = a.shift(); + b.call(c, d); + } else b._settlePromises(); + } + }, e.prototype._drainQueues = function() { + this._drainQueue(this._normalQueue), this._reset(), this._haveDrainedQueues = !0, + this._drainQueue(this._lateQueue); + }, e.prototype._queueTick = function() { + this._isTickUsed || (this._isTickUsed = !0, this._schedule(this.drainQueues)); + }, e.prototype._reset = function() { + this._isTickUsed = !1; + }, c.exports = e, c.exports.firstLineError = i; + }, { + "./queue": 26, + "./schedule": 29, + "./util": 36 + } ], + 3: [ function(a, b, c) { + "use strict"; + b.exports = function(a, b, c, d) { + var e = !1, f = function(a, b) { + this._reject(b); + }, g = function(a, b) { + b.promiseRejectionQueued = !0, b.bindingPromise._then(f, f, null, this, a); + }, h = function(a, b) { + 0 == (50397184 & this._bitField) && this._resolveCallback(b.target); + }, i = function(a, b) { + b.promiseRejectionQueued || this._reject(a); + }; + a.prototype.bind = function(f) { + e || (e = !0, a.prototype._propagateFrom = d.propagateFromFunction(), a.prototype._boundValue = d.boundValueFunction()); + var j = c(f), k = new a(b); + k._propagateFrom(this, 1); + var l = this._target(); + if (k._setBoundTo(j), j instanceof a) { + var m = { + promiseRejectionQueued: !1, + promise: k, + target: l, + bindingPromise: j + }; + l._then(b, g, void 0, k, m), j._then(h, i, void 0, k, m), k._setOnCancel(j); + } else k._resolveCallback(l); + return k; + }, a.prototype._setBoundTo = function(a) { + void 0 !== a ? (this._bitField = 2097152 | this._bitField, this._boundTo = a) : this._bitField = -2097153 & this._bitField; + }, a.prototype._isBound = function() { + return 2097152 == (2097152 & this._bitField); + }, a.bind = function(b, c) { + return a.resolve(c).bind(b); + }; + }; + }, {} ], + 4: [ function(a, b, c) { + "use strict"; + function d() { + try { + Promise === f && (Promise = e); + } catch (a) {} + return f; + } + var e; + "undefined" != typeof Promise && (e = Promise); + var f = a("./promise")(); + f.noConflict = d, b.exports = f; + }, { + "./promise": 22 + } ], + 5: [ function(a, b, c) { + "use strict"; + var d = Object.create; + if (d) { + var e = d(null), f = d(null); + e[" size"] = f[" size"] = 0; + } + b.exports = function(b) { + function c(a, c) { + var d; + if (null != a && (d = a[c]), "function" != typeof d) { + var e = "Object " + h.classString(a) + " has no method '" + h.toString(c) + "'"; + throw new b.TypeError(e); + } + return d; + } + function d(a) { + return c(a, this.pop()).apply(a, this); + } + function e(a) { + return a[this]; + } + function f(a) { + var b = +this; + return b < 0 && (b = Math.max(0, b + a.length)), a[b]; + } + var g, h = a("./util"), i = h.canEvaluate; + h.isIdentifier; + b.prototype.call = function(a) { + var b = [].slice.call(arguments, 1); + return b.push(a), this._then(d, void 0, void 0, b, void 0); + }, b.prototype.get = function(a) { + var b, c = "number" == typeof a; + if (c) b = f; else if (i) { + var d = g(a); + b = null !== d ? d : e; + } else b = e; + return this._then(b, void 0, void 0, a, void 0); + }; + }; + }, { + "./util": 36 + } ], + 6: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d, e) { + var f = a("./util"), g = f.tryCatch, h = f.errorObj, i = b._async; + b.prototype.break = b.prototype.cancel = function() { + if (!e.cancellation()) return this._warn("cancellation is disabled"); + for (var a = this, b = a; a._isCancellable(); ) { + if (!a._cancelBy(b)) { + b._isFollowing() ? b._followee().cancel() : b._cancelBranched(); + break; + } + var c = a._cancellationParent; + if (null == c || !c._isCancellable()) { + a._isFollowing() ? a._followee().cancel() : a._cancelBranched(); + break; + } + a._isFollowing() && a._followee().cancel(), a._setWillBeCancelled(), b = a, a = c; + } + }, b.prototype._branchHasCancelled = function() { + this._branchesRemainingToCancel--; + }, b.prototype._enoughBranchesHaveCancelled = function() { + return void 0 === this._branchesRemainingToCancel || this._branchesRemainingToCancel <= 0; + }, b.prototype._cancelBy = function(a) { + return a === this ? (this._branchesRemainingToCancel = 0, this._invokeOnCancel(), + !0) : (this._branchHasCancelled(), !!this._enoughBranchesHaveCancelled() && (this._invokeOnCancel(), + !0)); + }, b.prototype._cancelBranched = function() { + this._enoughBranchesHaveCancelled() && this._cancel(); + }, b.prototype._cancel = function() { + this._isCancellable() && (this._setCancelled(), i.invoke(this._cancelPromises, this, void 0)); + }, b.prototype._cancelPromises = function() { + this._length() > 0 && this._settlePromises(); + }, b.prototype._unsetOnCancel = function() { + this._onCancelField = void 0; + }, b.prototype._isCancellable = function() { + return this.isPending() && !this._isCancelled(); + }, b.prototype.isCancellable = function() { + return this.isPending() && !this.isCancelled(); + }, b.prototype._doInvokeOnCancel = function(a, b) { + if (f.isArray(a)) for (var c = 0; c < a.length; ++c) this._doInvokeOnCancel(a[c], b); else if (void 0 !== a) if ("function" == typeof a) { + if (!b) { + var d = g(a).call(this._boundValue()); + d === h && (this._attachExtraTrace(d.e), i.throwLater(d.e)); + } + } else a._resultCancelled(this); + }, b.prototype._invokeOnCancel = function() { + var a = this._onCancel(); + this._unsetOnCancel(), i.invoke(this._doInvokeOnCancel, this, a); + }, b.prototype._invokeInternalOnCancel = function() { + this._isCancellable() && (this._doInvokeOnCancel(this._onCancel(), !0), this._unsetOnCancel()); + }, b.prototype._resultCancelled = function() { + this.cancel(); + }; + }; + }, { + "./util": 36 + } ], + 7: [ function(a, b, c) { + "use strict"; + b.exports = function(b) { + function c(a, c, h) { + return function(i) { + var j = h._boundValue(); + a: for (var k = 0; k < a.length; ++k) { + var l = a[k]; + if (l === Error || null != l && l.prototype instanceof Error) { + if (i instanceof l) return f(c).call(j, i); + } else if ("function" == typeof l) { + var m = f(l).call(j, i); + if (m === g) return m; + if (m) return f(c).call(j, i); + } else if (d.isObject(i)) { + for (var n = e(l), o = 0; o < n.length; ++o) { + var p = n[o]; + if (l[p] != i[p]) continue a; + } + return f(c).call(j, i); + } + } + return b; + }; + } + var d = a("./util"), e = a("./es5").keys, f = d.tryCatch, g = d.errorObj; + return c; + }; + }, { + "./es5": 13, + "./util": 36 + } ], + 8: [ function(a, b, c) { + "use strict"; + b.exports = function(a) { + function b() { + this._trace = new b.CapturedTrace(d()); + } + function c() { + if (e) return new b(); + } + function d() { + var a = f.length - 1; + if (a >= 0) return f[a]; + } + var e = !1, f = []; + return a.prototype._promiseCreated = function() {}, a.prototype._pushContext = function() {}, + a.prototype._popContext = function() { + return null; + }, a._peekContext = a.prototype._peekContext = function() {}, b.prototype._pushContext = function() { + void 0 !== this._trace && (this._trace._promiseCreated = null, f.push(this._trace)); + }, b.prototype._popContext = function() { + if (void 0 !== this._trace) { + var a = f.pop(), b = a._promiseCreated; + return a._promiseCreated = null, b; + } + return null; + }, b.CapturedTrace = null, b.create = c, b.deactivateLongStackTraces = function() {}, + b.activateLongStackTraces = function() { + var c = a.prototype._pushContext, f = a.prototype._popContext, g = a._peekContext, h = a.prototype._peekContext, i = a.prototype._promiseCreated; + b.deactivateLongStackTraces = function() { + a.prototype._pushContext = c, a.prototype._popContext = f, a._peekContext = g, a.prototype._peekContext = h, + a.prototype._promiseCreated = i, e = !1; + }, e = !0, a.prototype._pushContext = b.prototype._pushContext, a.prototype._popContext = b.prototype._popContext, + a._peekContext = a.prototype._peekContext = d, a.prototype._promiseCreated = function() { + var a = this._peekContext(); + a && null == a._promiseCreated && (a._promiseCreated = this); + }; + }, b; + }; + }, {} ], + 9: [ function(b, c, d) { + "use strict"; + c.exports = function(c, d) { + function e(a, b) { + return { + promise: b + }; + } + function f() { + return !1; + } + function g(a, b, c) { + var d = this; + try { + a(b, c, function(a) { + if ("function" != typeof a) throw new TypeError("onCancel must be a function, got: " + N.toString(a)); + d._attachCancellationCallback(a); + }); + } catch (a) { + return a; + } + } + function h(a) { + if (!this._isCancellable()) return this; + var b = this._onCancel(); + void 0 !== b ? N.isArray(b) ? b.push(a) : this._setOnCancel([ b, a ]) : this._setOnCancel(a); + } + function i() { + return this._onCancelField; + } + function j(a) { + this._onCancelField = a; + } + function k() { + this._cancellationParent = void 0, this._onCancelField = void 0; + } + function l(a, b) { + if (0 != (1 & b)) { + this._cancellationParent = a; + var c = a._branchesRemainingToCancel; + void 0 === c && (c = 0), a._branchesRemainingToCancel = c + 1; + } + 0 != (2 & b) && a._isBound() && this._setBoundTo(a._boundTo); + } + function m(a, b) { + 0 != (2 & b) && a._isBound() && this._setBoundTo(a._boundTo); + } + function n() { + var a = this._boundTo; + return void 0 !== a && a instanceof c ? a.isFulfilled() ? a.value() : void 0 : a; + } + function o() { + this._trace = new G(this._peekContext()); + } + function p(a, b) { + if (O(a)) { + var c = this._trace; + if (void 0 !== c && b && (c = c._parent), void 0 !== c) c.attachExtraTrace(a); else if (!a.__stackCleaned__) { + var d = y(a); + N.notEnumerableProp(a, "stack", d.message + "\n" + d.stack.join("\n")), N.notEnumerableProp(a, "__stackCleaned__", !0); + } + } + } + function q(a, b, c, d, e) { + if (void 0 === a && null !== b && Y) { + if (void 0 !== e && e._returnedNonUndefined()) return; + if (0 == (65535 & d._bitField)) return; + c && (c += " "); + var f = "", g = ""; + if (b._trace) { + for (var h = b._trace.stack.split("\n"), i = w(h), j = i.length - 1; j >= 0; --j) { + var k = i[j]; + if (!Q.test(k)) { + var l = k.match(R); + l && (f = "at " + l[1] + ":" + l[2] + ":" + l[3] + " "); + break; + } + } + if (i.length > 0) for (var m = i[0], j = 0; j < h.length; ++j) if (h[j] === m) { + j > 0 && (g = "\n" + h[j - 1]); + break; + } + } + var n = "a promise was created in a " + c + "handler " + f + "but was not returned from it, see http://goo.gl/rRqMUw" + g; + d._warn(n, !0, b); + } + } + function r(a, b) { + var c = a + " is deprecated and will be removed in a future version."; + return b && (c += " Use " + b + " instead."), s(c); + } + function s(a, b, d) { + if (ga.warnings) { + var e, f = new M(a); + if (b) d._attachExtraTrace(f); else if (ga.longStackTraces && (e = c._peekContext())) e.attachExtraTrace(f); else { + var g = y(f); + f.stack = g.message + "\n" + g.stack.join("\n"); + } + ba("warning", f) || z(f, "", !0); + } + } + function t(a, b) { + for (var c = 0; c < b.length - 1; ++c) b[c].push("From previous event:"), b[c] = b[c].join("\n"); + return c < b.length && (b[c] = b[c].join("\n")), a + "\n" + b.join("\n"); + } + function u(a) { + for (var b = 0; b < a.length; ++b) (0 === a[b].length || b + 1 < a.length && a[b][0] === a[b + 1][0]) && (a.splice(b, 1), + b--); + } + function v(a) { + for (var b = a[0], c = 1; c < a.length; ++c) { + for (var d = a[c], e = b.length - 1, f = b[e], g = -1, h = d.length - 1; h >= 0; --h) if (d[h] === f) { + g = h; + break; + } + for (var h = g; h >= 0; --h) { + var i = d[h]; + if (b[e] !== i) break; + b.pop(), e--; + } + b = d; + } + } + function w(a) { + for (var b = [], c = 0; c < a.length; ++c) { + var d = a[c], e = " (No stack trace)" === d || S.test(d), f = e && da(d); + e && !f && (U && " " !== d.charAt(0) && (d = " " + d), b.push(d)); + } + return b; + } + function x(a) { + for (var b = a.stack.replace(/\s+$/g, "").split("\n"), c = 0; c < b.length; ++c) { + var d = b[c]; + if (" (No stack trace)" === d || S.test(d)) break; + } + return c > 0 && "SyntaxError" != a.name && (b = b.slice(c)), b; + } + function y(a) { + var b = a.stack, c = a.toString(); + return b = "string" == typeof b && b.length > 0 ? x(a) : [ " (No stack trace)" ], + { + message: c, + stack: "SyntaxError" == a.name ? b : w(b) + }; + } + function z(a, b, c) { + if ("undefined" != typeof console) { + var d; + if (N.isObject(a)) { + var e = a.stack; + d = b + T(e, a); + } else d = b + String(a); + "function" == typeof J ? J(d, c) : "function" != typeof console.log && "object" != typeof console.log || console.log(d); + } + } + function A(a, b, c, d) { + var e = !1; + try { + "function" == typeof b && (e = !0, "rejectionHandled" === a ? b(d) : b(c, d)); + } catch (a) { + L.throwLater(a); + } + "unhandledRejection" === a ? ba(a, c, d) || e || z(c, "Unhandled rejection ") : ba(a, d); + } + function B(a) { + var b; + if ("function" == typeof a) b = "[function " + (a.name || "anonymous") + "]"; else { + b = a && "function" == typeof a.toString ? a.toString() : N.toString(a); + if (/\[object [a-zA-Z0-9$_]+\]/.test(b)) try { + b = JSON.stringify(a); + } catch (a) {} + 0 === b.length && (b = "(empty array)"); + } + return "(<" + C(b) + ">, no stack trace)"; + } + function C(a) { + return a.length < 41 ? a : a.substr(0, 38) + "..."; + } + function D() { + return "function" == typeof fa; + } + function E(a) { + var b = a.match(ea); + if (b) return { + fileName: b[1], + line: parseInt(b[2], 10) + }; + } + function F(a, b) { + if (D()) { + for (var c, d, e = a.stack.split("\n"), f = b.stack.split("\n"), g = -1, h = -1, i = 0; i < e.length; ++i) { + var j = E(e[i]); + if (j) { + c = j.fileName, g = j.line; + break; + } + } + for (var i = 0; i < f.length; ++i) { + var j = E(f[i]); + if (j) { + d = j.fileName, h = j.line; + break; + } + } + g < 0 || h < 0 || !c || !d || c !== d || g >= h || (da = function(a) { + if (P.test(a)) return !0; + var b = E(a); + return !!(b && b.fileName === c && g <= b.line && b.line <= h); + }); + } + } + function G(a) { + this._parent = a, this._promisesCreated = 0; + var b = this._length = 1 + (void 0 === a ? 0 : a._length); + fa(this, G), b > 32 && this.uncycle(); + } + var H, I, J, K = c._getDomain, L = c._async, M = b("./errors").Warning, N = b("./util"), O = N.canAttachTrace, P = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/, Q = /\((?:timers\.js):\d+:\d+\)/, R = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/, S = null, T = null, U = !1, V = !(0 == N.env("BLUEBIRD_DEBUG")), W = !(0 == N.env("BLUEBIRD_WARNINGS") || !V && !N.env("BLUEBIRD_WARNINGS")), X = !(0 == N.env("BLUEBIRD_LONG_STACK_TRACES") || !V && !N.env("BLUEBIRD_LONG_STACK_TRACES")), Y = 0 != N.env("BLUEBIRD_W_FORGOTTEN_RETURN") && (W || !!N.env("BLUEBIRD_W_FORGOTTEN_RETURN")); + c.prototype.suppressUnhandledRejections = function() { + var a = this._target(); + a._bitField = -1048577 & a._bitField | 524288; + }, c.prototype._ensurePossibleRejectionHandled = function() { + if (0 == (524288 & this._bitField)) { + this._setRejectionIsUnhandled(); + var a = this; + setTimeout(function() { + a._notifyUnhandledRejection(); + }, 1); + } + }, c.prototype._notifyUnhandledRejectionIsHandled = function() { + A("rejectionHandled", H, void 0, this); + }, c.prototype._setReturnedNonUndefined = function() { + this._bitField = 268435456 | this._bitField; + }, c.prototype._returnedNonUndefined = function() { + return 0 != (268435456 & this._bitField); + }, c.prototype._notifyUnhandledRejection = function() { + if (this._isRejectionUnhandled()) { + var a = this._settledValue(); + this._setUnhandledRejectionIsNotified(), A("unhandledRejection", I, a, this); + } + }, c.prototype._setUnhandledRejectionIsNotified = function() { + this._bitField = 262144 | this._bitField; + }, c.prototype._unsetUnhandledRejectionIsNotified = function() { + this._bitField = -262145 & this._bitField; + }, c.prototype._isUnhandledRejectionNotified = function() { + return (262144 & this._bitField) > 0; + }, c.prototype._setRejectionIsUnhandled = function() { + this._bitField = 1048576 | this._bitField; + }, c.prototype._unsetRejectionIsUnhandled = function() { + this._bitField = -1048577 & this._bitField, this._isUnhandledRejectionNotified() && (this._unsetUnhandledRejectionIsNotified(), + this._notifyUnhandledRejectionIsHandled()); + }, c.prototype._isRejectionUnhandled = function() { + return (1048576 & this._bitField) > 0; + }, c.prototype._warn = function(a, b, c) { + return s(a, b, c || this); + }, c.onPossiblyUnhandledRejection = function(a) { + var b = K(); + I = "function" == typeof a ? null === b ? a : N.domainBind(b, a) : void 0; + }, c.onUnhandledRejectionHandled = function(a) { + var b = K(); + H = "function" == typeof a ? null === b ? a : N.domainBind(b, a) : void 0; + }; + var Z = function() {}; + c.longStackTraces = function() { + if (L.haveItemsQueued() && !ga.longStackTraces) throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n"); + if (!ga.longStackTraces && D()) { + var a = c.prototype._captureStackTrace, b = c.prototype._attachExtraTrace; + ga.longStackTraces = !0, Z = function() { + if (L.haveItemsQueued() && !ga.longStackTraces) throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n"); + c.prototype._captureStackTrace = a, c.prototype._attachExtraTrace = b, d.deactivateLongStackTraces(), + L.enableTrampoline(), ga.longStackTraces = !1; + }, c.prototype._captureStackTrace = o, c.prototype._attachExtraTrace = p, d.activateLongStackTraces(), + L.disableTrampolineIfNecessary(); + } + }, c.hasLongStackTraces = function() { + return ga.longStackTraces && D(); + }; + var $ = function() { + try { + if ("function" == typeof CustomEvent) { + var a = new CustomEvent("CustomEvent"); + return N.global.dispatchEvent(a), function(a, b) { + var c = new CustomEvent(a.toLowerCase(), { + detail: b, + cancelable: !0 + }); + return !N.global.dispatchEvent(c); + }; + } + if ("function" == typeof Event) { + var a = new Event("CustomEvent"); + return N.global.dispatchEvent(a), function(a, b) { + var c = new Event(a.toLowerCase(), { + cancelable: !0 + }); + return c.detail = b, !N.global.dispatchEvent(c); + }; + } + var a = document.createEvent("CustomEvent"); + return a.initCustomEvent("testingtheevent", !1, !0, {}), N.global.dispatchEvent(a), + function(a, b) { + var c = document.createEvent("CustomEvent"); + return c.initCustomEvent(a.toLowerCase(), !1, !0, b), !N.global.dispatchEvent(c); + }; + } catch (a) {} + return function() { + return !1; + }; + }(), _ = function() { + return N.isNode ? function() { + return a.emit.apply(a, arguments); + } : N.global ? function(a) { + var b = "on" + a.toLowerCase(), c = N.global[b]; + return !!c && (c.apply(N.global, [].slice.call(arguments, 1)), !0); + } : function() { + return !1; + }; + }(), aa = { + promiseCreated: e, + promiseFulfilled: e, + promiseRejected: e, + promiseResolved: e, + promiseCancelled: e, + promiseChained: function(a, b, c) { + return { + promise: b, + child: c + }; + }, + warning: function(a, b) { + return { + warning: b + }; + }, + unhandledRejection: function(a, b, c) { + return { + reason: b, + promise: c + }; + }, + rejectionHandled: e + }, ba = function(a) { + var b = !1; + try { + b = _.apply(null, arguments); + } catch (a) { + L.throwLater(a), b = !0; + } + var c = !1; + try { + c = $(a, aa[a].apply(null, arguments)); + } catch (a) { + L.throwLater(a), c = !0; + } + return c || b; + }; + c.config = function(a) { + if (a = Object(a), "longStackTraces" in a && (a.longStackTraces ? c.longStackTraces() : !a.longStackTraces && c.hasLongStackTraces() && Z()), + "warnings" in a) { + var b = a.warnings; + ga.warnings = !!b, Y = ga.warnings, N.isObject(b) && "wForgottenReturn" in b && (Y = !!b.wForgottenReturn); + } + if ("cancellation" in a && a.cancellation && !ga.cancellation) { + if (L.haveItemsQueued()) throw new Error("cannot enable cancellation after promises are in use"); + c.prototype._clearCancellationData = k, c.prototype._propagateFrom = l, c.prototype._onCancel = i, + c.prototype._setOnCancel = j, c.prototype._attachCancellationCallback = h, c.prototype._execute = g, + ca = l, ga.cancellation = !0; + } + return "monitoring" in a && (a.monitoring && !ga.monitoring ? (ga.monitoring = !0, + c.prototype._fireEvent = ba) : !a.monitoring && ga.monitoring && (ga.monitoring = !1, + c.prototype._fireEvent = f)), c; + }, c.prototype._fireEvent = f, c.prototype._execute = function(a, b, c) { + try { + a(b, c); + } catch (a) { + return a; + } + }, c.prototype._onCancel = function() {}, c.prototype._setOnCancel = function(a) {}, + c.prototype._attachCancellationCallback = function(a) {}, c.prototype._captureStackTrace = function() {}, + c.prototype._attachExtraTrace = function() {}, c.prototype._clearCancellationData = function() {}, + c.prototype._propagateFrom = function(a, b) {}; + var ca = m, da = function() { + return !1; + }, ea = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; + N.inherits(G, Error), d.CapturedTrace = G, G.prototype.uncycle = function() { + var a = this._length; + if (!(a < 2)) { + for (var b = [], c = {}, d = 0, e = this; void 0 !== e; ++d) b.push(e), e = e._parent; + a = this._length = d; + for (var d = a - 1; d >= 0; --d) { + var f = b[d].stack; + void 0 === c[f] && (c[f] = d); + } + for (var d = 0; d < a; ++d) { + var g = b[d].stack, h = c[g]; + if (void 0 !== h && h !== d) { + h > 0 && (b[h - 1]._parent = void 0, b[h - 1]._length = 1), b[d]._parent = void 0, + b[d]._length = 1; + var i = d > 0 ? b[d - 1] : this; + h < a - 1 ? (i._parent = b[h + 1], i._parent.uncycle(), i._length = i._parent._length + 1) : (i._parent = void 0, + i._length = 1); + for (var j = i._length + 1, k = d - 2; k >= 0; --k) b[k]._length = j, j++; + return; + } + } + } + }, G.prototype.attachExtraTrace = function(a) { + if (!a.__stackCleaned__) { + this.uncycle(); + for (var b = y(a), c = b.message, d = [ b.stack ], e = this; void 0 !== e; ) d.push(w(e.stack.split("\n"))), + e = e._parent; + v(d), u(d), N.notEnumerableProp(a, "stack", t(c, d)), N.notEnumerableProp(a, "__stackCleaned__", !0); + } + }; + var fa = function() { + var a = /^\s*at\s*/, b = function(a, b) { + return "string" == typeof a ? a : void 0 !== b.name && void 0 !== b.message ? b.toString() : B(b); + }; + if ("number" == typeof Error.stackTraceLimit && "function" == typeof Error.captureStackTrace) { + Error.stackTraceLimit += 6, S = a, T = b; + var c = Error.captureStackTrace; + return da = function(a) { + return P.test(a); + }, function(a, b) { + Error.stackTraceLimit += 6, c(a, b), Error.stackTraceLimit -= 6; + }; + } + var d = new Error(); + if ("string" == typeof d.stack && d.stack.split("\n")[0].indexOf("stackDetection@") >= 0) return S = /@/, + T = b, U = !0, function(a) { + a.stack = new Error().stack; + }; + var e; + try { + throw new Error(); + } catch (a) { + e = "stack" in a; + } + return "stack" in d || !e || "number" != typeof Error.stackTraceLimit ? (T = function(a, b) { + return "string" == typeof a ? a : "object" != typeof b && "function" != typeof b || void 0 === b.name || void 0 === b.message ? B(b) : b.toString(); + }, null) : (S = a, T = b, function(a) { + Error.stackTraceLimit += 6; + try { + throw new Error(); + } catch (b) { + a.stack = b.stack; + } + Error.stackTraceLimit -= 6; + }); + }(); + "undefined" != typeof console && void 0 !== console.warn && (J = function(a) { + console.warn(a); + }, N.isNode && a.stderr.isTTY ? J = function(a, b) { + var c = b ? "" : ""; + console.warn(c + a + "\n"); + } : N.isNode || "string" != typeof new Error().stack || (J = function(a, b) { + console.warn("%c" + a, b ? "color: darkorange" : "color: red"); + })); + var ga = { + warnings: W, + longStackTraces: !1, + cancellation: !1, + monitoring: !1 + }; + return X && c.longStackTraces(), { + longStackTraces: function() { + return ga.longStackTraces; + }, + warnings: function() { + return ga.warnings; + }, + cancellation: function() { + return ga.cancellation; + }, + monitoring: function() { + return ga.monitoring; + }, + propagateFromFunction: function() { + return ca; + }, + boundValueFunction: function() { + return n; + }, + checkForgottenReturns: q, + setBounds: F, + warn: s, + deprecated: r, + CapturedTrace: G, + fireDomEvent: $, + fireGlobalEvent: _ + }; + }; + }, { + "./errors": 12, + "./util": 36 + } ], + 10: [ function(a, b, c) { + "use strict"; + b.exports = function(a) { + function b() { + return this.value; + } + function c() { + throw this.reason; + } + a.prototype.return = a.prototype.thenReturn = function(c) { + return c instanceof a && c.suppressUnhandledRejections(), this._then(b, void 0, void 0, { + value: c + }, void 0); + }, a.prototype.throw = a.prototype.thenThrow = function(a) { + return this._then(c, void 0, void 0, { + reason: a + }, void 0); + }, a.prototype.catchThrow = function(a) { + if (arguments.length <= 1) return this._then(void 0, c, void 0, { + reason: a + }, void 0); + var b = arguments[1], d = function() { + throw b; + }; + return this.caught(a, d); + }, a.prototype.catchReturn = function(c) { + if (arguments.length <= 1) return c instanceof a && c.suppressUnhandledRejections(), + this._then(void 0, b, void 0, { + value: c + }, void 0); + var d = arguments[1]; + d instanceof a && d.suppressUnhandledRejections(); + var e = function() { + return d; + }; + return this.caught(c, e); + }; + }; + }, {} ], + 11: [ function(a, b, c) { + "use strict"; + b.exports = function(a, b) { + function c() { + return f(this); + } + function d(a, c) { + return e(a, c, b, b); + } + var e = a.reduce, f = a.all; + a.prototype.each = function(a) { + return e(this, a, b, 0)._then(c, void 0, void 0, this, void 0); + }, a.prototype.mapSeries = function(a) { + return e(this, a, b, b); + }, a.each = function(a, d) { + return e(a, d, b, 0)._then(c, void 0, void 0, a, void 0); + }, a.mapSeries = d; + }; + }, {} ], + 12: [ function(a, b, c) { + "use strict"; + function d(a, b) { + function c(d) { + if (!(this instanceof c)) return new c(d); + l(this, "message", "string" == typeof d ? d : b), l(this, "name", a), Error.captureStackTrace ? Error.captureStackTrace(this, this.constructor) : Error.call(this); + } + return k(c, Error), c; + } + function e(a) { + if (!(this instanceof e)) return new e(a); + l(this, "name", "OperationalError"), l(this, "message", a), this.cause = a, this.isOperational = !0, + a instanceof Error ? (l(this, "message", a.message), l(this, "stack", a.stack)) : Error.captureStackTrace && Error.captureStackTrace(this, this.constructor); + } + var f, g, h = a("./es5"), i = h.freeze, j = a("./util"), k = j.inherits, l = j.notEnumerableProp, m = d("Warning", "warning"), n = d("CancellationError", "cancellation error"), o = d("TimeoutError", "timeout error"), p = d("AggregateError", "aggregate error"); + try { + f = TypeError, g = RangeError; + } catch (a) { + f = d("TypeError", "type error"), g = d("RangeError", "range error"); + } + for (var q = "join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "), r = 0; r < q.length; ++r) "function" == typeof Array.prototype[q[r]] && (p.prototype[q[r]] = Array.prototype[q[r]]); + h.defineProperty(p.prototype, "length", { + value: 0, + configurable: !1, + writable: !0, + enumerable: !0 + }), p.prototype.isOperational = !0; + var s = 0; + p.prototype.toString = function() { + var a = Array(4 * s + 1).join(" "), b = "\n" + a + "AggregateError of:\n"; + s++, a = Array(4 * s + 1).join(" "); + for (var c = 0; c < this.length; ++c) { + for (var d = this[c] === this ? "[Circular AggregateError]" : this[c] + "", e = d.split("\n"), f = 0; f < e.length; ++f) e[f] = a + e[f]; + d = e.join("\n"), b += d + "\n"; + } + return s--, b; + }, k(e, Error); + var t = Error.__BluebirdErrorTypes__; + t || (t = i({ + CancellationError: n, + TimeoutError: o, + OperationalError: e, + RejectionError: e, + AggregateError: p + }), h.defineProperty(Error, "__BluebirdErrorTypes__", { + value: t, + writable: !1, + enumerable: !1, + configurable: !1 + })), b.exports = { + Error: Error, + TypeError: f, + RangeError: g, + CancellationError: t.CancellationError, + OperationalError: t.OperationalError, + TimeoutError: t.TimeoutError, + AggregateError: t.AggregateError, + Warning: m + }; + }, { + "./es5": 13, + "./util": 36 + } ], + 13: [ function(a, b, c) { + var d = function() { + "use strict"; + return void 0 === this; + }(); + if (d) b.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + getPrototypeOf: Object.getPrototypeOf, + isArray: Array.isArray, + isES5: d, + propertyIsWritable: function(a, b) { + var c = Object.getOwnPropertyDescriptor(a, b); + return !(c && !c.writable && !c.set); + } + }; else { + var e = {}.hasOwnProperty, f = {}.toString, g = {}.constructor.prototype, h = function(a) { + var b = []; + for (var c in a) e.call(a, c) && b.push(c); + return b; + }, i = function(a, b) { + return { + value: a[b] + }; + }, j = function(a, b, c) { + return a[b] = c.value, a; + }, k = function(a) { + return a; + }, l = function(a) { + try { + return Object(a).constructor.prototype; + } catch (a) { + return g; + } + }, m = function(a) { + try { + return "[object Array]" === f.call(a); + } catch (a) { + return !1; + } + }; + b.exports = { + isArray: m, + keys: h, + names: h, + defineProperty: j, + getDescriptor: i, + freeze: k, + getPrototypeOf: l, + isES5: d, + propertyIsWritable: function() { + return !0; + } + }; + } + }, {} ], + 14: [ function(a, b, c) { + "use strict"; + b.exports = function(a, b) { + var c = a.map; + a.prototype.filter = function(a, d) { + return c(this, a, d, b); + }, a.filter = function(a, d, e) { + return c(a, d, e, b); + }; + }; + }, {} ], + 15: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d) { + function e(a, b, c) { + this.promise = a, this.type = b, this.handler = c, this.called = !1, this.cancelPromise = null; + } + function f(a) { + this.finallyHandler = a; + } + function g(a, b) { + return null != a.cancelPromise && (arguments.length > 1 ? a.cancelPromise._reject(b) : a.cancelPromise._cancel(), + a.cancelPromise = null, !0); + } + function h() { + return j.call(this, this.promise._target()._settledValue()); + } + function i(a) { + if (!g(this, a)) return m.e = a, m; + } + function j(a) { + var e = this.promise, j = this.handler; + if (!this.called) { + this.called = !0; + var k = this.isFinallyHandler() ? j.call(e._boundValue()) : j.call(e._boundValue(), a); + if (k === d) return k; + if (void 0 !== k) { + e._setReturnedNonUndefined(); + var n = c(k, e); + if (n instanceof b) { + if (null != this.cancelPromise) { + if (n._isCancelled()) { + var o = new l("late cancellation observer"); + return e._attachExtraTrace(o), m.e = o, m; + } + n.isPending() && n._attachCancellationCallback(new f(this)); + } + return n._then(h, i, void 0, this, void 0); + } + } + } + return e.isRejected() ? (g(this), m.e = a, m) : (g(this), a); + } + var k = a("./util"), l = b.CancellationError, m = k.errorObj, n = a("./catch_filter")(d); + return e.prototype.isFinallyHandler = function() { + return 0 === this.type; + }, f.prototype._resultCancelled = function() { + g(this.finallyHandler); + }, b.prototype._passThrough = function(a, b, c, d) { + return "function" != typeof a ? this.then() : this._then(c, d, void 0, new e(this, b, a), void 0); + }, b.prototype.lastly = b.prototype.finally = function(a) { + return this._passThrough(a, 0, j, j); + }, b.prototype.tap = function(a) { + return this._passThrough(a, 1, j); + }, b.prototype.tapCatch = function(a) { + var c = arguments.length; + if (1 === c) return this._passThrough(a, 1, void 0, j); + var d, e = new Array(c - 1), f = 0; + for (d = 0; d < c - 1; ++d) { + var g = arguments[d]; + if (!k.isObject(g)) return b.reject(new TypeError("tapCatch statement predicate: expecting an object but got " + k.classString(g))); + e[f++] = g; + } + e.length = f; + var h = arguments[d]; + return this._passThrough(n(e, h, this), 1, void 0, j); + }, e; + }; + }, { + "./catch_filter": 7, + "./util": 36 + } ], + 16: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d, e, f, g) { + function h(a, c, d) { + for (var f = 0; f < c.length; ++f) { + d._pushContext(); + var g = n(c[f])(a); + if (d._popContext(), g === m) { + d._pushContext(); + var h = b.reject(m.e); + return d._popContext(), h; + } + var i = e(g, d); + if (i instanceof b) return i; + } + return null; + } + function i(a, c, e, f) { + if (g.cancellation()) { + var h = new b(d), i = this._finallyPromise = new b(d); + this._promise = h.lastly(function() { + return i; + }), h._captureStackTrace(), h._setOnCancel(this); + } else { + (this._promise = new b(d))._captureStackTrace(); + } + this._stack = f, this._generatorFunction = a, this._receiver = c, this._generator = void 0, + this._yieldHandlers = "function" == typeof e ? [ e ].concat(o) : o, this._yieldedPromise = null, + this._cancellationPhase = !1; + } + var j = a("./errors"), k = j.TypeError, l = a("./util"), m = l.errorObj, n = l.tryCatch, o = []; + l.inherits(i, f), i.prototype._isResolved = function() { + return null === this._promise; + }, i.prototype._cleanup = function() { + this._promise = this._generator = null, g.cancellation() && null !== this._finallyPromise && (this._finallyPromise._fulfill(), + this._finallyPromise = null); + }, i.prototype._promiseCancelled = function() { + if (!this._isResolved()) { + var a, c = void 0 !== this._generator.return; + if (c) this._promise._pushContext(), a = n(this._generator.return).call(this._generator, void 0), + this._promise._popContext(); else { + var d = new b.CancellationError("generator .return() sentinel"); + b.coroutine.returnSentinel = d, this._promise._attachExtraTrace(d), this._promise._pushContext(), + a = n(this._generator.throw).call(this._generator, d), this._promise._popContext(); + } + this._cancellationPhase = !0, this._yieldedPromise = null, this._continue(a); + } + }, i.prototype._promiseFulfilled = function(a) { + this._yieldedPromise = null, this._promise._pushContext(); + var b = n(this._generator.next).call(this._generator, a); + this._promise._popContext(), this._continue(b); + }, i.prototype._promiseRejected = function(a) { + this._yieldedPromise = null, this._promise._attachExtraTrace(a), this._promise._pushContext(); + var b = n(this._generator.throw).call(this._generator, a); + this._promise._popContext(), this._continue(b); + }, i.prototype._resultCancelled = function() { + if (this._yieldedPromise instanceof b) { + var a = this._yieldedPromise; + this._yieldedPromise = null, a.cancel(); + } + }, i.prototype.promise = function() { + return this._promise; + }, i.prototype._run = function() { + this._generator = this._generatorFunction.call(this._receiver), this._receiver = this._generatorFunction = void 0, + this._promiseFulfilled(void 0); + }, i.prototype._continue = function(a) { + var c = this._promise; + if (a === m) return this._cleanup(), this._cancellationPhase ? c.cancel() : c._rejectCallback(a.e, !1); + var d = a.value; + if (!0 === a.done) return this._cleanup(), this._cancellationPhase ? c.cancel() : c._resolveCallback(d); + var f = e(d, this._promise); + if (!(f instanceof b) && null === (f = h(f, this._yieldHandlers, this._promise))) return void this._promiseRejected(new k("A value %s was yielded that could not be treated as a promise\n\n See http://goo.gl/MqrFmX\n\n".replace("%s", String(d)) + "From coroutine:\n" + this._stack.split("\n").slice(1, -7).join("\n"))); + f = f._target(); + var g = f._bitField; + 0 == (50397184 & g) ? (this._yieldedPromise = f, f._proxy(this, null)) : 0 != (33554432 & g) ? b._async.invoke(this._promiseFulfilled, this, f._value()) : 0 != (16777216 & g) ? b._async.invoke(this._promiseRejected, this, f._reason()) : this._promiseCancelled(); + }, b.coroutine = function(a, b) { + if ("function" != typeof a) throw new k("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n"); + var c = Object(b).yieldHandler, d = i, e = new Error().stack; + return function() { + var b = a.apply(this, arguments), f = new d(void 0, void 0, c, e), g = f.promise(); + return f._generator = b, f._promiseFulfilled(void 0), g; + }; + }, b.coroutine.addYieldHandler = function(a) { + if ("function" != typeof a) throw new k("expecting a function but got " + l.classString(a)); + o.push(a); + }, b.spawn = function(a) { + if (g.deprecated("Promise.spawn()", "Promise.coroutine()"), "function" != typeof a) return c("generatorFunction must be a function\n\n See http://goo.gl/MqrFmX\n"); + var d = new i(a, this), e = d.promise(); + return d._run(b.spawn), e; + }; + }; + }, { + "./errors": 12, + "./util": 36 + } ], + 17: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d, e, f, g) { + var h = a("./util"); + h.canEvaluate, h.tryCatch, h.errorObj; + b.join = function() { + var a, b = arguments.length - 1; + if (b > 0 && "function" == typeof arguments[b]) { + a = arguments[b]; + var d; + } + var e = [].slice.call(arguments); + a && e.pop(); + var d = new c(e).promise(); + return void 0 !== a ? d.spread(a) : d; + }; + }; + }, { + "./util": 36 + } ], + 18: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d, e, f, g) { + function h(a, b, c, d) { + this.constructor$(a), this._promise._captureStackTrace(); + var e = j(); + this._callback = null === e ? b : k.domainBind(e, b), this._preservedValues = d === f ? new Array(this.length()) : null, + this._limit = c, this._inFlight = 0, this._queue = [], n.invoke(this._asyncInit, this, void 0); + } + function i(a, c, e, f) { + if ("function" != typeof c) return d("expecting a function but got " + k.classString(c)); + var g = 0; + if (void 0 !== e) { + if ("object" != typeof e || null === e) return b.reject(new TypeError("options argument must be an object but it is " + k.classString(e))); + if ("number" != typeof e.concurrency) return b.reject(new TypeError("'concurrency' must be a number but it is " + k.classString(e.concurrency))); + g = e.concurrency; + } + return g = "number" == typeof g && isFinite(g) && g >= 1 ? g : 0, new h(a, c, g, f).promise(); + } + var j = b._getDomain, k = a("./util"), l = k.tryCatch, m = k.errorObj, n = b._async; + k.inherits(h, c), h.prototype._asyncInit = function() { + this._init$(void 0, -2); + }, h.prototype._init = function() {}, h.prototype._promiseFulfilled = function(a, c) { + var d = this._values, f = this.length(), h = this._preservedValues, i = this._limit; + if (c < 0) { + if (c = -1 * c - 1, d[c] = a, i >= 1 && (this._inFlight--, this._drainQueue(), this._isResolved())) return !0; + } else { + if (i >= 1 && this._inFlight >= i) return d[c] = a, this._queue.push(c), !1; + null !== h && (h[c] = a); + var j = this._promise, k = this._callback, n = j._boundValue(); + j._pushContext(); + var o = l(k).call(n, a, c, f), p = j._popContext(); + if (g.checkForgottenReturns(o, p, null !== h ? "Promise.filter" : "Promise.map", j), + o === m) return this._reject(o.e), !0; + var q = e(o, this._promise); + if (q instanceof b) { + q = q._target(); + var r = q._bitField; + if (0 == (50397184 & r)) return i >= 1 && this._inFlight++, d[c] = q, q._proxy(this, -1 * (c + 1)), + !1; + if (0 == (33554432 & r)) return 0 != (16777216 & r) ? (this._reject(q._reason()), + !0) : (this._cancel(), !0); + o = q._value(); + } + d[c] = o; + } + return ++this._totalResolved >= f && (null !== h ? this._filter(d, h) : this._resolve(d), + !0); + }, h.prototype._drainQueue = function() { + for (var a = this._queue, b = this._limit, c = this._values; a.length > 0 && this._inFlight < b; ) { + if (this._isResolved()) return; + var d = a.pop(); + this._promiseFulfilled(c[d], d); + } + }, h.prototype._filter = function(a, b) { + for (var c = b.length, d = new Array(c), e = 0, f = 0; f < c; ++f) a[f] && (d[e++] = b[f]); + d.length = e, this._resolve(d); + }, h.prototype.preservedValues = function() { + return this._preservedValues; + }, b.prototype.map = function(a, b) { + return i(this, a, b, null); + }, b.map = function(a, b, c, d) { + return i(a, b, c, d); + }; + }; + }, { + "./util": 36 + } ], + 19: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d, e, f) { + var g = a("./util"), h = g.tryCatch; + b.method = function(a) { + if ("function" != typeof a) throw new b.TypeError("expecting a function but got " + g.classString(a)); + return function() { + var d = new b(c); + d._captureStackTrace(), d._pushContext(); + var e = h(a).apply(this, arguments), g = d._popContext(); + return f.checkForgottenReturns(e, g, "Promise.method", d), d._resolveFromSyncValue(e), + d; + }; + }, b.attempt = b.try = function(a) { + if ("function" != typeof a) return e("expecting a function but got " + g.classString(a)); + var d = new b(c); + d._captureStackTrace(), d._pushContext(); + var i; + if (arguments.length > 1) { + f.deprecated("calling Promise.try with more than 1 argument"); + var j = arguments[1], k = arguments[2]; + i = g.isArray(j) ? h(a).apply(k, j) : h(a).call(k, j); + } else i = h(a)(); + var l = d._popContext(); + return f.checkForgottenReturns(i, l, "Promise.try", d), d._resolveFromSyncValue(i), + d; + }, b.prototype._resolveFromSyncValue = function(a) { + a === g.errorObj ? this._rejectCallback(a.e, !1) : this._resolveCallback(a, !0); + }; + }; + }, { + "./util": 36 + } ], + 20: [ function(a, b, c) { + "use strict"; + function d(a) { + return a instanceof Error && k.getPrototypeOf(a) === Error.prototype; + } + function e(a) { + var b; + if (d(a)) { + b = new j(a), b.name = a.name, b.message = a.message, b.stack = a.stack; + for (var c = k.keys(a), e = 0; e < c.length; ++e) { + var f = c[e]; + l.test(f) || (b[f] = a[f]); + } + return b; + } + return g.markAsOriginatingFromRejection(a), a; + } + function f(a, b) { + return function(c, d) { + if (null !== a) { + if (c) { + var f = e(h(c)); + a._attachExtraTrace(f), a._reject(f); + } else if (b) { + var g = [].slice.call(arguments, 1); + a._fulfill(g); + } else a._fulfill(d); + a = null; + } + }; + } + var g = a("./util"), h = g.maybeWrapAsError, i = a("./errors"), j = i.OperationalError, k = a("./es5"), l = /^(?:name|message|stack|cause)$/; + b.exports = f; + }, { + "./errors": 12, + "./es5": 13, + "./util": 36 + } ], + 21: [ function(a, b, c) { + "use strict"; + b.exports = function(b) { + function c(a, b) { + var c = this; + if (!f.isArray(a)) return d.call(c, a, b); + var e = h(b).apply(c._boundValue(), [ null ].concat(a)); + e === i && g.throwLater(e.e); + } + function d(a, b) { + var c = this, d = c._boundValue(), e = void 0 === a ? h(b).call(d, null) : h(b).call(d, null, a); + e === i && g.throwLater(e.e); + } + function e(a, b) { + var c = this; + if (!a) { + var d = new Error(a + ""); + d.cause = a, a = d; + } + var e = h(b).call(c._boundValue(), a); + e === i && g.throwLater(e.e); + } + var f = a("./util"), g = b._async, h = f.tryCatch, i = f.errorObj; + b.prototype.asCallback = b.prototype.nodeify = function(a, b) { + if ("function" == typeof a) { + var f = d; + void 0 !== b && Object(b).spread && (f = c), this._then(f, e, void 0, this, a); + } + return this; + }; + }; + }, { + "./util": 36 + } ], + 22: [ function(b, c, d) { + "use strict"; + c.exports = function() { + function d() {} + function e(a, b) { + if (null == a || a.constructor !== f) throw new t("the promise constructor cannot be invoked directly\n\n See http://goo.gl/MqrFmX\n"); + if ("function" != typeof b) throw new t("expecting a function but got " + o.classString(b)); + } + function f(a) { + a !== v && e(this, a), this._bitField = 0, this._fulfillmentHandler0 = void 0, this._rejectionHandler0 = void 0, + this._promise0 = void 0, this._receiver0 = void 0, this._resolveFromExecutor(a), + this._promiseCreated(), this._fireEvent("promiseCreated", this); + } + function g(a) { + this.promise._resolveCallback(a); + } + function h(a) { + this.promise._rejectCallback(a, !1); + } + function i(a) { + var b = new f(v); + b._fulfillmentHandler0 = a, b._rejectionHandler0 = a, b._promise0 = a, b._receiver0 = a; + } + var j, k = function() { + return new t("circular promise resolution chain\n\n See http://goo.gl/MqrFmX\n"); + }, l = function() { + return new f.PromiseInspection(this._target()); + }, m = function(a) { + return f.reject(new t(a)); + }, n = {}, o = b("./util"); + j = o.isNode ? function() { + var b = a.domain; + return void 0 === b && (b = null), b; + } : function() { + return null; + }, o.notEnumerableProp(f, "_getDomain", j); + var p = b("./es5"), q = b("./async"), r = new q(); + p.defineProperty(f, "_async", { + value: r + }); + var s = b("./errors"), t = f.TypeError = s.TypeError; + f.RangeError = s.RangeError; + var u = f.CancellationError = s.CancellationError; + f.TimeoutError = s.TimeoutError, f.OperationalError = s.OperationalError, f.RejectionError = s.OperationalError, + f.AggregateError = s.AggregateError; + var v = function() {}, w = {}, x = {}, y = b("./thenables")(f, v), z = b("./promise_array")(f, v, y, m, d), A = b("./context")(f), B = A.create, C = b("./debuggability")(f, A), D = (C.CapturedTrace, + b("./finally")(f, y, x)), E = b("./catch_filter")(x), F = b("./nodeback"), G = o.errorObj, H = o.tryCatch; + return f.prototype.toString = function() { + return "[object Promise]"; + }, f.prototype.caught = f.prototype.catch = function(a) { + var b = arguments.length; + if (b > 1) { + var c, d = new Array(b - 1), e = 0; + for (c = 0; c < b - 1; ++c) { + var f = arguments[c]; + if (!o.isObject(f)) return m("Catch statement predicate: expecting an object but got " + o.classString(f)); + d[e++] = f; + } + return d.length = e, a = arguments[c], this.then(void 0, E(d, a, this)); + } + return this.then(void 0, a); + }, f.prototype.reflect = function() { + return this._then(l, l, void 0, this, void 0); + }, f.prototype.then = function(a, b) { + if (C.warnings() && arguments.length > 0 && "function" != typeof a && "function" != typeof b) { + var c = ".then() only accepts functions but was passed: " + o.classString(a); + arguments.length > 1 && (c += ", " + o.classString(b)), this._warn(c); + } + return this._then(a, b, void 0, void 0, void 0); + }, f.prototype.done = function(a, b) { + this._then(a, b, void 0, void 0, void 0)._setIsFinal(); + }, f.prototype.spread = function(a) { + return "function" != typeof a ? m("expecting a function but got " + o.classString(a)) : this.all()._then(a, void 0, void 0, w, void 0); + }, f.prototype.toJSON = function() { + var a = { + isFulfilled: !1, + isRejected: !1, + fulfillmentValue: void 0, + rejectionReason: void 0 + }; + return this.isFulfilled() ? (a.fulfillmentValue = this.value(), a.isFulfilled = !0) : this.isRejected() && (a.rejectionReason = this.reason(), + a.isRejected = !0), a; + }, f.prototype.all = function() { + return arguments.length > 0 && this._warn(".all() was passed arguments but it does not take any"), + new z(this).promise(); + }, f.prototype.error = function(a) { + return this.caught(o.originatesFromRejection, a); + }, f.getNewLibraryCopy = c.exports, f.is = function(a) { + return a instanceof f; + }, f.fromNode = f.fromCallback = function(a) { + var b = new f(v); + b._captureStackTrace(); + var c = arguments.length > 1 && !!Object(arguments[1]).multiArgs, d = H(a)(F(b, c)); + return d === G && b._rejectCallback(d.e, !0), b._isFateSealed() || b._setAsyncGuaranteed(), + b; + }, f.all = function(a) { + return new z(a).promise(); + }, f.cast = function(a) { + var b = y(a); + return b instanceof f || (b = new f(v), b._captureStackTrace(), b._setFulfilled(), + b._rejectionHandler0 = a), b; + }, f.resolve = f.fulfilled = f.cast, f.reject = f.rejected = function(a) { + var b = new f(v); + return b._captureStackTrace(), b._rejectCallback(a, !0), b; + }, f.setScheduler = function(a) { + if ("function" != typeof a) throw new t("expecting a function but got " + o.classString(a)); + return r.setScheduler(a); + }, f.prototype._then = function(a, b, c, d, e) { + var g = void 0 !== e, h = g ? e : new f(v), i = this._target(), k = i._bitField; + g || (h._propagateFrom(this, 3), h._captureStackTrace(), void 0 === d && 0 != (2097152 & this._bitField) && (d = 0 != (50397184 & k) ? this._boundValue() : i === this ? void 0 : this._boundTo), + this._fireEvent("promiseChained", this, h)); + var l = j(); + if (0 != (50397184 & k)) { + var m, n, p = i._settlePromiseCtx; + 0 != (33554432 & k) ? (n = i._rejectionHandler0, m = a) : 0 != (16777216 & k) ? (n = i._fulfillmentHandler0, + m = b, i._unsetRejectionIsUnhandled()) : (p = i._settlePromiseLateCancellationObserver, + n = new u("late cancellation observer"), i._attachExtraTrace(n), m = b), r.invoke(p, i, { + handler: null === l ? m : "function" == typeof m && o.domainBind(l, m), + promise: h, + receiver: d, + value: n + }); + } else i._addCallbacks(a, b, h, d, l); + return h; + }, f.prototype._length = function() { + return 65535 & this._bitField; + }, f.prototype._isFateSealed = function() { + return 0 != (117506048 & this._bitField); + }, f.prototype._isFollowing = function() { + return 67108864 == (67108864 & this._bitField); + }, f.prototype._setLength = function(a) { + this._bitField = -65536 & this._bitField | 65535 & a; + }, f.prototype._setFulfilled = function() { + this._bitField = 33554432 | this._bitField, this._fireEvent("promiseFulfilled", this); + }, f.prototype._setRejected = function() { + this._bitField = 16777216 | this._bitField, this._fireEvent("promiseRejected", this); + }, f.prototype._setFollowing = function() { + this._bitField = 67108864 | this._bitField, this._fireEvent("promiseResolved", this); + }, f.prototype._setIsFinal = function() { + this._bitField = 4194304 | this._bitField; + }, f.prototype._isFinal = function() { + return (4194304 & this._bitField) > 0; + }, f.prototype._unsetCancelled = function() { + this._bitField = -65537 & this._bitField; + }, f.prototype._setCancelled = function() { + this._bitField = 65536 | this._bitField, this._fireEvent("promiseCancelled", this); + }, f.prototype._setWillBeCancelled = function() { + this._bitField = 8388608 | this._bitField; + }, f.prototype._setAsyncGuaranteed = function() { + r.hasCustomScheduler() || (this._bitField = 134217728 | this._bitField); + }, f.prototype._receiverAt = function(a) { + var b = 0 === a ? this._receiver0 : this[4 * a - 4 + 3]; + if (b !== n) return void 0 === b && this._isBound() ? this._boundValue() : b; + }, f.prototype._promiseAt = function(a) { + return this[4 * a - 4 + 2]; + }, f.prototype._fulfillmentHandlerAt = function(a) { + return this[4 * a - 4 + 0]; + }, f.prototype._rejectionHandlerAt = function(a) { + return this[4 * a - 4 + 1]; + }, f.prototype._boundValue = function() {}, f.prototype._migrateCallback0 = function(a) { + var b = (a._bitField, a._fulfillmentHandler0), c = a._rejectionHandler0, d = a._promise0, e = a._receiverAt(0); + void 0 === e && (e = n), this._addCallbacks(b, c, d, e, null); + }, f.prototype._migrateCallbackAt = function(a, b) { + var c = a._fulfillmentHandlerAt(b), d = a._rejectionHandlerAt(b), e = a._promiseAt(b), f = a._receiverAt(b); + void 0 === f && (f = n), this._addCallbacks(c, d, e, f, null); + }, f.prototype._addCallbacks = function(a, b, c, d, e) { + var f = this._length(); + if (f >= 65531 && (f = 0, this._setLength(0)), 0 === f) this._promise0 = c, this._receiver0 = d, + "function" == typeof a && (this._fulfillmentHandler0 = null === e ? a : o.domainBind(e, a)), + "function" == typeof b && (this._rejectionHandler0 = null === e ? b : o.domainBind(e, b)); else { + var g = 4 * f - 4; + this[g + 2] = c, this[g + 3] = d, "function" == typeof a && (this[g + 0] = null === e ? a : o.domainBind(e, a)), + "function" == typeof b && (this[g + 1] = null === e ? b : o.domainBind(e, b)); + } + return this._setLength(f + 1), f; + }, f.prototype._proxy = function(a, b) { + this._addCallbacks(void 0, void 0, b, a, null); + }, f.prototype._resolveCallback = function(a, b) { + if (0 == (117506048 & this._bitField)) { + if (a === this) return this._rejectCallback(k(), !1); + var c = y(a, this); + if (!(c instanceof f)) return this._fulfill(a); + b && this._propagateFrom(c, 2); + var d = c._target(); + if (d === this) return void this._reject(k()); + var e = d._bitField; + if (0 == (50397184 & e)) { + var g = this._length(); + g > 0 && d._migrateCallback0(this); + for (var h = 1; h < g; ++h) d._migrateCallbackAt(this, h); + this._setFollowing(), this._setLength(0), this._setFollowee(d); + } else if (0 != (33554432 & e)) this._fulfill(d._value()); else if (0 != (16777216 & e)) this._reject(d._reason()); else { + var i = new u("late cancellation observer"); + d._attachExtraTrace(i), this._reject(i); + } + } + }, f.prototype._rejectCallback = function(a, b, c) { + var d = o.ensureErrorObject(a), e = d === a; + if (!e && !c && C.warnings()) { + var f = "a promise was rejected with a non-error: " + o.classString(a); + this._warn(f, !0); + } + this._attachExtraTrace(d, !!b && e), this._reject(a); + }, f.prototype._resolveFromExecutor = function(a) { + if (a !== v) { + var b = this; + this._captureStackTrace(), this._pushContext(); + var c = !0, d = this._execute(a, function(a) { + b._resolveCallback(a); + }, function(a) { + b._rejectCallback(a, c); + }); + c = !1, this._popContext(), void 0 !== d && b._rejectCallback(d, !0); + } + }, f.prototype._settlePromiseFromHandler = function(a, b, c, d) { + var e = d._bitField; + if (0 == (65536 & e)) { + d._pushContext(); + var f; + b === w ? c && "number" == typeof c.length ? f = H(a).apply(this._boundValue(), c) : (f = G, + f.e = new t("cannot .spread() a non-array: " + o.classString(c))) : f = H(a).call(b, c); + var g = d._popContext(); + e = d._bitField, 0 == (65536 & e) && (f === x ? d._reject(c) : f === G ? d._rejectCallback(f.e, !1) : (C.checkForgottenReturns(f, g, "", d, this), + d._resolveCallback(f))); + } + }, f.prototype._target = function() { + for (var a = this; a._isFollowing(); ) a = a._followee(); + return a; + }, f.prototype._followee = function() { + return this._rejectionHandler0; + }, f.prototype._setFollowee = function(a) { + this._rejectionHandler0 = a; + }, f.prototype._settlePromise = function(a, b, c, e) { + var g = a instanceof f, h = this._bitField, i = 0 != (134217728 & h); + 0 != (65536 & h) ? (g && a._invokeInternalOnCancel(), c instanceof D && c.isFinallyHandler() ? (c.cancelPromise = a, + H(b).call(c, e) === G && a._reject(G.e)) : b === l ? a._fulfill(l.call(c)) : c instanceof d ? c._promiseCancelled(a) : g || a instanceof z ? a._cancel() : c.cancel()) : "function" == typeof b ? g ? (i && a._setAsyncGuaranteed(), + this._settlePromiseFromHandler(b, c, e, a)) : b.call(c, e, a) : c instanceof d ? c._isResolved() || (0 != (33554432 & h) ? c._promiseFulfilled(e, a) : c._promiseRejected(e, a)) : g && (i && a._setAsyncGuaranteed(), + 0 != (33554432 & h) ? a._fulfill(e) : a._reject(e)); + }, f.prototype._settlePromiseLateCancellationObserver = function(a) { + var b = a.handler, c = a.promise, d = a.receiver, e = a.value; + "function" == typeof b ? c instanceof f ? this._settlePromiseFromHandler(b, d, e, c) : b.call(d, e, c) : c instanceof f && c._reject(e); + }, f.prototype._settlePromiseCtx = function(a) { + this._settlePromise(a.promise, a.handler, a.receiver, a.value); + }, f.prototype._settlePromise0 = function(a, b, c) { + var d = this._promise0, e = this._receiverAt(0); + this._promise0 = void 0, this._receiver0 = void 0, this._settlePromise(d, a, e, b); + }, f.prototype._clearCallbackDataAtIndex = function(a) { + var b = 4 * a - 4; + this[b + 2] = this[b + 3] = this[b + 0] = this[b + 1] = void 0; + }, f.prototype._fulfill = function(a) { + var b = this._bitField; + if (!((117506048 & b) >>> 16)) { + if (a === this) { + var c = k(); + return this._attachExtraTrace(c), this._reject(c); + } + this._setFulfilled(), this._rejectionHandler0 = a, (65535 & b) > 0 && (0 != (134217728 & b) ? this._settlePromises() : r.settlePromises(this)); + } + }, f.prototype._reject = function(a) { + var b = this._bitField; + if (!((117506048 & b) >>> 16)) { + if (this._setRejected(), this._fulfillmentHandler0 = a, this._isFinal()) return r.fatalError(a, o.isNode); + (65535 & b) > 0 ? r.settlePromises(this) : this._ensurePossibleRejectionHandled(); + } + }, f.prototype._fulfillPromises = function(a, b) { + for (var c = 1; c < a; c++) { + var d = this._fulfillmentHandlerAt(c), e = this._promiseAt(c), f = this._receiverAt(c); + this._clearCallbackDataAtIndex(c), this._settlePromise(e, d, f, b); + } + }, f.prototype._rejectPromises = function(a, b) { + for (var c = 1; c < a; c++) { + var d = this._rejectionHandlerAt(c), e = this._promiseAt(c), f = this._receiverAt(c); + this._clearCallbackDataAtIndex(c), this._settlePromise(e, d, f, b); + } + }, f.prototype._settlePromises = function() { + var a = this._bitField, b = 65535 & a; + if (b > 0) { + if (0 != (16842752 & a)) { + var c = this._fulfillmentHandler0; + this._settlePromise0(this._rejectionHandler0, c, a), this._rejectPromises(b, c); + } else { + var d = this._rejectionHandler0; + this._settlePromise0(this._fulfillmentHandler0, d, a), this._fulfillPromises(b, d); + } + this._setLength(0); + } + this._clearCancellationData(); + }, f.prototype._settledValue = function() { + var a = this._bitField; + return 0 != (33554432 & a) ? this._rejectionHandler0 : 0 != (16777216 & a) ? this._fulfillmentHandler0 : void 0; + }, f.defer = f.pending = function() { + return C.deprecated("Promise.defer", "new Promise"), { + promise: new f(v), + resolve: g, + reject: h + }; + }, o.notEnumerableProp(f, "_makeSelfResolutionError", k), b("./method")(f, v, y, m, C), + b("./bind")(f, v, y, C), b("./cancel")(f, z, m, C), b("./direct_resolve")(f), b("./synchronous_inspection")(f), + b("./join")(f, z, y, v, r, j), f.Promise = f, f.version = "3.5.1", b("./map.js")(f, z, m, y, v, C), + b("./call_get.js")(f), b("./using.js")(f, m, y, B, v, C), b("./timers.js")(f, v, C), + b("./generators.js")(f, m, v, y, d, C), b("./nodeify.js")(f), b("./promisify.js")(f, v), + b("./props.js")(f, z, y, m), b("./race.js")(f, v, y, m), b("./reduce.js")(f, z, m, y, v, C), + b("./settle.js")(f, z, C), b("./some.js")(f, z, m), b("./filter.js")(f, v), b("./each.js")(f, v), + b("./any.js")(f), o.toFastProperties(f), o.toFastProperties(f.prototype), i({ + a: 1 + }), i({ + b: 2 + }), i({ + c: 3 + }), i(1), i(function() {}), i(void 0), i(!1), i(new f(v)), C.setBounds(q.firstLineError, o.lastLineError), + f; + }; + }, { + "./any.js": 1, + "./async": 2, + "./bind": 3, + "./call_get.js": 5, + "./cancel": 6, + "./catch_filter": 7, + "./context": 8, + "./debuggability": 9, + "./direct_resolve": 10, + "./each.js": 11, + "./errors": 12, + "./es5": 13, + "./filter.js": 14, + "./finally": 15, + "./generators.js": 16, + "./join": 17, + "./map.js": 18, + "./method": 19, + "./nodeback": 20, + "./nodeify.js": 21, + "./promise_array": 23, + "./promisify.js": 24, + "./props.js": 25, + "./race.js": 27, + "./reduce.js": 28, + "./settle.js": 30, + "./some.js": 31, + "./synchronous_inspection": 32, + "./thenables": 33, + "./timers.js": 34, + "./using.js": 35, + "./util": 36 + } ], + 23: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d, e, f) { + function g(a) { + switch (a) { + case -2: + return []; + + case -3: + return {}; + + case -6: + return new Map(); + } + } + function h(a) { + var d = this._promise = new b(c); + a instanceof b && d._propagateFrom(a, 3), d._setOnCancel(this), this._values = a, + this._length = 0, this._totalResolved = 0, this._init(void 0, -2); + } + var i = a("./util"); + i.isArray; + return i.inherits(h, f), h.prototype.length = function() { + return this._length; + }, h.prototype.promise = function() { + return this._promise; + }, h.prototype._init = function a(c, f) { + var h = d(this._values, this._promise); + if (h instanceof b) { + h = h._target(); + var j = h._bitField; + if (this._values = h, 0 == (50397184 & j)) return this._promise._setAsyncGuaranteed(), + h._then(a, this._reject, void 0, this, f); + if (0 == (33554432 & j)) return 0 != (16777216 & j) ? this._reject(h._reason()) : this._cancel(); + h = h._value(); + } + if (null === (h = i.asArray(h))) { + var k = e("expecting an array or an iterable object but got " + i.classString(h)).reason(); + return void this._promise._rejectCallback(k, !1); + } + if (0 === h.length) return void (-5 === f ? this._resolveEmptyArray() : this._resolve(g(f))); + this._iterate(h); + }, h.prototype._iterate = function(a) { + var c = this.getActualLength(a.length); + this._length = c, this._values = this.shouldCopyValues() ? new Array(c) : this._values; + for (var e = this._promise, f = !1, g = null, h = 0; h < c; ++h) { + var i = d(a[h], e); + i instanceof b ? (i = i._target(), g = i._bitField) : g = null, f ? null !== g && i.suppressUnhandledRejections() : null !== g ? 0 == (50397184 & g) ? (i._proxy(this, h), + this._values[h] = i) : f = 0 != (33554432 & g) ? this._promiseFulfilled(i._value(), h) : 0 != (16777216 & g) ? this._promiseRejected(i._reason(), h) : this._promiseCancelled(h) : f = this._promiseFulfilled(i, h); + } + f || e._setAsyncGuaranteed(); + }, h.prototype._isResolved = function() { + return null === this._values; + }, h.prototype._resolve = function(a) { + this._values = null, this._promise._fulfill(a); + }, h.prototype._cancel = function() { + !this._isResolved() && this._promise._isCancellable() && (this._values = null, this._promise._cancel()); + }, h.prototype._reject = function(a) { + this._values = null, this._promise._rejectCallback(a, !1); + }, h.prototype._promiseFulfilled = function(a, b) { + return this._values[b] = a, ++this._totalResolved >= this._length && (this._resolve(this._values), + !0); + }, h.prototype._promiseCancelled = function() { + return this._cancel(), !0; + }, h.prototype._promiseRejected = function(a) { + return this._totalResolved++, this._reject(a), !0; + }, h.prototype._resultCancelled = function() { + if (!this._isResolved()) { + var a = this._values; + if (this._cancel(), a instanceof b) a.cancel(); else for (var c = 0; c < a.length; ++c) a[c] instanceof b && a[c].cancel(); + } + }, h.prototype.shouldCopyValues = function() { + return !0; + }, h.prototype.getActualLength = function(a) { + return a; + }, h; + }; + }, { + "./util": 36 + } ], + 24: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c) { + function d(a) { + return !v.test(a); + } + function e(a) { + try { + return !0 === a.__isPromisified__; + } catch (a) { + return !1; + } + } + function f(a, b, c) { + var d = n.getDataPropertyOrDefault(a, b + c, t); + return !!d && e(d); + } + function g(a, b, c) { + for (var d = 0; d < a.length; d += 2) { + var e = a[d]; + if (c.test(e)) for (var f = e.replace(c, ""), g = 0; g < a.length; g += 2) if (a[g] === f) throw new s("Cannot promisify an API that has normal methods with '%s'-suffix\n\n See http://goo.gl/MqrFmX\n".replace("%s", b)); + } + } + function h(a, b, c, d) { + for (var h = n.inheritedDataKeys(a), i = [], j = 0; j < h.length; ++j) { + var k = h[j], l = a[k], m = d === w || w(k, l, a); + "function" != typeof l || e(l) || f(a, k, b) || !d(k, l, a, m) || i.push(k, l); + } + return g(i, b, c), i; + } + function i(a, d, e, f, g, h) { + function i() { + var e = d; + d === m && (e = this); + var f = new b(c); + f._captureStackTrace(); + var g = "string" == typeof k && this !== j ? this[k] : a, i = o(f, h); + try { + g.apply(e, p(arguments, i)); + } catch (a) { + f._rejectCallback(q(a), !0, !0); + } + return f._isFateSealed() || f._setAsyncGuaranteed(), f; + } + var j = function() { + return this; + }(), k = a; + return "string" == typeof k && (a = f), n.notEnumerableProp(i, "__isPromisified__", !0), + i; + } + function j(a, b, c, d, e) { + for (var f = new RegExp(x(b) + "$"), g = h(a, b, f, c), i = 0, j = g.length; i < j; i += 2) { + var k = g[i], l = g[i + 1], o = k + b; + if (d === y) a[o] = y(k, m, k, l, b, e); else { + var p = d(l, function() { + return y(k, m, k, l, b, e); + }); + n.notEnumerableProp(p, "__isPromisified__", !0), a[o] = p; + } + } + return n.toFastProperties(a), a; + } + function k(a, b, c) { + return y(a, b, void 0, a, null, c); + } + var l, m = {}, n = a("./util"), o = a("./nodeback"), p = n.withAppended, q = n.maybeWrapAsError, r = n.canEvaluate, s = a("./errors").TypeError, t = { + __isPromisified__: !0 + }, u = [ "arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__" ], v = new RegExp("^(?:" + u.join("|") + ")$"), w = function(a) { + return n.isIdentifier(a) && "_" !== a.charAt(0) && "constructor" !== a; + }, x = function(a) { + return a.replace(/([$])/, "\\$"); + }, y = r ? l : i; + b.promisify = function(a, b) { + if ("function" != typeof a) throw new s("expecting a function but got " + n.classString(a)); + if (e(a)) return a; + b = Object(b); + var c = void 0 === b.context ? m : b.context, f = !!b.multiArgs, g = k(a, c, f); + return n.copyDescriptors(a, g, d), g; + }, b.promisifyAll = function(a, b) { + if ("function" != typeof a && "object" != typeof a) throw new s("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n"); + b = Object(b); + var c = !!b.multiArgs, d = b.suffix; + "string" != typeof d && (d = "Async"); + var e = b.filter; + "function" != typeof e && (e = w); + var f = b.promisifier; + if ("function" != typeof f && (f = y), !n.isIdentifier(d)) throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n"); + for (var g = n.inheritedDataKeys(a), h = 0; h < g.length; ++h) { + var i = a[g[h]]; + "constructor" !== g[h] && n.isClass(i) && (j(i.prototype, d, e, f, c), j(i, d, e, f, c)); + } + return j(a, d, e, f, c); + }; + }; + }, { + "./errors": 12, + "./nodeback": 20, + "./util": 36 + } ], + 25: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d, e) { + function f(a) { + var b, c = !1; + if (void 0 !== h && a instanceof h) b = l(a), c = !0; else { + var d = k.keys(a), e = d.length; + b = new Array(2 * e); + for (var f = 0; f < e; ++f) { + var g = d[f]; + b[f] = a[g], b[f + e] = g; + } + } + this.constructor$(b), this._isMap = c, this._init$(void 0, c ? -6 : -3); + } + function g(a) { + var c, g = d(a); + return j(g) ? (c = g instanceof b ? g._then(b.props, void 0, void 0, void 0, void 0) : new f(g).promise(), + g instanceof b && c._propagateFrom(g, 2), c) : e("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n"); + } + var h, i = a("./util"), j = i.isObject, k = a("./es5"); + "function" == typeof Map && (h = Map); + var l = function() { + function a(a, d) { + this[b] = a, this[b + c] = d, b++; + } + var b = 0, c = 0; + return function(d) { + c = d.size, b = 0; + var e = new Array(2 * d.size); + return d.forEach(a, e), e; + }; + }(), m = function(a) { + for (var b = new h(), c = a.length / 2 | 0, d = 0; d < c; ++d) { + var e = a[c + d], f = a[d]; + b.set(e, f); + } + return b; + }; + i.inherits(f, c), f.prototype._init = function() {}, f.prototype._promiseFulfilled = function(a, b) { + if (this._values[b] = a, ++this._totalResolved >= this._length) { + var c; + if (this._isMap) c = m(this._values); else { + c = {}; + for (var d = this.length(), e = 0, f = this.length(); e < f; ++e) c[this._values[e + d]] = this._values[e]; + } + return this._resolve(c), !0; + } + return !1; + }, f.prototype.shouldCopyValues = function() { + return !1; + }, f.prototype.getActualLength = function(a) { + return a >> 1; + }, b.prototype.props = function() { + return g(this); + }, b.props = function(a) { + return g(a); + }; + }; + }, { + "./es5": 13, + "./util": 36 + } ], + 26: [ function(a, b, c) { + "use strict"; + function d(a, b, c, d, e) { + for (var f = 0; f < e; ++f) c[f + d] = a[f + b], a[f + b] = void 0; + } + function e(a) { + this._capacity = a, this._length = 0, this._front = 0; + } + e.prototype._willBeOverCapacity = function(a) { + return this._capacity < a; + }, e.prototype._pushOne = function(a) { + var b = this.length(); + this._checkCapacity(b + 1), this[this._front + b & this._capacity - 1] = a, this._length = b + 1; + }, e.prototype.push = function(a, b, c) { + var d = this.length() + 3; + if (this._willBeOverCapacity(d)) return this._pushOne(a), this._pushOne(b), void this._pushOne(c); + var e = this._front + d - 3; + this._checkCapacity(d); + var f = this._capacity - 1; + this[e + 0 & f] = a, this[e + 1 & f] = b, this[e + 2 & f] = c, this._length = d; + }, e.prototype.shift = function() { + var a = this._front, b = this[a]; + return this[a] = void 0, this._front = a + 1 & this._capacity - 1, this._length--, + b; + }, e.prototype.length = function() { + return this._length; + }, e.prototype._checkCapacity = function(a) { + this._capacity < a && this._resizeTo(this._capacity << 1); + }, e.prototype._resizeTo = function(a) { + var b = this._capacity; + this._capacity = a, d(this, 0, this, b, this._front + this._length & b - 1); + }, b.exports = e; + }, {} ], + 27: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d, e) { + function f(a, f) { + var i = d(a); + if (i instanceof b) return h(i); + if (null === (a = g.asArray(a))) return e("expecting an array or an iterable object but got " + g.classString(a)); + var j = new b(c); + void 0 !== f && j._propagateFrom(f, 3); + for (var k = j._fulfill, l = j._reject, m = 0, n = a.length; m < n; ++m) { + var o = a[m]; + (void 0 !== o || m in a) && b.cast(o)._then(k, l, void 0, j, null); + } + return j; + } + var g = a("./util"), h = function(a) { + return a.then(function(b) { + return f(b, a); + }); + }; + b.race = function(a) { + return f(a, void 0); + }, b.prototype.race = function() { + return f(this, void 0); + }; + }; + }, { + "./util": 36 + } ], + 28: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d, e, f, g) { + function h(a, c, d, e) { + this.constructor$(a); + var g = m(); + this._fn = null === g ? c : n.domainBind(g, c), void 0 !== d && (d = b.resolve(d), + d._attachCancellationCallback(this)), this._initialValue = d, this._currentCancellable = null, + this._eachValues = e === f ? Array(this._length) : 0 === e ? null : void 0, this._promise._captureStackTrace(), + this._init$(void 0, -5); + } + function i(a, b) { + this.isFulfilled() ? b._resolve(a) : b._reject(a); + } + function j(a, b, c, e) { + return "function" != typeof b ? d("expecting a function but got " + n.classString(b)) : new h(a, b, c, e).promise(); + } + function k(a) { + this.accum = a, this.array._gotAccum(a); + var c = e(this.value, this.array._promise); + return c instanceof b ? (this.array._currentCancellable = c, c._then(l, void 0, void 0, this, void 0)) : l.call(this, c); + } + function l(a) { + var c = this.array, d = c._promise, e = o(c._fn); + d._pushContext(); + var f; + (f = void 0 !== c._eachValues ? e.call(d._boundValue(), a, this.index, this.length) : e.call(d._boundValue(), this.accum, a, this.index, this.length)) instanceof b && (c._currentCancellable = f); + var h = d._popContext(); + return g.checkForgottenReturns(f, h, void 0 !== c._eachValues ? "Promise.each" : "Promise.reduce", d), + f; + } + var m = b._getDomain, n = a("./util"), o = n.tryCatch; + n.inherits(h, c), h.prototype._gotAccum = function(a) { + void 0 !== this._eachValues && null !== this._eachValues && a !== f && this._eachValues.push(a); + }, h.prototype._eachComplete = function(a) { + return null !== this._eachValues && this._eachValues.push(a), this._eachValues; + }, h.prototype._init = function() {}, h.prototype._resolveEmptyArray = function() { + this._resolve(void 0 !== this._eachValues ? this._eachValues : this._initialValue); + }, h.prototype.shouldCopyValues = function() { + return !1; + }, h.prototype._resolve = function(a) { + this._promise._resolveCallback(a), this._values = null; + }, h.prototype._resultCancelled = function(a) { + if (a === this._initialValue) return this._cancel(); + this._isResolved() || (this._resultCancelled$(), this._currentCancellable instanceof b && this._currentCancellable.cancel(), + this._initialValue instanceof b && this._initialValue.cancel()); + }, h.prototype._iterate = function(a) { + this._values = a; + var c, d, e = a.length; + if (void 0 !== this._initialValue ? (c = this._initialValue, d = 0) : (c = b.resolve(a[0]), + d = 1), this._currentCancellable = c, !c.isRejected()) for (;d < e; ++d) { + var f = { + accum: null, + value: a[d], + index: d, + length: e, + array: this + }; + c = c._then(k, void 0, void 0, f, void 0); + } + void 0 !== this._eachValues && (c = c._then(this._eachComplete, void 0, void 0, this, void 0)), + c._then(i, i, void 0, c, this); + }, b.prototype.reduce = function(a, b) { + return j(this, a, b, null); + }, b.reduce = function(a, b, c, d) { + return j(a, b, c, d); + }; + }; + }, { + "./util": 36 + } ], + 29: [ function(b, c, e) { + "use strict"; + var f, g = b("./util"), h = function() { + throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n"); + }, i = g.getNativePromise(); + if (g.isNode && "undefined" == typeof MutationObserver) { + var j = d.setImmediate, k = a.nextTick; + f = g.isRecentNode ? function(a) { + j.call(d, a); + } : function(b) { + k.call(a, b); + }; + } else if ("function" == typeof i && "function" == typeof i.resolve) { + var l = i.resolve(); + f = function(a) { + l.then(a); + }; + } else f = "undefined" == typeof MutationObserver || "undefined" != typeof window && window.navigator && (window.navigator.standalone || window.cordova) ? "undefined" != typeof setImmediate ? function(a) { + setImmediate(a); + } : "undefined" != typeof setTimeout ? function(a) { + setTimeout(a, 0); + } : h : function() { + var a = document.createElement("div"), b = { + attributes: !0 + }, c = !1, d = document.createElement("div"); + new MutationObserver(function() { + a.classList.toggle("foo"), c = !1; + }).observe(d, b); + var e = function() { + c || (c = !0, d.classList.toggle("foo")); + }; + return function(c) { + var d = new MutationObserver(function() { + d.disconnect(), c(); + }); + d.observe(a, b), e(); + }; + }(); + c.exports = f; + }, { + "./util": 36 + } ], + 30: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d) { + function e(a) { + this.constructor$(a); + } + var f = b.PromiseInspection; + a("./util").inherits(e, c), e.prototype._promiseResolved = function(a, b) { + return this._values[a] = b, ++this._totalResolved >= this._length && (this._resolve(this._values), + !0); + }, e.prototype._promiseFulfilled = function(a, b) { + var c = new f(); + return c._bitField = 33554432, c._settledValueField = a, this._promiseResolved(b, c); + }, e.prototype._promiseRejected = function(a, b) { + var c = new f(); + return c._bitField = 16777216, c._settledValueField = a, this._promiseResolved(b, c); + }, b.settle = function(a) { + return d.deprecated(".settle()", ".reflect()"), new e(a).promise(); + }, b.prototype.settle = function() { + return b.settle(this); + }; + }; + }, { + "./util": 36 + } ], + 31: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d) { + function e(a) { + this.constructor$(a), this._howMany = 0, this._unwrap = !1, this._initialized = !1; + } + function f(a, b) { + if ((0 | b) !== b || b < 0) return d("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n"); + var c = new e(a), f = c.promise(); + return c.setHowMany(b), c.init(), f; + } + var g = a("./util"), h = a("./errors").RangeError, i = a("./errors").AggregateError, j = g.isArray, k = {}; + g.inherits(e, c), e.prototype._init = function() { + if (this._initialized) { + if (0 === this._howMany) return void this._resolve([]); + this._init$(void 0, -5); + var a = j(this._values); + !this._isResolved() && a && this._howMany > this._canPossiblyFulfill() && this._reject(this._getRangeError(this.length())); + } + }, e.prototype.init = function() { + this._initialized = !0, this._init(); + }, e.prototype.setUnwrap = function() { + this._unwrap = !0; + }, e.prototype.howMany = function() { + return this._howMany; + }, e.prototype.setHowMany = function(a) { + this._howMany = a; + }, e.prototype._promiseFulfilled = function(a) { + return this._addFulfilled(a), this._fulfilled() === this.howMany() && (this._values.length = this.howMany(), + 1 === this.howMany() && this._unwrap ? this._resolve(this._values[0]) : this._resolve(this._values), + !0); + }, e.prototype._promiseRejected = function(a) { + return this._addRejected(a), this._checkOutcome(); + }, e.prototype._promiseCancelled = function() { + return this._values instanceof b || null == this._values ? this._cancel() : (this._addRejected(k), + this._checkOutcome()); + }, e.prototype._checkOutcome = function() { + if (this.howMany() > this._canPossiblyFulfill()) { + for (var a = new i(), b = this.length(); b < this._values.length; ++b) this._values[b] !== k && a.push(this._values[b]); + return a.length > 0 ? this._reject(a) : this._cancel(), !0; + } + return !1; + }, e.prototype._fulfilled = function() { + return this._totalResolved; + }, e.prototype._rejected = function() { + return this._values.length - this.length(); + }, e.prototype._addRejected = function(a) { + this._values.push(a); + }, e.prototype._addFulfilled = function(a) { + this._values[this._totalResolved++] = a; + }, e.prototype._canPossiblyFulfill = function() { + return this.length() - this._rejected(); + }, e.prototype._getRangeError = function(a) { + var b = "Input array must contain at least " + this._howMany + " items but contains only " + a + " items"; + return new h(b); + }, e.prototype._resolveEmptyArray = function() { + this._reject(this._getRangeError(0)); + }, b.some = function(a, b) { + return f(a, b); + }, b.prototype.some = function(a) { + return f(this, a); + }, b._SomePromiseArray = e; + }; + }, { + "./errors": 12, + "./util": 36 + } ], + 32: [ function(a, b, c) { + "use strict"; + b.exports = function(a) { + function b(a) { + void 0 !== a ? (a = a._target(), this._bitField = a._bitField, this._settledValueField = a._isFateSealed() ? a._settledValue() : void 0) : (this._bitField = 0, + this._settledValueField = void 0); + } + b.prototype._settledValue = function() { + return this._settledValueField; + }; + var c = b.prototype.value = function() { + if (!this.isFulfilled()) throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n"); + return this._settledValue(); + }, d = b.prototype.error = b.prototype.reason = function() { + if (!this.isRejected()) throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n"); + return this._settledValue(); + }, e = b.prototype.isFulfilled = function() { + return 0 != (33554432 & this._bitField); + }, f = b.prototype.isRejected = function() { + return 0 != (16777216 & this._bitField); + }, g = b.prototype.isPending = function() { + return 0 == (50397184 & this._bitField); + }, h = b.prototype.isResolved = function() { + return 0 != (50331648 & this._bitField); + }; + b.prototype.isCancelled = function() { + return 0 != (8454144 & this._bitField); + }, a.prototype.__isCancelled = function() { + return 65536 == (65536 & this._bitField); + }, a.prototype._isCancelled = function() { + return this._target().__isCancelled(); + }, a.prototype.isCancelled = function() { + return 0 != (8454144 & this._target()._bitField); + }, a.prototype.isPending = function() { + return g.call(this._target()); + }, a.prototype.isRejected = function() { + return f.call(this._target()); + }, a.prototype.isFulfilled = function() { + return e.call(this._target()); + }, a.prototype.isResolved = function() { + return h.call(this._target()); + }, a.prototype.value = function() { + return c.call(this._target()); + }, a.prototype.reason = function() { + var a = this._target(); + return a._unsetRejectionIsUnhandled(), d.call(a); + }, a.prototype._value = function() { + return this._settledValue(); + }, a.prototype._reason = function() { + return this._unsetRejectionIsUnhandled(), this._settledValue(); + }, a.PromiseInspection = b; + }; + }, {} ], + 33: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c) { + function d(a, d) { + if (k(a)) { + if (a instanceof b) return a; + var e = f(a); + if (e === j) { + d && d._pushContext(); + var i = b.reject(e.e); + return d && d._popContext(), i; + } + if ("function" == typeof e) { + if (g(a)) { + var i = new b(c); + return a._then(i._fulfill, i._reject, void 0, i, null), i; + } + return h(a, e, d); + } + } + return a; + } + function e(a) { + return a.then; + } + function f(a) { + try { + return e(a); + } catch (a) { + return j.e = a, j; + } + } + function g(a) { + try { + return l.call(a, "_promise0"); + } catch (a) { + return !1; + } + } + function h(a, d, e) { + function f(a) { + h && (h._resolveCallback(a), h = null); + } + function g(a) { + h && (h._rejectCallback(a, l, !0), h = null); + } + var h = new b(c), k = h; + e && e._pushContext(), h._captureStackTrace(), e && e._popContext(); + var l = !0, m = i.tryCatch(d).call(a, f, g); + return l = !1, h && m === j && (h._rejectCallback(m.e, !0, !0), h = null), k; + } + var i = a("./util"), j = i.errorObj, k = i.isObject, l = {}.hasOwnProperty; + return d; + }; + }, { + "./util": 36 + } ], + 34: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d) { + function e(a) { + this.handle = a; + } + function f(a) { + return clearTimeout(this.handle), a; + } + function g(a) { + throw clearTimeout(this.handle), a; + } + var h = a("./util"), i = b.TimeoutError; + e.prototype._resultCancelled = function() { + clearTimeout(this.handle); + }; + var j = function(a) { + return k(+this).thenReturn(a); + }, k = b.delay = function(a, f) { + var g, h; + return void 0 !== f ? (g = b.resolve(f)._then(j, null, null, a, void 0), d.cancellation() && f instanceof b && g._setOnCancel(f)) : (g = new b(c), + h = setTimeout(function() { + g._fulfill(); + }, +a), d.cancellation() && g._setOnCancel(new e(h)), g._captureStackTrace()), g._setAsyncGuaranteed(), + g; + }; + b.prototype.delay = function(a) { + return k(a, this); + }; + var l = function(a, b, c) { + var d; + d = "string" != typeof b ? b instanceof Error ? b : new i("operation timed out") : new i(b), + h.markAsOriginatingFromRejection(d), a._attachExtraTrace(d), a._reject(d), null != c && c.cancel(); + }; + b.prototype.timeout = function(a, b) { + a = +a; + var c, h, i = new e(setTimeout(function() { + c.isPending() && l(c, b, h); + }, a)); + return d.cancellation() ? (h = this.then(), c = h._then(f, g, void 0, i, void 0), + c._setOnCancel(i)) : c = this._then(f, g, void 0, i, void 0), c; + }; + }; + }, { + "./util": 36 + } ], + 35: [ function(a, b, c) { + "use strict"; + b.exports = function(b, c, d, e, f, g) { + function h(a) { + setTimeout(function() { + throw a; + }, 0); + } + function i(a) { + var b = d(a); + return b !== a && "function" == typeof a._isDisposable && "function" == typeof a._getDisposer && a._isDisposable() && b._setDisposable(a._getDisposer()), + b; + } + function j(a, c) { + function e() { + if (g >= j) return k._fulfill(); + var f = i(a[g++]); + if (f instanceof b && f._isDisposable()) { + try { + f = d(f._getDisposer().tryDispose(c), a.promise); + } catch (a) { + return h(a); + } + if (f instanceof b) return f._then(e, h, null, null, null); + } + e(); + } + var g = 0, j = a.length, k = new b(f); + return e(), k; + } + function k(a, b, c) { + this._data = a, this._promise = b, this._context = c; + } + function l(a, b, c) { + this.constructor$(a, b, c); + } + function m(a) { + return k.isDisposer(a) ? (this.resources[this.index]._setDisposable(a), a.promise()) : a; + } + function n(a) { + this.length = a, this.promise = null, this[a - 1] = null; + } + var o = a("./util"), p = a("./errors").TypeError, q = a("./util").inherits, r = o.errorObj, s = o.tryCatch, t = {}; + k.prototype.data = function() { + return this._data; + }, k.prototype.promise = function() { + return this._promise; + }, k.prototype.resource = function() { + return this.promise().isFulfilled() ? this.promise().value() : t; + }, k.prototype.tryDispose = function(a) { + var b = this.resource(), c = this._context; + void 0 !== c && c._pushContext(); + var d = b !== t ? this.doDispose(b, a) : null; + return void 0 !== c && c._popContext(), this._promise._unsetDisposable(), this._data = null, + d; + }, k.isDisposer = function(a) { + return null != a && "function" == typeof a.resource && "function" == typeof a.tryDispose; + }, q(l, k), l.prototype.doDispose = function(a, b) { + return this.data().call(a, a, b); + }, n.prototype._resultCancelled = function() { + for (var a = this.length, c = 0; c < a; ++c) { + var d = this[c]; + d instanceof b && d.cancel(); + } + }, b.using = function() { + var a = arguments.length; + if (a < 2) return c("you must pass at least 2 arguments to Promise.using"); + var e = arguments[a - 1]; + if ("function" != typeof e) return c("expecting a function but got " + o.classString(e)); + var f, h = !0; + 2 === a && Array.isArray(arguments[0]) ? (f = arguments[0], a = f.length, h = !1) : (f = arguments, + a--); + for (var i = new n(a), l = 0; l < a; ++l) { + var p = f[l]; + if (k.isDisposer(p)) { + var q = p; + p = p.promise(), p._setDisposable(q); + } else { + var t = d(p); + t instanceof b && (p = t._then(m, null, null, { + resources: i, + index: l + }, void 0)); + } + i[l] = p; + } + for (var u = new Array(i.length), l = 0; l < u.length; ++l) u[l] = b.resolve(i[l]).reflect(); + var v = b.all(u).then(function(a) { + for (var b = 0; b < a.length; ++b) { + var c = a[b]; + if (c.isRejected()) return r.e = c.error(), r; + if (!c.isFulfilled()) return void v.cancel(); + a[b] = c.value(); + } + w._pushContext(), e = s(e); + var d = h ? e.apply(void 0, a) : e(a), f = w._popContext(); + return g.checkForgottenReturns(d, f, "Promise.using", w), d; + }), w = v.lastly(function() { + var a = new b.PromiseInspection(v); + return j(i, a); + }); + return i.promise = w, w._setOnCancel(i), w; + }, b.prototype._setDisposable = function(a) { + this._bitField = 131072 | this._bitField, this._disposer = a; + }, b.prototype._isDisposable = function() { + return (131072 & this._bitField) > 0; + }, b.prototype._getDisposer = function() { + return this._disposer; + }, b.prototype._unsetDisposable = function() { + this._bitField = -131073 & this._bitField, this._disposer = void 0; + }, b.prototype.disposer = function(a) { + if ("function" == typeof a) return new l(a, this, e()); + throw new p(); + }; + }; + }, { + "./errors": 12, + "./util": 36 + } ], + 36: [ function(b, c, e) { + "use strict"; + function f() { + try { + var a = F; + return F = null, a.apply(this, arguments); + } catch (a) { + return E.e = a, E; + } + } + function g(a) { + return F = a, f; + } + function h(a) { + return null == a || !0 === a || !1 === a || "string" == typeof a || "number" == typeof a; + } + function i(a) { + return "function" == typeof a || "object" == typeof a && null !== a; + } + function j(a) { + return h(a) ? new Error(s(a)) : a; + } + function k(a, b) { + var c, d = a.length, e = new Array(d + 1); + for (c = 0; c < d; ++c) e[c] = a[c]; + return e[c] = b, e; + } + function l(a, b, c) { + if (!C.isES5) return {}.hasOwnProperty.call(a, b) ? a[b] : void 0; + var d = Object.getOwnPropertyDescriptor(a, b); + return null != d ? null == d.get && null == d.set ? d.value : c : void 0; + } + function m(a, b, c) { + if (h(a)) return a; + var d = { + value: c, + configurable: !0, + enumerable: !1, + writable: !0 + }; + return C.defineProperty(a, b, d), a; + } + function n(a) { + throw a; + } + function o(a) { + try { + if ("function" == typeof a) { + var b = C.names(a.prototype), c = C.isES5 && b.length > 1, d = b.length > 0 && !(1 === b.length && "constructor" === b[0]), e = J.test(a + "") && C.names(a).length > 0; + if (c || d || e) return !0; + } + return !1; + } catch (a) { + return !1; + } + } + function p(a) { + function b() {} + b.prototype = a; + for (var c = 8; c--; ) new b(); + return a; + } + function q(a) { + return K.test(a); + } + function r(a, b, c) { + for (var d = new Array(a), e = 0; e < a; ++e) d[e] = b + e + c; + return d; + } + function s(a) { + try { + return a + ""; + } catch (a) { + return "[no string representation]"; + } + } + function t(a) { + return a instanceof Error || null !== a && "object" == typeof a && "string" == typeof a.message && "string" == typeof a.name; + } + function u(a) { + try { + m(a, "isOperational", !0); + } catch (a) {} + } + function v(a) { + return null != a && (a instanceof Error.__BluebirdErrorTypes__.OperationalError || !0 === a.isOperational); + } + function w(a) { + return t(a) && C.propertyIsWritable(a, "stack"); + } + function x(a) { + return {}.toString.call(a); + } + function y(a, b, c) { + for (var d = C.names(a), e = 0; e < d.length; ++e) { + var f = d[e]; + if (c(f)) try { + C.defineProperty(b, f, C.getDescriptor(a, f)); + } catch (a) {} + } + } + function z(b) { + return P ? a.env[b] : void 0; + } + function A() { + if ("function" == typeof Promise) try { + var a = new Promise(function() {}); + if ("[object Promise]" === {}.toString.call(a)) return Promise; + } catch (a) {} + } + function B(a, b) { + return a.bind(b); + } + var C = b("./es5"), D = "undefined" == typeof navigator, E = { + e: {} + }, F, G = "undefined" != typeof self ? self : "undefined" != typeof window ? window : void 0 !== d ? d : void 0 !== this ? this : null, H = function(a, b) { + function c() { + this.constructor = a, this.constructor$ = b; + for (var c in b.prototype) d.call(b.prototype, c) && "$" !== c.charAt(c.length - 1) && (this[c + "$"] = b.prototype[c]); + } + var d = {}.hasOwnProperty; + return c.prototype = b.prototype, a.prototype = new c(), a.prototype; + }, I = function() { + var a = [ Array.prototype, Object.prototype, Function.prototype ], b = function(b) { + for (var c = 0; c < a.length; ++c) if (a[c] === b) return !0; + return !1; + }; + if (C.isES5) { + var c = Object.getOwnPropertyNames; + return function(a) { + for (var d = [], e = Object.create(null); null != a && !b(a); ) { + var f; + try { + f = c(a); + } catch (a) { + return d; + } + for (var g = 0; g < f.length; ++g) { + var h = f[g]; + if (!e[h]) { + e[h] = !0; + var i = Object.getOwnPropertyDescriptor(a, h); + null != i && null == i.get && null == i.set && d.push(h); + } + } + a = C.getPrototypeOf(a); + } + return d; + }; + } + var d = {}.hasOwnProperty; + return function(c) { + if (b(c)) return []; + var e = []; + a: for (var f in c) if (d.call(c, f)) e.push(f); else { + for (var g = 0; g < a.length; ++g) if (d.call(a[g], f)) continue a; + e.push(f); + } + return e; + }; + }(), J = /this\s*\.\s*\S+\s*=/, K = /^[a-z$_][a-z$_0-9]*$/i, L = function() { + return "stack" in new Error() ? function(a) { + return w(a) ? a : new Error(s(a)); + } : function(a) { + if (w(a)) return a; + try { + throw new Error(s(a)); + } catch (a) { + return a; + } + }; + }(), M = function(a) { + return C.isArray(a) ? a : null; + }; + if ("undefined" != typeof Symbol && Symbol.iterator) { + var N = "function" == typeof Array.from ? function(a) { + return Array.from(a); + } : function(a) { + for (var b, c = [], d = a[Symbol.iterator](); !(b = d.next()).done; ) c.push(b.value); + return c; + }; + M = function(a) { + return C.isArray(a) ? a : null != a && "function" == typeof a[Symbol.iterator] ? N(a) : null; + }; + } + var O = void 0 !== a && "[object process]" === x(a).toLowerCase(), P = void 0 !== a && void 0 !== a.env, Q = { + isClass: o, + isIdentifier: q, + inheritedDataKeys: I, + getDataPropertyOrDefault: l, + thrower: n, + isArray: C.isArray, + asArray: M, + notEnumerableProp: m, + isPrimitive: h, + isObject: i, + isError: t, + canEvaluate: D, + errorObj: E, + tryCatch: g, + inherits: H, + withAppended: k, + maybeWrapAsError: j, + toFastProperties: p, + filledRange: r, + toString: s, + canAttachTrace: w, + ensureErrorObject: L, + originatesFromRejection: v, + markAsOriginatingFromRejection: u, + classString: x, + copyDescriptors: y, + hasDevTools: "undefined" != typeof chrome && chrome && "function" == typeof chrome.loadTimes, + isNode: O, + hasEnvVariables: P, + env: z, + global: G, + getNativePromise: A, + domainBind: B + }; + Q.isRecentNode = Q.isNode && function() { + var b = a.versions.node.split(".").map(Number); + return 0 === b[0] && b[1] > 10 || b[0] > 0; + }(), Q.isNode && Q.toFastProperties(a); + try { + throw new Error(); + } catch (a) { + Q.lastLineError = a; + } + c.exports = Q; + }, { + "./es5": 13 + } ] + }, {}, [ 4 ])(4); + }), "undefined" != typeof window && null !== window ? window.P = window.Promise : "undefined" != typeof self && null !== self && (self.P = self.Promise); + }).call(this, a("_process"), "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}); + }, { + _process: 15 + } ], + 2: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.PreCallTest = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./turnConnection"), g = a("./tests/rttTest"), h = a("./tests/throughputTest"), i = a("./utility/resultsHandler"), j = a("./utility/onlineCheck"), k = a("./utility/stats/detectbrowser"), l = a("bluebird"), m = { + RTT: "rtt", + THROUGHPUT: "throughput" + }, n = function() { + function a() { + d(this, a), this.browserInfo = (0, k.detect)(), this.turnConnection = new f.TurnConnection(this.browserInfo), + this.onlineCheck = new j.OnlineCheck(), this.callsInProgress = 0, this.turnTests = [ m.RTT, m.THROUGHPUT ], + this.active = !1, this.rtt = null, this.resultsHandler = null; + } + return e(a, [ { + key: "start", + value: function(a, b) { + if (this.browserInfo.browserName !== k.Constants.browserName.msie) if (this.iceServers = a, + this.callback = b, this.active) this.callback && this.callback(null, "Not started: already in progress"); else if (this.callsInProgress > 0) this.callback && this.callback(null, "Not started: call in progress"); else if (a) { + this.turnTestCounter = 0, this.resultsHandler = new i.ResultsHandler(); + var c = { + type: "browser", + os: this.browserInfo.os, + osVersion: this.browserInfo.osVersion, + buildName: this.browserInfo.browserName, + buildVersion: this.browserInfo.browserVersion + }; + this.resultsHandler.add("endpointInfo", c), this.onlineCheck.start(), this.active = !0, + this._start(); + } else this.callback && this.callback(null, "Not started: no ICE servers given"); else this.callback && this.callback(null, "Not started: disabled for IE"); + } + }, { + key: "_start", + value: function() { + var a = this; + this.active && this.turnConnection.connect(this.iceServers).then(function() { + a.active ? a.startTurnTests().then(function() { + a.stop(); + }, function(b) { + a.stop(); + }) : a.stop(); + }, function(b) { + var c = b.continueFlag; + if (a.resultsHandler.failure(b), !c) { + a.turnConnection.disconnect(), a.active = !1; + var d = ""; + try { + d = b.stack; + } catch (a) { + d = b.toString(); + } + return d && "" !== d || (d = b.toString()), void a.callback(null, d); + } + a.resultsHandler.getFailureNumber() >= 10 ? a.stop() : (a.turnConnection.disconnect(), + setTimeout(function() { + a._start(); + }, 0)); + }); + } + }, { + key: "stop", + value: function() { + var a = this; + if (this.browserInfo.browserName !== k.Constants.browserName.msie && this.active) { + this.active = !1, this.activeTurnTest && this.activeTurnTest.forceStop(); + var b = this.onlineCheck.stop(); + this.resultsHandler && this.resultsHandler.add("onlineStatus", b), this.turnConnection.getIceResults().then(function(b) { + a.resultsHandler && a.resultsHandler.add("ice", b), a.turnConnection.disconnect(), + a.sendResults(); + }, function(b) { + a.resultsHandler && a.resultsHandler.failure(b), a.turnConnection.disconnect(), + a.sendResults(); + }); + } + } + }, { + key: "sendResults", + value: function() { + this.resultsHandler || this.callback && this.callback(null, "No results present"); + var a = this.resultsHandler.getResults(); + this.callback && this.callback(a, null), this.resultsHandler = null; + } + }, { + key: "callStarts", + value: function() { + this.callsInProgress += 1, this.stop(); + } + }, { + key: "callFinished", + value: function() { + this.callsInProgress -= 1; + } + }, { + key: "getId", + value: function() { + return this.resultsHandler ? this.resultsHandler.getId() : null; + } + }, { + key: "crashDisconnect", + value: function() { + try { + this.turnConnection.disconnect(); + } catch (a) {} + } + }, { + key: "startTurnTests", + value: function() { + var a = this; + if (this.turnTestCounter >= this.turnTests.length) return new l(function(a, b) { + a(); + }); + var b = this.turnTests[this.turnTestCounter], c = null; + switch (b) { + case m.RTT: + c = new g.RttTest(this.turnConnection); + break; + + case m.THROUGHPUT: + c = new h.ThroughputTest(this.turnConnection, this.rtt); + break; + + default: + return new l(function(a, c) { + c(new Error("Unknown test: " + b)); + }); + } + return this.activeTurnTest = c, this.active ? c.start().then(function() { + return a.handleTestResults(b, c.getResults()), a.turnTestCounter += 1, a.activeTurnTest = null, + a.startTurnTests(); + }, function(d) { + return a.handleTestResults(b, c.getResults(), d), a.turnTestCounter += 1, a.activeTurnTest = null, + a.startTurnTests(); + }) : new l(function(a, b) { + b(new Error("Test trying to start while testing is not active")); + }); + } + }, { + key: "handleTestResults", + value: function(a, b) { + null == (arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : null) && a == m.RTT && (this.rtt = b.median), + this.resultsHandler && this.resultsHandler.add(a, b); + } + } ]), a; + }(); + c.PreCallTest = n; + }, { + "./tests/rttTest": 3, + "./tests/throughputTest": 4, + "./turnConnection": 6, + "./utility/onlineCheck": 8, + "./utility/resultsHandler": 10, + "./utility/stats/detectbrowser": 11, + bluebird: 1 + } ], + 3: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function f(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.RttTest = void 0; + var g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = function a(b, c, d) { + null === b && (b = Function.prototype); + var e = Object.getOwnPropertyDescriptor(b, c); + if (void 0 === e) { + var f = Object.getPrototypeOf(b); + return null === f ? void 0 : a(f, c, d); + } + if ("value" in e) return e.value; + var g = e.get; + return void 0 !== g ? g.call(d) : void 0; + }, i = a("../utility/timestamps"), j = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(i), k = a("./turnTest"), l = function(a) { + function b(a) { + d(this, b); + var c = e(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, a)); + return c.sendTimer = null, c.countSent = 0, c.rtts = [], c; + } + return f(b, k.TurnTest), g(b, [ { + key: "initiate", + value: function() { + this.results.startTimestamp = j.getCurrent(), this.sendPing(); + } + }, { + key: "handleMessage", + value: function(a) { + if (this.isActive()) { + var b = parseInt(a, 10), c = this.calculateRtt(b); + this.rtts.push(c), this.countSent < 10 ? this.sendPing() : this.calculateMetrics(); + } + } + }, { + key: "handleError", + value: function(a) { + this.fillResults(), this.failed(a); + } + }, { + key: "sendPing", + value: function() { + if (this.isActive()) { + var a = j.getCurrent(); + this.send(a.toString()), this.countSent += 1, this.sendTimer && (clearTimeout(this.sendTimer), + this.sendTimer = null), this.countSent < 10 ? this.sendTimer = setTimeout(this.sendPing.bind(this), 100) : this.sendTimer = setTimeout(this.calculateMetrics.bind(this), 500); + } + } + }, { + key: "calculateRtt", + value: function(a) { + return j.getCurrent() - a; + } + }, { + key: "calculateMetrics", + value: function() { + this.sendTimer && (clearTimeout(this.sendTimer), this.sendTimer = null), this.fillResults(), + this.finished(); + } + }, { + key: "fillResults", + value: function() { + this.results.sentMessages = this.countSent, this.results.unAckedMessages = this.countSent - this.rtts.length, + this.results.maxMessages = 10, this.results.forceStopped = this.forceStopped, this.results.median = this.median(), + this.results.variance = this.variance(), this.results.endTimestamp = j.getCurrent(); + } + }, { + key: "median", + value: function() { + if (0 == this.rtts.length) return null; + this.rtts.sort(); + var a = Math.floor(this.rtts.length / 2); + return this.rtts[a]; + } + }, { + key: "variance", + value: function() { + if (0 == this.rtts.length) return null; + for (var a = 0, b = this.median(), c = 0; c < this.rtts.length; c++) { + var d = this.rtts[c]; + a += Math.abs(d - b); + } + return a /= this.rtts.length; + } + }, { + key: "stop", + value: function() { + this.isActive() && (h(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "stop", this).call(this), + this.fillResults()); + } + } ]), b; + }(); + c.RttTest = l; + }, { + "../utility/timestamps": 14, + "./turnTest": 5 + } ], + 4: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function f(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.ThroughputTest = void 0; + var g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = function a(b, c, d) { + null === b && (b = Function.prototype); + var e = Object.getOwnPropertyDescriptor(b, c); + if (void 0 === e) { + var f = Object.getPrototypeOf(b); + return null === f ? void 0 : a(f, c, d); + } + if ("value" in e) return e.value; + var g = e.get; + return void 0 !== g ? g.call(d) : void 0; + }, i = a("../utility/timestamps"), j = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(i), k = a("../utility/messageMaker"), l = a("./turnTest"), m = function(a) { + function b(a, c) { + d(this, b); + var f = e(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, a)); + if (f.sentBytes = 0, f.receivedBytes = 0, f.secondHalfBytes = 0, f.secondHalfStart = null, + f.bufferEmpty = 0, f.chunkSize = 1200, f.messageMaker = new k.MessageMaker(f.chunkSize), + f.duration = 5e3, null != c) { + var g = 50 * c; + f.duration = Math.max(Math.min(g, 1e4), 1e3); + } + return f.sendTimer = null, f.lastMessage = null, f.intervals = [], f.intervalStart = 0, + f.intervalLength = 100, f.intervalBytes = 0, f; + } + return f(b, l.TurnTest), g(b, [ { + key: "initiate", + value: function() { + if (window && window.csioReactNative) { + this.handleError(new Error("Not running throughput test for react-native")); + } else this.startSend(); + } + }, { + key: "handleMessage", + value: function(a) { + var b = this; + if (this.isActive()) { + this.lastMessage = a, this.receivedBytes += a.length; + var c = j.getCurrent(); + if (this.sendTimer || (this.results.startTimestamp = c, this.sendTimer = setTimeout(function() { + b.stop(), b.finished(); + }, this.duration)), 0 == this.intervalStart && (this.intervalStart = c), this.intervalBytes += a.length, + c - this.intervalStart >= this.intervalLength) { + var d = c - this.intervalStart, e = this.averageThroughput(this.intervalBytes, d), f = null; + try { + f = c - JSON.parse(this.lastMessage).timestamp; + } catch (a) {} + this.intervals.push({ + startTimestamp: this.intervalStart, + endTimestamp: c, + bytesReceived: this.intervalBytes, + average: e, + rtt: f + }), this.intervalStart = c, this.intervalBytes = 0; + } + this.results.startTimestamp && c - this.results.startTimestamp > this.duration / 2 && (this.secondHalfStart || (this.secondHalfStart = c), + this.secondHalfBytes += a.length); + } + } + }, { + key: "handleError", + value: function(a) { + this.stop(), this.failed(a); + } + }, { + key: "averageThroughput", + value: function(a, b) { + return a / (b / 1e3) * 8 / 1024; + } + }, { + key: "bufferListener", + value: function() { + this.sendChannel.removeEventListener("bufferedamountlow", this.bufferListener.bind(this)), + this.fillBuffer(); + } + }, { + key: "fillBuffer", + value: function() { + for (0 == this.sendChannel.bufferedAmount && (this.bufferEmpty += 1); this.isActive(); ) { + if (this.sendChannel.bufferedAmount > this.bufferFullThreshold) return void (this.usePolling ? setTimeout(this.fillBuffer.bind(this), 250) : this.sendChannel.addEventListener("bufferedamountlow", this.bufferListener.bind(this))); + var a = this.messageMaker.make(this.sentBytes); + this.sentBytes += a.length, this.send(a); + } + this.sendChannel.removeEventListener("bufferedamountlow", this.bufferListener.bind(this)); + } + }, { + key: "startSend", + value: function() { + this.isActive() && (this.bufferFullThreshold = 1e3 * this.chunkSize, this.sendChannel = this.connection.sendChannel, + this.usePolling = !0, "number" == typeof this.sendChannel.bufferedAmountLowThreshold && (this.usePolling = !1, + this.sendChannel.bufferedAmountLowThreshold = this.bufferFullThreshold / 10), setTimeout(this.fillBuffer.bind(this), 0)); + } + }, { + key: "fillResults", + value: function() { + this.results.endTimestamp = j.getCurrent(), this.results.maxDuration = this.duration, + this.results.forceStopped = this.forceStopped, this.results.bufferEmpty = this.bufferEmpty, + this.results.intervals = this.intervals, this.results.bytesPrepared = this.sentBytes, + this.results.bytesReceived = this.receivedBytes; + var a = 0, b = 0; + this.secondHalfStart && (a = this.results.endTimestamp - this.secondHalfStart, b = this.averageThroughput(this.secondHalfBytes, a)); + var c = this.results.endTimestamp - this.results.startTimestamp, d = this.averageThroughput(this.receivedBytes, c); + d > b && (b = d), this.results.average = b; + var e = null; + try { + e = JSON.parse(this.lastMessage); + } catch (a) { + return; + } + if (e) { + var f = e.sentBytes + this.lastMessage.length; + this.results.bytesSent = f, this.results.fractionLostBytes = 1 - this.receivedBytes / f; + } else this.results.bytesSent = -1, this.results.fractionLostBytes = -1; + } + }, { + key: "stop", + value: function() { + this.isActive() && (clearTimeout(this.sendTimer), this.sendTimer = null, h(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "stop", this).call(this), + this.fillResults()); + } + } ]), b; + }(); + c.ThroughputTest = m; + }, { + "../utility/messageMaker": 7, + "../utility/timestamps": 14, + "./turnTest": 5 + } ], + 5: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("bluebird"), g = function() { + function a(b) { + d(this, a), this.connection = b, this.active = !1, this.results = {}; + } + return e(a, [ { + key: "getResults", + value: function() { + return this.results; + } + }, { + key: "start", + value: function() { + var a = this, b = new f(function(b, c) { + a.resolveCb = b, a.rejectCb = c; + }); + return this.connection.setMessageCallback(this.handleMessage.bind(this)), this.connection.setErrorCallback(this.handleError.bind(this)), + this.active = !0, this.forceStopped = !1, this.initiate(), b; + } + }, { + key: "stop", + value: function() { + this.active = !1; + } + }, { + key: "forceStop", + value: function() { + this.forceStopped = !0, this.stop(), this.finished(); + } + }, { + key: "isActive", + value: function() { + return this.active; + } + }, { + key: "initiate", + value: function() {} + }, { + key: "handleMessage", + value: function(a) {} + }, { + key: "handleError", + value: function(a) {} + }, { + key: "send", + value: function(a) { + this.connection.send(a); + } + }, { + key: "finished", + value: function() { + this.active = !1, this.resolveCb && (this.resolveCb(), this.resolveCb = null); + } + }, { + key: "failed", + value: function(a) { + this.active = !1, this.rejectCb && (this.rejectCb(a), this.rejectCb = null); + } + } ]), a; + }(); + c.TurnTest = g; + }, { + bluebird: 1 + } ], + 6: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.TurnConnection = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./utility/parsedIceCandidate"), g = a("./utility/stats/getstatshandler"), h = a("./utility/stats/detectbrowser"), i = a("bluebird"), j = function() { + function a(b) { + d(this, a), this.reset(), this.statshandler = new g.GetStatsHandler(b); + } + return e(a, [ { + key: "reset", + value: function() { + this.disconnect(), this.iceServers = null, this.pctpc1 = null, this.pctpc2 = null, + this.sendChannel = null, this.messageCallback = null, this.errorCallback = null, + this.parsedIceResults = {}, this.resolveCb = null, this.rejectCb = null; + } + }, { + key: "setMessageCallback", + value: function(a) { + this.messageCallback = a; + } + }, { + key: "setErrorCallback", + value: function(a) { + this.errorCallback = a; + } + }, { + key: "send", + value: function(a) { + if (this.sendChannel) try { + this.sendChannel.send(a); + } catch (a) { + this.raiseSendError(a); + } else this.raiseSendError(new Error("No send channel")); + } + }, { + key: "raiseSendError", + value: function(a) { + this.errorCallback && this.errorCallback(a); + } + }, { + key: "assignEvent", + value: function(a, b, c) { + a.addEventListener ? a.addEventListener(b, c.bind(this), !1) : a.attachEvent && (b = "on" + b, + a.attachEvent(b, c.bind(this))); + } + }, { + key: "connect", + value: function(a) { + var b = this; + this.reset(); + var c = new i(function(a, c) { + b.resolveCb = a, b.rejectCb = c; + }); + this.iceServers = a; + var d = null; + try { + if (RTCPeerConnection ? d = RTCPeerConnection : webkitRTCPeerConnection ? d = webkitRTCPeerConnection : mozRTCPeerConnection ? d = mozRTCPeerConnection : window && window.RTCPeerConnection && (d = window.RTCPeerConnection), + !d) { + var e = new Error("RTCPeerConnection not found"); + return e.continueFlag = !1, this.rejectCb(e), c; + } + } catch (e) { + return e.continueFlag = !1, this.rejectCb(e), c; + } + var f = { + ordered: !1, + maxRetransmits: 0 + }, g = { + iceTransportPolicy: "all", + iceServers: this.iceServers + }; + try { + this.pctpc1 = new d(g), this.pctpc2 = new d(g); + } catch (e) { + return this.rejectDisconnect(!1, e), c; + } + this.connectionTimer = setTimeout(function() { + delete b.connectionTimer, b.rejectDisconnect(!1, new Error("Connection timeout")); + }, 3e4); + try { + this.sendChannel = this.pctpc1.createDataChannel("precalltest", f), this.sendChannel.binaryType = "arraybuffer", + this.assignEvent(this.sendChannel, "error", function(a) { + b.raiseSendError(a), b.rejectDisconnect(!0, a); + }), this.assignEvent(this.pctpc2, "datachannel", function(a) { + var c = a.channel; + b.assignEvent(c, "open", function(a) { + b.resolveCb && (b.resolveCb(), b.resolveCb = null); + }), b.assignEvent(c, "close", function(a) { + b && b.disconnect && b.disconnect(); + }), b.assignEvent(c, "message", function(a) { + b.messageCallback && b.messageCallback(a.data); + }), b.assignEvent(c, "error", function(a) { + b.errorCallback && b.errorCallback(a), b.rejectDisconnect(!0, a); + }); + }); + } catch (e) { + return this.rejectDisconnect(!1, e), c; + } + try { + this.assignEvent(this.pctpc1, "icecandidate", function(a) { + b.onIceCandidate(b.pctpc1, a); + }), this.assignEvent(this.pctpc1, "iceconnectionstatechange", function(a) { + b.onIceStateChange(b.pctpc1, a); + }), this.assignEvent(this.pctpc2, "icecandidate", function(a) { + b.onIceCandidate(b.pctpc2, a); + }), this.assignEvent(this.pctpc2, "iceconnectionstatechange", function(a) { + b.onIceStateChange(b.pctpc2, a); + }), this.pctpc1.createOffer().then(function(a, c) { + b.onCreateOfferSuccess(a); + }, function(a) { + b.onCreateOfferError(b.pctpc1, a); + }); + } catch (e) { + return this.rejectDisconnect(!1, e), c; + } + return c; + } + }, { + key: "rejectDisconnect", + value: function(a, b) { + this.disconnect(), this.rejectCb && (b.continueFlag = a, this.rejectCb(b)), this.resolveCb = null, + this.rejectCb = null; + } + }, { + key: "disconnect", + value: function() { + if (clearTimeout(this.connectionTimer), clearTimeout(this.iceTimer), this.pctpc1) try { + this.pctpc1.close(); + } catch (a) {} + if (this.pctpc1 = null, this.pctpc2) try { + this.pctpc2.close(); + } catch (a) {} + this.pctpc2 = null; + } + }, { + key: "getName", + value: function(a) { + return a === this.pctpc1 ? "pctpc1" : "pctpc2"; + } + }, { + key: "getOtherPc", + value: function(a) { + return a === this.pctpc1 ? this.pctpc2 : this.pctpc1; + } + }, { + key: "onCreateOfferError", + value: function(a, b) { + this.rejectDisconnect(!1, b); + } + }, { + key: "onCreateAnswerError", + value: function(a, b) { + this.rejectDisconnect(!1, b); + } + }, { + key: "onCreateOfferSuccess", + value: function(a) { + var b = this; + try { + this.pctpc1.setLocalDescription(a).then(function() { + b.onSetLocalSuccess(b.pctpc1); + }, function(a) { + b.onSetSessionDescriptionError(b.pctpc1, a); + }), this.pctpc2.setRemoteDescription(a).then(function() { + b.onSetRemoteSuccess(b.pctpc2); + }, function(a) { + b.onSetRemoteSessionDescriptionError(b.pctpc2, a); + }), this.pctpc2.createAnswer().then(function(a) { + b.onCreateAnswerSuccess(a); + }, function(a) { + b.onCreateAnswerError(b.pctpc2, a); + }); + } catch (a) { + this.rejectDisconnect(!1, a); + } + } + }, { + key: "onSetLocalSuccess", + value: function(a) {} + }, { + key: "onSetRemoteSuccess", + value: function(a) {} + }, { + key: "onSetSessionDescriptionError", + value: function(a, b) { + this.rejectDisconnect(!1, b); + } + }, { + key: "onSetRemoteSessionDescriptionError", + value: function(a, b) { + this.rejectDisconnect(!1, b); + } + }, { + key: "onCreateAnswerSuccess", + value: function(a) { + var b = this; + try { + this.pctpc2.setLocalDescription(a).then(function() { + b.onSetLocalSuccess(b.pctpc2); + }, function(a) { + b.onSetSessionDescriptionError(b.pctpc2, a); + }), this.pctpc1.setRemoteDescription(a).then(function() { + b.onSetRemoteSuccess(b.pctpc1); + }, function(a) { + b.onSetRemoteSessionDescriptionError(b.pctpc1, a); + }); + } catch (a) { + this.rejectDisconnect(!1, a); + } + } + }, { + key: "onIceCandidate", + value: function(a, b) { + var c = this; + try { + if (!b.candidate) return; + var d = new f.ParsedIceCandidate(b.candidate); + if (a == this.pctpc1 && this.statshandler.codeBase == h.Constants.codeBaseType.chrome && (d.isRelay() && (d.isTypeTransportUdp() && (this.parsedIceResults.relayUdpGathered = !0), + d.isTypeTransportTcp() && (this.parsedIceResults.relayTcpGathered = !0), d.isTypeTransportTls() && (this.parsedIceResults.relayTlsGathered = !0)), + d.isServerReflexive() && (this.parsedIceResults.srflxGathered = !0)), !d.isRelay()) return; + this.getOtherPc(a).addIceCandidate(b.candidate).then(function() { + c.onAddIceCandidateSuccess(a); + }, function(b) { + c.onAddIceCandidateError(a, b, d.isRelay()); + }); + } catch (a) { + this.rejectDisconnect(!1, a); + } + } + }, { + key: "onAddIceCandidateSuccess", + value: function(a) {} + }, { + key: "onAddIceCandidateError", + value: function(a, b, c) { + c && this.rejectDisconnect(!1, b); + } + }, { + key: "onIceStateChange", + value: function(a, b) { + var c = this; + try { + var d = "(?)"; + a && (d = a.iceConnectionState), "failed" === d && this.rejectDisconnect(!0, new Error("ICE failure")), + "checking" !== d || this.iceTimer || (this.iceTimer = setTimeout(function() { + delete c.iceTimer, c.rejectDisconnect(!0, new Error("ICE timeout")); + }, 1e4)), "completed" !== d && "connected" !== d || (clearTimeout(this.iceTimer), + delete this.iceTimer); + } catch (a) { + this.rejectDisconnect(!1, a); + } + } + }, { + key: "getIceResults", + value: function() { + var a = this; + return new i(function(b, c) { + for (var d = JSON.parse(JSON.stringify(a.iceServers)), e = 0; e < d.length; e++) { + var f = d[e]; + d.hasOwnProperty(f) || delete f.credential; + } + var g = { + turnIpAddress: "", + turnIpVersion: "", + turnTransport: "", + iceServers: d, + ipv6Supported: !1, + ipv4Supported: !1, + relayTlsGathered: !1, + relayTcpGathered: !1, + relayUdpGathered: !1, + srflxGathered: !1, + relayTlsSuccess: !1, + relayTcpSuccess: !1, + relayUdpSuccess: !1, + srflxSuccess: !1 + }; + for (var h in a.parsedIceResults) a.parsedIceResults.hasOwnProperty(h) && (g[h] = a.parsedIceResults[h]); + a.pctpc1 ? a.statshandler.getIceCandidates(a.pctpc1).then(function(a) { + for (var c = 0; c < a.iceCandidatePairs.length; c++) { + var d = a.iceCandidatePairs[c]; + if (d.googActiveConnection || d.selected) for (var e = 0; e < a.localCandidates.length; e++) { + var f = a.localCandidates[e], h = null; + if (h = f.ip ? f.ip : f.ipAddress, f.id == d.localCandidateId) { + g.turnIpAddress = h; + var i = -1 !== h.indexOf(":"); + g.turnIpVersion = i ? "ipv6" : "ipv4", g.turnTransport = f.mozLocalTransport; + } + "relay" !== f.candidateType && "relayed" !== f.candidateType || ("udp" === f.mozLocalTransport && (g.relayUdpSuccess = !0), + "tcp" === f.mozLocalTransport && (g.relayTcpSuccess = !0), "tls" === f.mozLocalTransport && (g.relayTlsSuccess = !0)), + -1 !== h.indexOf(":") ? g.ipv6Supported = !0 : g.ipv4Supported = !0; + } + } + for (var j = 0; j < a.localCandidates.length; j++) { + var k = a.localCandidates[j]; + "relay" !== k.candidateType && "relayed" !== k.candidateType || ("udp" === k.mozLocalTransport && (g.relayUdpGathered = !0), + "tcp" === k.mozLocalTransport && (g.relayTcpGathered = !0), "tls" === k.mozLocalTransport && (g.relayTlsGathered = !0)), + "srflx" !== k.candidateType && "serverreflexive" !== k.candidateType || (g.srflxGathered = !0); + } + for (var l = 0; l < a.iceCandidatePairs.length; l++) { + var m = a.iceCandidatePairs[l]; + if ("succeeded" === m.state) for (var n = 0; n < a.localCandidates.length; n++) { + var o = a.localCandidates[n]; + o.id == m.localCandidateId && ("relay" !== o.candidateType && "relayed" !== o.candidateType || ("udp" === o.mozLocalTransport && (g.relayUdpSuccess = !0), + "tcp" === o.mozLocalTransport && (g.relayTcpSuccess = !0), "tls" === o.mozLocalTransport && (g.relayTlsSuccess = !0)), + "srflx" !== o.candidateType && "serverreflexive" !== o.candidateType || (g.srflxSuccess = !0)); + } + } + b(g); + }, function(a) { + c(a); + }) : c(new Error("PC not available for stats")); + }, function(a) { + reject(a); + }); + } + } ]), a; + }(); + c.TurnConnection = j; + }, { + "./utility/parsedIceCandidate": 9, + "./utility/stats/detectbrowser": 11, + "./utility/stats/getstatshandler": 12, + bluebird: 1 + } ], + 7: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e(a) { + for (var b = "", c = 0; c < a; c++) b += String.fromCharCode(35 + 58 * Math.random()); + return b; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.randomAsciiString = c.MessageMaker = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../utility/timestamps"), h = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(g), i = function() { + function a() { + var b = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 1200; + d(this, a), this.message = { + timestamp: "", + sentBytes: 1e4, + padding: "" + }; + var c = e(b - h.getCurrent().toString().length - JSON.stringify(this.message).length); + this.message.padding = c; + } + return f(a, [ { + key: "make", + value: function(a) { + return this.message.timestamp = h.getCurrent(), this.message.sentBytes = a, JSON.stringify(this.message); + } + } ]), a; + }(); + c.MessageMaker = i, c.randomAsciiString = e; + }, { + "../utility/timestamps": 14 + } ], + 8: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.OnlineCheck = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./timestamps"), g = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(f), h = function() { + function a() { + d(this, a), this.active = !1; + } + return e(a, [ { + key: "start", + value: function() { + var a = this; + this.active = !0, this.onlineCheck = [], window && window.addEventListener && "function" == typeof window.addEventListener && (window.addEventListener("offline", function() { + a.addEntry(); + }), window.addEventListener("online", function() { + a.addEntry(); + }), this.addEntry()); + } + }, { + key: "addEntry", + value: function() { + if (this.active) { + var a = g.getCurrent(); + if (navigator && navigator.onLine) { + var b = navigator.onLine; + this.onlineCheck.push({ + timestamp: a, + online: b + }); + } + } + } + }, { + key: "stop", + value: function() { + var a = this; + return this.active = !1, window && window.removeEventListener && "function" == typeof window.removeEventListener && (window.removeEventListener("offline", function() { + a.addEntry(); + }), window.removeEventListener("online", function() { + a.addEntry(); + })), this.onlineCheck; + } + } ]), a; + }(); + c.OnlineCheck = h; + }, { + "./timestamps": 14 + } ], + 9: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a(b) { + d(this, a), this.iceCandidateStr = b.candidate, this.parse(); + } + return e(a, [ { + key: "parse", + value: function() { + var a = this.iceCandidateStr.split(" "); + a.length < 8 || (this.protocol = "1" === a[1] ? "rtp" : "rtcp", this.transport = a[2], + this.typeTransport = this.extractTypeTransport(a[3]), this.ipv6 = -1 !== a[4].indexOf(":"), + this.ipAddress = a[4], this.port = a[5], this.type = a[7]); + } + }, { + key: "extractTypeTransport", + value: function(a) { + var b = "None", c = a >> 24; + if ("rtp" === this.protocol && c >= 0 && c <= 2) switch (c) { + case 0: + b = "TLS"; + break; + + case 1: + b = "TCP"; + break; + + case 2: + b = "UDP"; + } + return b; + } + }, { + key: "getString", + value: function() { + return this.iceCandidateStr; + } + }, { + key: "getType", + value: function() { + return this.type; + } + }, { + key: "isHost", + value: function() { + return "host" === this.type.toLowerCase(); + } + }, { + key: "isServerReflexive", + value: function() { + return "srflx" === this.type.toLowerCase(); + } + }, { + key: "isPeerReflexive", + value: function() { + return "prflx" === this.type.toLowerCase(); + } + }, { + key: "isRelay", + value: function() { + return "relay" === this.type.toLowerCase() || "relayed" === this.type.toLowerCase(); + } + }, { + key: "getTypeTransport", + value: function() { + return this.typeTransport; + } + }, { + key: "isTypeTransportUdp", + value: function() { + return "UDP" === this.typeTransport; + } + }, { + key: "isTypeTransportTcp", + value: function() { + return "TCP" === this.typeTransport; + } + }, { + key: "isTypeTransportTls", + value: function() { + return "TLS" === this.typeTransport; + } + }, { + key: "getTransport", + value: function() { + return this.transport; + } + }, { + key: "isUdp", + value: function() { + return "udp" === this.transport.toLowerCase(); + } + }, { + key: "isTcp", + value: function() { + return "tcp" === this.transport.toLowerCase(); + } + }, { + key: "getProtocol", + value: function() { + return this.protocol; + } + }, { + key: "isRtp", + value: function() { + return "rtp" === this.protocol; + } + }, { + key: "isRtcp", + value: function() { + return "rtcp" === this.protocol; + } + }, { + key: "isIpv6", + value: function() { + return this.ipv6; + } + }, { + key: "getIpAddress", + value: function() { + return this.ipAddress; + } + }, { + key: "getPort", + value: function() { + return this.port; + } + } ]), a; + }(); + c.ParsedIceCandidate = f; + }, {} ], + 10: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.ResultsHandler = void 0; + var e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(a) { + return typeof a; + } : function(a) { + return a && "function" == typeof Symbol && a.constructor === Symbol && a !== Symbol.prototype ? "symbol" : typeof a; + }, f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("./timestamps"), h = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(g), i = a("./messageMaker"), j = function() { + function a() { + d(this, a), this.start = h.getCurrent(), this.id = Math.trunc(this.start) + "-" + (0, + i.randomAsciiString)(20), this.version = "1.2.0", this.failures = [], this.results = {}, + this.forceStopped = !1; + } + return f(a, [ { + key: "getResults", + value: function() { + return { + id: this.id, + version: this.version, + forceStopped: this.forceStopped, + startTimestamp: this.start, + endTimestamp: h.getCurrent(), + failures: this.failures, + tests: this.results + }; + } + }, { + key: "getFailureNumber", + value: function() { + return this.failures.length; + } + }, { + key: "getId", + value: function() { + return this.id; + } + }, { + key: "add", + value: function(a, b) { + this.results[a] = b, b.forceStopped && !0 === b.forceStopped && (this.forceStopped = !0); + } + }, { + key: "failure", + value: function(a) { + "object" === (void 0 === a ? "undefined" : e(a)) && (a = a.toString()); + var b = { + timestamp: h.getCurrent(), + reason: a + }; + this.failures.push(b); + } + } ]), a; + }(); + c.ResultsHandler = j; + }, { + "./messageMaker": 7, + "./timestamps": 14 + } ], + 11: [ function(a, b, c) { + "use strict"; + function d() { + var a = e.browserName.chrome, b = null, c = null, d = null, f = e.codeBaseType.chrome; + if (window && (!window.navigator || !window.navigator.userAgent || window.csioReactNative)) return window && window.csioGetOsName && (b = window.csioGetOsName()), + window && window.csioGetOsVer && (c = window.csioGetOsVer()), window && window.csioReactNative && (d = "react-native"), + { + browserName: a, + codeBase: f, + os: b, + osVersion: c, + userAgent: d + }; + var g = (d = navigator.userAgent).toLowerCase(), h = navigator.appVersion, i = "" + parseFloat(navigator.appVersion), j = void 0; + -1 !== (j = g.indexOf("opera")) ? (a = e.browserName.opera, i = g.substring(j + 6), + -1 !== (j = g.indexOf("Version")) && (i = g.substring(j + 8)), f = e.codeBaseType.chrome) : -1 !== (j = g.indexOf("opr")) ? (a = e.browserName.opera, + i = g.substring(j + 4), -1 !== (j = g.indexOf("Version")) && (i = g.substring(j + 8)), + f = e.codeBaseType.chrome) : -1 !== (j = g.indexOf("msie")) ? (a = e.browserName.msie, + i = g.substring(j + 5), f = e.codeBaseType.chrome) : -1 !== (j = g.indexOf("edge")) ? (a = e.browserName.edge, + i = g.substring(j + 5), f = e.codeBaseType.edge) : -1 !== (j = g.indexOf("chrome")) ? (a = e.browserName.chrome, + i = g.substring(j + 7), f = e.codeBaseType.chrome) : -1 !== (j = g.indexOf("safari")) ? (a = e.browserName.safari, + i = g.substring(j + 7), -1 !== (j = g.indexOf("Version")) && (i = g.substring(j + 8)), + f = e.codeBaseType.chrome) : -1 !== (j = g.indexOf("firefox")) ? (a = e.browserName.firefox, + i = g.substring(j + 8), f = e.codeBaseType.firefox) : -1 !== (j = g.indexOf("trident")) && (a = e.browserName.msie, + j = g.indexOf("rv"), i = g.substring(j + 3, j + 7), f = e.codeBaseType.chrome); + var k = [ { + s: "Windows 3.11", + r: /win16/ + }, { + s: "Windows 95", + r: /(windows 95|win95|windows_95)/ + }, { + s: "Windows ME", + r: /(win 9x 4.90|windows me)/ + }, { + s: "Windows 98", + r: /(windows 98|win98)/ + }, { + s: "Windows CE", + r: /windows ce/ + }, { + s: "Windows 2000", + r: /(windows nt 5.0|windows 2000)/ + }, { + s: "Windows XP", + r: /(windows nt 5.1|windows xp)/ + }, { + s: "Windows Server 2003", + r: /windows nt 5.2/ + }, { + s: "Windows Vista", + r: /windows nt 6.0/ + }, { + s: "Windows 7", + r: /(windows 7|windows nt 6.1)/ + }, { + s: "Windows 8.1", + r: /(windows 8.1|windows nt 6.3)/ + }, { + s: "Windows 8", + r: /(windows 8|windows nt 6.2)/ + }, { + s: "Windows 10", + r: /(windows 10|windows nt 10.0)/ + }, { + s: "Windows NT 4.0", + r: /(windows nt 4.0|winnt4.0|winnt|windows nt)/ + }, { + s: "Windows ME", + r: /windows me/ + }, { + s: "Android", + r: /android/ + }, { + s: "Open BSD", + r: /openbsd/ + }, { + s: "Sun OS", + r: /sunos/ + }, { + s: "Linux", + r: /(linux|x11)/ + }, { + s: "iOS", + r: /(iphone|ipad|ipod)/ + }, { + s: "Mac OS X", + r: /mac os x/ + }, { + s: "Mac OS", + r: /(macppc|macintel|mac_powerpc|macintosh)/ + }, { + s: "QNX", + r: /qnx/ + }, { + s: "UNIX", + r: /unix/ + }, { + s: "BeOS", + r: /beos/ + }, { + s: "OS/2", + r: /os\/2/ + }, { + s: "Search Bot", + r: /(nuhk|googlebot|yammybot|openbot|slurp|msnbot|ask jeeves\/teoma|ia_archiver)/ + } ], l = void 0, m = void 0; + for (l in k) if (k.hasOwnProperty(l) && (m = k[l]).r.test(g)) { + b = m.s; + break; + } + switch (b && /Windows/.test(b) && (c = /Windows (.*)/.exec(b)[1], b = e.osName.windows), + b) { + case e.osName.mac: + c = /mac os x (10[\.\_\d]+)/.exec(g)[1]; + break; + + case e.osName.android: + c = /android ([\.\_\d]+)/.exec(g)[1]; + break; + + case e.osName.ios: + c = (c = /os (\d+)_(\d+)_?(\d+)?/.exec(h))[1] + "." + c[2] + "." + (0 | c[3]); + } + return { + browserName: a, + browserVersion: i.toString(), + os: b, + osVersion: c, + codeBase: f, + userAgent: d + }; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.detect = d; + var e = c.Constants = { + codeBaseType: { + chrome: "Chrome", + firefox: "Firefox", + edge: "Edge", + plugin: "Plugin" + }, + browserName: { + chrome: "Chrome", + firefox: "Firefox", + edge: "Edge", + msie: "Microsoft Internet Explorer", + safari: "Safari" + }, + osName: { + windows: "Windows", + mac: "Mac OS X", + android: "Android", + ios: "iOS" + } + }; + }, {} ], + 12: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.GetStatsHandler = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./detectbrowser"), g = a("./statsadapter"), h = a("bluebird"), i = function() { + function a(b) { + d(this, a), this.codeBase = b.codeBase, this.browserName = b.browserName, this.adapter = new g.StatsAdapter(this.codeBase, this.browserName), + this.isPromiseBased = !0; + } + return e(a, [ { + key: "getIceCandidates", + value: function(a) { + var b = this; + return new h(function(c, d) { + b.csioGetStats(b.iceCandidatesHandler.bind(b), a, function(a) { + c(a); + }); + }); + } + }, { + key: "iceCandidatesHandler", + value: function(a, b) { + b(this.adapter.getIceCandidates(a)); + } + }, { + key: "csioGetStats", + value: function(a, b, c) { + var d = f.Constants.codeBaseType.firefox, e = f.Constants.codeBaseType.chrome, g = f.Constants.codeBaseType.edge, h = f.Constants.browserName.safari; + b && (this.codeBase === d ? this.getStatsFirefox(a, b, c) : this.browserName === h ? this.getStatsSafari(a, b, c) : this.codeBase === e ? this.getStatsChrome(a, b, c) : this.codeBase === g && this.getStatsEdge(a, b, c)); + } + }, { + key: "getStatsFirefox", + value: function(a, b, c) { + var d = this; + if (d.isPromiseBased) try { + b.getStats().then(function(b) { + a(b, c); + }).catch(function(e) { + d.isPromiseBased = !1, b.getStats(null, function(b) { + a(b, c); + }, function() {}); + }); + } catch (e) { + d.isPromiseBased = !1, b.getStats(null, function(b) { + a(b, c); + }, function() {}); + } else b.getStats(null, function(b) { + a(b, c); + }, function() {}); + } + }, { + key: "getStatsChrome", + value: function(a, b, c) { + var d = this; + if (window && window.csioReactNative) b.getStats(null, function(b) { + a(b, c); + }, function(a) {}); else if (d.isPromiseBased) try { + b.getStats().then(function(b) { + a(b, c); + }).catch(function(e) { + d.isPromiseBased = !1, b.getStats(function(b) { + a(b, c); + }); + }); + } catch (d) { + isPromiseBased = !1, b.getStats(function(b) { + a(b, c); + }); + } else b.getStats(function(b) { + a(b, c); + }); + } + }, { + key: "getStatsEdge", + value: function(a, b, c) { + b.getStats().then(function(b) { + a(b, c); + }).catch(function(a) {}); + } + }, { + key: "getStatsSafari", + value: function(a, b, c) { + b.getStats().then(function(b) { + a(b, c); + }).catch(function(a) {}); + } + } ]), a; + }(); + c.GetStatsHandler = i; + }, { + "./detectbrowser": 11, + "./statsadapter": 13, + bluebird: 1 + } ], + 13: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.StatsAdapter = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./detectbrowser"), g = function() { + function a(b, c) { + d(this, a), this.codeBase = b, this.browser = c; + } + return e(a, [ { + key: "getIceCandidates", + value: function(a) { + if (!a) return null; + var b = this.extractRawStats(a); + return this.processRawStatsForIceInfo(b); + } + }, { + key: "extractRawStats", + value: function(a) { + var b = [], c = void 0, d = f.Constants.codeBaseType.firefox, e = f.Constants.codeBaseType.chrome, g = f.Constants.browserName.safari; + if (this.codeBase === d && this.browser !== g) a.forEach(function(a) { + b.push(a); + }); else if (this.codeBase === e && this.browser !== g) a && a.result ? b = a.result() : a && a.forEach && (b = [], + a.forEach(function(a) { + b.push(a); + })); else for (c in a) a.hasOwnProperty(c) && b.push(a[c]); + return b; + } + }, { + key: "processRawStatsForIceInfo", + value: function(a) { + var b = [], c = [], d = [], e = void 0; + if (!a) return null; + for (var f = 0; f < a.length; ++f) { + var g = this.getParsedStats(a[f]), h = this.statsClassifier(g); + if (h.candidatePair) d.push(h.candidatePair); else if (h.transportStats) { + if ("transport" === h.transportStats.type) { + e = h.transportStats.selectedCandidatePairId; + continue; + } + d.push(h.transportStats); + } else if (h.localCandidate) { + var i = h.localCandidate; + if ("relay" == i.candidateType || "relayed" == i.candidateType) { + if (!i.mozLocalTransport) { + var j = i.priority >> 24; + i.mozLocalTransport = this.formatRelayType(j); + } + i.mozLocalTransport = i.mozLocalTransport.toLowerCase(); + } + b.push(i); + } else h.remoteCandidate && c.push(h.remoteCandidate); + } + if (e) for (var k = 0; k < d.length; ++k) d[k].id === e && (d[k].googActiveConnection = "true"); + return { + localCandidates: b, + remoteCandidates: c, + iceCandidatePairs: d + }; + } + }, { + key: "getParsedStats", + value: function(a) { + var b = {}; + if (a.timestamp instanceof Date && (b.timestamp = a.timestamp.getTime().toString()), + a.type && (b.type = a.type), a.names) for (var c = a.names(), d = 0; d < c.length; ++d) b[c[d]] = a.stat(c[d]); else Object.assign(b, a); + if (b.values) { + for (var e = 0; e < b.values.length; e++) { + var f = b.values[e]; + Object.assign(b, f); + } + delete b.values; + } + return b; + } + }, { + key: "statsClassifier", + value: function(a) { + var b = {}, c = function() { + for (var b = arguments.length, c = Array(b), d = 0; d < b; d++) c[d] = arguments[d]; + for (var e = 0; e < c.length; e++) { + var f = c[e]; + if (a.type === f) return !0; + } + return !1; + }, d = c("inbound-rtp", "inboundrtp"), e = "true" === a.isRemote || !0 === a.isRemote; + return d || c("outbound-rtp", "outboundrtp") ? (b.tracks = {}, b.tracks.data = a, + b.tracks.ssrc = a.ssrc, b.tracks.streamType = d ? "inbound" : "outbound", b.tracks.reportType = "local", + void 0 !== a.isRemote && (b.tracks.reportType = e ? "remote" : "local")) : c("candidatepair") && a.selected ? b.transportStats = a : c("localcandidate", "local-candidate") ? b.localCandidate = a : c("remotecandidate", "remote-candidate") ? b.remoteCandidate = a : c("transport", "googCandidatePair") ? b.transportStats = a : c("VideoBwe") ? b.bwe = a : c("track") ? b.trackStats = a : c("candidate-pair") ? b.candidatePair = a : c("codec") ? b.codec = a : c("ssrc") && (b.tracks = {}, + b.tracks.data = a, b.tracks.ssrc = a.ssrc, b.tracks.reportType = "local", b.tracks.streamType = a.bytesSent ? "outbound" : "inbound"), + b; + } + }, { + key: "formatRelayType", + value: function(a) { + var b = "none"; + switch (a) { + case 0: + b = "tls"; + break; + + case 1: + b = "tcp"; + break; + + case 2: + b = "udp"; + } + return b; + } + } ]), a; + }(); + c.StatsAdapter = g; + }, { + "./detectbrowser": 11 + } ], + 14: [ function(a, b, c) { + "use strict"; + function d() { + return window && window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now(); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.getCurrent = d; + }, {} ], + 15: [ function(a, b, c) { + function d() { + throw new Error("setTimeout has not been defined"); + } + function e() { + throw new Error("clearTimeout has not been defined"); + } + function f(a) { + if (l === setTimeout) return setTimeout(a, 0); + if ((l === d || !l) && setTimeout) return l = setTimeout, setTimeout(a, 0); + try { + return l(a, 0); + } catch (b) { + try { + return l.call(null, a, 0); + } catch (b) { + return l.call(this, a, 0); + } + } + } + function g(a) { + if (m === clearTimeout) return clearTimeout(a); + if ((m === e || !m) && clearTimeout) return m = clearTimeout, clearTimeout(a); + try { + return m(a); + } catch (b) { + try { + return m.call(null, a); + } catch (b) { + return m.call(this, a); + } + } + } + function h() { + q && o && (q = !1, o.length ? p = o.concat(p) : r = -1, p.length && i()); + } + function i() { + if (!q) { + var a = f(h); + q = !0; + for (var b = p.length; b; ) { + for (o = p, p = []; ++r < b; ) o && o[r].run(); + r = -1, b = p.length; + } + o = null, q = !1, g(a); + } + } + function j(a, b) { + this.fun = a, this.array = b; + } + function k() {} + var l, m, n = b.exports = {}; + !function() { + try { + l = "function" == typeof setTimeout ? setTimeout : d; + } catch (a) { + l = d; + } + try { + m = "function" == typeof clearTimeout ? clearTimeout : e; + } catch (a) { + m = e; + } + }(); + var o, p = [], q = !1, r = -1; + n.nextTick = function(a) { + var b = new Array(arguments.length - 1); + if (arguments.length > 1) for (var c = 1; c < arguments.length; c++) b[c - 1] = arguments[c]; + p.push(new j(a, b)), 1 !== p.length || q || f(i); + }, j.prototype.run = function() { + this.fun.apply(null, this.array); + }, n.title = "browser", n.browser = !0, n.env = {}, n.argv = [], n.version = "", + n.versions = {}, n.on = k, n.addListener = k, n.once = k, n.off = k, n.removeListener = k, + n.removeAllListeners = k, n.emit = k, n.prependListener = k, n.prependOnceListener = k, + n.listeners = function(a) { + return []; + }, n.binding = function(a) { + throw new Error("process.binding is not supported"); + }, n.cwd = function() { + return "/"; + }, n.chdir = function(a) { + throw new Error("process.chdir is not supported"); + }, n.umask = function() { + return 0; + }; + }, {} ], + 16: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a() { + var b = this; + d(this, a), this.batteryManager = null, "function" == typeof navigator.getBattery && navigator.getBattery().then(function(a) { + b.batteryManager = a; + }); + } + return e(a, [ { + key: "getLevel", + value: function() { + return this.batteryManager ? this.batteryManager.level : -1; + } + }, { + key: "getCharging", + value: function() { + return this.batteryManager ? this.batteryManager.charging : null; + } + } ]), a; + }(); + c.Battery = f; + }, {} ], + 17: [ function(a, b, c) { + "use strict"; + function d() { + var a = f.browserName.chrome, b = null, c = null, d = null, e = null, g = f.codeBaseType.chrome; + if (!window.navigator.userAgent || window.csioReactNative) return window && window.csioGetOsName && (b = window.csioGetOsName()), + window && window.csioGetOsVer && (c = window.csioGetOsVer()), window && window.csioReactNative && (d = "react-native"), + { + browserName: a, + codeBase: g, + os: b, + osVersion: c, + userAgent: d, + browserVersion: null + }; + d = navigator.userAgent; + var h = d.toLowerCase(); + e = navigator.appVersion; + var i = e.toLowerCase(), j = "" + parseFloat(i), k = void 0; + -1 !== (k = h.indexOf("opera")) ? (a = f.browserName.opera, j = h.substring(k + 6), + -1 !== (k = h.indexOf("Version")) && (j = h.substring(k + 8)), g = f.codeBaseType.chrome) : -1 !== (k = h.indexOf("opr")) ? (a = f.browserName.opera, + j = h.substring(k + 4), -1 !== (k = h.indexOf("Version")) && (j = h.substring(k + 8)), + g = f.codeBaseType.chrome) : -1 !== (k = h.indexOf("msie")) ? (a = f.browserName.msie, + j = h.substring(k + 5), g = f.codeBaseType.chrome) : -1 !== (k = h.indexOf("edge")) ? (a = f.browserName.edge, + j = h.substring(k + 5), g = f.codeBaseType.edge) : -1 !== (k = h.indexOf("chrome")) ? (a = f.browserName.chrome, + j = h.substring(k + 7), g = f.codeBaseType.chrome) : -1 !== (k = h.indexOf("safari")) ? (a = f.browserName.safari, + j = h.substring(k + 7), -1 !== (k = h.indexOf("Version")) && (j = h.substring(k + 8)), + g = f.codeBaseType.chrome) : -1 !== (k = h.indexOf("firefox")) ? (a = f.browserName.firefox, + j = h.substring(k + 8), g = f.codeBaseType.firefox) : -1 !== (k = h.indexOf("trident")) && (a = f.browserName.msie, + k = h.indexOf("rv"), j = h.substring(k + 3, k + 7), g = f.codeBaseType.chrome); + var l = [ { + s: "Windows 3.11", + r: /win16/ + }, { + s: "Windows 95", + r: /(windows 95|win95|windows_95)/ + }, { + s: "Windows ME", + r: /(win 9x 4.90|windows me)/ + }, { + s: "Windows 98", + r: /(windows 98|win98)/ + }, { + s: "Windows CE", + r: /windows ce/ + }, { + s: "Windows 2000", + r: /(windows nt 5.0|windows 2000)/ + }, { + s: "Windows XP", + r: /(windows nt 5.1|windows xp)/ + }, { + s: "Windows Server 2003", + r: /windows nt 5.2/ + }, { + s: "Windows Vista", + r: /windows nt 6.0/ + }, { + s: "Windows 7", + r: /(windows 7|windows nt 6.1)/ + }, { + s: "Windows 8.1", + r: /(windows 8.1|windows nt 6.3)/ + }, { + s: "Windows 8", + r: /(windows 8|windows nt 6.2)/ + }, { + s: "Windows 10", + r: /(windows 10|windows nt 10.0)/ + }, { + s: "Windows NT 4.0", + r: /(windows nt 4.0|winnt4.0|winnt|windows nt)/ + }, { + s: "Windows ME", + r: /windows me/ + }, { + s: "Android", + r: /android/ + }, { + s: "Open BSD", + r: /openbsd/ + }, { + s: "Sun OS", + r: /sunos/ + }, { + s: "Linux", + r: /(linux|x11)/ + }, { + s: "iOS", + r: /(iphone|ipad|ipod)/ + }, { + s: "Mac OS X", + r: /mac os x/ + }, { + s: "Mac OS", + r: /(macppc|macintel|mac_powerpc|macintosh)/ + }, { + s: "QNX", + r: /qnx/ + }, { + s: "UNIX", + r: /unix/ + }, { + s: "BeOS", + r: /beos/ + }, { + s: "OS/2", + r: /os\/2/ + }, { + s: "Search Bot", + r: /(nuhk|googlebot|yammybot|openbot|slurp|msnbot|ask jeeves\/teoma|ia_archiver)/ + } ], m = void 0, n = void 0; + for (m in l) if (l.hasOwnProperty(m) && (n = l[m], n.r.test(h))) { + b = n.s; + break; + } + switch (b && /Windows/.test(b) && (c = /Windows (.*)/.exec(b)[1], b = f.osName.windows), + b) { + case f.osName.mac: + c = /mac os x (10[\.\_\d]+)/.exec(h)[1]; + break; + + case f.osName.android: + c = /android ([\.\_\d]+)/.exec(h)[1]; + break; + + case f.osName.ios: + if (!(c = /os (\d+)_(\d+)_?(\d+)?/.exec(i))) break; + c = c[1] + "." + c[2] + "." + (0 | c[3]); + } + return { + browserName: a, + browserVersion: j.toString(), + os: b, + osVersion: c, + codeBase: g, + userAgent: d + }; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.detect = d; + var e = a("../config/constants"), f = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(e); + }, { + "../config/constants": 32 + } ], + 18: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Devices = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../config/constants"), h = d(g), i = a("../utility/registry"), j = a("../utility/csiologger"), k = d(j), l = a("../utility/utils"), m = d(l), n = function() { + function a(b, c) { + e(this, a), this.conferenceId = b, this.pc = c, this.devices = null, this.emb = i.Registry.getEventMessageBuilder(); + } + return f(a, [ { + key: "collectConnected", + value: function() { + var a = this; + if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) { + var b = this; + navigator.mediaDevices.enumerateDevices().then(function(c) { + var d = m.normalizeMediaDeviceList(c); + b.sendConnected(d), setTimeout(a.collectConnected.bind(b), 1e4); + }).catch(function(c) { + setTimeout(a.collectConnected.bind(b), 1e4); + }); + } + } + }, { + key: "sendConnected", + value: function(a) { + this.devices ? this.compare(a) || (this.devices = a, this.send()) : (this.devices = a, + this.send()); + } + }, { + key: "compare", + value: function(a) { + return self.devices.sort().toString() === a.sort().toString(); + } + }, { + key: "send", + value: function() { + var a = { + mediaDeviceList: this.devices + }; + k.log("sending connectedDevice", h.internalFabricEvent.connectedDeviceList, a), + this.emb.make(h.internalFabricEvent.connectedDeviceList, this.conferenceId, this.pc, a); + } + } ]), a; + }(); + c.Devices = n; + }, { + "../config/constants": 32, + "../utility/csiologger": 87, + "../utility/registry": 94, + "../utility/utils": 100 + } ], + 19: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (b) try { + window && window.localStorage && window.localStorage.setItem(a, b); + } catch (a) { + return; + } + } + function e(a) { + try { + if (window && window.localStorage) return window.localStorage.getItem(a); + } catch (a) { + return null; + } + return null; + } + function f(a) { + try { + window && window.localStorage && window.localStorage.removeItem(a); + } catch (a) { + return; + } + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.store = d, c.get = e, c.remove = f; + }, {} ], + 20: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (b) try { + window && window.sessionStorage && window.sessionStorage.setItem(a, b); + } catch (a) { + return; + } + } + function e(a) { + try { + if (window && window.sessionStorage) return window.sessionStorage.getItem(a); + } catch (a) { + return null; + } + return null; + } + function f(a) { + try { + window && window.sessionStorage && window.sessionStorage.removeItem(a); + } catch (a) { + return; + } + } + function g(a, b) { + if (a) { + var c = JSON.parse(e("csio_ucid_data")); + c || (c = {}), c[a] || (c[a] = {}), c[a].ucID = b, d("csio_ucid_data", JSON.stringify(c)); + } + } + function h(a) { + if (!a) return null; + var b = JSON.parse(e("csio_ucid_data")); + return b && b[a] ? b[a].ucID : null; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.store = d, c.get = e, c.remove = f, c.storeUcId = g, c.getUcId = h; + }, {} ], + 21: [ function(a, b, c) { + (function(c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f(a, b) { + var c = {}; + return c.status = a, b && (c.message = b), c; + } + function g(a, b) { + return a + ": " + b + " " + (arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : ""); + } + function h() { + var a = null, b = r.Registry.getEndpoint().getBrowserName(); + return "Firefox" === b ? a = mozRTCPeerConnection : "Chrome" === b || "Opera" === b ? a = webkitRTCPeerConnection : "Safari" === b ? t.log("Browser type Safari") : "Edge" === b && (a = window.RTCPeerConnection), + a; + } + function i(a) { + if (null === a) return !1; + var b = r.Registry.getEndpoint().getCodeBase(); + if (b === m.codeBaseType.firefox) return "undefined" != typeof mozRTCPeerConnection && a instanceof mozRTCPeerConnection || "undefined" != typeof RTCPeerConnection && a instanceof RTCPeerConnection; + if (b === m.codeBaseType.edge || "function" == typeof a) return !0; + var c = h(); + return null !== c && a instanceof c || void 0 !== a.createOffer; + } + var j = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(a) { + return typeof a; + } : function(a) { + return a && "function" == typeof Symbol && a.constructor === Symbol && a !== Symbol.prototype ? "symbol" : typeof a; + }, k = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), l = a("./config/constants"), m = d(l), n = a("./config/settings"), o = d(n), p = a("./config/callstatserrors"), q = a("./fsm/mainfsm"), r = a("./utility/registry"), s = a("./utility/csiologger"), t = d(s), u = a("./utility/onerroreventlistner"), v = d(u), w = a("./utility/utils"), x = d(w); + v.setErrorEventListener(), x.assignPollyfill(), x.isIntegerPollyfill(); + var y = null, z = function() { + function a() { + e(this, a), y = new q.MainFSM(); + } + return k(a, [ { + key: "initialize", + value: function(a, b, c, d, e, h) { + if (!a || !c || !b) { + var i = g("initialize", p.csErrorStrings.argumentError); + return t.error(i), f(m.callstatsAPIReturnStatus.failure, i); + } + if (d && "function" != typeof d) { + var j = g("initialize", p.csErrorStrings.argumentError); + t.warn(j), d = null; + } + if (e && "function" != typeof e) { + var k = g("initialize", p.csErrorStrings.argumentError); + t.warn(k), e = null; + } + if ("function" != typeof b && !(window.crypto && (window.crypto.subtle || window.crypto.webkitSubtle) || window.msCrypto && window.msCrypto.subtle || window.csioReactNative)) { + var l = g("initialize", p.csErrorStrings.cryptoError); + return t.error(l), d && d(p.csError.tokenGenerationError, p.csErrorStrings.cryptoError), + f(m.callstatsAPIReturnStatus.failure, l); + } + try { + y.fire(q.MainEvents.onInitialize, a, c, b, d, e, h), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "initialize: Error", + error: a.message + ":" + a.stack + }), t.error("initialize: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "addNewFabric", + value: function(a, b, c, d, e, h) { + var j = null, k = m.endpointType.peer, l = m.transmissionDirection.sendrecv; + if (d || (d = m.tmpConferenceId), !a || !c) { + var n = g("addNewFabric", p.csErrorStrings.argumentError); + return t.error(n), f(m.callstatsAPIReturnStatus.failure, n); + } + if (h && "function" == typeof h && (j = h), e && "function" == typeof e && (j = e), + e && "function" != typeof e) { + if (e.remoteEndpointType) { + if (!m.endpointType.hasOwnProperty(e.remoteEndpointType)) { + var o = g("addNewFabric", p.csErrorStrings.invalidEndPointType, e.remoteEndpointType); + return t.error(o), f(m.callstatsAPIReturnStatus.failure, o); + } + k = e.remoteEndpointType; + } + if (e.fabricTransmissionDirection) { + if (!m.transmissionDirection.hasOwnProperty(e.fabricTransmissionDirection)) { + var s = g("addNewFabric", p.csErrorStrings.invalidTransmissionDirection, e.fabricTransmissionDirection); + return t.error(s), f(m.callstatsAPIReturnStatus.failure, s); + } + l = e.fabricTransmissionDirection; + } + } + if (!m.fabricUsage.hasOwnProperty(c) || c instanceof Function) { + var u = g("addNewFabric", p.csErrorStrings.fabricUsageInvalid, c); + return t.error(u), f(m.callstatsAPIReturnStatus.failure, u); + } + if (!i(a)) { + var v = g("addNewFabric", p.csErrorStrings.pcInvalid); + return t.error(v), f(m.callstatsAPIReturnStatus.failure, v); + } + var w = r.Registry.getConferenceManager().get(d); + if (w) { + if (w.getPeerConnectionManager().getPcHandler(a)) return f(m.callstatsAPIReturnStatus.success); + } + if (!r.Registry.getCredentials().getAppId() || !r.Registry.getCredentials().getUserId()) { + var x = g("addNewFabric", p.csErrorStrings.notInitialized); + return t.error(x), f(m.callstatsAPIReturnStatus.failure, x); + } + try { + y.fire(q.MainEvents.onAddNewFabric, a, b, c, d, k, l, j), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "addNewFabric: Error", + error: a.message + ":" + a.stack + }), t.error("addNewFabric: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "sendFabricEvent", + value: function(a, b, c, d) { + if (t.log("sendFabricEvent ", b), c || (c = m.tmpConferenceId), !a || !b) { + var e = g("sendFabricEvent", p.csErrorStrings.argumentError); + return t.error(e), f(m.callstatsAPIReturnStatus.failure, e); + } + if (b === m.fabricEvent.fabricSetupFailed) { + var h = g("sendFabricEvent", p.csErrorStrings.fabricEventUnsupported, b); + return t.error(h), f(m.callstatsAPIReturnStatus.failure, h); + } + if (!m.fabricEvent.hasOwnProperty(b) && !m.internalFabricEvent.hasOwnProperty(b)) { + var i = g("sendFabricEvent", p.csErrorStrings.fabricEventInvalid, b); + return t.error(i), f(m.callstatsAPIReturnStatus.failure, i); + } + if (!(b !== m.fabricEvent.activeDeviceList || d && d.deviceList)) { + var j = g("sendFabricEvent ", p.csErrorStrings.argumentError); + return t.error(j), f(m.callstatsAPIReturnStatus.failure, j); + } + var k = r.Registry.getConferenceManager().get(c); + if (!r.Registry.getCredentials().getAppId() || !r.Registry.getCredentials().getUserId() || !k) { + var l = g("sendFabricEvent ", p.csErrorStrings.notInitialized); + return t.error(l), f(m.callstatsAPIReturnStatus.failure, l); + } + if (!k.getPeerConnectionManager().getPcHandler(a)) { + var n = g("sendFabricEvent ", p.csErrorStrings.pcInvalid); + return t.error(n), f(m.callstatsAPIReturnStatus.failure, n); + } + try { + y.fire(q.MainEvents.onSendFabricEvent, a, b, c, d), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "sendFabricEvent: Error", + error: a.message + ":" + a.stack + }), t.error("sendFabricEvent: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "sendUserFeedback", + value: function(a, b, c) { + if (!b || !a) { + var d = g("sendUserFeedback", p.csErrorStrings.argumentError); + return t.error(d), f(m.callstatsAPIReturnStatus.failure, d); + } + if ("object" !== (void 0 === b ? "undefined" : j(b))) { + var e = g("sendUserFeedback", p.csErrorStrings.argumentError); + return t.error(e), f(m.callstatsAPIReturnStatus.failure, e); + } + if (0 === Object.keys(b).length) { + var h = g("sendUserFeedback", p.csErrorStrings.argumentError); + return t.error(h), f(m.callstatsAPIReturnStatus.failure, h); + } + try { + y.fire(q.MainEvents.onSendUserFeedback, a, b, c), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "sendUserFeedback: Error", + error: a.message + ":" + a.stack + }), t.error("sendUserFeedback: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "associateMstWithUserID", + value: function(a, b, c, d, e, h) { + if (c || (c = m.tmpConferenceId), !a || !d || !e) { + var j = g("associateMstWithUserID", p.csErrorStrings.argumentError); + return t.error(j), f(m.callstatsAPIReturnStatus.failure, j); + } + if (!i(a)) { + var k = g("associateMstWithUserID", p.csErrorStrings.pcInvalid); + return t.error(k), f(m.callstatsAPIReturnStatus.failure, k); + } + var l = r.Registry.getConferenceManager().get(c); + if (!l) { + var n = g("associateMstWithUserID", p.csErrorStrings.confereneDoesNotExist); + return t.error(n), f(m.callstatsAPIReturnStatus.failure, n); + } + if (!l.getPeerConnectionManager().getPcHandler(a)) { + var o = g("associateMstWithUserID", p.csErrorStrings.pcInvalid); + return t.error(o), f(m.callstatsAPIReturnStatus.failure, o); + } + h && "string" != typeof h && (t.error("associateMstWithUserID: Invalid videoTag"), + h = null); + try { + y.fire(q.MainEvents.onAssociateMstWithUserID, a, b, c, d, e, h), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "associateMstWithUserID: Error", + error: a.message + ":" + a.stack + }), t.error("associateMstWithUserID: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "reportError", + value: function(a, b, c, d, e, h) { + if (b || (b = m.tmpConferenceId), void 0 === a || !c) { + var i = g("reportError", p.csErrorStrings.argumentError); + return t.error(i), f(m.callstatsAPIReturnStatus.failure, i); + } + if (!m.webRTCFunctions.hasOwnProperty(c)) { + var j = g("reportError", p.csErrorStrings.webRTCFunctionsInvalid, c); + return t.error(j), f(m.callstatsAPIReturnStatus.failure, j); + } + if (void 0 === d && t.warn("reportError: Missing DOM error parameter"), !r.Registry.getCredentials().getAppId() || !r.Registry.getCredentials().getUserId()) { + var k = g("reportError", p.csErrorStrings.notInitialized); + return t.error(k), f(m.callstatsAPIReturnStatus.failure, k); + } + try { + y.fire(q.MainEvents.onReportError, a, b, c, d, e, h), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "reportError: Error", + error: a.message + ":" + a.stack + }), t.error("reportError: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "setProxyConfig", + value: function(a) { + if (window && !window.csioproxy) { + var b = g("setProxyConfig", p.csErrorStrings.setProxyConfigInvokeError); + return t.error(b), f(m.callstatsAPIReturnStatus.failure, b); + } + if (!a) { + var c = g("setProxyConfig", p.csErrorStrings.argumentError); + return t.error(c), f(m.callstatsAPIReturnStatus.failure, c); + } + try { + y.fire(q.MainEvents.onSetProxyConfig, a), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "setProxyConfig: Error", + error: a.message + ":" + a.stack + }), t.error("setProxyConfig: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "attachWifiStatsHandler", + value: function(a) { + if (!a) { + var b = g("attachWifiStatsHandler", p.csErrorStrings.argumentError); + return t.error(b), f(m.callstatsAPIReturnStatus.failure, b); + } + if ("function" != typeof a) { + var c = g("attachWifiStatsHandler", p.csErrorStrings.argumentError); + return t.error(c), f(m.callstatsAPIReturnStatus.failure, c); + } + try { + y.fire(q.MainEvents.onAttachWifiStatsHandler, a), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "attachWifiStatsHandler: Error", + error: a.message + ":" + a.stack + }), t.error("attachWifiStatsHandler: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "setIdentifiers", + value: function(a, b) { + if (!a) { + var c = g("setIdentifiers", p.csErrorStrings.argumentError); + return t.error(c), f(m.callstatsAPIReturnStatus.failure, c); + } + try { + y.fire(q.MainEvents.onSetIdentifiers, a, b), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "setIdentifiers: Error", + error: a.message + ":" + a.stack + }), t.error("setIdentifiers: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "makePrecallTest", + value: function() { + if (!r.Registry.getAuthenticator().getToken() || !r.Registry.getCredentials().getAppId()) { + var a = g("makePrecallTest", p.csErrorStrings.notInitialized); + return t.error(a), f(m.callstatsAPIReturnStatus.failure, a); + } + if (!r.Registry.getAuthenticator().getIceServers()) { + var b = g("makePrecallTest", p.csErrorStrings.notInitialized); + return t.error(b), f(m.callstatsAPIReturnStatus.failure, b); + } + if (!r.Registry.getCredentials().getCollectSDP()) { + var c = g("makePrecallTest", p.csErrorStrings.apiaccesserror); + return t.error(c), f(m.callstatsAPIReturnStatus.failure, c); + } + try { + y.fire(q.MainEvents.onMakePrecallTest), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "on: Error", + error: a.message + ":" + a.stack + }), t.error("makePrecallTest: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "on", + value: function(a, b) { + if (!b || "function" != typeof b) { + var c = g("on", p.csErrorStrings.argumentError); + return t.error(c), f(m.callstatsAPIReturnStatus.failure, c); + } + if (!a || !m.callbackFunctions.hasOwnProperty(a)) { + var d = g("on", p.csErrorStrings.argumentError); + return t.error(d), f(m.callstatsAPIReturnStatus.failure, d); + } + try { + y.fire(q.MainEvents.onOn, a, b), y.run(); + } catch (a) { + r.Registry.getGenericEventHandler().sendEvent(m.logEvents.error, { + msg: "on: Error", + error: a.message + ":" + a.stack + }), t.error("on: Error", a); + } + return f(m.callstatsAPIReturnStatus.success); + } + }, { + key: "fabricUsage", + get: function() { + return this.constructor.fabricUsage; + } + }, { + key: "fabricEvent", + get: function() { + return this.constructor.fabricEvent; + } + }, { + key: "webRTCFunctions", + get: function() { + return this.constructor.webRTCFunctions; + } + }, { + key: "csError", + get: function() { + return this.constructor.csError; + } + }, { + key: "qualityRating", + get: function() { + return this.constructor.qualityRating; + } + }, { + key: "callStatsAPIReturnStatus", + get: function() { + return this.constructor.callStatsAPIReturnStatus; + } + }, { + key: "version", + get: function() { + return this.constructor.version; + } + }, { + key: "userIDType", + get: function() { + return this.constructor.userIDType; + } + }, { + key: "transmissionDirection", + get: function() { + return this.constructor.transmissionDirection; + } + }, { + key: "endpointType", + get: function() { + return this.constructor.endpointType; + } + } ]), a; + }(); + z.fabricUsage = m.fabricUsage, z.fabricEvent = m.fabricEvent, z.webRTCFunctions = m.webRTCFunctions, + z.csError = p.csError, z.qualityRating = m.qualityRating, z.callStatsAPIReturnStatus = m.callstatsAPIReturnStatus, + z.version = o.version, z.userIDType = m.userIdType, z.endpointType = m.endpointType, + z.transmissionDirection = m.transmissionDirection, function() { + function a() { + return new z(); + } + "function" == typeof define && define.amd ? define("callstats", [], a) : c.callstats = a, + b.exports = a; + }("undefined" != typeof window && window); + }).call(this, "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}); + }, { + "./config/callstatserrors": 31, + "./config/constants": 32, + "./config/settings": 33, + "./fsm/mainfsm": 34, + "./utility/csiologger": 87, + "./utility/onerroreventlistner": 93, + "./utility/registry": 94, + "./utility/utils": 100 + } ], + 22: [ function(a, b, c) { + "use strict"; + function d(a) { + if (Array.isArray(a)) { + for (var b = 0, c = Array(a.length); b < a.length; b++) c[b] = a[b]; + return c; + } + return Array.from(a); + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.BinaryTree = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("./binarytreenode.js"), h = a("../utility/csiologger"), i = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(h), j = function() { + function a(b) { + e(this, a), this.root = null, this.top = null, this.bottom = null, this.comparator = b, + this.node_counter = 0, this.duplicate_counter = 0; + } + return f(a, [ { + key: "getTopNode", + value: function() { + return this.top; + } + }, { + key: "getTopValue", + value: function() { + return null === this.top ? null : this.top.peek(); + } + }, { + key: "getBottomValue", + value: function() { + return null === this.bottom ? null : this.bottom.peek(); + } + }, { + key: "getBottomNode", + value: function() { + return this.bottom; + } + }, { + key: "getDuplicatedCounter", + value: function() { + return this.duplicate_counter; + } + }, { + key: "getNodeCounter", + value: function() { + return this.node_counter; + } + }, { + key: "getSize", + value: function() { + return this.duplicate_counter + this.node_counter; + } + }, { + key: "insertNodeAtTop", + value: function(a) { + a && this.inserting(a.getValues(), this.top); + } + }, { + key: "insertNodeAtBottom", + value: function(a) { + a && this.inserting(a.getValues(), this.bottom); + } + }, { + key: "insert", + value: function(a) { + this.inserting([ a ], this.root); + } + }, { + key: "createNode", + value: function(a) { + var b = new (Function.prototype.bind.apply(g.BinaryTreeNode, [ null ].concat(d(a))))(); + return null === this.top ? this.top = b : this.comparator(this.top.peek(), b.peek()) < 0 && (this.top = b), + null === this.bottom ? this.bottom = b : this.comparator(b.peek(), this.bottom.peek()) < 0 && (this.bottom = b), + b; + } + }, { + key: "inserting", + value: function(a, b) { + if (null === this.root) return this.root = this.createNode(a), this.node_counter = 1, + void (this.duplicate_counter += a.length - 1); + for (var c = null, d = b, e = 0; null !== d; ) { + if (0 === (e = this.comparator(a[0], d.peek()))) return d.concat(a), this.duplicate_counter += a.length, + void d.find(a[0]); + c = d, d = e < 0 ? d.getLeft() : d.getRight(); + } + ++this.node_counter, this.duplicate_counter += a.length - 1, d = this.createNode(a), + e < 0 ? c.setLeft(d) : c.setRight(d); + } + }, { + key: "getRightist", + value: function(a) { + for (var b = null; null !== a.right; ) b = a, a = a.right; + return [ a, b ]; + } + }, { + key: "getLeftist", + value: function(a) { + for (var b = null; null !== a.getLeft(); ) b = a, a = a.getLeft(); + return [ a, b ]; + } + }, { + key: "popBottomNode", + value: function() { + if (null === this.bottom) return null; + var a = this.search(this.bottom.peek()), b = a[0], c = a[1]; + return this.replaceNode(b, c, b.getRight()), this.disposeNode(b), --this.node_counter, + this.duplicate_counter -= b.getLength() - 1, b.setRight(null), b; + } + }, { + key: "popTopNode", + value: function() { + if (null === this.top) return null; + var a = this.search(this.top.peek()), b = a[0], c = a[1]; + return null === b ? null : (this.replaceNode(b, c, b.getLeft()), this.disposeNode(b), + --this.node_counter, this.duplicate_counter -= b.getLength() - 1, b.setLeft(null), + b); + } + }, { + key: "search", + value: function(a) { + for (var b = this.root, c = null, d = void 0; null !== b; ) { + if (0 === (d = this.comparator(a, b.peek()))) return b.find(a) ? [ b, c ] : [ null, null ]; + c = b, b = d < 0 ? b.getLeft() : b.getRight(); + } + return [ null, null ]; + } + }, { + key: "replaceNode", + value: function(a, b, c) { + null !== b ? b.left === a ? b.left = c : b.right = c : this.root = c; + } + }, { + key: "disposeNode", + value: function(a) { + if (null === this.root) return void (this.bottom = this.top = null); + if (0 === this.comparator(this.top.peek(), a.peek())) { + var b = this.getRightist(this.root); + this.top = b[0]; + } + if (0 === this.comparator(this.bottom.peek(), a.peek())) { + var c = this.getLeftist(this.root); + this.bottom = c[0]; + } + } + }, { + key: "delete", + value: function(a) { + var b = this.search(a), c = b[0], d = b[1]; + if (null === c) return !1; + if (1 < c.getLength()) return c.remove(a), --this.duplicate_counter, !0; + if (--this.node_counter, null === c.getLeft() && null === c.getRight()) this.replaceNode(c, d, null); else if (null === c.getLeft()) this.replaceNode(c, d, c.getRight()); else if (null === c.getRight()) this.replaceNode(c, d, c.getLeft()); else { + for (var e = c.getLeft(), f = c; null !== e.getRight(); f = e, e = e.getRight()) ; + var g = e.getLeft(); + f === c ? f.setLeft(g) : f.setRight(g), c.setValues(e.getValues()); + } + return this.disposeNode(c), !0; + } + }, { + key: "logging", + value: function() { + if (null === this.root) return void i.log("This tree is empty Duplicate Counter: " + this.duplicate_counter); + i.log("Size of the tree: " + this.getSize() + " Node: " + this.getNodeCounter() + " Duplicates: " + this.getDuplicatedCounter() + " Top: " + this.getTopNode().toString() + " Bottom: " + this.getBottomNode().toString()), + function a(b, c, d) { + if (null !== b) { + for (var e = "-", f = 0; f < c; ++f) e += "--"; + i.log(e + "> (" + d + ") [" + b.toString() + "]"), null !== b.getLeft() && a(b.getLeft(), c + 1, "Left"), + null !== b.getRight() && a(b.getRight(), c + 1, "Right"); + } + }(this.root, 0, "Root"); + } + } ]), a; + }(); + c.BinaryTree = j; + }, { + "../utility/csiologger": 87, + "./binarytreenode.js": 23 + } ], + 23: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a() { + d(this, a); + for (var b = arguments.length, c = Array(b), e = 0; e < b; e++) c[e] = arguments[e]; + this.values = c, this.left = null, this.right = null; + } + return e(a, [ { + key: "getRight", + value: function() { + return this.right; + } + }, { + key: "setRight", + value: function(a) { + this.right = a; + } + }, { + key: "getLeft", + value: function() { + return this.left; + } + }, { + key: "setLeft", + value: function(a) { + this.left = a; + } + }, { + key: "push", + value: function(a) { + this.values.push(a); + } + }, { + key: "concat", + value: function(a) { + this.values = this.values.concat(a); + } + }, { + key: "pop", + value: function() { + return this.values.length < 1 ? null : this.values.shift(); + } + }, { + key: "remove", + value: function(a) { + this.values.splice(this.values.indexOf(a), 1); + } + }, { + key: "setValues", + value: function(a) { + this.values = a; + } + }, { + key: "getValues", + value: function() { + return this.values; + } + }, { + key: "hasValue", + value: function() { + return 0 < this.values.length; + } + }, { + key: "getLength", + value: function() { + return this.values.length; + } + }, { + key: "peek", + value: function() { + return this.values.length < 1 ? null : this.values[0]; + } + }, { + key: "find", + value: function(a) { + return this.values.find(function(b) { + return b === a; + }); + } + }, { + key: "toString", + value: function() { + return this.values.toString(); + } + } ]), a; + }(); + c.BinaryTreeNode = f; + }, {} ], + 24: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Cache = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("../utility/csiologger"), g = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(f), h = function() { + function a() { + d(this, a), this.queue = [], this.priority = []; + } + return e(a, [ { + key: "add", + value: function(a) { + var b = arguments.length > 1 && void 0 !== arguments[1] && arguments[1]; + if (this.length() > 1e6) return void g.error("Maximum cached items reached, dropping."); + b ? this.priority.push(a) : this.queue.push(a); + } + }, { + key: "pop", + value: function() { + return this.priority.length > 0 ? this.priority.shift() : this.queue.shift(); + } + }, { + key: "peak", + value: function() { + return this.priority.length > 0 ? this.priority[0] : this.queue.length > 0 ? this.queue[0] : null; + } + }, { + key: "length", + value: function() { + return this.queue.length + this.priority.length; + } + }, { + key: "updateConferenceId", + value: function(a) { + for (var b = 0; b < this.queue.length; ++b) { + this.queue[b].updateConferenceId(a); + } + for (var c = 0; c < this.priority.length; ++c) { + this.priority[c].updateConferenceId(a); + } + } + } ]), a; + }(); + c.Cache = h; + }, { + "../utility/csiologger": 87 + } ], + 25: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Component = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./port"), g = a("../utility/csiologger"), h = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(g), i = function() { + function a() { + var b = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "Unknown"; + d(this, a), this.name = b, this.ports = new Map(); + } + return e(a, [ { + key: "bindPort", + value: function(a, b) { + var c = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : this; + if (this.ports.has(a)) return void h.warn("Port (" + a + ") for " + this.name + " already exists."); + this.ports.set(a, new f.Port(b, c)); + } + }, { + key: "declarePort", + value: function(a) { + if (this.ports.has(a)) return void h.warn("Port (" + a + ") for " + this.name + " already exists."); + this.ports.set(a, null); + } + }, { + key: "getPort", + value: function(a) { + return this.ports.get(a); + } + }, { + key: "isConnected", + value: function(a) { + return !!this.ports.has(a) && null !== this.ports.get(a); + } + }, { + key: "connect", + value: function(a, b) { + if (!this.ports.has(a)) return void h.warn("Port (" + a + ") for " + this.name + " does not exists."); + this.ports.set(a, b); + } + }, { + key: "transmit", + value: function(a) { + var b = this.ports.get(a); + if (void 0 === b) return void h.warn("Port (" + a + ") for " + this.name + " does not exists."); + if (null === b) return void h.warn("Port (" + a + ") for " + this.name + " is not connected."); + for (var c = arguments.length, d = Array(c > 1 ? c - 1 : 0), e = 1; e < c; e++) d[e - 1] = arguments[e]; + b.transmit(d); + } + }, { + key: "request", + value: function(a) { + var b = this.ports.get(a); + if (void 0 === b) return h.warn("Port (" + a + ") for " + this.name + " does not exists."), + null; + if (null === b) return h.warn("Port (" + a + ") for " + this.name + " is not connected."), + null; + for (var c = arguments.length, d = Array(c > 1 ? c - 1 : 0), e = 1; e < c; e++) d[e - 1] = arguments[e]; + return b.request(d); + } + } ]), a; + }(); + c.Component = i; + }, { + "../utility/csiologger": 87, + "./port": 26 + } ], + 26: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a(b) { + var c = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null; + d(this, a), this.target = b, this.object = c; + } + return e(a, [ { + key: "transmit", + value: function(a) { + this.target.apply(this.object, a); + } + }, { + key: "request", + value: function(a) { + return this.target.apply(this.object, a); + } + } ]), a; + }(); + c.Port = f; + }, {} ], + 27: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.SlidingWindow = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./switem"), g = a("../utility/timestamps"), h = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(g), i = function() { + function a(b, c) { + d(this, a), this.items = [], this.plugins = [], this.postProcesses = [], this.preProcesses = [], + this.timeoutInMs = c, this.maxItemsNum = b, this.minItemsNum = 0; + } + return e(a, [ { + key: "setMaxItemsNum", + value: function(a) { + this.maxItemsNum = a; + } + }, { + key: "setTimeoutInMs", + value: function(a) { + this.timeoutInMs = a; + } + }, { + key: "setMinItemsNum", + value: function(a) { + this.minItemsNum = a; + } + }, { + key: "refresh", + value: function() { + var a = h.getCurrent(); + if (!(this.items.length <= this.minItemsNum)) { + for (;0 < this.maxItemsNum && this.maxItemsNum <= this.items.length; ) this.remove(); + this.timeoutInMs && this.timeoutInMs < a - this.items[0].getCreated() && (this.remove(), + this.refresh()); + } + } + }, { + key: "getLength", + value: function() { + return this.items.length; + } + }, { + key: "add", + value: function(a) { + this.refresh(), this.items.push(new f.SWItem(a)); + for (var b = 0; b < this.preProcesses.length; b++) { + (0, this.preProcesses[b])(a); + } + for (var c = 0; c < this.plugins.length; c++) { + this.plugins[c].add(a); + } + for (var d = 0; d < this.postProcesses.length; d++) { + (0, this.postProcesses[d])(a); + } + } + }, { + key: "remove", + value: function() { + for (var a = this.items.shift(), b = 0; b < this.plugins.length; b++) { + this.plugins[b].remove(a.value); + } + } + }, { + key: "peek", + value: function() { + var a = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 0; + return this.items.length <= a ? null : this.items[this.items.length - a - 1].getValue(); + } + }, { + key: "attach", + value: function(a) { + this.plugins.push(a); + } + }, { + key: "addPreProcess", + value: function(a) { + this.preProcesses.push(a); + } + }, { + key: "addPostProcess", + value: function(a) { + this.postProcesses.push(a); + } + }, { + key: "detach", + value: function(a) { + this.plugins = this.plugins.filter(function(b) { + return b !== a; + }); + } + } ]), a; + }(); + c.SlidingWindow = i; + }, { + "../utility/timestamps": 98, + "./switem": 28 + } ], + 28: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.SWItem = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("../utility/timestamps"), g = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(f), h = function() { + function a(b) { + d(this, a), this.value = b, this.created = g.getCurrent(); + } + return e(a, [ { + key: "getValue", + value: function() { + return this.value; + } + }, { + key: "getCreated", + value: function() { + return this.created; + } + }, { + key: "toString", + value: function() { + return ""; + } + } ]), a; + }(); + c.SWItem = h; + }, { + "../utility/timestamps": 98 + } ], + 29: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Conference = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../peerconnection/peerconnectionmanager"), h = a("../config/settings"), i = d(h), j = a("../utility/registry"), k = a("../browserapi/sessionstorage"), l = d(k), m = function() { + function a(b, c) { + e(this, a), this.conferenceId = b, this.startTime, this.peerConnectionManager = new g.PeerConnectionManager(), + this.credentials = c, this.ucId = null, this.url = null, this.userJoinedSent = !1; + } + return f(a, [ { + key: "getCredentials", + value: function() { + return this.credentials; + } + }, { + key: "getUcId", + value: function() { + return this.ucId; + } + }, { + key: "setUcId", + value: function(a) { + this.ucId = a, this.url = i.conferenceBaseUrl + j.Registry.getCredentials().getAppId() + "/conferences/" + encodeURIComponent(this.conferenceId) + "/" + a + "/general", + l.storeUcId(this.conferenceId, a); + } + }, { + key: "getPeerConnectionManager", + value: function() { + return this.peerConnectionManager; + } + }, { + key: "getUrl", + value: function() { + return this.url; + } + }, { + key: "updateConferenceId", + value: function(a) { + this.conferenceId = a, this.peerConnectionManager.updateConferenceId(a); + } + }, { + key: "close", + value: function(a) {} + } ]), a; + }(); + c.Conference = m; + }, { + "../browserapi/sessionstorage": 20, + "../config/settings": 33, + "../peerconnection/peerconnectionmanager": 41, + "../utility/registry": 94 + } ], + 30: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.ConferenceManager = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./conference"), g = a("../config/constants"), h = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(g), i = function() { + function a() { + d(this, a), this.conferenceMap = new Map(); + } + return e(a, [ { + key: "add", + value: function(a, b) { + if (!this.get(a)) { + var c = new f.Conference(a, b); + this.conferenceMap.set(a, c); + } + } + }, { + key: "get", + value: function(a) { + return this.conferenceMap.get(a); + } + }, { + key: "getConferenceForPc", + value: function(a) { + var b = null; + return a ? (this.conferenceMap.forEach(function(c, d) { + var e = c.getPeerConnectionManager().getPcHandler(a); + e && e.getConferenceId() === d && (b = c); + }), b) : b; + } + }, { + key: "getConferenceForPcHash", + value: function(a) { + var b = null; + return a ? (this.conferenceMap.forEach(function(c, d) { + var e = c.getPeerConnectionManager().getPcHandlerByHash(a); + e && e.getConferenceId() === d && (b = c); + }), b) : b; + } + }, { + key: "updateConferenceId", + value: function(a) { + var b = h.tmpConferenceId, c = this.get(b); + c && (c.updateConferenceId(a), this.conferenceMap.set(a, c), this.conferenceMap.delete(b)); + } + }, { + key: "getConferenceIds", + value: function() { + var a = []; + return this.conferenceMap.forEach(function(b, c) { + a.push(c); + }), a; + } + } ]), a; + }(); + c.ConferenceManager = i; + }, { + "../config/constants": 32, + "./conference": 29 + } ], + 31: [ function(a, b, c) { + "use strict"; + Object.defineProperty(c, "__esModule", { + value: !0 + }); + c.csError = { + httpError: "httpError", + authError: "authError", + wsChannelFailure: "wsChannelFailure", + success: "success", + csProtoError: "csProtoError", + appConnectivityError: "appConnectivityError", + tokenGenerationError: "tokenGenerationError", + ok: "OK", + authOngoing: "authOngoing", + invalidWebRTCFunctionName: "Invalid WebRTC function name", + invalidEndPointType: "Invalid EndPoint Type", + invalidTransmissionDirection: "Invalid fabric transmission direction" + }, c.csErrorStrings = { + argumentError: "Argument missing/invalid", + cryptoError: "Browser does not support Web Cryptography API. App secret based authentication requires Web Cryptography API", + fabricEventUnsupported: "Unsupported fabricEvent", + fabricEventInvalid: "Invalid fabricEvents value", + fabricUsageInvalid: "Invalid fabricUsage value", + notInitialized: "SDK is not initialized or no Fabrics added", + pcInvalid: "Invalid PeerConnection object passed", + confereneDoesNotExist: "conferenceId does not exist", + webRTCFunctionsInvalid: "Invalid webRTC functionName value", + setProxyConfigInvokeError: "cannot be called if window.csioproxy is false", + invalidWebRTCFunctionName: "Invalid WebRTC function name", + invalidEndPointType: "Invalid EndPoint Type", + invalidTransmissionDirection: "Invalid fabric transmission direction", + apiaccesserror: "API access Error" + }, c.csErrorReason = { + csProtoError: "Protocol fields cannot be empty.", + csNoAuthState: "Authentication state unavailable in server." + }, c.internalErrors = { + authOngoing: "authOngoing" + }, c.authErrorActions = { + RETRY: 0, + GET_NEW_TOKEN: 1, + REPORT_ERROR: 2 + }; + }, {} ], + 32: [ function(a, b, c) { + "use strict"; + Object.defineProperty(c, "__esModule", { + value: !0 + }); + c.logEvents = { + stateMachine: "stateMachine", + log: "log", + timing: "timing", + error: "error", + getStatsError: "getStatsError", + restResponseError: "restResponseError" + }, c.fabricEvent = { + fabricSetupFailed: "fabricSetupFailed", + fabricHold: "fabricHold", + fabricResume: "fabricResume", + audioMute: "audioMute", + audioUnmute: "audioUnmute", + videoPause: "videoPause", + videoResume: "videoResume", + fabricUsageEvent: "fabricUsageEvent", + fabricTerminated: "fabricTerminated", + screenShareStart: "screenShareStart", + screenShareStop: "screenShareStop", + dominantSpeaker: "dominantSpeaker", + activeDeviceList: "activeDeviceList", + applicationErrorLog: "applicationErrorLog" + }, c.internalFabricEvent = { + fabricSetup: "fabricSetup", + fabricSetupFailed: "fabricSetupFailed", + userJoined: "userJoined", + userLeft: "userLeft", + userAlive: "userAlive", + ssrcMap: "ssrcMap", + mediaPlaybackStart: "mediaPlaybackStart", + mediaPlaybackSuspended: "mediaPlaybackSuspended", + mediaPlaybackStalled: "mediaPlaybackStalled", + oneWayMedia: "oneWayMedia", + fabricStateChange: "fabricStateChange", + iceDisruptionStart: "iceDisruptionStart", + iceDisruptionEnd: "iceDisruptionEnd", + fabricTransportSwitch: "fabricTransportSwitch", + iceConnectionDisruptionStart: "iceConnectionDisruptionStart", + iceConnectionDisruptionEnd: "iceConnectionDisruptionEnd", + iceAborted: "iceAborted", + iceTerminated: "iceTerminated", + iceFailed: "iceFailed", + iceRestarted: "iceRestarted", + fabricDropped: "fabricDropped", + connectedDeviceList: "connectedDeviceList", + sdpSubmission: "sdpSubmissionEvent", + sendingThroughputObservations: "sendingThroughputObservations", + limitationObservations: "limitationObservations", + userDetails: "userDetails" + }, c.callstatsChannels = { + sdpSubmission: "sdpSubmissionEvent", + processedStats: "processedStats", + callstatsEvent: "callStatsEvent", + userFeedback: "userFeedbackEvent", + preCallTest: "preCallTest", + senderConfiguration: "senderConfiguration" + }, c.precalltestEvents = { + results: "preCallTestResults", + associate: "preCallTestAssociate" + }, c.callstatsAPIReturnStatus = { + success: "success", + failure: "failure" + }, c.fabricUsage = { + audio: "audio", + video: "video", + data: "data", + screen: "screen", + multiplex: "multiplex", + unbundled: "unbundled" + }, c.userIdType = { + local: "local", + remote: "remote" + }, c.qualityRating = { + excellent: 5, + good: 4, + fair: 3, + poor: 2, + bad: 1 + }, c.reportType = { + local: "local", + remote: "remote", + inbound: "inbound", + outbound: "outbound" + }, c.avQualityRatings = { + excellent: "excellent", + fair: "fair", + bad: "bad", + unknown: "unknown" + }, c.fabricState = { + established: "established", + initializing: "initializing", + failed: "failed", + disrupted: "disrupted", + hold: "hold", + checkingDisrupted: "checkingDisrupted", + terminated: "terminated" + }, c.webRTCFunctions = { + createOffer: "createOffer", + createAnswer: "createAnswer", + setLocalDescription: "setLocalDescription", + setRemoteDescription: "setRemoteDescription", + addIceCandidate: "addIceCandidate", + getUserMedia: "getUserMedia", + iceConnectionFailure: "iceConnectionFailure", + signalingError: "signalingError", + applicationError: "applicationError", + applicationLog: "applicationLog" + }, c.callFailureReasons = { + mediaConfigError: "MediaConfigError", + negotiationFailure: "NegotiationFailure", + sdpError: "SDPGenerationError", + iceFailure: "IceConnectionFailure", + transportFailure: "TransportFailure", + signalingError: "SignalingError", + applicationError: "ApplicationError", + applicationLog: "ApplicationLog", + invalidWebRTCFunctionName: "Invalid WebRTC function name" + }, c.throughputThreshold = { + video: { + green: 1024, + red: 256 + }, + audio: { + green: 30, + red: 8 + } + }, c.currOverPrevFrameRateThreshold = { + video: { + green: .8, + red: .3 + } + }, c.rttThreshold = { + video: { + green: 400, + red: 1e3 + } + }, c.fractionalLossThreshold = { + video: { + green: .1, + red: .5 + }, + audio: { + green: .15, + red: .3 + } + }, c.eModelThreshold = { + audio: { + green: 240, + red: 400 + } + }, c.codeBaseType = { + chrome: "Chrome", + firefox: "Firefox", + edge: "Edge", + plugin: "Plugin" + }, c.browserName = { + chrome: "Chrome", + firefox: "Firefox", + edge: "Edge", + msie: "Microsoft Internet Explorer", + safari: "Safari", + opera: "Opera" + }, c.osName = { + windows: "Windows", + mac: "Mac OS X", + android: "Android", + ios: "iOS" + }, c.mediaType = { + audio: "audio", + video: "video" + }, c.streamType = { + inbound: "inbound", + outbound: "outbound" + }, c.fabricStateChangeType = { + signalingState: "signalingState", + iceConnectionState: "iceConnectionState", + iceGatheringState: "iceGatheringState" + }, c.transportType = { + rest: "rest", + ws: "ws" + }, c.wsConnectionState = { + initiated: "initiated", + connected: "connected", + closed: "closed" + }, c.csCallBackMessages = { + authSuccessful: "SDK authentication successful.", + authFailed: "SDK authentication failed.", + authProtocolInvalid: "Fatal authentication error. Invalid auth protocol message.", + authOngoing: "Authentication on going.", + wsConnected: "WebSocket establishment successful.", + wsClosed: "WebSocket server closed.", + wsFailed: "WebSocket establishment failed." + }, c.oneWayMediaTypes = { + audio: "audio", + video: "video", + screen: "screen" + }, c.limitationType = { + cpu: "cpu", + network: "network" + }, c.qualityDisruptionTypes = { + qpchange: "qpchange" + }, c.callbackFunctions = { + stats: "stats", + defaultConfig: "defaultConfig", + recommendedConfig: "recommendedConfig", + preCallTestResults: "preCallTestResults" + }, c.endpointType = { + peer: "peer", + server: "server" + }, c.transmissionDirection = { + sendonly: "sendonly", + receiveonly: "receiveonly", + sendrecv: "sendrecv", + inactive: "inactive" + }, c.tmpConferenceId = "csio-conf-id-tmp"; + }, {} ], + 33: [ function(a, b, c) { + "use strict"; + function d(a) { + c.configServiceUrl = m = a; + } + function e(a) { + c.authServiceUrl = n = a; + } + function f(a) { + c.conferenceBaseUrl = o = a; + } + function g(a) { + c.wsUrl = p = a; + } + function h(a) { + c.restEventUrl = q = a; + } + function i(a) { + c.restStatsUrl = r = a; + } + function j(a) { + c.baseUrl = s = a; + } + function k(a) { + c.qmodelThresholdsAPIUrl = t = a; + } + function l(a) { + c.transportType = u = a; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.setConfigServiceUrl = d, c.setAuthServiceUrl = e, c.setConferenceBaseUrl = f, + c.setWsUrl = g, c.setRestEventUrl = h, c.setRestStatsUrl = i, c.setBaseUrl = j, + c.setQmodelThresholdsAPIUrl = k, c.setTransportType = l; + var m = (c.version = "3.50.3", c.configServiceUrl = "https://appsettings.callstats.io/v1/apps/"), n = c.authServiceUrl = "https://auth.callstats.io/", o = (c.authRetryTimeout = 5e3, + c.conferenceBaseUrl = "https://dashboard.callstats.io/apps/"), p = c.wsUrl = "wss://collector.callstats.io:443/csiows/collectCallStats", q = c.restEventUrl = "https://events.callstats.io/v1/apps/", r = c.restStatsUrl = "https://stats.callstats.io/v1/apps/", s = c.baseUrl = "https://collector.callstats.io:443/", t = c.qmodelThresholdsAPIUrl = "https://dashboard.callstats.io/api-internal/v1/qmodelthresholds", u = (c.csioDebug = "false", + c.transportType = "@@transportType"); + }, {} ], + 34: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a) { + if (Array.isArray(a)) { + for (var b = 0, c = Array(a.length); b < a.length; b++) c[b] = a[b]; + return c; + } + return Array.from(a); + } + function f(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function g(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function h(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + function i() { + Array.prototype.find || Object.defineProperty(Array.prototype, "find", { + value: function(a) { + if (null === this) throw new TypeError("Array.prototype.find called on null or undefined"); + if ("function" != typeof a) throw new TypeError("predicate must be a function"); + for (var b = Object(this), c = b.length >>> 0, d = arguments[1], e = void 0, f = 0; f < c; f++) if (e = b[f], + a.call(d, e, f, b)) return e; + } + }); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.MainFSM = c.MainEvents = void 0; + var j = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(a) { + return typeof a; + } : function(a) { + return a && "function" == typeof Symbol && a.constructor === Symbol && a !== Symbol.prototype ? "symbol" : typeof a; + }, k = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), l = a("./statemachine"), m = a("../utility/registry"), n = a("../utility/csiologger"), o = d(n), p = a("../utility/utils"), q = d(p), r = a("../utility/timestamps"), s = d(r), t = a("../config/constants"), u = d(t), v = a("../config/settings"), w = d(v), x = a("./utility"), y = d(x), z = a("../statspipeline/statsadapter"), A = a("../statspipeline/statsparser"), B = a("../statspipeline/statsmonitor"), C = a("../statspipeline/statstransmitter"), D = a("../statspipeline/statsassembler"), E = { + Created: "Created", + Initializing: "Initializing", + Idle: "Idle", + Run: "Run" + }, F = c.MainEvents = { + onStart: "onStart", + onInitialize: "onInitialize", + onAddNewFabric: "onAddNewFabric", + onSendFabricEvent: "onSendFabricEvent", + onReportError: "onReportError", + onAssociateMstWithUserID: "onAssociateMstWithUserID", + onSetProxyConfig: "onSetProxyConfig", + onAttachWifiStatsHandler: "onAttachWifiStatsHandler", + onSendUserFeedback: "onSendUserFeedback", + onOn: "onOn", + onSetIdentifiers: "onSetIdentifiers", + onMakePrecallTest: "onMakePrecallTest" + }, G = { + onServicesFinished: "onServicesFinished" + }, H = function(a) { + function b() { + f(this, b); + var a = g(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, E.Created)); + return o.log("FSM:", a.getState()), a.fire(F.onStart), a.run(), i(), a; + } + return h(b, a), k(b, [ { + key: "proceed", + value: function(a, b) { + switch (this.getState()) { + case E.Created: + switch (a) { + case F.onStart: + this.onStart.apply(this, e(b)); + break; + + case F.onInitialize: + this.setState(E.Initializing), o.log("FSM:", this.getState()), this.onInitialize.apply(this, e(b)); + break; + + case F.onOn: + this.onOn.apply(this, e(b)); + } + break; + + case E.Initializing: + switch (a) { + case G.onServicesFinished: + this.onServicesFinished() && (this.setState(E.Idle), o.log("FSM:", this.getState())); + break; + + case F.onAddNewFabric: + this.onAddNewFabric.apply(this, e(b)); + break; + + case F.onSendFabricEvent: + this.onSendFabricEvent.apply(this, e(b)); + break; + + case F.onReportError: + this.onReportError.apply(this, e(b)); + break; + + case F.onAssociateMstWithUserID: + this.onAssociateMstWithUserID.apply(this, e(b)); + break; + + case F.onSendUserFeedback: + this.onSendUserFeedback.apply(this, e(b)); + break; + + case F.onAttachWifiStatsHandler: + this.onAttachWifiStatsHandler.apply(this, e(b)); + break; + + case F.onOn: + this.onOn.apply(this, e(b)); + break; + + case F.onMakePrecallTest: + this.onMakePrecallTest(); + break; + + case F.onSetIdentifiers: + this.onSetIdentifiers.apply(this, e(b)); + } + break; + + case E.Idle: + case E.Run: + switch (a) { + case F.onAddNewFabric: + this.onAddNewFabric.apply(this, e(b)); + break; + + case F.onSendFabricEvent: + this.onSendFabricEvent.apply(this, e(b)); + break; + + case F.onReportError: + this.onReportError.apply(this, e(b)); + break; + + case F.onAssociateMstWithUserID: + this.onAssociateMstWithUserID.apply(this, e(b)); + break; + + case F.onSendUserFeedback: + this.onSendUserFeedback.apply(this, e(b)); + break; + + case F.onAttachWifiStatsHandler: + this.onAttachWifiStatsHandler.apply(this, e(b)); + break; + + case F.onOn: + this.onOn.apply(this, e(b)); + break; + + case F.onMakePrecallTest: + this.onMakePrecallTest(); + break; + + case F.onSetIdentifiers: + this.onSetIdentifiers.apply(this, e(b)); + } + } + } + }, { + key: "onStart", + value: function() { + m.Registry.getEndpoint().setup(), this.authenticator = m.Registry.getAuthenticator(), + this.configservicewrapper = m.Registry.getConfigServiceWrapper(), this.precalltest = m.Registry.getPreCallTest(), + this.precalltestIds = []; + var a = m.Registry.getStatsAdapter(), b = m.Registry.getStatsParser(), c = m.Registry.getStatsMonitor(), d = m.Registry.getStatsTransmitter(), e = m.Registry.getStatsAssembler(); + a.connect(z.StatsAdapterIO.RawStatsOut, b.getPort(A.StatsParserIO.RawStatsIn)), + b.connect(A.StatsParserIO.PcStatsTupleOut, c.getPort(B.StatsMonitorIO.PcStatsTupleIn)), + c.connect(B.StatsMonitorIO.StatsTupleOut, e.getPort(D.StatsAssemblerIO.StatsTupleIn)), + e.connect(D.StatsAssemblerIO.CallstatsOut, d.getPort(C.StatsTransmitterIO.CallstatsIn)), + a.connect(z.StatsAdapterIO.UnprocessedOut, d.getPort(C.StatsTransmitterIO.UnprocessedIn)); + } + }, { + key: "setupConnection", + value: function() { + var a = this; + this.connectionManager = m.Registry.getConnectionManager(), this.connectionManager.setupCollectorConnection(m.Registry.getCredentials().getTransportType()), + this.connectionManager.setup().then(function() { + o.log("Connected to connectionManager"), a.fire(G.onServicesFinished), a.run(); + }).catch(function(a) { + return o.log("Could not connect to connectionManager", a); + }); + } + }, { + key: "setup", + value: function() { + var a = this; + this.clocksync = m.Registry.getClockSync(), this.clocksync.initiate().then(function() { + o.log("Clocksync completed"), a.fire(G.onServicesFinished), a.run(); + }).catch(function(a) { + return o.log("Could not finish ClockSync", a); + }); + } + }, { + key: "onInitialize", + value: function(a, b, c, d, e, f) { + var g = this, h = m.Registry.getCredentials(); + if (h.setAppId(a), h.setUserId(b), m.Registry.getCallbacks().set(u.callbackFunctions.stats, e), + this.doPrecalltest = !0, m.Registry.getGenericEventHandler().sendEvent(u.logEvents.log, { + msg: "callstats initialize in progress" + }), f) { + if (!0 === f.disableBeforeUnloadHandler && this.setBeforeUnloadHandler(), f.applicationVersion) { + m.Registry.getEndpoint().setAppVersion(f.applicationVersion); + } + f.transportType && w.setTransportType(f.transportType), f.disablePrecalltest && (this.doPrecalltest = !1); + } + this.setup(), this.authenticator.initiate(c, d).then(function(a) { + o.log("Authentication complete"), g.setupConnection(); + var b = m.Registry.getCredentials().getStatsSubmissionInterval(); + m.Registry.getStatsMonitor().setIntervals(b, b), g.fire(G.onServicesFinished), g.run(); + var c = g.authenticator.getIceServers(); + c && g.doPrecalltest && g.precalltest.start(c, g.precalltestCallback.bind(g)), g.configservicewrapper.initiateInternalConfig().then(function() { + o.log("ConfigService internal config:", g.configservicewrapper.getInternalConfig()), + g.fire(G.onServicesFinished), g.run(); + }, function(a) { + return o.log(a); + }), g.configservicewrapper.initiateAppConfig().then(function() { + var a = m.Registry.getCallbacks().get(u.callbackFunctions.defaultConfig), b = g.configservicewrapper.getAppDefaultConfig(); + a && b && a(b); + var c = m.Registry.getCallbacks().get(u.callbackFunctions.recommendedConfig), d = g.configservicewrapper.getAppRecommendedConfig(); + c && d && c(d), g.fire(G.onServicesFinished), g.run(); + }, function(a) { + return o.log(a); + }); + }, function(a) { + o.log(a); + }), this.genericevent = m.Registry.getGenericEventHandler(), this.genericevent.sendEvent(u.logEvents.log, { + msg: "callstats initialize in progress" + }); + } + }, { + key: "precalltestCallback", + value: function(a, b) { + var c = m.Registry.getCallbacks().get(u.callbackFunctions.preCallTestResults); + if (c) { + if (b) { + var d = { + msg: "precalltest error: " + b + }; + return o.warn("backendlog", d), this.genericevent.sendEvent(u.logEvents.log, d), + void c(u.callstatsAPIReturnStatus.failure, null); + } + var e = y.getPublicPrecalltestResults(a); + c(u.callstatsAPIReturnStatus.success, e); + } + a && (this.precalltestIds.push(a.id), a.tests && a.tests.ice && ("" === a.tests.ice.turnIpAddress && delete a.tests.ice.turnIpAddress, + "" === a.tests.ice.turnIpVersion && delete a.tests.ice.turnIpVersion, "" === a.tests.ice.turnTransport && delete a.tests.ice.turnTransport), + o.log("sending preCallTest results", a), m.Registry.getEventMessageBuilder().make(u.precalltestEvents.results, null, null, { + results: a + })); + } + }, { + key: "setBeforeUnloadHandler", + value: function() { + window && window.addEventListener && (o.log("setBeforeUnloadHandler"), window.addEventListener("beforeunload", function(a) { + return m.Registry.getConferenceManager().conferenceMap.forEach(function(a, b) { + a && a.getPeerConnectionManager().pcHandlers.forEach(function(a, b) { + m.Registry.getEventMessageBuilder().make(u.internalFabricEvent.userLeft, a.getConferenceId(), a.getPeerConnection()); + }); + }), "Are you sure you want to close the call?"; + })); + } + }, { + key: "onServicesFinished", + value: function() { + return !!(this.connectionManager && this.connectionManager.isReady() && this.clocksync.isCompleted() && this.authenticator.isCompleted()) && (m.Registry.getTransmissionManager().trySend(), + !0); + } + }, { + key: "onAddNewFabric", + value: function(a, b, c, d, e, f, g) { + o.warn("FSM onAddNewFabric"), m.Registry.getConferenceManager().add(d, m.Registry.getCredentials()); + var h = m.Registry.getConferenceManager().get(d); + h.getPeerConnectionManager().addPcHandler(a, b, c, d, e, f, g); + var i = { + endpointInfo: m.Registry.getEndpoint().serialize() + }; + m.Registry.getCredentials().getUserIdObject() && (i.localUserIDObject = m.Registry.getCredentials().getUserIdObject()), + h.userJoinedSent || (m.Registry.getEventMessageBuilder().make(u.internalFabricEvent.userJoined, d, a, i), + h.userJoinedSent = !0, m.Registry.getCredentials().getTransportType() === u.transportType.rest && i.localUserIDObject && i.localUserIDObject.userName && m.Registry.getEventMessageBuilder().make(u.internalFabricEvent.userDetails, d, a, { + userName: String(i.localUserIDObject.userName) + })); + var j = this.precalltestIds; + this.precalltestIds = []; + var k = this.precalltest.getId(); + k && j.push(k), j.length > 0 && m.Registry.getEventMessageBuilder().make(u.precalltestEvents.associate, d, a, { + ids: j + }); + } + }, { + key: "onSendFabricEvent", + value: function(a, b, c, d) { + o.warn("FSM onSendFabricEvent"); + var e = {}; + if (d && (e = d), b === u.fabricEvent.activeDeviceList) { + e = { + mediaDeviceList: q.normalizeMediaDeviceList(d.deviceList) + }; + } + m.Registry.getEventMessageBuilder().make(b, c, a, e); + var f = m.Registry.getConferenceManager().get(c); + if (f) { + var g = f.getPeerConnectionManager().getPcHandler(a); + b !== u.fabricEvent.fabricTerminated && b !== u.internalFabricEvent.fabricSetupFailed || (g.stopUserAliveHandler(), + g.setPcState(u.fabricState.terminated), g.stopStatsPolling()), b === u.fabricEvent.fabricHold && (g.setPcState(u.fabricState.hold), + g.stopStatsPolling()), b === u.fabricEvent.fabricResume && (g.setPcState(u.fabricState.established), + g.startStatsPolling()); + } + } + }, { + key: "onReportError", + value: function(a, b, c, d, e, f) { + o.warn("FSM onReportError"); + var g = { + failureDelay: 0, + reason: this.callFailureClassifier(c), + function: c, + magicKey: m.Registry.getEndpoint().getMagicKey(), + endpoint: m.Registry.getEndpoint().serialize(), + level: "debug" + }; + if (d) { + var h = this.formatDomError(d); + g.message = h.message, g.messageType = h.messageType, g.name = d.name, g.stack = d.stack; + } + if (a) { + var i = m.Registry.getConferenceManager().get(b), j = void 0; + if (i && (j = i.getPeerConnectionManager().getPcHandler(a)), !j) return void o.error("onReportError: No handler found for given PeerConnection!"); + if (g.failureDelay = s.getCurrent() - j.getStartTime(), g.fabricState = j.getPcState(), + g.iceConnectionState = j.getIceConnectionState(), (e || f || a && "closed" !== a.signalingState) && m.Registry.getCredentials().getCollectSDP() && c === u.fabricEvent.fabricSetupFailed) { + var k = {}; + k.localSDP = this.pickSDP(a, e, "localDescription"), k.remoteSDP = this.pickSDP(a, f, "remoteDescription"), + m.Registry.getEventMessageBuilder().make(u.callstatsChannels.sdpSubmission, b, a, k); + } + } + c === u.webRTCFunctions.applicationLog || c === u.webRTCFunctions.applicationError ? m.Registry.getEventMessageBuilder().make(u.fabricEvent.applicationErrorLog, b, a, g) : m.Registry.getEventMessageBuilder().make(u.fabricEvent.fabricSetupFailed, b, a, g); + } + }, { + key: "onAssociateMstWithUserID", + value: function(a, b, c, d, e, f) { + var g = m.Registry.getConferenceManager().get(c); + if (g) { + var h = g.getPeerConnectionManager().getPcHandler(a); + "string" != typeof d && (d += ""), h.updateSSRCInfo(d, b, e, f); + } + } + }, { + key: "onAttachWifiStatsHandler", + value: function(a) { + m.Registry.getWifiStatsExecutor().setGetWifiStatsMethod(a); + } + }, { + key: "onSetProxyConfig", + value: function(a) { + a.collectorURL && w.setBaseUrl(a.collectorURL), a.authServiceURL && w.setAuthServiceUrl(a.authServiceURL), + a.csioInternalAPIURL && w.setQmodelThresholdsAPIUrl(a.csioInternalAPIURL), a.wsURL && w.setWsUrl(a.wsURL), + a.restEventUrl && w.setRestEventUrl(a.restEventURL), a.restStatsUrl && w.setRestStatsUrl(a.restStatsURL), + this.setup(); + } + }, { + key: "onSendUserFeedback", + value: function(a, b, c) { + var d = { + feedback: { + overallRating: b.overall + } + }; + b.video && (d.feedback.videoQualityRating = b.video), b.audio && (d.feedback.audioQualityRating = b.audio), + b.comment && (d.feedback.comments = b.comment), m.Registry.getEventMessageBuilder().make(u.callstatsChannels.userFeedback, a, null, d); + } + }, { + key: "onOn", + value: function(a, b) { + m.Registry.getCallbacks().set(a, b); + } + }, { + key: "onSetIdentifiers", + value: function(a, b) { + if (a.conferenceID && (m.Registry.getConferenceManager().updateConferenceId(a.conferenceID), + m.Registry.getTransmissionManager().updateConferenceId(a.conferenceID), m.Registry.getTransmissionManager().trySend()), + a.remoteUserID && b) { + var c = m.Registry.getConferenceManager().getConferenceForPc(b); + if (!c) return void o.log("onSetIdentifiers conference not found"); + var d = c.getPeerConnectionManager().getPcHandler(b); + if (!d) return void o.log("pcHandler not found"); + d.updateRemoteId(a.remoteUserID), m.Registry.getTransmissionManager().trySend(); + } + } + }, { + key: "onMakePrecallTest", + value: function() { + var a = this, b = this.authenticator.getIceServers(); + a.precalltest.start(b, a.precalltestCallback.bind(a)); + } + }, { + key: "callFailureClassifier", + value: function(a) { + var b = void 0; + return u.webRTCFunctions.hasOwnProperty(a) ? a === u.webRTCFunctions.createOffer || a === u.webRTCFunctions.createAnswer || a === u.webRTCFunctions.setRemoteDescription ? b = u.callFailureReasons.negotiationFailure : a === u.webRTCFunctions.setLocalDescription ? b = u.callFailureReasons.sdpError : a === u.webRTCFunctions.addIceCandidate ? b = u.callFailureReasons.sdpError : a === u.webRTCFunctions.getUserMedia ? b = u.callFailureReasons.mediaConfigError : a === u.webRTCFunctions.iceConnectionFailure ? b = u.callFailureReasons.iceFailure : a === u.webRTCFunctions.signalingError ? b = u.callFailureReasons.signalingError : (a === u.webRTCFunctions.applicationLog || u.webRTCFunctions.applicationError) && (b = u.callFailureReasons.applicationLog) : b = u.callFailureReasons.invalidWebRTCFunctionName, + b; + } + }, { + key: "formatDomError", + value: function(a) { + var b = {}, c = {}; + a && (window.DOMException && a instanceof window.DOMException ? (c.message = a.message, + c.name = a.name, b.messageType = "domError") : "object" === (void 0 === a ? "undefined" : j(a)) ? (a.message && (c.message = a.message), + a.name && (c.name = a.name), a.constraintName && (c.name = a.constraintName), a.stack && (c.stack = a.stack), + b.messageType = "json") : (c = a, b.messageType = "text")); + var d = this.truncateLog(c); + return "object" === (void 0 === d ? "undefined" : j(d)) ? b.message = JSON.stringify(d) : b.message = d, + b; + } + }, { + key: "pickSDP", + value: function(a, b, c) { + return b || (a && a[c] ? a[c].sdp : ""); + } + }, { + key: "truncateString", + value: function(a) { + return a.length > 2e4 && (o.log("Log exceeds 20kb, It will be truncated"), a = a.substring(0, 2e4)), + a; + } + }, { + key: "truncateLog", + value: function(a) { + return a ? ("string" == typeof a ? a = this.truncateString(a) : "object" === (void 0 === a ? "undefined" : j(a)) && a.message && (a.message = this.truncateString(a.message)), + a) : a; + } + } ]), b; + }(l.StateMachine); + c.MainFSM = H; + }, { + "../config/constants": 32, + "../config/settings": 33, + "../statspipeline/statsadapter": 68, + "../statspipeline/statsassembler": 69, + "../statspipeline/statsmonitor": 71, + "../statspipeline/statsparser": 72, + "../statspipeline/statstransmitter": 73, + "../utility/csiologger": 87, + "../utility/registry": 94, + "../utility/timestamps": 98, + "../utility/utils": 100, + "./statemachine": 36, + "./utility": 37 + } ], + 35: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a(b, c) { + d(this, a), this.type = b, this.args = void 0 !== c ? c : null; + } + return e(a, [ { + key: "getType", + value: function() { + return this.type; + } + }, { + key: "getArgs", + value: function() { + return this.args; + } + } ]), a; + }(); + c.ProgramEvent = f; + }, {} ], + 36: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.StateMachine = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./programevent"), g = a("../utility/csiologger"), h = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(g), i = function() { + function a(b) { + d(this, a), this.events = [], this.state = b; + } + return e(a, [ { + key: "fire", + value: function(a) { + for (var b = arguments.length, c = Array(b > 1 ? b - 1 : 0), d = 1; d < b; d++) c[d - 1] = arguments[d]; + var e = new f.ProgramEvent(a, c); + this.events.push(e); + } + }, { + key: "proceed", + value: function(a, b) { + h.warn("You need to overwrite the proceed function inan extended StateMachine"); + } + }, { + key: "setState", + value: function(a) { + this.state = a; + } + }, { + key: "getState", + value: function() { + return this.state; + } + }, { + key: "run", + value: function() { + if (!(this.events.length < 1)) { + var a = this.events.shift(); + this.proceed(a.getType(), a.getArgs()); + } + } + } ]), a; + }(); + c.StateMachine = i; + }, { + "../utility/csiologger": 87, + "./programevent": 35 + } ], + 37: [ function(a, b, c) { + "use strict"; + function d(a) { + var b = { + mediaConnectivity: !1, + throughput: null, + fractionalLoss: null, + rtt: null + }; + return a && a.tests ? (a.tests.rtt && (b.rtt = a.tests.rtt.median, b.mediaConnectivity = !0), + a.tests.throughput && (b.throughput = a.tests.throughput.average, b.fractionalLoss = Math.max(a.tests.throughput.fractionLostBytes, 0), + b.mediaConnectivity = !0), a.tests.ice && (a.tests.ice.relayTcpSuccess || a.tests.ice.relayTlsSuccess || a.tests.ice.relayUdpSuccess) && (b.mediaConnectivity = !0), + b) : b; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.getPublicPrecalltestResults = d; + }, {} ], + 38: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.GetStatsHandler = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../config/constants"), h = d(g), i = a("../statspipeline/statsadapter"), j = a("../utility/registry"), k = a("../utility/rttregistry"), l = a("../utility/csiologger"), m = d(l), n = function() { + function a(b, c, d, f, g) { + e(this, a), this.pc = b, this.interval = d, this.codeBase = f, this.browserName = g, + this.getStatsTimer = null, this.isPromiseBased = !0, this.pcHash = c, this.genericevent = j.Registry.getGenericEventHandler(); + } + return f(a, [ { + key: "startStatsPolling", + value: function() { + var a = this; + a.getStatsTimer || (m.log("startStatsPolling for ", a.pcHash), this.getStatsTimer = setInterval(function() { + a.csioGetStats(a.statsHandler, a.pcHash); + }, a.interval)); + } + }, { + key: "stopStatsPolling", + value: function() { + this.getStatsTimer && (clearInterval(this.getStatsTimer), this.getStatsTimer = null); + } + }, { + key: "csioGetStats", + value: function(a, b) { + var c = h.codeBaseType.firefox, d = h.codeBaseType.chrome, e = h.codeBaseType.edge, f = h.browserName.safari; + if (this.pc) try { + this.isTemaSys() ? this.getStatsTemasys(a, b) : this.codeBase === c ? this.getStatsFirefox(a, b) : this.browserName === f ? this.getStatsSafari(a, b) : this.codeBase === d ? this.getStatsChrome(a, b) : this.codeBase === e && this.getStatsEdge(a, b); + } catch (a) { + m.log("csioGetStats: Error ", a); + } + } + }, { + key: "getStatsTemasys", + value: function(a, b) { + this.pc.getStats(null, function(c) { + a(c, b); + }, function(a) { + m("getStatsTemasys error", a); + }); + } + }, { + key: "getStatsFirefox", + value: function(a, b) { + var c = this, d = this.pc; + if (!c.isPromiseBased) return void d.getStats(null, function(c) { + a(c, b); + }); + try { + d.getStats().then(function(c) { + a(c, b); + }).catch(function(e) { + c.isPromiseBased = !1, d.getStats(null, function(c) { + a(c, b); + }); + }); + } catch (e) { + c.isPromiseBased = !1, c.genericevent.sendEvent(h.logEvents.getStatsError, { + msg: "Firefox getStats reports error ", + error: e.message + ":" + e.stack + }), d.getStats(null, function(c) { + a(c, b); + }); + } + } + }, { + key: "getStatsChrome", + value: function(a, b) { + var c = this, d = c.pc; + if (window && window.csioReactNative) return void d.getStats(null, function(c) { + a(c, b); + }, function(a) { + c.genericevent.sendEvent(h.logEvents.getStatsError, { + msg: "react-native getStats reports error", + error: a.message + ":" + a.stack + }); + }); + if (!c.isPromiseBased) return void d.getStats(function(c) { + a(c, b); + }); + try { + d.getStats().then(function(c) { + (0, k.getRTTRegistry)().update(d), a(c, b); + }).catch(function(e) { + m.log("Chrome getStats Error ", e), c.isPromiseBased = !1, c.genericevent.sendEvent(h.logEvents.getStatsError, { + msg: "Chrome getStats reports error", + error: e.message + ":" + e.stack + }), d.getStats(function(c) { + a(c, b); + }); + }); + } catch (e) { + c.isPromiseBased = !1, c.genericevent.sendEvent(h.logEvents.getStatsError, { + msg: "Chrome getStats reports error", + error: e.message + ":" + e.stack + }), d.getStats(function(c) { + a(c, b); + }); + } + } + }, { + key: "getStatsEdge", + value: function(a, b) { + var c = this; + c.pc.getStats().then(function(c) { + a(c, b); + }).catch(function(d) { + a({}, b), d ? c.genericevent.sendEvent(h.logEvents.getStatsError, { + msg: "Edge getStats reports error", + error: d.message + ":" + d.stack + }) : c.genericevent.sendEvent(h.logEvents.getStatsError, { + msg: "Edge getStats reports error" + }); + }); + } + }, { + key: "getStatsSafari", + value: function(a, b) { + var c = this; + c.pc.getStats().then(function(c) { + a(c, b); + }).catch(function(a) { + c.genericevent.sendEvent(h.logEvents.getStatsError, { + msg: "Safari getStats reports error", + error: a.message + ":" + a.stack + }); + }); + } + }, { + key: "statsHandler", + value: function(a, b) { + var c = j.Registry.getStatsAdapter(); + if (a && c) try { + c.transmit(i.StatsAdapterIO.RawStatsIn, a, b); + } catch (a) { + m.log("statsHandler 123: Error ", a), j.Registry.getGenericEventHandler().sendEvent(h.logEvents.error, { + msg: "statsHandler: Error", + error: a.message + ":" + a.stack + }); + } + } + }, { + key: "iceCandidatesHandler", + value: function(a, b) { + var c = j.Registry.getStatsAdapter(), d = void 0; + d = c.getIceCandidates(a), b(d); + } + }, { + key: "getIceCandidates", + value: function() { + var a = this; + return new Promise(function(b, c) { + a.csioGetStats(a.iceCandidatesHandler, function(a) { + b(a); + }); + }); + } + }, { + key: "isTemaSys", + value: function() { + return !!(window && window.AdapterJS && window.AdapterJS.WebRTCPlugin && window.AdapterJS.WebRTCPlugin.plugin); + } + } ]), a; + }(); + c.GetStatsHandler = n; + }, { + "../config/constants": 32, + "../statspipeline/statsadapter": 68, + "../utility/csiologger": 87, + "../utility/registry": 94, + "../utility/rttregistry": 95 + } ], + 39: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.PcCallbackHandler = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../config/constants"), h = d(g), i = a("../utility/registry"), j = a("../utility/timestamps"), k = d(j), l = a("../config/callstatserrors"), m = d(l), n = a("../utility/csiologger"), o = d(n), p = function() { + function a(b, c, d, f, g, j) { + var l = this; + e(this, a), c && (this.conferenceId = b, this.pc = c, this.getStatsHandler = d, + this.userAlive = f, this.callback = j, this.remoteId = g, this.clocksync = i.Registry.getClockSync(), + this.emb = i.Registry.getEventMessageBuilder(), this.precalltest = i.Registry.getPreCallTest(), + this.genericevent = i.Registry.getGenericEventHandler(), this.iceCandidates = [], + this.iceConnectionState = c.iceConnectionState, this.iceGatheringState = c.iceGatheringState, + this.signalingState = c.signalingState, this.oldIceConnectionState = "", this.oldIceGatheringState = "", + this.iceConnectionStateTS = "", this.negotiationNeeded = 0, this.pcState = h.fabricState.initializing, + this.disruptedTS = 0, this.startTime = k.getCurrent(), this.established = !1, this.activeIceCandidatePair = null, + this.prevActiveIceCandidatePair = null, this.localIceCandidates = [], this.remoteIceCandidates = [], + this.iceCandidatePairs = [], this.iceConnectivityDelay = 0, this.iceGatheringDelay = 0, + this.fabricSetupSent = !1, this.pc && this.pc.addEventListener ? (this.pc.addEventListener("icecandidate", this.iceCandidateCallback.bind(this), !1), + this.pc.addEventListener("iceconnectionstatechange", this.iceConnectionStateChangeCallback.bind(this), !1), + this.pc.addEventListener("signalingstatechange", this.pcSignalingStateChangeCallback.bind(this), !1), + this.pc.addEventListener("negotiationneeded", this.pcNegotiationNeededCallback.bind(this), !1)) : this.pc && this.pc.attachEvent ? (o.info("attachEvent"), + this.pc.attachEvent("onicecandidate", this.iceCandidateCallback.bind(this)), this.pc.attachEvent("oniceconnectionstatechange", this.iceConnectionStateChangeCallback.bind(this)), + this.pc.attachEvent("onsignalingstatechange", this.pcSignalingStateChangeCallback.bind(this)), + this.pc.attachEvent("onnegotiationneeded", this.pcNegotiationNeededCallback.bind(this))) : o.error("callstats cannot monitor or collect stats"), + !c || "connected" !== c.iceConnectionState && "completed" !== c.iceConnectionState || (this.pcState = h.fabricState.established, + this.getStatsHandler.getIceCandidates().then(function(a) { + l.localIceCandidates = a.localIceCandidates, l.remoteIceCandidates = a.remoteIceCandidates, + l.iceCandidatePairs = a.iceCandidatePairs, l.prevActiveIceCandidatePair = l.activeIceCandidatePair, + l.activeIceCandidatePair = l.getActiveIceCandidatePair(), l.sendfabricSetup(), l.startStatsPolling(); + }))); + } + return f(a, [ { + key: "iceCandidateCallback", + value: function(a) { + if (a && a.candidate) { + var b = a.candidate.candidate.split(" "); + if ("0" !== b[4] && "0" !== b[5]) { + var c = -1 !== b[4].indexOf(":"), d = "1" === b[1] ? "rtp" : "rtcp", e = { + transport: b[2], + protocol: d, + typePreference: b[3], + address: c ? "[" + b[4] + "]:" + b[5] : b[4] + ":" + b[5], + type: b[7], + media: a.candidate.sdpMid + }; + -1 === this.iceCandidates.indexOf(e) && (this.iceCandidates.push(e), o.warn("CALLBACK: ICE candidate", e)); + } + } + } + }, { + key: "iceConnectionStateChangeCallback", + value: function(a) { + var b = this; + if (a) { + o.log("pc states ", this.pc.iceGatheringState, this.pc.iceConnectionState), this.iceConnectionStateTS = this.clocksync.getSynchronizedTimestamp(), + this.handleIceGatheringState(), this.handleIceConnectionState(), o.log("states ", this.iceGatheringState, this.iceConnectionState), + "complete" === this.iceGatheringState && "checking" === this.iceConnectionState && this.handleIceChecking(); + var c = { + prevIceConnectionState: this.oldIceConnectionState, + currIceConnectionState: this.iceConnectionState + }, d = this.iceConnectionState; + this.getStatsHandler.getIceCandidates().then(function(a) { + b.localIceCandidates = a.localIceCandidates, b.remoteIceCandidates = a.remoteIceCandidates, + b.iceCandidatePairs = a.iceCandidatePairs, b.prevActiveIceCandidatePair = b.activeIceCandidatePair, + b.activeIceCandidatePair = b.getActiveIceCandidatePair(), "connected" === d || "completed" === d ? b.handleIceConnectedOrCompleted(c) : "failed" === d ? b.handleIceFailed(c) : "disconnected" === d ? b.handleIceDisconnected(c) : "closed" === d ? b.handleIceClosed(c) : "new" === d && b.handleIceRestart(c); + }); + } + } + }, { + key: "sendFabricStateChange", + value: function(a) { + this.emb.make(h.internalFabricEvent.fabricStateChange, this.conferenceId, this.pc, a); + } + }, { + key: "handleIceConnectionState", + value: function() { + this.oldIceConnectionState = this.iceConnectionState, this.iceConnectionState = this.pc.iceConnectionState, + o.warn("CALLBACK: ICE connection state change", this.oldIceConnectionState, "->", this.iceConnectionState); + var a = { + changedState: h.fabricStateChangeType.iceConnectionState, + prevState: this.oldIceConnectionState, + newState: this.iceConnectionState + }; + this.sendFabricStateChange(a); + } + }, { + key: "handleIceGatheringState", + value: function() { + if (this.iceGatheringState !== this.pc.iceGatheringState) { + "complete" === this.pc.iceGatheringState && (this.iceGatheringDelay = k.getCurrent() - this.startTime), + this.oldIceGatheringState = this.iceGatheringState, this.iceGatheringState = this.pc.iceGatheringState, + o.warn("CALLBACK: ICE gathering state change", this.oldIceGatheringState, "->", this.iceGatheringState); + var a = { + changedState: h.fabricStateChangeType.iceGatheringState, + prevState: this.oldIceGatheringState, + newState: this.iceGatheringState + }; + this.sendFabricStateChange(a); + } + } + }, { + key: "handleIceChecking", + value: function() { + if ("disconnected" === this.oldIceConnectionState && this.pcState === h.fabricState.checkingDisrupted) { + var a = { + prevIceConnectionState: this.oldIceConnectionState, + currIceConnectionState: this.iceConnectionState, + disruptionDelay: k.getCurrent() - this.disruptedTS + }; + this.emb.make(h.internalFabricEvent.iceConnectionDisruptionEnd, this.conferenceId, this.pc, a); + } + } + }, { + key: "handleIceConnectedOrCompleted", + value: function(a) { + var b = k.getCurrent(); + this.pcState === h.fabricState.disrupted && (a.prevIceCandidatePair = this.prevActiveIceCandidatePair, + a.currIceCandidatePair = this.activeIceCandidatePair, a.disruptionDelay = b - this.disruptedTS, + this.emb.make(h.internalFabricEvent.iceDisruptionEnd, this.conferenceId, this.pc, a)), + this.iceConnectivityDelay = b - this.startTime, this.established = !0, this.pcState = h.fabricState.established, + this.sendfabricSetup(), this.startStatsPolling(); + } + }, { + key: "sendfabricSetup", + value: function() { + if (this.fabricSetupSent) return void o.log("fabricSetup has been sent already"); + var a = { + delay: k.getCurrent() - this.startTime, + iceGatheringDelay: this.iceGatheringDelay, + iceConnectivityDelay: this.iceConnectivityDelay, + localIceCandidates: this.localIceCandidates, + remoteIceCandidates: this.remoteIceCandidates, + iceCandidatePairs: this.iceCandidatePairs + }; + this.fabricSetupSent = !0; + var b = void 0; + if (this.conferenceId) { + b = i.Registry.getConferenceManager().get(this.conferenceId).getPeerConnectionManager().getPcHandler(this.pc), + a.remoteEndpointType = b.getRemoteEndpointType(), a.fabricTransmissionDirection = b.getFabricTransmissionDirection(); + } + this.pcState = h.fabricState.established, this.emb.make(h.internalFabricEvent.fabricSetup, this.conferenceId, this.pc, a); + } + }, { + key: "isFabricSetupSent", + value: function() { + return this.fabricSetupSent; + } + }, { + key: "startStatsPolling", + value: function() { + this.getStatsHandler.startStatsPolling(); + } + }, { + key: "stopStatsPolling", + value: function() { + this.getStatsHandler.stopStatsPolling(); + } + }, { + key: "handleIceFailed", + value: function(a) { + a.currIceCandidatePair = this.activeIceCandidatePair, a.failureDelay = k.getCurrent() - this.startTime, + a.delay = k.getCurrent() - this.startTime, this.pcState = h.fabricState.failed, + "checking" === this.oldIceConnectionState ? this.sendIceFailed(a) : "completed" === this.oldIceConnectionState || "connected" === this.oldIceConnectionState ? this.emb.make(h.internalFabricEvent.fabricDropped, this.conferenceId, this.pc, a) : "disconnected" === this.oldIceConnectionState && this.established ? this.emb.make(h.internalFabricEvent.fabricDropped, this.conferenceId, this.pc, a) : "disconnected" === this.oldIceConnectionState && this.sendIceFailed(a); + } + }, { + key: "getActiveIceCandidatePair", + value: function() { + var a = null, b = this.iceCandidatePairs; + if (b && b.length > 0) { + var c = b.filter(function(a) { + return "true" === a.selected || "true" === a.googActiveConnection || !0 === a.selected || !0 === a.googActiveConnection; + }); + c.length > 0 && (a = c[0]); + } + return a; + } + }, { + key: "sendIceFailed", + value: function(a) { + a.localIceCandidates = this.localIceCandidates, a.remoteIceCandidates = this.remoteIceCandidates, + a.iceCandidatePairs = this.iceCandidatePairs, o.log("sending icefailed ", a), this.emb.make(h.internalFabricEvent.iceFailed, this.conferenceId, this.pc, a); + } + }, { + key: "sendFabricTransportSwitch", + value: function(a) { + var b = this, c = {}; + c.prevIceCandidatePair = b.activeIceCandidatePair, c.relayType = a, c.currIceConnectionState = b.iceConnectionState, + c.prevIceConnectionState = b.oldIceConnectionState, c.switchDelay = null, b.getStatsHandler.getIceCandidates().then(function(a) { + b.localIceCandidates = a.localIceCandidates, b.remoteIceCandidates = a.remoteIceCandidates, + b.iceCandidatePairs = a.iceCandidatePairs, b.activeIceCandidatePair = b.getActiveIceCandidatePair(), + c.currIceCandidatePair = b.activeIceCandidatePair, c.localIceCandidates = b.localIceCandidates, + c.remoteIceCandidates = b.remoteIceCandidates, o.log("sending fabric transport switch ", c), + "completed" !== c.currIceConnectionState && "connected" !== c.currIceConnectionState || "completed" !== c.prevIceConnectionState && "connected" !== c.prevIceConnectionState || b.emb.make(h.internalFabricEvent.fabricTransportSwitch, b.conferenceId, b.pc, c); + }); + } + }, { + key: "handleIceDisconnected", + value: function(a) { + var b = k.getCurrent(); + this.startTime = b, a.prevIceConnectionStateTs = this.iceConnectionStateTS, a.currIceCandidatePair = this.activeIceCandidatePair, + "connected" === this.oldIceConnectionState || "completed" === this.oldIceConnectionState ? (this.pcState = h.fabricState.disrupted, + this.disruptedTS = b, this.emb.make(h.internalFabricEvent.iceDisruptionStart, this.conferenceId, this.pc, a), + this.callback && this.callback(m.csError.appConnectivityError, "Connectivity check for PC object to " + this.remoteId + " failed.")) : "checking" === this.oldIceConnectionState && (this.pcState = h.fabricState.checkingDisrupted, + this.disruptedTS = b, this.emb.make(h.internalFabricEvent.iceConnectionDisruptionStart, this.conferenceId, this.pc, a), + this.callback && this.callback(m.csError.appConnectivityError, "Connectivity check for PC object to " + this.remoteId + " failed.")); + } + }, { + key: "handleIceClosed", + value: function(a) { + "new" === this.oldIceConnectionState || "checking" === this.oldIceConnectionState ? (a.failureDelay = k.getCurrent() - this.startTime, + a.localIceCandidates = this.localIceCandidates, a.remoteIceCandidates = this.remoteIceCandidates, + a.iceCandidatePairs = this.iceCandidatePairs, this.emb.make(h.internalFabricEvent.iceAborted, this.conferenceId, this.pc, a)) : (a.currIceCandidatePair = this.activeIceCandidatePair, + this.emb.make(h.internalFabricEvent.iceTerminated, this.conferenceId, this.pc, a), + this.stopStatsPolling()); + } + }, { + key: "handleIceRestart", + value: function(a) { + a.prevIceCandidatePair = this.prevActiveIceCandidatePair, "new" !== this.oldIceConnectionState && (o.log("iceRestarted sending"), + this.established = !1, this.emb.make(h.internalFabricEvent.iceRestarted, this.conferenceId, this.pc, a)); + } + }, { + key: "pcSignalingStateChangeCallback", + value: function(a) { + var b = this; + if (a) { + var c = this.signalingState; + this.signalingState = this.pc.signalingState, o.warn("CALLBACK: signaling state change", c, "->", this.signalingState); + var d = { + changedState: h.fabricStateChangeType.signalingState, + prevState: c, + newState: this.signalingState + }; + this.sendFabricStateChange(d), "have-remote-offer" !== this.signalingState && "stable" !== this.signalingState || (this.precalltest.callStarts(), + this.genericevent.sendEvent(h.logEvents.log, { + msg: "precalltest told to stop " + })), "closed" === this.signalingState && (this.emb.make(h.fabricEvent.fabricTerminated, this.conferenceId, this.pc), + this.userAlive.stop(), this.precalltest.callFinished(), this.stopStatsPolling(), + this.genericevent.sendEvent(h.logEvents.log, { + msg: "precalltest finished " + })), "have-local-offer" !== this.signalingState && "have-local-pranswer" !== this.signalingState && "stable" !== this.signalingState || (o.log(this.signalingState, ".. requesting sender config."), + i.Registry.getConfigServiceWrapper().initiateSenderConfig(this.pc).then(function() { + var a = i.Registry.getConfigServiceWrapper().getSenderConfig(); + o.log("Sender config:", a); + var c = h.callstatsChannels.senderConfiguration; + i.Registry.getEventMessageBuilder().make(c, b.conferenceId, b.pc, a); + }).catch(function(a) { + o.warn(a); + })); + } + } + }, { + key: "pcNegotiationNeededCallback", + value: function(a) { + a && (this.negotiationNeeded++, this.startTime = k.getCurrent(), o.warn("CALLBACK: negotiation needed", this.negotiationNeeded)); + } + } ]), a; + }(); + c.PcCallbackHandler = p; + }, { + "../config/callstatserrors": 31, + "../config/constants": 32, + "../utility/csiologger": 87, + "../utility/registry": 94, + "../utility/timestamps": 98 + } ], + 40: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.PeerConnectionHandler = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../utility/registry"), h = a("../peerconnection/pccallbackhandler"), i = a("../browserapi/devices"), j = a("./useralivehandler"), k = a("./getstatshandler"), l = a("../config/constants"), m = d(l), n = a("../utility/timestamps"), o = d(n), p = a("../utility/csiologger"), q = d(p), r = function() { + function a(b) { + e(this, a), this.pc = b.pc, this.remoteId = b.remoteId, this.fabricUsage = b.fabricUsage, + this.callback = b.callback, this.conferenceId = b.conferenceId, this.remoteEndpointType = b.remoteEndpointType, + this.fabricTransmissionDirection = b.fabricTransmissionDirection, this.clocksync = g.Registry.getClockSync(), + this.startTime = this.clocksync.getSynchronizedTimestamp(), this.credentials = g.Registry.getCredentials(), + this.pcHash = this.generatePcHash(), this.ssrcMap = new Map(), this.localSdp = null, + this.remoteSdp = null, this.transportInfo = null, this.userAliveHandler = new j.UserAliveHandler(this.conferenceId, this.pc), + this.userAliveHandler.start(), this.emb = g.Registry.getEventMessageBuilder(), this.devices = new i.Devices(this.conferenceId, this.pc); + var c = g.Registry.getEndpoint(); + this.getStatsHandler = new k.GetStatsHandler(this.pc, this.pcHash, 5e3, c.getCodeBase(), c.getBrowserName()), + this.pcCallbackHandler = new h.PcCallbackHandler(this.conferenceId, this.pc, this.getStatsHandler, this.userAliveHandler, this.remoteId, this.callback), + this.devices.collectConnected(), this.fabricTransmissionDirection || (this.fabricTransmissionDirection = "sendrecv"), + this.remoteEndpointType || (this.remoteEndpointType = "peer"); + } + return f(a, [ { + key: "getFabricTransmissionDirection", + value: function() { + return this.fabricTransmissionDirection; + } + }, { + key: "getRemoteEndpointType", + value: function() { + return this.remoteEndpointType; + } + }, { + key: "stopUserAliveHandler", + value: function() { + this.userAliveHandler.stop(); + } + }, { + key: "getPcState", + value: function() { + return this.pcCallbackHandler.pcState; + } + }, { + key: "stopStatsPolling", + value: function() { + this.getStatsHandler.stopStatsPolling(); + } + }, { + key: "startStatsPolling", + value: function() { + this.getStatsHandler.startStatsPolling(); + } + }, { + key: "setPcState", + value: function(a) { + a in m.fabricState ? this.pcCallbackHandler.pcState = a : q.error("setPcState: Invalid state"); + } + }, { + key: "getAppId", + value: function() { + return this.credentials.getAppId(); + } + }, { + key: "getLocalId", + value: function() { + return this.credentials.getUserId(); + } + }, { + key: "getConferenceId", + value: function() { + return this.conferenceId; + } + }, { + key: "getPeerConnection", + value: function() { + return this.pc; + } + }, { + key: "getRemoteId", + value: function() { + return this.remoteId; + } + }, { + key: "isFabricSetupSent", + value: function() { + return this.pcCallbackHandler.isFabricSetupSent(); + } + }, { + key: "getStartTime", + value: function() { + return this.startTime; + } + }, { + key: "getCallback", + value: function() { + return this.callback; + } + }, { + key: "getPcHash", + value: function() { + return this.pcHash; + } + }, { + key: "getIceCandidates", + value: function() { + return this.pcCallbackHandler ? this.pcCallbackHandler.iceCandidates : null; + } + }, { + key: "getIceConnectionState", + value: function() { + return this.pcCallbackHandler ? this.pcCallbackHandler.iceConnectionState : null; + } + }, { + key: "getNegotiationsNumber", + value: function() { + return this.pcCallbackHandler ? this.pcCallbackHandler.negotiationNeeded : 0; + } + }, { + key: "sendFabricTransportSwitch", + value: function(a) { + this.pcCallbackHandler && this.pcCallbackHandler.sendFabricTransportSwitch(a); + } + }, { + key: "getSdp", + value: function() { + return { + localSdp: this.localSdp, + remoteSdp: this.remoteSdp + }; + } + }, { + key: "setSdp", + value: function(a, b) { + this.localSdp = a, this.remoteSdp = b; + } + }, { + key: "generatePcHash", + value: function() { + var a = (Math.random() + 1).toString(36); + return a.substring(2, a.length); + } + }, { + key: "getTransportInfo", + value: function() { + return this.transportInfo; + } + }, { + key: "setTransportInfo", + value: function(a) { + this.transportInfo = a; + } + }, { + key: "updateSDP", + value: function(a) { + var b = this, c = this.pc.localDescription.sdp, d = this.pc.remoteDescription.sdp; + if (c && d && (c !== this.localSdp || d !== this.remoteSdp)) { + this.parseSDP(c, m.streamType.outbound), this.parseSDP(d, m.streamType.inbound); + var e = { + localSDP: c !== this.localSdp ? c : "", + remoteSDP: d !== this.remoteSdp ? d : "" + }; + "" === c && "" === remoteSDP || !g.Registry.getCredentials().getCollectSDP() || this.emb.make(m.internalFabricEvent.sdpSubmission, this.conferenceId, this.pc, e), + a && a.forEach(function(a) { + var c = String(a.data.ssrc), d = b.ssrcMap.get(c); + d || (d = {}), d.mediaType = a.data.mediaType, d.reportType = a.data.isRemote ? "remote" : "local", + d.ssrc = c, b.ssrcMap.set(c, d); + }); + var f = []; + this.ssrcMap.forEach(function(a, b) { + f.push(a); + }); + for (var h = { + ssrcData: f + }, i = 0; i < h.ssrcData.length; i += 1) { + h.ssrcData[i].userID = g.Registry.getCredentials().getUserId(); + } + this.emb.make(m.internalFabricEvent.ssrcMap, this.conferenceId, this.pc, h), this.setSdp(c, d); + } + } + }, { + key: "parseSDP", + value: function(a, b) { + var c = this, d = RegExp.prototype.test.bind(/^([a-z])=(.*)/), e = /^ssrc:(\d*) ([\w_]*):(.*)/, f = /^ssrc-group:SIM (\d*)/; + a.split(/(\r\n|\r|\n)/).filter(d).forEach(function(a) { + var d = a[0], g = a.slice(2); + if ("a" === d && e.test(g)) { + var h = g.match(e), i = h[1], j = h[2], k = h[3], l = c.ssrcMap.get(i); + if (l || (l = {}), l.ssrc = i, l[j] = k, l.localStartTime = o.getCurrent(), l.syncedStartTime = c.clocksync.getSynchronizedTimestamp(), + l.streamType = b, !f.test(g)) return void c.ssrcMap.set(i, l); + l.ssrcGroup = {}, l.ssrcGroup[b] = {}, l.ssrcGroup[b].simulcastGroup = g.match(/\d+/g), + c.ssrcMap.set(i, l); + } + }); + } + }, { + key: "getSSRCInfo", + value: function(a) { + return this.ssrcMap.get(a); + } + }, { + key: "setupVideoTagMethods", + value: function(a, b) { + var c = this, d = document.getElementById(a); + d && (d.oncanplay = function() { + var a = { + ssrc: String(b), + highResTs: o.getCurrent() + }; + c.emb.make(m.internalFabricEvent.mediaPlaybackStart, c.conferenceId, c.pc, a); + }, d.onsuspend = function() { + var a = { + ssrc: String(b), + highResTs: o.getCurrent() + }; + c.emb.make(m.internalFabricEvent.mediaPlaybackSuspended, c.conferenceId, c.pc, a); + }); + } + }, { + key: "updateSSRCInfo", + value: function(a, b, c, d) { + var e = this.ssrcMap.get(a); + e || (e = {}), e.ssrc = a, e.remoteUserID = b, e.usageLabel = c, e.associatedVideoTag = d, + this.ssrcMap.set(a, e), d && b !== this.credentials.getUserId() && this.setupVideoTagMethods(d, a); + } + }, { + key: "updateConferenceId", + value: function(a) { + this.conferenceId = a, this.userAliveHandler.updateConferenceId(a); + } + }, { + key: "updateRemoteId", + value: function(a) { + this.remoteId = a; + } + } ], [ { + key: "Builder", + get: function() { + return function() { + function b() { + e(this, b); + } + return f(b, [ { + key: "withPc", + value: function(a) { + return this.pc = a, this; + } + }, { + key: "withRemoteId", + value: function(a) { + return this.remoteId = a, this; + } + }, { + key: "withFabricUsage", + value: function(a) { + return this.fabricUsage = a, this; + } + }, { + key: "withConferenceId", + value: function(a) { + return this.conferenceId = a, this; + } + }, { + key: "withRemoteEndpointType", + value: function(a) { + return this.remoteEndpointType = a, this; + } + }, { + key: "withFabricTransmissionDirection", + value: function(a) { + return this.fabricTransmissionDirection = a, this; + } + }, { + key: "withCallback", + value: function(a) { + return this.callback = a, this; + } + }, { + key: "make", + value: function() { + return new a(this); + } + } ]), b; + }(); + } + } ]), a; + }(); + c.PeerConnectionHandler = r; + }, { + "../browserapi/devices": 18, + "../config/constants": 32, + "../peerconnection/pccallbackhandler": 39, + "../utility/csiologger": 87, + "../utility/registry": 94, + "../utility/timestamps": 98, + "./getstatshandler": 38, + "./useralivehandler": 42 + } ], + 41: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.PeerConnectionManager = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./peerconnectionhandler"), g = function() { + function a() { + d(this, a), this.pcHandlers = new Map(); + } + return e(a, [ { + key: "addPcHandler", + value: function(a, b, c, d, e, g, h) { + if (!this.getPcHandler(a)) { + var i = new f.PeerConnectionHandler.Builder().withPc(a).withRemoteId(b).withFabricUsage(c).withConferenceId(d).withRemoteEndpointType(e).withFabricTransmissionDirection(g).withCallback(h).make(); + this.pcHandlers.set(i.getPcHash(), i); + } + } + }, { + key: "getPcHandler", + value: function(a) { + var b = null; + return a ? (this.pcHandlers.forEach(function(c, d) { + c && c.getPeerConnection() === a && (b = c); + }), b) : b; + } + }, { + key: "getPcHandlerByHash", + value: function(a) { + return a && this.pcHandlers.has(a) ? this.pcHandlers.get(a) : null; + } + }, { + key: "updateConferenceId", + value: function(a) { + this.pcHandlers.forEach(function(b, c) { + b.updateConferenceId(a); + }); + } + } ]), a; + }(); + c.PeerConnectionManager = g; + }, { + "./peerconnectionhandler": 40 + } ], + 42: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function f(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.UserAliveHandler = void 0; + var g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = a("../config/constants"), i = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(h), j = a("../utility/timeoutprocess"), k = a("../utility/registry"), l = 1e4, m = function(a) { + function b(a, c) { + d(this, b); + var f = e(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, l)); + return f.emb = k.Registry.getEventMessageBuilder(), f.pc = c, f.conferenceId = a, + f.setCallback(f.send), f; + } + return f(b, a), g(b, [ { + key: "send", + value: function() { + this.conferenceId !== i.tmpConferenceId && this.pc && this.emb.make(i.internalFabricEvent.userAlive, this.conferenceId, this.pc); + } + }, { + key: "updateConferenceId", + value: function(a) { + this.conferenceId = a; + } + } ]), b; + }(j.TimeoutProcess); + c.UserAliveHandler = m; + }, { + "../config/constants": 32, + "../utility/registry": 94, + "../utility/timeoutprocess": 97 + } ], + 43: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function g(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Authenticator = void 0; + var h = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), i = function a(b, c, d) { + null === b && (b = Function.prototype); + var e = Object.getOwnPropertyDescriptor(b, c); + if (void 0 === e) { + var f = Object.getPrototypeOf(b); + return null === f ? void 0 : a(f, c, d); + } + if ("value" in e) return e.value; + var g = e.get; + if (void 0 !== g) return g.call(d); + }, j = a("./jwt/jwt"), k = a("./jwt/jwttoken"), l = a("../config/settings"), m = d(l), n = a("../utility/base64"), o = d(n), p = a("../config/callstatserrors"), q = d(p), r = a("../config/constants"), s = d(r), t = a("../browserapi/localstorage"), u = d(t), v = a("../utility/json"), w = d(v), x = a("./xmlhttp"), y = a("./xmlhttpservice"), z = a("../utility/registry"), A = a("../utility/csiologger"), B = d(A), C = m.authRetryTimeout, D = function(a) { + function b() { + e(this, b); + var a = f(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, "Authenticator")); + return a.clockSync = z.Registry.getClockSync(), a.credentials = z.Registry.getCredentials(), + a.url = m.authServiceUrl, a; + } + return g(b, a), h(b, [ { + key: "initiate", + value: function(a, c) { + var d = this; + return this.inProgress ? (c && c(q.csError.authOngoing, null), new Promise(function(a, b) { + b(new Error(d.name + ": in progress")); + })) : this.credentials.getAppId() && this.credentials.getUserId() ? (this.initCallback = c, + "function" == typeof a ? (this.setTokenGenerator(a), i(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "initiate", this).call(this)) : new Promise(function(c, e) { + d.createTokenGenerator(a).then(function(a) { + d.setTokenGenerator(a), i(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "initiate", d).call(d).then(function() { + c(); + }, function(a) { + e(a); + }); + }, function(a) { + e(new Error(d.name + ": tokenGenerator creation problem (" + a + ")")); + }); + })) : new Promise(function(a, b) { + b(new Error(d.name + ": credentials not set")); + }); + } + }, { + key: "getToken", + value: function() { + var a = null; + return this.token && (a = this.token.getToken()), a; + } + }, { + key: "isTokenValid", + value: function() { + return !!this.token && this.token.isValid(this.credentials); + } + }, { + key: "getElapsed", + value: function() { + return this.isCompleted() ? this.elapsed : null; + } + }, { + key: "getIceServers", + value: function() { + return this.iceServers; + } + }, { + key: "reset", + value: function() { + this.token = null, this.reauthTimer = null, this.renew = !1, this.credentials = null, + this.jwt = new j.Jwt(), this.tokenGenerator = function(a, b) { + b("Token generator is not set"); + }, this.elapsed = 0, this.iceServers = null, i(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "reset", this).call(this); + } + }, { + key: "setupToken", + value: function(a) { + u.store("csio_auth_data", JSON.stringify(a)), this.token = new k.JwtToken(a, this.clockSync); + } + }, { + key: "clearReauthTimer", + value: function() { + null !== this.reauthTimer && (clearTimeout(this.reauthTimer), this.reauthTimer = null); + } + }, { + key: "setupReauthTimer", + value: function(a) { + var b = this; + b.clearReauthTimer(), b.reauthTimer = setTimeout(function() { + b.reAuthenticate(); + }, a); + } + }, { + key: "reAuthenticate", + value: function() { + this.inProgress || (this.inProgress = !0, this.token = null, this.sendRequest()); + } + }, { + key: "handleErrorActions", + value: function(a) { + if (0 !== a.length) { + var b = a.shift(); + if (b.action === q.authErrorActions.RETRY) { + var c = b.params.timeout ? b.params.timeout : m.authRetryTimeout; + this.setupReauthTimer(c), this.handleErrorActions(a); + } + b.action === q.authErrorActions.GET_NEW_TOKEN && (this.renew = !0, this.handleErrorActions(a)), + b.action === q.authErrorActions.REPORT_ERROR && (B.error(this.name + ": " + b.params.errorReason), + this.handleErrorActions(a)); + } + } + }, { + key: "setTokenGenerator", + value: function(a) { + this.tokenGenerator = a; + } + }, { + key: "handleResponse", + value: function(a) { + var b = a.getXhr(), c = a.getElapsed(), d = w.parse(b.response); + if (!d) return B.error(this.name + ": invalid authentication response"), void this.sendNextRequest(); + if (d["urn:x-callstats:auth:errorActions"] && d["urn:x-callstats:auth:errorActions"].length > 0) return void this.handleErrorActions(d["urn:x-callstats:auth:errorActions"]); + if (200 === b.status) { + if ("bearer" !== d.token_type) return B.error(this.name + ": successful, but token type was not bearer. Scheduling retry."), + void this.sendNextRequest(); + this.setupToken(d.access_token), d.iceServers && (this.iceServers = d.iceServers); + var e = parseInt(1e3 * parseInt(d.expires_in) * .9); + return this.setupReauthTimer(e), this.renew = !1, this.initCallback && this.initCallback(q.csError.success, s.csCallBackMessages.authSuccessful), + this.elapsed = c, void this.completeProcess(); + } + B.error("Authentication failed, but no error actions were defined in response."), + this.sendNextRequest(); + } + }, { + key: "request", + value: function() { + var a = this; + this.clearReauthTimer(); + var b = new Promise(function(b, c) { + a.tempResolve = b, a.tempReject = c; + }); + return this.tokenGenerator(this.renew, function(b, c) { + if (null !== b) return a.initCallback && a.initCallback(q.csError.tokenGenerationError, b.toString()), + a.rejectCb(new Error(a.name + ": tokenGenerationError")), B.error("tokenGenerationError ", b), + null; + var d = a.url + "authenticate", e = { + client_id: a.credentials.userId + "@" + a.credentials.getAppId(), + code: c, + grant_type: "authorization_code" + }, f = { + "Content-Type": "application/x-www-form-urlencoded" + }; + (0, x.sendPostRequest)(d, f, C, e).then(function(b) { + a.tempResolve(b); + }, function(b) { + a.tempReject(b); + }); + }), b; + } + }, { + key: "tokenGeneratorCreator", + value: function(a, b) { + var c = this; + return function(d, e) { + var f = null, g = { + alg: "HS256" + }; + if (!d && null !== f) return e(null, f); + var h = c.credentials, i = { + userID: h.getUserId(), + appID: h.getAppId() + }; + b && (i.keyId = b), c.jwt.sign(g, i, a).then(function(a) { + f = a, e(null, a); + }).catch(function(a) { + e(a); + }); + }; + } + }, { + key: "createTokenGenerator", + value: function(a) { + var b = this; + return new Promise(function(c, d) { + var e = null; + a.indexOf(":") > -1 && (e = o.strtohex(a.split(":")[0]), a = a.split(":")[1]), b.jwt.importKey(a).then(function(d) { + a = null; + var f = b.tokenGeneratorCreator(d, e); + c(f); + }).catch(function(a) { + B.error(b.name + ": could not import key (" + a + ")"), d(a); + }); + }); + } + } ]), b; + }(y.XMLHttpService); + c.Authenticator = D; + }, { + "../browserapi/localstorage": 19, + "../config/callstatserrors": 31, + "../config/constants": 32, + "../config/settings": 33, + "../utility/base64": 84, + "../utility/csiologger": 87, + "../utility/json": 92, + "../utility/registry": 94, + "./jwt/jwt": 51, + "./jwt/jwttoken": 52, + "./xmlhttp": 57, + "./xmlhttpservice": 58 + } ], + 44: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.GenericEventHandler = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../config/settings"), h = d(g), i = a("./xmlhttp"), j = a("../utility/registry"), k = a("../utility/csiologger"), l = d(k), m = h.baseUrl + "generics", n = function() { + function a() { + e(this, a), this.credentials = j.Registry.getCredentials(), this.enabled = !1; + } + return f(a, [ { + key: "enable", + value: function() { + this.enabled = !0; + } + }, { + key: "disable", + value: function() { + this.enabled = !1; + } + }, { + key: "sendEvent", + value: function(a, b) { + this.send(a, b).then(function(a) { + l.log("Got generic response: %o", a); + }).catch(function(a) { + l.log("Got error for generic request", a); + }); + } + }, { + key: "send", + value: function(a, b) { + if (!this.enabled) return new Promise(function(a, b) { + b(new Error("GenericEvent Error: not enabled")); + }); + var c = this; + return new Promise(function(d, e) { + var f = { + "Content-Type": "application/json" + }, g = { + appID: c.credentials.appId, + userID: encodeURIComponent(c.credentials.userId), + version: h.version, + eventType: a, + data: b + }; + (0, i.sendPostRequest)(m, f, 5e3, g).then(function(a) { + d(a.getXhr().response); + }, function(a) { + e(a); + }); + }); + } + } ]), a; + }(); + c.GenericEventHandler = n; + }, { + "../config/settings": 33, + "../utility/csiologger": 87, + "../utility/registry": 94, + "./xmlhttp": 57 + } ], + 45: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function g(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.ClockSync = void 0; + var h = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), i = function a(b, c, d) { + null === b && (b = Function.prototype); + var e = Object.getOwnPropertyDescriptor(b, c); + if (void 0 === e) { + var f = Object.getPrototypeOf(b); + return null === f ? void 0 : a(f, c, d); + } + if ("value" in e) return e.value; + var g = e.get; + if (void 0 !== g) return g.call(d); + }, j = a("../config/settings"), k = d(j), l = a("./xmlhttp"), m = a("../utility/timestamps"), n = d(m), o = a("./xmlhttpservice"), p = a("../utility/registry"), q = a("../config/constants"), r = d(q), s = k.baseUrl + "clockSync", t = function(a) { + function b() { + e(this, b); + var a = f(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, "ClockSync")); + return a.currentOffset = 0, a.completed = !1, a; + } + return g(b, a), h(b, [ { + key: "initiate", + value: function() { + return this.startTime = n.getCurrent(), p.Registry.getGenericEventHandler().sendEvent(r.logEvents.log, { + msg: "Starting clocksync" + }), i(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "initiate", this).call(this); + } + }, { + key: "getSynchronizedTimestamp", + value: function() { + return n.getCurrent() + this.currentOffset; + } + }, { + key: "getElapsed", + value: function() { + return this.isCompleted() ? this.endTime - this.startTime : null; + } + }, { + key: "getOffset", + value: function() { + return this.currentOffset; + } + }, { + key: "reset", + value: function() { + this.currentOffset = 0, this.offsetResults = [], this.startTime = 0, this.endTime = 0, + i(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "reset", this).call(this); + } + }, { + key: "request", + value: function() { + return (0, l.sendGetRequest)(s, null, 5e3); + } + }, { + key: "handleResponse", + value: function(a) { + var b = a.getXhr(), c = a.getElapsed(), d = JSON.parse(b.response), e = n.getCurrent(); + this.handleMessage(d, c, e); + } + }, { + key: "handleMessage", + value: function(a, b, c) { + var d = b / 2; + d > 6e4 ? (this.offsetResults = [], p.Registry.getGenericEventHandler().sendEvent(r.logEvents.log, { + msg: "clockSync restarting" + })) : this.addOffset(a, d, c), this.offsetResults.length >= 5 ? (this.calculateOffset(), + this.endTime = n.getCurrent(), this.completeProcess()) : this.sendRequest(); + } + }, { + key: "isCompleted", + value: function() { + return this.completed; + } + }, { + key: "addOffset", + value: function(a, b, c) { + var d = a.now + b, e = d - c; + this.offsetResults.push(e), p.Registry.getGenericEventHandler().sendEvent(r.logEvents.log, { + msg: "clockSync Info: serverTime " + d + " responseRecvTs: " + c + }); + } + }, { + key: "calculateOffset", + value: function() { + var a = this.offsetResults.reduce(function(a, b) { + return a + b; + }); + this.currentOffset = a / this.offsetResults.length, this.currentOffset = isNaN(this.currentOffset) ? 0 : this.currentOffset, + p.Registry.getGenericEventHandler().sendEvent(r.logEvents.log, { + msg: "clockSync Done, offset is: " + this.currentOffset + "results length" + this.offsetResults.length + }), this.offsetResults = [], this.completed = !0; + } + } ]), b; + }(o.XMLHttpService); + c.ClockSync = t; + }, { + "../config/constants": 32, + "../config/settings": 33, + "../utility/registry": 94, + "../utility/timestamps": 98, + "./xmlhttp": 57, + "./xmlhttpservice": 58 + } ], + 46: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a() { + d(this, a), this.connected = !1, this.reconnected = !1, this.conferenceUrl = {}; + } + return e(a, [ { + key: "setup", + value: function() { + return new Promise(function(a, b) { + a(); + }); + } + }, { + key: "isReady", + value: function() { + return this.connected; + } + }, { + key: "send", + value: function(a) {} + } ]), a; + }(); + c.CollectorConnection = f; + }, {} ], + 47: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function f(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.ConfigServiceGet = void 0; + var g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = function a(b, c, d) { + null === b && (b = Function.prototype); + var e = Object.getOwnPropertyDescriptor(b, c); + if (void 0 === e) { + var f = Object.getPrototypeOf(b); + return null === f ? void 0 : a(f, c, d); + } + if ("value" in e) return e.value; + var g = e.get; + if (void 0 !== g) return g.call(d); + }, i = a("../xmlhttp"), j = a("../xmlhttpservice"), k = a("../../utility/registry"), l = function(a) { + function b() { + return d(this, b), e(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, "ConfigService")); + } + return f(b, a), g(b, [ { + key: "initiate", + value: function(a) { + var c = this; + return this.url = a, this.authToken = k.Registry.getAuthenticator().getToken(), + this.authToken ? h(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "initiate", this).call(this) : new Promise(function(a, b) { + b(new Error(c.name + ": authToken has to be string")); + }); + } + }, { + key: "getConfig", + value: function() { + return this.config; + } + }, { + key: "getElapsed", + value: function() { + return this.isCompleted() ? this.elapsed : null; + } + }, { + key: "reset", + value: function() { + this.authToken = null, this.url = null, this.config = null, this.elapsed = 0, h(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "reset", this).call(this); + } + }, { + key: "request", + value: function() { + var a = { + Authorization: "Bearer " + this.authToken + }; + return (0, i.sendGetRequest)(this.url, a, 2e3); + } + }, { + key: "handleResponse", + value: function(a) { + var b = a.getXhr(), c = a.getElapsed(); + this.config = JSON.parse(b.response), this.elapsed = c, this.completeProcess(); + } + } ]), b; + }(j.XMLHttpService); + c.ConfigServiceGet = l; + }, { + "../../utility/registry": 94, + "../xmlhttp": 57, + "../xmlhttpservice": 58 + } ], + 48: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function f(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.ConfigServicePost = void 0; + var g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = function a(b, c, d) { + null === b && (b = Function.prototype); + var e = Object.getOwnPropertyDescriptor(b, c); + if (void 0 === e) { + var f = Object.getPrototypeOf(b); + return null === f ? void 0 : a(f, c, d); + } + if ("value" in e) return e.value; + var g = e.get; + if (void 0 !== g) return g.call(d); + }, i = a("../xmlhttp"), j = a("./configserviceget"), k = function(a) { + function b() { + return d(this, b), e(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this)); + } + return f(b, a), g(b, [ { + key: "initiate", + value: function(a, c) { + return this.body = c, h(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "initiate", this).call(this, a); + } + }, { + key: "request", + value: function() { + var a = { + Authorization: "Bearer " + this.authToken + }; + return a["Content-Type"] = "application/json", (0, i.sendPostRequest)(this.url, a, 2e3, this.body); + } + } ]), b; + }(j.ConfigServiceGet); + c.ConfigServicePost = k; + }, { + "../xmlhttp": 57, + "./configserviceget": 47 + } ], + 49: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.ConfigServiceWrapper = void 0; + var f = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(a) { + return typeof a; + } : function(a) { + return a && "function" == typeof Symbol && a.constructor === Symbol && a !== Symbol.prototype ? "symbol" : typeof a; + }, g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = a("./configserviceget"), i = a("./configservicepost"), j = a("../../config/settings"), k = d(j), l = a("../../utility/registry"), m = a("../../utility/csiologger"), n = d(m), o = k.configServiceUrl, p = function() { + function a() { + e(this, a), this.internalConfigService = new h.ConfigServiceGet(), this.appConfigService = new h.ConfigServiceGet(), + this.senderConfigService = new i.ConfigServicePost(), this.defaultSenderConfig = null; + } + return g(a, [ { + key: "initiateInternalConfig", + value: function() { + var a = this, b = l.Registry.getCredentials().getAppId(); + if (!b) return new Promise(function(b, c) { + n.log("appId has to be string"), c(new Error(a.internalConfigService.name + ": appId has to be string")); + }); + var c = o + b; + return this.internalConfigService.initiate(c + "/configurations/internal"); + } + }, { + key: "initiateAppConfig", + value: function() { + var a = this, b = l.Registry.getCredentials().getAppId(); + if (!b) return new Promise(function(b, c) { + n.log("appId has to be string"), c(new Error(a.appConfigService.name + ": appId has to be string")); + }); + var c = o + b; + return this.appConfigService.initiate(c + "/configurations"); + } + }, { + key: "initiateSenderConfig", + value: function(a) { + var b = this; + if (this.senderConfigService.getConfig()) return new Promise(function(a, c) { + n.log("sender config already present"), c(new Error(b.senderConfigService.name + ": sender config already present")); + }); + var c = l.Registry.getCredentials().getAppId(), d = l.Registry.getCredentials().getUserId(); + if (!c || !d) return new Promise(function(a, c) { + n.log("appId and userId have to be string"), c(new Error(b.senderConfigService.name + ": appId and userId have to be string")); + }); + if (this.defaultSenderConfig = this.getCurrentVideoSenderConfig(a), !this.defaultSenderConfig) return new Promise(function(a, c) { + n.log("Could not obtain a sender config"), c(new Error(b.senderConfigService.name + ": Could not obtain a sender config")); + }); + var e = o + c, f = { + app_id: c, + local_id: d, + rtc_rtp_parameters: this.defaultSenderConfig + }; + return this.senderConfigService.initiate(e + "/configurations", f); + } + }, { + key: "getInternalConfig", + value: function() { + return this.internalConfigService.getConfig(); + } + }, { + key: "getAppDefaultConfig", + value: function() { + var a = this.appConfigService.getConfig(), b = { + peerConnection: null, + media: null + }; + return a.default ? (a.default.peerConnection && (b.peerConnection = a.default.peerConnection), + a.default.media && (b.media = a.default.media), b) : b; + } + }, { + key: "getAppRecommendedConfig", + value: function() { + var a = this.appConfigService.getConfig(), b = {}; + return a.recommended ? (a.recommended.peerConnection && (b.peerConnection = a.recommended.peerConnection), + a.recommended.media && (b.media = a.recommended.media), b) : b; + } + }, { + key: "getSenderConfig", + value: function() { + var a = this.senderConfigService.getConfig(); + return a && a.recommended && a.recommended.sender ? a.recommended.sender : null; + } + }, { + key: "getDefaultSenderConfig", + value: function() { + return this.defaultSenderConfig ? this.defaultSenderConfig : null; + } + }, { + key: "getInternalElapsed", + value: function() { + return this.internalConfigService.getElapsed(); + } + }, { + key: "getAppElapsed", + value: function() { + return this.appConfigService.getElapsed(); + } + }, { + key: "getSenderElapsed", + value: function() { + return this.senderConfigService.getElapsed(); + } + }, { + key: "getCurrentVideoSenderConfig", + value: function(a) { + var b = { + encodings: [ { + maxBitrate: 0 + } ] + }, c = l.Registry.getConferenceManager().getConferenceForPc(a); + if (!c) return n.warn("No conference found for PC, skipping"), null; + if (c.getPeerConnectionManager().pcHandlers.size > 1) return n.warn("Multiple PCs found, skipping"), + null; + if (!a.getSenders || "function" != typeof a.getSenders) return n.warn("Get senders error"), + b; + for (var d = a.getSenders(), e = void 0, g = 0; g < d.length; g += 1) { + var h = d[g]; + if ("object" !== (void 0 === h ? "undefined" : f(h)) || !h.track || "object" !== f(h.track) || !h.track.kind) return n.warn("Access senders error"), + null; + if ("video" === h.track.kind) { + if (e) return n.warn("Multiple video sender, skipping"), null; + e = h; + } + } + if (!e) return n.warn("No video sender found"), null; + if (!e.getParameters || "function" != typeof e.getParameters) return n.warn("Sender getParameters error"), + b; + var i = e.getParameters(); + return "object" !== (void 0 === i ? "undefined" : f(i)) ? null : ("encodings" in i || (i.encodings = []), + 0 === i.encodings.length && i.encodings.push({ + maxBitrate: 0 + }), i); + } + } ]), a; + }(); + c.ConfigServiceWrapper = p; + }, { + "../../config/settings": 33, + "../../utility/csiologger": 87, + "../../utility/registry": 94, + "./configserviceget": 47, + "./configservicepost": 48 + } ], + 50: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.ConnectionManager = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("../config/constants"), g = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(f), h = a("./wscollectorconnection"), i = a("./restcollectorconnection"), j = a("../utility/registry"), k = function() { + function a() { + d(this, a), this.connection = null; + } + return e(a, [ { + key: "setupCollectorConnection", + value: function(a) { + a === g.transportType.rest ? this.connection = new i.RestCollectorConnection() : this.connection = new h.WsCollectorConnection(); + } + }, { + key: "setup", + value: function() { + return this.connection ? this.connection.setup() : new Promise(function(a, b) { + b(); + }); + } + }, { + key: "isReady", + value: function() { + return !!this.connection && this.connection.isReady(); + } + }, { + key: "send", + value: function(a) { + if (!this.connection) return void j.Registry.getGenericEventHandler().sendEvent(g.logEvents.error, { + msg: "Connection not available to the collector" + }); + this.connection.send(a); + } + } ]), a; + }(); + c.ConnectionManager = k; + }, { + "../config/constants": 32, + "../utility/registry": 94, + "./restcollectorconnection": 53, + "./wscollectorconnection": 56 + } ], + 51: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Jwt = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../../utility/base64"), h = d(g), i = a("../../utility/csiologger"), j = d(i), k = a("../../utility/registry"), l = a("../../config/constants"), m = d(l), n = function() { + function a() { + e(this, a), this.cryptotype = null, window.crypto && window.crypto.subtle ? (this.cryptotype = "standard", + this.subtlecrypto = window.crypto.subtle) : window.crypto && !window.crypto.subtle && window.crypto.webkitSubtle ? (this.cryptotype = "webkit", + this.subtlecrypto = window.crypto.webkitSubtle) : window.msCrypto && window.msCrypto.subtle ? (this.cryptotype = "ie", + this.subtlecrypto = window.msCrypto.subtle) : (this.subtlecrypto = null, j.info("WebCryptography API not supported in this browser.")), + this.browserName = k.Registry.getEndpoint().getBrowserName(); + } + return f(a, [ { + key: "sign", + value: function(a, b, c) { + var d = this; + return new Promise(function(e, f) { + "HS256" !== a.alg && f("Use header.alg=HS256"), a = JSON.stringify(a), "string" != typeof b && (b = JSON.stringify(b)); + var g = h.urlencodeUnicode(a) + "." + h.urlencodeUnicode(b); + window.csioReactNative && window.csiosign(g, c, function(a, b) { + if (a) return j.log("Token sign error", a), void f(error); + e(b); + }); + var i = new ArrayBuffer(g.length), k = new Uint8Array(i), l = { + name: "HMAC" + }; + "ie" !== d.cryptotype && "webkit" !== d.cryptotype && d.browserName !== m.browserName.edge || (l.hash = { + name: "sha-256" + }); + for (var n = g.length - 1; n >= 0; n--) k[n] = g.charCodeAt(n); + var o = d.subtlecrypto.sign(l, c, k); + "ie" === d.cryptotype ? (o.onerror = f, o.oncomplete = function(a) { + g = d.buildToken(a.target.result, g), e(g); + }) : o.then(function(a) { + g = d.buildToken(a, g), e(g); + }).catch(function(a) { + f(a); + }); + }); + } + }, { + key: "buildToken", + value: function(a, b) { + for (var c = "", d = new Uint8Array(a), e = d.byteLength, f = 0; f < e; f++) c += String.fromCharCode(d[f]); + return b += "." + h.urlencode(c); + } + }, { + key: "decode", + value: function(a) { + try { + var b = a.split(".")[1], c = h.decode(b); + return JSON.parse(c); + } catch (a) { + return j.error("Could not decode token. "), null; + } + } + }, { + key: "importKey", + value: function(a) { + var b = this; + return new Promise(function(c, d) { + if (window.csioReactNative) return void c(a); + if ("webkit" === b.cryptotype) for (;a.length < 32; ) a += "\0"; + var e = { + kty: "oct", + k: h.urlencode(a), + alg: "HS256" + }, f = { + name: "HMAC", + hash: { + name: "SHA-256" + } + }; + if ("ie" === b.cryptotype ? e.extractable = !1 : e.ext = !1, "webkit" === b.cryptotype && (f = null, + e.use = "sig"), "ie" === b.cryptotype || "webkit" === b.cryptotype) { + var g = JSON.stringify(e); + e = new Uint8Array(g.length); + for (var i = 0; i < g.length; i++) e[i] = g.charCodeAt(i); + } + var j = b.subtlecrypto.importKey("jwk", e, f, !1, [ "sign" ]); + "ie" === b.cryptotype ? (j.onerror = d, j.oncomplete = function(a) { + c(a.target.result); + }) : j.then(c).catch(d); + }); + } + } ]), a; + }(); + c.Jwt = n; + }, { + "../../config/constants": 32, + "../../utility/base64": 84, + "../../utility/csiologger": 87, + "../../utility/registry": 94 + } ], + 52: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.JwtToken = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("./jwt"), h = a("../../utility/registry"), i = a("../../config/constants"), j = d(i), k = a("../../utility/csiologger"), l = d(k), m = function() { + function a(b) { + e(this, a), this.token = b, this.statsSubmissionInterval = 15e3, this.collectSDP = !1, + this.appId = null, this.userId = null, this.tokenPayload = null, this.jwt = new g.Jwt(), + this.expires = null, this.clockSync = h.Registry.getClockSync(), this.adaptiveInterval = !1, + this.transportType = j.transportType.rest, this.setupTokenPayload(), this.restApiTransport = !1; + } + return f(a, [ { + key: "getToken", + value: function() { + return this.token; + } + }, { + key: "setupTokenPayload", + value: function() { + var a = this.jwt.decode(this.token); + if (this.statsSubmissionInterval = parseInt(a.submissionInterval, 10), this.collectSDP = a.collectSDP, + this.adaptiveInterval = a.adaptiveInterval, this.appId = a.appID, this.userId = a.userID, + this.restApiTransport = a.restApiTransport, navigator.mozGetUserMedia) { + var b = a.expiry.split(" ").join("T"); + this.expires = Date.parse(b); + } else this.expires = new Date(a.expiry); + this.restApiTransport ? this.transportType = j.transportType.rest : this.transportType = j.transportType.ws, + l.info("transportType is ", this.transportType, this.restApiTransport), h.Registry.getCredentials().setStatsSubmissionInterval(this.statsSubmissionInterval), + h.Registry.getCredentials().setCollectSDP(this.collectSDP), h.Registry.getCredentials().setTransportType(this.transportType), + h.Registry.getCredentials().setAdaptiveInterval(this.adaptiveInterval); + } + }, { + key: "isValid", + value: function(a) { + var b = this, c = !1; + if (null !== b.token && b.appId === a.appId && b.userId === encodeURIComponent(a.userId)) { + new Date(this.clockSync.getSynchronizedTimestamp()) < b.expires && (c = !0); + } + return c; + } + } ]), a; + }(); + c.JwtToken = m; + }, { + "../../config/constants": 32, + "../../utility/csiologger": 87, + "../../utility/registry": 94, + "./jwt": 51 + } ], + 53: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function g(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.RestCollectorConnection = void 0; + var h = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), i = a("../utility/registry"), j = a("./xmlhttp"), k = a("./collectorconnection"), l = a("./restrelays"), m = a("../config/constants"), n = d(m), o = a("../utility/csiologger"), p = d(o), q = function(a) { + function b() { + e(this, b); + var a = f(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this)); + return a.relays = new l.RestRelays(), a; + } + return g(b, a), h(b, [ { + key: "isReady", + value: function() { + return !0; + } + }, { + key: "send", + value: function(a) { + var b = { + "Content-Type": "application/json", + Authorization: "Bearer " + i.Registry.getAuthenticator().getToken() + }, c = a.eventType, d = a.confID, e = a.ucID, f = this.relays, g = f.getRequestUrl(c, d, e); + if (!g) return void p.warn("No action for message type: " + c); + var h = this.getMessage(c, a); + p.log("sending ", g, a), (0, j.sendPostRequest)(g, b, 5e3, h).then(function(a) { + f.handleResponse(c, a, d); + }, function(a) { + p.error(a); + }); + } + }, { + key: "getMessage", + value: function(a, b) { + delete b.confID, delete b.channel, delete b.token, delete b.appID, delete b.action, + delete b.ucID, delete b.version; + var c = decodeURIComponent(b.localID); + b.localID = c; + var d = decodeURIComponent(b.remoteID); + return b.remoteID = d, a === n.callstatsChannels.processedStats && (b.eventType = "stats"), + b; + } + } ]), b; + }(k.CollectorConnection); + c.RestCollectorConnection = q; + }, { + "../config/constants": 32, + "../utility/csiologger": 87, + "../utility/registry": 94, + "./collectorconnection": 46, + "./restrelays": 54, + "./xmlhttp": 57 + } ], + 54: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f() { + var a = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : null, b = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null; + return function(c, d) { + if (!c || !c.xhr) return void p.log("Response for request is null"); + var e = c.xhr.response, f = JSON.parse(e); + f.conferenceId = d, "success" === f.status ? a && a(f) : b ? b(f) : (m.Registry.getGenericEventHandler().sendEvent(j.logEvents.restResponseError, { + msg: "response failure " + f.msg + ":" + f.status + }), p.error("Response error:", f.msg, e)); + }; + } + function g(a) { + var b = f(); + return new Map([ [ j.fabricEvent.fabricTerminated, new r(l.restEventUrl, "/events/fabric/terminated", b) ], [ j.fabricEvent.audioMute, new r(l.restEventUrl, "/events/media/actions", b) ], [ j.fabricEvent.audioUnmute, new r(l.restEventUrl, "/events/media/actions", b) ], [ j.fabricEvent.videoPause, new r(l.restEventUrl, "/events/media/actions", b) ], [ j.fabricEvent.videoResume, new r(l.restEventUrl, "/events/media/actions", b) ], [ j.fabricEvent.screenShareStart, new r(l.restEventUrl, "/events/media/actions", b) ], [ j.fabricEvent.screenShareStop, new r(l.restEventUrl, "/events/media/actions", b) ], [ j.fabricEvent.activeDeviceList, new r(l.restEventUrl, "/events/devices/list", b) ], [ j.fabricEvent.applicationErrorLog, new r(l.restEventUrl, "/events/app/logs", b) ], [ j.fabricEvent.dominantSpeaker, new r(l.restEventUrl, "/events/dominantspeaker", b) ], [ j.fabricEvent.fabricHold, new r(l.restEventUrl, "/events/fabric/actions", b) ], [ j.fabricEvent.fabricResume, new r(l.restEventUrl, "/events/fabric/actions", b) ], [ j.internalFabricEvent.fabricSetup, new r(l.restEventUrl, "/events/fabric/setup", b) ], [ j.fabricEvent.fabricSetupFailed, new r(l.restEventUrl, "/events/fabric/setupfailed", b) ], [ j.internalFabricEvent.userJoined, new r(l.restEventUrl, "", f(function(a) { + if ("success" !== a.status) return void m.Registry.getGenericEventHandler().sendEvent(j.logEvents.restResponseError, { + msg: "userJoined response failure" + a.msg + ":" + a.status + }); + var b = decodeURIComponent(a.conferenceId), c = m.Registry.getConferenceManager().get(b); + c && (p.log("UcId =", a.ucID, b), c.setUcId(a.ucID), m.Registry.getTransmissionManager().trySend()); + })) ], [ j.internalFabricEvent.userLeft, new r(l.restEventUrl, "/events/user/left", b) ], [ j.internalFabricEvent.userAlive, new r(l.restEventUrl, "/events/user/alive", b) ], [ j.internalFabricEvent.fabricTransportSwitch, new r(l.restEventUrl, "/events/fabric/transportchange", b) ], [ j.internalFabricEvent.mediaPlaybackStart, new r(l.restEventUrl, "/events/media/pipeline", b) ], [ j.internalFabricEvent.mediaPlaybackSuspended, new r(l.restEventUrl, "/events/media/pipeline", b) ], [ j.internalFabricEvent.mediaPlaybackStalled, new r(l.restEventUrl, "/events/media/pipeline", b) ], [ j.internalFabricEvent.ssrcMap, new r(l.restEventUrl, "/events/ssrcmap", b) ], [ j.internalFabricEvent.connectedDeviceList, new r(l.restEventUrl, "/events/devices/list", b) ], [ j.internalFabricEvent.sdpSubmission, new r(l.restEventUrl, "/events/sdp", b) ], [ j.internalFabricEvent.iceDisruptionStart, new r(l.restEventUrl, "/events/ice/status", b) ], [ j.internalFabricEvent.iceDisruptionEnd, new r(l.restEventUrl, "/events/ice/status", b) ], [ j.internalFabricEvent.iceConnectionDisruptionStart, new r(l.restEventUrl, "/events/ice/status", b) ], [ j.internalFabricEvent.iceConnectionDisruptionEnd, new r(l.restEventUrl, "/events/ice/status", b) ], [ j.internalFabricEvent.iceAborted, new r(l.restEventUrl, "/events/ice/status", b) ], [ j.internalFabricEvent.iceTerminated, new r(l.restEventUrl, "/events/ice/status", b) ], [ j.internalFabricEvent.iceFailed, new r(l.restEventUrl, "/events/ice/status", b) ], [ j.internalFabricEvent.iceRestarted, new r(l.restEventUrl, "/events/ice/status", b) ], [ j.internalFabricEvent.fabricDropped, new r(l.restEventUrl, "/events/fabric/status", b) ], [ j.callstatsChannels.processedStats, new r(l.restStatsUrl, "/stats", b) ], [ j.internalFabricEvent.fabricStateChange, new r(l.restEventUrl, "/events/fabric/statechange", b) ], [ j.callstatsChannels.userFeedback, new r(l.restEventUrl, "/events/feedback", b) ], [ j.precalltestEvents.results, new r(l.restEventUrl, "/events/precall", b) ], [ j.precalltestEvents.associate, new r(l.restEventUrl, "/events/precall", b) ], [ j.internalFabricEvent.userDetails, new r(l.restEventUrl, "/events/userdetails", b) ] ]); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.RestRelays = void 0; + var h = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), i = a("../config/constants"), j = d(i), k = a("../config/settings"), l = d(k), m = a("../utility/registry"), n = a("../utility/url"), o = a("../utility/csiologger"), p = d(o), q = function() { + function a() { + e(this, a), this.items = g(); + } + return h(a, [ { + key: "getRequestUrl", + value: function(a, b, c) { + return this.items.has(a) ? this.items.get(a).getRequestUrl(a, b, c) : (p.warn("EventType Unsupported ", a), + null); + } + }, { + key: "handleResponse", + value: function(a, b, c) { + if (!this.items.has(a)) return void p.warn("No response handler for event type " + a); + this.items.get(a).handleResponse(b, c); + } + } ]), a; + }(), r = function() { + function a(b, c) { + var d = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : null; + e(this, a), this.baseUrl = b, this.urlAppendix = c, this.responseHandler = d; + } + return h(a, [ { + key: "getRequestUrl", + value: function(a, b, c) { + return this.makeRequestUrl(a, b, c), this.requestUrl.toString(); + } + }, { + key: "makeRequestUrl", + value: function(a, b, c) { + a === j.precalltestEvents.results ? this.requestUrl = new n.Url(this.baseUrl, m.Registry.getCredentials().getAppId(), this.urlAppendix) : (a === j.internalFabricEvent.userJoined && c && (c = ""), + this.requestUrl = new n.Url(this.baseUrl, m.Registry.getCredentials().getAppId() + "/conferences/" + b, c, this.urlAppendix)); + } + }, { + key: "handleResponse", + value: function(a, b) { + this.responseHandler(a, b); + } + } ]), a; + }(); + c.RestRelays = q; + }, { + "../config/constants": 32, + "../config/settings": 33, + "../utility/csiologger": 87, + "../utility/registry": 94, + "../utility/url": 99 + } ], + 55: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.TransmissionManager = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../utility/timestamps"), h = d(g), i = a("../collections/cache"), j = a("../utility/registry"), k = a("../config/constants"), l = d(k), m = a("../utility/csiologger"), n = d(m), o = function() { + function a() { + e(this, a), this.cache = [], this.connectionManager = j.Registry.getConnectionManager(), + this.lastTS = 0, this.timerStarted = !1; + } + return f(a, [ { + key: "send", + value: function(a) { + (a.isCachable() || a.canBeSent()) && (this.cache[a.getConferenceId()] || (this.cache[a.getConferenceId()] = new i.Cache()), + this.cache[a.getConferenceId()].add(a, a.isPriority()), this.trySend()); + } + }, { + key: "trySend", + value: function() { + if (!this.connectionManager.isReady()) return void this.setupConnection(); + if (!this.timerStarted) return this.timeToSend() ? void (this.sendMessage() && this.startTimer()) : void (this.getCacheLength() > 0 && this.startTimer()); + } + }, { + key: "setupConnection", + value: function() { + this.connectionManager.setup().then(function() { + n.log("Connected to connectionManager"); + }).catch(function(a) { + return n.log("Could not connect to connectionManager", a); + }); + } + }, { + key: "sendMessage", + value: function() { + var a = void 0, b = void 0; + if (0 === this.getCacheLength()) return !1; + for (var c in this.cache) if (this.cache.hasOwnProperty(c) && (b = c, (a = this.cache[b].peak()) && a.canBeSent())) break; + return !(!a || !a.canBeSent()) && (n.log("sending message type :", a.toJson().action, a.toJson()), + a = this.cache[b].pop(), this.lastTS = h.getCurrent(), this.connectionManager.send(a.toJson()), + !0); + } + }, { + key: "startTimer", + value: function() { + var a = this; + this.timerStarted || 0 != this.getCacheLength() && (this.timerStarted = !0, setTimeout(function() { + a.timerStarted = !1, a.trySend(); + }, 200)); + } + }, { + key: "timeToSend", + value: function() { + return h.getCurrent() >= this.lastTS + 200; + } + }, { + key: "getCacheLength", + value: function() { + var a = 0; + for (var b in this.cache) this.cache.hasOwnProperty(b) && (a += this.cache[b].length()); + return a; + } + }, { + key: "updateConferenceId", + value: function(a) { + var b = l.tmpConferenceId; + this.cache[b] && this.cache[b].updateConferenceId(a); + } + } ]), a; + }(); + c.TransmissionManager = o; + }, { + "../collections/cache": 24, + "../config/constants": 32, + "../utility/csiologger": 87, + "../utility/registry": 94, + "../utility/timestamps": 98 + } ], + 56: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function g(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.WsCollectorConnection = void 0; + var h = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), i = a("../config/callstatserrors"), j = d(i), k = a("../config/constants"), l = d(k), m = a("../config/settings"), n = d(m), o = a("../utility/registry"), p = a("../utility/csiologger"), q = d(p), r = a("./collectorconnection"), s = function(a) { + function b() { + e(this, b); + var a = f(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this)); + return a.wsConnection = null, a.wsUrl = n.wsUrl, a.wsConnectionState = l.wsConnectionState.closed, + a.connected = !1, a.reconnected = !1, a; + } + return g(b, a), h(b, [ { + key: "onOpenHandler", + value: function() { + var a = this; + a.wsConnectionState = l.wsConnectionState.connected, a.connected ? a.reconnected = !0 : a.connected = !0, + a.reconnected = !1; + } + }, { + key: "onCloseHandler", + value: function() { + var a = this; + a.wsConnectionState = l.wsConnectionState.closed, q.log("**** Connection to the backend closed."), + a.wsConnection && (a.wsConnection = null); + } + }, { + key: "onErrorHandler", + value: function(a) { + var b = this; + b.wsConnectionState = l.wsConnectionState.closed, q.log("**** Connection establishment to the backend failed."), + b.callback && b.callback(j.csError.wsChannelFailure, "WebSocket establishment failed.", a); + } + }, { + key: "onMessageHandler", + value: function(a) { + var b = a.data, c = JSON.parse(b); + if ("200 OK" === c.status) { + if ("feedback" === c.event) window.localStorage.removeItem("feedback"); else if (c.event === l.internalFabricEvent.userJoined) { + var d = o.Registry.getConferenceManager().get(decodeURIComponent(c.conferenceID)); + d && d.setUcId(c.ucID), q.log("UcId =", c.ucID), o.Registry.getTransmissionManager().trySend(); + } + } else q.error("Collector error:", c.reason); + } + }, { + key: "setup", + value: function() { + var a = this; + return new Promise(function(b, c) { + if (a.wsConnectionState === l.wsConnectionState.initiated || a.wsConnectionState === l.wsConnectionState.connected) return q.log("setupWebSocketConnection is called when already connected!"), + a.callback && a.callback(j.csError.success, l.csCallBackMessages.wsConnected), void b(); + a.wsConnectionState = l.wsConnectionState.initiated, q.log("creating new WebSocket", a.wsUrl), + a.wsConnection = new WebSocket(a.wsUrl, "echo-protocol"), a.wsConnection.onopen = function() { + b(), a.onOpenHandler(); + }, a.wsConnection.onclose = function() { + a.onCloseHandler(); + }, a.wsConnection.onerror = function(b) { + c(b), a.onErrorHandler(b); + }, a.wsConnection.onmessage = function(b) { + a.onMessageHandler(b); + }; + }); + } + }, { + key: "isReady", + value: function() { + var a = this; + return !(!a.wsConnection || 1 !== a.wsConnection.readyState); + } + }, { + key: "getState", + value: function() { + var a = this; + return a.wsConnection ? a.wsConnection.readyState : -1; + } + }, { + key: "send", + value: function(a) { + this.wsConnection.send(JSON.stringify(a)); + } + } ]), b; + }(r.CollectorConnection); + c.WsCollectorConnection = s; + }, { + "../config/callstatserrors": 31, + "../config/constants": 32, + "../config/settings": 33, + "../utility/csiologger": 87, + "../utility/registry": 94, + "./collectorconnection": 46 + } ], + 57: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f(a, b, c, d, e) { + return new Promise(function(f, g) { + var h = null, i = null, j = null, l = new XMLHttpRequest(), p = n.Registry.getEndpoint().getBrowserName(); + if (!l) return void g(new Error("creating instance failed")); + h = k.getCurrent(), l.open(a, b), p !== m.browserName.msie && (l.timeout = d); + for (var q in c) c.hasOwnProperty(q) && l.setRequestHeader(q, c[q]); + var r = null; + if ("POST" === a) { + if ("application/x-www-form-urlencoded" === c["Content-Type"]) { + var s = []; + for (var t in e) e.hasOwnProperty(t) && s.push(encodeURIComponent(t) + "=" + encodeURIComponent(e[t])); + r = s.join("&"); + } + "application/json" === c["Content-Type"] && (r = JSON.stringify(e)); + } + l.onload = function() { + i = k.getCurrent(), j = i - h; + var a = new o(l, j); + f(a); + }, l.ontimeout = function() { + g(new Error("connection timeout")); + }, l.onreadystatechange = function() { + 4 === l.readyState && 0 === l.status && g(new Error("no server response received")); + }, l.send(r); + }); + } + function g(a, b, c) { + return f("GET", a, b, c, null); + } + function h(a, b, c, d) { + return f("POST", a, b, c, d); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var i = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(); + c.sendGetRequest = g, c.sendPostRequest = h; + var j = a("../utility/timestamps"), k = d(j), l = a("../config/constants"), m = d(l), n = a("../utility/registry"), o = function() { + function a(b, c) { + e(this, a), this.xhr = b, this.elapsed = c; + } + return i(a, [ { + key: "getXhr", + value: function() { + return this.xhr; + } + }, { + key: "getElapsed", + value: function() { + return this.elapsed; + } + } ]), a; + }(); + }, { + "../config/constants": 32, + "../utility/registry": 94, + "../utility/timestamps": 98 + } ], + 58: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.XMLHttpService = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("../utility/sigmoid"), g = a("../utility/csiologger"), h = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(g), i = 100, j = 1e4, k = function() { + function a() { + var b = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "XMLHttpService", c = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : i, e = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : j; + d(this, a), this.name = b, this.minRetryTimeout = c, this.sigmoid = new f.Sigmoid(e - c, 15, .5), + this.reset(); + } + return e(a, [ { + key: "reset", + value: function() { + this.inProgress = !1, this.completed = !1, this.resolveCb && this.rejectCb(new Error(this.name + ": resetting")), + this.resolveCb = null, this.rejectCb = null; + } + }, { + key: "initiate", + value: function() { + var a = this; + if (this.inProgress) return new Promise(function(b, c) { + c(new Error(a.name + ": in progress")); + }); + var b = new Promise(function(b, c) { + a.resolveCb = b, a.rejectCb = c; + }); + return this.inProgress = !0, this.sendRequest(), b; + } + }, { + key: "isCompleted", + value: function() { + return this.completed; + } + }, { + key: "handleSendError", + value: function(a) { + h.log(this.name + ": send next request (" + a + ")"), this.sendNextRequest(); + } + }, { + key: "handleResponseProxy", + value: function(a) { + this.handleResponse(a), this.resetTimeout(); + } + }, { + key: "handleResponse", + value: function(a) { + h.error(this.name + ": handleResponse() not implemented"), this.completeProcess(); + } + }, { + key: "completeProcess", + value: function() { + this.inProgress = !1, this.completed = !0, this.resolveCb.apply(this, arguments); + } + }, { + key: "request", + value: function() { + return h.error(this.name + ": request() not implemented!"), new Promise(function(a, b) { + a(); + }); + } + }, { + key: "sendRequest", + value: function() { + if (this.inProgress) { + var a = this.request(); + a && a.then(this.handleResponseProxy.bind(this), this.handleSendError.bind(this)); + } + } + }, { + key: "sendNextRequest", + value: function() { + setTimeout(this.sendRequest.bind(this), this.getTimeout()); + } + }, { + key: "resetTimeout", + value: function() { + this.sigmoid.reset(); + } + }, { + key: "getTimeout", + value: function() { + return this.minRetryTimeout + this.sigmoid.getActual(); + } + } ]), a; + }(); + c.XMLHttpService = k; + }, { + "../utility/csiologger": 87, + "../utility/sigmoid": 96 + } ], + 59: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Measurement = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./resolution"), g = a("./validator"), h = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(g), i = function() { + function a() { + d(this, a), this.pcHash = null, this.ssrc = null, this.streamType = null, this.mediaType = null, + this.resolution = null, this.frameRateReceived = null, this.frameHeight = null, + this.frameWidth = null, this.droppedFramesNum = null, this.rtt = null, this.jitter = null, + this.lostPackets = -1, this.receivedPackets = -1, this.sentPackets = -1, this.discardedPackets = -1, + this.sentBytes = -1, this.receivedBytes = -1, this.track = null, this.fractionLost = 0; + } + return e(a, null, [ { + key: "make", + value: function(b, c, d, e, g, i, j, k, l, m, n, o, p, q, r, s, t) { + var u = new a(), v = function(a, b) { + -1 === [ void 0, null ].indexOf(b) && (u[a] = b); + }; + return v("pcHash", b), v("ssrc", c), v("streamType", d), v("mediaType", e), v("frameRateReceived", g), + v("frameHeight", h.checkForNan(parseInt(i, 10))), v("frameWidth", h.checkForNan(parseInt(j, 10))), + v("droppedFramesNum", k), v("rtt", l), v("jitter", m), v("lostPackets", n), v("receivedPackets", o), + v("sentPackets", p), v("discardedPackets", q), v("sentBytes", r), v("receivedBytes", s), + v("track", t), u.resolution = void 0 !== g && void 0 !== j && void 0 !== i && j > 0 && i > 0 ? new f.Resolution(j, i, g) : null, + u; + } + } ]), e(a, [ { + key: "getPcHash", + value: function() { + return this.pcHash; + } + }, { + key: "getSSRC", + value: function() { + return this.ssrc; + } + }, { + key: "getStreamType", + value: function() { + return this.streamType; + } + }, { + key: "getMediaType", + value: function() { + return this.mediaType; + } + }, { + key: "getResolution", + value: function() { + return this.resolution ? this.resolution.toString() : null; + } + }, { + key: "getFrameRateReceived", + value: function() { + return this.frameRateReceived; + } + }, { + key: "getFrameHeight", + value: function() { + return this.frameHeight; + } + }, { + key: "getFrameWidth", + value: function() { + return this.frameWidth; + } + }, { + key: "getDroppedFramesNum", + value: function() { + return this.droppedFramesNum; + } + }, { + key: "getJitter", + value: function() { + return this.jitter; + } + }, { + key: "getRTT", + value: function() { + return this.rtt; + } + }, { + key: "getLostPackets", + value: function() { + return this.lostPackets; + } + }, { + key: "getDiscardedPackets", + value: function() { + return this.discardedPackets; + } + }, { + key: "getReceivedPackets", + value: function() { + return this.receivedPackets; + } + }, { + key: "getSentPackets", + value: function() { + return this.sentPackets; + } + }, { + key: "getSentBytes", + value: function() { + return this.sentBytes; + } + }, { + key: "getReceivedBytes", + value: function() { + return this.receivedBytes; + } + }, { + key: "setFractionLost", + value: function(a) { + this.fractionLost = void 0 === a ? null : a; + } + }, { + key: "getFractionLost", + value: function() { + return this.fractionLost; + } + }, { + key: "extractTrack", + value: function() { + var a = this.track; + return this.track = null, a; + } + }, { + key: "toString", + value: function() { + return "pcHash: " + this.pcHash + ", ssrc: " + this.ssrc + ", streamType: " + this.streamType + ", mediaType: " + this.mediaType + ", frameRateReceived: " + this.frameRateReceived + ", frameHeight: " + this.frameHeight + ", frameWidth: " + this.frameWidth + ", droppedFramesNum: " + this.droppedFramesNum + ", rtt: " + this.rtt + ", jitter: " + this.jitter + ", lostPackets: " + this.lostPackets + ", receivedPackets: " + this.receivedPackets + ", sentPackets: " + this.sentPackets + ", discardedPackets: " + this.discardedPackets + ", sentBytes: " + this.sentBytes + ", receivedBytes: " + this.receivedBytes; + } + } ]), a; + }(); + c.Measurement = i; + }, { + "./resolution": 67, + "./validator": 82 + } ], + 60: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.CPULimitationObserver = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../../config/constants"), h = d(g), i = a("../../utility/timestamps"), j = d(i), k = function() { + function a() { + e(this, a), this.ewmaDiscardedPackets = 0, this.ewmaLostPackets = 0, this.ewmaDroppedFrames = 0, + this.last = 0, this.noticed = 0; + } + return f(a, [ { + key: "test", + value: function(a) { + var b = a.discardedPackets, c = a.lostPackets; + if (!c || c < 1 || !b || b < 1) return !1; + if (0 === this.last) return this.last = j.getCurrent(), this.ewmaLostPackets = c, + this.ewmaDiscardedPackets = b, !1; + var d = j.getCurrent(), e = Math.max(d - this.last, 1), f = Math.min((5e3 - e) / 5e3, .9), g = a.droppedFrames; + return this.ewmaLostPackets = this.ewmaLostPackets * f + c, this.ewmaDroppedFrames = this.ewmaDroppedFrames * f + g, + this.ewmaDiscardedPackets = this.ewmaDiscardedPackets * f + b, !(!g || g < 1) && (!(1 < this.ewmaLostPackets || 1 < this.ewmaDiscardedPackets) && (!(d - this.noticed < 1e4) && (!(this.ewmaDroppedFrames < 1) && (this.noticed = d, + !0)))); + } + } ]), a; + }(), l = function() { + function a(b) { + e(this, a), this.notifyCallback = b, this.inbVideoTesters = new Map(); + } + return f(a, [ { + key: "accept", + value: function(a) { + for (var b = a.filter(function(a) { + return a.getMediaType() === h.mediaType.video && a.getStreamType() === h.streamType.inbound; + }), c = 0; c < b.length; ++c) { + var d = b[c]; + this.checkInboundVideo(d); + } + } + }, { + key: "checkInboundVideo", + value: function(a) { + var b = a.peek(), c = a.getSSRC(); + if (this.inbVideoTesters.has(c) || this.inbVideoTesters.set(c, new k()), this.inbVideoTesters.get(c).test(b)) { + var d = { + reason: h.limitationType.cpu, + ssrc: c + }; + this.notifyCallback(d); + } + } + }, { + key: "toString", + value: function() { + return "CPULimitationObserver"; + } + } ]), a; + }(); + c.CPULimitationObserver = l; + }, { + "../../config/constants": 32, + "../../utility/timestamps": 98 + } ], + 61: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.OneWayMediaObserver = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../../config/constants"), h = d(g), i = a("../onewaymediadisruption"), j = a("../../utility/timestamps"), k = d(j), l = function() { + function a(b) { + e(this, a), this.notifierCallback = b, this.inbOneWayAudioDisruption = { + sent: !1, + started: 0, + hasTrafficTs: 0 + }, this.outbOneWayAudioDisruption = { + sent: !1, + started: 0, + hasTrafficTs: 0 + }; + } + return f(a, [ { + key: "accept", + value: function(a) { + var b = a.filter(function(a) { + return a.getMediaType() == h.mediaType.audio && a.getStreamType() === h.streamType.inbound; + }), c = a.filter(function(a) { + return a.getMediaType() == h.mediaType.audio && a.getStreamType() === h.streamType.outbound; + }), d = [ this.getInbOneWayAudioDisruption(b, c), this.getOutbOneWayAudioDisruption(b, c) ], e = d.filter(function(a) { + return null !== a; + }); + 0 < e.length && this.notifierCallback(e); + } + }, { + key: "toString", + value: function() { + return "DisruptionObserver"; + } + }, { + key: "getInbOneWayAudioDisruption", + value: function(a, b) { + var c = this.inbOneWayAudioDisruption; + if (c.sent) return null; + var d = b.filter(function(a) { + return 0 === a.getStartTime(); + }).length < 1, e = b.filter(function(a) { + return !a.hasTraffic(); + }).length < 1; + if (!d || e) return null; + var f = a.filter(function(a) { + return !a.hasTraffic(); + }).length < 1; + return 0 < a.length && f ? (c.started = 0, null) : 0 === c.started ? (c.started = k.getCurrent(), + null) : k.getCurrent() - 5e3 < c.started ? null : (c.sent = !0, new i.OneWayMediaDisruption(h.oneWayMediaTypes.audio)); + } + }, { + key: "getOutbOneWayAudioDisruption", + value: function(a, b) { + var c = this.outbOneWayAudioDisruption; + if (c.sent) return null; + var d = a.filter(function(a) { + return 0 === a.getStartTime(); + }).length < 1, e = a.filter(function(a) { + return !a.hasTraffic(); + }).length < 1; + if (!d || !e) return null; + var f = b.filter(function(a) { + return !a.hasTraffic(); + }).length < 1; + return 0 < b.length && f ? (c.started = 0, null) : 0 === c.started ? (c.started = k.getCurrent(), + null) : k.getCurrent() - 5e3 < c.started ? null : (c.sent = !0, new i.OneWayMediaDisruption(h.oneWayMediaTypes.audio)); + } + } ]), a; + }(); + c.OneWayMediaObserver = l; + }, { + "../../config/constants": 32, + "../../utility/timestamps": 98, + "../onewaymediadisruption": 65 + } ], + 62: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.QPSumObserver = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../../config/constants"), h = d(g), i = a("../../utility/timestamps"), j = d(i), k = function() { + function a(b) { + e(this, a), this.lastQpSum = null, this.qpAvg = null, this.noticed = 0; + } + return f(a, [ { + key: "test", + value: function(a) { + var b = a.getTrack(); + if (!b || !b.data || !b.data.qpSum) return !1; + if (!this.lastQpSum) return this.lastQpSum = b.data.qpSum, !1; + var c = b.data.qpSum - this.lastQpSum; + if (this.lastQpSum = b.data.qpSum, null === this.qpAvg) this.qpAvg = c; else { + this.qpAvg = .2 * c + .8 * this.qpAvg; + } + var d = Math.max(2 * this.qpAvg, 1); + if (c < this.qpAvg + d) return !1; + var e = j.getCurrent(); + return this.noticed < e - 1e4; + } + } ]), a; + }(), l = function() { + function a(b) { + e(this, a), this.notifyCallback = b, this.testers = new Map(); + } + return f(a, [ { + key: "accept", + value: function(a) { + for (var b = 0; b < a.length; ++b) { + var c = a[b]; + if (c.getMediaType() === h.mediaType.video) { + var d = c.getSSRC(); + this.testers.has(d) || this.testers.set(d, new k(c)); + if (this.testers.get(d).test(c)) { + var e = { + reason: h.qualityDisruptionTypes.qpchange + }; + this.notifyCallback(e); + } + } + } + } + }, { + key: "toString", + value: function() { + return "QPSumObserver"; + } + } ]), a; + }(); + c.QPSumObserver = l; + }, { + "../../config/constants": 32, + "../../utility/timestamps": 98 + } ], + 63: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.SendingTrigger = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../../utility/timestamps"), h = d(g), i = a("../validator"), j = d(i), k = 1e3, l = 3e4, m = function() { + function a(b, c, d) { + e(this, a), this.last = null, this.actual = 0, this.name = b, this.alpha = c, this.supplier = d; + } + return f(a, [ { + key: "update", + value: function(a) { + if (null === this.last) return void (this.last = a); + var b = Math.abs(a - this.last); + this.actual = b * this.alpha + this.actual * (1 - this.alpha), this.last = a; + } + }, { + key: "doTest", + value: function(a) { + var b = this.last; + return this.update(a), null !== b && b + this.supplier(this.actual) < a; + } + } ]), a; + }(), n = function() { + function a() { + e(this, a); + var b = this; + this.marginFactor = 1, this.rttTester = new m("RTT Tester", .2, function(a) { + return Math.max(50, a) * b.marginFactor; + }), this.throughputTester = new m("Throughput Tester", .1, function(a) { + return Math.max(100, a) * b.marginFactor; + }), this.FLTester = new m("FL Tester", .1, function(a) { + return Math.max(.2, a) * b.marginFactor; + }), this.lastDecreased = h.getCurrent(); + } + return f(a, [ { + key: "test", + value: function(a) { + var b = a.peek(); + if (!b) return !1; + var c = a.getTrack(), d = c.data, e = b.getRTT(), f = j.checkForNan(parseInt(d.csioIntBRKbps, 10)), g = b.getFractionLost(); + if (this.rttTester.doTest(e) || this.throughputTester.doTest(f) || this.FLTester.doTest(g)) return this.marginFactor = Math.min(2 * this.marginFactor, 15), + !0; + var i = h.getCurrent(); + return 3e3 < i - this.lastChanged && (this.marginFactor = Math.max(this.marginFactor - .5, 1), + this.lastDecreased = i), !1; + } + } ]), a; + }(), o = function() { + function a(b) { + e(this, a), this.notifyCallback = b, this.minInterval = k, this.maxInterval = l, + this.notified = 0, this.testers = new Map(); + } + return f(a, [ { + key: "setup", + value: function(a, b) { + this.minInterval = a, this.maxInterval = b; + } + }, { + key: "accept", + value: function(a) { + var b = h.getCurrent(), c = b - this.notified; + if (this.minInterval === this.maxInterval) return void (this.minInterval <= c && (this.notifyCallback(), + this.notified = b)); + if (!(c < this.minInterval)) { + if (c < this.maxInterval) { + if (!1 === this.doSend(a)) return; + } + this.notifyCallback(), this.notified = b; + } + } + }, { + key: "setIntervals", + value: function(a, b) { + this.minInterval = a, this.maxInterval = b; + } + }, { + key: "toString", + value: function() { + return "SendingTrigger"; + } + }, { + key: "doSend", + value: function(a) { + for (var b = 0; b < a.length; ++b) { + var c = a[b], d = c.getSSRC(); + this.testers.has(d) || this.testers.set(d, new n()); + if (this.testers.get(d).test(c)) return !0; + } + return !1; + } + } ]), a; + }(); + c.SendingTrigger = o; + }, { + "../../utility/timestamps": 98, + "../validator": 82 + } ], + 64: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.ThroughputObserver = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../../config/constants"), h = d(g), i = a("../../utility/timestamps"), j = d(i), k = function() { + function a(b) { + e(this, a), this.notifierCallback = b, this.observations = new Map(); + } + return f(a, [ { + key: "accept", + value: function(a) { + var b = a.filter(function(a) { + return a.getMediaType() === h.mediaType.video && a.getStreamType() === h.streamType.outbound; + }); + if (!(b.length < 1)) { + var c = this; + b.forEach(function(a) { + c.observe(a); + }); + } + } + }, { + key: "toString", + value: function() { + return "ThroughputObserver"; + } + }, { + key: "getObservations", + value: function(a) { + if (this.observations.has(a)) return this.observations.get(a); + var b = { + ssrc: 0, + started: 0, + max: 0, + maxTs: 0, + stable: 0, + stableTs: 0, + ready: !1, + maxVerified: !1, + stableVerified: !1 + }; + return this.observations.set(a, b), this.observations.get(a); + } + }, { + key: "observe", + value: function(a) { + var b = a.getSSRC(), c = this.getObservations(b), d = j.getCurrent(); + if (!0 !== c.ready) { + if (0 === c.started) return c.ssrc = b, void (c.started = d); + var e = a.getTrack(), f = e.data, g = f.csioIntBRKbps, h = Math.min(50, .05 * g); + if (c.max < g ? (c.max = g, c.maxTs = d) : 1e4 < d - c.maxTs && (c.maxVerified = !0), + !(d - c.started < 15e3) && (g - h < f.csioAvgBRKbps && f.csioAvgBRKbps < g + h && (c.stableTs = d, + c.stable = g, c.stableVerified = !0), c.stableVerified && c.maxVerified)) { + var i = { + ssrc: String(c.ssrc), + maxsendingKBitrate: c.max, + timeToMaxSendingKBitrate: c.maxTs - c.started, + stablesendingKBitrate: c.stable, + timeToStableSendingKBitrate: c.stableTs - c.started + }; + this.notifierCallback(i), c.ready = !0; + } + } + } + } ]), a; + }(); + c.ThroughputObserver = k; + }, { + "../../config/constants": 32, + "../../utility/timestamps": 98 + } ], + 65: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a(b) { + var c = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : "0"; + d(this, a), this.mediaType = b, this.ssrc = c; + } + return e(a, [ { + key: "getContent", + value: function() { + var a = this; + return { + mediaType: a.mediaType, + ssrc: a.ssrc + }; + } + } ]), a; + }(); + c.OneWayMediaDisruption = f; + }, {} ], + 66: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a(b, c, e, f, g, h) { + d(this, a), this.candidatePair = b, this.codec = c, this.pcHash = e, this.trackStats = f, + this.transportStats = g, this.measurements = h; + } + return e(a, [ { + key: "getCandidatePair", + value: function() { + return this.candidatePair; + } + }, { + key: "getCodec", + value: function() { + return this.codec; + } + }, { + key: "getPcHash", + value: function() { + return this.pcHash; + } + }, { + key: "getTrackStats", + value: function() { + return this.trackStats; + } + }, { + key: "getTransportStats", + value: function() { + return this.transportStats; + } + }, { + key: "getMeasurements", + value: function() { + return this.measurements; + } + } ]), a; + }(); + c.PcStats = f; + }, {} ], + 67: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a(b, c, e) { + d(this, a), this.width = b, this.height = c, this.frameRate = e; + } + return e(a, [ { + key: "getWidth", + value: function() { + return this.width; + } + }, { + key: "getHeight", + value: function() { + return this.height; + } + }, { + key: "getFrameRate", + value: function() { + return this.frameRate; + } + }, { + key: "toString", + value: function() { + return this.width && this.height && this.frameRate ? this.width.toString() + "X" + this.height.toString() + "X" + this.frameRate.toString() : null; + } + } ]), a; + }(); + c.Resolution = f; + }, {} ], + 68: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function g(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.StatsAdapter = c.StatsAdapterIO = void 0; + var h = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), i = a("../config/constants"), j = d(i), k = a("../collections/component"), l = a("../utility/registry"), m = a("../utility/hash"), n = d(m), o = c.StatsAdapterIO = { + RawStatsIn: "RawStatsIn", + RawStatsOut: "RawStatsOut", + UnprocessedOut: "UnprocessedOut" + }, p = function(a) { + function b(a, c) { + e(this, b); + var d = f(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, "StatsAdapter")); + return d.bindPort(o.RawStatsIn, d.receiveRawData, d), d.declarePort(o.RawStatsOut), + d.declarePort(o.UnprocessedOut), d.codeBase = a, d.browser = c, d; + } + return g(b, a), h(b, [ { + key: "receiveRawData", + value: function(a, b) { + if (a) { + var c = this.extractRawStats(a); + if (c) { + window && window.csioReactNative && (c = this.removeValues(c)), this.isConnected(o.UnprocessedOut) && this.transmit(o.UnprocessedOut, c); + var d = this.processRawStats(c, b); + if (d && d.transportStats) for (var e = 0; e < d.transportStats.length; e++) d.transportStats[e].hash = this.getTransportHash(d.transportStats[e]); + d && d.transportStats && this.checkTransportStatsUpdates(d.transportStats, b), d && d.trackStats && (d = this.backFillTrackStats(d)), + d && d.transportStats && d.candidatePair && (d = this.backFillCandidatePairStats(d)), + d.pcHash = b, this.transmit(o.RawStatsOut, d); + } + } + } + }, { + key: "removeValues", + value: function(a) { + for (var b = 0; b < a.length; ++b) { + var c = a[b]; + if (c && c.values) { + for (var d = 0; d < c.values.length; ++d) Object.assign(c, c.values[d]); + delete c.values; + } + } + return a; + } + }, { + key: "getIceCandidates", + value: function(a) { + if (!a) return null; + var b = this.extractRawStats(a); + return this.processRawStatsForIceInfo(b); + } + }, { + key: "extractRawStats", + value: function(a) { + var b = []; + if (a && a.result) b = a.result(); else if (a && a.forEach) a.forEach(function(a) { + b.push(a); + }); else for (var c in a) a.hasOwnProperty(c) && b.push(a[c]); + return b; + } + }, { + key: "normalizeIceCandidates", + value: function(a) { + for (var b = 0; b < a.length; b += 1) { + var c = a[b]; + c.transport = c.protocol ? c.protocol : "udp", c.ip = c.ip ? c.ip : c.ipAddress, + c.port = c.portNumber ? Number(c.portNumber) : c.port, "ssltcp" === c.transport && (c.transport = "tcp"); + } + return a; + } + }, { + key: "normalizeCanidatePairs", + value: function(a) { + for (var b = 0; b < a.length; b += 1) { + var c = a[b]; + "in-progress" === c.state && (c.state = "inprogress"), c.state || (c.state = "succeeded"), + c.nominated || (c.nominated = "true" === c.googActiveConnection), c.priority || (c.priority = 123); + } + return a; + } + }, { + key: "processRawStatsForIceInfo", + value: function(a) { + var b = [], c = [], d = [], e = void 0; + if (!a) return null; + for (var f = 0; f < a.length; ++f) { + var g = this.getParsedStats(a[f]), h = this.statsClassifier(g); + if (h.candidatePair) d.push(h.candidatePair); else if (h.transportStats) { + if ("transport" === h.transportStats.type) { + e = h.transportStats.selectedCandidatePairId; + continue; + } + d.push(h.transportStats); + } else h.localCandidate ? b.push(h.localCandidate) : h.remoteCandidate && c.push(h.remoteCandidate); + } + if (e) for (var i = 0; i < d.length; ++i) d[i].id === e && (d[i].googActiveConnection = "true"); + return { + localIceCandidates: this.normalizeIceCandidates(b), + remoteIceCandidates: this.normalizeIceCandidates(c), + iceCandidatePairs: this.normalizeCanidatePairs(d) + }; + } + }, { + key: "processRawStats", + value: function(a, b) { + var c = {}, d = {}, e = {}; + c.tracks = [], c.candidatePair = [], c.transportStats = [], c.trackStats = [], c.codec = []; + for (var f = 0; f < a.length; f++) { + var g = this.getParsedStats(a[f]), h = this.statsClassifier(g); + h.tracks ? c.tracks.push(h.tracks) : h.candidatePair ? c.candidatePair.push(h.candidatePair) : h.transportStats ? this.codeBase !== j.codeBaseType.firefox ? (parseInt(h.transportStats.bytesReceived, 10) > 0 || parseInt(h.transportStats.bytesSent, 10) > 0) && (c.transportStats.push(h.transportStats), + "true" !== h.transportStats.googActiveConnection && !0 !== h.transportStats.googActiveConnection || (c.activeConnectionIndex = h.transportStats.length)) : "true" !== h.transportStats.selected && !0 !== h.transportStats.selected || (c.transportStats.push(h.transportStats), + c.activeConnectionIndex = h.transportStats.length) : h.bwe ? c.bwe = h.bwe : h.trackStats ? c.trackStats.push(h.trackStats) : h.codec ? c.codec.push(h.codec) : h.localCandidate ? d[h.localCandidate.id] = h.localCandidate : h.remoteCandidate && (e[h.remoteCandidate.id] = h.remoteCandidate); + } + if (c.tracks) { + var i = l.Registry.getConferenceManager().getConferenceForPcHash(b), k = void 0; + i && (k = i.getPeerConnectionManager().getPcHandlerByHash(b)), c.tracks.forEach(function(a) { + var b = k.getSSRCInfo(a.data.ssrc); + void 0 !== b && b.localStartTime || k && (k.updateSDP(c.tracks), b = k.getSSRCInfo(a.data.ssrc)), + b && (a.cname = b.cname, a.msid = b.msid, a.associatedVideoTag = b.associatedVideoTag, + a.usageLabel = b.usageLabel); + }); + } + return c.transportStats && this.codeBase === j.codeBaseType.firefox && (c.transportStats = this.getAddressInfoFromCandidates(c.transportStats, d, e)), + c; + } + }, { + key: "getParsedStats", + value: function(a) { + var b = {}; + if (a.timestamp instanceof Date && (b.timestamp = a.timestamp.getTime().toString()), + a.type && (b.type = a.type), a.names) { + for (var c = a.names(), d = 0; d < c.length; ++d) b[c[d]] = a.stat(c[d]); + a.id && (b.id = a.id); + } else Object.assign(b, a); + if (b.values) { + for (var e = 0; e < b.values.length; ++e) Object.assign(b, b.values[e]); + delete b.values; + } + return b; + } + }, { + key: "statsClassifier", + value: function(a) { + var b = {}, c = function() { + for (var b = arguments.length, c = Array(b), d = 0; d < b; d++) c[d] = arguments[d]; + return -1 !== c.indexOf(a.type); + }, d = c("inbound-rtp", "inboundrtp"), e = "true" === a.isRemote || !0 === a.isRemote; + return d || c("outbound-rtp", "outboundrtp") ? (b.tracks = {}, b.tracks.data = a, + b.tracks.ssrc = a.ssrc, b.tracks.streamType = d ? "inbound" : "outbound", b.tracks.reportType = "local", + void 0 !== a.isRemote && (b.tracks.reportType = e ? "remote" : "local")) : c("candidatepair") && a.selected ? b.transportStats = a : c("localcandidate", "local-candidate") ? b.localCandidate = a : c("remotecandidate", "remote-candidate") ? b.remoteCandidate = a : c("transport", "googCandidatePair") ? b.transportStats = a : c("VideoBwe") ? b.bwe = a : c("track") ? b.trackStats = a : c("candidate-pair") ? b.candidatePair = a : c("codec") ? b.codec = a : c("ssrc") && (b.tracks = {}, + b.tracks.data = a, b.tracks.ssrc = a.ssrc, b.tracks.reportType = "local", b.tracks.streamType = a.bytesSent ? "outbound" : "inbound"), + b; + } + }, { + key: "getAddressInfoFromCandidates", + value: function(a, b, c) { + for (var d = void 0, e = void 0, f = 0; f < a.length; f++) d = b[a[f].localCandidateId], + e = c[a[f].remoteCandidateId], d && e && (a[f].localAddr = d.ipAddress + ":" + d.portNumber, + a[f].remoteAddr = e.ipAddress + ":" + e.portNumber, a[f].localAddrType = d.candidateType, + a[f].remoteAddrType = e.candidateType, a[f].transportType = d.transport); + return a; + } + }, { + key: "getTransportHash", + value: function(a) { + var b = void 0; + return a && (this.codeBase === j.codeBaseType.chrome ? a.googLocalAddress ? (b = a.googLocalAddress, + b.concat(":", a.googRemoteAddress)) : a.selectedCandidatePairId && (b = a.selectedCandidatePairId) : this.codeBase === j.codeBaseType.firefox && (b = a.localAddr, + b.concat(":", a.remoteAddr))), n.generateHash(b); + } + }, { + key: "backFillTrackStats", + value: function(a) { + for (var b = a.tracks.length, c = void 0, d = void 0, e = void 0, f = 0; f < b; f++) c = a.tracks[f], + c.data.trackId && (d = this.getStatsForId(a.trackStats, c.data.trackId)) && (a.tracks[f].data = this.mergeObjects(a.tracks[f].data, d)), + c.data.codecId && (e = this.getStatsForId(a.codec, c.data.codecId)) && (a.tracks[f].data = this.mergeObjects(a.tracks[f].data, e)); + return a; + } + }, { + key: "backFillCandidatePairStats", + value: function(a) { + for (var b = a.transportStats.length, c = void 0, d = void 0, e = 0; e < b; e++) d = a.transportStats[e], + d.selectedCandidatePairId && (c = this.getStatsForId(a.candidatePair, d.selectedCandidatePairId)) && (a.transportStats[e] = this.mergeObjects(a.transportStats[e], c)); + return a; + } + }, { + key: "mergeObjects", + value: function(a, b) { + for (var c in b) b.hasOwnProperty(c) && "id" !== c && "type" !== c && (a[c] = b[c]); + return a; + } + }, { + key: "getStatsForId", + value: function(a, b) { + if (a) { + var c = a.filter(function(a) { + return a.id === b; + }); + if (c.length > 0) return c[0]; + } + } + }, { + key: "formatRelayType", + value: function(a) { + var b = "None"; + switch (a) { + case 0: + b = "TURN/TLS"; + break; + + case 1: + b = "TURN/TCP"; + break; + + case 2: + b = "TURN/UDP"; + } + return b; + } + }, { + key: "getRelayType", + value: function(a, b) { + var c = this, d = void 0, e = function(b) { + if (b.typePreference) { + var e = b.typePreference >> 24; + return "rtp" === b.protocol && b.address === a && (e >= 0 && e <= 2 && (d = c.formatTypePreference(e)), + !0); + } + return !1; + }; + return b.getIceCandidates().some(e), d; + } + }, { + key: "getTransportInfo", + value: function(a, b) { + for (var c = {}, d = !1, e = 0; e < a.length; e++) { + var f = a[e]; + if (navigator.mozGetUserMedia && "candidatepair" === f.type && ("true" === f.selected || !0 === f.selected)) { + c.foundActive = !0, c.localAddr = f.localAddr, c.remoteAddr = f.remoteAddr, c.localAddrType = f.localAddrType, + c.remoteAddrType = f.remoteAddrType, c.transportType = f.transportType, c.localCandidateId = f.localCandidateId, + c.remoteCandidateId = f.remoteCandidateId; + break; + } + if ("googCandidatePair" === f.type && ("true" === f.googActiveConnection || !0 === f.googActiveConnection)) { + c.foundActive = !0, c.localAddr = f.googLocalAddress, c.remoteAddr = f.googRemoteAddress, + c.localAddrType = f.googLocalCandidateType, c.remoteAddrType = f.googRemoteCandidateType, + c.transportType = f.googTransportType; + break; + } + if ("transport" === f.type) { + d = !0, f.selectedCandidatePairId && (c.selectedCandidatePairId = f.selectedCandidatePairId); + break; + } + } + return d && c.localAddr && (c.ipv6 = 0 === c.localAddr.indexOf("["), c.relayType = getRelayType(c.localAddr, b)), + c; + } + }, { + key: "sendFabricTransportSwitch", + value: function(a, b) { + a.sendFabricTransportSwitch(b); + } + }, { + key: "checkTransportStatsUpdates", + value: function(a, b) { + var c = l.Registry.getConferenceManager().getConferenceForPcHash(b); + if (c) { + var d = c.getPeerConnectionManager().getPcHandlerByHash(b); + if (d) { + var e = this.getTransportInfo(a, d), f = d.getTransportInfo(); + f && (f.localAddr === e.localAddr && f.remoteAddr === e.remoteAddr && f.transportType === e.transportType && f.selectedCandidatePairId === e.selectedCandidatePairId && f.localCandidateId === e.localCandidateId && f.remoteCandidateId === e.remoteCandidateId || (d.setTransportInfo(e), + this.sendFabricTransportSwitch(d, e.relayType))); + } + } + } + } ]), b; + }(k.Component); + c.StatsAdapter = p; + }, { + "../collections/component": 25, + "../config/constants": 32, + "../utility/hash": 91, + "../utility/registry": 94 + } ], + 69: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function f(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.StatsAssembler = c.StatsAssemblerIO = void 0; + var g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = a("../collections/component"), i = c.StatsAssemblerIO = { + StatsTupleIn: "StatsTupleIn", + CallstatsOut: "CallstatsOut" + }, j = function(a) { + function b() { + d(this, b); + var a = e(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, "StatsAssembler")); + return a.pcHashes = [], a.bindPort(i.StatsTupleIn, a.receiveStats, a), a.declarePort(i.CallstatsOut), + a; + } + return f(b, a), g(b, [ { + key: "receiveStats", + value: function(a) { + for (var b = this, c = 0; c < a.tracks.length; c++) { + (function(c) { + var d = a.tracks[c]; + if (b.pcHashes.find(function(a) { + return a === d.pcHash; + })) return "continue"; + b.pcHashes.push(d.pcHash); + })(c); + } + for (var d = a.getTransportStats(), c = 0; c < this.pcHashes.length; c++) { + var e = this.pcHashes[c], f = {}; + f.codec = a.getCodec(), f.trackStats = a.getTrackStats(), f.tracks = []; + for (var g = 0; g < a.tracks.length; g++) { + var h = a.tracks[g]; + h.pcHash === e && f.tracks.push(h); + } + var j = d.get(e); + 1 == j.length ? f.Transport = j[0] : f.Transport = j, this.transmit(i.CallstatsOut, e, f); + } + } + } ]), b; + }(h.Component); + c.StatsAssembler = j; + }, { + "../collections/component": 25 + } ], + 70: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.StatsCallbackBuilder = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("../utility/registry"), g = function() { + function a() { + d(this, a), this.callback = null; + } + return e(a, [ { + key: "setCallback", + value: function(a) { + this.callback = a; + } + }, { + key: "buildStats", + value: function(a, b) { + this.callback && this.buildFromUnifiedFormat(a, b); + } + }, { + key: "getConnectionState", + value: function() { + return !0 === navigator.onLine ? "online" : "offline"; + } + }, { + key: "buildConferenceUrl", + value: function(a) { + var b = a.getConferenceId(), c = f.Registry.getConferenceManager().get(b); + return c ? c.getUrl() : null; + } + }, { + key: "buildFromUnifiedFormat", + value: function(a, b) { + var c = {}; + c.connectionState = this.getConnectionState(), c.conferenceURL = this.buildConferenceUrl(b), + c.fabricState = b.getPcState(), c.streams = {}; + for (var d = 0; d < a.length; d++) { + var e = a[d]; + if ("inbound-rtp" === e.type || "outbound-rtp" === e.type) { + var f = { + ssrc: e.ssrc, + statsType: e.type, + fractionLoss: e.csioIntFL, + bitrate: e.csioIntBRKbps, + quality: e.csioMark, + mediaType: e.csioMediaType, + jitter: e.jitter, + audioOutputLevel: e.audioOutputLevel, + audioIntputLevel: e.audioIntputLevel, + audioLevel: e.audioLevel, + averageRTT: e.csioAvgRtt, + averageJitter: e.csioAvgJitter, + packetLossPercentage: e.csioPktLossPercentage, + rtt: e.roundTripTime, + remoteUserID: b.getRemoteId() + }, g = b.getSSRCInfo(e.ssrc + ""); + g && (f.cname = g.cname, f.msid = g.msid, f.usageLabel = g.usageLabel, f.associatedVideoTag = g.associatedVideoTag), + e.hasOwnProperty("googRtt") && (f.rtt = e.googRtt), e.hasOwnProperty("mozRtt") && (f.rtt = e.mozRtt), + e.hasOwnProperty("googJitterReceived") && (f.jitter = e.googJitterReceived), c.streams[e.ssrc] = f; + } + } + this.callback(c); + } + } ]), a; + }(); + c.StatsCallbackBuilder = g; + }, { + "../utility/registry": 94 + } ], + 71: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function g(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.StatsMonitor = c.StatsMonitorIO = void 0; + var h = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), i = a("../collections/component"), j = a("./tracksmonitor"), k = a("./transportsmonitor"), l = a("./statstuple"), m = a("../utility/registry"), n = a("./monitorhooks/sendingtrigger"), o = a("./monitorhooks/onewaymediaobserver"), p = a("./monitorhooks/throughputobserver"), q = a("./monitorhooks/cpulimitationobserver"), r = a("./monitorhooks/qpsumobserver"), s = a("../config/constants"), t = d(s), u = a("../utility/csiologger"), v = d(u), w = c.StatsMonitorIO = { + PcStatsTupleIn: "PcStatsTupleIn", + StatsTupleOut: "StatsTupleOut" + }, x = function(a) { + function b(a) { + e(this, b); + var c = f(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, "StatsMonitor")); + return c.bindPort(w.PcStatsTupleIn, c.receive, c), c.declarePort(w.StatsTupleOut), + c.lastPcStats = null, c.lastPcHash = null, c.tracksmonitor = new j.TracksMonitor(), + c.transportsmonitor = new k.TransportsMonitor(a), c.candidatepairs = new Map(), + c.monitorhooks = [], c.sendingTrigger = new n.SendingTrigger(c.sendStatsTuple.bind(c)), + c.oneWayMediaObserver = new o.OneWayMediaObserver(c.sendDisruptions.bind(c)), c.throughputObserver = new p.ThroughputObserver(c.sendThroughputObservations.bind(c)), + c.cpuLimitationObserver = new q.CPULimitationObserver(c.sendCPULimitationObservations.bind(c)), + c.qpSumObserver = new r.QPSumObserver(c.sendQPSumDistortions.bind(c)), c.setupHooks(), + c; + } + return g(b, a), h(b, [ { + key: "setupHooks", + value: function() { + this.monitorhooks.push(this.sendingTrigger.accept.bind(this.sendingTrigger)), this.monitorhooks.push(this.oneWayMediaObserver.accept.bind(this.oneWayMediaObserver)), + this.monitorhooks.push(this.throughputObserver.accept.bind(this.throughputObserver)), + this.monitorhooks.push(this.cpuLimitationObserver.accept.bind(this.cpuLimitationObserver)), + this.monitorhooks.push(this.qpSumObserver.accept.bind(this.qpSumObserver)); + } + }, { + key: "setIntervals", + value: function(a, b) { + this.sendingTrigger.setup(a, b); + } + }, { + key: "receive", + value: function(a) { + var b = a.getPcHash(), c = a.getMeasurements(); + this.candidatepairs.set(b, a.getCandidatePair()), this.transportsmonitor.set(b, a.getTransportStats()); + for (var d = 0; d < c.length; d++) { + var e = c[d], f = this.tracksmonitor.getMonitor(e); + f ? f.add(e) : v.warn("No monitor for ssrc " + e.getSSRC()); + } + this.lastPcStats = a, this.lastPcHash = b; + for (var g = this.tracksmonitor.getMonitors(), h = this.monitorhooks, i = 0; i < h.length; i++) { + (0, h[i])(g); + } + } + }, { + key: "getCandidatePairs", + value: function() { + var a = []; + return this.candidatepairs.forEach(function(b, c) { + var d = [ c, b ]; + a.push(d); + }), a; + } + }, { + key: "sendStatsTuple", + value: function() { + var a = new l.StatsTuple(this.getCandidatePairs(), this.lastPcStats.getCodec(), this.lastPcStats.getTrackStats(), this.transportsmonitor.getIntervalStats(), this.tracksmonitor.extractTracks()); + this.transmit(w.StatsTupleOut, a); + } + }, { + key: "sendDisruptions", + value: function(a) { + var b = this; + a.forEach(function(a) { + b.sendEventMsg(t.internalFabricEvent.oneWayMedia, a.getContent()); + }); + } + }, { + key: "sendCPULimitationObservations", + value: function(a) {} + }, { + key: "sendQPSumDistortions", + value: function(a) {} + }, { + key: "sendThroughputObservations", + value: function(a) { + this.sendEventMsg(t.internalFabricEvent.sendingThroughputObservations, a); + } + }, { + key: "sendEventMsg", + value: function(a, b) { + if (this.lastPcHash) { + var c = m.Registry.getConferenceManager().getConferenceForPcHash(this.lastPcHash); + if (c) { + var d = c.getPeerConnectionManager().getPcHandlerByHash(this.lastPcHash), e = d.getPeerConnection(), f = d.getConferenceId(); + m.Registry.getEventMessageBuilder().make(a, f, e, b); + } + } + } + } ]), b; + }(i.Component); + c.StatsMonitor = x; + }, { + "../collections/component": 25, + "../config/constants": 32, + "../utility/csiologger": 87, + "../utility/registry": 94, + "./monitorhooks/cpulimitationobserver": 60, + "./monitorhooks/onewaymediaobserver": 61, + "./monitorhooks/qpsumobserver": 62, + "./monitorhooks/sendingtrigger": 63, + "./monitorhooks/throughputobserver": 64, + "./statstuple": 74, + "./tracksmonitor": 80, + "./transportsmonitor": 81 + } ], + 72: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function g(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.StatsParser = c.StatsParserIO = void 0; + var h = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), i = a("../collections/component"), j = a("./measurement"), k = a("./pcstats"), l = a("../utility/rttregistry"), m = a("./validator"), n = d(m), o = a("../config/constants"), p = d(o), q = a("../utility/csiologger"), r = d(q), s = c.StatsParserIO = { + RawStatsIn: "RawStatsIn", + PcStatsTupleOut: "PcStatsTupleOut" + }, t = function(a) { + function b() { + e(this, b); + var a = f(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, "StatsParser")); + return a.bindPort(s.RawStatsIn, a.receive, a), a.declarePort(s.PcStatsTupleOut), + a; + } + return g(b, a), h(b, [ { + key: "receive", + value: function(a) { + if (null === a) return void r.warn("Stats object can not be null"); + for (var b = a.tracks, c = [], d = 0; d < b.length; ++d) { + var e = b[d]; + if (e && e.data) { + var f = j.Measurement.make(a.pcHash, this.getSSRC(e), this.getStreamType(e), this.getMediaType(e), this.getFrameRateReceived(e), this.getFrameHeight(e), this.getFrameWidth(e), this.getDroppedFramesNum(e), this.getRTT(e), this.getJitter(e), this.getLostPackets(e), this.getReceivedPackets(e), this.getSentPackets(e), this.getDiscardedPackets(e), this.getSentBytes(e), this.getReceivedBytes(e), e); + c.push(f); + } else r.log("No track or track.data."); + } + var g = new k.PcStats(a.candidatePair, a.codec, a.pcHash, a.trackStats, a.transportStats, c); + this.transmit(s.PcStatsTupleOut, g); + } + }, { + key: "getSSRC", + value: function(a) { + return a.ssrc; + } + }, { + key: "getStreamType", + value: function(a) { + return a.streamType === p.streamType.inbound ? p.streamType.inbound : a.streamType === p.streamType.outbound ? p.streamType.outbound : void 0; + } + }, { + key: "getSentBytes", + value: function(a) { + if (void 0 === a.data.bytesSent) return -1; + var b = n.checkForNan(parseInt(a.data.bytesSent, 10)); + return null !== b ? b : -1; + } + }, { + key: "getReceivedBytes", + value: function(a) { + if (void 0 === a.data.bytesReceived) return -1; + var b = n.checkForNan(parseInt(a.data.bytesReceived, 10)); + return null !== b ? b : -1; + } + }, { + key: "getReceivedPackets", + value: function(a) { + if (void 0 === a.data.packetsReceived) return -1; + var b = n.checkForNegativeValue(parseInt(a.data.packetsReceived, 10)); + return null !== b ? b : -1; + } + }, { + key: "getSentPackets", + value: function(a) { + if (void 0 === a.data.packetsSent) return -1; + var b = n.checkForNegativeValue(parseInt(a.data.packetsSent, 10)); + return null !== b ? b : -1; + } + }, { + key: "getDiscardedPackets", + value: function(a) { + if (void 0 === a.data.discardedPackets) return -1; + var b = n.checkForNan(parseInt(a.data.discardedPackets, 10)); + return null !== b ? b : -1; + } + }, { + key: "getLostPackets", + value: function(a) { + if (void 0 === a.data.packetsLost) return -1; + var b = n.checkForNegativeValue(parseInt(a.data.packetsLost, 10)); + return null !== b ? b : -1; + } + }, { + key: "getDroppedFramesNum", + value: function(a) { + if (void 0 === a.data.droppedFrames) return -1; + var b = n.checkForNegativeValue(parseInt(a.data.droppedFrames, 10)); + return null !== b ? b : -1; + } + }, { + key: "getFrameRateReceived", + value: function(a) { + var b = null; + return void 0 !== a.data.googFrameRateOutput ? b = parseInt(a.data.googFrameRateOutput, 10) : void 0 !== a.data.googFrameRateDecoded ? b = parseInt(a.data.googFrameRateDecoded, 10) : void 0 !== a.data.googFrameRateReceived ? b = parseInt(a.data.googFrameRateReceived, 10) : void 0 !== a.data.googFrameRateSent ? b = parseInt(a.data.googFrameRateSent, 10) : void 0 !== a.data.framerateMean && (b = parseInt(a.data.framerateMean, 10)), + void 0 !== b && (b = n.checkForNegativeValue(b)), b; + } + }, { + key: "getFrameHeight", + value: function(a) { + var b = void 0; + return void 0 !== a.data.googFrameHeightReceived ? b = a.data.googFrameHeightReceived : void 0 !== a.data.googFrameHeightSent ? b = a.data.googFrameHeightSent : void 0 !== a.data.frameHeight && (b = a.data.frameHeight), + b; + } + }, { + key: "getJitter", + value: function(a) { + return void 0 !== a.data.googJitterReceived ? n.checkForNan(parseInt(a.data.googJitterReceived, 10)) : void 0 !== a.data.jitter ? n.checkForNan(parseInt(a.data.jitter, 10)) : void 0; + } + }, { + key: "getFrameWidth", + value: function(a) { + return void 0 !== a.data.googFrameWidthReceived ? a.data.googFrameWidthReceived : void 0 !== a.data.googFrameWidthSent ? a.data.googFrameWidthSent : void 0 !== a.data.frameWidth ? a.data.frameWidth : void 0; + } + }, { + key: "getRTT", + value: function(a) { + var b = function(a) { + return isNaN(a) || a < 0 ? null : a; + }; + if (void 0 !== a.data.googRtt) return b(parseInt(a.data.googRtt, 10)); + if (void 0 !== a.data.mozRtt) return b(parseInt(a.data.mozRtt, 10)); + if (a.data.roundTripTime) return b(parseInt(a.data.roundTripTime, 10)); + var c = this.getSSRC(a), d = (0, l.getRTTRegistry)().getRTT(c); + return d && (a.data.roundTripTime = d), d; + } + }, { + key: "getMediaType", + value: function(a) { + var b = p.mediaType.unknown; + return a.data && void 0 !== a.data.mediaType ? a.data.mediaType : (void 0 !== a.data.googFrameRateReceived || void 0 !== a.data.googFrameRateSent ? b = p.mediaType.video : void 0 !== a.data.audioInputLevel || void 0 !== a.data.audioOutputLevel ? b = p.mediaType.audio : a.data.mediaType ? b = a.data.mediaType : void 0 !== a.data.framerateMean && (b = p.mediaType.video), + b); + } + } ]), b; + }(i.Component); + c.StatsParser = t; + }, { + "../collections/component": 25, + "../config/constants": 32, + "../utility/csiologger": 87, + "../utility/rttregistry": 95, + "./measurement": 59, + "./pcstats": 66, + "./validator": 82 + } ], + 73: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function f(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function g(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.StatsTransmitter = c.StatsTransmitterIO = void 0; + var h = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), i = a("../collections/component"), j = a("../utility/registry"), k = a("../config/constants"), l = d(k), m = a("../utility/csiologger"), n = d(m), o = c.StatsTransmitterIO = { + CallstatsIn: "CallstatsIn", + UnprocessedIn: "UnprocessedIn" + }, p = function(a) { + function b() { + e(this, b); + var a = f(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, "StatsTransmitter")); + return a.pcHashes = [], a.battery = j.Registry.getBattery(), a.lastUnprocessed = null, + a.bindPort(o.CallstatsIn, a.receiveCallstats, a), a.bindPort(o.UnprocessedIn, a.receiveUnprocessed, a), + a; + } + return g(b, a), h(b, [ { + key: "receiveUnprocessed", + value: function(a) { + this.lastUnprocessed = a; + } + }, { + key: "receiveCallstats", + value: function(a, b) { + var c = null; + if (!(c = this.getUnifiedFormat(b))) return void n.warn("Content can not be sent"); + this.send(a, c); + } + }, { + key: "send", + value: function(a, b) { + var c = j.Registry.getConferenceManager().getConferenceForPcHash(a); + if (c) { + var d = c.getPeerConnectionManager().getPcHandlerByHash(a); + if (d) { + j.Registry.getEventMessageBuilder().make(l.callstatsChannels.processedStats, d.getConferenceId(), d.getPeerConnection(), b), + this.sendToStatsCallback(b.stats, d); + } + } + } + }, { + key: "sendToStatsCallback", + value: function(a, b) { + var c = j.Registry.getStatsCallbackBuilder(); + c && c.buildStats(a, b); + } + }, { + key: "getUnifiedFormat", + value: function(a) { + for (var b = this.lastUnprocessed, c = [], d = 0; d < b.length; d++) { + var e = b[d], f = {}; + e.id && (f.id = e.id), e.timestamp && (f.timestamp = e.timestamp), e.type && (f.type = e.type), + Object.assign(f, e); + var g = function(b) { + for (var c = 0; c < a.tracks.length; c++) { + var d = a.tracks[c]; + if (d.data.id === b.id && d.data.type === b.type) return d.data; + } + return b.id === a.Transport.id && b.type === a.Transport.type ? a.Transport : null; + }(e); + if (g) { + for (var h in g) if (g.hasOwnProperty(h)) { + if ("id" === h || "type" === h || "timestamp" === h) continue; + f[h] = g[h]; + } + c.push(f); + } else c.push(f); + } + var i = { + stats: c + }; + return i.wifiStats = j.Registry.getWifiStatsExecutor().getWifiStats(), i.batteryStatus = {}, + i.batteryStatus.batteryLevel = this.battery.getLevel(), i.batteryStatus.isBatteryCharging = this.battery.getCharging(), + i; + } + } ]), b; + }(i.Component); + c.StatsTransmitter = p; + }, { + "../collections/component": 25, + "../config/constants": 32, + "../utility/csiologger": 87, + "../utility/registry": 94 + } ], + 74: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a(b, c, e, f, g) { + d(this, a), this.candidatePairs = b, this.codec = c, this.trackStats = e, this.transportStats = f, + this.tracks = g; + } + return e(a, [ { + key: "getCandidatePairs", + value: function() { + return this.candidatePairs; + } + }, { + key: "getCodec", + value: function() { + return this.codec; + } + }, { + key: "getTrackStats", + value: function() { + return this.trackStats; + } + }, { + key: "getTransportStats", + value: function() { + return this.transportStats; + } + }, { + key: "getTracks", + value: function() { + return this.tracks; + } + } ]), a; + }(); + c.StatsTuple = f; + }, {} ], + 75: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function f(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.SWAvg = void 0; + var g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = a("./swplugin"), i = function(a) { + function b(a, c) { + var f = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : null; + d(this, b); + var g = e(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, a, c, f)); + return g.sum = 0, g.counter = 0, g; + } + return f(b, a), g(b, [ { + key: "add", + value: function(a) { + this.filter(a) && (this.sum += this.extract(a), ++this.counter, this.calculate()); + } + }, { + key: "remove", + value: function(a) { + this.filter(a) && (this.sum -= this.extract(a), --this.counter, this.calculate()); + } + }, { + key: "calculate", + value: function() { + var a = 0; + if (this.counter < 1) return void this.notify(a); + a = this.sum / this.counter, this.notify(a); + } + } ]), b; + }(h.SWPlugin); + c.SWAvg = i; + }, { + "./swplugin": 78 + } ], + 76: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function f(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.SWBTreePercentile = void 0; + var g = function() { + function a(a, b) { + var c = [], d = !0, e = !1, f = void 0; + try { + for (var g, h = a[Symbol.iterator](); !(d = (g = h.next()).done) && (c.push(g.value), + !b || c.length !== b); d = !0) ; + } catch (a) { + e = !0, f = a; + } finally { + try { + !d && h.return && h.return(); + } finally { + if (e) throw f; + } + } + return c; + } + return function(b, c) { + if (Array.isArray(b)) return b; + if (Symbol.iterator in Object(b)) return a(b, c); + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + }; + }(), h = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), i = a("./swplugin"), j = a("../../collections/binarytree"), k = function(a) { + function b(a, c, f, g) { + var h = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : null, i = arguments.length > 5 && void 0 !== arguments[5] ? arguments[5] : null, k = arguments.length > 6 && void 0 !== arguments[6] ? arguments[6] : null; + d(this, b); + var l = e(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, f, g, i)); + if (99 < a || a < 1) throw new RangeError("Percentile parameter must be between 1 and 99"); + return l.comparator = c, l.percentile = a, l.meanCalcer = k, l.estimator = h, l.ratio = a / (100 - a), + l.maxtree = new j.BinaryTree(c), l.mintree = new j.BinaryTree(c), l.ratio < 1 ? l.required = 1 / l.ratio + 1 : 1 < l.ratio ? l.required = l.ratio + 1 : l.required = 2, + l.result = null, l; + } + return f(b, a), h(b, [ { + key: "add", + value: function(a) { + if (this.filter(a)) { + if (this.maxtree.getNodeCounter() < 1) return this.maxtree.insert(a), void this.calculate(); + this.comparator(a, this.maxtree.getTopValue()) <= 0 ? this.maxtree.insert(a) : this.mintree.insert(a), + this.balancing(), this.calculate(); + } + } + }, { + key: "remove", + value: function(a) { + if (this.filter(a)) { + var b = this.mintree.getNodeCounter(); + this.maxtree.getNodeCounter() < 1 ? this.mintree.delete(a) : b < 1 ? this.maxtree.delete(a) : this.comparator(a, this.maxtree.getTopValue()) <= 0 ? this.maxtree.delete(a) : this.mintree.delete(a), + this.calculate(); + } + } + }, { + key: "getThresholds", + value: function() { + var a = this.mintree.getSize(), b = this.maxtree.getSize(), c = a + 1, d = b + 1; + return 1 < this.ratio ? (c = Math.ceil(a * this.ratio), d = Math.floor(b / this.ratio) + 1) : this.ratio < 1 && (c = Math.floor(a * this.ratio) + 1, + d = Math.ceil(b / this.ratio)), [ c, d ]; + } + }, { + key: "balancing", + value: function() { + var a = this.mintree, b = this.maxtree, c = a.getSize(), d = b.getSize(); + if (!(d + c < this.required)) { + if (c < 1) return void a.insertNodeAtBottom(b.popTopNode()); + for (d < 1 && b.insertNodeAtTop(a.popBottomNode()); ;) { + var e = 1 < a.getNodeCounter(), f = 1 < b.getNodeCounter(), h = a.getBottomNode().getLength(), i = b.getTopNode().getLength(); + if (a.getNodeCounter() < 1 || b.getNodeCounter() < 1) break; + var j = this.getThresholds(), k = g(j, 2), l = k[0], m = k[1]; + if (f &= c + i <= m, e &= d + h <= l, c = a.getSize(), d = b.getSize(), l < d && f) a.insertNodeAtBottom(b.popTopNode()); else { + if (!(m < c && e)) break; + b.insertNodeAtTop(a.popBottomNode()); + } + } + } + } + }, { + key: "getMean", + value: function(a, b) { + return this.meanCalcer ? this.meanCalcer(a, b) : a; + } + }, { + key: "estimate", + value: function(a, b) { + return this.estimator ? this.estimator(a, b) : null; + } + }, { + key: "calculate", + value: function() { + var a = null, b = this.mintree, c = this.maxtree, d = b.getSize(), e = c.getSize(), f = e + d; + if (!(f < 1)) { + if (f < this.required || d < 1 || e < 1) { + if (0 == f) return; + var g = void 0, h = void 0; + d < 1 ? (g = this.maxtree.getBottomValue(), h = this.maxtree.getTopValue()) : e < 1 ? (g = this.mintree.getBottomValue(), + h = this.mintree.getTopValue()) : (h = this.mintree.getTopValue(), g = this.maxtree.getBottomValue()); + var i = this.estimate(g, h); + return void this.notify(i); + } + var j = c.getTopNode(), k = b.getBottomNode(); + if (j || k) { + if (!j) { + var l = this.extract(k); + return void this.notify(l); + } + if (!k) { + var m = this.extract(j); + return void this.notify(m); + } + var n = f * (this.percentile / 100); + if (!Number.isInteger(n)) { + var o = e / d; + a = this.ratio < o ? j.peek() : o < this.ratio ? k.peek() : this.ratio < 1 ? k.peek() : j.peek(); + } else { + var p = Math.floor(n); + a = Math.ceil(n + 1) <= e ? j.peek() : p <= e ? this.getMean(j.peek(), k.peek()) : k.peek(); + } + var q = this.extract(a); + this.notify(q); + } + } + } + } ]), b; + }(i.SWPlugin); + c.SWBTreePercentile = k; + }, { + "../../collections/binarytree": 22, + "./swplugin": 78 + } ], + 77: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function f(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.SWFunctor = void 0; + var g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = a("./swplugin"), i = function(a) { + function b(a, c) { + var f = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : null; + d(this, b); + var g = e(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, null, null, f)); + return g.addFunc = a, g.remFunc = c, g; + } + return f(b, a), g(b, [ { + key: "add", + value: function(a) { + this.filter(a) && this.addFunc && this.addFunc(a); + } + }, { + key: "remove", + value: function(a) { + this.filter(a) && this.remFunc && this.remFunc(a); + } + }, { + key: "toString", + value: function() { + return "SWFuncPlugin"; + } + } ]), b; + }(h.SWPlugin); + c.SWFunctor = i; + }, { + "./swplugin": 78 + } ], + 78: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.SWPlugin = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("../../utility/csiologger"), g = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(f), h = function() { + function a(b, c) { + var e = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : null; + d(this, a), this.extractorFnc = b, this.notifierFnc = c, this.filterFunc = e; + } + return e(a, [ { + key: "notify", + value: function(a) { + if (!this.notifierFnc) return void g.warn("Failed notification for " + this.toString()); + this.notifierFnc(a); + } + }, { + key: "extract", + value: function(a) { + return this.extractorFnc ? this.extractorFnc(a) : (g.warn(this.toString() + " tried to extract without extractorFnc"), + null); + } + }, { + key: "filter", + value: function(a) { + return !this.filterFunc || this.filterFunc(a); + } + }, { + key: "add", + value: function(a) { + g.log("Abstract method is called width value: " + a); + } + }, { + key: "remove", + value: function(a) { + g.log("Abstract method is called with value: " + a); + } + }, { + key: "toString", + value: function() { + return "SWPlugin"; + } + } ]), a; + }(); + c.SWPlugin = h; + }, { + "../../utility/csiologger": 87 + } ], + 79: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!a) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return !b || "object" != typeof b && "function" != typeof b ? a : b; + } + function f(a, b) { + if ("function" != typeof b && null !== b) throw new TypeError("Super expression must either be null or a function, not " + typeof b); + a.prototype = Object.create(b && b.prototype, { + constructor: { + value: a, + enumerable: !1, + writable: !0, + configurable: !0 + } + }), b && (Object.setPrototypeOf ? Object.setPrototypeOf(a, b) : a.__proto__ = b); + } + function g(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function h(a, b) { + return b.green <= a ? t.avQualityRatings.excellent : b.red < a ? t.avQualityRatings.fair : t.avQualityRatings.bad; + } + function i(a, b) { + return b.red < a ? t.avQualityRatings.bad : b.green <= a ? t.avQualityRatings.fair : t.avQualityRatings.excellent; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.TrackMonitor = void 0; + var j = function a(b, c, d) { + null === b && (b = Function.prototype); + var e = Object.getOwnPropertyDescriptor(b, c); + if (void 0 === e) { + var f = Object.getPrototypeOf(b); + return null === f ? void 0 : a(f, c, d); + } + if ("value" in e) return e.value; + var g = e.get; + if (void 0 !== g) return g.call(d); + }, k = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), l = a("../utility/registry"), m = a("../collections/slidingwindow"), n = a("../statspipeline/swplugins/swavg"), o = a("../statspipeline/swplugins/swbtreepercentile"), p = a("../statspipeline/swplugins/swfunctor"), q = a("../utility/timestamps"), r = d(q), s = a("../config/constants"), t = d(s), u = a("../utility/csiologger"), v = d(u), w = function() { + function a() { + g(this, a), this.evaluators = []; + } + return k(a, [ { + key: "addEvaluator", + value: function(a) { + var b = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1, c = { + processFnc: a, + weight: b + }; + this.evaluators.push(c); + } + }, { + key: "getQuality", + value: function(a) { + for (var b = 0, c = [], d = 0, e = 0; e < this.evaluators.length; e++) { + var f = this.evaluators[e], g = 0, h = f.processFnc ? f.processFnc(a) : 0; + if (h) { + if (h === t.avQualityRatings.bad) g = t.qualityRating.bad; else if (h === t.avQualityRatings.fair) g = t.qualityRating.fair; else if (h === t.avQualityRatings.excellent) g = t.qualityRating.excellent; else if (h === t.avQualityRatings.unknown) continue; + b += f.weight, c.push({ + result: g, + weight: f.weight + }); + } + } + for (var i = 0; i < c.length; i++) { + var j = c[i]; + d += j.result * (j.weight / b); + } + return d = Math.floor(d), d === t.qualityRating.excellent ? t.avQualityRatings.excellent : d === t.qualityRating.good ? t.avQualityRatings.fair : d === t.qualityRating.fair ? t.avQualityRatings.fair : d === t.qualityRating.poor ? t.avQualityRatings.fair : d === t.qualityRating.bad ? t.avQualityRatings.bad : void 0; + } + } ]), a; + }(), x = function(a) { + function b(a, c, d, f) { + g(this, b); + var h = e(this, (b.__proto__ || Object.getPrototypeOf(b)).call(this, a, c)); + return h.thresholds = [], h.enableThresholds = !1, h.requestTime = 0, h.started = 0, + h.created = r.getCurrent(), h.mediaType = f, h.streamType = d, h.qualityHelper = new w(), + h.metrics = h.makeTrack(), h.lastTrack = {}, h.prevFrameRateMean = null, h.ssrc = null, + h.scsHelper = { + total: 0, + above: 0, + ccDriven: 0, + sumMaxBitrateDiff: 0, + sumThroughputDiff: 0, + prevCsioAvgBRKbps: 0 + }, h; + } + return f(b, a), k(b, null, [ { + key: "make", + value: function(a, c, d, e) { + var f = new b(a, c, d, e), g = f.metrics; + return f.attach(new n.SWAvg(function(a) { + return a.getJitter(); + }, function(a) { + g.csioAvgJitter = a; + }, function(a) { + var b = a.getJitter(); + return null !== b && void 0 !== b; + })), f.attach(new n.SWAvg(function(a) { + return a.getRTT(); + }, function(a) { + g.csioAvgRtt = a; + }, function(a) { + var b = a.getRTT(); + return null !== b && void 0 !== b; + })), f.attach(new o.SWBTreePercentile(95, function(a, b) { + var c = a.getJitter(), d = b.getJitter(); + return c == d ? 0 : c < d ? -1 : 1; + }, function(a) { + return a.getJitter(); + }, function(a) { + g.csioPercentileJitter = a; + }, function(a, b) { + return b ? b.getJitter() : a ? a.getJitter() : void 0; + }, function(a) { + var b = a.getJitter(); + return null !== b && void 0 !== b; + }, function(a, b) { + return a; + })), f.attach(new o.SWBTreePercentile(95, function(a, b) { + var c = a.getRTT(), d = b.getRTT(); + return c == d ? 0 : c < d ? -1 : 1; + }, function(a) { + return a.getRTT(); + }, function(a) { + g.csioSig2Latency = a, g.csioeM = a + 40; + }, function(a, b) { + return b ? b.getRTT() : a ? a.getRTT() : void 0; + }, function(a) { + var b = a.getRTT(); + return null !== b && void 0 !== b; + }, function(a, b) { + return a; + })), d === t.streamType.inbound ? b.setupInboundMonitor(f) : d === t.streamType.outbound ? b.setupOutboundMonitor(f) : v.warn("Unrecognized streamType (" + d + ") at TrackMonitor"), + e === t.mediaType.audio ? b.setupAudioMonitor(f) : e === t.mediaType.video ? b.setupVideoMonitor(f) : v.warn("Unrecognized mediaType (" + e + ") at TrackMonitor"), + d === t.streamType.inbound && e === t.mediaType.audio ? b.setupInbAudioQualityEvaluator(f) : d === t.streamType.inbound && e === t.mediaType.video ? b.setupInbVideoQualityEvaluator(f) : d === t.streamType.outbound && e === t.mediaType.audio ? b.setupOutbAudioQualityEvaluator(f) : d === t.streamType.outbound && e === t.mediaType.video && (b.setupOutbVideoQualityEvaluator(f), + b.setupSCSValidator(f)), f.addPostProcess(function(a) { + g.csioMark = f.getQuality(a); + }), f; + } + }, { + key: "setupInbAudioQualityEvaluator", + value: function(a) { + var b = a.metrics; + a.addQualityEvaluator(function(a) { + return void 0 === b.csioIntBRKbps || null === b.csioIntBRKbps || b.csioIntBRKbps < 0 ? t.avQualityRatings.unknown : h(b.csioIntBRKbps, t.throughputThreshold.audio); + }), a.addQualityEvaluator(function(a) { + return void 0 === b.csioIntFL || null === b.csioIntFL || b.csioIntFL < 0 ? t.avQualityRatings.unknown : i(b.csioIntFL, t.fractionalLossThreshold.audio); + }), a.addQualityEvaluator(function(a) { + return void 0 === b.csioeM || null === b.csioeM ? t.avQualityRatings.unknown : i(b.csioeM, t.eModelThreshold.audio); + }); + } + }, { + key: "setupOutbAudioQualityEvaluator", + value: function(a) { + var b = a.metrics; + a.addQualityEvaluator(function(a) { + return void 0 === b.csioIntBRKbps || null === b.csioIntBRKbps || b.csioIntBRKbps < 0 ? t.avQualityRatings.unknown : h(b.csioIntBRKbps, t.throughputThreshold.audio); + }), a.addQualityEvaluator(function(a) { + return void 0 === b.csioeM || null === b.csioeM ? t.avQualityRatings.unknown : i(b.csioeM, t.eModelThreshold.audio); + }); + } + }, { + key: "setupInbVideoQualityEvaluator", + value: function(a) { + var b = a.metrics; + a.addQualityEvaluator(function(a) { + return void 0 === b.csioIntBRKbps || null === b.csioIntBRKbps || b.csioIntBRKbps < 0 ? t.avQualityRatings.unknown : h(b.csioIntBRKbps, t.throughputThreshold.video); + }), a.addQualityEvaluator(function(c) { + return void 0 === b.csioFrameRateMean || null === b.csioFrameRateMean ? t.avQualityRatings.unknown : b.csioFrameRateMean && a.prevFrameRateMean ? h(b.csioFrameRateMean / a.prevFrameRateMean, t.currOverPrevFrameRateThreshold.video) : t.avQualityRatings.bad; + }), a.addQualityEvaluator(function(a) { + return void 0 === b.csioSig2Latency || null === b.csioSig2Latency ? t.avQualityRatings.unknown : i(b.csioSig2Latency, t.rttThreshold.video); + }); + } + }, { + key: "setupOutbVideoQualityEvaluator", + value: function(a) { + var b = a.metrics; + a.addQualityEvaluator(function(a) { + return void 0 == b.csioIntBRKbps || null == b.csioIntBRKbps ? t.avQualityRatings.unknown : h(b.csioIntBRKbps, t.throughputThreshold.video); + }), a.addQualityEvaluator(function(c) { + return void 0 === b.csioFrameRateMean || null === b.csioFrameRateMean ? t.avQualityRatings.unknown : b.csioFrameRateMean && a.prevFrameRateMean ? h(b.csioFrameRateMean / a.prevFrameRateMean, t.currOverPrevFrameRateThreshold.video) : t.avQualityRatings.bad; + }), a.addQualityEvaluator(function(a) { + return void 0 === b.csioSig2Latency || null === b.csioSig2Latency ? t.avQualityRatings.unknown : i(b.csioSig2Latency, t.rttThreshold.video); + }); + } + }, { + key: "setupInboundMonitor", + value: function(a) { + var b = a.metrics; + a.addPreProcess(function(c) { + var d = c.getLostPackets(), e = c.getReceivedPackets(), f = a.getRequestedMeasurement(), g = 0, h = 0; + f ? (g = d - f.getLostPackets(), h = e - f.getReceivedPackets()) : (g = d, h = e); + var i = 0; + (0 < g || 0 < h) && (i = g / (h + g)), b.csioIntPktLoss = g, b.csioIntFL = i, c.setFractionLost(i); + }), a.attach(new p.SWFunctor(function(c) { + var d = r.getCurrent(), e = c.getResolution(), f = a.getRequestedMeasurement(), g = a.getRequestTime(), h = c.getLostPackets(), i = 8 * c.getReceivedBytes(), j = c.getReceivedPackets(), k = d - a.getStartTime(), m = 0, n = 0, o = 0, p = 0, q = 1e3, s = Math.max(d - a.getStartTime(), q); + f ? (p = j - f.getReceivedPackets(), m = i - 8 * f.getReceivedBytes(), n = h - f.getLostPackets(), + o = Math.max(d - g, q)) : (q = (l.Registry.getCredentials().getAdaptiveInterval(), + l.Registry.getCredentials().getStatsSubmissionInterval()), s = Math.max(d - a.getStartTime(), q), + p = j, m = i, n = h, o = Math.max(s, q)), b.csioIntPktRcv = p, b.csioIntPR = p / (o / 1e3), + b.csioAvgBRKbps = i / s, b.csioIntBRKbps = m / o, b.csioAvgPacketSize = c.getReceivedBytes() / j, + b.csioIntMs = k, b.csioTimeElapseMs = o, b.csiores = e, b.csioPktLostPercentage = n / m * 100; + }, null, null)), a.attach(new o.SWBTreePercentile(95, function(a, b) { + var c = a.getFractionLost(), d = b.getFractionLost(); + return c == d ? 0 : c < d ? -1 : 1; + }, function(a) { + return a.getFractionLost(); + }, function(a) { + b.csioPercentileFl = a; + }, function(a, b) { + return b ? b.getFractionLost() : a ? a.getFractionLost() : void 0; + }, function(a) { + var b = a.getFractionLost(); + return null !== b && void 0 !== b; + }, function(a, b) { + return a; + })); + } + }, { + key: "setupOutboundMonitor", + value: function(a) { + var b = a.metrics; + a.addPreProcess(function(c) { + var d = c.getLostPackets(), e = c.getSentPackets(), f = a.getRequestedMeasurement(), g = 0, h = 0; + f ? (g = d - f.getLostPackets(), h = e - f.getSentPackets()) : (g = d, h = e); + var i = 0; + (0 < g || 0 < h) && (i = g / (h + g)), b.csioIntPktLoss = g, b.csioIntFL = i, c.setFractionLost(i); + }), a.attach(new p.SWFunctor(function(c) { + var d = r.getCurrent(), e = c.getResolution(), f = a.getRequestedMeasurement(), g = a.getRequestTime(), h = c.getLostPackets(), i = 8 * c.getSentBytes(), j = c.getSentPackets(), k = d - a.getStartTime(), m = 0, n = 0, o = 0, p = 0, q = 1e3, s = Math.max(d - a.getStartTime(), q); + f ? (p = j - f.getSentPackets(), m = i - 8 * f.getSentBytes(), n = h - f.getLostPackets(), + o = Math.max(d - g, q)) : (q = (l.Registry.getCredentials().getAdaptiveInterval(), + l.Registry.getCredentials().getStatsSubmissionInterval()), s = Math.max(d - a.getStartTime(), q), + p = j, m = i, n = h, o = Math.max(s, q)), b.csioIntPktRcv = p, b.csioAvgBRKbps = i / s, + b.csioIntBRKbps = m / o, b.csioIntPR = p / (o / 1e3), b.csioAvgPacketSize = c.getSentBytes() / j, + b.csioIntMs = k, b.csioTimeElapseMs = o, b.csiores = e, b.csioPktLostPercentage = n / m * 100; + }, null, null)), a.attach(new o.SWBTreePercentile(95, function(a, b) { + var c = a.getFractionLost(), d = b.getFractionLost(); + return c == d ? 0 : c < d ? -1 : 1; + }, function(a) { + return a.getFractionLost(); + }, function(a) { + b.csioPercentileFl = a; + }, function(a, b) { + return b ? b.getFractionLost() : a ? a.getFractionLost() : void 0; + }, function(a) { + var b = a.getFractionLost(); + return null !== b && void 0 !== b; + }, function(a, b) { + return a; + })); + } + }, { + key: "setupAudioMonitor", + value: function(a) { + var b = a.metrics; + a.attach(new p.SWFunctor(function(a) { + b.csioMediaType = t.mediaType.audio; + }, null, null)); + } + }, { + key: "setupVideoMonitor", + value: function(a) { + var b = a.metrics; + a.attach(new n.SWAvg(function(a) { + return a.getFrameRateReceived(); + }, function(c) { + a.prevFrameRateMean = b.csioFrameRateMean, b.csioFrameRateMean = c; + }, function(a) { + var b = a.getFrameRateReceived(); + return null !== b && void 0 !== b; + })), a.attach(new n.SWAvg(function(a) { + return a.getFrameHeight(); + }, function(a) { + b.csioFrameHeightMean = a; + }, function(a) { + var b = a.getFrameHeight(); + return null !== b && void 0 !== b; + })), a.attach(new n.SWAvg(function(a) { + return a.getFrameWidth(); + }, function(a) { + b.csioFrameWidthMean = a; + }, function(a) { + var b = a.getFrameWidth(); + return null !== b && void 0 !== b; + })), a.attach(new o.SWBTreePercentile(95, function(a, b) { + var c = a.getFrameRateReceived(), d = b.getFrameRateReceived(); + return c == d ? 0 : c < d ? -1 : 1; + }, function(a) { + return a.getFrameRateReceived(); + }, function(a) { + b.csioFrameRate95Percentile = a; + }, function(a, b) { + return b ? b.getFrameRateReceived() : a ? a.getFrameRateReceived() : void 0; + }, function(a) { + var b = a.getFrameRateReceived(); + return null !== b && void 0 !== b; + }, function(a, b) { + return a; + })), a.attach(new o.SWBTreePercentile(50, function(a, b) { + var c = a.getFrameRateReceived(), d = b.getFrameRateReceived(); + return c == d ? 0 : c < d ? -1 : 1; + }, function(a) { + return a.getFrameRateReceived(); + }, function(a) { + b.csioFrameRate50Percentile = a; + }, function(a, b) { + return b ? b.getFrameRateReceived() : a ? a.getFrameRateReceived() : void 0; + }, function(a) { + var b = a.getFrameRateReceived(); + return null !== b && void 0 !== b; + }, function(a, b) { + return a; + })), a.attach(new o.SWBTreePercentile(95, function(a, b) { + var c = a.getFrameHeight(), d = b.getFrameHeight(); + return c == d ? 0 : c < d ? -1 : 1; + }, function(a) { + return a.getFrameHeight(); + }, function(a) { + b.csioFrameHeight95Percentile = a; + }, function(a, b) { + return b ? b.getFrameHeight() : a ? a.getFrameHeight() : void 0; + }, function(a) { + var b = a.getFrameHeight(); + return null !== b && void 0 !== b; + }, function(a, b) { + return a; + })), a.attach(new o.SWBTreePercentile(50, function(a, b) { + var c = a.getFrameHeight(), d = b.getFrameHeight(); + return c == d ? 0 : c < d ? -1 : 1; + }, function(a) { + return a.getFrameHeight(); + }, function(a) { + b.csioFrameHeight50Percentile = a; + }, function(a, b) { + return b ? b.getFrameHeight() : a ? a.getFrameHeight() : void 0; + }, function(a) { + var b = a.getFrameHeight(); + return null !== b && void 0 !== b; + }, function(a, b) { + return a; + })), a.attach(new o.SWBTreePercentile(95, function(a, b) { + var c = a.getFrameWidth(), d = b.getFrameWidth(); + return c == d ? 0 : c < d ? -1 : 1; + }, function(a) { + return a.getFrameWidth(); + }, function(a) { + b.csioFrameWidth95Percentile = a; + }, function(a, b) { + return b ? b.getFrameWidth() : a ? a.getFrameWidth() : void 0; + }, function(a) { + var b = a.getFrameWidth(); + return null !== b && void 0 !== b; + }, function(a, b) { + return a; + })), a.attach(new o.SWBTreePercentile(50, function(a, b) { + var c = a.getFrameWidth(), d = b.getFrameWidth(); + return c == d ? 0 : c < d ? -1 : 1; + }, function(a) { + return a.getFrameWidth(); + }, function(a) { + b.csioFrameWidth50Percentile = a; + }, function(a, b) { + return b ? b.getFrameWidth() : a ? a.getFrameWidth() : void 0; + }, function(a) { + var b = a.getFrameWidth(); + return null !== b && void 0 !== b; + }, function(a, b) { + return a; + })), a.attach(new p.SWFunctor(function(a) { + b.csioMediaType = t.mediaType.video; + }, null, null)); + } + }, { + key: "setupSCSValidator", + value: function(a) { + var b = a.metrics; + a.attach(new p.SWFunctor(function(c) { + var d = l.Registry.getConfigServiceWrapper().getSenderConfig(); + if (!d || !d.rtc_rtp_parameters || !d.rtc_rtp_parameters.encodings) return b.csioSCSValidationSampleCount = null, + b.csioAvgMaxBitrateDiff = null, b.csioAvgDeltaThroughput = null, b.csioMaxBitrateAboveRatio = null, + void (b.csioCCDrivenRatio = null); + var e = 0; + d.rtc_rtp_parameters.encodings.forEach(function(a) { + a && (e = Math.max(e, a.maxBitrate)); + }); + var f = 0, g = l.Registry.getConfigServiceWrapper().getDefaultSenderConfig(); + if (g && g.encodings) { + g.encodings.forEach(function(a) { + f = Math.max(f, a.maxBitrate); + }); + var h = 0, i = 0, j = null, k = null, m = a.getSCSHelper(); + 0 < f && .9 * f < 1e3 * b.csioAvgBRKbps ? (h = e - f, k = !1) : (h = e - 1e3 * b.csioAvgBRKbps, + k = !0), j = 0 < h, i = b.csioAvgBRKbps - b.prevCsioAvgBRKbps, m.prevCsioAvgBRKbps = b.csioAvgBRKbps, + b.csioSCSValidationSampleCount = ++m.total, m.sumMaxBitrateDiff += h, b.csioAvgMaxBitrateDiff = m.sumMaxBitrateDiff / m.total, + m.sumThroughputDiff += i, b.csioAvgDeltaThroughput = m.sumThroughputDiff / m.total, + j && (m.above += 1), b.csioMaxBitrateAboveRatio = m.above / m.total, k && (m.ccDriven += 1), + b.csioCCDrivenRatio = m.ccDriven / m.total; + } + }, null, null)); + } + } ]), k(b, [ { + key: "makeTrack", + value: function() { + var a = {}; + return a.csioMediaType = void 0, a.csioMark = void 0, a.csioIntBRKbps = void 0, + a.csioAvgBRKbps = void 0, a.csioIntFL = void 0, a.csioIntMs = void 0, a.csioIntPR = void 0, + a.csioPercentileFl = void 0, a.csioAvgJitter = void 0, a.csioAvgRtt = void 0, a.csioPercentileJitter = void 0, + a.csioSig2Latency = void 0, a.csioTimeElapseMs = void 0, a.csioeM = void 0, a.csiores = void 0, + a.csioFrameWidth95Percentile = void 0, a.csioFrameWidth50Percentile = void 0, a.csioFrameHeight95Percentile = void 0, + a.csioFrameHeight50Percentile = void 0, a.csioFrameRate95Percentile = void 0, a.csioFrameRate50Percentile = void 0, + a.csioFrameWidthMean = void 0, a.csioFrameHeightMean = void 0, a.csioFrameRateMean = void 0, + a.csioIntPktRcv = void 0, a.csioSCSValidationSampleCount = null, a.csioAvgMaxBitrateDiff = null, + a.csioAvgDeltaThroughput = null, a.csioMaxBitrateAboveRatio = null, a.csioCCDrivenRatio = null, + a; + } + }, { + key: "getSSRC", + value: function() { + return this.ssrc; + } + }, { + key: "add", + value: function(a) { + this.ssrc = a.getSSRC(), this.lastTrack = a.extractTrack(), this.lastTrack.pcHash = a.getPcHash(), + 0 === this.started && (this.started = r.getCurrent()), j(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "add", this).call(this, a); + } + }, { + key: "hasTraffic", + value: function() { + return 0 < this.metrics.csioIntBRKbps; + } + }, { + key: "getTrack", + value: function() { + var a = this.lastTrack; + return Object.assign(a.data, this.metrics), a; + } + }, { + key: "extractTrack", + value: function() { + var a = this.lastTrack; + return Object.assign(a.data, this.metrics), this.requestTime = r.getCurrent(), this.requestedMeasurement = this.peek(), + a; + } + }, { + key: "getMediaType", + value: function() { + return this.mediaType; + } + }, { + key: "getStreamType", + value: function() { + return this.streamType; + } + }, { + key: "getStartTime", + value: function() { + return this.started; + } + }, { + key: "getCreationTime", + value: function() { + return this.created; + } + }, { + key: "getRequestTime", + value: function() { + return Math.max(this.started, this.requestTime); + } + }, { + key: "getRequestedMeasurement", + value: function() { + return this.requestedMeasurement; + } + }, { + key: "getSCSHelper", + value: function() { + return this.scsHelper; + } + }, { + key: "addQualityEvaluator", + value: function(a) { + var b = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1; + this.qualityHelper.addEvaluator(a, b); + } + }, { + key: "getQuality", + value: function(a) { + return this.qualityHelper.getQuality(a); + } + }, { + key: "addPreProcess", + value: function(a) { + j(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "addPreProcess", this).call(this, a); + } + }, { + key: "addPostProcess", + value: function(a) { + j(b.prototype.__proto__ || Object.getPrototypeOf(b.prototype), "addPostProcess", this).call(this, a); + } + } ]), b; + }(m.SlidingWindow); + c.TrackMonitor = x; + }, { + "../collections/slidingwindow": 27, + "../config/constants": 32, + "../statspipeline/swplugins/swavg": 75, + "../statspipeline/swplugins/swbtreepercentile": 76, + "../statspipeline/swplugins/swfunctor": 77, + "../utility/csiologger": 87, + "../utility/registry": 94, + "../utility/timestamps": 98 + } ], + 80: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.TracksMonitor = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./trackmonitor"), g = a("../config/constants"), h = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(g), i = function() { + function a() { + d(this, a), this.inbMonitors = new Map(), this.outbMonitors = new Map(); + } + return e(a, [ { + key: "getMonitor", + value: function(a) { + var b = a.getStreamType(), c = a.getMediaType(), d = a.getSSRC(), e = null; + return b === h.streamType.inbound ? c === h.mediaType.audio ? e = this.getInbAudioMonitor(d) : c === h.mediaType.video && (e = this.getInbVideoMonitor(d)) : b === h.streamType.outbound && (c === h.mediaType.audio ? e = this.getOutbAudioMonitor(d) : c === h.mediaType.video && (e = this.getOutbVideoMonitor(d))), + e; + } + }, { + key: "extractTracks", + value: function() { + var a = []; + return this.outbMonitors.forEach(function(b, c) { + a.push(b.extractTrack()); + }), this.inbMonitors.forEach(function(b, c) { + a.push(b.extractTrack()); + }), a; + } + }, { + key: "getTracks", + value: function() { + var a = []; + return this.outbMonitors.forEach(function(b, c) { + a.push(b.getTrack()); + }), this.inbMonitors.forEach(function(b, c) { + a.push(b.getTrack()); + }), a; + } + }, { + key: "getMonitors", + value: function() { + var a = []; + return this.outbMonitors.forEach(function(b, c) { + a.push(b); + }), this.inbMonitors.forEach(function(b, c) { + a.push(b); + }), a; + } + }, { + key: "getInbAudioMonitor", + value: function(a) { + var b = this.inbMonitors.get(a); + return b || (b = f.TrackMonitor.make(1e3, 3e4, h.streamType.inbound, h.mediaType.audio), + this.inbMonitors.set(a, b)), b; + } + }, { + key: "getInbVideoMonitor", + value: function(a) { + var b = this.inbMonitors.get(a); + return b || (b = f.TrackMonitor.make(1e3, 3e4, h.streamType.inbound, h.mediaType.video), + this.inbMonitors.set(a, b)), b; + } + }, { + key: "getOutbAudioMonitor", + value: function(a) { + var b = this.outbMonitors.get(a); + return b || (b = f.TrackMonitor.make(1e3, 3e4, h.streamType.outbound, h.mediaType.audio), + this.outbMonitors.set(a, b)), b; + } + }, { + key: "getOutbVideoMonitor", + value: function(a) { + var b = this.outbMonitors.get(a); + return b || (b = f.TrackMonitor.make(1e3, 3e4, h.streamType.outbound, h.mediaType.video), + this.outbMonitors.set(a, b)), b; + } + } ]), a; + }(); + c.TracksMonitor = i; + }, { + "../config/constants": 32, + "./trackmonitor": 79 + } ], + 81: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.TransportsMonitor = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../config/constants"), h = d(g), i = a("../utility/timestamps"), j = d(i), k = a("../utility/rttregistry"), l = function() { + function a(b) { + e(this, a), this.previous = b, this.actual = b, this.outdated = j.getCurrent(); + } + return f(a, [ { + key: "setActual", + value: function(a) { + this.actual = a; + } + }, { + key: "outdate", + value: function() { + this.previous = this.actual, this.outdated = j.getCurrent(); + } + }, { + key: "getActual", + value: function() { + return this.actual; + } + }, { + key: "getPrevious", + value: function() { + return this.previous; + } + }, { + key: "getElapsedTime", + value: function() { + return j.getCurrent() - this.outdated; + } + } ]), a; + }(), m = function() { + function a(b) { + e(this, a), this.stats = new Map(), this.codeBase = b; + } + return f(a, [ { + key: "set", + value: function(a, b) { + var c = this.stats.get(a); + if (!c) return void this.stats.set(a, new l(b)); + c.setActual(b); + } + }, { + key: "getIntervalStats", + value: function() { + var a = this, b = new Map(); + return this.stats.forEach(function(c, d) { + b.set(d, a.getIntervalStat(c)), c.outdate(); + }), b; + } + }, { + key: "getIntervalStat", + value: function(a) { + var b = null; + switch (this.codeBase) { + case h.codeBaseType.chrome: + b = this.getIntervalStatForChrome(a); + break; + + default: + b = a.getActual(); + } + return b; + } + }, { + key: "getIntervalStatForChrome", + value: function(a) { + var b = a.getActual(), c = a.getPrevious(), d = a.getElapsedTime(); + if (!c) return actual; + for (var e = 0; e < b.length; ++e) { + var f = b[e], g = c[e]; + if (!g || !f) return b; + var i = parseInt(g.bytesReceived, 10), j = parseInt(g.bytesSent, 10); + f.csioReceivedBwKbps = 8 * (parseInt(f.bytesReceived, 10) - i) / d, f.csioSentBwKbps = 8 * (parseInt(f.bytesSent, 10) - j) / d, + f.csioIntBytesReceived = parseInt(f.bytesReceived, 10) - i, f.csioIntBytesSent = parseInt(f.bytesSent, 10) - j, + void 0 !== g.packetsSent && void 0 !== f.packetsSent && (f.csioSentPacketRate = (parseInt(f.packetsSent, 10) - parseInt(g.packetsSent, 10)) / (d / 1e3), + f.csioIntPacketsSent = parseInt(f.packetsSent, 10) - parseInt(g.packetsSent, 10)), + void 0 !== g.packetsReceived && void 0 !== f.packetsReceived && (f.csioReceivedPacketRate = (parseInt(f.packetsReceived, 10) - parseInt(g.packetsReceived, 10)) / (d / 1e3), + f.csioIntPacketsReceived = parseInt(f.packetsReceived, 10) - parseInt(g.packetsReceived, 10)), + this.codeBase == h.codeBaseType.chrome && (f.currentRoundTripTime = (0, k.getRTTRegistry)().getTransportRTT()); + } + return b; + } + } ]), a; + }(); + c.TransportsMonitor = m; + }, { + "../config/constants": 32, + "../utility/rttregistry": 95, + "../utility/timestamps": 98 + } ], + 82: [ function(a, b, c) { + "use strict"; + function d(a) { + return isNaN(a) ? null : a; + } + function e(a) { + return null !== d(a) && 0 < a ? a : null; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.checkForNan = d, c.checkForNegativeValue = e; + }, {} ], + 83: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a() { + d(this, a), this.getWifiStatsMethod = null, this.wifiStats = null, this.interval = 1e4; + } + return e(a, [ { + key: "setGetWifiStatsMethod", + value: function(a) { + this.getWifiStatsMethod = a, this.wifiStatsHandler(); + } + }, { + key: "getWifiStats", + value: function() { + return this.wifiStats; + } + }, { + key: "wifiStatsHandler", + value: function() { + var a = this; + a.getWifiStatsMethod && a.getWifiStatsMethod().then(function(b) { + a.wifiStats = JSON.parse(b), setTimeout(function() { + a.wifiStatsHandler(); + }, a.interval); + }).catch(function() { + setTimeout(function() { + a.wifiStatsHandler(); + }, a.interval); + }); + } + } ]), a; + }(); + c.WifiStatsExecutor = f; + }, {} ], + 84: [ function(a, b, c) { + "use strict"; + function d(a) { + return window.btoa(a); + } + function e(a) { + return window.atob(a); + } + function f(a) { + return d(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g, function(a, b) { + return String.fromCharCode("0x" + b); + })); + } + function g(a) { + return d(a).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=+$/, ""); + } + function h(a) { + return f(a).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=+$/, ""); + } + function i(a) { + for (var b = e(a.replace(/[ \r\n]+$/, "")), c = [], d = 0; d < b.length; ++d) { + var f = b.charCodeAt(d).toString(16); + 1 === f.length && (f = "0" + f), c.push(f); + } + return c.join(""); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.encode = d, c.decode = e, c.urlencode = g, c.urlencodeUnicode = h, c.strtohex = i; + }, {} ], + 85: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Callbacks = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../config/constants"), h = d(g), i = a("./registry"), j = a("./csiologger"), k = d(j), l = function() { + function a() { + e(this, a), this.callbacks = {}; + } + return f(a, [ { + key: "set", + value: function(a, b) { + if ("function" == typeof b) return h.callbackFunctions.hasOwnProperty(a) ? (this.callbacks[a] = b, + void (a === h.callbackFunctions.stats && i.Registry.getStatsCallbackBuilder().setCallback(b))) : void k.error("Couldn't set callback: " + a); + } + }, { + key: "get", + value: function(a) { + return this.callbacks.hasOwnProperty(a) ? this.callbacks[a] : null; + } + } ]), a; + }(); + c.Callbacks = l; + }, { + "../config/constants": 32, + "./csiologger": 87, + "./registry": 94 + } ], + 86: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Credentials = void 0; + var f = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(a) { + return typeof a; + } : function(a) { + return a && "function" == typeof Symbol && a.constructor === Symbol && a !== Symbol.prototype ? "symbol" : typeof a; + }, g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = a("../config/constants"), i = d(h), j = a("./csiologger"), k = d(j), l = function() { + function a() { + e(this, a), this.appId = null, this.userId = null, this.userIdObject = null, this.deviceId = null, + this.statsSubmissionInterval = 15e3, this.collectSDP = !1, this.transportType = i.transportType.rest, + this.adaptiveInterval = !1; + } + return g(a, [ { + key: "getAppId", + value: function() { + return this.appId; + } + }, { + key: "setAppId", + value: function(a) { + this.appId = "string" == typeof a ? parseInt(a, 10) : a; + } + }, { + key: "getUserId", + value: function() { + return this.userId; + } + }, { + key: "setUserId", + value: function(a) { + "object" === (void 0 === a ? "undefined" : f(a)) ? (this.userId = a.aliasName, this.setUserIdObject(a)) : this.userId = a; + } + }, { + key: "getUserIdObject", + value: function() { + return this.userIdObject; + } + }, { + key: "setUserIdObject", + value: function(a) { + this.userIdObject = a; + } + }, { + key: "getStatsSubmissionInterval", + value: function() { + return this.statsSubmissionInterval; + } + }, { + key: "setStatsSubmissionInterval", + value: function(a) { + k.log("setStatsSubmissionInterval is ", a), this.statsSubmissionInterval = a; + } + }, { + key: "getCollectSDP", + value: function() { + return this.collectSDP; + } + }, { + key: "setCollectSDP", + value: function(a) { + this.collectSDP = a; + } + }, { + key: "getTransportType", + value: function() { + return this.transportType; + } + }, { + key: "setTransportType", + value: function(a) { + this.transportType = a; + } + }, { + key: "getAdaptiveInterval", + value: function() { + return this.adaptiveInterval; + } + }, { + key: "setAdaptiveInterval", + value: function(a) { + this.adaptiveInterval = a; + } + } ]), a; + }(); + c.Credentials = l; + }, { + "../config/constants": 32, + "./csiologger": 87 + } ], + 87: [ function(a, b, c) { + "use strict"; + function d() { + if ("true" === i.csioDebug) { + var a; + (a = console).info.apply(a, arguments); + } + } + function e() { + if ("true" === i.csioDebug) { + var a; + (a = console).log.apply(a, arguments); + } + } + function f() { + if ("true" === i.csioDebug) { + var a; + (a = console).warn.apply(a, arguments); + } + } + function g() { + var a; + (a = console).warn.apply(a, arguments); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.info = d, c.log = e, c.warn = f, c.error = g; + var h = a("../config/settings"), i = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(h); + }, { + "../config/settings": 33 + } ], + 88: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Endpoint = void 0; + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = a("../browserapi/localstorage"), h = d(g), i = a("../browserapi/detectbrowser"), j = d(i), k = a("../utility/timestamps"), l = d(k), m = a("../utility/hash"), n = d(m), o = function() { + function a() { + e(this, a), this.id = null, this.appversion = null, this.magicKey = Math.floor(4294967296 * Math.random()), + this.browserName = null, this.browserVersion = null, this.osName = null, this.osVersion = null, + this.codeBase = null, this.userAgent = null, this.retrieveId(); + } + return f(a, [ { + key: "setup", + value: function() { + var a = j.detect(); + this.browserName = a.browserName, this.browserVersion = a.browserVersion, this.osName = a.os, + this.osVersion = a.osVersion, this.codeBase = a.codeBase, this.userAgent = a.userAgent; + } + }, { + key: "retrieveId", + value: function() { + var a = this, b = h.get("endpointID"); + if (null === b) { + var c = l.getCurrent(), d = Math.random() * c; + n.generateSHA256(d.toString(), function(b) { + a.id = b, h.store("endpointID", b); + }); + } else this.id = b; + } + }, { + key: "getId", + value: function() { + return this.id; + } + }, { + key: "getAppVersion", + value: function() { + return this.appversion; + } + }, { + key: "setAppVersion", + value: function(a) { + this.appversion = a; + } + }, { + key: "getMagicKey", + value: function() { + return this.magicKey; + } + }, { + key: "getBrowserName", + value: function() { + return this.browserName; + } + }, { + key: "getBrowserVersion", + value: function() { + return this.browserVersion; + } + }, { + key: "getOsName", + value: function() { + return this.osName; + } + }, { + key: "getOsVersion", + value: function() { + return this.osVersion; + } + }, { + key: "getCodeBase", + value: function() { + return this.codeBase; + } + }, { + key: "getUserAgent", + value: function() { + return this.userAgent; + } + }, { + key: "serialize", + value: function() { + return { + type: "browser", + buildName: this.browserName, + buildVersion: this.browserVersion, + appVersion: this.appversion, + os: this.osName, + osVersion: this.osVersion, + userAgent: this.userAgent + }; + } + } ]), a; + }(); + c.Endpoint = o; + }, { + "../browserapi/detectbrowser": 17, + "../browserapi/localstorage": 19, + "../utility/hash": 91, + "../utility/timestamps": 98 + } ], + 89: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.EventMessage = void 0; + var f = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(a) { + return typeof a; + } : function(a) { + return a && "function" == typeof Symbol && a.constructor === Symbol && a !== Symbol.prototype ? "symbol" : typeof a; + }, g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = a("../config/constants"), i = d(h), j = a("../config/settings"), k = d(j), l = a("./registry"), m = a("./csiologger"), n = d(m), o = function() { + function a(b, c, d, f) { + e(this, a), this.eventType = b, this.customEntries = d, this.pcHandler = f, this.auth = l.Registry.getAuthenticator(), + this.clocksync = l.Registry.getClockSync(), this.timestamp = this.clocksync.getSynchronizedTimestamp(), + this.conferenceId = c, this.clockUnSynced = !this.clocksync.isCompleted(); + } + return g(a, [ { + key: "updateConferenceId", + value: function(a) { + n.log("updating conferenceId to ", this.eventType, this.conferenceId, a), this.conferenceId = a; + } + }, { + key: "toJson", + value: function() { + if (!this.canBeSent()) return null; + var a = this.getCommonHeader(); + return Object.assign(a, this.customEntries), this.eventType === i.internalFabricEvent.userJoined && delete a.connectionID, + a; + } + }, { + key: "getCallback", + value: function() { + return this.pcHandler ? this.pcHandler.getCallback() : null; + } + }, { + key: "canBeSent", + value: function() { + var a = void 0, b = i.tmpConferenceId; + if (this.conferenceId === b) return !1; + if (this.pcHandler && !this.pcHandler.getRemoteId()) return !1; + if (this.eventType !== i.precalltestEvents.results) { + var c = l.Registry.getConferenceManager().get(this.conferenceId); + if (!c) return !1; + a = c.getUcId(); + } + return !!this.auth.getToken() && (this.auth.isTokenValid() ? !!(this.isPriority() || this.clocksync.isCompleted() && a) && !(this.eventType === i.internalFabricEvent.userAlive && !a) : (this.auth.reAuthenticate(), + !1)); + } + }, { + key: "isCachable", + value: function() { + return -1 === [ i.internalFabricEvent.userAlive ].indexOf(this.eventType); + } + }, { + key: "isPriority", + value: function() { + var a = !1; + return this.eventType !== i.internalFabricEvent.userJoined && this.eventType !== i.precalltestEvents.results && this.eventType !== i.internalFabricEvent.userAlive || (a = !0), + a; + } + }, { + key: "getConferenceId", + value: function() { + return this.conferenceId; + } + }, { + key: "getCommonHeader", + value: function() { + var a = { + version: k.version, + callstatsVersion: k.version, + channel: this.decideChannel(), + timestamp: this.timestamp, + action: this.eventType, + eventType: this.eventType, + localID: encodeURIComponent(l.Registry.getCredentials().getUserId()), + timeShift: 0, + appID: l.Registry.getCredentials().getAppId(), + deviceID: l.Registry.getEndpoint().getId(), + token: this.auth.getToken(), + confID: encodeURIComponent(this.conferenceId) + }; + this.clockUnSynced && (a.timestamp += this.clocksync.getOffset()); + var b = l.Registry.getConferenceManager().get(this.conferenceId); + return a.ucID = b ? b.getUcId() : null, this.eventType !== i.callstatsChannels.userFeedback && this.eventType !== i.precalltestEvents.results && (this.pcHandler ? (a.remoteID = encodeURIComponent(this.pcHandler.getRemoteId()), + a.connectionID = this.pcHandler.getPcHash()) : (a.remoteID = encodeURIComponent(l.Registry.getCredentials().getUserId()), + a.connectionID = encodeURIComponent(l.Registry.getCredentials().getUserId()))), + a; + } + }, { + key: "decideChannel", + value: function() { + if (this.eventType == i.callstatsChannels.sdpSubmission) return i.callstatsChannels.sdpSubmission; + if (this.eventType == i.callstatsChannels.userFeedback) return i.callstatsChannels.userFeedback; + if (this.eventType == i.callstatsChannels.processedStats) return i.callstatsChannels.processedStats; + for (var a in i.precalltestEvents) if (this.eventType == i.precalltestEvents[a]) return i.callstatsChannels.preCallTest; + return i.callstatsChannels.callstatsEvent; + } + } ], [ { + key: "checkCustomEntries", + value: function(a, b) { + if (!p[a]) return n.error("eventType not recognized:", a), !1; + var c = p[a]; + for (var d in c) if (!b.hasOwnProperty(d) || f(b[d]) !== c[d]) return n.error("customEntries for", a, "should have", d, "of type", c[d]), + !1; + return !0; + } + } ]), a; + }(), p = {}; + p[i.internalFabricEvent.userJoined] = { + endpointInfo: "object" + }, p[i.internalFabricEvent.userLeft] = {}, p[i.internalFabricEvent.userAlive] = {}, + p[i.internalFabricEvent.userDetails] = { + userName: "string" + }, p[i.internalFabricEvent.connectedDeviceList] = { + mediaDeviceList: "object" + }, p[i.fabricEvent.activeDeviceList] = { + mediaDeviceList: "object" + }, p[i.fabricEvent.audioMute] = {}, p[i.fabricEvent.audioUnmute] = {}, p[i.fabricEvent.videoPause] = {}, + p[i.fabricEvent.videoResume] = {}, p[i.fabricEvent.screenShareStart] = {}, p[i.fabricEvent.screenShareStop] = {}, + p[i.internalFabricEvent.mediaPlaybackStart] = { + ssrc: "string" + }, p[i.internalFabricEvent.mediaPlaybackSuspended] = { + ssrc: "string" + }, p[i.internalFabricEvent.mediaPlaybackStalled] = { + ssrc: "string" + }, p[i.internalFabricEvent.oneWayMedia] = { + mediaType: "string", + ssrc: "string" + }, p[i.internalFabricEvent.fabricSetup] = { + localIceCandidates: "object", + remoteIceCandidates: "object", + iceCandidatePairs: "object" + }, p[i.fabricEvent.fabricSetupFailed] = { + failureDelay: "number", + reason: "string", + function: "string", + endpoint: "object" + }, p[i.internalFabricEvent.fabricStateChange] = { + changedState: "string", + prevState: "string", + newState: "string" + }, p[i.internalFabricEvent.fabricDropped] = { + prevIceConnectionState: "string", + currIceConnectionState: "string", + currIceCandidatePair: "object", + failureDelay: "number" + }, p[i.internalFabricEvent.iceConnectionDisruptionStart] = { + prevIceConnectionState: "string", + currIceConnectionState: "string", + prevIceConnectionStateTs: "number", + currIceCandidatePair: "object" + }, p[i.internalFabricEvent.iceConnectionDisruptionEnd] = { + prevIceConnectionState: "string", + currIceConnectionState: "string", + disruptionDelay: "number" + }, p[i.internalFabricEvent.iceDisruptionStart] = { + prevIceConnectionState: "string", + currIceConnectionState: "string", + prevIceConnectionStateTs: "number", + currIceCandidatePair: "object" + }, p[i.internalFabricEvent.iceDisruptionEnd] = { + prevIceConnectionState: "string", + currIceConnectionState: "string", + prevIceCandidatePair: "object" + }, p[i.internalFabricEvent.iceFailed] = { + localIceCandidates: "object", + prevIceConnectionState: "string", + currIceConnectionState: "string", + currIceCandidatePair: "object", + failureDelay: "number" + }, p[i.internalFabricEvent.iceAborted] = { + prevIceConnectionState: "string", + currIceConnectionState: "string" + }, p[i.internalFabricEvent.iceRestarted] = { + prevIceConnectionState: "string", + currIceConnectionState: "string", + prevIceCandidatePair: "object" + }, p[i.internalFabricEvent.fabricTransportSwitch] = { + prevIceCandidatePair: "object", + currIceCandidatePair: "object" + }, p[i.internalFabricEvent.iceTerminated] = { + prevIceConnectionState: "string", + currIceConnectionState: "string" + }, p[i.fabricEvent.fabricTerminated] = {}, p[i.fabricEvent.fabricHold] = {}, p[i.fabricEvent.fabricResume] = {}, + p[i.callstatsChannels.sdpSubmission] = { + localSDP: "string", + remoteSDP: "string" + }, p[i.internalFabricEvent.ssrcMap] = { + ssrcData: "object" + }, p[i.callstatsChannels.userFeedback] = { + feedback: "object" + }, p[i.internalFabricEvent.sendingThroughputObservations] = { + ssrc: "string", + maxsendingKBitrate: "number", + timeToMaxSendingKBitrate: "number", + stablesendingKBitrate: "number", + timeToStableSendingKBitrate: "number" + }, p[i.fabricEvent.dominantSpeaker] = {}, p[i.fabricEvent.applicationErrorLog] = { + message: "string", + messageType: "string" + }, p[i.callstatsChannels.processedStats] = { + stats: "object" + }, p[i.callstatsChannels.senderConfiguration] = { + rtc_rtp_parameters: "object" + }, p[i.internalFabricEvent.limitationObservations] = { + reason: "string" + }, p[i.qualityDisruptionTypes.qpchange] = { + reason: "string" + }, p[i.precalltestEvents.results] = { + results: "object" + }, p[i.precalltestEvents.associate] = { + ids: "object" + }, c.EventMessage = o; + }, { + "../config/constants": 32, + "../config/settings": 33, + "./csiologger": 87, + "./registry": 94 + } ], + 90: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.EventMessageBuilder = void 0; + var f = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(a) { + return typeof a; + } : function(a) { + return a && "function" == typeof Symbol && a.constructor === Symbol && a !== Symbol.prototype ? "symbol" : typeof a; + }, g = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), h = a("./eventmessage"), i = a("../config/constants"), j = d(i), k = a("./registry"), l = a("./csiologger"), m = d(l), n = function() { + function a() { + e(this, a), this.transmissionmanager = k.Registry.getTransmissionManager(); + } + return g(a, [ { + key: "make", + value: function(a, b, c) { + var d = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}; + if ("string" != typeof a || null === d || "object" !== (void 0 === d ? "undefined" : f(d))) return m.error("failed typeof checks:", a, void 0 === a ? "undefined" : f(a), void 0 === d ? "undefined" : f(d), d), + k.Registry.getGenericEventHandler().sendEvent(j.logEvents.error, { + msg: "failed typeof checks:" + a + ":" + (void 0 === d ? "undefined" : f(d)) + }), !1; + if (null === b && a !== j.precalltestEvents.results) return m.error("failed conferenceId checks:", a, b), + k.Registry.getGenericEventHandler().sendEvent(j.logEvents.error, { + msg: "failed conferenceId checks:" + a + }), !1; + if (!c && a !== j.callstatsChannels.userFeedback && a !== j.fabricEvent.applicationErrorLog && a !== j.fabricEvent.fabricSetupFailed && a !== j.precalltestEvents.results) return m.error("peerconnection cannot be null", a), + k.Registry.getGenericEventHandler().sendEvent(j.logEvents.error, { + msg: "peerconnection cannot be null" + a + }), !1; + if (!h.EventMessage.checkCustomEntries(a, d)) return m.error("failed checks:", a, d), + k.Registry.getGenericEventHandler().sendEvent(j.logEvents.error, { + msg: "failed customEntries checks:" + a + }), !1; + var e = void 0; + if (b) { + var g = k.Registry.getConferenceManager().get(b); + g && c && (e = g.getPeerConnectionManager().getPcHandler(c)); + } + var i = new h.EventMessage(a, b, d, e); + return this.transmissionmanager.send(i), !0; + } + } ]), a; + }(); + c.EventMessageBuilder = n; + }, { + "../config/constants": 32, + "./csiologger": 87, + "./eventmessage": 89, + "./registry": 94 + } ], + 91: [ function(a, b, c) { + "use strict"; + function d(a, b) { + var c = { + name: "SHA-256" + }; + if (window.crypto) { + var d = window.crypto.subtle || window.crypto.webkitSubtle; + if (!d) return void e(a, b); + d.digest(c, f(a)).then(function(a) { + b(g(a)); + }).catch(function() { + e(a, b); + }); + } else if (window.msCrypto) { + if (!window.msCrypto.subtle) return void e(a, b); + var h = window.msCrypto.subtle.digest(c, f(a)); + h.oncomplete = function(a) { + a.target && b(g(a.target.result)); + }, h.onerror = function() { + e(a, b); + }; + } else e(a, b); + } + function e(a) { + var b = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null, c = 0; + if (!a) return c; + for (var d = 0, e = a.length; d < e; d++) { + c = (c << 5) - c + a.charCodeAt(d), c |= 0; + } + return b && b(c + ""), c + ""; + } + function f(a) { + for (var b = [], c = 0; c < a.length; ++c) { + var d = a.charCodeAt(c); + d < 128 ? b[b.length] = d : d > 127 && d < 2048 ? (b[b.length] = d >> 6 | 192, b[b.length] = 63 & d | 128) : (b[b.length] = d >> 12 | 224, + b[b.length] = d >> 6 & 63 | 128, b[b.length] = 63 & d | 128); + } + return new Uint8Array(b).buffer; + } + function g(a) { + for (var b = new DataView(a), c = "", d = void 0, e = 0; e < b.byteLength; e++) d = b.getUint8(e).toString(16), + d.length < 2 && (d = "0" + d), c += d; + return c; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.generateSHA256 = d, c.generateHash = e; + }, {} ], + 92: [ function(a, b, c) { + "use strict"; + function d(a) { + return !!/^[\],:{}\s]*$/.test(a.replace(/\\["\\\/bfnrtu]/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, "")); + } + function e(a) { + var b = null; + return null === a ? b : (d(a) && (b = JSON.parse(a)), b); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.isValid = d, c.parse = e; + }, {} ], + 93: [ function(a, b, c) { + "use strict"; + function d(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + } + function e() { + window && window.addEventListener && window.addEventListener("error", function(a) { + var b = f.Registry.getGenericEventHandler(); + if (a && a.filename && a.filename.indexOf("callstats") > -1) { + for (var c = !1, d = { + fileName: a.filename, + line: a.lineno, + col: a.colno, + jsVersion: h.version, + eventType: "error", + message: a.message, + pageURL: window.location.href + }, e = f.Registry.getConferenceManager().getConferenceIds(), g = 0; g < e.length; g++) d.conferenceID = e[g], + b.sendEvent(j.logEvents.error, d), c = !0; + c || b.sendEvent(j.logEvents.error, d); + } + }); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.setErrorEventListener = e; + var f = a("./registry"), g = a("../config/settings"), h = d(g), i = a("../config/constants"), j = d(i); + }, { + "../config/constants": 32, + "../config/settings": 33, + "./registry": 94 + } ], + 94: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.Registry = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("../services/clocksync"), g = a("../services/configservice/configservicewrapper"), h = a("../services/authenticator"), i = a("../services/backendlog"), j = a("../services/transmissionmanager"), k = a("./eventmessagebuilder"), l = a("../conference/conferencemanager"), m = a("../utility/credentials"), n = a("../statspipeline/statsadapter"), o = a("../statspipeline/statsparser"), p = a("../statspipeline/statsmonitor"), q = a("../statspipeline/statstransmitter"), r = a("../statspipeline/statsassembler"), s = a("../utility/endpoint"), t = a("../browserapi/battery"), u = a("precalltest"), v = a("../statspipeline/wifistatsexecutor"), w = a("./callbacks"), x = a("../statspipeline/statscallbackbuilder"), y = a("../services/connectionmanager"), z = null, A = null, B = null, C = null, D = null, E = null, F = null, G = null, H = null, I = null, J = null, K = null, L = null, M = null, N = null, O = null, P = null, Q = null, R = null, S = null, T = function() { + function a() { + d(this, a); + } + return e(a, null, [ { + key: "getConferenceManager", + value: function() { + return O || (O = new l.ConferenceManager()), O; + } + }, { + key: "getStatsCallbackBuilder", + value: function() { + return R || (R = new x.StatsCallbackBuilder()), R; + } + }, { + key: "getClockSync", + value: function() { + return A || (A = new f.ClockSync()), A; + } + }, { + key: "getWifiStatsExecutor", + value: function() { + return P || (P = new v.WifiStatsExecutor()), P; + } + }, { + key: "getAuthenticator", + value: function() { + return B || (B = new h.Authenticator()), B; + } + }, { + key: "getConfigServiceWrapper", + value: function() { + return C || (C = new g.ConfigServiceWrapper()), C; + } + }, { + key: "getGenericEventHandler", + value: function() { + return D || (D = new i.GenericEventHandler(), D.enable()), D; + } + }, { + key: "getConnectionManager", + value: function() { + return S || (S = new y.ConnectionManager()), S; + } + }, { + key: "getTransmissionManager", + value: function() { + return E || (E = new j.TransmissionManager()), E; + } + }, { + key: "getEventMessageBuilder", + value: function() { + return F || (F = new k.EventMessageBuilder()), F; + } + }, { + key: "getCredentials", + value: function() { + return G || (G = new m.Credentials()), G; + } + }, { + key: "getEndpoint", + value: function() { + return H || (H = new s.Endpoint()), H; + } + }, { + key: "getStatsAdapter", + value: function() { + if (!I) { + var b = a.getEndpoint().getCodeBase(), c = a.getEndpoint().getBrowserName(); + I = new n.StatsAdapter(b, c); + } + return I; + } + }, { + key: "getPreCallTest", + value: function() { + return z || (z = new u.PreCallTest()), z; + } + }, { + key: "getStatsParser", + value: function() { + return J || (J = new o.StatsParser()), J; + } + }, { + key: "getStatsMonitor", + value: function() { + if (!K) { + var b = a.getEndpoint().getCodeBase(); + K = new p.StatsMonitor(b); + } + return K; + } + }, { + key: "getStatsTransmitter", + value: function() { + return L || (L = new q.StatsTransmitter()), L; + } + }, { + key: "getStatsAssembler", + value: function() { + return M || (M = new r.StatsAssembler()), M; + } + }, { + key: "getBattery", + value: function() { + return N || (N = new t.Battery()), N; + } + }, { + key: "getCallbacks", + value: function() { + return Q || (Q = new w.Callbacks()), Q; + } + } ]), a; + }(); + c.Registry = T; + }, { + "../browserapi/battery": 16, + "../conference/conferencemanager": 30, + "../services/authenticator": 43, + "../services/backendlog": 44, + "../services/clocksync": 45, + "../services/configservice/configservicewrapper": 49, + "../services/connectionmanager": 50, + "../services/transmissionmanager": 55, + "../statspipeline/statsadapter": 68, + "../statspipeline/statsassembler": 69, + "../statspipeline/statscallbackbuilder": 70, + "../statspipeline/statsmonitor": 71, + "../statspipeline/statsparser": 72, + "../statspipeline/statstransmitter": 73, + "../statspipeline/wifistatsexecutor": 83, + "../utility/credentials": 86, + "../utility/endpoint": 88, + "./callbacks": 85, + "./eventmessagebuilder": 90, + precalltest: 2 + } ], + 95: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + function e() { + return null === i && (i = new j()), i; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(); + c.getRTTRegistry = e; + var g = a("../statspipeline/validator"), h = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(g), i = null, j = function() { + function a() { + d(this, a), this.rtts = new Map(), this.transportRTT = null; + } + return f(a, [ { + key: "update", + value: function(a) { + var b = this; + a.getStats(function(a) { + for (var c = [], d = a.result(), e = 0; e < d.length; ++e) { + var f = d[e]; + if ("googCandidatePair" !== f.type) { + if ("ssrc" === f.type) { + var g = f.stat("googRtt"), i = f.stat("ssrc"); + g && b.rtts.set(h.checkForNan(parseInt(i, 10)), h.checkForNan(parseInt(g, 10))); + } + } else { + var j = f.stat("googRtt"); + c.push(j); + } + } + b.transportRTT = Math.max.apply(Math, c); + }); + } + }, { + key: "getTransportRTT", + value: function() { + return this.transportRTT; + } + }, { + key: "getRTT", + value: function(a) { + var b = h.checkForNan(parseInt(a, 10)); + return this.rtts.has(b) ? this.rtts.get(b) : null; + } + } ]), a; + }(); + }, { + "../statspipeline/validator": 82 + } ], + 96: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = function() { + function a(b, c, e) { + d(this, a), this.max = b, this.midpoint = c, this.stepness = e, this.actualStep = 0, + this.reset(); + } + return e(a, [ { + key: "reset", + value: function() { + this.actualStep = 0; + } + }, { + key: "setMidpoint", + value: function(a) { + this.midpoint = a; + } + }, { + key: "setMax", + value: function(a) { + this.max = a; + } + }, { + key: "setStepness", + value: function(a) { + this.stepness = a; + } + }, { + key: "increaseActualStep", + value: function(a) { + this.actualStep += a; + } + }, { + key: "getActual", + value: function() { + var a = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 1; + return this.actualStep += a, this.max / (1 + Math.exp(-1 * this.stepness * (this.actualStep - this.midpoint))); + } + } ]), a; + }(); + c.Sigmoid = f; + }, {} ], + 97: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.TimeoutProcess = void 0; + var e = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), f = a("./csiologger"), g = function(a) { + if (a && a.__esModule) return a; + var b = {}; + if (null != a) for (var c in a) Object.prototype.hasOwnProperty.call(a, c) && (b[c] = a[c]); + return b.default = a, b; + }(f), h = function() { + function a(b) { + d(this, a), this.interval = b, this.timerId = null, this.callback = function() { + g.warn("no callback function set", this); + }; + } + return e(a, [ { + key: "setCallback", + value: function(a) { + this.callback = a; + } + }, { + key: "start", + value: function() { + var a = this; + this.timerId = setInterval(function() { + a.callback(); + }, this.interval); + } + }, { + key: "stop", + value: function() { + clearInterval(this.timerId), this.timerId = null; + } + }, { + key: "isStarted", + value: function() { + return null !== this.timerId; + } + } ]), a; + }(); + c.TimeoutProcess = h; + }, { + "./csiologger": 87 + } ], + 98: [ function(a, b, c) { + "use strict"; + function d() { + return window && window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now(); + } + function e() { + return window && window.performance && window.performance.now ? window.performance.now() : null; + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.getCurrent = d, c.getSinceOrigin = e; + }, {} ], + 99: [ function(a, b, c) { + "use strict"; + function d(a, b) { + if (!(a instanceof b)) throw new TypeError("Cannot call a class as a function"); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }); + var e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(a) { + return typeof a; + } : function(a) { + return a && "function" == typeof Symbol && a.constructor === Symbol && a !== Symbol.prototype ? "symbol" : typeof a; + }, f = function() { + function a(a, b) { + for (var c = 0; c < b.length; c++) { + var d = b[c]; + d.enumerable = d.enumerable || !1, d.configurable = !0, "value" in d && (d.writable = !0), + Object.defineProperty(a, d.key, d); + } + } + return function(b, c, d) { + return c && a(b.prototype, c), d && a(b, d), b; + }; + }(), g = function() { + function a(b) { + d(this, a), this.base = b; + for (var c = arguments.length, e = Array(c > 1 ? c - 1 : 0), f = 1; f < c; f++) e[f - 1] = arguments[f]; + this.appendixes = e; + } + return f(a, null, [ { + key: "concat", + value: function(a, b) { + if (!b) return a; + if (!a) return b; + var c = "/" === a.substr(a.length - 1), d = "/" === b.substring(0, 1); + return c || d ? c && d ? a + b.substring(1) : a + b : a + "/" + b; + } + } ]), f(a, [ { + key: "append", + value: function(a) { + this.appendixes.push(a); + } + }, { + key: "toString", + value: function() { + var b = this.getString(this.base), c = this; + return this.appendixes.forEach(function(d) { + if (null !== d && void 0 !== d) { + var e = c.getString(d); + b = a.concat(b, e); + } + }), b; + } + }, { + key: "getString", + value: function(a) { + switch (void 0 === a ? "undefined" : e(a)) { + case "function": + return this.getString(a()); + + case "number": + return a + ""; + + case "string": + default: + return a; + } + } + } ]), a; + }(); + c.Url = g; + }, {} ], + 100: [ function(a, b, c) { + "use strict"; + function d(a) { + var b = []; + if (!a) return b; + for (var c = 0; c < a.length; c++) { + var d = {}; + d.mediaDeviceID = a[c].deviceId, d.groupID = a[c].groupId, d.kind = a[c].kind, d.label = a[c].label, + b.push(d); + } + return b; + } + function e() { + Number.isInteger || (Number.isInteger = Number.isInteger || function(a) { + return "number" == typeof a && isFinite(a) && Math.floor(a) === a; + }); + } + function f() { + "function" != typeof Object.assign && Object.defineProperty(Object, "assign", { + value: function(a, b) { + if (null == a) throw new TypeError("Cannot convert undefined or null to object"); + for (var c = Object(a), d = 1; d < arguments.length; d++) { + var e = arguments[d]; + if (null != e) for (var f in e) Object.prototype.hasOwnProperty.call(e, f) && (c[f] = e[f]); + } + return c; + }, + writable: !0, + configurable: !0 + }); + } + Object.defineProperty(c, "__esModule", { + value: !0 + }), c.normalizeMediaDeviceList = d, c.isIntegerPollyfill = e, c.assignPollyfill = f; + }, {} ] +}, {}, [ 21 ]); \ No newline at end of file diff --git a/webApp-plivo/public/lib/plivostats.min.js b/webApp-plivo/public/lib/plivostats.min.js deleted file mode 100644 index a80d04e..0000000 --- a/webApp-plivo/public/lib/plivostats.min.js +++ /dev/null @@ -1,26 +0,0 @@ -/*** -Copyright (c) 2013-2016, callstats.io -All rights reserved. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. -***/ - -/*! callstats.js version = 3.25.0 2017-10-03 */ -!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g0;){var b=a.shift();if("function"==typeof b){var c=a.shift(),d=a.shift();b.call(c,d)}else b._settlePromises()}},e.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},e.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},e.prototype._reset=function(){this._isTickUsed=!1},c.exports=e,c.exports.firstLineError=i},{"./queue":26,"./schedule":29,"./util":36}],3:[function(a,b,c){"use strict";b.exports=function(a,b,c,d){var e=!1,f=function(a,b){this._reject(b)},g=function(a,b){b.promiseRejectionQueued=!0,b.bindingPromise._then(f,f,null,this,a)},h=function(a,b){0===(50397184&this._bitField)&&this._resolveCallback(b.target)},i=function(a,b){b.promiseRejectionQueued||this._reject(a)};a.prototype.bind=function(f){e||(e=!0,a.prototype._propagateFrom=d.propagateFromFunction(),a.prototype._boundValue=d.boundValueFunction());var j=c(f),k=new a(b);k._propagateFrom(this,1);var l=this._target();if(k._setBoundTo(j),j instanceof a){var m={promiseRejectionQueued:!1,promise:k,target:l,bindingPromise:j};l._then(b,g,void 0,k,m),j._then(h,i,void 0,k,m),k._setOnCancel(j)}else k._resolveCallback(l);return k},a.prototype._setBoundTo=function(a){void 0!==a?(this._bitField=2097152|this._bitField,this._boundTo=a):this._bitField=this._bitField&-2097153},a.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},a.bind=function(b,c){return a.resolve(c).bind(b)}}},{}],4:[function(a,b,c){"use strict";function d(){try{Promise===f&&(Promise=e)}catch(a){}return f}var e;"undefined"!=typeof Promise&&(e=Promise);var f=a("./promise")();f.noConflict=d,b.exports=f},{"./promise":22}],5:[function(a,b,c){"use strict";var d=Object.create;if(d){var e=d(null),f=d(null);e[" size"]=f[" size"]=0}b.exports=function(b){function c(a,c){var d;if(null!=a&&(d=a[c]),"function"!=typeof d){var e="Object "+h.classString(a)+" has no method '"+h.toString(c)+"'";throw new b.TypeError(e)}return d}function d(a){var b=this.pop(),d=c(a,b);return d.apply(a,this)}function e(a){return a[this]}function f(a){var b=+this;return b<0&&(b=Math.max(0,b+a.length)),a[b]}var g,h=a("./util"),i=h.canEvaluate;h.isIdentifier;b.prototype.call=function(a){var b=[].slice.call(arguments,1);return b.push(a),this._then(d,void 0,void 0,b,void 0)},b.prototype.get=function(a){var b,c="number"==typeof a;if(c)b=f;else if(i){var d=g(a);b=null!==d?d:e}else b=e;return this._then(b,void 0,void 0,a,void 0)}}},{"./util":36}],6:[function(a,b,c){"use strict";b.exports=function(b,c,d,e){var f=a("./util"),g=f.tryCatch,h=f.errorObj,i=b._async;b.prototype.break=b.prototype.cancel=function(){if(!e.cancellation())return this._warn("cancellation is disabled");for(var a=this,b=a;a._isCancellable();){if(!a._cancelBy(b)){b._isFollowing()?b._followee().cancel():b._cancelBranched();break}var c=a._cancellationParent;if(null==c||!c._isCancellable()){a._isFollowing()?a._followee().cancel():a._cancelBranched();break}a._isFollowing()&&a._followee().cancel(),a._setWillBeCancelled(),b=a,a=c}},b.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},b.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},b.prototype._cancelBy=function(a){return a===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},b.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},b.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),i.invoke(this._cancelPromises,this,void 0))},b.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},b.prototype._unsetOnCancel=function(){this._onCancelField=void 0},b.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},b.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},b.prototype._doInvokeOnCancel=function(a,b){if(f.isArray(a))for(var c=0;c=0)return f[a]}var e=!1,f=[];return a.prototype._promiseCreated=function(){},a.prototype._pushContext=function(){},a.prototype._popContext=function(){return null},a._peekContext=a.prototype._peekContext=function(){},b.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,f.push(this._trace))},b.prototype._popContext=function(){if(void 0!==this._trace){var a=f.pop(),b=a._promiseCreated;return a._promiseCreated=null,b}return null},b.CapturedTrace=null,b.create=c,b.deactivateLongStackTraces=function(){},b.activateLongStackTraces=function(){var c=a.prototype._pushContext,f=a.prototype._popContext,g=a._peekContext,h=a.prototype._peekContext,i=a.prototype._promiseCreated;b.deactivateLongStackTraces=function(){a.prototype._pushContext=c,a.prototype._popContext=f,a._peekContext=g,a.prototype._peekContext=h,a.prototype._promiseCreated=i,e=!1},e=!0,a.prototype._pushContext=b.prototype._pushContext,a.prototype._popContext=b.prototype._popContext,a._peekContext=a.prototype._peekContext=d,a.prototype._promiseCreated=function(){var a=this._peekContext();a&&null==a._promiseCreated&&(a._promiseCreated=this)}},b}},{}],9:[function(b,c,d){"use strict";c.exports=function(c,d){function e(a,b){return{promise:b}}function f(){return!1}function g(a,b,c){var d=this;try{a(b,c,function(a){if("function"!=typeof a)throw new TypeError("onCancel must be a function, got: "+N.toString(a));d._attachCancellationCallback(a)})}catch(a){return a}}function h(a){if(!this._isCancellable())return this;var b=this._onCancel();void 0!==b?N.isArray(b)?b.push(a):this._setOnCancel([b,a]):this._setOnCancel(a)}function i(){return this._onCancelField}function j(a){this._onCancelField=a}function k(){this._cancellationParent=void 0,this._onCancelField=void 0}function l(a,b){if(0!==(1&b)){this._cancellationParent=a;var c=a._branchesRemainingToCancel;void 0===c&&(c=0),a._branchesRemainingToCancel=c+1}0!==(2&b)&&a._isBound()&&this._setBoundTo(a._boundTo)}function m(a,b){0!==(2&b)&&a._isBound()&&this._setBoundTo(a._boundTo)}function n(){var a=this._boundTo;return void 0!==a&&a instanceof c?a.isFulfilled()?a.value():void 0:a}function o(){this._trace=new G(this._peekContext())}function p(a,b){if(O(a)){var c=this._trace;if(void 0!==c&&b&&(c=c._parent),void 0!==c)c.attachExtraTrace(a);else if(!a.__stackCleaned__){var d=y(a);N.notEnumerableProp(a,"stack",d.message+"\n"+d.stack.join("\n")),N.notEnumerableProp(a,"__stackCleaned__",!0)}}}function q(a,b,c,d,e){if(void 0===a&&null!==b&&Y){if(void 0!==e&&e._returnedNonUndefined())return;if(0===(65535&d._bitField))return;c&&(c+=" ");var f="",g="";if(b._trace){for(var h=b._trace.stack.split("\n"),i=w(h),j=i.length-1;j>=0;--j){var k=i[j];if(!Q.test(k)){var l=k.match(R);l&&(f="at "+l[1]+":"+l[2]+":"+l[3]+" ");break}}if(i.length>0)for(var m=i[0],j=0;j0&&(g="\n"+h[j-1]);break}}var n="a promise was created in a "+c+"handler "+f+"but was not returned from it, see http://goo.gl/rRqMUw"+g;d._warn(n,!0,b)}}function r(a,b){var c=a+" is deprecated and will be removed in a future version.";return b&&(c+=" Use "+b+" instead."),s(c)}function s(a,b,d){if(ga.warnings){var e,f=new M(a);if(b)d._attachExtraTrace(f);else if(ga.longStackTraces&&(e=c._peekContext()))e.attachExtraTrace(f);else{var g=y(f);f.stack=g.message+"\n"+g.stack.join("\n")}ba("warning",f)||z(f,"",!0)}}function t(a,b){for(var c=0;c=0;--h)if(d[h]===f){g=h;break}for(var h=g;h>=0;--h){var i=d[h];if(b[e]!==i)break;b.pop(),e--}b=d}}function w(a){for(var b=[],c=0;c0&&"SyntaxError"!=a.name&&(b=b.slice(c)),b}function y(a){var b=a.stack,c=a.toString();return b="string"==typeof b&&b.length>0?x(a):[" (No stack trace)"],{message:c,stack:"SyntaxError"==a.name?b:w(b)}}function z(a,b,c){if("undefined"!=typeof console){var d;if(N.isObject(a)){var e=a.stack;d=b+T(e,a)}else d=b+String(a);"function"==typeof J?J(d,c):"function"==typeof console.log||"object"==typeof console.log}}function A(a,b,c,d){var e=!1;try{"function"==typeof b&&(e=!0,"rejectionHandled"===a?b(d):b(c,d))}catch(a){L.throwLater(a)}"unhandledRejection"===a?ba(a,c,d)||e||z(c,"Unhandled rejection "):ba(a,d)}function B(a){var b;if("function"==typeof a)b="[function "+(a.name||"anonymous")+"]";else{b=a&&"function"==typeof a.toString?a.toString():N.toString(a);var c=/\[object [a-zA-Z0-9$_]+\]/;if(c.test(b))try{var d=JSON.stringify(a);b=d}catch(a){}0===b.length&&(b="(empty array)")}return"(<"+C(b)+">, no stack trace)"}function C(a){var b=41;return a.length=h||(da=function(a){if(P.test(a))return!0;var b=E(a);return!!(b&&b.fileName===c&&g<=b.line&&b.line<=h)})}}function G(a){this._parent=a,this._promisesCreated=0;var b=this._length=1+(void 0===a?0:a._length);fa(this,G),b>32&&this.uncycle()}var H,I,J,K=c._getDomain,L=c._async,M=b("./errors").Warning,N=b("./util"),O=N.canAttachTrace,P=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,Q=/\((?:timers\.js):\d+:\d+\)/,R=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,S=null,T=null,U=!1,V=!(0==N.env("BLUEBIRD_DEBUG")),W=!(0==N.env("BLUEBIRD_WARNINGS")||!V&&!N.env("BLUEBIRD_WARNINGS")),X=!(0==N.env("BLUEBIRD_LONG_STACK_TRACES")||!V&&!N.env("BLUEBIRD_LONG_STACK_TRACES")),Y=0!=N.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(W||!!N.env("BLUEBIRD_W_FORGOTTEN_RETURN"));c.prototype.suppressUnhandledRejections=function(){var a=this._target();a._bitField=a._bitField&-1048577|524288},c.prototype._ensurePossibleRejectionHandled=function(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),L.invokeLater(this._notifyUnhandledRejection,this,void 0))},c.prototype._notifyUnhandledRejectionIsHandled=function(){A("rejectionHandled",H,void 0,this)},c.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},c.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},c.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var a=this._settledValue();this._setUnhandledRejectionIsNotified(),A("unhandledRejection",I,a,this)}},c.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},c.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=this._bitField&-262145},c.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},c.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},c.prototype._unsetRejectionIsUnhandled=function(){this._bitField=this._bitField&-1048577,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},c.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},c.prototype._warn=function(a,b,c){return s(a,b,c||this)},c.onPossiblyUnhandledRejection=function(a){var b=K();I="function"==typeof a?null===b?a:N.domainBind(b,a):void 0},c.onUnhandledRejectionHandled=function(a){var b=K();H="function"==typeof a?null===b?a:N.domainBind(b,a):void 0};var Z=function(){};c.longStackTraces=function(){if(L.haveItemsQueued()&&!ga.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ga.longStackTraces&&D()){var a=c.prototype._captureStackTrace,b=c.prototype._attachExtraTrace;ga.longStackTraces=!0,Z=function(){if(L.haveItemsQueued()&&!ga.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");c.prototype._captureStackTrace=a,c.prototype._attachExtraTrace=b,d.deactivateLongStackTraces(),L.enableTrampoline(),ga.longStackTraces=!1},c.prototype._captureStackTrace=o,c.prototype._attachExtraTrace=p,d.activateLongStackTraces(),L.disableTrampolineIfNecessary()}},c.hasLongStackTraces=function(){return ga.longStackTraces&&D()};var $=function(){try{if("function"==typeof CustomEvent){var a=new CustomEvent("CustomEvent");return N.global.dispatchEvent(a),function(a,b){var c=new CustomEvent(a.toLowerCase(),{detail:b,cancelable:!0});return!N.global.dispatchEvent(c)}}if("function"==typeof Event){var a=new Event("CustomEvent");return N.global.dispatchEvent(a),function(a,b){var c=new Event(a.toLowerCase(),{cancelable:!0});return c.detail=b,!N.global.dispatchEvent(c)}}var a=document.createEvent("CustomEvent");return a.initCustomEvent("testingtheevent",!1,!0,{}),N.global.dispatchEvent(a),function(a,b){var c=document.createEvent("CustomEvent");return c.initCustomEvent(a.toLowerCase(),!1,!0,b),!N.global.dispatchEvent(c)}}catch(a){}return function(){return!1}}(),_=function(){return N.isNode?function(){return a.emit.apply(a,arguments)}:N.global?function(a){var b="on"+a.toLowerCase(),c=N.global[b];return!!c&&(c.apply(N.global,[].slice.call(arguments,1)),!0)}:function(){return!1}}(),aa={promiseCreated:e,promiseFulfilled:e,promiseRejected:e,promiseResolved:e,promiseCancelled:e,promiseChained:function(a,b,c){return{promise:b,child:c}},warning:function(a,b){return{warning:b}},unhandledRejection:function(a,b,c){return{reason:b,promise:c}},rejectionHandled:e},ba=function(a){var b=!1;try{b=_.apply(null,arguments)}catch(a){L.throwLater(a),b=!0}var c=!1;try{c=$(a,aa[a].apply(null,arguments))}catch(a){L.throwLater(a),c=!0}return c||b};c.config=function(a){if(a=Object(a),"longStackTraces"in a&&(a.longStackTraces?c.longStackTraces():!a.longStackTraces&&c.hasLongStackTraces()&&Z()),"warnings"in a){var b=a.warnings;ga.warnings=!!b,Y=ga.warnings,N.isObject(b)&&"wForgottenReturn"in b&&(Y=!!b.wForgottenReturn)}if("cancellation"in a&&a.cancellation&&!ga.cancellation){if(L.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");c.prototype._clearCancellationData=k,c.prototype._propagateFrom=l,c.prototype._onCancel=i,c.prototype._setOnCancel=j,c.prototype._attachCancellationCallback=h,c.prototype._execute=g,ca=l,ga.cancellation=!0}return"monitoring"in a&&(a.monitoring&&!ga.monitoring?(ga.monitoring=!0,c.prototype._fireEvent=ba):!a.monitoring&&ga.monitoring&&(ga.monitoring=!1,c.prototype._fireEvent=f)),c},c.prototype._fireEvent=f,c.prototype._execute=function(a,b,c){try{a(b,c)}catch(a){return a}},c.prototype._onCancel=function(){},c.prototype._setOnCancel=function(a){},c.prototype._attachCancellationCallback=function(a){},c.prototype._captureStackTrace=function(){},c.prototype._attachExtraTrace=function(){},c.prototype._clearCancellationData=function(){},c.prototype._propagateFrom=function(a,b){};var ca=m,da=function(){return!1},ea=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;N.inherits(G,Error),d.CapturedTrace=G,G.prototype.uncycle=function(){var a=this._length;if(!(a<2)){for(var b=[],c={},d=0,e=this;void 0!==e;++d)b.push(e),e=e._parent;a=this._length=d;for(var d=a-1;d>=0;--d){var f=b[d].stack;void 0===c[f]&&(c[f]=d)}for(var d=0;d0&&(b[h-1]._parent=void 0,b[h-1]._length=1),b[d]._parent=void 0,b[d]._length=1;var i=d>0?b[d-1]:this;h=0;--k)b[k]._length=j,j++;return}}}},G.prototype.attachExtraTrace=function(a){if(!a.__stackCleaned__){this.uncycle();for(var b=y(a),c=b.message,d=[b.stack],e=this;void 0!==e;)d.push(w(e.stack.split("\n"))),e=e._parent;v(d),u(d),N.notEnumerableProp(a,"stack",t(c,d)),N.notEnumerableProp(a,"__stackCleaned__",!0)}};var fa=function(){var a=/^\s*at\s*/,b=function(a,b){return"string"==typeof a?a:void 0!==b.name&&void 0!==b.message?b.toString():B(b)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,S=a,T=b;var c=Error.captureStackTrace;return da=function(a){return P.test(a)},function(a,b){Error.stackTraceLimit+=6,c(a,b),Error.stackTraceLimit-=6}}var d=new Error;if("string"==typeof d.stack&&d.stack.split("\n")[0].indexOf("stackDetection@")>=0)return S=/@/,T=b,U=!0,function(a){a.stack=(new Error).stack};var e;try{throw new Error}catch(a){e="stack"in a}return"stack"in d||!e||"number"!=typeof Error.stackTraceLimit?(T=function(a,b){return"string"==typeof a?a:"object"!=typeof b&&"function"!=typeof b||void 0===b.name||void 0===b.message?B(b):b.toString()},null):(S=a,T=b,function(a){Error.stackTraceLimit+=6;try{throw new Error}catch(b){a.stack=b.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(J=function(a){},N.isNode&&a.stderr.isTTY?J=function(a,b){}:N.isNode||"string"!=typeof(new Error).stack||(J=function(a,b){}));var ga={warnings:W,longStackTraces:!1,cancellation:!1,monitoring:!1};return X&&c.longStackTraces(),{longStackTraces:function(){return ga.longStackTraces},warnings:function(){return ga.warnings},cancellation:function(){return ga.cancellation},monitoring:function(){return ga.monitoring},propagateFromFunction:function(){return ca},boundValueFunction:function(){return n},checkForgottenReturns:q,setBounds:F,warn:s,deprecated:r,CapturedTrace:G,fireDomEvent:$,fireGlobalEvent:_}}},{"./errors":12,"./util":36}],10:[function(a,b,c){"use strict";b.exports=function(a){function b(){return this.value}function c(){throw this.reason}a.prototype.return=a.prototype.thenReturn=function(c){return c instanceof a&&c.suppressUnhandledRejections(),this._then(b,void 0,void 0,{value:c},void 0)},a.prototype.throw=a.prototype.thenThrow=function(a){return this._then(c,void 0,void 0,{reason:a},void 0)},a.prototype.catchThrow=function(a){if(arguments.length<=1)return this._then(void 0,c,void 0,{reason:a},void 0);var b=arguments[1],d=function(){throw b};return this.caught(a,d)},a.prototype.catchReturn=function(c){if(arguments.length<=1)return c instanceof a&&c.suppressUnhandledRejections(),this._then(void 0,b,void 0,{value:c},void 0);var d=arguments[1];d instanceof a&&d.suppressUnhandledRejections();var e=function(){return d};return this.caught(c,e)}}},{}],11:[function(a,b,c){"use strict";b.exports=function(a,b){function c(){return f(this)}function d(a,c){return e(a,c,b,b)}var e=a.reduce,f=a.all;a.prototype.each=function(a){return e(this,a,b,0)._then(c,void 0,void 0,this,void 0)},a.prototype.mapSeries=function(a){return e(this,a,b,b)},a.each=function(a,d){return e(a,d,b,0)._then(c,void 0,void 0,a,void 0)},a.mapSeries=d}},{}],12:[function(a,b,c){"use strict";function d(a,b){function c(d){return this instanceof c?(l(this,"message","string"==typeof d?d:b),l(this,"name",a),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new c(d)}return k(c,Error),c}function e(a){return this instanceof e?(l(this,"name","OperationalError"),l(this,"message",a),this.cause=a,this.isOperational=!0,void(a instanceof Error?(l(this,"message",a.message),l(this,"stack",a.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new e(a)}var f,g,h=a("./es5"),i=h.freeze,j=a("./util"),k=j.inherits,l=j.notEnumerableProp,m=d("Warning","warning"),n=d("CancellationError","cancellation error"),o=d("TimeoutError","timeout error"),p=d("AggregateError","aggregate error");try{f=TypeError,g=RangeError}catch(a){f=d("TypeError","type error"),g=d("RangeError","range error")}for(var q="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),r=0;r1?a.cancelPromise._reject(b):a.cancelPromise._cancel(),a.cancelPromise=null,!0)}function h(){return j.call(this,this.promise._target()._settledValue())}function i(a){if(!g(this,a))return m.e=a,m}function j(a){var e=this.promise,j=this.handler;if(!this.called){this.called=!0;var k=this.isFinallyHandler()?j.call(e._boundValue()):j.call(e._boundValue(),a);if(k===d)return k;if(void 0!==k){e._setReturnedNonUndefined();var n=c(k,e);if(n instanceof b){if(null!=this.cancelPromise){if(n._isCancelled()){var o=new l("late cancellation observer");return e._attachExtraTrace(o),m.e=o,m}n.isPending()&&n._attachCancellationCallback(new f(this))}return n._then(h,i,void 0,this,void 0)}}}return e.isRejected()?(g(this),m.e=a,m):(g(this),a)}var k=a("./util"),l=b.CancellationError,m=k.errorObj,n=a("./catch_filter")(d);return e.prototype.isFinallyHandler=function(){return 0===this.type},f.prototype._resultCancelled=function(){g(this.finallyHandler)},b.prototype._passThrough=function(a,b,c,d){return"function"!=typeof a?this.then():this._then(c,d,void 0,new e(this,b,a),void 0)},b.prototype.lastly=b.prototype.finally=function(a){return this._passThrough(a,0,j,j)},b.prototype.tap=function(a){return this._passThrough(a,1,j)},b.prototype.tapCatch=function(a){var c=arguments.length;if(1===c)return this._passThrough(a,1,void 0,j);var d,e=new Array(c-1),f=0;for(d=0;d0&&"function"==typeof arguments[b]){a=arguments[b];var d}var e=[].slice.call(arguments);a&&e.pop();var d=new c(e).promise();return void 0!==a?d.spread(a):d}}},{"./util":36}],18:[function(a,b,c){"use strict";b.exports=function(b,c,d,e,f,g){function h(a,b,c,d){this.constructor$(a),this._promise._captureStackTrace();var e=j();this._callback=null===e?b:k.domainBind(e,b),this._preservedValues=d===f?new Array(this.length()):null,this._limit=c,this._inFlight=0,this._queue=[],n.invoke(this._asyncInit,this,void 0)}function i(a,c,e,f){if("function"!=typeof c)return d("expecting a function but got "+k.classString(c));var g=0;if(void 0!==e){if("object"!=typeof e||null===e)return b.reject(new TypeError("options argument must be an object but it is "+k.classString(e)));if("number"!=typeof e.concurrency)return b.reject(new TypeError("'concurrency' must be a number but it is "+k.classString(e.concurrency)));g=e.concurrency}return g="number"==typeof g&&isFinite(g)&&g>=1?g:0,new h(a,c,g,f).promise()}var j=b._getDomain,k=a("./util"),l=k.tryCatch,m=k.errorObj,n=b._async;k.inherits(h,c),h.prototype._asyncInit=function(){this._init$(void 0,-2)},h.prototype._init=function(){},h.prototype._promiseFulfilled=function(a,c){var d=this._values,f=this.length(),h=this._preservedValues,i=this._limit;if(c<0){if(c=c*-1-1,d[c]=a,i>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(i>=1&&this._inFlight>=i)return d[c]=a,this._queue.push(c),!1;null!==h&&(h[c]=a);var j=this._promise,k=this._callback,n=j._boundValue();j._pushContext();var o=l(k).call(n,a,c,f),p=j._popContext();if(g.checkForgottenReturns(o,p,null!==h?"Promise.filter":"Promise.map",j),o===m)return this._reject(o.e),!0;var q=e(o,this._promise);if(q instanceof b){q=q._target();var r=q._bitField;if(0===(50397184&r))return i>=1&&this._inFlight++,d[c]=q,q._proxy(this,(c+1)*-1),!1;if(0===(33554432&r))return 0!==(16777216&r)?(this._reject(q._reason()),!0):(this._cancel(),!0);o=q._value()}d[c]=o}var s=++this._totalResolved;return s>=f&&(null!==h?this._filter(d,h):this._resolve(d),!0)},h.prototype._drainQueue=function(){for(var a=this._queue,b=this._limit,c=this._values;a.length>0&&this._inFlight1){f.deprecated("calling Promise.try with more than 1 argument");var j=arguments[1],k=arguments[2];i=g.isArray(j)?h(a).apply(k,j):h(a).call(k,j)}else i=h(a)();var l=d._popContext();return f.checkForgottenReturns(i,l,"Promise.try",d),d._resolveFromSyncValue(i),d},b.prototype._resolveFromSyncValue=function(a){a===g.errorObj?this._rejectCallback(a.e,!1):this._resolveCallback(a,!0)}}},{"./util":36}],20:[function(a,b,c){"use strict";function d(a){return a instanceof Error&&k.getPrototypeOf(a)===Error.prototype}function e(a){var b;if(d(a)){b=new j(a),b.name=a.name,b.message=a.message,b.stack=a.stack;for(var c=k.keys(a),e=0;e1){var c,d=new Array(b-1),e=0;for(c=0;c0&&"function"!=typeof a&&"function"!=typeof b){var c=".then() only accepts functions but was passed: "+o.classString(a);arguments.length>1&&(c+=", "+o.classString(b)),this._warn(c)}return this._then(a,b,void 0,void 0,void 0)},f.prototype.done=function(a,b){var c=this._then(a,b,void 0,void 0,void 0);c._setIsFinal()},f.prototype.spread=function(a){return"function"!=typeof a?m("expecting a function but got "+o.classString(a)):this.all()._then(a,void 0,void 0,w,void 0)},f.prototype.toJSON=function(){var a={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(a.fulfillmentValue=this.value(),a.isFulfilled=!0):this.isRejected()&&(a.rejectionReason=this.reason(),a.isRejected=!0),a},f.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new z(this).promise()},f.prototype.error=function(a){return this.caught(o.originatesFromRejection,a)},f.getNewLibraryCopy=c.exports,f.is=function(a){return a instanceof f},f.fromNode=f.fromCallback=function(a){var b=new f(v);b._captureStackTrace();var c=arguments.length>1&&!!Object(arguments[1]).multiArgs,d=H(a)(F(b,c));return d===G&&b._rejectCallback(d.e,!0),b._isFateSealed()||b._setAsyncGuaranteed(),b},f.all=function(a){return new z(a).promise()},f.cast=function(a){var b=y(a);return b instanceof f||(b=new f(v),b._captureStackTrace(),b._setFulfilled(),b._rejectionHandler0=a),b},f.resolve=f.fulfilled=f.cast,f.reject=f.rejected=function(a){var b=new f(v);return b._captureStackTrace(),b._rejectCallback(a,!0),b},f.setScheduler=function(a){if("function"!=typeof a)throw new t("expecting a function but got "+o.classString(a));return r.setScheduler(a)},f.prototype._then=function(a,b,c,d,e){var g=void 0!==e,h=g?e:new f(v),i=this._target(),k=i._bitField;g||(h._propagateFrom(this,3),h._captureStackTrace(),void 0===d&&0!==(2097152&this._bitField)&&(d=0!==(50397184&k)?this._boundValue():i===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,h));var l=j();if(0!==(50397184&k)){var m,n,p=i._settlePromiseCtx;0!==(33554432&k)?(n=i._rejectionHandler0,m=a):0!==(16777216&k)?(n=i._fulfillmentHandler0,m=b,i._unsetRejectionIsUnhandled()):(p=i._settlePromiseLateCancellationObserver,n=new u("late cancellation observer"),i._attachExtraTrace(n),m=b),r.invoke(p,i,{handler:null===l?m:"function"==typeof m&&o.domainBind(l,m),promise:h,receiver:d,value:n})}else i._addCallbacks(a,b,h,d,l);return h},f.prototype._length=function(){return 65535&this._bitField},f.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},f.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},f.prototype._setLength=function(a){this._bitField=this._bitField&-65536|65535&a},f.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},f.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},f.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},f.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},f.prototype._isFinal=function(){return(4194304&this._bitField)>0},f.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},f.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},f.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},f.prototype._setAsyncGuaranteed=function(){r.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},f.prototype._receiverAt=function(a){var b=0===a?this._receiver0:this[4*a-4+3];if(b!==n)return void 0===b&&this._isBound()?this._boundValue():b},f.prototype._promiseAt=function(a){return this[4*a-4+2]},f.prototype._fulfillmentHandlerAt=function(a){return this[4*a-4+0]},f.prototype._rejectionHandlerAt=function(a){return this[4*a-4+1]},f.prototype._boundValue=function(){},f.prototype._migrateCallback0=function(a){var b=(a._bitField,a._fulfillmentHandler0),c=a._rejectionHandler0,d=a._promise0,e=a._receiverAt(0);void 0===e&&(e=n),this._addCallbacks(b,c,d,e,null)},f.prototype._migrateCallbackAt=function(a,b){var c=a._fulfillmentHandlerAt(b),d=a._rejectionHandlerAt(b),e=a._promiseAt(b),f=a._receiverAt(b);void 0===f&&(f=n),this._addCallbacks(c,d,e,f,null)},f.prototype._addCallbacks=function(a,b,c,d,e){var f=this._length();if(f>=65531&&(f=0,this._setLength(0)),0===f)this._promise0=c,this._receiver0=d,"function"==typeof a&&(this._fulfillmentHandler0=null===e?a:o.domainBind(e,a)),"function"==typeof b&&(this._rejectionHandler0=null===e?b:o.domainBind(e,b));else{var g=4*f-4;this[g+2]=c,this[g+3]=d,"function"==typeof a&&(this[g+0]=null===e?a:o.domainBind(e,a)),"function"==typeof b&&(this[g+1]=null===e?b:o.domainBind(e,b))}return this._setLength(f+1),f},f.prototype._proxy=function(a,b){this._addCallbacks(void 0,void 0,b,a,null)},f.prototype._resolveCallback=function(a,b){if(0===(117506048&this._bitField)){if(a===this)return this._rejectCallback(k(),!1);var c=y(a,this);if(!(c instanceof f))return this._fulfill(a);b&&this._propagateFrom(c,2);var d=c._target();if(d===this)return void this._reject(k());var e=d._bitField;if(0===(50397184&e)){var g=this._length();g>0&&d._migrateCallback0(this);for(var h=1;h>>16)){if(a===this){var c=k();return this._attachExtraTrace(c),this._reject(c)}this._setFulfilled(),this._rejectionHandler0=a,(65535&b)>0&&(0!==(134217728&b)?this._settlePromises():r.settlePromises(this))}},f.prototype._reject=function(a){var b=this._bitField;if(!((117506048&b)>>>16))return this._setRejected(),this._fulfillmentHandler0=a,this._isFinal()?r.fatalError(a,o.isNode):void((65535&b)>0?r.settlePromises(this):this._ensurePossibleRejectionHandled())},f.prototype._fulfillPromises=function(a,b){for(var c=1;c0){if(0!==(16842752&a)){var c=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,c,a),this._rejectPromises(b,c)}else{var d=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,d,a),this._fulfillPromises(b,d)}this._setLength(0)}this._clearCancellationData()},f.prototype._settledValue=function(){var a=this._bitField;return 0!==(33554432&a)?this._rejectionHandler0:0!==(16777216&a)?this._fulfillmentHandler0:void 0},f.defer=f.pending=function(){C.deprecated("Promise.defer","new Promise");var a=new f(v);return{promise:a,resolve:g,reject:h}},o.notEnumerableProp(f,"_makeSelfResolutionError",k),b("./method")(f,v,y,m,C),b("./bind")(f,v,y,C),b("./cancel")(f,z,m,C),b("./direct_resolve")(f),b("./synchronous_inspection")(f),b("./join")(f,z,y,v,r,j),f.Promise=f,f.version="3.5.0",b("./map.js")(f,z,m,y,v,C),b("./call_get.js")(f),b("./using.js")(f,m,y,B,v,C),b("./timers.js")(f,v,C),b("./generators.js")(f,m,v,y,d,C),b("./nodeify.js")(f),b("./promisify.js")(f,v),b("./props.js")(f,z,y,m),b("./race.js")(f,v,y,m),b("./reduce.js")(f,z,m,y,v,C),b("./settle.js")(f,z,C),b("./some.js")(f,z,m),b("./filter.js")(f,v),b("./each.js")(f,v),b("./any.js")(f),o.toFastProperties(f),o.toFastProperties(f.prototype),i({a:1}),i({b:2}),i({c:3}),i(1),i(function(){}),i(void 0),i(!1),i(new f(v)),C.setBounds(q.firstLineError,o.lastLineError),f}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(a,b,c){"use strict";b.exports=function(b,c,d,e,f){function g(a){switch(a){case-2:return[];case-3:return{};case-6:return new Map}}function h(a){var d=this._promise=new b(c);a instanceof b&&d._propagateFrom(a,3),d._setOnCancel(this),this._values=a,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var i=a("./util");i.isArray;return i.inherits(h,f),h.prototype.length=function(){return this._length},h.prototype.promise=function(){return this._promise},h.prototype._init=function a(c,f){var h=d(this._values,this._promise);if(h instanceof b){h=h._target();var j=h._bitField;if(this._values=h,0===(50397184&j))return this._promise._setAsyncGuaranteed(),h._then(a,this._reject,void 0,this,f);if(0===(33554432&j))return 0!==(16777216&j)?this._reject(h._reason()):this._cancel();h=h._value()}if(h=i.asArray(h),null===h){var k=e("expecting an array or an iterable object but got "+i.classString(h)).reason();return void this._promise._rejectCallback(k,!1)}return 0===h.length?void(f===-5?this._resolveEmptyArray():this._resolve(g(f))):void this._iterate(h)},h.prototype._iterate=function(a){var c=this.getActualLength(a.length);this._length=c,this._values=this.shouldCopyValues()?new Array(c):this._values;for(var e=this._promise,f=!1,g=null,h=0;h=this._length&&(this._resolve(this._values),!0)},h.prototype._promiseCancelled=function(){return this._cancel(),!0},h.prototype._promiseRejected=function(a){return this._totalResolved++,this._reject(a),!0},h.prototype._resultCancelled=function(){if(!this._isResolved()){var a=this._values;if(this._cancel(),a instanceof b)a.cancel();else for(var c=0;c=this._length){var d;if(this._isMap)d=m(this._values);else{d={};for(var e=this.length(),f=0,g=this.length();f>1},b.prototype.props=function(){return g(this)},b.props=function(a){return g(a)}}},{"./es5":13,"./util":36}],26:[function(a,b,c){"use strict";function d(a,b,c,d,e){for(var f=0;f=this._length&&(this._resolve(this._values),!0)},e.prototype._promiseFulfilled=function(a,b){var c=new f;return c._bitField=33554432,c._settledValueField=a,this._promiseResolved(b,c)},e.prototype._promiseRejected=function(a,b){var c=new f;return c._bitField=16777216,c._settledValueField=a,this._promiseResolved(b,c)},b.settle=function(a){return d.deprecated(".settle()",".reflect()"), -new e(a).promise()},b.prototype.settle=function(){return b.settle(this)}}},{"./util":36}],31:[function(a,b,c){"use strict";b.exports=function(b,c,d){function e(a){this.constructor$(a),this._howMany=0,this._unwrap=!1,this._initialized=!1}function f(a,b){if((0|b)!==b||b<0)return d("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var c=new e(a),f=c.promise();return c.setHowMany(b),c.init(),f}var g=a("./util"),h=a("./errors").RangeError,i=a("./errors").AggregateError,j=g.isArray,k={};g.inherits(e,c),e.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var a=j(this._values);!this._isResolved()&&a&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},e.prototype.init=function(){this._initialized=!0,this._init()},e.prototype.setUnwrap=function(){this._unwrap=!0},e.prototype.howMany=function(){return this._howMany},e.prototype.setHowMany=function(a){this._howMany=a},e.prototype._promiseFulfilled=function(a){return this._addFulfilled(a),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},e.prototype._promiseRejected=function(a){return this._addRejected(a),this._checkOutcome()},e.prototype._promiseCancelled=function(){return this._values instanceof b||null==this._values?this._cancel():(this._addRejected(k),this._checkOutcome())},e.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var a=new i,b=this.length();b0?this._reject(a):this._cancel(),!0}return!1},e.prototype._fulfilled=function(){return this._totalResolved},e.prototype._rejected=function(){return this._values.length-this.length()},e.prototype._addRejected=function(a){this._values.push(a)},e.prototype._addFulfilled=function(a){this._values[this._totalResolved++]=a},e.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},e.prototype._getRangeError=function(a){var b="Input array must contain at least "+this._howMany+" items but contains only "+a+" items";return new h(b)},e.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},b.some=function(a,b){return f(a,b)},b.prototype.some=function(a){return f(this,a)},b._SomePromiseArray=e}},{"./errors":12,"./util":36}],32:[function(a,b,c){"use strict";b.exports=function(a){function b(a){void 0!==a?(a=a._target(),this._bitField=a._bitField,this._settledValueField=a._isFateSealed()?a._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}b.prototype._settledValue=function(){return this._settledValueField};var c=b.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},d=b.prototype.error=b.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},e=b.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},f=b.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},g=b.prototype.isPending=function(){return 0===(50397184&this._bitField)},h=b.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};b.prototype.isCancelled=function(){return 0!==(8454144&this._bitField)},a.prototype.__isCancelled=function(){return 65536===(65536&this._bitField)},a.prototype._isCancelled=function(){return this._target().__isCancelled()},a.prototype.isCancelled=function(){return 0!==(8454144&this._target()._bitField)},a.prototype.isPending=function(){return g.call(this._target())},a.prototype.isRejected=function(){return f.call(this._target())},a.prototype.isFulfilled=function(){return e.call(this._target())},a.prototype.isResolved=function(){return h.call(this._target())},a.prototype.value=function(){return c.call(this._target())},a.prototype.reason=function(){var a=this._target();return a._unsetRejectionIsUnhandled(),d.call(a)},a.prototype._value=function(){return this._settledValue()},a.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},a.PromiseInspection=b}},{}],33:[function(a,b,c){"use strict";b.exports=function(b,c){function d(a,d){if(k(a)){if(a instanceof b)return a;var e=f(a);if(e===j){d&&d._pushContext();var i=b.reject(e.e);return d&&d._popContext(),i}if("function"==typeof e){if(g(a)){var i=new b(c);return a._then(i._fulfill,i._reject,void 0,i,null),i}return h(a,e,d)}}return a}function e(a){return a.then}function f(a){try{return e(a)}catch(a){return j.e=a,j}}function g(a){try{return l.call(a,"_promise0")}catch(a){return!1}}function h(a,d,e){function f(a){h&&(h._resolveCallback(a),h=null)}function g(a){h&&(h._rejectCallback(a,l,!0),h=null)}var h=new b(c),k=h;e&&e._pushContext(),h._captureStackTrace(),e&&e._popContext();var l=!0,m=i.tryCatch(d).call(a,f,g);return l=!1,h&&m===j&&(h._rejectCallback(m.e,!0,!0),h=null),k}var i=a("./util"),j=i.errorObj,k=i.isObject,l={}.hasOwnProperty;return d}},{"./util":36}],34:[function(a,b,c){"use strict";b.exports=function(b,c,d){function e(a){this.handle=a}function f(a){return clearTimeout(this.handle),a}function g(a){throw clearTimeout(this.handle),a}var h=a("./util"),i=b.TimeoutError;e.prototype._resultCancelled=function(){clearTimeout(this.handle)};var j=function(a){return k(+this).thenReturn(a)},k=b.delay=function(a,f){var g,h;return void 0!==f?(g=b.resolve(f)._then(j,null,null,a,void 0),d.cancellation()&&f instanceof b&&g._setOnCancel(f)):(g=new b(c),h=setTimeout(function(){g._fulfill()},+a),d.cancellation()&&g._setOnCancel(new e(h)),g._captureStackTrace()),g._setAsyncGuaranteed(),g};b.prototype.delay=function(a){return k(a,this)};var l=function(a,b,c){var d;d="string"!=typeof b?b instanceof Error?b:new i("operation timed out"):new i(b),h.markAsOriginatingFromRejection(d),a._attachExtraTrace(d),a._reject(d),null!=c&&c.cancel()};b.prototype.timeout=function(a,b){a=+a;var c,h,i=new e(setTimeout(function(){c.isPending()&&l(c,b,h)},a));return d.cancellation()?(h=this.then(),c=h._then(f,g,void 0,i,void 0),c._setOnCancel(i)):c=this._then(f,g,void 0,i,void 0),c}}},{"./util":36}],35:[function(a,b,c){"use strict";b.exports=function(b,c,d,e,f,g){function h(a){setTimeout(function(){throw a},0)}function i(a){var b=d(a);return b!==a&&"function"==typeof a._isDisposable&&"function"==typeof a._getDisposer&&a._isDisposable()&&b._setDisposable(a._getDisposer()),b}function j(a,c){function e(){if(g>=j)return k._fulfill();var f=i(a[g++]);if(f instanceof b&&f._isDisposable()){try{f=d(f._getDisposer().tryDispose(c),a.promise)}catch(a){return h(a)}if(f instanceof b)return f._then(e,h,null,null,null)}e()}var g=0,j=a.length,k=new b(f);return e(),k}function k(a,b,c){this._data=a,this._promise=b,this._context=c}function l(a,b,c){this.constructor$(a,b,c)}function m(a){return k.isDisposer(a)?(this.resources[this.index]._setDisposable(a),a.promise()):a}function n(a){this.length=a,this.promise=null,this[a-1]=null}var o=a("./util"),p=a("./errors").TypeError,q=a("./util").inherits,r=o.errorObj,s=o.tryCatch,t={};k.prototype.data=function(){return this._data},k.prototype.promise=function(){return this._promise},k.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():t},k.prototype.tryDispose=function(a){var b=this.resource(),c=this._context;void 0!==c&&c._pushContext();var d=b!==t?this.doDispose(b,a):null;return void 0!==c&&c._popContext(),this._promise._unsetDisposable(),this._data=null,d},k.isDisposer=function(a){return null!=a&&"function"==typeof a.resource&&"function"==typeof a.tryDispose},q(l,k),l.prototype.doDispose=function(a,b){var c=this.data();return c.call(a,a,b)},n.prototype._resultCancelled=function(){for(var a=this.length,c=0;c0},b.prototype._getDisposer=function(){return this._disposer},b.prototype._unsetDisposable=function(){this._bitField=this._bitField&-131073,this._disposer=void 0},b.prototype.disposer=function(a){if("function"==typeof a)return new l(a,this,e());throw new p}}},{"./errors":12,"./util":36}],36:[function(b,c,e){"use strict";function f(){try{var a=F;return F=null,a.apply(this,arguments)}catch(a){return E.e=a,E}}function g(a){return F=a,f}function h(a){return null==a||a===!0||a===!1||"string"==typeof a||"number"==typeof a}function i(a){return"function"==typeof a||"object"==typeof a&&null!==a}function j(a){return h(a)?new Error(s(a)):a}function k(a,b){var c,d=a.length,e=new Array(d+1);for(c=0;c1,d=b.length>0&&!(1===b.length&&"constructor"===b[0]),e=J.test(a+"")&&C.names(a).length>0;if(c||d||e)return!0}return!1}catch(a){return!1}}function p(a){function b(){}b.prototype=a;for(var c=8;c--;)new b;return a}function q(a){return K.test(a)}function r(a,b,c){for(var d=new Array(a),e=0;e10||b[0]>0}(),Q.isNode&&Q.toFastProperties(a);try{throw new Error}catch(a){Q.lastLineError=a}c.exports=Q},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:2}],2:[function(a,b,c){function d(){throw new Error("setTimeout has not been defined")}function e(){throw new Error("clearTimeout has not been defined")}function f(a){if(l===setTimeout)return setTimeout(a,0);if((l===d||!l)&&setTimeout)return l=setTimeout,setTimeout(a,0);try{return l(a,0)}catch(b){try{return l.call(null,a,0)}catch(b){return l.call(this,a,0)}}}function g(a){if(m===clearTimeout)return clearTimeout(a);if((m===e||!m)&&clearTimeout)return m=clearTimeout,clearTimeout(a);try{return m(a)}catch(b){try{return m.call(null,a)}catch(b){return m.call(this,a)}}}function h(){q&&o&&(q=!1,o.length?p=o.concat(p):r=-1,p.length&&i())}function i(){if(!q){var a=f(h);q=!0;for(var b=p.length;b;){for(o=p,p=[];++r1)for(var c=1;c0)&&a)){this.turnTestCounter=0,this.resultsHandler=new i.ResultsHandler;var c={type:"browser",os:this.browserInfo.os,osVersion:this.browserInfo.osVersion,buildName:this.browserInfo.browserName,buildVersion:this.browserInfo.browserVersion};this.resultsHandler.add("endpointInfo",c),this.onlineCheck.start(),this.active=!0,this._start()}}},{key:"_start",value:function(){var a=this;this.active&&this.turnConnection.connect(this.iceServers).then(function(){a.active&&a.startTurnTests().then(function(){a.stop()},function(b){a.stop()})},function(b){a.resultsHandler.failure(b),a.resultsHandler.getFailureNumber()>=n?a.stop():(a.turnConnection.disconnect(),setTimeout(function(){a._start()},0))})}},{key:"stop",value:function(){var a=this;if(this.browserInfo.browserName!==k.Constants.browserName.msie&&this.active){this.active=!1,this.activeTurnTest&&this.activeTurnTest.forceStop();var b=this.onlineCheck.stop();this.resultsHandler.add("onlineStatus",b),this.turnConnection.getIceResults().then(function(b){a.resultsHandler.add("ice",b),a.turnConnection.disconnect(),a.sendResults()},function(b){a.resultsHandler.failure(b),a.turnConnection.disconnect(),a.sendResults()})}}},{key:"sendResults",value:function(){var a=this.resultsHandler.getResults();this.callback&&this.callback(a),this.resultsHandler=null}},{key:"callStarts",value:function(){this.callsInProgress+=1,this.stop()}},{key:"callFinished",value:function(){this.callsInProgress-=1}},{key:"getId",value:function(){return this.resultsHandler?this.resultsHandler.getId():null}},{key:"crashDisconnect",value:function(){try{this.turnConnection.disconnect()}catch(a){}}},{key:"startTurnTests",value:function(){var a=this;if(this.turnTestCounter>=this.turnTests.length)return new l(function(a,b){a()});var b=this.turnTests[this.turnTestCounter],c=null;switch(b){case m.RTT:c=new g.RttTest(this.turnConnection);break;case m.THROUGHPUT:c=new h.ThroughputTest(this.turnConnection,this.rtt);break;default:return new l(function(a,c){c(new Error("Unknown test: "+b))})}return this.activeTurnTest=c,this.active?c.start().then(function(){return a.handleTestResults(b,c.getResults()),a.turnTestCounter+=1,a.activeTurnTest=null,a.startTurnTests()},function(d){return a.handleTestResults(b,c.getResults(),d),a.turnTestCounter+=1,a.activeTurnTest=null,a.startTurnTests()}):new l(function(a,b){b(new Error("Test trying to start while testing is not active"))})}},{key:"handleTestResults",value:function(a,b){null==(arguments.length>2&&void 0!==arguments[2]?arguments[2]:null)&&a==m.RTT&&(this.rtt=b.median),this.resultsHandler&&this.resultsHandler.add(a,b)}}]),a}();c.PreCallTest=o},{"./tests/rttTest":4,"./tests/throughputTest":5,"./turnConnection":7,"./utility/onlineCheck":9,"./utility/resultsHandler":11,"./utility/stats/detectbrowser":12,bluebird:1}],4:[function(a,b,c){"use strict";function d(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b.default=a,b}function e(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function f(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function g(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}Object.defineProperty(c,"__esModule",{value:!0}),c.RttTest=void 0;var h=function(){function a(a,b){for(var c=0;c=this.intervalLength){var d=c-this.intervalStart,e=this.averageThroughput(this.intervalBytes,d),f=null;try{f=c-JSON.parse(this.lastMessage).timestamp}catch(a){}this.intervals.push({startTimestamp:this.intervalStart,endTimestamp:c,bytesReceived:this.intervalBytes,average:e,rtt:f}),this.intervalStart=c,this.intervalBytes=0}this.results.startTimestamp&&c-this.results.startTimestamp>this.duration/2&&(this.secondHalfStart||(this.secondHalfStart=c),this.secondHalfBytes+=a.length)}}},{key:"handleError",value:function(a){this.stop(),this.failed(a)}},{key:"averageThroughput",value:function(a,b){return a/(b/1e3)*8/1024}},{key:"bufferListener",value:function(){this.sendChannel.removeEventListener("bufferedamountlow",this.bufferListener.bind(this)),this.fillBuffer()}},{key:"fillBuffer",value:function(){for(0==this.sendChannel.bufferedAmount&&(this.bufferEmpty+=1);this.isActive();){if(this.sendChannel.bufferedAmount>this.bufferFullThreshold)return void(this.usePolling?setTimeout(this.fillBuffer.bind(this),250):this.sendChannel.addEventListener("bufferedamountlow",this.bufferListener.bind(this)));var a=this.messageMaker.make(this.sentBytes);this.sentBytes+=a.length,this.send(a)}this.sendChannel.removeEventListener("bufferedamountlow",this.bufferListener.bind(this))}},{key:"startSend",value:function(){this.isActive()&&(this.bufferFullThreshold=1e3*this.chunkSize,this.sendChannel=this.connection.sendChannel,this.usePolling=!0,"number"==typeof this.sendChannel.bufferedAmountLowThreshold&&(this.usePolling=!1,this.sendChannel.bufferedAmountLowThreshold=this.bufferFullThreshold/10),setTimeout(this.fillBuffer.bind(this),0))}},{key:"fillResults",value:function(){this.results.endTimestamp=k.getCurrent(),this.results.maxDuration=this.duration,this.results.forceStopped=this.forceStopped,this.results.bufferEmpty=this.bufferEmpty,this.results.intervals=this.intervals,this.results.bytesPrepared=this.sentBytes,this.results.bytesReceived=this.receivedBytes;var a=0,b=0;this.secondHalfStart&&(a=this.results.endTimestamp-this.secondHalfStart,b=this.averageThroughput(this.secondHalfBytes,a));var c=this.results.endTimestamp-this.results.startTimestamp,d=this.averageThroughput(this.receivedBytes,c);d>b&&(b=d),this.results.average=b;var e=null;try{e=JSON.parse(this.lastMessage)}catch(a){return}var f=e.sentBytes+this.lastMessage.length;this.results.bytesSent=f,this.results.fractionLostBytes=1-this.receivedBytes/f}},{key:"stop",value:function(){this.isActive()&&(clearTimeout(this.sendTimer),this.sendTimer=null,i(b.prototype.__proto__||Object.getPrototypeOf(b.prototype),"stop",this).call(this),this.fillResults())}}]),b}();c.ThroughputTest=n},{"../utility/messageMaker":8,"../utility/timestamps":15,"./turnTest":6}],6:[function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(c,"__esModule",{value:!0});var e=function(){function a(a,b){for(var c=0;c0&&void 0!==arguments[0]?arguments[0]:1200;e(this,a),this.message={timestamp:"",sentBytes:1e4,padding:""};var c=f(b-i.getCurrent().toString().length-JSON.stringify(this.message).length);this.message.padding=c}return g(a,[{key:"make",value:function(a){return this.message.timestamp=i.getCurrent(),this.message.sentBytes=a,JSON.stringify(this.message)}}]),a}();c.MessageMaker=j,c.randomAsciiString=f},{"../utility/timestamps":15}],9:[function(a,b,c){"use strict";function d(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b.default=a,b}function e(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(c,"__esModule",{value:!0}),c.OnlineCheck=void 0;var f=function(){function a(a,b){for(var c=0;c>24;if("rtp"===this.protocol&&c>=0&&c<=2)switch(c){case 0:b="TLS";break;case 1:b="TCP";break;case 2:b="UDP"}return b}},{key:"getString",value:function(){return this.iceCandidateStr}},{key:"getType",value:function(){return this.type}},{key:"isHost",value:function(){return"host"===this.type.toLowerCase()}},{key:"isServerReflexive",value:function(){return"srflx"===this.type.toLowerCase()}},{key:"isPeerReflexive",value:function(){return"prflx"===this.type.toLowerCase()}},{key:"isRelay",value:function(){return"relay"===this.type.toLowerCase()||"relayed"===this.type.toLowerCase()}},{key:"getTypeTransport",value:function(){return this.typeTransport}},{key:"isTypeTransportUdp",value:function(){return"UDP"===this.typeTransport}},{key:"isTypeTransportTcp",value:function(){return"TCP"===this.typeTransport}},{key:"isTypeTransportTls",value:function(){return"TLS"===this.typeTransport}},{key:"getTransport",value:function(){return this.transport}},{key:"isUdp",value:function(){return"udp"===this.transport.toLowerCase()}},{key:"isTcp",value:function(){return"tcp"===this.transport.toLowerCase()}},{key:"getProtocol",value:function(){return this.protocol}},{key:"isRtp",value:function(){return"rtp"===this.protocol}},{key:"isRtcp",value:function(){return"rtcp"===this.protocol}},{key:"isIpv6",value:function(){return this.ipv6}},{key:"getIpAddress",value:function(){return this.ipAddress}},{key:"getPort",value:function(){return this.port}}]),a}();c.ParsedIceCandidate=f},{}],11:[function(a,b,c){"use strict";function d(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b.default=a,b}function e(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(c,"__esModule",{value:!0}),c.ResultsHandler=void 0;var f="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},g=function(){function a(a,b){for(var c=0;c>24;i.mozLocalTransport=this.formatRelayType(j)}i.mozLocalTransport=i.mozLocalTransport.toLowerCase()}b.push(i)}else h.remoteCandidate&&c.push(h.remoteCandidate)}if(e)for(var k=0;k0&&(b[d].csioReceivedBwKbps=8*(parseInt(b[d].bytesReceived,10)-i)/k,b[d].csioSentBwKbps=8*(parseInt(b[d].bytesSent,10)-j)/k,b[d].csioIntBytesReceived=parseInt(b[d].bytesReceived,10)-i,b[d].csioIntBytesSent=parseInt(b[d].bytesSent,10)-j,void 0!==h.packetsSent&&void 0!==b[d].packetsSent&&(b[d].csioSentPacketRate=(parseInt(b[d].packetsSent,10)-parseInt(h.packetsSent,10))/(k/1e3),b[d].csioIntPacketsSent=parseInt(b[d].packetsSent,10)-parseInt(h.packetsSent,10)),void 0!==h.packetsReceived&&void 0!==b[d].packetsReceived&&(b[d].csioReceivedPacketRate=(parseInt(b[d].packetsReceived,10)-parseInt(h.packetsReceived,10))/(k/1e3),b[d].csioIntPacketsReceived=parseInt(b[d].packetsReceived,10)-parseInt(h.packetsReceived,10))),l.push(b[d]))}return l}function t(a,b,c,d){var e=[];return c===ub.firefox?e=b:b&&(e=s(a,b,d)),e}function u(a){var b,c,d;for(b in a.streams)if(a.streams.hasOwnProperty(b)){if(a.streams[b].inbound)for(d in a.streams[b].inbound)a.streams[b].inbound.hasOwnProperty(d)&&(c=a.streams[b].inbound[d].mark,c===lb.bad?a.streams[b].inbound[d].mark=2:c===lb.fair?a.streams[b].inbound[d].mark=1:a.streams[b].inbound[d].mark=0);if(a.streams[b].outbound)for(d in a.streams[b].outbound)a.streams[b].outbound.hasOwnProperty(d)&&(c=a.streams[b].outbound[d].mark,c===lb.bad?a.streams[b].outbound[d].mark=2:c===lb.fair?a.streams[b].outbound[d].mark=1:a.streams[b].outbound[d].mark=0)}return a}function v(a){var b={},c=ad.getConferenceURL();return a.connectionState&&(b.connectionState=a.connectionState),a.fabricState&&(b.fabricState=a.fabricState),c&&(b.conferenceURL=c),b.streams={},null===a.streams?b:(a.streams.forEach(function(a){var c={cname:a.cname,ssrc:a.ssrc,msid:a.msid,remoteUserID:a.userID,usageLabel:a.usage,associatedVideoTag:a.associatedVideoTag};a.data.hasOwnProperty("csioIntFL")&&(c.fractionLoss=a.data.csioIntFL),a.data.hasOwnProperty("csioIntBRKbps")&&(c.bitrate=a.data.csioIntBRKbps),a.data.hasOwnProperty("csioMark")&&(c.quality=a.data.csioMark),a.data.hasOwnProperty("csioMediaType")&&(c.mediaType=a.data.csioMediaType),a.data.hasOwnProperty("googRtt")&&(c.rtt=a.data.googRtt),a.data.hasOwnProperty("mozRtt")&&(c.rtt=a.data.mozRtt), -a.data.hasOwnProperty("roundTripTime")&&(c.rtt=a.data.roundTripTime),a.data.hasOwnProperty("jitter")&&(c.jitter=a.data.jitter),a.data.hasOwnProperty("googJitterReceived")&&(c.jitter=a.data.googJitterReceived),a.data.hasOwnProperty("audioOutputLevel")&&(c.audioOutputLevel=a.data.audioOutputLevel),a.data.hasOwnProperty("audioInputLevel")&&(c.audioInputLevel=a.data.audioInputLevel),a.data.hasOwnProperty("audioLevel")&&(c.audioLevel=a.data.audioLevel),a.data.hasOwnProperty("csioAvgRtt")&&(c.averageRTT=a.data.csioAvgRtt),a.data.hasOwnProperty("csioAvgJitter")&&(c.averageJitter=a.data.csioAvgJitter),a.data.hasOwnProperty("csioPktLossPercentage")&&(c.packetLossPercentage=a.data.csioPktLossPercentage),a.reportType&&"local"===a.reportType?a.streamType&&(c.statsType=a.streamType+"-rtp"):a.reportType&&"remote"===a.reportType&&a.streamType&&(c.statsType="remote-"+a.streamType+"-rtp"),b.streams[a.ssrc]=c}),b)}function w(a,b,c,e,f,g){var h=d();a.hasOwnProperty("token")&&a.hasOwnProperty("ucID")&&!Ua?(Q(ab.processedStats,a,g),b.latestEventSent=h,b.lastFabricState=b.pcState):(a.clockUnsynced=Ua,Ha.cacheEvent({channel:ab.processedStats,data:a}))}function x(a,b){for(var c in b)b.hasOwnProperty(c)&&"id"!==c&&"type"!==c&&"timestamp"!==c&&(a[c]=b[c]);return a}function y(a,b,e,f,i){function j(j){if(j){var k=d(),l=c();void 0===f.lastRawStatsSentInterval||null===f.lastRawStatsSentInterval?f.lastRawStatsSentInterval=l-f.statsPollingStart:f.lastRawStatsSentInterval=l-f.rawstatsTS+f.lastRawStatsSentInterval,void 0===f.lastProcessedStatsSentInterval||null===f.lastProcessedStatsSentInterval?f.lastProcessedStatsSentInterval=za+1:f.lastProcessedStatsSentInterval=l-f.rawstatsTS+f.lastProcessedStatsSentInterval,f.rawstatsTS=l;var m={},n=ua.codebase,o=f.conferenceID,s=f.remoteUserID;m.version=aa,m.appID=ia,m.conferenceID=encodeURIComponent(o),m.apiTS=k,m.timeShift=0,m.fabricState=f.pcState,m.pcID=f.pcHash,void 0!==e&&(m.ucID=e),Na.authToken&&(m.token=Na.authToken),m.localID=encodeURIComponent(b),m.remoteID=s?encodeURIComponent(s):null,m.deviceID=la;var x,y,z,B,F,G,I,J={streams:[]},K=null,L=!1,M=!1,N={},O={};for(K=bc(j),x=0;x0||parseInt(z[B].bytesSent,10)>0)&&(J[B].push(z[B]),"true"!==z[B].googActiveConnection&&z[B].googActiveConnection!==!0||(m.activeConnectionIndex=J[B].length)):(J[B].push(z[B]),"true"!==z[B].selected&&z[B].selected!==!0||(m.activeConnectionIndex=J[B].length));else if(z.localCandidate)N[z.localCandidate.id]=z.localCandidate;else if(z.remoteCandidate)O[z.remoteCandidate.id]=z.remoteCandidate;else if(z.bwe)J.bwe=z.bwe;else if(z.trackStats)J.trackStats||(J.trackStats=[]),J.trackStats.push(z.trackStats);else if(z.codec)J.codec||(J.codec=[]),J.codec.push(z.codec);else if(z.candidatePair)J.candidatePair||(J.candidatePair=[]),J.candidatePair.push(z.candidatePair);else{G=Ib(f,z.ssrc),void 0!==G&&G.localStartTime||(I=Kb(s,o,e,f,i,null),I&&(M=!0),G=Ib(f,z.ssrc)),G&&(F=G.remoteUserID),void 0===F&&(F=s);var P={userID:F,data:z.data,reportType:z.reportType,streamType:z.streamType,ssrc:z.ssrc};void 0!==G&&(P.cname=G.cname,P.msid=G.msid,P.associatedVideoTag=G.associatedVideoTag,P.usage=G.usageLabel),J.streams.push(P)}if(m.statistics=J,J.Transport&&(L=C(J.Transport,f)),L&&Qc(i,_a.fabricTransportSwitch,o),J.Transport||n!==ub.firefox||(J.Transport=J.candidatePair.filter(function(a){return!(!a.selected&&"true"!==a.selected)})),J.Transport)for(var Q=0;Q=za&&(f.processedStatsTupleArray=[],Ka.add(X,X.processedStatistics.length),X.msgStat=Ka.getStat(),w(X,f,o,s,b,a),f.lastProcessedStatsSentInterval=0)}}}return j}function z(a){var b;return nb.hasOwnProperty(a)?a===nb.createOffer||a===nb.createAnswer||a===nb.setRemoteDescription?b=ob.negotiationFailure:a===nb.setLocalDescription?b=ob.sdpError:a===nb.addIceCandidate?b=ob.sdpError:a===nb.getUserMedia?b=ob.mediaConfigError:a===nb.iceConnectionFailure?b=ob.iceFailure:a===nb.signalingError?b=ob.signalingError:(a===nb.applicationLog||nb.applicationError)&&(b=ob.applicationLog):b=Eb.invalidWebRTCFunctionName,b}function A(a){var b={};if("inboundrtp"===a.type||"outboundrtp"===a.type||"inbound-rtp"===a.type||"outbound-rtp"===a.type){if(b.ssrc=a.ssrc,b.streamType="inboundrtp"===a.type||"inbound-rtp"===a.type?"inbound":"outbound","Safari"===ua.name&&!a.mediaType){a.id.includes("Audio")?a.mediaType="audio":a.id.includes("Video")&&(a.mediaType="video");var c=a.id.split("_");if(c[1])try{a.ssrc=parseInt(c[1]),b.ssrc=a.ssrc}catch(a){}}b.data=a,void 0!==a.isRemote?b.reportType="true"===a.isRemote||a.isRemote===!0?"remote":"local":b.reportType="local",a.trackId&&(b.trackId=a.trackId),a.mediaType&&(b.mediaType=a.mediaType)}else"candidatepair"===a.type&&a.selected?b.Transport=a:"localcandidate"===a.type||"local-candidate"===a.type?b.localCandidate=a:"remotecandidate"===a.type||"remote-candidate"===a.type?b.remoteCandidate=a:"transport"===a.type||"googCandidatePair"===a.type?b.Transport=a:"VideoBwe"===a.type?b.bwe=a:"track"===a.type?b.trackStats=a:"candidate-pair"===a.type?b.candidatePair=a:"codec"===a.type?b.codec=a:"ssrc"===a.type&&(b.reportType="local",a.bytesSent?b.streamType="outbound":b.streamType="inbound",b.ssrc=a.ssrc,b.data=a);return b}function B(a){var b="None";switch(a){case 0:b="TURN/TLS";break;case 1:b="TURN/TCP";break;case 2:b="TURN/UDP"}return b}function C(a,b){var c,d,e,f,g,h,i,j,k,l=!1,m="None",n=!1,o=ua.codebase,p=function(a){if(a.typePreference){var b=a.typePreference>>24;return"rtp"===a.protocol&&a.address===c&&(b>=0&&b<=2&&(m=B(b)),!0)}return!1};for(i=0;i0)return!1;if(0===a.length)return!0;var b;for(b in a)if(a.hasOwnProperty(b))return!1;return!0}function F(a){return{magicKey:a,statsSubmissionInterval:za,endpoint:Ra,localUserIDObject:ka}}function G(a,b,c){var d=Sa[a];void 0===d&&(Sa[a]={},Sa[a].participants=null,c&&(Sa[a].userJoinedSent=!0),b&&(Sa[a].refreshPresence=b))}function H(a){var b,c=a.statistics.outbound;if(void 0!==c)for(b in c)c.hasOwnProperty(b)&&(c[b].data.mozRtt?c[b].data.mozRtt=0:c[b].data.googRtt?c[b].data.googRtt=0:c[b].data.rtt?c[b].data.rtt=0:c[b].data.roundTripTime&&(c[b].data.roundTripTime=0))}function I(a){return clearInterval(a),null}function J(){var a;for(a in Sa)Sa.hasOwnProperty(a)&&(Sa[a].refreshPresence=I(Sa[a].refreshPresence),delete Sa[a].refreshPresence);U()}function K(a){var b=!1;if(!a)return b;var c=Sa[a];return void 0!==c&&c.participants&&c.participants.length>0&&(b=!0),b}function L(a,b){var c=Sa[a],d=[];if(void 0===c)d.push(b),Sa[a]={},Sa[a].participants=d;else{var e=c.participants;null===e?(d.push(b),c.participants=d):e.push(b)}}function M(a){var b=!1;if(!Sa[a])return{conferenceFinished:b,ucID:null};var c=Sa[a].ucID;return 0===Sa[a].participants.length&&(I(Sa[a].refreshPresence),U(),Ha.sendCachedEvents(Na,Ua),delete Sa[a],b=!0),{conferenceFinished:b,ucID:c}}function N(a,b){Lb(_a.userLeft,null,a,b,null,null,null),U(),Va=Gb,Gb=null}function O(){var a,b=function(a){return setInterval(function(){Qb(a)},Ba)};for(a in Sa)if(Sa.hasOwnProperty(a)){if(a===fa)return;Qb(a),Sa[a].refreshPresence=b(a)}V()}function P(a){try{if(window&&window.sessionStorage){var b=JSON.parse(window.sessionStorage.getItem("csio_ucid_data"));if(b&&b[a])return b[a].ucID}}catch(a){return null}return null}function Q(a,b,c){var d=b.action,e=b.remoteID,f=b.ucID;b.channel=a,Na._isTokenValid(Na.authToken,ia,ja)?(f&&!Ua&&e||wb.indexOf(d)!==-1)&&b.conferenceID!==fa?(b.token=Na.authToken,bd(a,b,c),c&&d&&c(db.success,d+" sent to the backend.")):(b.clockUnsynced=Ua,Ha.cacheEvent({channel:a,data:b,callback:c})):Na.sendAuthenticationRequest(ia,ja,function(g,h){g!==db.success?(g===eb.authOngoing&&(b.clockUnsynced=Ua,Ha.cacheEvent({channel:a,data:b,callback:c})),c&&g!==eb.authOngoing&&c(g,h)):g===db.success&&"SDK authentication successful."===h&&((f&&!Ua&&e||wb.indexOf(d)!==-1)&&b.conferenceID!==fa?(b.token=Na.authToken,bd(a,b,c),c&&d&&c(db.success,d+" sent to the backend.")):(b.clockUnsynced=Ua,Ha.cacheEvent({channel:a,data:b,callback:c})))})}function R(a){a&&a(eb.authOngoing,"Authentication Ongoing")}function S(a){if(null===a||"object"!=typeof a)return a;var b,c=new a.constructor;for(b in a)a.hasOwnProperty(b)&&(c[b]=S(a[b]));return c}function T(){var a={};Object.keys(Sa).forEach(function(b){var c=Sa[b];if(!c)return!0;var d,e,f={ucID:c.ucID,userJoinedSent:c.userJoinedSent},g=[];if(c.participants){var h,i=c.participants;for(d=0;d>>0,e=arguments[1],f=0;f=n-f||!l.data.ucID)if(m=decodeURIComponent(l.data.conferenceID),Sa[m]&&Sa[m].ucID)l.data.ucID=Sa[m].ucID;else{if(m!==g){o.push(i.eventCache[j]);continue}l.data.ucID=h}if(l.data.clockUnsynced&&(l.data.apiTS+=Ta.currentOffset),l.channel===ab.processedStats&&l.data.clockUnsynced&&l.data.processedStatistics&&l.data.processedStatistics.length>0)for(k=0;k=0;h--)g[h]=e.charCodeAt(h);var i=function(a){for(var b="",c=new Uint8Array(a),f=c.byteLength,g=0;g0)return r(d,f,h,k[b],a.type);console.error("Authentication failed, but no error actions were defined in response."),e=setTimeout(a.sendAuthenticationRequest,Ca,d,f,h)}})})}};var p=function(){null!==f&&(clearTimeout(f),f=null)},q=function(b,c,d,e){p(),f=setTimeout(function(){a.sendAuthenticationRequest(c,d,e)},b)},r=function(a,b,c,d,e){if(0!==d.length){var f=d.shift();if(f.action===Fb.RETRY)return e===La.jwt&&q(f.params.timeout,a,b,c),r(a,b,c,d);if(f.action===Fb.GET_NEW_TOKEN)return g=!0,r(a,b,c,d);if(f.action===Fb.REPORT_ERROR){var h="Authentication Error";return f.params&&f.params.errorCode>=0&&(h=j[f.params.errorCode]),c&&c(db.authError,h),r(a,b,c,d)}}};this.appSecretTokenGenerator=function(b){var c=null,d=null,e=!1,f=null;b.indexOf(":")>-1&&(f=n(b.split(":")[0]),b=b.split(":")[1]);var g=function(a){b=null,c=a},h=function(a){e=!0,b=null,console.error("Couldn't import key",a)};return o.importKey(b,g,h),function(b,g){if(e)return g("appsecret based token generation failed");if(!b&&null!==d)return g(null,d);if(null===c)return setTimeout(function(){a.tokenGenerator(b,g)},100);var h={userID:ja,appID:ia};f&&(h.keyID=f),o.sign({alg:"HS256"},h,c,function(a,b){return a?g(a):(d=b,g(null,b))})}}},Na=new Ma,Oa=new X;try{ua=Oa.detectBrowserInfo()}catch(a){console.log("detectBrowserInfo: Error",a)}var Pa;window.csioReactNative||(Pa=Oa.measureAppLoadingPerformance(ua),wa.loading=Pa);var Qa,Ra={type:"browser",name:ua.name,ver:ua.ver,os:ua.os,osVersion:ua.osVersion,userAgent:ua.userAgent},Sa={},Ta={currentOffset:0,offsetResults:[],syncStartTime:null,syncAttempts:5,syncHandler:null,maxAllowedLatency:6e4},Ua=!0,Va=null,Wa=null,Xa=2e4,Ya=100,Za=null;"Firefox"===ua.name?Za=mozRTCPeerConnection:"Chrome"===ua.name||"Opera"===ua.name?Za=webkitRTCPeerConnection:"Safari"===ua.name||"Edge"===ua.name&&(Za=window.RTCPeerConnection);var $a={fabricSetupFailed:"fabricSetupFailed",fabricHold:"fabricHold",fabricResume:"fabricResume",audioMute:"audioMute",audioUnmute:"audioUnmute",videoPause:"videoPause",videoResume:"videoResume",fabricUsageEvent:"fabricUsageEvent",fabricTerminated:"fabricTerminated",screenShareStart:"screenShareStart",screenShareStop:"screenShareStop",dominantSpeaker:"dominantSpeaker",userIDChangedEvent:"userIDChangedEvent",activeDeviceList:"activeDeviceList",applicationErrorLog:"applicationErrorLog"},_a={autoFabricSetup:"autoFabricSetup",userJoined:"userJoined",userLeft:"userLeft",refreshPresence:"userAlive",ssrcMap:"ssrcMap",mediaPlaybackStartEvent:"mediaPlaybackStartEvent",mediaSuspendedEvent:"mediaSuspendedEvent",oneWayMedia:"oneWayMedia",fabricStateChange:"fabricStateChange",iceDisruptionStart:"iceDisruptionStart",iceDisruptionEnd:"iceDisruptionEnd",fabricTransportSwitch:"fabricTransportSwitch",iceConnectionDisruptionStart:"iceConnectionDisruptionStart",iceConnectionDisruptionEnd:"iceConnectionDisruptionEnd",iceAborted:"iceAborted",iceTerminated:"iceTerminated",iceFailed:"iceFailed",iceRestarted:"iceRestarted",fabricDropped:"fabricDropped",connectedDevices:"connectedDevices",iceCompleted:"iceCompleted",iceCandidateFound:"iceCandidateFound"},ab={sdpSubmission:"sdpSubmissionEvent",rtpStats:"rtpStats",processedStats:"processedStats",callStatsEvent:"callStatsEvent",userFeedback:"userFeedbackEvent",clockSync:"clockSync",preCallTest:"preCallTest"},bb={results:"preCallTestResults",associate:"preCallTestAssociate"},cb={success:"success",failure:"failure"},db={httpError:"httpError",authError:"authError",wsChannelFailure:"wsChannelFailure",success:"success",csProtoError:"csProtoError",appConnectivityError:"appConnectivityError",tokenGenerationError:"tokenGenerationError",ok:"OK"},eb={authOngoing:"authOngoing"},fb={peer:"peer",server:"server"},gb={sendonly:"sendonly",receiveonly:"receiveonly",sendrecv:"sendrecv",inactive:"inactive"},hb={audio:"audio",video:"video",data:"data",screen:"screen",multiplex:"multiplex",unbundled:"unbundled"},ib={local:"local",remote:"remote"},jb={excellent:5,good:4,fair:3,poor:2,bad:1},kb={local:"local",remote:"remote",inbound:"inbound",outbound:"outbound"},lb={excellent:"excellent",fair:"fair",bad:"bad"},mb={established:"established",initializing:"initializing",failed:"failed",disrupted:"disrupted",checkingDisrupted:"checkingDisrupted"},nb={createOffer:"createOffer",createAnswer:"createAnswer",setLocalDescription:"setLocalDescription",setRemoteDescription:"setRemoteDescription",addIceCandidate:"addIceCandidate",getUserMedia:"getUserMedia",iceConnectionFailure:"iceConnectionFailure",signalingError:"signalingError",applicationError:"applicationError",applicationLog:"applicationLog"},ob={mediaConfigError:"MediaConfigError",negotiationFailure:"NegotiationFailure",sdpError:"SDPGenerationError",iceFailure:"IceConnectionFailure",transportFailure:"TransportFailure",signalingError:"SignalingError",applicationError:"ApplicationError",applicationLog:"ApplicationLog"},pb={video:{gThreshold:1024,rThreshold:256},audio:{gThreshold:30,rThreshold:8}},qb={video:{gThreshold:.8,rThreshold:.3}},rb={video:{gThreshold:400,rThreshold:1e3}},sb={video:{gThreshold:10,rThreshold:50},audio:{gThreshold:15,rThreshold:30}},tb={audio:{gThreshold:240,rThreshold:400}},ub={chrome:"Chrome",firefox:"Firefox",edge:"Edge"},vb={signalingState:"signalingState",iceConnectionState:"iceConnectionState",iceGatheringState:"iceGatheringState"},wb=[_a.userJoined,_a.refreshPresence,$a.fabricSetupFailed],xb=function(a,b){try{window&&window.localStorage&&window.localStorage.setItem(a,b)}catch(a){return}},yb=function(a){try{if(window&&window.localStorage)return window.localStorage.getItem(a)}catch(a){return null}return null},zb=function(a){try{window&&window.localStorage&&window.localStorage.removeItem(a)}catch(a){return}},Ab=function(){if(la=yb("endpointID"),null===la){var a=c(),b=Math.random()*a;oc(b.toString(),function(a){la=a,xb("endpointID",la)})}},Bb=function(a,b,d,e,f){var g=null,h=null,i=null,j=new XMLHttpRequest;if("Microsoft Internet Explorer"!==ua.name&&(j.timeout=d),j){j.open("GET",encodeURI(a));for(var k in b)j.setRequestHeader(k,b[k]);g=c(),j.onload=function(){h=c(),i=h-g,e(j,i)},j.ontimeout=f,j.send()}},Cb=function(a,b,c){var d=new XMLHttpRequest;d&&(d.open("POST",encodeURI(a)),d.setRequestHeader("Content-Type","application/json"),d.onload=function(){c(d)},d.send(b))},Db=function(a,b,c,d){if(Ea&&a){var e=$+"generics",f={appID:a,userID:encodeURIComponent(b),version:aa,eventType:c,data:d},g=JSON.stringify(f);ta!==g&&(ta=g,Cb(e,g,function(a){200===a.status||200!==a.status}))}};window&&window.addEventListener&&window.addEventListener("error",function(a){if(a&&a.filename&&a.filename.indexOf("callstats")>-1){var b,c=!1,d={fileName:a.filename,line:a.lineno,col:a.colno,jsVersion:aa,eventType:"error",message:a.message,pageURL:window.location.href};for(b in Sa)Sa.hasOwnProperty(b)&&(d.conferenceID=b,Db(ia,ja,"onErrorLog",d),c=!0);c||Db(ia,ja,"onErrorLog",d)}});var Eb={invalidWebRTCFunctionName:"Invalid WebRTC function name"},Fb={RETRY:0,GET_NEW_TOKEN:1,REPORT_ERROR:2},Gb=b(),Hb=function(a,b,e){var f=RegExp.prototype.test.bind(/^([a-z])=(.*)/),g=/^ssrc:(\d*) ([\w_]*):(.*)/,h=/^ssrc-group:SIM (\d*)/;b.split(/(\r\n|\r|\n)/).filter(f).forEach(function(b){var f=b[0],i=b.slice(2);if("a"===f){if(g.test(i)){var j=i.match(g),k=j[1];void 0===a.ssrcMap[k]&&(a.ssrcMap[k]={}),a.ssrcMap[k][j[2]]=j[3],a.ssrcMap[k].localStartTime=c(),a.ssrcMap[k].syncedStartTime=d(),a.ssrcMap[k].streamType=e}h.test(i)&&(void 0===a.ssrcMap.ssrcGroup&&(a.ssrcMap.ssrcGroup={},a.ssrcMap.ssrcGroup[e]={}),a.ssrcMap.ssrcGroup[e].simulcastGroup=i.match(/\d+/g))}})},Ib=function(a,b){return a.ssrcMap[b]},Jb=function(a){return a.ssrcMap},Kb=function(a,b,c,d,e,f){if(!e.localDescription||!e.remoteDescription)return!1;var g=e.localDescription.sdp,h=e.remoteDescription.sdp;if(!g||!h||g===d.localSDP&&h===d.remoteSDP)return!1;if(Hb(d,g,kb.outbound),Hb(d,h,kb.inbound),Aa){var i={sdp:{}};i.sdp.localSDP=g!==d.localSDP?g:-1,i.sdp.remoteSDP=h!==d.remoteSDP?h:-1,Nb(a,b,c,i,d.pcHash,f)}return d.localSDP=g,d.remoteSDP=h,!0},Lb=function(a,b,c,e,f,g,h){if(!a)return void console.error("sendEvent: Invalid eventType ");var i=d(),j={version:aa,apiTS:i,action:a,localID:encodeURIComponent(ja),remoteID:b?encodeURIComponent(b):null,conferenceID:encodeURIComponent(c),timeShift:0,appID:ia,ucID:e,pcID:g,deviceID:la,value:f};return null===c?void Db(ia,ja,"log",{msg:"conferenceID is null in sendEvent for "+a}):void Q(ab.callStatsEvent,j,h)},Mb=function(a,b,c,e){if(!a)return void console.error("sendEvent: Invalid eventType ");var f=d(),g={version:aa,channel:ab.preCallTest,timestamp:f,apiTS:f,action:a,eventType:a,localID:encodeURIComponent(ja),remoteID:encodeURIComponent(ja),conferenceID:encodeURIComponent(b),timeShift:0,appID:ia,ucID:c,deviceID:la,token:Na.authToken};return a===bb.results&&(g.results=e,null==b)?void bd(ab.preCallTest,g):(a===bb.associate&&(g.ids=e),void(c&&!Ua?Q(ab.preCallTest,g):(g.clockUnsynced=Ua,Ha.cacheEvent({channel:ab.preCallTest,data:g,callback:null}))))},Nb=function(a,b,c,e,f,g){var h=d(),i={version:aa,appID:ia,conferenceID:encodeURIComponent(b),ucID:c,apiTS:h,localID:encodeURIComponent(ja),remoteID:encodeURIComponent(a),pcID:f,deviceID:la,sdpPayload:e,action:ab.sdpSubmission};Na.authToken&&c&&!Ua?(i.token=Na.authToken,Q(ab.sdpSubmission,i,g)):(i.clockUnsynced=Ua,Ha.cacheEvent({channel:ab.sdpSubmission,data:i,callback:g}),Na.authToken||Na.sendAuthenticationRequest(ia,ja))},Ob=function(a,b,c,d,e,f,g){gc(a,function(a){b.localCandidates=a.localCandidates,b.remoteCandidates=a.remoteCandidates,b.iceCandidatePairs=a.iceCandidatePairs,b.activeIceCandidatePair=Ac(b.iceCandidatePairs),g.currPair=b.activeIceCandidatePair,Lb(_a.fabricStateChange,e,c,d,g,f)})},Pb=function(a){var b={connectedDevices:ha},c=Sa[a]?Sa[a].ucID:null;Lb(_a.connectedDevices,null,a,c,b,null)},Qb=function(a){var b={ucID:Sa[a].ucID,endpoint:Ra,magicKey:Gb};Lb(_a.refreshPresence,null,a,Sa[a].ucID,b,null)},Rb=function(a,b){var c={};return c.status=a,b&&(c.message=b),c},Sb=function(a,b){var c,d,e,f=0;if(!a)return f;for(c=0,e=a.length;c0?d[0]:null},$b=function(a,b){var c=null,d=null;return c=Zb(a,b),c&&(d=c.pcHash),d},_b=function(a){var b=null,c=null,d=null;for(b in Sa)if(Sa.hasOwnProperty(b)&&(d=Zb(b,a))){c={fabric:d,conferenceID:b};break}return c},ac=function(a,b){var c=0;if(a&&Sa[b].participants)for(c=0;cya&&(console.log("Log exceeds 20kb, It will be truncated"),a=a.substring(0,ya)),a},jc=function(a){return a&&"string"==typeof a?a=ic(a):a&&"object"==typeof a&&a.message&&(a.message=ic(a.message)),a},kc=function(a,b,c){return b?b:a&&a[c]?a[c].sdp:-1},lc=function(a,d,e,f,g,h){if(d||(d=fa),void 0===a||!e)return console.error("reportError: Arguments missing/invalid"),Rb(cb.error,"reportError: Arguments missing/invalid");if(!ia||!ja)return console.error("reportError: SDK is not initialized"),Rb(cb.error,"reportError: SDK is not initialized");if(!nb.hasOwnProperty(e))return console.error("reportError: Invalid webRTC functionName value: %o",e),Rb(cb.error,"reportError: Invalid webRTC functionName value: "+e);void 0===f&&console.warn("reportError: Missing dom error parameter");var i,j,k,l=null,m=c(),n=Sa[d],p=null,q=m,r=null,s=null,t=null,u=null;if(t=P(d),j=z(e),e!==nb.getUserMedia&&(u=b()),f)if(window.DOMException&&f instanceof window.DOMException)f={message:f.message,name:f.name};else if("object"==typeof f){var v={};f.message&&(v.message=f.message),f.name&&(v.name=f.name),f.constraintName&&(v.constraintName=f.constraintName),f.stack&&(v.stack=f.stack),f=v}if(f=jc(f),o(a)){n&&(t=n.ucID),p=Zb(d,a),p?(i=p.remoteUserID,q=p.startTime,r=p.pcState,s=p.pc.iceConnectionState,u=p.pcHash,k=p.pcCallback):i=ja;var w=m-q;if(l={failureDelay:w,reason:j,domError:f,fabricState:r,iceConnectionState:s,function:e,magicKey:Gb,endpoint:Ra},e===nb.applicationLog||e===nb.applicationError?Lb($a.applicationErrorLog,i,d,t,l,u,k):(Lb($a.fabricSetupFailed,i,d,t,l,u,k),wa.errorSinceCreate=c()-wa.create,Ub()),g||h||a&&a.localDescription||a&&a.remoteDescription){var x={sdp:{}};x.sdp.localSDP=kc(a,g,"localDescription"),x.sdp.remoteSDP=kc(a,h,"remoteDescription"),Nb(i,d,t,x,u)}}else null===Gb&&(Gb=b()),i=ja,l={failureDelay:0,reason:j,domError:f,function:e,magicKey:Gb,endpoint:Ra},e===nb.applicationLog||e===nb.applicationError?Lb($a.applicationErrorLog,i,d,t,l,null,null):Lb($a.fabricSetupFailed,i,d,t,l,u,null);return Rb(cb.success)},mc=function(a){for(var b=[],c=0;c127&&d<2048?(b[b.length]=d>>6|192,b[b.length]=63&d|128):(b[b.length]=d>>12|224,b[b.length]=d>>6&63|128,b[b.length]=63&d|128)}return new Uint8Array(b).buffer},nc=function(a){for(var b,c=new DataView(a),d="",e=0;e0){var x=Sa[f].ucID;Mb(bb.associate,f,x,v)}}catch(a){qa("send associate",a)}return Rb(cb.success)},zc=function(a,b,c,d){if(!(a&&c&&d&&b))return console.error("reportUserIDChange: Arguments missing/Invalid"),Rb(cb.error,"reportUserIDChange: Arguments missing/Invalid");if(!ia||!ja)return console.error("reportUserIDChange: SDK not initialized."),Rb(cb.error,"reportUserIDChange: SDK not initialized");if(""===c||""===b)return console.error("reportUserIDChange: id or conferenceID MUST not be empty"),Rb(cb.error,"reportUserIDChange: id or conferenceID MUST not be empty");if(!o(a))return console.error("reportUserIDChange: Invalid PeerConnection object passed"),Rb(cb.error,"reportUserIDChange: Invalid PeerConnection object passed");var e,f=null,g=Sa[b];if(void 0===g)return console.error("reportUserIDChange: Conference ID not found!"),Rb(cb.error,"reportUserIDChange: Conference ID not found!");var h=null;if(void 0===g.ucID)return console.error("reportUserIDChange: addNewFabric was not called"),Db(ia,ja,"log",{msg:"### reportUserIDChange: addNewFabric was not called"}),Rb(cb.error,"reportUserIDChange: addNewFabric was not called");if(h=g.ucID,f=Zb(b,a),null===f)return console.error("reportUserIDChange: Invalid pcObject passed as argument"),Rb(cb.error,"reportUserIDChange: Invalid pcObject passed as argument");var i={id:c,idType:d};return Lb($a.userIDChangedEvent,e,b,h,i,null,f.pcCallback),Rb(cb.success)},Ac=function(a){var b=null;if(a&&a.length>0){var c=a.filter(function(a){return"true"===a.selected||"true"===a.googActiveConnection||a.selected===!0||a.googActiveConnection===!0});c.length>0&&(b=c[0])}return b},Bc=function(a,b){if(a){var d,e=null;if(void 0!==b){var f=b.signalingState;if(e=_b(b),e&&e.fabric){d=e.fabric.signalingState,e.fabric.signalingState=f;var g=e.conferenceID,h=e.fabric,i=h.remoteUserID,j=Sa[g].ucID,k={changedState:vb.signalingState,prevState:d,newState:f};if(Ob(b,h,g,j,i,h.pcHash,k),"closed"===f&&(hc(b,$a.fabricTerminated,e.conferenceID),sa))try{sa.callFinished()}catch(a){qa("callFinished",a),sa.crashDisconnect()}}if("have-remote-offer"===f||"stable"===f){if(wa.remoteofferSinceCreate=c()-wa.create,Ub(),sa)try{sa.callStarts()}catch(a){qa("callStarts",a),sa.crashDisconnect()}Db(ia,ja,"log",{msg:"precalltest told to stop"})}}}},Cc=function(a,b,d){if(!a.onHold){var e=b,f=d;null===a.statsInterval&&(a.statsPollingStart=c(),Oc(e,f),a.statsInterval=setInterval(function(){Oc(e,f)},pa))}},Dc=function(a,b,c,d,e,f){f.localCandidates=b.localCandidates,f.remoteCandidates=b.remoteCandidates,f.iceCandidatePairs=b.iceCandidatePairs,Lb(_a.iceFailed,c,d,e,f,b.pcHash,b.pcCallback)},Ec=function(a,b,c,d){var e=b.iceConnectionState,f=b.remoteUserID,g=Sa[c],h={prevIceConnectionState:e,currIceConnectionState:a.iceConnectionState,currPair:b.activeIceCandidatePair,failureDelay:d};b.pcState=mb.failed,"checking"===e?Dc(a,b,f,c,g.ucID,h):"completed"===e||"connected"===e?Lb(_a.fabricDropped,f,c,g.ucID,h,b.pcHash,b.pcCallback):"disconnected"===e&&b.established?Lb(_a.fabricDropped,f,c,g.ucID,h,b.pcHash,b.pcCallback):"disconnected"===e&&Dc(a,b,f,c,g.ucID,h)},Fc=function(a,b,d,e){var f=b.iceConnectionState,g=b.remoteUserID,h=Sa[d],i=c(),j={prevIceConnectionState:f,currIceConnectionState:a.iceConnectionState,prevPair:b.activeIceCandidatePair},k=b.pcState===mb.disrupted,l="completed"===a.iceConnectionState;b.connectivityIceStatusDelay=e,b.established=!0,gc(a,function(a){if(b.localCandidates=a.localCandidates,b.remoteCandidates=a.remoteCandidates,b.iceCandidatePairs=a.iceCandidatePairs,b.activeIceCandidatePair=Ac(b.iceCandidatePairs),j.currPair=b.activeIceCandidatePair,j.disruptionDelay=i-b.disruptedTS,k)Lb(_a.iceDisruptionEnd,g,d,h.ucID,j,b.pcHash);else if(l){var c={};c.iceCandidatePairs=a.iceCandidatePairs,Lb(_a.iceCompleted,g,d,h.ucID,c,b.pcHash)}}),Pc(b.pc,_a.autoFabricSetup,d),b.pcState=mb.established,Cc(b,a,d,g)},Gc=function(a,b,d){var e=b.iceConnectionState,f=b.remoteUserID,g=Sa[d],h=c(),i={prevIceConnectionState:e,currIceConnectionState:a.iceConnectionState,prevIceConnectionStateTs:b.iceConnectionStateTS,currPair:b.activeIceCandidatePair};b.startTime=h,"connected"===e||"completed"===e?(b.pcState=mb.disrupted,b.disruptedTS=h,Lb(_a.iceDisruptionStart,f,d,g.ucID,i,b.pcHash,b.pcCallback),b.pcCallback&&b.pcCallback(db.appConnectivityError,"Connectivity check for PC object to "+f+" failed.")):"checking"===e&&(b.pcState=mb.checkingDisrupted,b.disruptedTS=h,Lb(_a.iceConnectionDisruptionStart,f,d,g.ucID,i,b.pcHash,b.pcCallback),b.pcCallback&&b.pcCallback(db.appConnectivityError,"Connectivity check for PC object to "+f+" failed."))},Hc=function(a,b,c,d){var e=b.iceConnectionState,f=b.remoteUserID,g=Sa[c],h={prevIceConnectionState:e,currIceConnectionState:a.iceConnectionState};"new"===e||"checking"===e?(h.failureDelay=d,Lb(_a.iceAborted,f,c,g.ucID,h,b.pcHash,b.pcCallback)):(h.currPair=b.activeIceCandidatePair,Lb(_a.iceTerminated,f,c,g.ucID,h,b.pcHash,b.pcCallback))},Ic=function(a,b,c){var d=b.iceConnectionState,e=b.remoteUserID,f=Sa[c],g={prevIceConnectionState:d,currIceConnectionState:a.iceConnectionState,prevPair:b.activeIceCandidatePair};"new"!==d&&(b.established=!1,Lb(_a.iceRestarted,e,c,f.ucID,g,b.pcHash,b.pcCallback))},Jc=function(a,b,d,e){var f=b.iceConnectionState,g=b.remoteUserID,h=Sa[d],i=c(),j={prevIceConnectionState:f,currIceConnectionState:a.iceConnectionState};b.gatheringIceCandidatesDelay=e,"disconnected"===f&&b.pcState===mb.checkingDisrupted&&(j.disruptionDelay=i-b.disruptedTS,Lb(_a.iceConnectionDisruptionEnd,g,d,h.ucID,j,b.pcHash,b.pcCallback))},Kc=function(a,b){if(a&&void 0!==b){var c=null;c=_b(b),c&&c.fabric&&c.fabric.numNegotiationNeededCalls++}},Lc=function(a,b){if(a&&void 0!==b){var d,e,f,g,h,i=null,j=null;if(j=_b(b),j&&j.fabric){i=j.fabric,d=j.conferenceID,e=c(),f=e-i.startTime,g=i.iceConnectionState,h=i.iceGatheringState;var k=i.remoteUserID,l=Sa[d].ucID,m={changedState:vb.iceConnectionState,prevState:g,newState:b.iceConnectionState};if(Ob(b,i,d,l,k,i.pcHash,m),h!==b.iceGatheringState){var n={changedState:vb.iceGatheringState,prevState:h,newState:b.iceGatheringState};Ob(b,i,d,l,k,i.pcHash,n)}"complete"===b.iceGatheringState&&"checking"===b.iceConnectionState&&Jc(b,i,d,f),"connected"===b.iceConnectionState||"completed"===b.iceConnectionState?Fc(b,i,d,f):"failed"===b.iceConnectionState?Ec(b,i,d,f):"disconnected"===b.iceConnectionState?Gc(b,i,d):"closed"===b.iceConnectionState?Hc(b,i,d,f):"new"===b.iceConnectionState&&Ic(),i.iceConnectionState=b.iceConnectionState,i.iceGatheringState=b.iceGatheringState,i.iceConnectionStateTS=c()}}},Mc=function(a,b){var c=_b(a);if(c&&c.fabric){var d=c.fabric,e=d.remoteUserID,f=c.conferenceID,g=Sa[f].ucID;Lb(_a.iceCandidateFound,e,f,g,b,d.pcHash)}},Nc=function(a,b){var c,d,e;if(void 0!==b){if(null!==a.candidate){var f=a.candidate.candidate;d=f.split(" ");var g="1"===d[1]?"rtp":"rtcp";"0"!==d[5]&&(e=d[4].indexOf(":")!==-1,c={transport:d[2],protocol:g,typePreference:d[3],address:e?"["+d[4]+"]:"+d[5]:d[4]+":"+d[5],type:d[7],media:a.candidate.sdpMid})}var h=null;h=_b(b),gc(b,function(a){h.localCandidates=a.localCandidates,h.remoteCandidates=a.remoteCandidates,h.iceCandidatePairs=a.iceCandidatePairs,h.activeIceCandidatePair=Ac(h.iceCandidatePairs)}),h&&h.fabric&&(void 0!==c&&h.fabric.iceCandidates.indexOf(c)===-1&&h.fabric.iceCandidates.push(c),c&&h.fabric.fabricSetupSent&&Mc(b,c))}},Oc=function(a,b){if(!Sa.hasOwnProperty(b))return void console.error("ConferenceID %o doesn't exist. Can't call getStats for it.",b);if("closed"===a.signalingState)return hc(a,$a.fabricTerminated,b),!0;var c=Zb(b,a);if(c.pcState!==mb.established&&c.lastFabricState===c.pcState&&"connected"!==a.iceConnectionState&&"completed"!==a.iceConnectionState)return!0;var d=Sa[b].ucID;try{fc(a,c.pcCallback,y,ja,d,c)}catch(a){console.log("csioGetStats: Error",a)}},Pc=function(a,b,d){var e,f=null,g=Sa[d],h=null,i=c();if(void 0===g&&console.error("sendAutoFabricSetupEvent: Conference ID not found!"),h=Zb(d,a),null===h&&console.error("sendAutoFabricSetupEvent: fabricData is null"),!h.fabricSetupSent){f=h.remoteUserID,e=i-h.startTime;var j={setupDelay:e,iceGatheringDelay:h.gatheringIceCandidatesDelay,iceConnectivityDelay:h.connectivityIceStatusDelay,remoteEndpointType:h.remoteEndpointType,fabricTransmissionDirection:h.fabricTransmissionDirection};Ua||(j.clockSyncOffset=Ta.currentOffset),gc(a,function(a){j.localCandidates=a.localCandidates,j.remoteCandidates=a.remoteCandidates,j.iceCandidatePairs=a.iceCandidatePairs,h.localCandidates=a.localCandidates,h.remoteCandidates=a.remoteCandidates,h.iceCandidatePairs=a.iceCandidatePairs,h.pcState=mb.established,h.fabricSetupSent=!0,h.activeIceCandidatePair=Ac(h.iceCandidatePairs),Lb(b,f,d,g.ucID,j,h.pcHash,h.pcCallback)})}},Qc=function(a,b,c){var d={},e=null,f=Sa[c],g=null;void 0===f&&console.error("sendFabricTransportSwitchEvent: Conference ID not found!"),g=Zb(c,a),null===g&&console.error("sendFabricTransportSwitchEvent: fabricData is null"),e=g.remoteUserID,d.prevPair=g.activeIceCandidatePair,gc(a,function(a){d.currPair=Ac(a.iceCandidatePairs),g.activeIceCandidatePair=d.currPair,d.switchDelay=null,d.relayType=g.transportData.relayType,Lb(b,e,c,f.ucID,d,g.pcHash,g.pcCallback)})},Rc=function(a,b){if(a.trackStats){var c=a.trackStats.filter(function(a){return a.id===b});if(c.length>0)return c[0]}},Sc=function(a,b){if(a.codec){var c=a.codec.filter(function(a){return a.id===b});if(c.length>0)return c[0]}},Tc=function(a,b){if(a.candidatePair){var c=a.candidatePair.filter(function(a){return a.id===b});if(c.length>0)return c[0]}},Uc=function(a){for(var b,c,d=a.Transport.length,e=0;eTa.maxAllowedLatency)Ta.offsetResults=[],Db(ia,ja,"log",{msg:"clockSync restarting"});else{var e=a.now+d,f=e-c;Ta.offsetResults.push(f)}if(Ta.offsetResults.length>=Ta.syncAttempts){var g=Ta.offsetResults.reduce(function(a,b){return a+b});Ta.currentOffset=g/Ta.offsetResults.length,Ta.offsetResults=[],Ua=!1,Db(ia,ja,"log",{msg:"clockSync Done"}),Ha.sendCachedUserJoinedEvents(Na),Ha.sendCachedEvents(Na,Ua)}else Ua&&setTimeout(function(){Zc()},100)}},_c=function(){var a=this,b=null,d=!1,e=!1,f={},g={initiated:"initiated",connected:"connected",closed:"closed"};this._wsConnectionState=g.closed;var h=function(a,b){try{if(window&&window.sessionStorage){var c=JSON.parse(window.sessionStorage.getItem("csio_ucid_data"));c||(c={}),c[a]||(c[a]={}),c[a].ucID=b,window.sessionStorage.setItem("csio_ucid_data",JSON.stringify(c))}}catch(a){return}f[a]=ca+ia+"/conferences/"+encodeURIComponent(a)+"/"+b+"/general"};this.getConferenceURL=function(){return f},this._setupWebSocketConnection=function(f){return a._wsConnectionState===g.initiated||a._wsConnectionState===g.connected?(Db(ia,ja,"log",{msg:"### _setupWebSocketConnection is called when already connected!"}),void(f&&f(db.success,"WebSocket establishment successful."))):(a._wsConnectionState=g.initiated,b=new WebSocket(ba,"echo-protocol"),b.onopen=function(){Db(ia,ja,"log",{msg:"Successfully connected to the backend"}),a._wsConnectionState=g.connected,d?e=!0:d=!0,Ta.syncHandler||(Db(ia,ja,"log",{msg:"start clockSync"}),Ta.offsetResults=[],Zc(),Ta.syncHandler=!0),Ha.sendCachedUserJoinedEvents(Na),e&&(O(),Ha.sendCachedEvents(Na,Ua)),e=!1},b.onclose=function(){a._wsConnectionState=g.closed,Db(ia,ja,"log",{msg:"Connection to the server closed."}),J(),Ua&&(Ta.offsetResults=[],Ta.syncHandler=null,Ua=!1),b&&(b=null),f&&f(db.httpError,"Connection to the server closed.")},b.onerror=function(b){a._wsConnectionState=g.closed,Db(ia,ja,"log",{msg:"WebSocket establishment failed."}),f&&f(db.wsChannelFailure,"WebSocket establishment failed.",b)},void(b.onmessage=function(a){var b,d=a.data,e=c(),g=JSON.parse(d);if("Error"===g.status)"Invalid client token."===g.reason&&(Na.tokenData=null,Na.authToken=null,Na.sendAuthenticationRequest(ia,ja)),f&&f(db.csProtoError,d.reason);else if("200 OK"===g.status)if("feedback"===g.event)zb("feedback");else if(g.event===_a.userJoined||g.event===_a.refreshPresence){var i=!1,j=null;b=decodeURIComponent(g.conferenceID);var k=function(a){return setInterval(function(){Qb(a)},Ba)};Sa.hasOwnProperty(b)&&(Sa[b].ucID!==g.ucID&&(i=!0,h(b,g.ucID),j=g.conferenceCreationTS?g.conferenceCreationTS:g.conferenceDuration),g.event!==_a.userJoined||Sa[b].refreshPresence||(Sa[b].refreshPresence=k(b),V()),Sa[b].ucID=g.ucID),Ha.sendCachedFeedback(),Ha.sendCachedEvents(Na,Ua,i,j,b,g.ucID)}else g.event===ab.clockSync?$c(g,e):g.event===$a.fabricSetupFailed&&(b=decodeURIComponent(g.conferenceID),g.ucID&&(h(b,g.ucID),Ha.sendCachedFeedback(),Ha.sendCachedEvents(Na,Ua,!0,0,b,g.ucID)))}))},this._isChannelReady=function(){return!(!b||1!==b.readyState)},this.getWSConnectionState=function(){return b?b.readyState:-1},this.send=function(a){b.send(JSON.stringify(a))}},ad=new _c,bd=function(a,b,c){if(ad._isChannelReady())try{ad.send(b)}catch(d){d&&"InvalidStateError"===d.name&&Ha.cacheEvent({channel:a,data:b,callback:c})}else Ha.cacheEvent({channel:a,data:b,callback:c}),ad._setupWebSocketConnection()};return f(),Ab(),W(),window&&!window.csioproxy&&(Ea=!0,Yc(),Zc()),window&&window.csioChromeLegacyGetStats&&(Fa=!1),{version:aa,initialize:Tb,on:Vb,fabricEvent:$a,addNewFabric:yc,sendFabricEvent:hc,sendUserFeedback:pc,associateMstWithUserID:qc,csError:db,fabricUsage:hb,qualityRating:jb,webRTCFunctions:nb,reportError:lc,reportUserIDChange:zc,userIDType:ib,setProxyConfig:xc,callStatsAPIReturnStatus:cb,setIdentifiers:wc,transmissionDirection:gb,endpointType:fb}}"function"==typeof define&&define.amd?define("callstats",[],d):c.callstats=d,b.exports=d}("undefined"!=typeof window?window:"undefined"!=typeof c?c:this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./callstatsUtils":18,"./pcCallbackHandler":19,"./statsReporter":21,precalltest:3}],18:[function(a,b,c){"use strict";function d(){}d.prototype.measureAppLoadingPerformance=function(a){var b=0,c=Number.MAX_VALUE,d=0,e="",f="",g=window.performance;if(!("performance"in window&&"timing"in window.performance&&"navigation"in window.performance))return{support:"none",total:void 0};var h=g.timing.loadEventEnd-g.timing.navigationStart;if("Chrome"===a.name||"Opera"===a.name){var i,j=g.getEntriesByType("resource");for(i=0;id&&(f=j[i].name.substr(j[i].name.lastIndexOf("/")+1),d=j[i].duration),j[i].duration-1&&(b=j[i].duration);return{support:"full",callstats:b,min:{name:e,time:c},max:{name:f,time:d},total:h}; -}return"Firefox"===a.name?{support:"limited",total:h}:void 0},d.prototype.detectBrowserInfo=function(){var a="Chrome",b=null,c=null,d=null,e={goog:"Chrome",moz:"Firefox",plugin:"Plugin",edge:"Edge"},f=e.goog;if(!window.navigator.userAgent||window.csioReactNative)return console.log("Invalid userAgent"),window&&window.csioGetOsName&&(b=window.csioGetOsName()),window&&window.csioGetOsVer&&(c=window.csioGetOsVer()),window&&window.csioReactNative&&(d="react-native"),{name:a,codebase:f,os:b,osVersion:c,userAgent:d};d=navigator.userAgent;var g,h=d.toLowerCase(),i=navigator.appVersion,j=""+parseFloat(navigator.appVersion);(g=h.indexOf("opera"))!==-1?(a="Opera",j=h.substring(g+6),(g=h.indexOf("Version"))!==-1&&(j=h.substring(g+8)),f=e.goog):(g=h.indexOf("opr"))!==-1?(a="Opera",j=h.substring(g+4),(g=h.indexOf("Version"))!==-1&&(j=h.substring(g+8)),f=e.goog):(g=h.indexOf("msie"))!==-1?(a="Microsoft Internet Explorer",j=h.substring(g+5),f=e.goog):(g=h.indexOf("edge"))!==-1?(a=e.edge,j=h.substring(g+5),f=e.edge):(g=h.indexOf("chrome"))!==-1?(a=e.goog,j=h.substring(g+7),f=e.goog):(g=h.indexOf("safari"))!==-1?(a="Safari",j=h.substring(g+7),(g=h.indexOf("version"))!==-1&&(j=h.substring(g+8)),f=e.goog):(g=h.indexOf("firefox"))!==-1?(a="Firefox",j=h.substring(g+8),f=e.moz):(g=h.indexOf("trident"))!==-1&&(a="Microsoft Internet Explorer",g=h.indexOf("rv"),j=h.substring(g+3,g+7),f=e.goog);var k,l,m=[{s:"Windows 3.11",r:/win16/},{s:"Windows 95",r:/(windows 95|win95|windows_95)/},{s:"Windows ME",r:/(win 9x 4.90|windows me)/},{s:"Windows 98",r:/(windows 98|win98)/},{s:"Windows CE",r:/windows ce/},{s:"Windows 2000",r:/(windows nt 5.0|windows 2000)/},{s:"Windows XP",r:/(windows nt 5.1|windows xp)/},{s:"Windows Server 2003",r:/windows nt 5.2/},{s:"Windows Vista",r:/windows nt 6.0/},{s:"Windows 7",r:/(windows 7|windows nt 6.1)/},{s:"Windows 8.1",r:/(windows 8.1|windows nt 6.3)/},{s:"Windows 8",r:/(windows 8|windows nt 6.2)/},{s:"Windows 10",r:/(windows 10|windows nt 10.0)/},{s:"Windows NT 4.0",r:/(windows nt 4.0|winnt4.0|winnt|windows nt)/},{s:"Windows ME",r:/windows me/},{s:"Android",r:/android/},{s:"Open BSD",r:/openbsd/},{s:"Sun OS",r:/sunos/},{s:"Linux",r:/(linux|x11)/},{s:"iOS",r:/(iphone|ipad|ipod)/},{s:"Mac OS X",r:/mac os x/},{s:"Mac OS",r:/(macppc|macintel|mac_powerpc|macintosh)/},{s:"QNX",r:/qnx/},{s:"UNIX",r:/unix/},{s:"BeOS",r:/beos/},{s:"OS/2",r:/os\/2/},{s:"Search Bot",r:/(nuhk|googlebot|yammybot|openbot|slurp|msnbot|ask jeeves\/teoma|ia_archiver)/}];for(k in m)if(l=m[k],l.r.test(h)){b=l.s;break}switch(b&&/Windows/.test(b)&&(c=/Windows (.*)/.exec(b)[1],b="Windows"),b){case"Mac OS X":c=/mac os x (10[\.\_\d]+)/.exec(h)[1];break;case"Android":c=/android ([\.\_\d]+)/.exec(h)[1];break;case"iOS":c=/os (\d+)_(\d+)_?(\d+)?/.exec(i),c=c[1]+"."+c[2]+"."+(0|c[3])}return{name:a,ver:j.toString(),os:b,osVersion:c,codebase:f,userAgent:d}},b.exports=d},{}],19:[function(a,b,c){function d(a,b,c,d,e){this.pc=a,this.onIceCandidateCallback=b,this.onIceConnectionStateChangeCallback=c,this.onPcSignalingStateChangeCallback=d,this.onPcNegotiationNeededCallback=e,a.addEventListener?(this.pc.addEventListener("icecandidate",this.iceCandidateCallback.bind(this),!1),this.pc.addEventListener("iceconnectionstatechange",this.iceConnectionStateChangeCallback.bind(this),!1),this.pc.addEventListener("signalingstatechange",this.pcSignalingStateChangeCallback.bind(this),!1),this.pc.addEventListener("negotiationneeded",this.pcNegotiationNeededCallback.bind(this),!1)):a.attachEvent&&(this.pc.attachEvent("onicecandidate",this.iceCandidateCallback.bind(this)),this.pc.attachEvent("oniceconnectionstatechange",this.iceConnectionStateChangeCallback.bind(this)),this.pc.attachEvent("onsignalingstatechange",this.pcSignalingStateChangeCallback.bind(this)),this.pc.attachEvent("onnegotiationneeded",this.pcNegotiationNeededCallback.bind(this)))}d.prototype.iceCandidateCallback=function(a){try{this.onIceCandidateCallback(a,this.pc)}catch(a){console.log("onIceCandidateCallback: Error",a)}},d.prototype.iceConnectionStateChangeCallback=function(a){try{this.onIceConnectionStateChangeCallback(a,this.pc)}catch(a){console.log("onIceConnectionStateChangeCallback: Error",a)}},d.prototype.pcSignalingStateChangeCallback=function(a){try{this.onPcSignalingStateChangeCallback(a,this.pc)}catch(a){console.log("onPcSignalingStateChangeCallback: Error",a)}},d.prototype.pcNegotiationNeededCallback=function(a){try{this.onPcNegotiationNeededCallback(a,this.pc)}catch(a){console.log("onPcNegotiationNeededCallback: Error",a)}},b.exports=d},{}],20:[function(a,b,c){function d(a,b){this.items=[],this.plugins=[],this.timeoutInMs=b,this.maxItemsNum=a,this.minItemsNum=0,this.last=null}var e=a("./swItem");d.prototype={constructor:d,signalize:function(a,b){for(var c=0;c0&&c>0&&(e=d.concat("x",c,"@",b)),e},getFrameWidth:function(a){var b;return void 0!==a.data.googFrameWidthReceived?b=a.data.googFrameWidthReceived:void 0!==a.data.googFrameWidthSent?b=a.data.googFrameWidthSent:void 0!==a.data.frameWidth&&(b=a.data.frameWidth),b},validateRTT:function(a){var b;return b=isNaN(a)||a<0?null:a},getLatencyData:function(a){return void 0===a?null:void 0!==a.data.googRtt?this.validateRTT(parseInt(a.data.googRtt,10)):void 0!==a.data.roundTripTime?this.validateRTT(parseInt(a.data.roundTripTime,10)):void 0!==a.data.mozRtt?this.validateRTT(parseInt(a.data.mozRtt,10)):null},getMediaType:function(a){var b=this.mediaType.unknown;if(void 0!==a)return a.data&&void 0!==a.data.mediaType?a.data.mediaType:(a.data.mediaType?b=a.data.mediaType:void 0!==a.data.googFrameRateReceived||void 0!==a.data.googFrameRateSent?b=this.mediaType.video:void 0!==a.data.audioInputLevel||void 0!==a.data.audioOutputLevel||void 0!==a.data.audioLevel?b=this.mediaType.audio:void 0!==a.data.framerateMean&&(b=this.mediaType.video),b)},checkForNan:function(a){var b=isNaN(a)?null:a;return b},checkForNegativeValue:function(a){if(a=this.checkForNan(a),null!==a){var b=a<0?null:a;return b}},toString:function(){return"ToString function is not defined. for this object"}},o.prototype=Object.create(E.prototype),o.prototype.constructor=o,o.prototype.onDataSent=function(){this.prev=this.actual},o.prototype.getActual=function(){return this.actual},o.prototype.getFirst=function(){return this.first},o.prototype.getDelta=function(){return this.delta=this.actual-this.prev,this.delta},o.prototype.getPrevious=function(){return this.prev},o.prototype.add=function(a){var b=this.extractorFnc(a);if(void 0!==b&&null!==b){if(0===this.first)return this.first=b,void(this.actual=b);this.actual=b,this.notify({last:this.prev,delta:this.delta})}},o.prototype.remove=function(){},p.prototype=Object.create(E.prototype),p.prototype.constructor=p,p.prototype.add=function(a){void 0!==a&&null!==a&&(this.prev=this.extractorFnc(a))},p.prototype.remove=function(){},p.prototype.getPrevious=function(){return this.prev},q.prototype={constructor:q,getIntervalLoss:function(){return this.intervalLoss},getIntervalPacketsRecv:function(){return this.intervalPacketsRecv},getValue:function(){return void 0===this.intervalPacketsRecv||void 0===this.intervalLoss?null:null===this.intervalPacketsRecv||null===this.intervalLoss?null:0===this.intervalLoss&&0===this.intervalPacketsRecv?0:this.intervalLoss/(this.intervalPacketsRecv+this.intervalLoss)}},t.VideoThroughputThresholds={green:1024,red:256},t.AudioThroughputThresholds={green:30,red:8},t.FrameRateRatioTresholds={green:.8,red:.3},t.VideoRTTThresholds={green:400,red:1e3},t.VideoFractionLostTreshdolds={green:10,red:50},t.AudioFractionLostTresholds={green:15,red:30},t.AudioEModelTresholds={green:240,red:400},t.avQualityRating={excellent:3,fair:2,bad:1},t.avQualityRatingString={excellent:"excellent",fair:"fair",bad:"bad"},t.prototype={constructor:t,doStart:function(){return!0},getStartTime:function(){return this.firstAdded},hasTraffic:function(){var a=this.getLastMeasurement();return this.direction===g.Direction.inbound?00&&(a.data.csioAvgBRKbps=8*this.bytesReceivedTracker.getPrevious()/this.getTotalTimeInMs()),a.data.csioIntFL=b.getValue(),a.data.csioPercentileFl=this.getIntervalFractionLost95(),a.data.csioeM=(null!==this.getRTT95()?this.getRTT95():0)+40,a.data.csioIntPktLoss=this.packetLostTracker.getDelta(),void 0!==a.data.csioAvgBRKbps&&null!==a.data.csioAvgBRKbps?a.data.csioAvgPacketSize=this.bytesReceivedTracker.getDelta()/this.packetsReceivedTracker.getDelta():a.data.csioAvgPacketSize=null,a.data.csioPktLossPercentage=this.packetLostTracker.getDelta()/this.packetsReceivedTracker.getDelta()*100},v.prototype=Object.create(u.prototype),v.prototype.constructor=v,v.prototype.setup=function(a){u.prototype.setup.call(this,a),a.data.csioMediaType=g.MediaTypes.audio,this.quality.eModel=this.getQualityReverseEvaluation(a.data.csioeM,t.AudioEModelTresholds),this.quality.bandwidth=this.getQualityEvaluation(a.data.csioIntBRKbps,t.AudioThroughputThresholds),a.data.csioMark=this.getQuality()},v.prototype.getQuality=function(){var a=0,b=.5*this.quality.bandwidth+.5*this.quality.eModel;return b=Math.floor(b),b===t.avQualityRating.excellent?a=t.avQualityRatingString.excellent:b===t.avQualityRating.fair?a=t.avQualityRatingString.fair:b===t.avQualityRating.bad&&(a=t.avQualityRatingString.bad),a},w.prototype=Object.create(u.prototype),w.prototype.constructor=w,w.prototype.setFrameRatioQuality=function(){var a=this.frameRateReceivedTracker.getActual(),b=this.frameRateReceivedTracker.getPrevious(),c=0;this.quality.frameRate=0,void 0!==a&&void 0!==b&&null!==a&&null!==b&&0!==b&&(c=a/b,this.quality.frameRate=this.getQualityEvaluation(c,t.FrameRateRatioTresholds))},w.prototype.setFrameRateReceived10=function(a){return null===a?void(this.frameRateReceived10=null):void(this.frameRateReceived10=a.actual)},w.prototype.setup=function(a){u.prototype.setup.call(this,a),a.data.csioMediaType=g.MediaTypes.video,this.setFrameRatioQuality(),this.quality.eModel=this.getQualityReverseEvaluation(a.data.csioeM,t.AudioEModelTresholds),this.quality.bandwidth=this.getQualityEvaluation(a.data.csioIntBRKbps,t.VideoThroughputThresholds),a.data.csioMark=this.getQuality()},w.prototype.getQuality=function(){var a=0,b=.33*this.quality.bandwidth+.33*this.quality.eModel+.33*this.quality.frameRate;return b=Math.floor(b),b===t.avQualityRating.excellent?a=t.avQualityRatingString.excellent:b===t.avQualityRating.fair?a=t.avQualityRatingString.fair:b===t.avQualityRating.bad&&(a=t.avQualityRatingString.bad),a},x.prototype=Object.create(t.prototype),x.prototype.constructor=x,x.prototype.setup=function(a){t.prototype.setup.call(this,a);var b=new q(this.packetLostTracker.getDelta(),this.packetsSentTracker.getDelta());this.addIntervalFractionLost(b),this.setIntBRAndPR(this.bytesSentTracker,this.packetsSentTracker,a),this.getTotalTimeInMs()>0&&(a.data.csioAvgBRKbps=8*this.bytesSentTracker.getPrevious()/this.getTotalTimeInMs()),a.data.csioIntFL=b.getValue(),a.data.csioIntPktRcv=this.packetsSentTracker.getDelta(),a.data.csioPercentileFl=this.getIntervalFractionLost95(),a.data.csioeM=(null!==this.getRTT95()?this.getRTT95():0)+40,a.data.csioIntPktLoss=this.packetLostTracker.getDelta(),void 0!==a.data.csioAvgBRKbps&&null!==a.data.csioAvgBRKbps?a.data.csioAvgPacketSize=this.bytesSentTracker.getDelta()/this.packetsSentTracker.getDelta():a.data.csioAvgPacketSize=null,a.data.csioPktLossPercentage=this.packetLostTracker.getDelta()/this.packetsSentTracker.getDelta()*100},y.prototype=Object.create(x.prototype),y.prototype.constructor=y,y.prototype.setFrameRatioQuality=function(){var a=this.frameRateReceivedTracker.getActual(),b=this.frameRateReceivedTracker.getPrevious(),c=0; -this.quality.frameRate=0,void 0!==a&&void 0!==b&&null!==a&&null!==b&&0!==b&&(c=a/b,this.quality.frameRate=this.getQualityEvaluation(c,t.FrameRateRatioTresholds))},y.prototype.setFrameRateReceived10=function(a){return null===a?void(this.frameRateReceived10=null):void(this.frameRateReceived10=a.actual)},y.prototype.setup=function(a){x.prototype.setup.call(this,a),a.data.csioMediaType=g.MediaTypes.video,this.setFrameRatioQuality(),this.quality.eModel=this.getQualityReverseEvaluation(a.data.csioeM,t.AudioEModelTresholds),this.quality.bandwidth=this.getQualityEvaluation(a.data.csioIntBRKbps,t.VideoThroughputThresholds),a.data.csioMark=this.getQuality()},y.prototype.getQuality=function(){var a=0,b=.33*this.quality.bandwidth+.33*this.quality.eModel+.33*this.quality.frameRate;return b=Math.floor(b),b===t.avQualityRating.excellent?a=t.avQualityRatingString.excellent:b===t.avQualityRating.fair?a=t.avQualityRatingString.fair:b===t.avQualityRating.bad&&(a=t.avQualityRatingString.bad),a},z.prototype=Object.create(x.prototype),z.prototype.constructor=z,z.prototype.setEModelQuality=function(a){at.AudioEModelTresholds.green&&at.AudioEModelTresholds.red&&(this.quality.eModel=t.avQualityRating.bad)},z.prototype.setThroughputQuality=function(a){null!==a&&void 0!==a&&(a>t.AudioThroughputThresholds.green?this.quality.bandwidth=t.avQualityRating.excellent:a>t.AudioThroughputThresholds.red&&aMic Visualization
  • audioFileRTC
  • Call Rec
  • -
  • Caller ID
  • +
  • Caller ID
  • @@ -546,7 +546,8 @@
    - + +